Add Quick Fix: a bar chat that hands quick fixes to Claude, Codex or a local model

Each request runs in its own systemd user unit and survives the shell
restarting; the chat reopens on a running job or an unseen result. Auto
picks the subscription with the most usage left (ai-usagebar). Runs are
snapshotted so Undo can restore files and revert commits.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
mxandClaude Opus 5.5 committed 2026-11-25 23:59:20 +01:00
1 parent 30e98bac63
commit 3d976b5961
8 files changed
+1693

No files matched your search

+45
View File
@@ -0,0 +1,45 @@
import QtQuick
import Quickshell
import qs.Commons
import qs.Ui
// Bar button for Quick Fix. Click opens the chat under it; the icon turns
// into an hourglass while a job runs and takes the alert colour when one
// failed while the chat was closed.
BarWidget {
id: root
moduleName: "mx-quickfix"
readonly property var service: bar && bar.shell ? bar.shell.serviceFor(moduleName) : null
readonly property bool opened: panel.opened
readonly property bool popoutSwitchClosing: panel.popoutSwitchClosing
implicitWidth: button.implicitWidth
implicitHeight: button.implicitHeight
function open() { panel.open() }
function close() { panel.close() }
function toggle() { panel.opened ? panel.close() : panel.open() }
function closeForPopoutSwitch() { panel.closeForPopoutSwitch() }
BarIconButton {
id: button
anchors.fill: parent
bar: root.bar
text: root.service && root.service.running ? "󰔟" : "󰚩"
tooltipText: root.service && root.service.running ? "Quick fix: working…" : "Quick fix"
active: !!root.service && root.service.unseenFailure
onPressed: function(mouseButton) {
if (mouseButton === Qt.LeftButton) root.toggle()
}
}
ChatPanel {
id: panel
bar: root.bar
moduleName: root.moduleName
settings: root.settings
anchorItem: button
service: root.service
}
}
+407
View File
@@ -0,0 +1,407 @@
pragma ComponentBehavior: Bound
import QtQuick
import QtQuick.Controls
import qs.Commons
import qs.Ui
// The chat: what you asked, and the agent's one-line answer to each. A
// follow-up continues the same conversation; closing it starts fresh next
// time (the conversation stays in History).
Panel {
id: root
property Item anchorItem: null
property var service: null
readonly property var session: service ? service.session : null
readonly property var messages: session ? session.messages : []
readonly property bool busy: !!service && service.running
readonly property var providers: [
{ value: "auto", label: "Auto" },
{ value: "claude", label: "Claude" },
{ value: "gpt", label: "GPT" },
{ value: "local", label: "Local" }
]
readonly property string defaultProvider: setting("provider", "auto")
readonly property int cardWidth: Style.space(460)
readonly property int cardHeight: Style.space(470)
function send() {
if (service && service.send(input.text, root.settings)) input.text = ""
}
function focusInput() {
if (service) service.passive = false
input.forceActiveFocus()
}
function when(seconds) {
if (!seconds) return ""
const d = new Date(seconds * 1000), now = new Date()
const time = Qt.formatTime(d, "hh:mm")
return d.toDateString() === now.toDateString() ? time : Qt.formatDate(d, "d MMM") + " " + time
}
function providerName(id) {
return { claude: "Claude", gpt: "GPT", local: "Local", undo: "Undo" }[id] || ""
}
function usageLine() {
if (!service) return ""
const left = service.remaining || {}
const parts = []
if (left.claude !== undefined) parts.push("Claude " + Math.round(left.claude) + "% left")
if (left.gpt !== undefined) parts.push("GPT " + Math.round(left.gpt) + "% left")
if (!service.available.local) parts.push("no local model running")
return parts.join(" · ")
}
onOpenedChanged: {
if (!service) return
service.openPanels += opened ? 1 : -1
if (opened) {
if (!service.passive) service.provider = defaultProvider
service.checkProviders(root.settings)
input.text = ""
}
}
Component.onDestruction: if (opened && service) service.openPanels--
// Scroll to the newest message whenever the conversation changes.
Connections {
target: root.service
function onSessionChanged() { Qt.callLater(() => list.positionViewAtEnd()) }
}
Timer {
id: clock
property real now: Date.now()
interval: 1000
repeat: true
running: root.opened && root.busy
onTriggered: now = Date.now()
}
KeyboardPanel {
id: card
anchorItem: root.anchorItem
owner: root
bar: root.bar
open: root.opened
// After a restart it shows without taking the keyboard; a click on it does.
mode: root.service && root.service.passive ? "hover" : "keyboard"
focusTarget: input
contentWidth: card.fittedContentWidth(root.cardWidth)
contentHeight: card.cappedContentHeight(root.cardHeight)
Column {
id: column
anchors.fill: parent
spacing: Style.spacing.lg
// Pointing at it after a restart hands it the keyboard.
HoverHandler {
enabled: !!root.service && root.service.passive
onHoveredChanged: if (hovered) root.focusInput()
}
// Header
Item {
width: parent.width
height: Style.space(30)
Text {
anchors.left: parent.left
anchors.verticalCenter: parent.verticalCenter
text: root.service && root.service.showHistory ? "History" : "Quick fix"
color: Color.foreground
font.family: Style.font.family
font.pixelSize: Style.font.heading
font.bold: true
}
Row {
anchors.right: parent.right
anchors.verticalCenter: parent.verticalCenter
spacing: Style.spacing.sm
Button {
iconText: "󰋚"
tooltipText: "History"
selected: !!root.service && root.service.showHistory
onClicked: root.service.openHistory()
}
Button {
iconText: "󰐕"
tooltipText: "New conversation"
enabled: !root.busy
opacity: enabled ? 1 : 0.4
onClicked: { root.service.newChat(); root.focusInput() }
}
Button {
iconText: "󰅖"
tooltipText: "Close"
onClicked: root.close()
}
}
}
// Conversation or history
Item {
id: middle
width: parent.width
height: parent.height - y - footer.height - parent.spacing
ListView {
id: list
anchors.fill: parent
visible: !(root.service && root.service.showHistory)
clip: true
spacing: Style.spacing.lg
model: root.messages
boundsBehavior: Flickable.StopAtBounds
ScrollBar.vertical: ScrollBar {}
onCountChanged: Qt.callLater(positionViewAtEnd)
delegate: Item {
id: row
required property var modelData
required property int index
readonly property bool mine: modelData.role === "user"
readonly property bool newest: index === root.messages.length - 1
readonly property bool working: !mine && modelData.status === "running"
readonly property bool canUndo: !mine && modelData.changed === true && !modelData.undone && !!modelData.run && !root.busy
width: list.width
height: bubble.height
Rectangle {
id: bubble
x: row.mine ? row.width - width : 0
width: Math.min(row.width * 0.86, Math.max(body.implicitWidth, meta.implicitWidth) + 2 * Style.spacing.xxl)
height: content.implicitHeight + 2 * Style.spacing.xl
radius: Style.cornerRadius + 4
color: row.mine ? Qt.alpha(Color.accent, 0.2)
: row.modelData.status === "failed" ? Qt.alpha(Color.urgent, 0.14)
: Qt.alpha(Color.foreground, 0.06)
border.width: 1
border.color: row.mine ? Qt.alpha(Color.accent, 0.45) : Qt.alpha(Color.foreground, 0.1)
Column {
id: content
x: Style.spacing.xxl
y: Style.spacing.xl
width: bubble.width - 2 * Style.spacing.xxl
spacing: Style.spacing.sm
Text {
id: meta
visible: !row.mine
textFormat: Text.PlainText
text: {
const m = row.modelData
const parts = [root.providerName(m.provider) || (row.working ? "Starting" : "")]
if (m.status === "ok") parts.push("done")
else if (m.status === "failed") parts.push("failed")
if (m.rebuilt) parts.push("rebuilt")
else if (m.changed) parts.push("files changed")
if (m.undone) parts.push("undone")
return parts.filter(p => p).join(" · ")
}
color: row.modelData.status === "failed" ? Color.urgent : Color.muted
font.family: Style.font.family
font.pixelSize: Style.font.caption
font.bold: true
}
Text {
id: body
width: Math.min(implicitWidth, content.width)
textFormat: Text.PlainText
wrapMode: Text.Wrap
text: row.working ? "Working… " + root.elapsed(row.modelData.time) : row.modelData.text
color: row.working ? Color.muted : Color.foreground
font.family: Style.font.family
font.pixelSize: Style.font.subtitle
}
Row {
visible: row.canUndo
spacing: Style.spacing.sm
Button {
text: "Undo"
iconText: "󰕌"
bordered: true
fontSize: Style.font.bodySmall
onClicked: root.service.undo(row.modelData.run, root.settings)
}
}
}
}
}
}
// Empty conversation
Column {
anchors.centerIn: parent
width: parent.width - 2 * Style.spacing.huge
spacing: Style.spacing.md
visible: list.visible && root.messages.length === 0
Text {
width: parent.width
horizontalAlignment: Text.AlignHCenter
text: "󰚩"
color: Color.muted
font.family: Style.font.family
font.pixelSize: Style.font.displayLarge
}
Text {
width: parent.width
horizontalAlignment: Text.AlignHCenter
wrapMode: Text.Wrap
textFormat: Text.PlainText
text: "Ask for a quick fix: install an app, make a window float, squash a bug. It works on its own and answers in a line."
color: Color.muted
font.family: Style.font.family
font.pixelSize: Style.font.body
}
Text {
width: parent.width
horizontalAlignment: Text.AlignHCenter
wrapMode: Text.Wrap
textFormat: Text.PlainText
text: root.usageLine()
visible: text !== ""
color: Color.muted
opacity: 0.75
font.family: Style.font.family
font.pixelSize: Style.font.caption
}
}
ListView {
id: historyList
anchors.fill: parent
visible: !!root.service && root.service.showHistory
clip: true
spacing: Style.spacing.xs
model: root.service ? root.service.history : []
boundsBehavior: Flickable.StopAtBounds
ScrollBar.vertical: ScrollBar {}
delegate: Rectangle {
id: entry
required property var modelData
width: historyList.width
height: Style.space(42)
radius: Style.cornerRadius
color: entryArea.containsMouse ? Qt.alpha(Color.foreground, 0.08) : "transparent"
Rectangle {
id: dot
x: Style.spacing.lg
anchors.verticalCenter: parent.verticalCenter
width: 7
height: 7
radius: 4
color: entry.modelData.status === "failed" ? Color.urgent : entry.modelData.status === "running" ? Color.accent : Qt.alpha(Color.foreground, 0.45)
}
Text {
anchors.left: dot.right
anchors.leftMargin: Style.spacing.lg
anchors.right: stamp.left
anchors.rightMargin: Style.spacing.lg
anchors.verticalCenter: parent.verticalCenter
textFormat: Text.PlainText
text: entry.modelData.title
elide: Text.ElideRight
color: Color.foreground
font.family: Style.font.family
font.pixelSize: Style.font.body
}
Text {
id: stamp
anchors.right: parent.right
anchors.rightMargin: Style.spacing.lg
anchors.verticalCenter: parent.verticalCenter
text: root.when(entry.modelData.updated)
color: Color.muted
font.family: Style.font.family
font.pixelSize: Style.font.caption
}
MouseArea {
id: entryArea
anchors.fill: parent
hoverEnabled: true
cursorShape: Qt.PointingHandCursor
onClicked: root.service.load(entry.modelData.id)
}
}
footer: Item {
width: historyList.width
height: historyList.count ? Style.space(44) : 0
Button {
visible: historyList.count > 0
anchors.right: parent.right
anchors.bottom: parent.bottom
text: "Clear history"
fontSize: Style.font.bodySmall
onClicked: root.service.clearHistory()
}
}
}
Text {
anchors.centerIn: parent
visible: historyList.visible && historyList.count === 0
text: "Nothing yet"
color: Color.muted
font.family: Style.font.family
font.pixelSize: Style.font.body
}
}
// Input, agent choice and errors
Column {
id: footer
width: parent.width
spacing: Style.spacing.md
Text {
width: parent.width
visible: !!root.service && root.service.error !== ""
text: root.service ? root.service.error : ""
textFormat: Text.PlainText
wrapMode: Text.Wrap
color: Color.urgent
font.family: Style.font.family
font.pixelSize: Style.font.bodySmall
}
Row {
width: parent.width
spacing: Style.spacing.md
TextField {
id: input
width: parent.width - action.width - parent.spacing
placeholderText: root.busy ? "Working on it…" : root.messages.length ? "Follow up…" : "Fix or install something…"
enabled: !root.busy
maximumLength: 8000
font.pixelSize: Style.font.subtitle
onAccepted: root.send()
Keys.onEscapePressed: {
if (text !== "") text = ""
else root.close()
}
}
Button {
id: action
anchors.verticalCenter: input.verticalCenter
iconText: root.busy ? "󰓛" : "󰒊"
tooltipText: root.busy ? "Stop" : "Send"
bordered: true
onClicked: root.busy ? root.service.stop() : root.send()
}
}
ButtonGroup {
options: root.providers.map(p => ({
value: p.value,
label: p.label,
tooltip: p.value === "auto" ? "The subscription with the most usage left" : ""
}))
value: root.service && root.service.provider ? root.service.provider : root.defaultProvider
focusable: false
fontSize: Style.font.bodySmall
onChanged: function(value) { if (root.service) root.service.provider = value }
}
}
}
}
function elapsed(started) {
if (!started) return ""
const s = Math.max(0, Math.round(clock.now / 1000 - started))
return Math.floor(s / 60) + ":" + String(s % 60).padStart(2, "0")
}
}
+63
View File
@@ -0,0 +1,63 @@
# Quick Fix
A bar button that opens a small chat. Type a quick fix ("install Heroic
Launcher", "make Discord open floating", "the clock is off by one pixel") and a
coding agent does it on its own and answers in a line: "OK: Installed Heroic
Launcher." It cannot ask questions, so keep requests small and clear.
Agents: Claude Code (`claude`), Codex (`codex`), or a local OpenAI-compatible
model (Ollama, llama.cpp, LM Studio) through OpenCode (`opencode`). **Auto**
picks Claude or GPT by the usage left on each subscription, read from
[ai-usagebar](https://github.com/akitaonrails/ai-usagebar) (the tighter of the
session and weekly windows counts), then a local model if one is running.
## How it works
- Each request runs in its own systemd user unit
(`glassmxrph-quickfix-<id>`), so a rebuild that restarts the shell does not
stop it. When the shell starts and a job is running, or its result has not
been seen, the chat opens again by itself (without taking the keyboard
until you point at it) and shows how it went.
- Closing the chat and opening it again starts fresh. Earlier conversations
are under History; opening one continues it. A follow-up resumes the same
agent session.
- If the chat is closed when a job ends, you get a notification.
- Before each run the folders under **Repositories to snapshot** are
snapshotted (only files that differ from the last commit are copied). Undo
puts changed files back, removes new ones, reverts the run's commits and
pushes the revert, then runs **Apply after Undo**. It refuses, touching
nothing, when a file was edited again since.
- The rules the agent follows live in
`~/.config/glassMxrph/quickfix/AGENTS.md` (created on first use): where your
configuration is, how to apply changes, what may be committed. Every agent
gets them, plus a short protocol asking for a one-line `OK:`/`FAILED:` reply.
## Permissions
The agents run without anyone to approve them:
- Claude Code runs in `auto` permission mode (its classifier blocks risky
actions), with **Always allowed** rules on top and a deny list for
destructive commands (`git reset --hard`, `git clean`, force pushes, `rm -rf
/`, garbage collection, reboots, …).
- Codex runs in the workspace-write sandbox with network access; approval
requests go to its automatic reviewer.
- OpenCode runs with `--auto` and the same deny list.
None of this is a sandbox. Only use it on a machine and with rules you trust
it with.
## IPC
```sh
quickshell ipc --path <shell> call quickfix toggle
quickshell ipc --path <shell> call quickfix send "install btop"
quickshell ipc --path <shell> call quickfix undo
quickshell ipc --path <shell> call quickfix status
```
With glassMxrph: `glassmxrph plugin toggle mx-quickfix`.
## Tests
`python3 tests/quickfix_test.py`
+243
View File
@@ -0,0 +1,243 @@
import QtQuick
import Quickshell
import Quickshell.Io
// Shared state for every Quick Fix widget (one per bar): the conversation on
// screen, whether a job runs, history. Jobs run in their own systemd user
// units (helpers/quickfix.py), so a rebuild that restarts the shell does not
// stop them; on start this reopens the chat when a job is running or its
// result has not been seen yet.
Item {
id: root
property var shell: null
property string pluginId: "mx-quickfix"
property var session: null
property bool running: false
property bool showHistory: false
property var history: []
property string error: ""
property var available: ({ claude: true, gpt: true, local: false })
property var remaining: ({})
property string provider: ""
// Opened by a restart, not by the user: it does not take the keyboard.
property bool passive: false
// Open panels (one per screen at most).
property int openPanels: 0
readonly property bool panelOpen: openPanels > 0
readonly property var last: session && session.messages.length ? session.messages[session.messages.length - 1] : null
readonly property bool unseenFailure: !panelOpen && !!last && last.status === "failed" && pendingSeen
readonly property string helper: decodeURIComponent(Qt.resolvedUrl("helpers/quickfix.py").toString().replace(/^file:\/\//, ""))
// Bar settings -> helper options.
function options(settings) {
const s = settings || {}
const list = value => String(value || "").split(/[,\n]/).map(v => v.trim()).filter(v => v)
return {
repositories: list(s.repositories),
allow: list(s.allow),
applyCommand: String(s.applyCommand || "").trim() ? ["sh", "-c", String(s.applyCommand)] : [],
claudeModel: String(s.claudeModel || ""),
gptModel: String(s.gptModel || ""),
localUrl: String(s.localUrl || ""),
localModel: String(s.localModel || "")
}
}
// One helper call at a time; replies arrive in order.
property var queue: []
function call(request, done) {
queue = queue.concat([{ request: request, done: done || null }])
if (!job.running) next()
}
function next() {
if (!queue.length) return
job.current = queue[0]
queue = queue.slice(1)
job.command = ["python3", helper, JSON.stringify(job.current.request)]
job.running = true
}
Process {
id: job
property var current: null
stdout: StdioCollector { id: out }
stderr: StdioCollector { id: err }
onExited: function(code) {
let result
try { result = JSON.parse(out.text) }
catch (e) { result = { ok: false, error: (err.text || "The helper failed").trim().split("\n").pop() } }
const entry = job.current
if (!result.ok) root.error = result.error || "Something went wrong"
else if (entry && entry.request.op !== "state" && entry.request.op !== "providers") root.error = ""
if (entry && entry.done) entry.done(result)
Qt.callLater(root.next)
}
}
function apply(result) {
if (!result.ok || result.session === undefined) return
const wasRunning = running
session = result.session
running = !!result.session && !!result.session.running
if (wasRunning && !running) finished()
}
property bool pendingSeen: false
function finished() {
if (!session) return
if (panelOpen) {
call({ op: "seen", session: session.id })
pendingSeen = false
return
}
// Closed while it worked: say how it went, then start fresh next time.
pendingSeen = true
const text = last ? last.text : ""
Quickshell.execDetached(["notify-send", "-a", "Quick Fix", "-i", last && last.status === "failed" ? "dialog-error" : "dialog-information",
last && last.status === "failed" ? "Quick fix failed" : "Quick fix done", text])
}
// Settings of the widget that last used the service, for IPC calls.
property var lastSettings: ({})
function send(text, settings) {
text = String(text || "").trim()
if (!text || running) return false
lastSettings = settings || lastSettings
const request = { op: "send", text: text, provider: provider || "auto", options: options(settings) }
if (session && !showHistory) request.session = session.id
showHistory = false
// Shown at once; the helper's copy replaces it.
const shown = session && request.session ? JSON.parse(JSON.stringify(session)) : { id: "", messages: [] }
shown.messages.push({ role: "user", text: text }, { role: "agent", text: "", status: "running", provider: "" })
session = shown
running = true
call(request, result => {
if (result.ok) apply(result)
else { running = false; session = request.session ? session : null; if (request.session) refresh() }
})
return true
}
function stop() {
if (session && running) call({ op: "stop", session: session.id })
}
function undo(run, settings) {
if (!session || running) return
running = true
call({ op: "undo", session: session.id, run: run, options: options(settings) }, result => {
if (result.ok) apply(result)
else { running = false; refresh() }
})
}
function refresh() {
call({ op: "state" }, result => {
if (!result.ok) return
// Another conversation may be on screen (history); only follow ours.
if (result.session && (!session || session.id === result.session.id || result.running))
apply(result)
else if (running && !result.running) {
running = false
}
})
}
function newChat() {
showHistory = false
if (!running) session = null
error = ""
}
function openHistory() {
showHistory = !showHistory
if (showHistory) call({ op: "history" }, result => { if (result.ok) history = result.history })
}
function load(id) {
call({ op: "load", session: id }, result => {
if (!result.ok) return
showHistory = false
if (!running) session = result.session
})
}
function clearHistory() {
call({ op: "clearHistory" }, result => { if (result.ok) history = result.history })
}
function checkProviders(settings) {
lastSettings = settings || lastSettings
call({ op: "providers", options: options(settings) }, result => {
if (!result.ok) return
available = result.available
remaining = result.remaining
})
}
// A fresh start each time it opens, unless a job is still running.
onPanelOpenChanged: {
if (panelOpen) {
if (pendingSeen && session) {
call({ op: "seen", session: session.id })
pendingSeen = false
if (!running) session = null
}
return
}
passive = false
showHistory = false
error = ""
if (!running) session = null
}
Timer {
interval: 1500
repeat: true
running: root.running
onTriggered: root.refresh()
}
// After a restart: reopen on a running job or an unseen result.
property int summonTries: 0
Timer {
id: summonRetry
interval: 500
repeat: true
onTriggered: {
root.summonTries++
if (root.panelOpen || root.summonTries > 40) { stop(); return }
if (root.shell && root.shell.summon(root.pluginId, "")) stop()
}
}
Component.onCompleted: call({ op: "state" }, result => {
if (!result.ok || !result.session || !(result.running || !result.seen)) return
root.session = result.session
root.running = result.running
root.passive = true
root.summonTries = 0
summonRetry.start()
})
IpcHandler {
target: "quickfix"
function toggle(): void {
if (root.shell) root.shell.toggle(root.pluginId, "")
}
// Sends to the open (or a new) conversation with the bar's settings.
function send(text: string): bool {
return root.send(text, root.lastSettings)
}
// Shows or hides History in the open chat.
function history(): void {
root.openHistory()
}
// Undoes the newest change in the conversation on screen.
function undo(): bool {
const run = root.session ? root.session.messages.slice().reverse().find(m => m.changed && !m.undone && m.run) : null
if (!run || root.running) return false
root.undo(run.run, root.lastSettings)
return true
}
function status(): string {
return JSON.stringify({ open: root.panelOpen, running: root.running, passive: root.passive,
session: root.session ? root.session.id : "", error: root.error,
messages: root.session ? root.session.messages.length : 0,
last: root.last ? root.last.status + ": " + root.last.text : "" })
}
}
}
+709
View File
@@ -0,0 +1,709 @@
#!/usr/bin/env python3
"""Quick fix: hands a short request to a coding agent and keeps its final reply.
JSON protocol for the shell (one request in argv, one reply on stdout); argv-only
execution. Each request runs in its own transient systemd user unit, so it
survives the shell restarting under it (a rebuild restarts the shell). Sessions
are JSON files below the state directory; the shell watches state.json.
"""
import json
import os
from pathlib import Path
import fcntl
import hashlib
import re
import shutil
import signal
import subprocess
import sys
import time
import urllib.request
HOME = Path.home()
STATE = Path(os.environ.get('XDG_STATE_HOME') or HOME / '.local/state') / 'glassMxrph' / 'quickfix'
CONFIG = Path(os.environ.get('XDG_CONFIG_HOME') or HOME / '.config') / 'glassMxrph'
RULES = CONFIG / 'quickfix' / 'AGENTS.md'
SESSIONS = STATE / 'sessions'
SNAPSHOTS = STATE / 'snapshots'
KEEP_SESSIONS = 50
KEEP_SNAPSHOTS = 10
UNIT = 'glassmxrph-quickfix'
PROVIDERS = ('claude', 'gpt', 'local')
ID = re.compile(r'^[0-9]{8}-[0-9]{6}-[0-9a-f]{4}$')
TIMEOUT = 60 * 60
MAX_FILE = 20 * 1024 * 1024 # larger untracked files are not snapshotted
DEFAULT_RULES = """# Quick fix rules
You are run from the desktop shell for small, well-defined changes. Nobody can
answer questions while you work: make a sensible choice and finish the job.
Describe here where your configuration lives, how changes are applied
(for example the rebuild command) and what may be committed or pushed.
"""
PROTOCOL = """You were started from a desktop quick-fix box. Work on your own until the request is done; you cannot ask questions.
Reply with the final result only: one or two short plain sentences, no headings, lists, code blocks or preamble.
Start the reply with "OK: " if everything asked for is done and applied, or "FAILED: " if it is not, followed by the message, e.g. "OK: Installed Heroic Launcher." or "FAILED: The rebuild stopped on a hash mismatch in heroic.nix; nothing was applied."
Never reply OK unless the commands that apply the change finished successfully. If something fails and you cannot fix it, put your own edits back the way they were."""
# Commands that throw away work or the machine's state are refused outright.
DENY = ['git reset --hard', 'git clean', 'git checkout -- ', 'git restore', 'git stash', 'git push --force',
'git push -f', 'sudo rm', 'rm -rf /', 'rm -rf ~', 'mkfs', 'dd ', 'nix-collect-garbage', 'nh clean',
'zcli cleanup', 'docker system prune', 'docker volume', 'systemctl poweroff', 'systemctl reboot',
'reboot', 'shutdown', 'poweroff']
# Files -----------------------------------------------------------------------
def write_json(path, value):
path.parent.mkdir(parents=True, exist_ok=True)
tmp = path.with_name(path.name + f'.{os.getpid()}.part')
tmp.write_text(json.dumps(value, ensure_ascii=False))
tmp.replace(path)
def read_json(path, fallback=None):
try:
return json.loads(path.read_text())
except (OSError, ValueError):
return fallback
class locked:
"""Serialises read-modify-write between the shell's calls and the worker."""
def __enter__(self):
STATE.mkdir(parents=True, exist_ok=True)
self.file = open(STATE / 'lock', 'w')
fcntl.flock(self.file, fcntl.LOCK_EX)
def __exit__(self, *_):
self.file.close()
def session_path(id_):
if not isinstance(id_, str) or not ID.match(id_):
raise ValueError('Invalid session')
return SESSIONS / f'{id_}.json'
def load_session(id_):
session = read_json(session_path(id_))
if not session:
raise ValueError('That conversation no longer exists')
return session
def save_session(session):
write_json(session_path(session['id']), session)
def read_state():
return read_json(STATE / 'state.json', {}) or {}
def save_state(**changes):
state = read_state()
state.update(changes)
state['serial'] = state.get('serial', 0) + 1
write_json(STATE / 'state.json', state)
def ensure_rules():
if not RULES.exists():
RULES.parent.mkdir(parents=True, exist_ok=True)
RULES.write_text(DEFAULT_RULES)
return RULES.read_text()
def new_id():
return time.strftime('%Y%m%d-%H%M%S') + '-' + os.urandom(2).hex()
# Units -----------------------------------------------------------------------
def unit_active(id_):
r = subprocess.run(['systemctl', '--user', 'is-active', f'{UNIT}-{id_}.service'], capture_output=True, text=True)
return r.stdout.strip() in ('active', 'activating', 'deactivating')
def start_unit(id_, action):
# A follow-up may arrive before the previous run's unit has gone.
for _ in range(30):
if not unit_active(id_):
break
time.sleep(0.1)
command = ['systemd-run', '--user', '--collect', '--quiet', f'--unit={UNIT}-{id_}',
'--description=glassMxrph quick fix', '--property=KillMode=mixed', '--property=TimeoutStopSec=10',
f'--working-directory={HOME}']
for key in ('PATH', 'XDG_STATE_HOME', 'XDG_CONFIG_HOME', 'SSH_AUTH_SOCK', 'GLASSMXRPH_QUICKFIX_TEST'):
if os.environ.get(key):
command.append(f'--setenv={key}={os.environ[key]}')
r = subprocess.run(command + [sys.executable, os.path.abspath(__file__), action, id_],
capture_output=True, text=True)
if r.returncode:
raise ValueError((r.stderr or 'Could not start the job').strip()[-300:])
# Providers -------------------------------------------------------------------
def remaining():
"""Percent left per subscription, limited by its tightest window."""
result = {}
if not shutil.which('ai-usagebar'):
return result
try:
r = subprocess.run(['ai-usagebar', 'usage', '--json'], capture_output=True, text=True, timeout=25)
entries = json.loads(r.stdout).get('entries', [])
except (subprocess.TimeoutExpired, OSError, ValueError, AttributeError):
return result
for entry in entries:
name = {'anthropic': 'claude', 'openai': 'gpt'}.get(entry.get('id'))
used = [m['percent'] for m in entry.get('metrics') or [] if isinstance(m.get('percent'), (int, float))]
if name and used and entry.get('status') == 'ready':
result[name] = max(0, 100 - max(used))
return result
def local_models(options):
url = options.get('localUrl', '')
if not re.match(r'^https?://', url):
return []
try:
with urllib.request.urlopen(url.rstrip('/') + '/models', timeout=2) as response:
return [m['id'] for m in json.load(response).get('data') or [] if m.get('id')]
except (OSError, ValueError, KeyError, TypeError):
return []
def installed():
return {'claude': bool(shutil.which('claude')), 'gpt': bool(shutil.which('codex')),
'local': bool(shutil.which('opencode'))}
def choose(provider, options):
"""The provider to use, or ValueError saying why none works."""
have = installed()
if provider == 'auto':
left = remaining()
usable = [p for p in ('claude', 'gpt') if have[p] and left.get(p, 1) > 0]
# Unknown usage ranks below any known remainder.
if usable:
return max(usable, key=lambda p: left.get(p, 0.5)), left
if have['local'] and local_models(options):
return 'local', left
raise ValueError('No usage left on Claude or GPT, and no local model is running')
if provider not in PROVIDERS:
raise ValueError('Unknown provider')
if not have[provider]:
raise ValueError({'claude': 'claude', 'gpt': 'codex', 'local': 'opencode'}[provider] + ' is not installed')
if provider == 'local' and not local_models(options):
raise ValueError('No local model server at ' + options.get('localUrl', ''))
return provider, {}
def transcript(session, provider):
"""Earlier messages, for an agent that has not seen this conversation."""
earlier = [m for m in session['messages'][:-2] if m.get('text')]
if not earlier or session['agents'].get(provider):
return ''
lines = [('User: ' if m['role'] == 'user' else 'Reply: ') + m['text'] for m in earlier[-10:]]
return 'Earlier in this conversation:\n' + '\n'.join(lines) + '\n\n'
REMINDER = '\n\n(Work on your own, then reply in one or two short sentences starting with "OK: " or "FAILED: ".)'
def build_command(provider, session, prompt, options, last_file):
"""argv and extra environment for one run."""
resume = session['agents'].get(provider)
if resume:
prompt += REMINDER
rules = PROTOCOL + '\n\n' + ensure_rules()
if provider == 'claude':
command = ['claude', '-p', '--output-format', 'json', '--permission-mode', 'auto',
'--append-system-prompt', rules]
command += ['--allowedTools', *options['allow']] if options.get('allow') else []
command += ['--disallowedTools', *(f'Bash({d.strip()}:*)' for d in DENY)]
if options.get('claudeModel'):
command += ['--model', options['claudeModel']]
if resume:
command += ['--resume', resume]
return command, {}, prompt
if provider == 'gpt':
command = ['codex', 'exec']
if resume:
command += ['resume', resume]
command += ['--json', '--skip-git-repo-check', '-o', str(last_file)]
# Runs on its own: the automatic reviewer answers approval requests.
command += ['-c', 'approval_policy="on-request"', '-c', 'approvals_reviewer="auto_review"',
'-c', 'sandbox_mode="workspace-write"', '-c', 'sandbox_workspace_write.network_access=true']
if options.get('gptModel'):
command += ['-m', options['gptModel']]
# "-" reads the prompt from stdin.
return command + ['-'], {}, prompt if resume else rules + '\n\n# Request\n\n' + prompt
models = local_models(options)
model = options.get('localModel') or (models[0] if models else '')
deny = {'*': 'allow'}
deny.update({d.strip() + '*': 'deny' for d in DENY})
config = {
'provider': {'quickfix': {'npm': '@ai-sdk/openai-compatible', 'name': 'Local',
'options': {'baseURL': options.get('localUrl')}, 'models': {model: {}}}},
'permission': {'bash': deny}}
command = ['opencode', 'run', '--format', 'json', '--auto', '--dir', str(HOME), '-m', 'quickfix/' + model]
if resume:
command += ['-s', resume]
return command, {'OPENCODE_CONFIG_CONTENT': json.dumps(config)}, \
prompt if resume else rules + '\n\n# Request\n\n' + prompt
def parse_output(provider, out, last_file):
"""(final text, agent session id, agent-reported error)"""
text, agent, error = '', '', False
if provider == 'claude':
for line in reversed(out.strip().splitlines()):
try:
value = json.loads(line)
except ValueError:
continue
if isinstance(value, dict) and value.get('type') == 'result':
return str(value.get('result') or ''), value.get('session_id') or '', bool(value.get('is_error'))
return '', '', True
for line in out.splitlines():
try:
event = json.loads(line)
except ValueError:
continue
if not isinstance(event, dict):
continue
if provider == 'gpt':
if event.get('type') == 'thread.started':
agent = event.get('thread_id') or agent
elif event.get('type') in ('error', 'turn.failed'):
error = True
detail = event.get('error')
text = event.get('message') or (detail.get('message') if isinstance(detail, dict) else '') or text
elif event.get('type') == 'turn.completed':
error = False
else:
agent = event.get('sessionID') or agent
part = event.get('part') or {}
if event.get('type') == 'text' and part.get('text'):
text = part['text']
elif event.get('type') == 'error':
error = True
if provider == 'gpt' and not error:
try:
text = last_file.read_text()
except OSError:
pass
return text, agent, error
def tidy(text):
"""(ok or None when the agent did not say, message)"""
text = text.strip()
match = re.match(r'^\**(OK|FAILED)\**\s*[:.\-–—]\**\s*', text)
if not match:
return None, text
return match[1] == 'OK', text[match.end():].strip() or ('Done.' if match[1] == 'OK' else 'It did not work.')
# Snapshots and undo ------------------------------------------------------------
def git(repo, *args, check=True, **kwargs):
r = subprocess.run(['git', '-C', str(repo), *args], capture_output=True, timeout=120, **kwargs)
if check and r.returncode:
raise ValueError(r.stderr.decode(errors='replace').strip()[-300:] or 'git failed')
return r.stdout
def repositories(options):
found = []
for entry in options.get('repositories') or []:
path = Path(entry).expanduser()
if (path / '.git').exists():
found.append(path)
return found
def digest(path):
if path.is_symlink():
return 'link:' + os.readlink(path)
try:
return hashlib.sha256(path.read_bytes()).hexdigest() + (':x' if os.access(path, os.X_OK) else '')
except OSError:
return ''
def listing(repo):
"""Every tracked or untracked (not ignored) file and its digest."""
names = git(repo, 'ls-files', '-z', '--cached', '--others', '--exclude-standard').decode(errors='surrogateescape')
files = {}
for name in set(filter(None, names.split('\0'))):
path = repo / name
if path.is_symlink() or path.is_file():
if path.is_symlink() or path.stat().st_size <= MAX_FILE:
files[name] = digest(path)
return files
def snapshot(run, options):
"""Copies each repository's files aside, so a run can be undone even where
changes are never committed."""
record = {'repos': []}
for number, repo in enumerate(repositories(options)):
files = listing(repo)
target = SNAPSHOTS / run / str(number)
# Files identical to the last commit come back from git; only the rest
# (edited or untracked) need a copy.
dirty = git(repo, 'diff', '--name-only', '-z', 'HEAD', check=False) + \
git(repo, 'ls-files', '-z', '--others', '--exclude-standard')
for name in set(dirty.decode(errors='surrogateescape').split('\0')) & set(files):
copy = target / name
copy.parent.mkdir(parents=True, exist_ok=True)
copy_file(repo / name, copy)
record['repos'].append({'path': str(repo), 'head': git(repo, 'rev-parse', 'HEAD', check=False).decode().strip(),
'before': files})
write_json(SNAPSHOTS / run / 'record.json', record)
old = sorted(p for p in SNAPSHOTS.iterdir() if p.is_dir())[:-KEEP_SNAPSHOTS]
for path in old:
shutil.rmtree(path, ignore_errors=True)
return record
def copy_file(source, target):
shutil.copy2(source, target, follow_symlinks=False)
def finish_snapshot(run, record):
"""Records what the run changed; True when there is something to undo."""
changed = False
for repo in record['repos']:
path = Path(repo['path'])
before, after = repo.pop('before'), listing(path)
# `git add` may be all that changed for a file; contents are what count.
repo['files'] = {n: {'before': before.get(n, ''), 'after': after.get(n, '')}
for n in set(before) | set(after) if before.get(n, '') != after.get(n, '')}
head = git(path, 'rev-parse', 'HEAD', check=False).decode().strip()
repo['commits'] = []
if head != repo['head'] and repo['head']:
repo['commits'] = git(path, 'rev-list', f"{repo['head']}..{head}", check=False).decode().split()
changed = changed or bool(repo['files'] or repo['commits'])
write_json(SNAPSHOTS / run / 'record.json', record)
return changed
def undo(run, options):
"""Puts a run's files back and reverts its commits. Refuses, before touching
anything, when a file was edited again afterwards."""
record = read_json(SNAPSHOTS / run / 'record.json')
if not record:
raise ValueError('The snapshot for this change is gone')
plans, conflicts = [], []
for number, repo in enumerate(record['repos']):
path = Path(repo['path'])
commits = repo.get('commits') or []
committed = set()
for commit in commits:
committed |= set(filter(None, git(path, 'diff-tree', '--no-commit-id', '--name-only', '-r', '-z', commit)
.decode(errors='surrogateescape').split('\0')))
# Lock files move on with every update, so that is no reason to refuse.
for name, state in repo['files'].items():
if name != 'flake.lock' and digest(path / name) != state['after']:
conflicts.append(f'{path.name}/{name}')
if commits and git(path, 'status', '--porcelain', '--untracked-files=no', check=False).strip():
conflicts.append(f'{path.name} (uncommitted changes)')
plans.append((SNAPSHOTS / run / str(number), path, repo, commits, committed))
if conflicts:
raise ValueError('Changed again since, so it was left alone: ' + ', '.join(conflicts[:4]))
for _, path, _, commits, _ in plans:
for commit in commits: # newest first
try:
git(path, 'revert', '--no-edit', commit)
except ValueError:
git(path, 'revert', '--abort', check=False)
raise
for copy, path, repo, _, committed in plans:
for name, state in repo['files'].items():
if name in committed:
continue
target = path / name
if state['before']:
if not os.path.lexists(copy / name):
git(path, 'restore', '--source', repo['head'], '--worktree', '--', name)
continue
target.parent.mkdir(parents=True, exist_ok=True)
tmp = target.with_name(target.name + '.quickfix-undo')
copy_file(copy / name, tmp)
tmp.replace(target)
else:
target.unlink(missing_ok=True)
# Forget an intent-to-add entry left by the run.
git(path, 'rm', '--cached', '--quiet', '--ignore-unmatch', '--', name, check=False)
pushed = []
for _, path, _, commits, _ in plans:
if commits:
r = subprocess.run(['git', '-C', str(path), 'push'], capture_output=True, text=True, timeout=180)
if r.returncode:
pushed.append(path.name)
return pushed
# Worker (inside the transient unit) ----------------------------------------------
def finish(session, ok, text, **extra):
with locked():
session = load_session(session['id'])
message = session['messages'][-1]
agent = extra.pop('agent', '')
message.update(text=text, status='ok' if ok else 'failed' if ok is False else 'done',
finished=int(time.time()), **extra)
if agent:
session['agents'][message['provider']] = agent
session['running'] = False
save_session(session)
save_state(current=session['id'], running=False, seen=False)
def system_generation():
return os.path.realpath('/run/current-system')
def worker(id_):
session = load_session(id_)
options = session['options']
run = session['messages'][-1]['run']
prompt = session['messages'][-2]['text']
stopped = []
child = []
def stop(*_):
stopped.append(True)
for process in child:
try:
os.killpg(process.pid, signal.SIGTERM)
except ProcessLookupError:
pass
signal.signal(signal.SIGTERM, stop)
record, generation = None, system_generation()
last_file = STATE / f'{id_}.last'
try:
provider, _ = choose(session['provider'], options)
with locked():
session = load_session(id_)
session['messages'][-1]['provider'] = provider
save_session(session)
save_state(current=id_, running=True, seen=False)
record = snapshot(run, options)
prompt = transcript(session, provider) + prompt
command, env, text = build_command(provider, session, prompt, options, last_file)
last_file.unlink(missing_ok=True)
if stopped:
raise InterruptedError
process = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
text=True, cwd=HOME, start_new_session=True, env={**os.environ, **env})
child.append(process)
if stopped:
stop()
try:
out, err = process.communicate(text, timeout=TIMEOUT)
except subprocess.TimeoutExpired:
os.killpg(process.pid, signal.SIGKILL)
out, err = process.communicate()
err = 'It took longer than an hour and was stopped.'
if stopped:
raise InterruptedError
text, agent, error = parse_output(provider, out, last_file)
ok, text = tidy(text)
if error or process.returncode or not text:
ok = False
text = text or (err.strip().splitlines() or ['The agent gave no reply.'])[-1][-300:]
except InterruptedError:
ok, text, agent = False, 'Stopped.', ''
except Exception as error: # always leave a result behind
ok, text, agent = False, str(error) or type(error).__name__, ''
finally:
last_file.unlink(missing_ok=True)
changed = False
if record:
signal.signal(signal.SIGTERM, signal.SIG_IGN)
try:
changed = finish_snapshot(run, record)
except (OSError, ValueError, subprocess.SubprocessError):
pass
finish(session, ok, text, agent=agent, changed=changed, rebuilt=system_generation() != generation)
def undo_worker(id_):
session = load_session(id_)
run = session['messages'][-1]['undoes']
generation = system_generation()
try:
unpushed = undo(run, session['options'])
text, ok = 'Undone.', True
apply = session['options'].get('applyCommand') or []
if apply:
r = subprocess.run(apply, capture_output=True, text=True, timeout=TIMEOUT, cwd=HOME, stdin=subprocess.DEVNULL)
if r.returncode:
ok = False
text = 'The files are back, but applying them failed: ' + \
((r.stderr or r.stdout).strip().splitlines() or ['unknown error'])[-1][-200:]
if unpushed:
ok, text = False, text + ' Could not push ' + ', '.join(unpushed) + '.'
with locked():
session = load_session(id_)
for message in session['messages']:
if message.get('run') == run:
message['undone'] = True
save_session(session)
except Exception as error:
ok, text = False, str(error) or type(error).__name__
finish(session, ok, text, rebuilt=system_generation() != generation)
# Requests from the shell -----------------------------------------------------------
def clean_options(value):
value = value if isinstance(value, dict) else {}
strings = lambda key: [s for s in value.get(key) or [] if isinstance(s, str) and s]
options = {key: strings(key) for key in ('repositories', 'allow', 'applyCommand')}
for key in ('claudeModel', 'gptModel', 'localUrl', 'localModel'):
options[key] = value.get(key) if isinstance(value.get(key), str) else ''
if options[key].startswith('-'):
raise ValueError('Invalid ' + key)
return options
def recover():
"""Marks a run whose unit died (power loss, crash) as failed."""
state = read_state()
if not state.get('running') or not state.get('current'):
return
id_ = state['current']
if time.time() - state.get('started', 0) < 5 or unit_active(id_):
return
with locked():
if not read_state().get('running'):
return
session = read_json(session_path(id_))
if session and session.get('running'):
session['running'] = False
session['messages'][-1].update(text='It was interrupted before it finished.', status='failed',
finished=int(time.time()))
save_session(session)
save_state(running=False, seen=False)
def begin(session, request_messages, action):
with locked():
if read_state().get('running'):
raise ValueError('Something is already running')
session['messages'] += request_messages
session['running'] = True
session['updated'] = int(time.time())
save_session(session)
save_state(current=session['id'], running=True, seen=False, started=int(time.time()))
try:
start_unit(session['id'], action)
except (OSError, ValueError) as error:
finish(session, False, str(error))
return load_session(session['id'])
def handle(request):
op = request.get('op')
recover()
if op == 'state':
state = read_state()
session = read_json(session_path(state['current'])) if state.get('current') else None
return {'session': session, 'running': bool(state.get('running')), 'seen': bool(state.get('seen', True))}
if op == 'send':
text = str(request.get('text') or '').strip()
if not text or len(text) > 8000:
raise ValueError('Type what to do')
options = clean_options(request.get('options'))
provider = request.get('provider')
if provider != 'auto' and provider not in PROVIDERS:
raise ValueError('Unknown provider')
if request.get('session'):
session = load_session(request['session'])
else:
session = {'id': new_id(), 'created': int(time.time()), 'title': text.splitlines()[0][:80],
'messages': [], 'agents': {}}
session.update(provider=provider, options=options)
now = int(time.time())
session = begin(session, [{'role': 'user', 'text': text, 'time': now},
{'role': 'agent', 'text': '', 'status': 'running', 'time': now,
'provider': '' if provider == 'auto' else provider, 'run': new_id()}], 'worker')
prune()
return {'session': session}
if op == 'undo':
session = load_session(request.get('session'))
session['options'] = clean_options(request.get('options'))
run = request.get('run')
if not any(m.get('run') == run and m.get('changed') and not m.get('undone') for m in session['messages']):
raise ValueError('Nothing to undo')
now = int(time.time())
return {'session': begin(session, [{'role': 'user', 'text': 'Undo', 'time': now},
{'role': 'agent', 'text': '', 'status': 'running', 'time': now,
'provider': 'undo', 'undoes': run}], 'undo')}
if op == 'stop':
session_path(request.get('session'))
subprocess.run(['systemctl', '--user', 'stop', '--no-block', f"{UNIT}-{request['session']}.service"],
capture_output=True, timeout=10)
return {}
if op == 'seen':
with locked():
state = read_state()
if not state.get('running') and state.get('current') == request.get('session'):
save_state(seen=True)
return {}
if op == 'load':
return {'session': load_session(request.get('session'))}
if op == 'history':
rows = []
for path in sorted(SESSIONS.glob('*.json'), reverse=True)[:KEEP_SESSIONS] if SESSIONS.is_dir() else []:
session = read_json(path)
if session:
rows.append({'id': session['id'], 'title': session.get('title', ''),
'updated': session.get('updated', session.get('created', 0)),
'status': session['messages'][-1].get('status', '') if session['messages'] else ''})
return {'history': sorted(rows, key=lambda r: r['updated'], reverse=True)}
if op == 'clearHistory':
with locked():
state = read_state()
for path in SESSIONS.glob('*.json') if SESSIONS.is_dir() else []:
if not (state.get('running') and path.stem == state.get('current')):
path.unlink(missing_ok=True)
return {'history': []}
if op == 'providers':
options = clean_options(request.get('options'))
have = installed()
have['local'] = have['local'] and bool(local_models(options))
return {'available': have, 'remaining': remaining()}
if op == 'rules':
ensure_rules()
return {'path': str(RULES)}
raise ValueError('Unknown operation')
def prune():
for path in sorted(SESSIONS.glob('*.json'))[:-KEEP_SESSIONS]:
path.unlink(missing_ok=True)
def main():
if len(sys.argv) == 3 and sys.argv[1] in ('worker', 'undo'):
(worker if sys.argv[1] == 'worker' else undo_worker)(sys.argv[2])
return
try:
result = handle(json.loads(sys.argv[1]))
result['ok'] = True
except (OSError, ValueError, IndexError, KeyError, TypeError, subprocess.SubprocessError) as error:
result = {'ok': False, 'error': str(error) or type(error).__name__}
print(json.dumps(result))
if __name__ == '__main__':
main()
+92
View File
@@ -0,0 +1,92 @@
{
"schemaVersion": 1,
"id": "mx-quickfix",
"name": "Quick Fix",
"version": "0.1.0",
"author": "mx",
"license": "MIT",
"description": "A small chat box in the bar that hands quick fixes to Claude Code, Codex or a local model. It works on its own and replies with one line. Needs claude, codex or opencode; ai-usagebar picks the subscription with the most usage left.",
"kinds": [
"bar-widget",
"service"
],
"entryPoints": {
"barWidget": "BarWidget.qml",
"service": "Service.qml"
},
"barWidget": {
"displayName": "Quick Fix",
"description": "Click to type a quick fix; the agent does it and answers in a line.",
"category": "AI",
"allowMultiple": false,
"defaultSection": "right",
"defaults": {
"provider": "auto",
"claudeModel": "",
"gptModel": "",
"localUrl": "http://127.0.0.1:11434/v1",
"localModel": "",
"repositories": "",
"allow": "",
"applyCommand": ""
},
"schema": [
{
"key": "provider",
"label": "Default agent",
"description": "Auto picks Claude or GPT by the usage left on each (from ai-usagebar), then a local model.",
"choices": ["auto", "claude", "gpt", "local"],
"defaultValue": "auto"
},
{
"key": "repositories",
"type": "string",
"label": "Repositories to snapshot",
"description": "Comma-separated git folders, e.g. ~/zaneyos, ~/glassMxrph. Each run is snapshotted first so Undo can put files back and revert its commits.",
"defaultValue": ""
},
{
"key": "applyCommand",
"type": "string",
"label": "Apply after Undo",
"description": "Shell command run after Undo restores files, e.g. your rebuild command. Blank: nothing.",
"defaultValue": ""
},
{
"key": "allow",
"type": "string",
"label": "Always allowed (Claude)",
"description": "Comma-separated Claude Code permission rules the run may use without its safety check, e.g. Bash(zcli rebuild:*), Bash(git push:*).",
"defaultValue": ""
},
{
"key": "claudeModel",
"type": "string",
"label": "Claude model",
"description": "Blank: Claude Code's default.",
"defaultValue": ""
},
{
"key": "gptModel",
"type": "string",
"label": "GPT model",
"description": "Blank: Codex's default.",
"defaultValue": ""
},
{
"key": "localUrl",
"type": "string",
"label": "Local server",
"description": "OpenAI-compatible endpoint (Ollama, llama.cpp, LM Studio), run through OpenCode.",
"defaultValue": "http://127.0.0.1:11434/v1"
},
{
"key": "localModel",
"type": "string",
"label": "Local model",
"description": "Blank: the first model the server lists.",
"defaultValue": ""
}
]
}
}
+133
View File
@@ -0,0 +1,133 @@
#!/usr/bin/env python3
import json,os,subprocess,sys,tempfile,unittest
from pathlib import Path
from unittest.mock import patch
ROOT=Path(__file__).resolve().parents[1]
sys.path.insert(0,str(ROOT/'helpers'))
import quickfix
class QuickFix(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
base = Path(self.tmp.name)
self.repo = base / 'repo'
self.repo.mkdir()
self.patches = [patch.object(quickfix, 'STATE', base / 's'), patch.object(quickfix, 'SESSIONS', base / 's/sessions'),
patch.object(quickfix, 'SNAPSHOTS', base / 's/snapshots'), patch.object(quickfix, 'RULES', base / 'r/AGENTS.md')]
for p in self.patches:
p.start()
env = {'GIT_AUTHOR_NAME': 't', 'GIT_AUTHOR_EMAIL': 't@t', 'GIT_COMMITTER_NAME': 't', 'GIT_COMMITTER_EMAIL': 't@t'}
self.env = patch.dict(os.environ, env)
self.env.start()
self.git('init', '-q')
(self.repo / 'clean').write_text('clean')
(self.repo / 'dirty').write_text('old')
self.git('add', '.')
self.git('-c', 'commit.gpgsign=false', 'commit', '-qm', 'one')
(self.repo / 'dirty').write_text('mine')
(self.repo / 'untracked').write_text('also mine')
self.options = {'repositories': [str(self.repo)]}
def tearDown(self):
for p in self.patches:
p.stop()
self.env.stop()
self.tmp.cleanup()
def git(self, *a):
subprocess.run(['git', '-C', str(self.repo), *a], check=True, capture_output=True)
def text(self, name):
return (self.repo / name).read_text()
def test_undo_restores_uncommitted_work(self):
record = quickfix.snapshot('run', self.options)
for name in ('clean', 'dirty'):
(self.repo / name).write_text('agent')
(self.repo / 'untracked').unlink()
(self.repo / 'new').write_text('agent')
self.git('add', '-N', 'new')
self.assertTrue(quickfix.finish_snapshot('run', record))
self.assertEqual(quickfix.undo('run', self.options), [])
self.assertEqual([self.text(n) for n in ('clean', 'dirty', 'untracked')], ['clean', 'mine', 'also mine'])
self.assertFalse((self.repo / 'new').exists())
def test_undo_refuses_files_edited_since(self):
record = quickfix.snapshot('run', self.options)
(self.repo / 'clean').write_text('agent')
(self.repo / 'dirty').write_text('agent')
quickfix.finish_snapshot('run', record)
(self.repo / 'dirty').write_text('mine again')
with self.assertRaisesRegex(ValueError, 'dirty'):
quickfix.undo('run', self.options)
self.assertEqual((self.text('clean'), self.text('dirty')), ('agent', 'mine again'))
def test_undo_reverts_commits(self):
(self.repo / 'untracked').unlink()
self.git('checkout', '-q', '--', 'dirty')
remote = Path(self.tmp.name) / 'remote'
subprocess.run(['git', 'init', '-q', '--bare', str(remote)], check=True)
self.git('remote', 'add', 'origin', str(remote))
self.git('push', '-qu', 'origin', 'HEAD')
self.git('config', 'commit.gpgsign', 'false')
record = quickfix.snapshot('run', self.options)
(self.repo / 'clean').write_text('agent')
self.git('commit', '-qam', 'fix')
self.assertTrue(quickfix.finish_snapshot('run', record))
self.assertEqual(quickfix.undo('run', self.options), [])
self.assertEqual(self.text('clean'), 'clean')
def test_unchanged_run_has_nothing_to_undo(self):
self.assertFalse(quickfix.finish_snapshot('run', quickfix.snapshot('run', self.options)))
def test_auto_takes_the_most_usage_left(self):
have = {'claude': True, 'gpt': True, 'local': True}
with patch.object(quickfix, 'installed', return_value=have), patch.object(quickfix, 'local_models', return_value=['m']):
for left, expected in (({'claude': 30, 'gpt': 100}, 'gpt'), ({'claude': 30, 'gpt': 0}, 'claude'),
({'claude': 0, 'gpt': 0}, 'local'), ({'gpt': 5}, 'gpt')):
with patch.object(quickfix, 'remaining', return_value=left):
self.assertEqual(quickfix.choose('auto', {})[0], expected)
def test_usage_is_limited_by_the_tightest_window(self):
report = {'entries': [{'id': 'anthropic', 'status': 'ready', 'metrics': [{'percent': 3}, {'percent': 70}]},
{'id': 'openai', 'status': 'error', 'metrics': []}]}
done = subprocess.CompletedProcess([], 0, json.dumps(report), '')
with patch.object(quickfix.shutil, 'which', return_value='x'), patch.object(quickfix.subprocess, 'run', return_value=done):
self.assertEqual(quickfix.remaining(), {'claude': 30})
def test_replies(self):
self.assertEqual(quickfix.tidy('OK: Installed X.'), (True, 'Installed X.'))
self.assertEqual(quickfix.tidy('**FAILED:** no'), (False, 'no'))
self.assertEqual(quickfix.tidy('Six containers.'), (None, 'Six containers.'))
out = '{"type":"thread.started","thread_id":"t"}\n{"type":"turn.completed"}'
last = Path(self.tmp.name) / 'last'
last.write_text('OK: hi')
self.assertEqual(quickfix.parse_output('gpt', out, last), ('OK: hi', 't', False))
self.assertEqual(quickfix.parse_output('claude', '{"type":"result","result":"x","session_id":"s","is_error":false}', last), ('x', 's', False))
def test_requests_are_validated(self):
for bad in ('../x', '', None, '20260101-000000-zzzz'):
with self.assertRaises(ValueError):
quickfix.session_path(bad)
with self.assertRaises(ValueError):
quickfix.clean_options({'gptModel': '--danger'})
with patch.object(quickfix, 'start_unit') as start:
for request in ({'op': 'send', 'text': ' ', 'provider': 'auto'}, {'op': 'send', 'text': 'x', 'provider': 'sh'}):
with self.assertRaises(ValueError):
quickfix.handle(request)
start.assert_not_called()
def test_one_run_at_a_time_and_dead_runs_recover(self):
request = {'op': 'send', 'text': 'x', 'provider': 'claude', 'options': {}}
with patch.object(quickfix, 'start_unit'), patch.object(quickfix, 'unit_active', return_value=False):
quickfix.handle(request)
with self.assertRaisesRegex(ValueError, 'already running'):
quickfix.handle(request)
quickfix.save_state(started=0)
state = quickfix.handle({'op': 'state'})
self.assertFalse(state['running'])
self.assertFalse(state['seen'])
self.assertEqual(state['session']['messages'][-1]['status'], 'failed')
if __name__ == '__main__':
unittest.main()