From 5e0ceeefe5ed9bd038a5d104251ee537e6eb4eb3 Mon Sep 17 00:00:00 2001 From: Austin Wang <38676809+austinywang@users.noreply.github.com> Date: Tue, 13 Oct 2026 21:48:43 -0700 Subject: [PATCH 01/20] test: cover OpenCode lifecycle notification regressions --- tests/test_opencode_plugin_install.py | 35 +++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/tests/test_opencode_plugin_install.py b/tests/test_opencode_plugin_install.py index f2f161dfe7fb..ab193488999d 100644 --- a/tests/test_opencode_plugin_install.py +++ b/tests/test_opencode_plugin_install.py @@ -250,6 +250,35 @@ def main() -> int: } } }); +await v1Hooks.event({ + event: { + type: "session.updated", + properties: { + info: { id: "opencode-session-test", time: { archived: false } } + } + } +}); +await v1Hooks.event({ + event: { + type: "session.status", + properties: { sessionID: "opencode-session-test", status: { type: "idle" } } + } +}); +await v1Hooks.event({ + event: { + type: "session.idle", + properties: { sessionID: "opencode-session-test" } + } +}); +await v1Hooks.event({ + event: { + type: "session.error", + properties: { + sessionID: "opencode-session-test", + error: { name: "ProviderAuthError", message: "provider failed" } + } + } +}); """ check = subprocess.run( [bun, "--eval", check_source], @@ -276,6 +305,12 @@ def main() -> int: if args_log.count("hooks enqueue opencode session-start") != 1: print(f"FAIL: plugin invoked duplicate session-start hooks, got {args_log!r}") return 1 + if args_log.count("hooks enqueue opencode stop") != 2: + print(f"FAIL: plugin did not dispatch one completion and one failure hook, got {args_log!r}") + return 1 + if stdin_log.count('"hook_event_name":"Stop"') != 1 or stdin_log.count('"hook_event_name":"StopFailure"') != 1: + print(f"FAIL: plugin did not preserve completion/error hook identity, got {stdin_log!r}") + return 1 if '"session_id":"opencode-session-test"' not in stdin_log or '"/tmp/opencode-project"' not in stdin_log: print(f"FAIL: plugin did not pass expected session payload, got {stdin_log!r}") return 1 From 0d93f4f28957935528fa443385238f8666b6e369 Mon Sep 17 00:00:00 2001 From: Austin Wang <38676809+austinywang@users.noreply.github.com> Date: Tue, 13 Oct 2026 22:08:28 -0700 Subject: [PATCH 02/20] fix: restore OpenCode lifecycle notifications Handle current OpenCode completion and failure events, coalesce duplicate idle callbacks, and preserve error state through the feed and TUI journal bridges. Co-authored-by: e-jung --- CLI/cmux.swift | 113 ++++++++++++++++-- Resources/opencode-plugin.js | 65 ++++++++-- Resources/opencode-tui-plugin.js | 61 ++++++++-- Sources/AgentFeedSemanticInput.swift | 2 + .../crates/cmux-tui-core/src/agent_hooks.rs | 30 +++++ .../cmux-tui/assets/agent-hooks/opencode.js | 7 +- cmuxTests/OpenCodeHookRegressionTests.swift | 2 +- tests/test_opencode_v2_tui_bridge.py | 11 +- 8 files changed, 264 insertions(+), 27 deletions(-) diff --git a/CLI/cmux.swift b/CLI/cmux.swift index dcbecf3a946b..79bb18162d61 100644 --- a/CLI/cmux.swift +++ b/CLI/cmux.swift @@ -36430,6 +36430,7 @@ function sessionState(sessionId) { lastUserMessage: null, assistantPreamble: null, cwd: null, + lastStopKind: null, updatedAt: Date.now(), }); } @@ -36465,6 +36466,31 @@ function dropSession(sessionId) { } } +function failureMessage(event) { + const props = eventProperties(event); + const raw = props.error || props.failure || props.reason; + if (typeof raw === "string") return normalizeText(raw, 500); + if (raw && typeof raw === "object") { + const nested = firstString(raw.message, raw.error, raw.reason, raw.description, raw.name); + if (nested) return normalizeText(nested, 500); + } + return normalizeText(firstString(props.message, props.description), 500); +} + +function sessionStatusType(status) { + if (typeof status === "string") return status.trim().toLowerCase(); + if (!status || typeof status !== "object") return null; + return firstString(status.type, status.status, status.state)?.toLowerCase() || null; +} + +function shouldSendStop(sessionId, kind) { + const state = sessionState(sessionId); + if (state.lastStopKind === "failure") return false; + if (state.lastStopKind === "success" && kind === "success") return false; + state.lastStopKind = kind; + return true; +} + function contextForSession(sessionId) { const state = sessionState(sessionId); const context = {}; @@ -36614,6 +36640,7 @@ function trackMessage(event) { const role = info.role || props.role; if (messageId && sessionId && role) { messageRoles.set(messageId, { sessionId, role }); + if (role === "user") sessionState(sessionId).lastStopKind = null; if (messageRoles.size > 300) { messageRoles.delete(messageRoles.keys().next().value); } @@ -36636,29 +36663,63 @@ function trackMessage(event) { } } +function resetTurnFromEvent(event) { + const props = eventProperties(event); + if (["session.next.prompted", "session.next.prompt.admitted", "session.inbox.enqueued"].includes(event?.type)) { + const sessionId = sessionIdFor(event); + if (sessionId) sessionState(sessionId).lastStopKind = null; + return; + } + if (event?.type === "session.status") { + if (sessionStatusType(props.status) === "busy") { + const sessionId = sessionIdFor(event); + if (sessionId) sessionState(sessionId).lastStopKind = null; + } + } +} + +function sendStop(ctx, event, failed = false) { + const sessionId = sessionIdFor(event); + if (!sessionId || !shouldSendStop(sessionId, failed ? "failure" : "success")) return; + const error = failed ? failureMessage(event) : null; + sendHook("stop", ctx, event, { + hook_event_name: failed ? "StopFailure" : "Stop", + ...(error ? { error } : {}), + }); +} + const createCMUXSessionRestore = async (ctx) => { const handleEvent = async (event) => { trackMessage(event); + resetTurnFromEvent(event); const props = eventProperties(event); switch (event && event.type) { case "session.created": + sessionState(sessionIdFor(event)).lastStopKind = null; sendHook("session-start", ctx, event); break; case "session.updated": if (props.info && props.info.time && props.info.time.archived) { sendHook("session-end", ctx, event); dropSession(sessionIdFor(event)); - } else { - sendHook("session-start", ctx, event); } break; case "session.status": - if (props.status && props.status.type === "idle") { - sendHook("stop", ctx, event); + if (sessionStatusType(props.status) === "idle") { + sendStop(ctx, event); } break; case "session.idle": - sendHook("stop", ctx, event); + sendStop(ctx, event); + break; + case "session.execution.succeeded": + case "session.execution.interrupted": + sendStop(ctx, event); + break; + case "session.execution.failed": + case "session.next.step.failed": + case "session.error": + sendStop(ctx, event, true); break; case "session.deleted": sendHook("session-end", ctx, event); @@ -40355,6 +40416,27 @@ export default { ) return summary.status == .error ? summary : nil }() + let openCodeFailure: AgentHookNotificationSummary? = { + guard def.name == "opencode" else { return nil } + let event = reportedHookEventName(from: input)?.lowercased() ?? "" + let isFailure = event == "stopfailure" + || event.contains("execution.failed") + || event.contains("next.step.failed") + || event == "session.error" + || event == "error" + guard isFailure else { return nil } + let rawObject = input.rawObject ?? input.object ?? [:] + let message = firstString( + in: rawObject, + keys: ["error", "message", "reason", "description"] + ) ?? "" + return classifyAgentHookNotification( + def: def, + signal: event, + message: message, + isFallback: false + ) + }() let rawCwd = hookCwd ?? mapped?.cwd let launchCommand = agentLaunchCommandFromEnvironment(env, fallbackPID: pid, fallbackKind: def.name, cwd: rawCwd) let cwd = preferredAgentHookResumeWorkingDirectory(kind: def.name, current: launchCommand, currentCwd: hookCwd, mapped: mapped) @@ -40381,8 +40463,10 @@ export default { ) if let antigravityFailure { subtitle = antigravityFailure.subtitle + } else if let openCodeFailure { + subtitle = openCodeFailure.subtitle } - if codexFailure == nil, antigravityFailure == nil, let projectName, !projectName.isEmpty { + if codexFailure == nil, antigravityFailure == nil, openCodeFailure == nil, let projectName, !projectName.isEmpty { subtitle = String.localizedStringWithFormat( String( localized: "agent.codex.completion.subtitle.completedInProject", @@ -40393,6 +40477,7 @@ export default { } let body = codexFailure?.body ?? antigravityFailure?.body + ?? openCodeFailure?.body ?? lastMsg.map { truncate(normalizedSingleLine($0), maxLength: 200) } ?? grokAssistantMessage.map { truncate(normalizedSingleLine($0), maxLength: 200) } ?? String( @@ -40409,7 +40494,7 @@ export default { inputTurnID: input.turnId, terminationReason: stopTerminationReason ) - let stopNotificationStatus: AgentHookNotificationStatus = codexFailure != nil || antigravityFailure != nil + let stopNotificationStatus: AgentHookNotificationStatus = codexFailure != nil || antigravityFailure != nil || openCodeFailure != nil ? .error : (sameTurnNeedsInput ? .needsInput : .idle) var lifecycleAfterStop: AgentHibernationLifecycleState = { @@ -40600,7 +40685,7 @@ export default { // reducer's per-session fold handles stale sessions (a newer // running session outranks this one) and subagent tagging keeps // nested sessions off the pane badge — no emit-side guessing. - let stopHadFailure = codexFailure != nil || antigravityFailure != nil + let stopHadFailure = codexFailure != nil || antigravityFailure != nil || openCodeFailure != nil emitJournal( stopHadFailure ? .errorReported : (sameTurnNeedsInput ? .questionRequested : .turnCompleted), workspaceId: workspaceId, @@ -40775,6 +40860,18 @@ export default { client: client ) } + } else if openCodeFailure != nil { + let statusValue = agentErrorStatusValue(for: def) + if def.name == "cursor" { + sendCursorCriticalCommand( + "set_status \(def.statusKey) \(statusValue) --icon=exclamationmark.triangle.fill --color=#FF453A --priority=100 --tab=\(workspaceId)\(socketPanelOption(surfaceId))" + ) + } else { + _ = try? sendV1Command( + "set_status \(def.statusKey) \(statusValue) --icon=exclamationmark.triangle.fill --color=#FF453A --priority=100 --tab=\(workspaceId)\(socketPanelOption(surfaceId))", + client: client + ) + } } else if hasActiveBackgroundWork { let runningStatus = String(localized: "agent.generic.status.running", defaultValue: "Running") if def.name == "cursor" { diff --git a/Resources/opencode-plugin.js b/Resources/opencode-plugin.js index 2d00ad80cd31..4ddbadb9ef05 100644 --- a/Resources/opencode-plugin.js +++ b/Resources/opencode-plugin.js @@ -84,6 +84,23 @@ const createCMUXFeed = async (ctx, options = {}) => { return firstString(status.type, status.status, status.state)?.toLowerCase() === "idle"; }; + const sessionStatusType = (status) => { + if (typeof status === "string") return status.trim().toLowerCase(); + if (!isObject(status)) return null; + return firstString(status.type, status.status, status.state)?.toLowerCase() || null; + }; + + const failureMessage = (event) => { + const props = eventProperties(event); + const raw = props.error || props.failure || props.reason; + if (typeof raw === "string") return normalizeText(raw, 500); + if (isObject(raw)) { + const nested = firstString(raw.message, raw.error, raw.reason, raw.description, raw.name); + if (nested) return normalizeText(nested, 500); + } + return normalizeText(firstString(props.message, props.description), 500); + }; + const normalizeText = (value, max = 1000) => { if (typeof value !== "string") return null; const normalized = value.replace(/\s+/g, " ").trim(); @@ -98,6 +115,7 @@ const createCMUXFeed = async (ctx, options = {}) => { lastUserMessage: null, assistantPreamble: null, cwd: null, + lastStopKind: null, }); } return sessions.get(key); @@ -663,6 +681,7 @@ const createCMUXFeed = async (ctx, options = {}) => { if (!sid || !text) return null; const state = sessionState(sid); state.lastUserMessage = text; + state.lastStopKind = null; return base(sid, { hook_event_name: "UserPromptSubmit", tool_input: { prompt: text }, @@ -682,6 +701,7 @@ const createCMUXFeed = async (ctx, options = {}) => { const role = info.role || props.role; if (messageId && sessionId && role) { messageRoles.set(messageId, { sessionId, role }); + if (role === "user") sessionState(sessionId).lastStopKind = null; if (messageRoles.size > 300) { messageRoles.delete(messageRoles.keys().next().value); } @@ -699,6 +719,7 @@ const createCMUXFeed = async (ctx, options = {}) => { const state = sessionState(meta.sessionId); if (meta.role === "user") { state.lastUserMessage = text; + state.lastStopKind = null; return base(meta.sessionId, { hook_event_name: "UserPromptSubmit", tool_input: { prompt: text }, @@ -711,6 +732,14 @@ const createCMUXFeed = async (ctx, options = {}) => { return null; }; + const shouldEmitStop = (sessionId, kind) => { + const state = sessionState(sessionId); + if (state.lastStopKind === "failure") return false; + if (state.lastStopKind === "success" && kind === "success") return false; + state.lastStopKind = kind; + return true; + }; + const pushBlocking = (event, requestId) => { const reply = new Promise((resolve) => { let timeout; @@ -768,6 +797,7 @@ const createCMUXFeed = async (ctx, options = {}) => { const info = props.info || {}; const sid = sessionIdFromProperties(props) || "unknown"; const state = sessionState(sid); + state.lastStopKind = null; state.cwd = info.directory || props.location?.directory || event.location?.directory || ctx?.location?.directory || ctx?.directory || state.cwd; pushTelemetry(base(sid, { hook_event_name: "SessionStart", @@ -777,19 +807,36 @@ const createCMUXFeed = async (ctx, options = {}) => { } case "session.status": { const props = eventProperties(event); - if (!sessionStatusIsIdle(props.status)) break; const sid = sessionIdFromProperties(props); - if (!sid) break; + if (sid && sessionStatusType(props.status) === "busy") { + sessionState(sid).lastStopKind = null; + break; + } + if (!sessionStatusIsIdle(props.status)) break; + if (!sid || !shouldEmitStop(sid, "success")) break; pushTelemetry(base(sid, { hook_event_name: "Stop", })); break; } case "session.execution.succeeded": - case "session.execution.failed": case "session.execution.interrupted": { const sid = sessionIdFromEvent(event); - if (sid) pushTelemetry(base(sid, { hook_event_name: "Stop" })); + if (sid && shouldEmitStop(sid, "success")) pushTelemetry(base(sid, { hook_event_name: "Stop" })); + break; + } + case "session.execution.failed": + case "session.next.step.failed": + case "session.error": { + const sid = sessionIdFromEvent(event); + if (sid && shouldEmitStop(sid, "failure")) { + const error = failureMessage(event); + pushTelemetry(base(sid, { + hook_event_name: "Stop", + is_error: true, + ...(error ? { error } : {}), + })); + } break; } case "session.updated": { @@ -798,19 +845,23 @@ const createCMUXFeed = async (ctx, options = {}) => { if (eventProperties(event).info?.time?.archived) { pushTelemetry(base(sid, { hook_event_name: "SessionEnd" })); sessions.delete(sid); - } else { - pushTelemetry(base(sid, { hook_event_name: "SessionStart" })); } break; } case "session.idle": { const sid = sessionIdFromProperties(eventProperties(event)); - if (!sid) break; + if (!sid || !shouldEmitStop(sid, "success")) break; pushTelemetry(base(sid, { hook_event_name: "Stop", })); break; } + case "session.next.prompted": + case "session.next.prompt.admitted": { + const sid = sessionIdFromEvent(event); + if (sid) sessionState(sid).lastStopKind = null; + break; + } case "session.deleted": { const sid = sessionIdFromProperties(eventProperties(event)); if (!sid) break; diff --git a/Resources/opencode-tui-plugin.js b/Resources/opencode-tui-plugin.js index 2d50c0387577..bf077d4502ad 100644 --- a/Resources/opencode-tui-plugin.js +++ b/Resources/opencode-tui-plugin.js @@ -9,6 +9,11 @@ import { CMUXFeed } from "./index.js"; const firstString = (...values) => values.find((value) => typeof value === "string" && value.trim())?.trim() || null; const properties = (event) => event?.data || event?.properties || {}; +const statusType = (status) => { + if (typeof status === "string") return status.trim().toLowerCase(); + if (!status || typeof status !== "object") return null; + return firstString(status.type, status.status, status.state)?.toLowerCase() || null; +}; function sessionID(event) { const data = properties(event); @@ -50,6 +55,17 @@ function cwd(ctx, event) { ); } +function failureMessage(event) { + const data = properties(event); + const raw = data.error || data.failure || data.reason; + if (typeof raw === "string") return raw.slice(0, 500); + if (raw && typeof raw === "object") { + const nested = firstString(raw.message, raw.error, raw.reason, raw.description, raw.name); + if (nested) return nested.slice(0, 500); + } + return firstString(data.message, data.description)?.slice(0, 500) || null; +} + function rootFor(ctx, id) { try { return ctx?.data?.session?.root?.(id) || id; } catch (_) { return id; } } @@ -171,13 +187,21 @@ function sessionEventName(event) { const data = properties(event); if (event?.type === "session.created") return "session-start"; if (event?.type === "session.deleted") return "session-end"; - if (event?.type === "session.updated") return data.info?.time?.archived ? "session-end" : "session-start"; - if (["session.execution.succeeded", "session.execution.failed", "session.execution.interrupted"].includes(event?.type)) return "stop"; + if (event?.type === "session.updated") return data.info?.time?.archived ? "session-end" : null; + if (["session.execution.succeeded", "session.execution.interrupted"].includes(event?.type)) return "stop"; + if (["session.execution.failed", "session.next.step.failed", "session.error"].includes(event?.type)) return "stop-failure"; if (event?.type === "session.idle") return "stop"; - if (event?.type === "session.status" && (data.status?.type || data.status?.status || data.status) === "idle") return "stop"; + if (event?.type === "session.status" && statusType(data.status) === "idle") return "stop"; return null; } +function isTurnStartEvent(event) { + if (["session.next.prompted", "session.next.prompt.admitted", "session.inbox.enqueued"].includes(event?.type)) return true; + if (event?.type !== "session.status") return false; + const data = properties(event); + return statusType(data.status) === "busy"; +} + function reportError(ctx, _error) { try { const toast = ctx?.ui?.toast?.show; @@ -190,18 +214,36 @@ function reportError(ctx, _error) { } catch (_) {} } -async function handleEvent(ctx, ownership, feed, details, environment) { +async function handleEvent(ctx, ownership, feed, details, environment, lifecycleStops) { const event = details?.event || details; const id = sessionID(event); if (!id || !ownership.belongs(id)) return; + if (isTurnStartEvent(event)) lifecycleStops.delete(id); const hook = sessionEventName(event); - if (hook) { - dispatchSessionHook(hook, { + let admittedHook = hook; + if (hook === "session-start") lifecycleStops.delete(id); + if (hook === "session-end") lifecycleStops.delete(id); + if (hook === "stop" || hook === "stop-failure") { + const kind = hook === "stop-failure" ? "failure" : "success"; + const previous = lifecycleStops.get(id); + if (previous === "failure" || (previous === "success" && kind === "success")) { + admittedHook = null; + } else { + lifecycleStops.set(id, kind); + } + } + if (admittedHook) { + const payload = { session_id: id, cwd: cwd(ctx, event), event: event.type, - hook_event_name: hook === "stop" ? "Stop" : event.type, - }, spawn, environment); + hook_event_name: admittedHook === "stop-failure" ? "StopFailure" : admittedHook === "stop" ? "Stop" : event.type, + }; + if (admittedHook === "stop-failure") { + const error = failureMessage(event); + if (error) payload.error = error; + } + dispatchSessionHook(admittedHook === "stop-failure" ? "stop" : admittedHook, payload, spawn, environment); } // The ownership check above is also the admission decision for the Feed // bridge. Avoid scanning the visible tab set a second time for this event. @@ -217,8 +259,9 @@ export async function createCMUXTUIBridge(ctx, options = {}) { locationForSession: () => ctx?.location, environment, }); + const lifecycleStops = new Map(); const onEvent = ({ details, event }) => { - void handleEvent(ctx, ownership, feed, details || event, environment).catch((error) => reportError(ctx, error)); + void handleEvent(ctx, ownership, feed, details || event, environment, lifecycleStops).catch((error) => reportError(ctx, error)); }; const stop = ctx.data.listen(onEvent); return () => { diff --git a/Sources/AgentFeedSemanticInput.swift b/Sources/AgentFeedSemanticInput.swift index 0bac6947bf64..46a70ef8c87d 100644 --- a/Sources/AgentFeedSemanticInput.swift +++ b/Sources/AgentFeedSemanticInput.swift @@ -34,6 +34,8 @@ struct AgentFeedSemanticInput: Sendable { let kind: AgentJournalEventKind if resolved { kind = .attentionResolved + } else if event.hookEventName == .stop, event.isError == true { + kind = .errorReported } else if isToolActivity { kind = .stateChanged } else { diff --git a/cmux-tui/crates/cmux-tui-core/src/agent_hooks.rs b/cmux-tui/crates/cmux-tui-core/src/agent_hooks.rs index bb8375b370b2..129a1f8ed607 100644 --- a/cmux-tui/crates/cmux-tui-core/src/agent_hooks.rs +++ b/cmux-tui/crates/cmux-tui-core/src/agent_hooks.rs @@ -297,6 +297,14 @@ fn semantic_kind( ("antigravity" | "hermes-agent", "sessionend" | "onsessionend") => "agent.turn.completed", ("opencode", "sessioncreated") => "agent.session.started", ("opencode", "sessionidle") => "agent.turn.completed", + ( + "opencode", + "sessionexecutionsucceeded" | "sessionexecutioninterrupted", + ) => "agent.turn.completed", + ( + "opencode", + "sessionexecutionfailed" | "sessionnextstepfailed" | "sessionerror", + ) => "agent.error.reported", ("opencode", "sessiondeleted") => "agent.session.ended", (_, event) if is_child_spawn(event) => "agent.child.spawned", (_, event) if is_child_completion(event) => "agent.child.completed", @@ -959,6 +967,28 @@ mod tests { assert_eq!(deleted.kind, "agent.session.ended"); } + #[test] + fn current_opencode_failure_events_report_errors() { + for event in ["session.execution.failed", "session.next.step.failed", "session.error"] { + let ingress = agent_hook_journal_ingress( + "opencode", + event, + None, + json!({"event":{"properties":{"sessionID":"opencode-session"}}}), + ) + .unwrap(); + assert_eq!(ingress.kind, "agent.error.reported", "{event}"); + } + } + + #[test] + fn current_opencode_completion_events_report_completed_turns() { + for event in ["session.execution.succeeded", "session.execution.interrupted"] { + let ingress = agent_hook_journal_ingress("opencode", event, None, json!({})).unwrap(); + assert_eq!(ingress.kind, "agent.turn.completed", "{event}"); + } + } + #[test] fn wrapped_opencode_events_keep_native_shape_and_normalize_properties() { let native = json!({ diff --git a/cmux-tui/crates/cmux-tui/assets/agent-hooks/opencode.js b/cmux-tui/crates/cmux-tui/assets/agent-hooks/opencode.js index 14c569d6f9da..de4013eaabe2 100644 --- a/cmux-tui/crates/cmux-tui/assets/agent-hooks/opencode.js +++ b/cmux-tui/crates/cmux-tui/assets/agent-hooks/opencode.js @@ -7,6 +7,11 @@ const events = new Set([ "session.updated", "session.status", "session.idle", + "session.execution.succeeded", + "session.execution.interrupted", + "session.execution.failed", + "session.next.step.failed", + "session.error", "session.compacted", "session.deleted", "message.updated", @@ -22,7 +27,7 @@ const events = new Set([ const sessionRoots = new Map(); function topology(event) { - const properties = event?.properties || {}; + const properties = event?.data || event?.properties || {}; const info = properties.info || {}; const sessionId = info.id || properties.sessionID || properties.sessionId; if (!sessionId) return {}; diff --git a/cmuxTests/OpenCodeHookRegressionTests.swift b/cmuxTests/OpenCodeHookRegressionTests.swift index 88b81026516a..b3e680035cce 100644 --- a/cmuxTests/OpenCodeHookRegressionTests.swift +++ b/cmuxTests/OpenCodeHookRegressionTests.swift @@ -82,7 +82,7 @@ final class OpenCodeHookRegressionTests: XCTestCase { event["hook_event_name"] as? String == "Stop" else { return nil } return event } - XCTAssertEqual(stopEvents.count, 3, "Expected all OpenCode idle forms to emit Stop: \(frames)") + XCTAssertEqual(stopEvents.count, 1, "Expected duplicate OpenCode idle forms to coalesce: \(frames)") XCTAssertTrue(stopEvents.allSatisfy { $0["session_id"] as? String == "opencode-ses-feed-shape" }) let requestIDs = frames.compactMap { $0["id"] as? String } XCTAssertEqual(requestIDs.count, Set(requestIDs).count, "OpenCode telemetry request IDs must not collide: \(frames)") diff --git a/tests/test_opencode_v2_tui_bridge.py b/tests/test_opencode_v2_tui_bridge.py index 7f8f98fe2140..fa355ac124c5 100755 --- a/tests/test_opencode_v2_tui_bridge.py +++ b/tests/test_opencode_v2_tui_bridge.py @@ -147,6 +147,10 @@ def main() -> int: liveA.emit({ details: { type: "session.created", data: { sessionID: "child-a", location: { directory: "/tmp/a" } }, location: { directory: "/tmp/a" } } }); await new Promise((resolve) => setImmediate(resolve)); +liveA.emit({ details: { type: "session.updated", data: { sessionID: "child-a", info: { id: "child-a", time: { archived: false } } } } }); +liveA.emit({ details: { type: "session.status", data: { sessionID: "child-a", status: "idle" } } }); +liveA.emit({ details: { type: "session.idle", data: { sessionID: "child-a" } } }); +liveA.emit({ details: { type: "session.error", data: { sessionID: "child-a", error: { message: "provider failed" } } } }); liveB.emit({ details: { type: "session.execution.succeeded", data: { sessionID: "child-b" } } }); liveA.emit({ details: { type: "permission.asked", data: { sessionID: "child-a", id: "perm-a", action: "edit", resources: ["/tmp/a/file"] } } }); liveB.emit({ details: { type: "permission.asked", data: { sessionID: "child-a", id: "perm-wrong", action: "edit" } } }); @@ -207,7 +211,12 @@ def main() -> int: await waitForObserved((event) => event.hook_event_name === "SessionStart"); await waitForObserved((event) => event.hook_event_name === "Stop"); const sessionStart = observed.find((event) => event.hook_event_name === "SessionStart"); -const stop = observed.find((event) => event.hook_event_name === "Stop"); +const stop = observed.find((event) => event.hook_event_name === "Stop" && event.session_id === "opencode-child-b"); +const childALifecycle = observed.filter((event) => event.session_id === "opencode-child-a" + && ["SessionStart", "Stop"].includes(event.hook_event_name)); +if (childALifecycle.filter((event) => event.hook_event_name === "SessionStart").length !== 1) throw new Error("session.updated reopened the OpenCode session"); +if (childALifecycle.filter((event) => event.hook_event_name === "Stop").length !== 2) throw new Error("OpenCode completion/error lifecycle events were lost or duplicated"); +if (!childALifecycle.some((event) => event.hook_event_name === "Stop" && event.is_error === true && event.error === "provider failed")) throw new Error("OpenCode session.error did not preserve an error completion"); if (sessionStart?.surface_id !== "surface-a" || sessionStart?.workspace_id !== "workspace-a") throw new Error("Feed event was routed to the wrong surface"); if (sessionStart?.cwd !== "/tmp/a") throw new Error("V2 session location was dropped from Feed telemetry"); if (stop?.surface_id !== "surface-b" || stop?.workspace_id !== "workspace-b") throw new Error("second TUI Feed event was routed to the first surface"); From 0b2bd4ba512187c0837fcab04fa053520e304ee7 Mon Sep 17 00:00:00 2001 From: Austin Wang <38676809+austinywang@users.noreply.github.com> Date: Tue, 13 Oct 2026 22:31:25 -0700 Subject: [PATCH 03/20] fix: finish OpenCode notification repair Route lifecycle plugins through OpenCode's XDG config directory, preserve failed turns in Feed, and cover the current error event shape and ordering. Co-authored-by: e-jung --- CLI/CMUXCLI+AgentHookCatalog.swift | 1 + CLI/cmux.swift | 65 +++++++++++++++- Resources/opencode-plugin.js | 13 +++- Resources/opencode-tui-plugin.js | 13 +++- cmuxTests/OpenCodeHookRegressionTests.swift | 85 +++++++++++++++++++++ tests/test_opencode_plugin_install.py | 29 +++---- tests/test_opencode_v2_tui_bridge.py | 6 +- 7 files changed, 191 insertions(+), 21 deletions(-) diff --git a/CLI/CMUXCLI+AgentHookCatalog.swift b/CLI/CMUXCLI+AgentHookCatalog.swift index b187fd7d96a5..e6e5b85e9f27 100644 --- a/CLI/CMUXCLI+AgentHookCatalog.swift +++ b/CLI/CMUXCLI+AgentHookCatalog.swift @@ -48,6 +48,7 @@ extension CMUXCLI { AgentHookDef( name: "opencode", displayName: "OpenCode", statusKey: "opencode", configDir: ".config/opencode", configFile: "plugins/cmux-session.js", configDirEnvOverride: "OPENCODE_CONFIG_DIR", + configDirResolver: { OpenCodePaths(environment: ProcessInfo.processInfo.environment).configDirectory.path }, sessionStoreSuffix: "opencode", disableEnvVar: "CMUX_OPENCODE_HOOKS_DISABLED", hookMarker: "cmux hooks opencode", format: .flat, events: [] diff --git a/CLI/cmux.swift b/CLI/cmux.swift index 79bb18162d61..2f0bd9929047 100644 --- a/CLI/cmux.swift +++ b/CLI/cmux.swift @@ -36471,7 +36471,18 @@ function failureMessage(event) { const raw = props.error || props.failure || props.reason; if (typeof raw === "string") return normalizeText(raw, 500); if (raw && typeof raw === "object") { - const nested = firstString(raw.message, raw.error, raw.reason, raw.description, raw.name); + const nestedData = raw.data && typeof raw.data === "object" ? raw.data : {}; + const nested = firstString( + raw.message, + raw.error, + raw.reason, + raw.description, + nestedData.message, + nestedData.error, + nestedData.reason, + nestedData.description, + raw.name + ); if (nested) return normalizeText(nested, 500); } return normalizeText(firstString(props.message, props.description), 500); @@ -40429,7 +40440,14 @@ export default { let message = firstString( in: rawObject, keys: ["error", "message", "reason", "description"] - ) ?? "" + ) + if message == nil, let error = rawObject["error"] as? [String: Any] { + message = firstString(in: error, keys: ["message", "reason", "description"]) + ?? (error["data"] as? [String: Any]).flatMap { + firstString(in: $0, keys: ["message", "error", "reason", "description"]) + } + ?? firstString(in: error, keys: ["name"]) + } return classifyAgentHookNotification( def: def, signal: event, @@ -41723,9 +41741,17 @@ export default { ) { let fallbackHookEventName = Self.feedEventName(forClaudeSubcommand: subcommand) let reportedEvent = reportedHookEventName(from: parsedInput) + let isOpenCodeStopFailure = source == "opencode" + && reportedEvent.map { normalizedOpenCodeHookEventName($0) == "stopfailure" } == true let hookEventName: String - if let reportedEvent, - (source == "claude" || source == "codex") { + if isOpenCodeStopFailure { + // OpenCode uses the Claude-compatible StopFailure discriminator in + // its lifecycle bridge, but Feed's wire schema represents a + // failed turn as Stop + is_error. Preserve the failure bit while + // avoiding a successful completion event in the app reducer. + hookEventName = "Stop" + } else if let reportedEvent, + (source == "claude" || source == "codex") { // Preserve an explicit lifecycle discriminator when a command // entrypoint was selected by stale/duplicated settings. The // classifier keeps approval semantics (including Codex's native @@ -41811,6 +41837,15 @@ export default { failureDetailsForFeed = failureDetails } } + if isOpenCodeStopFailure { + event["is_error"] = true + if let message = openCodeFailureMessage(from: fallbackObject) { + event["error"] = message + var failureDetails = event["failure"] as? [String: Any] ?? [:] + failureDetails["message"] = message + event["failure"] = failureDetails + } + } if let toolInput = parsedInput.object?["tool_input"] { event["tool_input"] = source == "cursor" ? sanitizedCursorFeedToolInput(toolInput) @@ -42064,6 +42099,28 @@ export default { /// Feed reading must retain the completion, not the notification preview. /// Both native Feed hooks and wrapper hooks call this with the raw payload. + private func normalizedOpenCodeHookEventName(_ value: String) -> String { + value + .trimmingCharacters(in: .whitespacesAndNewlines) + .replacingOccurrences(of: "_", with: "") + .replacingOccurrences(of: "-", with: "") + .lowercased() + } + + private func openCodeFailureMessage(from object: [String: Any]) -> String? { + if let message = firstString(in: object, keys: ["error", "message", "reason", "description"]) { + return truncate(normalizedSingleLine(message), maxLength: 500) + } + guard let error = object["error"] as? [String: Any] else { return nil } + let nestedData = error["data"] as? [String: Any] + let message = firstString(in: error, keys: ["message", "reason", "description"]) + ?? nestedData.flatMap { + firstString(in: $0, keys: ["message", "error", "reason", "description"]) + } + ?? firstString(in: error, keys: ["name"]) + return message.map { truncate(normalizedSingleLine($0), maxLength: 500) } + } + private func enrichStopFeedEvent( _ event: inout [String: Any], hookEventName: String, diff --git a/Resources/opencode-plugin.js b/Resources/opencode-plugin.js index 4ddbadb9ef05..7a8e122f4e07 100644 --- a/Resources/opencode-plugin.js +++ b/Resources/opencode-plugin.js @@ -95,7 +95,18 @@ const createCMUXFeed = async (ctx, options = {}) => { const raw = props.error || props.failure || props.reason; if (typeof raw === "string") return normalizeText(raw, 500); if (isObject(raw)) { - const nested = firstString(raw.message, raw.error, raw.reason, raw.description, raw.name); + const nestedData = isObject(raw.data) ? raw.data : {}; + const nested = firstString( + raw.message, + raw.error, + raw.reason, + raw.description, + nestedData.message, + nestedData.error, + nestedData.reason, + nestedData.description, + raw.name + ); if (nested) return normalizeText(nested, 500); } return normalizeText(firstString(props.message, props.description), 500); diff --git a/Resources/opencode-tui-plugin.js b/Resources/opencode-tui-plugin.js index bf077d4502ad..1a01cb9795f0 100644 --- a/Resources/opencode-tui-plugin.js +++ b/Resources/opencode-tui-plugin.js @@ -60,7 +60,18 @@ function failureMessage(event) { const raw = data.error || data.failure || data.reason; if (typeof raw === "string") return raw.slice(0, 500); if (raw && typeof raw === "object") { - const nested = firstString(raw.message, raw.error, raw.reason, raw.description, raw.name); + const nestedData = raw.data && typeof raw.data === "object" ? raw.data : {}; + const nested = firstString( + raw.message, + raw.error, + raw.reason, + raw.description, + nestedData.message, + nestedData.error, + nestedData.reason, + nestedData.description, + raw.name + ); if (nested) return nested.slice(0, 500); } return firstString(data.message, data.description)?.slice(0, 500) || null; diff --git a/cmuxTests/OpenCodeHookRegressionTests.swift b/cmuxTests/OpenCodeHookRegressionTests.swift index b3e680035cce..a92f1404e106 100644 --- a/cmuxTests/OpenCodeHookRegressionTests.swift +++ b/cmuxTests/OpenCodeHookRegressionTests.swift @@ -34,6 +34,52 @@ final class OpenCodeHookRegressionTests: XCTestCase { XCTAssertEqual(OpenCodePaths(environment: environment).databaseURL.path, "/tmp/home/.local/share/opencode/opencode.db") } + func testOpenCodeInstallHooksUsesXDGConfigHome() throws { + let cliPath = try bundledCLIPath() + let fileManager = FileManager.default + let root = fileManager.temporaryDirectory.appendingPathComponent( + "cmux-opencode-xdg-install-\(UUID().uuidString)", isDirectory: true + ) + let xdgConfigHome = root.appendingPathComponent("xdg-config", isDirectory: true) + let binDir = root.appendingPathComponent("bin", isDirectory: true) + try fileManager.createDirectory(at: binDir, withIntermediateDirectories: true) + defer { try? fileManager.removeItem(at: root) } + + let fakeOpenCodeURL = binDir.appendingPathComponent("opencode", isDirectory: false) + try "#!/bin/sh\nexit 0\n".write(to: fakeOpenCodeURL, atomically: true, encoding: .utf8) + chmod(fakeOpenCodeURL.path, 0o755) + + var environment = ProcessInfo.processInfo.environment + environment.removeValue(forKey: "OPENCODE_CONFIG_DIR") + environment["HOME"] = root.appendingPathComponent("home", isDirectory: true).path + environment["XDG_CONFIG_HOME"] = xdgConfigHome.path + environment["PATH"] = "\(binDir.path):\(environment["PATH"] ?? "/usr/bin")" + environment["CMUX_CLI_SENTRY_DISABLED"] = "1" + + let result = runProcess( + executablePath: cliPath, + arguments: ["hooks", "opencode", "install", "--yes"], + environment: environment, + timeout: 5 + ) + XCTAssertFalse(result.timedOut, result.stderr) + XCTAssertEqual(result.status, 0, result.stderr) + + let configDir = xdgConfigHome.appendingPathComponent("opencode", isDirectory: true) + XCTAssertTrue( + fileManager.fileExists(atPath: configDir.appendingPathComponent("plugins/cmux-session.js").path), + "OpenCode's lifecycle plugin must follow XDG_CONFIG_HOME" + ) + XCTAssertTrue( + fileManager.fileExists(atPath: configDir.appendingPathComponent("plugins/cmux-feed.js").path), + "OpenCode's Feed bridge must follow XDG_CONFIG_HOME" + ) + XCTAssertFalse( + fileManager.fileExists(atPath: root.appendingPathComponent("home/.config/opencode/plugins/cmux-session.js").path), + "OpenCode hooks must not be split across legacy and XDG config directories" + ) + } + private struct ProcessRunResult { let status: Int32 let stdout: String @@ -332,3 +378,42 @@ const fs = require("node:fs"); ) } } + +extension CLINotifyProcessIntegrationRegressionTests { + func testOpenCodeStopFailureFeedEventRetainsErrorState() throws { + let context = try makeClaudeHookContext(name: "opencode-stop-failure-feed") + defer { + Darwin.close(context.listenerFD) + unlink(context.socketPath) + try? FileManager.default.removeItem(at: context.root) + } + startAgentHookMockServerAccepting(context: context) + + let result = runAgentHook( + context: context, + agent: "opencode", + subcommand: "stop", + standardInput: #"{"session_id":"opencode-error-feed","cwd":"/tmp/opencode","hook_event_name":"StopFailure","error":{"name":"UnknownError","data":{"message":"Model not found: unknown/foo"}}}"# + ) + XCTAssertFalse(result.timedOut, result.stderr) + XCTAssertEqual(result.status, 0, result.stderr) + + let deadline = Date().addingTimeInterval(5) + var feedEvent: [String: Any]? + while Date() < deadline, feedEvent == nil { + feedEvent = context.state.snapshot().compactMap { command -> [String: Any]? in + guard let payload = jsonObject(command), + payload["method"] as? String == "feed.push", + let params = payload["params"] as? [String: Any] else { return nil } + return params["event"] as? [String: Any] + }.first + if feedEvent == nil { + RunLoop.current.run(until: Date().addingTimeInterval(0.01)) + } + } + + XCTAssertEqual(feedEvent?["hook_event_name"] as? String, "Stop") + XCTAssertEqual(feedEvent?["is_error"] as? Bool, true) + XCTAssertEqual(feedEvent?["error"] as? String, "Model not found: unknown/foo") + } +} diff --git a/tests/test_opencode_plugin_install.py b/tests/test_opencode_plugin_install.py index ab193488999d..2b4707d981cb 100644 --- a/tests/test_opencode_plugin_install.py +++ b/tests/test_opencode_plugin_install.py @@ -260,23 +260,23 @@ def main() -> int: }); await v1Hooks.event({ event: { - type: "session.status", - properties: { sessionID: "opencode-session-test", status: { type: "idle" } } + type: "session.error", + properties: { + sessionID: "opencode-session-test", + error: { name: "UnknownError", data: { message: "provider failed" } } + } } }); await v1Hooks.event({ event: { - type: "session.idle", - properties: { sessionID: "opencode-session-test" } + type: "session.status", + properties: { sessionID: "opencode-session-test", status: { type: "idle" } } } }); await v1Hooks.event({ event: { - type: "session.error", - properties: { - sessionID: "opencode-session-test", - error: { name: "ProviderAuthError", message: "provider failed" } - } + type: "session.idle", + properties: { sessionID: "opencode-session-test" } } }); """ @@ -305,11 +305,14 @@ def main() -> int: if args_log.count("hooks enqueue opencode session-start") != 1: print(f"FAIL: plugin invoked duplicate session-start hooks, got {args_log!r}") return 1 - if args_log.count("hooks enqueue opencode stop") != 2: - print(f"FAIL: plugin did not dispatch one completion and one failure hook, got {args_log!r}") + if args_log.count("hooks enqueue opencode stop") != 1: + print(f"FAIL: plugin did not coalesce the failure-first stop hook, got {args_log!r}") + return 1 + if stdin_log.count('"hook_event_name":"Stop"') != 0 or stdin_log.count('"hook_event_name":"StopFailure"') != 1: + print(f"FAIL: plugin did not coalesce the failure-first lifecycle, got {stdin_log!r}") return 1 - if stdin_log.count('"hook_event_name":"Stop"') != 1 or stdin_log.count('"hook_event_name":"StopFailure"') != 1: - print(f"FAIL: plugin did not preserve completion/error hook identity, got {stdin_log!r}") + if '"hook_event_name":"StopFailure"' not in stdin_log or '"error":"provider failed"' not in stdin_log: + print(f"FAIL: plugin did not preserve the OpenCode nested error message, got {stdin_log!r}") return 1 if '"session_id":"opencode-session-test"' not in stdin_log or '"/tmp/opencode-project"' not in stdin_log: print(f"FAIL: plugin did not pass expected session payload, got {stdin_log!r}") diff --git a/tests/test_opencode_v2_tui_bridge.py b/tests/test_opencode_v2_tui_bridge.py index fa355ac124c5..47808f7c3aae 100755 --- a/tests/test_opencode_v2_tui_bridge.py +++ b/tests/test_opencode_v2_tui_bridge.py @@ -148,9 +148,11 @@ def main() -> int: liveA.emit({ details: { type: "session.created", data: { sessionID: "child-a", location: { directory: "/tmp/a" } }, location: { directory: "/tmp/a" } } }); await new Promise((resolve) => setImmediate(resolve)); liveA.emit({ details: { type: "session.updated", data: { sessionID: "child-a", info: { id: "child-a", time: { archived: false } } } } }); +// OpenCode 1.19 reports a failure before the idle status and idle marker. +// The failure must win the lifecycle race; the later idle forms are duplicates. +liveA.emit({ details: { type: "session.error", data: { sessionID: "child-a", error: { name: "UnknownError", data: { message: "provider failed" } } } } }); liveA.emit({ details: { type: "session.status", data: { sessionID: "child-a", status: "idle" } } }); liveA.emit({ details: { type: "session.idle", data: { sessionID: "child-a" } } }); -liveA.emit({ details: { type: "session.error", data: { sessionID: "child-a", error: { message: "provider failed" } } } }); liveB.emit({ details: { type: "session.execution.succeeded", data: { sessionID: "child-b" } } }); liveA.emit({ details: { type: "permission.asked", data: { sessionID: "child-a", id: "perm-a", action: "edit", resources: ["/tmp/a/file"] } } }); liveB.emit({ details: { type: "permission.asked", data: { sessionID: "child-a", id: "perm-wrong", action: "edit" } } }); @@ -215,7 +217,7 @@ def main() -> int: const childALifecycle = observed.filter((event) => event.session_id === "opencode-child-a" && ["SessionStart", "Stop"].includes(event.hook_event_name)); if (childALifecycle.filter((event) => event.hook_event_name === "SessionStart").length !== 1) throw new Error("session.updated reopened the OpenCode session"); -if (childALifecycle.filter((event) => event.hook_event_name === "Stop").length !== 2) throw new Error("OpenCode completion/error lifecycle events were lost or duplicated"); +if (childALifecycle.filter((event) => event.hook_event_name === "Stop").length !== 1) throw new Error("OpenCode failure-first lifecycle event was lost or duplicated"); if (!childALifecycle.some((event) => event.hook_event_name === "Stop" && event.is_error === true && event.error === "provider failed")) throw new Error("OpenCode session.error did not preserve an error completion"); if (sessionStart?.surface_id !== "surface-a" || sessionStart?.workspace_id !== "workspace-a") throw new Error("Feed event was routed to the wrong surface"); if (sessionStart?.cwd !== "/tmp/a") throw new Error("V2 session location was dropped from Feed telemetry"); From 353bac7c506e3a11c695a29f01b53bcdde09c283 Mon Sep 17 00:00:00 2001 From: Austin Wang <38676809+austinywang@users.noreply.github.com> Date: Tue, 13 Oct 2026 22:40:00 -0700 Subject: [PATCH 04/20] fix: share OpenCode failure detail extraction Use the same non-optional failure message in notification and Feed delivery, and let the coalesced idle fixture finish on a session-end marker. Co-authored-by: e-jung --- CLI/cmux.swift | 17 +++-------------- cmuxTests/OpenCodeHookRegressionTests.swift | 6 +++++- 2 files changed, 8 insertions(+), 15 deletions(-) diff --git a/CLI/cmux.swift b/CLI/cmux.swift index 2f0bd9929047..e48faf5fc902 100644 --- a/CLI/cmux.swift +++ b/CLI/cmux.swift @@ -40437,21 +40437,10 @@ export default { || event == "error" guard isFailure else { return nil } let rawObject = input.rawObject ?? input.object ?? [:] - let message = firstString( - in: rawObject, - keys: ["error", "message", "reason", "description"] - ) - if message == nil, let error = rawObject["error"] as? [String: Any] { - message = firstString(in: error, keys: ["message", "reason", "description"]) - ?? (error["data"] as? [String: Any]).flatMap { - firstString(in: $0, keys: ["message", "error", "reason", "description"]) - } - ?? firstString(in: error, keys: ["name"]) - } return classifyAgentHookNotification( def: def, signal: event, - message: message, + message: openCodeFailureMessage(from: rawObject) ?? "", isFallback: false ) }() @@ -42097,8 +42086,6 @@ export default { return "fallback-\(String(digest.prefix(16)))" } - /// Feed reading must retain the completion, not the notification preview. - /// Both native Feed hooks and wrapper hooks call this with the raw payload. private func normalizedOpenCodeHookEventName(_ value: String) -> String { value .trimmingCharacters(in: .whitespacesAndNewlines) @@ -42121,6 +42108,8 @@ export default { return message.map { truncate(normalizedSingleLine($0), maxLength: 500) } } + /// Feed reading must retain the completion, not the notification preview. + /// Both native Feed hooks and wrapper hooks call this with the raw payload. private func enrichStopFeedEvent( _ event: inout [String: Any], hookEventName: String, diff --git a/cmuxTests/OpenCodeHookRegressionTests.swift b/cmuxTests/OpenCodeHookRegressionTests.swift index a92f1404e106..144bc1e31395 100644 --- a/cmuxTests/OpenCodeHookRegressionTests.swift +++ b/cmuxTests/OpenCodeHookRegressionTests.swift @@ -293,7 +293,7 @@ const fs = require("node:fs"); if (!line.trim()) continue; const frame = JSON.parse(line); frames.push(frame); - if (frames.length === 4) resolveFrames(); + if (frames.length === 3) resolveFrames(); conn.write(JSON.stringify({ id: frame.id, ok: true, result: { status: "acknowledged" } }) + "\n"); } }); @@ -334,6 +334,10 @@ const fs = require("node:fs"); type: "session.status", properties: { session_id: "ses-feed-shape", status: "idle" } } }); + await hooks.event({ event: { + type: "session.deleted", + properties: { session_id: "ses-feed-shape" } + } }); await framesReady; for (const socket of sockets) socket.destroy(); await new Promise((resolve) => server.close(resolve)); From e6ec9c511239a719cc9fa0b6f58bb8b9922ef3d0 Mon Sep 17 00:00:00 2001 From: Austin Wang <38676809+austinywang@users.noreply.github.com> Date: Tue, 13 Oct 2026 23:31:43 -0700 Subject: [PATCH 05/20] test: wait for OpenCode failure hook --- tests/test_opencode_plugin_install.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/test_opencode_plugin_install.py b/tests/test_opencode_plugin_install.py index 2b4707d981cb..bce3284908fa 100644 --- a/tests/test_opencode_plugin_install.py +++ b/tests/test_opencode_plugin_install.py @@ -297,7 +297,7 @@ def main() -> int: return 1 args_log = wait_for_log(fake_args_log, "hooks enqueue opencode session-start") - stdin_log = wait_for_log(fake_stdin_log, '"session_id":"opencode-session-test"') + stdin_log = wait_for_log(fake_stdin_log, '"hook_event_name":"StopFailure"') env_log = wait_for_log(fake_env_log, "kind=opencode") if "hooks enqueue opencode session-start" not in args_log: print(f"FAIL: plugin did not invoke hooks opencode session-start, got {args_log!r}") From ea430161786f9129cd9c3c370558655d522792be Mon Sep 17 00:00:00 2001 From: Austin Wang <38676809+austinywang@users.noreply.github.com> Date: Wed, 14 Oct 2026 00:31:04 -0700 Subject: [PATCH 06/20] test: cover OpenCode server entry notifications Co-Authored-By: Claude Opus 5.5 --- tests/test-execution.toml | 4 + tests/test_opencode_server_entry.py | 167 ++++++++++++++++++++++++++++ 2 files changed, 171 insertions(+) create mode 100644 tests/test_opencode_server_entry.py diff --git a/tests/test-execution.toml b/tests/test-execution.toml index dd70912a932a..03225bd079e0 100644 --- a/tests/test-execution.toml +++ b/tests/test-execution.toml @@ -1729,6 +1729,10 @@ path = "tests/test_opencode_v2_tui_bridge.py" lane = "manual" reason = "Focused OpenCode V2 Node bridge harness; it uses a TUI/socket fixture and is run by the OpenCode regression verification command." +[[test]] +path = "tests/test_opencode_server_entry.py" +lane = "linux-guard" + [[test]] path = "tests/test_nightly_resume_tracks.py" lane = "linux-guard" diff --git a/tests/test_opencode_server_entry.py b/tests/test_opencode_server_entry.py new file mode 100644 index 000000000000..34e471036b4d --- /dev/null +++ b/tests/test_opencode_server_entry.py @@ -0,0 +1,167 @@ +#!/usr/bin/env python3 +"""Released OpenCode loads cmux through each plugin's default `server` entry. + +OpenCode 1.x (including the current dev channel) calls `default.server(ctx)` +inside the TUI process with `{ client, project, worktree, directory, +serverUrl, $ }` and delivers events through the returned `event` hook. It +loads `cmux-feed.js`, `cmux-session.js` and `plugins/cmux/index.js`, so the +server entries must deliver one Stop per turn instead of returning `{}`. +""" +from __future__ import annotations + +import json +import os +import re +import shutil +import subprocess +import tempfile +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] + + +def session_plugin_source() -> str: + swift = (ROOT / "CLI/cmux.swift").read_text(encoding="utf-8") + match = re.search(r'openCodeSessionPluginSource = #"""\n(.*?)\n"""#', swift, re.S) + if match is None: + raise RuntimeError("openCodeSessionPluginSource not found") + return match.group(1) + + +HARNESS = r''' +const { pluginDir, logPath, socketPath } = JSON.parse(process.env.CMUX_OPENCODE_SERVER_HARNESS); +const fs = await import("node:fs"); +const net = await import("node:net"); +const path = await import("node:path"); + +const frames = []; +const server = net.createServer((connection) => { + connection.setEncoding("utf8"); + connection.on("error", () => {}); + let buffered = ""; + connection.on("data", (chunk) => { + buffered += chunk; + let index; + while ((index = buffered.indexOf("\n")) >= 0) { + const line = buffered.slice(0, index); + buffered = buffered.slice(index + 1); + if (!line) continue; + const frame = JSON.parse(line); + frames.push(frame); + connection.write(JSON.stringify({ id: frame.id, ok: true, result: {} }) + "\n"); + } + }); +}); +await new Promise((resolve) => server.listen(socketPath, resolve)); + +// Shape observed from OpenCode 1.19.0 and the dev channel. +const ctx = { + client: {}, + project: { id: "project" }, + worktree: "/tmp", + directory: "/tmp", + experimental_workspace: {}, + serverUrl: new URL("http://127.0.0.1:4096"), + $: () => {}, +}; + +// Old V2 snapshots called setup()/server() without the server context; they +// must stay inert because their shared service is not owned by one TUI. +const v2 = await import(path.join(pluginDir, "cmux", "index.js")); +const v2Hooks = await v2.default.server({}); +if (v2Hooks && typeof v2Hooks.event === "function") throw new Error("V2 shared server entry subscribed"); +const v2Cleanup = await v2.default.setup({}); +if (typeof v2Cleanup !== "function") throw new Error("V2 setup did not return cleanup"); +v2Cleanup(); + +const hooks = []; +for (const file of ["cmux-feed.js", "cmux-session.js", path.join("cmux", "index.js")]) { + const mod = await import(path.join(pluginDir, file)); + if (typeof mod.default?.server !== "function") throw new Error(`${file} lacks a server entry`); + hooks.push(await mod.default.server(ctx, {})); +} +const active = hooks.filter((hook) => hook && typeof hook.event === "function"); +if (active.length === 0) throw new Error("no OpenCode server entry subscribed to events"); + +const emit = async (event) => { + for (const hook of active) await hook.event({ event }); +}; +const sid = "ses_server_entry"; +await emit({ type: "session.created", properties: { info: { id: sid, directory: "/tmp" } } }); +await emit({ type: "session.status", properties: { sessionID: sid, status: { type: "busy" } } }); +await emit({ type: "session.status", properties: { sessionID: sid, status: { type: "idle" } } }); +await emit({ type: "session.idle", properties: { sessionID: sid } }); + +const deadline = Date.now() + 5000; +const stopFrames = () => frames.filter((frame) => frame.params?.event?.hook_event_name === "Stop"); +const hookLog = () => (fs.existsSync(logPath) ? fs.readFileSync(logPath, "utf8") : ""); +while (Date.now() < deadline && (stopFrames().length === 0 || !hookLog().includes("hooks enqueue opencode stop"))) { + await new Promise((resolve) => setTimeout(resolve, 20)); +} +// Give duplicate deliveries a chance to arrive before counting. +await new Promise((resolve) => setTimeout(resolve, 200)); +const stops = stopFrames(); +if (stops.length !== 1) throw new Error(`expected one feed Stop, got ${stops.length}: ${JSON.stringify(frames)}`); +if (stops[0].params.event.surface_id !== "surface-server-entry") throw new Error("feed Stop lost the surface id"); +const hookStops = hookLog().split("\n").filter((line) => line.includes("hooks enqueue opencode stop")); +if (hookStops.length !== 1) throw new Error(`expected one stop hook, got ${hookStops.length}: ${hookLog()}`); +for (const hook of active) hook.dispose?.(); +server.close(); +console.log("PASS: OpenCode server entry delivers one completion"); +process.exit(0); +''' + + +def main() -> int: + node = shutil.which("node") + if node is None: + print("SKIP: node not found") + return 0 + with tempfile.TemporaryDirectory(prefix="cmux-opencode-server-") as td: + root = Path(td) + plugin_dir = root / "plugins" + package_dir = plugin_dir / "cmux" + package_dir.mkdir(parents=True) + feed_source = (ROOT / "Resources/opencode-plugin.js").read_text(encoding="utf-8") + (plugin_dir / "cmux-feed.js").write_text(feed_source, encoding="utf-8") + (plugin_dir / "cmux-session.js").write_text(session_plugin_source(), encoding="utf-8") + (package_dir / "index.js").write_text( + "// cmux-opencode-tui-plugin-server-marker v2\n" + feed_source, encoding="utf-8" + ) + (plugin_dir / "package.json").write_text('{"type":"module"}', encoding="utf-8") + (package_dir / "package.json").write_text('{"type":"module"}', encoding="utf-8") + log_path = root / "cmux.log" + fake_cmux = root / "cmux" + fake_cmux.write_text(f'#!/bin/sh\necho "$*" >> "{log_path}"\ncat >/dev/null\n', encoding="utf-8") + fake_cmux.chmod(0o755) + socket_path = f"/tmp/cmux-oc-server-{os.getpid()}.sock" + env = os.environ.copy() + env.update( + CMUX_SURFACE_ID="surface-server-entry", + CMUX_WORKSPACE_ID="workspace-server-entry", + CMUX_SOCKET_PATH=socket_path, + CMUX_OPENCODE_CMUX_BIN=str(fake_cmux), + CMUX_OPENCODE_HOOKS_DISABLED="", + CMUX_OPENCODE_SERVER_HARNESS=json.dumps( + {"pluginDir": str(plugin_dir), "logPath": str(log_path), "socketPath": socket_path} + ), + ) + harness = root / "harness.mjs" + harness.write_text(HARNESS, encoding="utf-8") + try: + result = subprocess.run([node, str(harness)], env=env, capture_output=True, text=True, timeout=30) + finally: + try: + os.unlink(socket_path) + except FileNotFoundError: + pass + sys_out = (result.stdout + result.stderr).strip() + if result.returncode != 0: + print(f"FAIL: {sys_out[-3000:]}") + return 1 + print(sys_out) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) From 7a30c279b218a453962bcc460707aa59f52f01b4 Mon Sep 17 00:00:00 2001 From: Austin Wang <38676809+austinywang@users.noreply.github.com> Date: Wed, 14 Oct 2026 00:32:20 -0700 Subject: [PATCH 07/20] fix: activate OpenCode server plugin entries Released OpenCode (1.x and the dev channel) loads cmux through each plugin's default server(ctx) entry inside the TUI process. Those entries returned {}, so no lifecycle event reached cmux. Subscribe when the TUI process server context is present, once per process. Co-Authored-By: Claude Opus 5.5 --- CLI/cmux.swift | 11 ++++++++--- Resources/opencode-plugin.js | 17 +++++++++++++++-- 2 files changed, 23 insertions(+), 5 deletions(-) diff --git a/CLI/cmux.swift b/CLI/cmux.swift index e48faf5fc902..26e90abbb533 100644 --- a/CLI/cmux.swift +++ b/CLI/cmux.swift @@ -36753,11 +36753,16 @@ export const CMUXSessionRestore = async (ctx) => { return createCMUXSessionRestore(ctx); }; +// Released OpenCode calls `server(ctx)` inside each TUI process with the +// project server context. Old V2 snapshots called it from a shared service +// without that context, so only subscribe when it is present. +function isTUIProcessServerContext(ctx) { + return Boolean(ctx && typeof ctx === "object" && ctx.client && ctx.serverUrl && ctx.directory); +} + export default { id: "cmux.server", - // Keep the legacy server entry inert in V2. Session hooks run from the - // per-TUI ./tui entrypoint so a shared service never reuses one TUI's IDs. - server() { return {}; }, + server(ctx) { return isTUIProcessServerContext(ctx) ? CMUXSessionRestore(ctx) : {}; }, // Compatibility alias for older V2 snapshots that called setup(). setup() { return () => {}; }, }; diff --git a/Resources/opencode-plugin.js b/Resources/opencode-plugin.js index 7a8e122f4e07..7880be517709 100644 --- a/Resources/opencode-plugin.js +++ b/Resources/opencode-plugin.js @@ -1061,10 +1061,23 @@ const createCMUXFeed = async (ctx, options = {}) => { export const CMUXFeed = createCMUXFeed; +const CMUX_FEED_SERVER_INSTALLED_KEY = Symbol.for("cmux.feed.server.installed"); + +// Released OpenCode calls `server(ctx)` inside each TUI process with the +// project server context. Old V2 snapshots called it from a shared service +// without that context, so only subscribe when it is present. +const isTUIProcessServerContext = (ctx) => + Boolean(ctx && typeof ctx === "object" && ctx.client && ctx.serverUrl && ctx.directory); + export default { id: "cmux.server", - // V2 uses the package's ./tui export; never subscribe in the shared service. - server() { return {}; }, + async server(ctx) { + if (!isTUIProcessServerContext(ctx)) return {}; + // cmux-feed.js and plugins/cmux/index.js both load this source. + if (globalThis[CMUX_FEED_SERVER_INSTALLED_KEY]) return {}; + globalThis[CMUX_FEED_SERVER_INSTALLED_KEY] = true; + return createCMUXFeed(ctx); + }, // Compatibility alias for older V2 snapshots that called setup(). setup() { return () => {}; }, }; From 2e3ecf544bf914788186596143fef04a887dc0a5 Mon Sep 17 00:00:00 2001 From: Austin Wang <38676809+austinywang@users.noreply.github.com> Date: Wed, 14 Oct 2026 00:55:31 -0700 Subject: [PATCH 08/20] fix(opencode): publish one terminal stop per turn A turn now settles on its first terminal event and is reopened only by a turn identity the session has not seen (a new user message or prompt). Repeated message updates and busy status no longer clear the recorded stop, and a failure after a published idle stop is dropped instead of producing a second notification. Applies to the Feed bridge and the session plugin source. Co-Authored-By: Claude Opus 5.5 --- CLI/cmux.swift | 38 ++++++++++-------- Resources/opencode-plugin.js | 36 ++++++++++++------ tests/test_opencode_plugin_install.py | 55 +++++++++++++++++++++------ 3 files changed, 92 insertions(+), 37 deletions(-) diff --git a/CLI/cmux.swift b/CLI/cmux.swift index de28ebb1131e..e19fa3f04b0b 100644 --- a/CLI/cmux.swift +++ b/CLI/cmux.swift @@ -36460,6 +36460,7 @@ function sessionState(sessionId) { assistantPreamble: null, cwd: null, lastStopKind: null, + turnKeys: new Set(), updatedAt: Date.now(), }); } @@ -36523,10 +36524,24 @@ function sessionStatusType(status) { return firstString(status.type, status.status, status.state)?.toLowerCase() || null; } +// A turn publishes exactly one terminal stop. Only a turn identity this +// session has not seen clears it, so a repeated update for the same prompt +// cannot reopen a finished turn. A missing identity starts a new turn. +function beginTurn(sessionId, turnKey) { + const state = sessionState(sessionId); + if (turnKey) { + if (state.turnKeys.has(turnKey)) return; + state.turnKeys.add(turnKey); + if (state.turnKeys.size > 50) state.turnKeys.delete(state.turnKeys.values().next().value); + } + state.lastStopKind = null; +} + +// The first terminal event settles the turn. A published stop cannot be +// reclassified, so a later failure or idle for the same turn is dropped. function shouldSendStop(sessionId, kind) { const state = sessionState(sessionId); - if (state.lastStopKind === "failure") return false; - if (state.lastStopKind === "success" && kind === "success") return false; + if (state.lastStopKind) return false; state.lastStopKind = kind; return true; } @@ -36680,7 +36695,7 @@ function trackMessage(event) { const role = info.role || props.role; if (messageId && sessionId && role) { messageRoles.set(messageId, { sessionId, role }); - if (role === "user") sessionState(sessionId).lastStopKind = null; + if (role === "user") beginTurn(sessionId, messageId); if (messageRoles.size > 300) { messageRoles.delete(messageRoles.keys().next().value); } @@ -36703,19 +36718,12 @@ function trackMessage(event) { } } +// Busy status carries no turn identity; prompts and user messages own it. function resetTurnFromEvent(event) { + if (!["session.next.prompted", "session.next.prompt.admitted", "session.inbox.enqueued"].includes(event?.type)) return; + const sessionId = sessionIdFor(event); const props = eventProperties(event); - if (["session.next.prompted", "session.next.prompt.admitted", "session.inbox.enqueued"].includes(event?.type)) { - const sessionId = sessionIdFor(event); - if (sessionId) sessionState(sessionId).lastStopKind = null; - return; - } - if (event?.type === "session.status") { - if (sessionStatusType(props.status) === "busy") { - const sessionId = sessionIdFor(event); - if (sessionId) sessionState(sessionId).lastStopKind = null; - } - } + if (sessionId) beginTurn(sessionId, firstString(props.item?.id, props.messageID, props.promptID, props.id, event.id)); } function sendStop(ctx, event, failed = false) { @@ -36735,7 +36743,7 @@ const createCMUXSessionRestore = async (ctx) => { const props = eventProperties(event); switch (event && event.type) { case "session.created": - sessionState(sessionIdFor(event)).lastStopKind = null; + beginTurn(sessionIdFor(event), null); sendHook("session-start", ctx, event); break; case "session.updated": diff --git a/Resources/opencode-plugin.js b/Resources/opencode-plugin.js index 7880be517709..790407757f29 100644 --- a/Resources/opencode-plugin.js +++ b/Resources/opencode-plugin.js @@ -127,11 +127,25 @@ const createCMUXFeed = async (ctx, options = {}) => { assistantPreamble: null, cwd: null, lastStopKind: null, + turnKeys: new Set(), }); } return sessions.get(key); }; + // A turn publishes exactly one terminal stop. Only a turn identity this + // session has not seen clears it, so a repeated update for the same prompt + // cannot reopen a finished turn. A missing identity starts a new turn. + const beginTurn = (sessionId, turnKey) => { + const state = sessionState(sessionId); + if (turnKey) { + if (state.turnKeys.has(turnKey)) return; + state.turnKeys.add(turnKey); + if (state.turnKeys.size > 50) state.turnKeys.delete(state.turnKeys.values().next().value); + } + state.lastStopKind = null; + }; + const contextForSession = (sessionId) => { const state = sessionState(sessionId); const context = {}; @@ -692,7 +706,7 @@ const createCMUXFeed = async (ctx, options = {}) => { if (!sid || !text) return null; const state = sessionState(sid); state.lastUserMessage = text; - state.lastStopKind = null; + beginTurn(sid, firstString(item.id, props.id, event.id)); return base(sid, { hook_event_name: "UserPromptSubmit", tool_input: { prompt: text }, @@ -712,7 +726,7 @@ const createCMUXFeed = async (ctx, options = {}) => { const role = info.role || props.role; if (messageId && sessionId && role) { messageRoles.set(messageId, { sessionId, role }); - if (role === "user") sessionState(sessionId).lastStopKind = null; + if (role === "user") beginTurn(sessionId, messageId); if (messageRoles.size > 300) { messageRoles.delete(messageRoles.keys().next().value); } @@ -730,7 +744,7 @@ const createCMUXFeed = async (ctx, options = {}) => { const state = sessionState(meta.sessionId); if (meta.role === "user") { state.lastUserMessage = text; - state.lastStopKind = null; + beginTurn(meta.sessionId, part.messageID); return base(meta.sessionId, { hook_event_name: "UserPromptSubmit", tool_input: { prompt: text }, @@ -744,9 +758,10 @@ const createCMUXFeed = async (ctx, options = {}) => { }; const shouldEmitStop = (sessionId, kind) => { + // The first terminal event settles the turn. A published stop cannot be + // reclassified, so a later failure or idle for the same turn is dropped. const state = sessionState(sessionId); - if (state.lastStopKind === "failure") return false; - if (state.lastStopKind === "success" && kind === "success") return false; + if (state.lastStopKind) return false; state.lastStopKind = kind; return true; }; @@ -807,8 +822,8 @@ const createCMUXFeed = async (ctx, options = {}) => { const props = eventProperties(event); const info = props.info || {}; const sid = sessionIdFromProperties(props) || "unknown"; + beginTurn(sid, null); const state = sessionState(sid); - state.lastStopKind = null; state.cwd = info.directory || props.location?.directory || event.location?.directory || ctx?.location?.directory || ctx?.directory || state.cwd; pushTelemetry(base(sid, { hook_event_name: "SessionStart", @@ -819,10 +834,8 @@ const createCMUXFeed = async (ctx, options = {}) => { case "session.status": { const props = eventProperties(event); const sid = sessionIdFromProperties(props); - if (sid && sessionStatusType(props.status) === "busy") { - sessionState(sid).lastStopKind = null; - break; - } + // Busy carries no turn identity; prompts and user messages own it. + if (sid && sessionStatusType(props.status) === "busy") break; if (!sessionStatusIsIdle(props.status)) break; if (!sid || !shouldEmitStop(sid, "success")) break; pushTelemetry(base(sid, { @@ -870,7 +883,8 @@ const createCMUXFeed = async (ctx, options = {}) => { case "session.next.prompted": case "session.next.prompt.admitted": { const sid = sessionIdFromEvent(event); - if (sid) sessionState(sid).lastStopKind = null; + const props = eventProperties(event); + if (sid) beginTurn(sid, firstString(props.messageID, props.promptID, props.id, event.id)); break; } case "session.deleted": { diff --git a/tests/test_opencode_plugin_install.py b/tests/test_opencode_plugin_install.py index bce3284908fa..8d477faafc93 100644 --- a/tests/test_opencode_plugin_install.py +++ b/tests/test_opencode_plugin_install.py @@ -177,13 +177,12 @@ def main() -> int: check_env["FAKE_CMUX_STDIN_LOG"] = str(fake_stdin_log) check_env["FAKE_CMUX_ENV_LOG"] = str(fake_env_log) check_env["CMUX_OPENCODE_HOOKS_DISABLED"] = "" - for launch_key in ( - "CMUX_AGENT_LAUNCH_KIND", - "CMUX_AGENT_LAUNCH_EXECUTABLE", - "CMUX_AGENT_LAUNCH_ARGV_B64", - "CMUX_AGENT_LAUNCH_CWD", - ): - check_env.pop(launch_key, None) + # OpenCode started from a shell inside another agent inherits that + # agent's launch capture; the plugin must record OpenCode's own. + check_env["CMUX_AGENT_LAUNCH_KIND"] = "claude" + check_env["CMUX_AGENT_LAUNCH_EXECUTABLE"] = "/opt/homebrew/bin/claude" + check_env["CMUX_AGENT_LAUNCH_ARGV_B64"] = base64.b64encode(b"/opt/homebrew/bin/claude\0").decode() + check_env["CMUX_AGENT_LAUNCH_CWD"] = "/tmp/claude-project" check_source = """ const pluginPath = process.env.CMUX_TEST_OPENCODE_PLUGIN_PATH; const pluginCopyPath = process.env.CMUX_TEST_OPENCODE_PLUGIN_COPY_PATH; @@ -235,6 +234,8 @@ def main() -> int: 0, process.argv.length, "/Users/example/.bun/bin/opencode", + // OpenCode 1.x reports src/index.js; V2 reports the TUI worker. + "/$bunfs/root/src/index.js", "/$bunfs/root/src/cli/cmd/tui/worker.js", "--model", "anthropic/claude-sonnet-4-6" @@ -279,6 +280,29 @@ def main() -> int: properties: { sessionID: "opencode-session-test" } } }); +// One terminal stop per turn. A new user message starts turn 2; a repeated +// update for that same message after its stop must not reopen the turn, and a +// failure after the published idle stop is dropped rather than reclassified. +const userMessage = (id) => ({ + event: { + type: "message.updated", + properties: { info: { id, sessionID: "opencode-session-test", role: "user" } } + } +}); +const idle = { event: { type: "session.idle", properties: { sessionID: "opencode-session-test" } } }; +const failure = { + event: { + type: "session.error", + properties: { sessionID: "opencode-session-test", error: { name: "UnknownError", data: { message: "late failure" } } } + } +}; +await v1Hooks.event(userMessage("msg-turn-2")); +await v1Hooks.event({ event: { type: "session.status", properties: { sessionID: "opencode-session-test", status: { type: "busy" } } } }); +await v1Hooks.event(idle); +await v1Hooks.event(userMessage("msg-turn-2")); +await v1Hooks.event({ event: { type: "session.status", properties: { sessionID: "opencode-session-test", status: { type: "busy" } } } }); +await v1Hooks.event(idle); +await v1Hooks.event(failure); """ check = subprocess.run( [bun, "--eval", check_source], @@ -296,6 +320,12 @@ def main() -> int: print(f"stderr={check.stderr.strip()}") return 1 + deadline = time.monotonic() + 5.0 + while time.monotonic() < deadline: + stdin_text = fake_stdin_log.read_text(encoding="utf-8") if fake_stdin_log.exists() else "" + if stdin_text.count('"hook_event_name":"Stop') >= 2: + break + time.sleep(0.01) args_log = wait_for_log(fake_args_log, "hooks enqueue opencode session-start") stdin_log = wait_for_log(fake_stdin_log, '"hook_event_name":"StopFailure"') env_log = wait_for_log(fake_env_log, "kind=opencode") @@ -305,11 +335,14 @@ def main() -> int: if args_log.count("hooks enqueue opencode session-start") != 1: print(f"FAIL: plugin invoked duplicate session-start hooks, got {args_log!r}") return 1 - if args_log.count("hooks enqueue opencode stop") != 1: - print(f"FAIL: plugin did not coalesce the failure-first stop hook, got {args_log!r}") + if args_log.count("hooks enqueue opencode stop") != 2: + print(f"FAIL: plugin did not publish exactly one stop per turn, got {args_log!r}") + return 1 + if stdin_log.count('"hook_event_name":"Stop"') != 1 or stdin_log.count('"hook_event_name":"StopFailure"') != 1: + print(f"FAIL: plugin did not settle one terminal outcome per turn, got {stdin_log!r}") return 1 - if stdin_log.count('"hook_event_name":"Stop"') != 0 or stdin_log.count('"hook_event_name":"StopFailure"') != 1: - print(f"FAIL: plugin did not coalesce the failure-first lifecycle, got {stdin_log!r}") + if "late failure" in stdin_log: + print(f"FAIL: plugin reclassified a turn after its stop was published, got {stdin_log!r}") return 1 if '"hook_event_name":"StopFailure"' not in stdin_log or '"error":"provider failed"' not in stdin_log: print(f"FAIL: plugin did not preserve the OpenCode nested error message, got {stdin_log!r}") From dc19c3bcc82030a42c6dc285da604f7966e9d481 Mon Sep 17 00:00:00 2001 From: Austin Wang <38676809+austinywang@users.noreply.github.com> Date: Wed, 14 Oct 2026 00:55:31 -0700 Subject: [PATCH 09/20] fix(opencode): redact credentials in upstream failure text OpenCode error text reaches notifications and Feed error fields. Redact credentials, bearer tokens, JWTs and emails first, keep paths and model names readable, and fall back to product copy when nothing safe remains. Co-Authored-By: Claude Opus 5.5 --- CLI/AgentHookNotificationPolicy.swift | 24 +++++++++++++ CLI/cmux.swift | 30 +++++++++++----- cmuxTests/OpenCodeHookRegressionTests.swift | 38 +++++++++++++++++++++ 3 files changed, 83 insertions(+), 9 deletions(-) diff --git a/CLI/AgentHookNotificationPolicy.swift b/CLI/AgentHookNotificationPolicy.swift index c228b2458442..23d73a92b01c 100644 --- a/CLI/AgentHookNotificationPolicy.swift +++ b/CLI/AgentHookNotificationPolicy.swift @@ -435,6 +435,30 @@ enum AgentHookNotificationPolicy { return patternIndex == patternScalars.count } + /// Redacts credentials in upstream error text before notifications or + /// Feed show it. Unlike commands, paths and long identifiers such as model + /// names stay readable because they are the useful part of the error. + static func redactSensitiveErrorDetail(_ value: String) -> String { + let boundedValue = value.utf8.count > 8_192 + ? String(decoding: value.utf8.prefix(8_191), as: UTF8.self) + "…" + : value + let patterns: [(pattern: String, replacement: String)] = [ + (#"[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}"#, ""), + (#"\b(?:gh[pousr]_[A-Za-z0-9_]{20,}|AKIA[0-9A-Z]{16})\b"#, ""), + (#"(?i)\bBearer\s+[A-Za-z0-9._~+/=-]{12,}"#, "Bearer "), + (#"\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\b"#, ""), + (#"(?i)\b(?:x[-_])?(?:api[-_]?key|password|secret|token|authorization|cookie)\s*[:=]\s*(?:Bearer\s+)?(?:'[^']*'|\"[^\"]*\"|[^\s'\";&|,]+)"#, ":"), + (#"\b(?:sk|rk|sess)-[A-Za-z0-9._:-]{8,}\b"#, ""), + ] + return patterns.reduce(boundedValue) { partial, entry in + partial.replacingOccurrences( + of: entry.pattern, + with: entry.replacement, + options: [.regularExpression, .caseInsensitive] + ) + } + } + /// Redacts credentials before a command reaches durable hook state or UI. static func redactSensitiveCommand(_ value: String) -> String { let boundedValue = value.utf8.count > 8_192 diff --git a/CLI/cmux.swift b/CLI/cmux.swift index e19fa3f04b0b..5699954876c8 100644 --- a/CLI/cmux.swift +++ b/CLI/cmux.swift @@ -42136,18 +42136,30 @@ export default { .lowercased() } + /// Upstream error text reaches notifications and Feed, so credentials are + /// redacted first. Nil when no safe detail remains; callers then + /// use their product-level failure copy. private func openCodeFailureMessage(from object: [String: Any]) -> String? { + let raw: String? if let message = firstString(in: object, keys: ["error", "message", "reason", "description"]) { - return truncate(normalizedSingleLine(message), maxLength: 500) + raw = message + } else if let error = object["error"] as? [String: Any] { + let nestedData = error["data"] as? [String: Any] + raw = firstString(in: error, keys: ["message", "reason", "description"]) + ?? nestedData.flatMap { + firstString(in: $0, keys: ["message", "error", "reason", "description"]) + } + ?? firstString(in: error, keys: ["name"]) + } else { + raw = nil } - guard let error = object["error"] as? [String: Any] else { return nil } - let nestedData = error["data"] as? [String: Any] - let message = firstString(in: error, keys: ["message", "reason", "description"]) - ?? nestedData.flatMap { - firstString(in: $0, keys: ["message", "error", "reason", "description"]) - } - ?? firstString(in: error, keys: ["name"]) - return message.map { truncate(normalizedSingleLine($0), maxLength: 500) } + guard let raw else { return nil } + let redacted = normalizedSingleLine(AgentHookNotificationPolicy.redactSensitiveErrorDetail(normalizedSingleLine(raw))) + let remaining = redacted.replacingOccurrences( + of: #"<[a-z]+>|[\s\p{P}]"#, with: "", options: .regularExpression + ) + guard !remaining.isEmpty else { return nil } + return truncate(redacted, maxLength: 500) } /// Feed reading must retain the completion, not the notification preview. diff --git a/cmuxTests/OpenCodeHookRegressionTests.swift b/cmuxTests/OpenCodeHookRegressionTests.swift index 144bc1e31395..06306b957530 100644 --- a/cmuxTests/OpenCodeHookRegressionTests.swift +++ b/cmuxTests/OpenCodeHookRegressionTests.swift @@ -420,4 +420,42 @@ extension CLINotifyProcessIntegrationRegressionTests { XCTAssertEqual(feedEvent?["is_error"] as? Bool, true) XCTAssertEqual(feedEvent?["error"] as? String, "Model not found: unknown/foo") } + + func testOpenCodeStopFailureFeedEventRedactsCredentials() throws { + let context = try makeClaudeHookContext(name: "opencode-stop-failure-redact") + defer { + Darwin.close(context.listenerFD) + unlink(context.socketPath) + try? FileManager.default.removeItem(at: context.root) + } + startAgentHookMockServerAccepting(context: context) + + let result = runAgentHook( + context: context, + agent: "opencode", + subcommand: "stop", + standardInput: #"{"session_id":"opencode-error-redact","cwd":"/tmp/opencode","hook_event_name":"StopFailure","error":{"name":"UnknownError","data":{"message":"401 invalid x-api-key: sk-ant-api03-abcdefghijklmnop for me@example.com"}}}"# + ) + XCTAssertFalse(result.timedOut, result.stderr) + XCTAssertEqual(result.status, 0, result.stderr) + + let deadline = Date().addingTimeInterval(5) + var feedEvent: [String: Any]? + while Date() < deadline, feedEvent == nil { + feedEvent = context.state.snapshot().compactMap { command -> [String: Any]? in + guard let payload = jsonObject(command), + payload["method"] as? String == "feed.push", + let params = payload["params"] as? [String: Any] else { return nil } + return params["event"] as? [String: Any] + }.first + if feedEvent == nil { + RunLoop.current.run(until: Date().addingTimeInterval(0.01)) + } + } + + XCTAssertEqual(feedEvent?["hook_event_name"] as? String, "Stop") + XCTAssertEqual(feedEvent?["is_error"] as? Bool, true) + // Upstream error text reaches Feed and notifications; credentials must not. + XCTAssertEqual(feedEvent?["error"] as? String, "401 invalid : for ") + } } From 8c75b03e198eb9ee831b58df448eeb12d04263b1 Mon Sep 17 00:00:00 2001 From: Austin Wang <38676809+austinywang@users.noreply.github.com> Date: Wed, 14 Oct 2026 00:55:32 -0700 Subject: [PATCH 10/20] fix(opencode): record OpenCode's own launch for resume On OpenCode 1.x the TUI process argv is [opencode, /$bunfs/root/src/index.js], and the sanitizer only dropped the V2 TUI worker entry, so restore replayed the Bun virtual path as a project directory. Drop any Bun virtual entry. Also stop reusing an inherited launch capture that describes another agent, which recorded e.g. a Claude command for an OpenCode session started from a Claude shell. Co-Authored-By: Claude Opus 5.5 --- CLI/cmux.swift | 8 ++++++-- .../Sources/CMUXAgentLaunch/AgentLaunchSanitizer.swift | 4 +++- .../OpenCodeBunWorkerSanitizerTests.swift | 2 ++ 3 files changed, 11 insertions(+), 3 deletions(-) diff --git a/CLI/cmux.swift b/CLI/cmux.swift index 5699954876c8..6185ecfc1217 100644 --- a/CLI/cmux.swift +++ b/CLI/cmux.swift @@ -36598,10 +36598,12 @@ function looksLikeOpenCodeScript(value) { return lower.includes("opencode") || lower.includes("open-code"); } +// Compiled OpenCode reports Bun's virtual entry (src/index.js on 1.x, the TUI +// worker on V2) as an argument. It is never a user argument. function isOpenCodeInternalWorkerArg(value) { if (!value) return false; const normalized = String(value).replaceAll("\\", "/"); - return normalized.includes("/$bunfs/") && normalized.endsWith("/tui/worker.js"); + return normalized.includes("/$bunfs/") || normalized.includes("/~BUN/"); } function withoutOpenCodeInternalWorkerArgs(argv) { @@ -36640,7 +36642,9 @@ function base64NulSeparated(values) { function hookEnvironment(cwd) { const env = { ...process.env }; delete env.AMP_API_KEY; - if (!env.CMUX_AGENT_LAUNCH_ARGV_B64) { + // A shell started inside another agent inherits that agent's launch + // capture. Only reuse a capture that already describes OpenCode. + if (env.CMUX_AGENT_LAUNCH_KIND !== "opencode" || !env.CMUX_AGENT_LAUNCH_ARGV_B64) { const argv = normalizedLaunchArgv(); env.CMUX_AGENT_LAUNCH_KIND = "opencode"; env.CMUX_AGENT_LAUNCH_EXECUTABLE = argv[0] || resolveExecutable("opencode"); diff --git a/Packages/macOS/CMUXAgentLaunch/Sources/CMUXAgentLaunch/AgentLaunchSanitizer.swift b/Packages/macOS/CMUXAgentLaunch/Sources/CMUXAgentLaunch/AgentLaunchSanitizer.swift index 861e653bcfb5..471d8ea06194 100644 --- a/Packages/macOS/CMUXAgentLaunch/Sources/CMUXAgentLaunch/AgentLaunchSanitizer.swift +++ b/Packages/macOS/CMUXAgentLaunch/Sources/CMUXAgentLaunch/AgentLaunchSanitizer.swift @@ -165,8 +165,10 @@ public enum AgentLaunchSanitizer { var tail = args while let first = tail.first { let normalized = first.replacingOccurrences(of: "\\", with: "/") + // Compiled OpenCode reports Bun's virtual entry (src/index.js on + // 1.x, the TUI worker on V2); it is never a user argument. let isInternalArgument = first == "tui-settings" || - (normalized.contains("/$bunfs/") && normalized.hasSuffix("/tui/worker.js")) + normalized.contains("/$bunfs/") || normalized.contains("/~BUN/") guard isInternalArgument else { break } tail.removeFirst() } diff --git a/Packages/macOS/CMUXAgentLaunch/Tests/CMUXAgentLaunchTests/OpenCodeBunWorkerSanitizerTests.swift b/Packages/macOS/CMUXAgentLaunch/Tests/CMUXAgentLaunchTests/OpenCodeBunWorkerSanitizerTests.swift index 68c5c2dc4597..f958fa72cca2 100644 --- a/Packages/macOS/CMUXAgentLaunch/Tests/CMUXAgentLaunchTests/OpenCodeBunWorkerSanitizerTests.swift +++ b/Packages/macOS/CMUXAgentLaunch/Tests/CMUXAgentLaunchTests/OpenCodeBunWorkerSanitizerTests.swift @@ -6,6 +6,8 @@ struct OpenCodeBunWorkerSanitizerTests { @Test("Drops internal TUI worker paths", arguments: [ "/$bunfs/root/src/cli/cmd/tui/worker.js", "/$bunfs/root/src/cli/tui/worker.js", + "/$bunfs/root/src/index.js", + "B:/~BUN/root/src/index.js", ]) func dropsInternalTUIWorkerPaths(workerPath: String) { #expect( From c3198e3d19ef127dee62edb7ad7cb0de6d338516 Mon Sep 17 00:00:00 2001 From: Austin Wang <38676809+austinywang@users.noreply.github.com> Date: Wed, 14 Oct 2026 00:55:32 -0700 Subject: [PATCH 11/20] fix(cmux-tui): keep shutdown-interrupted OpenCode turns running OpenCode retains an execution interrupted by shutdown and resumes it, so map that interruption to agent.state.changed instead of completing the turn. Read the structured reason before redaction replaces free-form strings. Co-Authored-By: Claude Opus 5.5 --- .../crates/cmux-tui-core/src/agent_hooks.rs | 33 ++++++++++++++++++- 1 file changed, 32 insertions(+), 1 deletion(-) diff --git a/cmux-tui/crates/cmux-tui-core/src/agent_hooks.rs b/cmux-tui/crates/cmux-tui-core/src/agent_hooks.rs index 129a1f8ed607..f84ecebded60 100644 --- a/cmux-tui/crates/cmux-tui-core/src/agent_hooks.rs +++ b/cmux-tui/crates/cmux-tui-core/src/agent_hooks.rs @@ -47,10 +47,18 @@ pub fn agent_hook_journal_ingress( validate_agent_source(source)?; validate_native_event(native_event)?; let terminal_id = terminal_id.map(TerminalPublicId::parse).transpose()?; + // Read the structured reason before redaction replaces free-form strings. + let resumable_interruption = is_resumable_opencode_interruption(source, native_event, &native); let native = redact_agent_native(native_event, native); let mut normalized = normalized_fields(&native); add_agent_topology(source, native_event, terminal_id.as_ref(), &mut normalized); - let kind = semantic_kind(source, native_event, &normalized); + let kind = if resumable_interruption { + // OpenCode keeps a shutdown-interrupted execution and resumes it, so + // the turn is still running rather than completed. + "agent.state.changed" + } else { + semantic_kind(source, native_event, &normalized) + }; let mut subjects = Vec::with_capacity(4); if let Some(terminal_id) = terminal_id { subjects.push(JournalSubject { kind: "terminal".into(), id: terminal_id.to_string() }); @@ -335,6 +343,17 @@ fn semantic_kind( } } +fn is_resumable_opencode_interruption(source: &str, native_event: &str, native: &Value) -> bool { + if source != "opencode" || semantic_key(native_event) != "sessionexecutioninterrupted" { + return false; + } + let event = native.get("event").unwrap_or(native); + ["data", "properties"] + .iter() + .filter_map(|key| event.get(key)) + .any(|properties| properties.get("reason").and_then(Value::as_str) == Some("shutdown")) +} + fn is_child_spawn(event: &str) -> bool { matches!( event, @@ -981,6 +1000,18 @@ mod tests { } } + #[test] + fn opencode_shutdown_interruption_keeps_the_turn_running() { + let interrupted = "session.execution.interrupted"; + let kind = |field: &str, reason: &str| { + let native = json!({"event":{"type":interrupted,field:{"reason":reason}}}); + agent_hook_journal_ingress("opencode", interrupted, None, native).unwrap().kind + }; + assert_eq!(kind("data", "shutdown"), "agent.state.changed"); + assert_eq!(kind("properties", "shutdown"), "agent.state.changed"); + assert_eq!(kind("data", "user"), "agent.turn.completed"); + } + #[test] fn current_opencode_completion_events_report_completed_turns() { for event in ["session.execution.succeeded", "session.execution.interrupted"] { From 19a62eb777b408681ac8ed0f88807c57ceea4486 Mon Sep 17 00:00:00 2001 From: Austin Wang <38676809+austinywang@users.noreply.github.com> Date: Wed, 14 Oct 2026 00:55:32 -0700 Subject: [PATCH 12/20] test: register the OpenCode server-entry harness as manual No workflow names tests/test_opencode_server_entry.py, so the registry guard rejected its linux-guard lane. Co-Authored-By: Claude Opus 5.5 --- tests/test-execution.toml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/test-execution.toml b/tests/test-execution.toml index 03225bd079e0..6c13d617b9ec 100644 --- a/tests/test-execution.toml +++ b/tests/test-execution.toml @@ -1731,7 +1731,8 @@ reason = "Focused OpenCode V2 Node bridge harness; it uses a TUI/socket fixture [[test]] path = "tests/test_opencode_server_entry.py" -lane = "linux-guard" +lane = "manual" +reason = "Focused OpenCode server-entry Node harness; no workflow names it yet, so it is run by the OpenCode regression verification command." [[test]] path = "tests/test_nightly_resume_tracks.py" From 8a659bfbbbb3eb942543929f4c8918bf7ff5ab7f Mon Sep 17 00:00:00 2001 From: Austin Wang <38676809+austinywang@users.noreply.github.com> Date: Wed, 14 Oct 2026 00:50:55 -0700 Subject: [PATCH 13/20] fix: resubscribe OpenCode server entries after scope reinit The process-global guards blocked a reinitialized plugin scope from subscribing again. Key the owner on the plugin ctx, which every loader in one scope shares, and replace the previous feed when it changes. The regression harness now waits on a session.deleted sentinel instead of a fixed delay and keeps its socket in the temporary directory. Co-Authored-By: Claude Opus 5.5 --- CLI/cmux.swift | 13 +++- Resources/opencode-plugin.js | 22 +++++-- tests/test_opencode_server_entry.py | 97 +++++++++++++++++++---------- 3 files changed, 93 insertions(+), 39 deletions(-) diff --git a/CLI/cmux.swift b/CLI/cmux.swift index 6185ecfc1217..98dda98aaf2d 100644 --- a/CLI/cmux.swift +++ b/CLI/cmux.swift @@ -36801,9 +36801,20 @@ function isTUIProcessServerContext(ctx) { return Boolean(ctx && typeof ctx === "object" && ctx.client && ctx.serverUrl && ctx.directory); } +const CMUX_SESSION_SERVER_OWNER_KEY = Symbol.for("cmux.session.server.owner"); + export default { id: "cmux.server", - server(ctx) { return isTUIProcessServerContext(ctx) ? CMUXSessionRestore(ctx) : {}; }, + server(ctx) { + if (!isTUIProcessServerContext(ctx)) return {}; + // Every loader in one plugin scope receives the same ctx; a reinitialized + // scope receives a new one and must subscribe again. + const owner = globalThis[CMUX_SESSION_SERVER_OWNER_KEY] ||= { ctx: null }; + if (owner.ctx === ctx) return {}; + owner.ctx = ctx; + globalThis[CMUX_PLUGIN_INSTALLED_KEY] = true; + return createCMUXSessionRestore(ctx); + }, // Compatibility alias for older V2 snapshots that called setup(). setup() { return () => {}; }, }; diff --git a/Resources/opencode-plugin.js b/Resources/opencode-plugin.js index 790407757f29..742a6a29290a 100644 --- a/Resources/opencode-plugin.js +++ b/Resources/opencode-plugin.js @@ -1075,7 +1075,7 @@ const createCMUXFeed = async (ctx, options = {}) => { export const CMUXFeed = createCMUXFeed; -const CMUX_FEED_SERVER_INSTALLED_KEY = Symbol.for("cmux.feed.server.installed"); +const CMUX_FEED_SERVER_OWNER_KEY = Symbol.for("cmux.feed.server.owner"); // Released OpenCode calls `server(ctx)` inside each TUI process with the // project server context. Old V2 snapshots called it from a shared service @@ -1087,10 +1087,22 @@ export default { id: "cmux.server", async server(ctx) { if (!isTUIProcessServerContext(ctx)) return {}; - // cmux-feed.js and plugins/cmux/index.js both load this source. - if (globalThis[CMUX_FEED_SERVER_INSTALLED_KEY]) return {}; - globalThis[CMUX_FEED_SERVER_INSTALLED_KEY] = true; - return createCMUXFeed(ctx); + // cmux-feed.js and plugins/cmux/index.js both load this source. Every + // loader in one plugin scope receives the same ctx; a reinitialized scope + // receives a new one, which replaces the previous feed. + const owner = globalThis[CMUX_FEED_SERVER_OWNER_KEY] ||= { ctx: null, feed: null }; + if (owner.ctx === ctx) return {}; + const previous = owner.feed; + owner.ctx = ctx; + owner.feed = null; + previous?.dispose?.(); + const feed = await createCMUXFeed(ctx); + if (owner.ctx !== ctx) { + feed.dispose(); + return {}; + } + owner.feed = feed; + return feed; }, // Compatibility alias for older V2 snapshots that called setup(). setup() { return () => {}; }, diff --git a/tests/test_opencode_server_entry.py b/tests/test_opencode_server_entry.py index 34e471036b4d..e064b33b787e 100644 --- a/tests/test_opencode_server_entry.py +++ b/tests/test_opencode_server_entry.py @@ -29,7 +29,7 @@ def session_plugin_source() -> str: HARNESS = r''' -const { pluginDir, logPath, socketPath } = JSON.parse(process.env.CMUX_OPENCODE_SERVER_HARNESS); +const { pluginDir, logPath, socketPath, fakeCmux } = JSON.parse(process.env.CMUX_OPENCODE_SERVER_HARNESS); const fs = await import("node:fs"); const net = await import("node:net"); const path = await import("node:path"); @@ -74,38 +74,69 @@ def session_plugin_source() -> str: if (typeof v2Cleanup !== "function") throw new Error("V2 setup did not return cleanup"); v2Cleanup(); -const hooks = []; -for (const file of ["cmux-feed.js", "cmux-session.js", path.join("cmux", "index.js")]) { - const mod = await import(path.join(pluginDir, file)); - if (typeof mod.default?.server !== "function") throw new Error(`${file} lacks a server entry`); - hooks.push(await mod.default.server(ctx, {})); -} -const active = hooks.filter((hook) => hook && typeof hook.event === "function"); -if (active.length === 0) throw new Error("no OpenCode server entry subscribed to events"); - -const emit = async (event) => { - for (const hook of active) await hook.event({ event }); -}; -const sid = "ses_server_entry"; -await emit({ type: "session.created", properties: { info: { id: sid, directory: "/tmp" } } }); -await emit({ type: "session.status", properties: { sessionID: sid, status: { type: "busy" } } }); -await emit({ type: "session.status", properties: { sessionID: sid, status: { type: "idle" } } }); -await emit({ type: "session.idle", properties: { sessionID: sid } }); - -const deadline = Date.now() + 5000; -const stopFrames = () => frames.filter((frame) => frame.params?.event?.hook_event_name === "Stop"); +const { execFileSync } = await import("node:child_process"); const hookLog = () => (fs.existsSync(logPath) ? fs.readFileSync(logPath, "utf8") : ""); -while (Date.now() < deadline && (stopFrames().length === 0 || !hookLog().includes("hooks enqueue opencode stop"))) { - await new Promise((resolve) => setTimeout(resolve, 20)); -} -// Give duplicate deliveries a chance to arrive before counting. -await new Promise((resolve) => setTimeout(resolve, 200)); -const stops = stopFrames(); -if (stops.length !== 1) throw new Error(`expected one feed Stop, got ${stops.length}: ${JSON.stringify(frames)}`); -if (stops[0].params.event.surface_id !== "surface-server-entry") throw new Error("feed Stop lost the surface id"); +const fakeCmuxRunning = () => { + try { + execFileSync("pgrep", ["-f", fakeCmux], { stdio: "ignore" }); + return true; + } catch (_) { + return false; + } +}; +const waitFor = async (predicate, message) => { + const deadline = Date.now() + 5000; + while (!predicate()) { + if (Date.now() > deadline) throw new Error(message); + await new Promise((resolve) => setTimeout(resolve, 20)); + } +}; + +// Load the three cmux entries for one plugin scope and drive one turn. The +// session.deleted sentinel follows the duplicate-prone idle events: socket +// frames are ordered, and every hook process is spawned before the sentinel's. +const runScope = async (scopeCtx, sid) => { + const hooks = []; + for (const file of ["cmux-feed.js", "cmux-session.js", path.join("cmux", "index.js")]) { + const mod = await import(path.join(pluginDir, file)); + if (typeof mod.default?.server !== "function") throw new Error(`${file} lacks a server entry`); + hooks.push(await mod.default.server(scopeCtx, {})); + } + const active = hooks.filter((hook) => hook && typeof hook.event === "function"); + if (active.length === 0) throw new Error("no OpenCode server entry subscribed to events"); + const emit = async (event) => { + for (const hook of active) await hook.event({ event }); + }; + await emit({ type: "session.created", properties: { info: { id: sid, directory: "/tmp" } } }); + await emit({ type: "session.status", properties: { sessionID: sid, status: { type: "busy" } } }); + await emit({ type: "session.status", properties: { sessionID: sid, status: { type: "idle" } } }); + await emit({ type: "session.idle", properties: { sessionID: sid } }); + await emit({ type: "session.deleted", properties: { info: { id: sid } } }); + + const forSession = (frame) => frame.params?.event?.session_id === `opencode-${sid}`; + await waitFor( + () => frames.some((frame) => forSession(frame) && frame.params.event.hook_event_name === "SessionEnd"), + `feed sentinel never arrived for ${sid}: ${JSON.stringify(frames)}`, + ); + const sessionEnds = () => hookLog().split("\n").filter((line) => line.includes("opencode session-end")).length; + await waitFor(() => sessionEnds() >= runs + 1, `session-end hook never ran for ${sid}`); + await waitFor(() => !fakeCmuxRunning(), "hook processes did not exit"); + const stops = frames.filter((frame) => forSession(frame) && frame.params.event.hook_event_name === "Stop"); + if (stops.length !== 1) throw new Error(`expected one feed Stop for ${sid}, got ${stops.length}: ${JSON.stringify(frames)}`); + if (stops[0].params.event.surface_id !== "surface-server-entry") throw new Error("feed Stop lost the surface id"); + return active; +}; + +let runs = 0; +const first = await runScope(ctx, "ses_server_entry"); +runs++; +// OpenCode can reinitialize a plugin scope in the same process; the new scope +// gets a new ctx and must subscribe again. +await runScope({ ...ctx }, "ses_server_entry_reinit"); +runs++; const hookStops = hookLog().split("\n").filter((line) => line.includes("hooks enqueue opencode stop")); -if (hookStops.length !== 1) throw new Error(`expected one stop hook, got ${hookStops.length}: ${hookLog()}`); -for (const hook of active) hook.dispose?.(); +if (hookStops.length !== 2) throw new Error(`expected one stop hook per turn, got ${hookStops.length}: ${hookLog()}`); +for (const hook of first) hook.dispose?.(); server.close(); console.log("PASS: OpenCode server entry delivers one completion"); process.exit(0); @@ -134,7 +165,7 @@ def main() -> int: fake_cmux = root / "cmux" fake_cmux.write_text(f'#!/bin/sh\necho "$*" >> "{log_path}"\ncat >/dev/null\n', encoding="utf-8") fake_cmux.chmod(0o755) - socket_path = f"/tmp/cmux-oc-server-{os.getpid()}.sock" + socket_path = str(root / "cmux.sock") env = os.environ.copy() env.update( CMUX_SURFACE_ID="surface-server-entry", @@ -143,7 +174,7 @@ def main() -> int: CMUX_OPENCODE_CMUX_BIN=str(fake_cmux), CMUX_OPENCODE_HOOKS_DISABLED="", CMUX_OPENCODE_SERVER_HARNESS=json.dumps( - {"pluginDir": str(plugin_dir), "logPath": str(log_path), "socketPath": socket_path} + {"pluginDir": str(plugin_dir), "logPath": str(log_path), "socketPath": socket_path, "fakeCmux": str(fake_cmux)} ), ) harness = root / "harness.mjs" From f63c4606073d6b74ecbca277a80d182a6495e4d3 Mon Sep 17 00:00:00 2001 From: Austin Wang <38676809+austinywang@users.noreply.github.com> Date: Wed, 14 Oct 2026 01:07:47 -0700 Subject: [PATCH 14/20] fix(opencode): open turns on run signals, not message updates A queued prompt's admission and user message arrive while the previous turn is still running, so keying turns on first-seen message IDs dropped the stop for the queued turn. Open a turn only on a run signal (session creation, busy status, a promoted prompt or an execution start) in all three bridges; a repeated message update after a stop still cannot reopen the turn. The TUI bridge tracks turn starts before its ownership check so a turn that starts in a hidden tab keeps its stop. Also: - Do not publish a stop for an execution interrupted by shutdown, which OpenCode resumes, matching cmux-tui. - Redact credentials in the Feed plugin's own failure text, which reaches Feed without passing through the CLI. - Drop inherited subrouter and routed-account launch keys when recapturing OpenCode's own launch. Co-Authored-By: Claude Opus 5.5 --- CLI/cmux.swift | 40 +++++++++++--------- Resources/opencode-plugin.js | 62 ++++++++++++++++++++----------- Resources/opencode-tui-plugin.js | 64 ++++++++++++-------------------- 3 files changed, 85 insertions(+), 81 deletions(-) diff --git a/CLI/cmux.swift b/CLI/cmux.swift index 98dda98aaf2d..03efc84ef4e9 100644 --- a/CLI/cmux.swift +++ b/CLI/cmux.swift @@ -36460,7 +36460,6 @@ function sessionState(sessionId) { assistantPreamble: null, cwd: null, lastStopKind: null, - turnKeys: new Set(), updatedAt: Date.now(), }); } @@ -36524,17 +36523,18 @@ function sessionStatusType(status) { return firstString(status.type, status.status, status.state)?.toLowerCase() || null; } -// A turn publishes exactly one terminal stop. Only a turn identity this -// session has not seen clears it, so a repeated update for the same prompt -// cannot reopen a finished turn. A missing identity starts a new turn. -function beginTurn(sessionId, turnKey) { - const state = sessionState(sessionId); - if (turnKey) { - if (state.turnKeys.has(turnKey)) return; - state.turnKeys.add(turnKey); - if (state.turnKeys.size > 50) state.turnKeys.delete(state.turnKeys.values().next().value); - } - state.lastStopKind = null; +// A turn publishes exactly one terminal stop. Only a run signal (session +// creation, busy status, a promoted prompt or an execution start) opens the +// next turn. Message updates and queued prompts do not: a queued prompt's +// message arrives while the previous turn is still running, and a repeated +// update after a stop must not reopen a finished turn. +function beginTurn(sessionId) { + sessionState(sessionId).lastStopKind = null; +} + +// OpenCode keeps an execution interrupted by shutdown and resumes it. +function isResumableInterruption(event) { + return event?.type === "session.execution.interrupted" && eventProperties(event).reason === "shutdown"; } // The first terminal event settles the turn. A published stop cannot be @@ -36645,6 +36645,9 @@ function hookEnvironment(cwd) { // A shell started inside another agent inherits that agent's launch // capture. Only reuse a capture that already describes OpenCode. if (env.CMUX_AGENT_LAUNCH_KIND !== "opencode" || !env.CMUX_AGENT_LAUNCH_ARGV_B64) { + delete env.CMUX_AGENT_LAUNCH_SUBROUTER_CLAUDE_RESUME_COMMAND; + delete env.CMUX_AGENT_LAUNCH_SUBROUTER_CODEX_RESUME_COMMAND; + delete env.CMUX_AGENT_LAUNCH_ROUTED_CLAUDE_ACCOUNT; const argv = normalizedLaunchArgv(); env.CMUX_AGENT_LAUNCH_KIND = "opencode"; env.CMUX_AGENT_LAUNCH_EXECUTABLE = argv[0] || resolveExecutable("opencode"); @@ -36699,7 +36702,6 @@ function trackMessage(event) { const role = info.role || props.role; if (messageId && sessionId && role) { messageRoles.set(messageId, { sessionId, role }); - if (role === "user") beginTurn(sessionId, messageId); if (messageRoles.size > 300) { messageRoles.delete(messageRoles.keys().next().value); } @@ -36724,10 +36726,12 @@ function trackMessage(event) { // Busy status carries no turn identity; prompts and user messages own it. function resetTurnFromEvent(event) { - if (!["session.next.prompted", "session.next.prompt.admitted", "session.inbox.enqueued"].includes(event?.type)) return; - const sessionId = sessionIdFor(event); const props = eventProperties(event); - if (sessionId) beginTurn(sessionId, firstString(props.item?.id, props.messageID, props.promptID, props.id, event.id)); + const running = ["session.next.prompted", "session.execution.started"].includes(event?.type) + || (event?.type === "session.status" && sessionStatusType(props.status) === "busy"); + if (!running) return; + const sessionId = sessionIdFor(event); + if (sessionId) beginTurn(sessionId); } function sendStop(ctx, event, failed = false) { @@ -36747,7 +36751,7 @@ const createCMUXSessionRestore = async (ctx) => { const props = eventProperties(event); switch (event && event.type) { case "session.created": - beginTurn(sessionIdFor(event), null); + beginTurn(sessionIdFor(event)); sendHook("session-start", ctx, event); break; case "session.updated": @@ -36766,7 +36770,7 @@ const createCMUXSessionRestore = async (ctx) => { break; case "session.execution.succeeded": case "session.execution.interrupted": - sendStop(ctx, event); + if (!isResumableInterruption(event)) sendStop(ctx, event); break; case "session.execution.failed": case "session.next.step.failed": diff --git a/Resources/opencode-plugin.js b/Resources/opencode-plugin.js index 742a6a29290a..41d291d4e60b 100644 --- a/Resources/opencode-plugin.js +++ b/Resources/opencode-plugin.js @@ -90,7 +90,25 @@ const createCMUXFeed = async (ctx, options = {}) => { return firstString(status.type, status.status, status.state)?.toLowerCase() || null; }; - const failureMessage = (event) => { + // Mirrors AgentHookNotificationPolicy.redactSensitiveErrorDetail: Feed + // receives this text directly, so credentials are redacted here. Paths and + // model names stay readable because they are the useful part of the error. + const redactErrorDetail = (value) => { + if (!value) return value; + const redacted = [ + [/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/gi, ""], + [/\b(?:gh[pousr]_[A-Za-z0-9_]{20,}|AKIA[0-9A-Z]{16})\b/gi, ""], + [/\bBearer\s+[A-Za-z0-9._~+/=-]{12,}/gi, "Bearer "], + [/\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\b/gi, ""], + [/\b(?:x[-_])?(?:api[-_]?key|password|secret|token|authorization|cookie)\s*[:=]\s*(?:Bearer\s+)?(?:'[^']*'|"[^"]*"|[^\s'";&|,]+)/gi, ":"], + [/\b(?:sk|rk|sess)-[A-Za-z0-9._:-]{8,}\b/gi, ""], + ].reduce((text, [pattern, replacement]) => text.replace(pattern, replacement), value); + return redacted.replace(/<[a-z]+>|[\s\p{P}]/gu, "") ? redacted : null; + }; + + const failureMessage = (event) => redactErrorDetail(rawFailureMessage(event)); + + const rawFailureMessage = (event) => { const props = eventProperties(event); const raw = props.error || props.failure || props.reason; if (typeof raw === "string") return normalizeText(raw, 500); @@ -127,25 +145,24 @@ const createCMUXFeed = async (ctx, options = {}) => { assistantPreamble: null, cwd: null, lastStopKind: null, - turnKeys: new Set(), }); } return sessions.get(key); }; - // A turn publishes exactly one terminal stop. Only a turn identity this - // session has not seen clears it, so a repeated update for the same prompt - // cannot reopen a finished turn. A missing identity starts a new turn. - const beginTurn = (sessionId, turnKey) => { - const state = sessionState(sessionId); - if (turnKey) { - if (state.turnKeys.has(turnKey)) return; - state.turnKeys.add(turnKey); - if (state.turnKeys.size > 50) state.turnKeys.delete(state.turnKeys.values().next().value); - } - state.lastStopKind = null; + // A turn publishes exactly one terminal stop. Only a run signal (session + // creation, busy status, a promoted prompt or an execution start) opens the + // next turn. Message updates and queued prompts do not: a queued prompt's + // message arrives while the previous turn is still running, and a repeated + // update after a stop must not reopen a finished turn. + const beginTurn = (sessionId) => { + sessionState(sessionId).lastStopKind = null; }; + // OpenCode keeps an execution interrupted by shutdown and resumes it. + const isResumableInterruption = (event) => + event?.type === "session.execution.interrupted" && eventProperties(event).reason === "shutdown"; + const contextForSession = (sessionId) => { const state = sessionState(sessionId); const context = {}; @@ -706,7 +723,6 @@ const createCMUXFeed = async (ctx, options = {}) => { if (!sid || !text) return null; const state = sessionState(sid); state.lastUserMessage = text; - beginTurn(sid, firstString(item.id, props.id, event.id)); return base(sid, { hook_event_name: "UserPromptSubmit", tool_input: { prompt: text }, @@ -726,7 +742,6 @@ const createCMUXFeed = async (ctx, options = {}) => { const role = info.role || props.role; if (messageId && sessionId && role) { messageRoles.set(messageId, { sessionId, role }); - if (role === "user") beginTurn(sessionId, messageId); if (messageRoles.size > 300) { messageRoles.delete(messageRoles.keys().next().value); } @@ -744,7 +759,6 @@ const createCMUXFeed = async (ctx, options = {}) => { const state = sessionState(meta.sessionId); if (meta.role === "user") { state.lastUserMessage = text; - beginTurn(meta.sessionId, part.messageID); return base(meta.sessionId, { hook_event_name: "UserPromptSubmit", tool_input: { prompt: text }, @@ -822,7 +836,7 @@ const createCMUXFeed = async (ctx, options = {}) => { const props = eventProperties(event); const info = props.info || {}; const sid = sessionIdFromProperties(props) || "unknown"; - beginTurn(sid, null); + beginTurn(sid); const state = sessionState(sid); state.cwd = info.directory || props.location?.directory || event.location?.directory || ctx?.location?.directory || ctx?.directory || state.cwd; pushTelemetry(base(sid, { @@ -834,8 +848,10 @@ const createCMUXFeed = async (ctx, options = {}) => { case "session.status": { const props = eventProperties(event); const sid = sessionIdFromProperties(props); - // Busy carries no turn identity; prompts and user messages own it. - if (sid && sessionStatusType(props.status) === "busy") break; + if (sid && sessionStatusType(props.status) === "busy") { + beginTurn(sid); + break; + } if (!sessionStatusIsIdle(props.status)) break; if (!sid || !shouldEmitStop(sid, "success")) break; pushTelemetry(base(sid, { @@ -846,6 +862,7 @@ const createCMUXFeed = async (ctx, options = {}) => { case "session.execution.succeeded": case "session.execution.interrupted": { const sid = sessionIdFromEvent(event); + if (isResumableInterruption(event)) break; if (sid && shouldEmitStop(sid, "success")) pushTelemetry(base(sid, { hook_event_name: "Stop" })); break; } @@ -880,11 +897,12 @@ const createCMUXFeed = async (ctx, options = {}) => { })); break; } + // Admission queues a prompt behind the running turn; promotion and + // execution start are when it actually runs. case "session.next.prompted": - case "session.next.prompt.admitted": { + case "session.execution.started": { const sid = sessionIdFromEvent(event); - const props = eventProperties(event); - if (sid) beginTurn(sid, firstString(props.messageID, props.promptID, props.id, event.id)); + if (sid) beginTurn(sid); break; } case "session.deleted": { diff --git a/Resources/opencode-tui-plugin.js b/Resources/opencode-tui-plugin.js index 8336ff9310c8..4faa228cc798 100644 --- a/Resources/opencode-tui-plugin.js +++ b/Resources/opencode-tui-plugin.js @@ -177,6 +177,9 @@ function launchEnvironment(cwdValue, baseEnvironment = process.env) { // A shell started inside another agent inherits that agent's launch // capture. Only reuse a capture that already describes OpenCode. if (env.CMUX_AGENT_LAUNCH_KIND !== "opencode" || !env.CMUX_AGENT_LAUNCH_ARGV_B64) { + delete env.CMUX_AGENT_LAUNCH_SUBROUTER_CLAUDE_RESUME_COMMAND; + delete env.CMUX_AGENT_LAUNCH_SUBROUTER_CODEX_RESUME_COMMAND; + delete env.CMUX_AGENT_LAUNCH_ROUTED_CLAUDE_ACCOUNT; const argv = launchArgv(); env.CMUX_AGENT_LAUNCH_KIND = "opencode"; env.CMUX_AGENT_LAUNCH_EXECUTABLE = argv[0] || resolveExecutable("opencode"); @@ -211,6 +214,8 @@ function sessionEventName(event) { if (event?.type === "session.created") return "session-start"; if (event?.type === "session.deleted") return "session-end"; if (event?.type === "session.updated") return data.info?.time?.archived ? "session-end" : null; + // OpenCode keeps an execution interrupted by shutdown and resumes it. + if (event?.type === "session.execution.interrupted" && data.reason === "shutdown") return null; if (["session.execution.succeeded", "session.execution.interrupted"].includes(event?.type)) return "stop"; if (["session.execution.failed", "session.next.step.failed", "session.error"].includes(event?.type)) return "stop-failure"; if (event?.type === "session.idle") return "stop"; @@ -218,51 +223,28 @@ function sessionEventName(event) { return null; } -// Identity of a new turn, or null when the event does not start one. Busy -// status carries no identity; prompts and user messages own the turn. -function turnStart(event) { - const data = properties(event); - if (["session.next.prompted", "session.next.prompt.admitted", "session.inbox.enqueued"].includes(event?.type)) { - return { key: firstString(data.item?.id, data.messageID, data.promptID, data.id, event?.id) }; - } - if (event?.type === "message.updated") { - const info = data.info || data.message || {}; - if ((info.role || data.role) === "user") return { key: firstString(info.id, data.messageID) }; - } - return null; +// True when the event shows the session running a turn. Message updates and +// queued prompts are not run signals: a queued prompt's message arrives while +// the previous turn is still running, and a repeated update after a stop must +// not reopen a finished turn. +function isTurnStart(event) { + if (["session.created", "session.next.prompted", "session.execution.started"].includes(event?.type)) return true; + return event?.type === "session.status" && statusType(properties(event).status) === "busy"; } -// A turn publishes exactly one terminal stop. Only a turn identity the session -// has not seen clears it, so a repeated update for the same prompt cannot -// reopen a finished turn. The first terminal event settles the turn: a -// published stop cannot be reclassified, so later idle or failure is dropped. +// A turn publishes exactly one terminal stop, and only a run signal opens the +// next one. The first terminal event settles the turn: a published stop cannot +// be reclassified, so a later idle or failure for the same turn is dropped. function createTurnLedger() { - const sessions = new Map(); - const state = (id) => { - let entry = sessions.get(id); - if (!entry) { - entry = { stopped: false, keys: new Set() }; - sessions.set(id, entry); - } - return entry; - }; + const stopped = new Set(); return { - begin(id, key) { - const entry = state(id); - if (key) { - if (entry.keys.has(key)) return; - entry.keys.add(key); - if (entry.keys.size > 50) entry.keys.delete(entry.keys.values().next().value); - } - entry.stopped = false; - }, + begin(id) { stopped.delete(id); }, settle(id) { - const entry = state(id); - if (entry.stopped) return false; - entry.stopped = true; + if (stopped.has(id)) return false; + stopped.add(id); return true; }, - end(id) { sessions.delete(id); }, + end(id) { stopped.delete(id); }, }; } @@ -279,11 +261,8 @@ function reportError(ctx, _error) { } async function deliverEvent(ctx, feed, event, id, environment, turns) { - const started = turnStart(event); - if (started) turns.begin(id, started.key); const hook = sessionEventName(event); let admittedHook = hook; - if (hook === "session-start") turns.begin(id, null); if (hook === "session-end") turns.end(id); if ((hook === "stop" || hook === "stop-failure") && !turns.settle(id)) admittedHook = null; if (admittedHook) { @@ -309,6 +288,9 @@ async function handleEvent(ctx, ownership, feed, details, environment, retrySess const id = sessionID(event); const hook = sessionEventName(event); if (!id) return; + // Track turn boundaries even while the session is hidden, so a turn that + // starts in a background tab still publishes its stop once visible again. + if (isTurnStart(event)) turns?.begin(id); if (hook === "session-end") retrySessionStart?.cancel(id); if (!ownership.belongs(id)) { if (hook === "session-start") retrySessionStart?.enqueue(event, id); From 47911cb19e97a2661572c9f20a8601cb7fd8e529 Mon Sep 17 00:00:00 2001 From: Austin Wang <38676809+austinywang@users.noreply.github.com> Date: Wed, 14 Oct 2026 01:08:53 -0700 Subject: [PATCH 15/20] test(opencode): cover queued prompts and shutdown interruptions Drive a prompt that is admitted during a running turn and promoted after its stop, a repeated user-message update after a stop, a late failure, and a shutdown interruption through the session plugin and the Feed bridge. Wait for a session-end sentinel before counting so a late extra stop is caught. Co-Authored-By: Claude Opus 5.5 --- tests/test_opencode_plugin_install.py | 44 ++++++++++++++++++--------- tests/test_opencode_v2_tui_bridge.py | 22 ++++++++++++++ 2 files changed, 52 insertions(+), 14 deletions(-) diff --git a/tests/test_opencode_plugin_install.py b/tests/test_opencode_plugin_install.py index 8d477faafc93..6da9907e305a 100644 --- a/tests/test_opencode_plugin_install.py +++ b/tests/test_opencode_plugin_install.py @@ -280,29 +280,42 @@ def main() -> int: properties: { sessionID: "opencode-session-test" } } }); -// One terminal stop per turn. A new user message starts turn 2; a repeated -// update for that same message after its stop must not reopen the turn, and a -// failure after the published idle stop is dropped rather than reclassified. +// One terminal stop per turn, opened only by a run signal. Turn 2 starts on +// busy; a repeated user-message update after its stop must not reopen it, and +// a failure after the published idle stop is dropped, not reclassified. +// Turn 3 queues prompt 4 while running: the queued prompt's user message and +// admission arrive mid-turn, yet turn 4 still publishes its own stop. +const sid = "opencode-session-test"; const userMessage = (id) => ({ - event: { - type: "message.updated", - properties: { info: { id, sessionID: "opencode-session-test", role: "user" } } - } + event: { type: "message.updated", properties: { info: { id, sessionID: sid, role: "user" } } } }); -const idle = { event: { type: "session.idle", properties: { sessionID: "opencode-session-test" } } }; +const busy = { event: { type: "session.status", properties: { sessionID: sid, status: { type: "busy" } } } }; +const idle = { event: { type: "session.idle", properties: { sessionID: sid } } }; const failure = { event: { type: "session.error", - properties: { sessionID: "opencode-session-test", error: { name: "UnknownError", data: { message: "late failure" } } } + properties: { sessionID: sid, error: { name: "UnknownError", data: { message: "late failure" } } } } }; await v1Hooks.event(userMessage("msg-turn-2")); -await v1Hooks.event({ event: { type: "session.status", properties: { sessionID: "opencode-session-test", status: { type: "busy" } } } }); +await v1Hooks.event(busy); await v1Hooks.event(idle); await v1Hooks.event(userMessage("msg-turn-2")); -await v1Hooks.event({ event: { type: "session.status", properties: { sessionID: "opencode-session-test", status: { type: "busy" } } } }); await v1Hooks.event(idle); await v1Hooks.event(failure); +await v1Hooks.event(userMessage("msg-turn-3")); +await v1Hooks.event(busy); +await v1Hooks.event(userMessage("msg-turn-4")); +await v1Hooks.event({ event: { type: "session.next.prompt.admitted", properties: { sessionID: sid, messageID: "msg-turn-4" } } }); +await v1Hooks.event(idle); +await v1Hooks.event({ event: { type: "session.next.prompted", properties: { sessionID: sid, messageID: "msg-turn-4" } } }); +await v1Hooks.event({ event: { type: "session.execution.succeeded", properties: { sessionID: sid } } }); +// Shutdown keeps the execution for resumption; it is not a completed turn. +await v1Hooks.event(busy); +await v1Hooks.event({ event: { type: "session.execution.interrupted", properties: { sessionID: sid, reason: "shutdown" } } }); +// Sentinel: hook processes are spawned in event order, so once session-end +// has run every earlier stop hook has been spawned too. +await v1Hooks.event({ event: { type: "session.deleted", properties: { info: { id: sid } } } }); """ check = subprocess.run( [bun, "--eval", check_source], @@ -320,10 +333,13 @@ def main() -> int: print(f"stderr={check.stderr.strip()}") return 1 + # Wait for the session-end sentinel and for every hook process to finish + # writing, so a late extra stop cannot land after the counts below. deadline = time.monotonic() + 5.0 while time.monotonic() < deadline: + args_text = fake_args_log.read_text(encoding="utf-8") if fake_args_log.exists() else "" stdin_text = fake_stdin_log.read_text(encoding="utf-8") if fake_stdin_log.exists() else "" - if stdin_text.count('"hook_event_name":"Stop') >= 2: + if "opencode session-end" in args_text and stdin_text.count("\n---\n") >= args_text.count("\n"): break time.sleep(0.01) args_log = wait_for_log(fake_args_log, "hooks enqueue opencode session-start") @@ -335,10 +351,10 @@ def main() -> int: if args_log.count("hooks enqueue opencode session-start") != 1: print(f"FAIL: plugin invoked duplicate session-start hooks, got {args_log!r}") return 1 - if args_log.count("hooks enqueue opencode stop") != 2: + if args_log.count("hooks enqueue opencode stop") != 4: print(f"FAIL: plugin did not publish exactly one stop per turn, got {args_log!r}") return 1 - if stdin_log.count('"hook_event_name":"Stop"') != 1 or stdin_log.count('"hook_event_name":"StopFailure"') != 1: + if stdin_log.count('"hook_event_name":"Stop"') != 3 or stdin_log.count('"hook_event_name":"StopFailure"') != 1: print(f"FAIL: plugin did not settle one terminal outcome per turn, got {stdin_log!r}") return 1 if "late failure" in stdin_log: diff --git a/tests/test_opencode_v2_tui_bridge.py b/tests/test_opencode_v2_tui_bridge.py index ed7fc93c2677..1beeeca493b0 100755 --- a/tests/test_opencode_v2_tui_bridge.py +++ b/tests/test_opencode_v2_tui_bridge.py @@ -278,6 +278,28 @@ def main() -> int: if (observed.find((event) => event.hook_event_name === "SessionEnd" && event.session_id === "opencode-child-b")?.surface_id !== "surface-b") throw new Error("archived session was not ended on its owning TUI"); if (observed.some((event) => event._opencode_request_id === "perm-wrong")) throw new Error("TUI B accepted a session owned by TUI A"); +// A prompt queued during a running turn is admitted mid-turn and promoted +// after the stop. Both turns publish exactly one Stop; the repeated idle +// forms, a late failure and a shutdown interruption publish none. +liveA.setRoute({ type: "session", sessionID: "child-queue" }); +const queueEvents = [ + ["session.status", { sessionID: "child-queue", status: { type: "busy" } }], + ["session.next.prompt.admitted", { sessionID: "child-queue", messageID: "queued-m2" }], + ["session.status", { sessionID: "child-queue", status: "idle" }], + ["session.idle", { sessionID: "child-queue" }], + ["session.error", { sessionID: "child-queue", error: { message: "late failure" } }], + ["session.next.prompted", { sessionID: "child-queue", messageID: "queued-m2" }], + ["session.execution.succeeded", { sessionID: "child-queue" }], + ["session.status", { sessionID: "child-queue", status: { type: "busy" } }], + ["session.execution.interrupted", { sessionID: "child-queue", reason: "shutdown" }], + ["session.deleted", { sessionID: "child-queue" }], +]; +for (const [type, data] of queueEvents) liveA.emit({ details: { type, data } }); +await waitForObserved((event) => event.hook_event_name === "SessionEnd" && event.session_id === "opencode-child-queue"); +const queueStops = observed.filter((event) => event.session_id === "opencode-child-queue" && event.hook_event_name === "Stop"); +if (queueStops.length !== 2 || queueStops.some((event) => event.is_error)) throw new Error(`queued prompt turns published ${JSON.stringify(queueStops)}`); +liveA.setRoute(routeA); + // A bridge that never owns a queued session must release its expiry timer on // disposal, rather than retaining the entire TUI context until the TTL elapses. const expiryTimers = new Set(); From 34dd634f8bea9143c5ba931ca8c938337b584443 Mon Sep 17 00:00:00 2001 From: Austin Wang <38676809+austinywang@users.noreply.github.com> Date: Wed, 14 Oct 2026 01:10:30 -0700 Subject: [PATCH 16/20] fix: bind OpenCode hooks to this process and plugin scope An OpenCode started from another OpenCode inherited the parent's opencode launch capture and recorded the parent's resume command. Always capture this process's launch; no cmux wrapper exports one. OpenCode never disposes a replaced plugin scope's hooks, so the session bridge now ignores events once a new scope owns the process. Co-Authored-By: Claude Opus 5.5 --- CLI/cmux.swift | 32 ++++++++++++++++------------ Resources/opencode-tui-plugin.js | 22 +++++++++---------- tests/test_opencode_server_entry.py | 14 ++++++++++++ tests/test_opencode_v2_tui_bridge.py | 5 ++++- 4 files changed, 46 insertions(+), 27 deletions(-) diff --git a/CLI/cmux.swift b/CLI/cmux.swift index 03efc84ef4e9..b13aa6fdc83a 100644 --- a/CLI/cmux.swift +++ b/CLI/cmux.swift @@ -36642,18 +36642,16 @@ function base64NulSeparated(values) { function hookEnvironment(cwd) { const env = { ...process.env }; delete env.AMP_API_KEY; - // A shell started inside another agent inherits that agent's launch - // capture. Only reuse a capture that already describes OpenCode. - if (env.CMUX_AGENT_LAUNCH_KIND !== "opencode" || !env.CMUX_AGENT_LAUNCH_ARGV_B64) { - delete env.CMUX_AGENT_LAUNCH_SUBROUTER_CLAUDE_RESUME_COMMAND; - delete env.CMUX_AGENT_LAUNCH_SUBROUTER_CODEX_RESUME_COMMAND; - delete env.CMUX_AGENT_LAUNCH_ROUTED_CLAUDE_ACCOUNT; - const argv = normalizedLaunchArgv(); - env.CMUX_AGENT_LAUNCH_KIND = "opencode"; - env.CMUX_AGENT_LAUNCH_EXECUTABLE = argv[0] || resolveExecutable("opencode"); - env.CMUX_AGENT_LAUNCH_ARGV_B64 = base64NulSeparated(argv); - env.CMUX_AGENT_LAUNCH_CWD = cwd || process.cwd(); - } + // Any inherited capture describes a parent process: another agent, or an + // OpenCode that started this one. Always describe this process's launch. + delete env.CMUX_AGENT_LAUNCH_SUBROUTER_CLAUDE_RESUME_COMMAND; + delete env.CMUX_AGENT_LAUNCH_SUBROUTER_CODEX_RESUME_COMMAND; + delete env.CMUX_AGENT_LAUNCH_ROUTED_CLAUDE_ACCOUNT; + const argv = normalizedLaunchArgv(); + env.CMUX_AGENT_LAUNCH_KIND = "opencode"; + env.CMUX_AGENT_LAUNCH_EXECUTABLE = argv[0] || resolveExecutable("opencode"); + env.CMUX_AGENT_LAUNCH_ARGV_B64 = base64NulSeparated(argv); + env.CMUX_AGENT_LAUNCH_CWD = cwd || process.cwd(); return env; } @@ -36809,7 +36807,7 @@ const CMUX_SESSION_SERVER_OWNER_KEY = Symbol.for("cmux.session.server.owner"); export default { id: "cmux.server", - server(ctx) { + async server(ctx) { if (!isTUIProcessServerContext(ctx)) return {}; // Every loader in one plugin scope receives the same ctx; a reinitialized // scope receives a new one and must subscribe again. @@ -36817,7 +36815,13 @@ export default { if (owner.ctx === ctx) return {}; owner.ctx = ctx; globalThis[CMUX_PLUGIN_INSTALLED_KEY] = true; - return createCMUXSessionRestore(ctx); + const hooks = await createCMUXSessionRestore(ctx); + // OpenCode never disposes a scope's hooks, so a replaced scope goes quiet. + return { + event: async (input) => { + if (owner.ctx === ctx) await hooks.event(input); + }, + }; }, // Compatibility alias for older V2 snapshots that called setup(). setup() { return () => {}; }, diff --git a/Resources/opencode-tui-plugin.js b/Resources/opencode-tui-plugin.js index 4faa228cc798..3cf2222ae310 100644 --- a/Resources/opencode-tui-plugin.js +++ b/Resources/opencode-tui-plugin.js @@ -174,18 +174,16 @@ function launchArgv() { function launchEnvironment(cwdValue, baseEnvironment = process.env) { const env = { ...baseEnvironment, CMUXTERM_CLI_RESPONSE_TIMEOUT_SEC: "1" }; delete env.AMP_API_KEY; - // A shell started inside another agent inherits that agent's launch - // capture. Only reuse a capture that already describes OpenCode. - if (env.CMUX_AGENT_LAUNCH_KIND !== "opencode" || !env.CMUX_AGENT_LAUNCH_ARGV_B64) { - delete env.CMUX_AGENT_LAUNCH_SUBROUTER_CLAUDE_RESUME_COMMAND; - delete env.CMUX_AGENT_LAUNCH_SUBROUTER_CODEX_RESUME_COMMAND; - delete env.CMUX_AGENT_LAUNCH_ROUTED_CLAUDE_ACCOUNT; - const argv = launchArgv(); - env.CMUX_AGENT_LAUNCH_KIND = "opencode"; - env.CMUX_AGENT_LAUNCH_EXECUTABLE = argv[0] || resolveExecutable("opencode"); - env.CMUX_AGENT_LAUNCH_ARGV_B64 = Buffer.from(`${argv.join("\0")}\0`, "utf8").toString("base64"); - env.CMUX_AGENT_LAUNCH_CWD = cwdValue || process.cwd(); - } + // Any inherited capture describes a parent process: another agent, or an + // OpenCode that started this one. Always describe this process's launch. + delete env.CMUX_AGENT_LAUNCH_SUBROUTER_CLAUDE_RESUME_COMMAND; + delete env.CMUX_AGENT_LAUNCH_SUBROUTER_CODEX_RESUME_COMMAND; + delete env.CMUX_AGENT_LAUNCH_ROUTED_CLAUDE_ACCOUNT; + const argv = launchArgv(); + env.CMUX_AGENT_LAUNCH_KIND = "opencode"; + env.CMUX_AGENT_LAUNCH_EXECUTABLE = argv[0] || resolveExecutable("opencode"); + env.CMUX_AGENT_LAUNCH_ARGV_B64 = Buffer.from(`${argv.join("\0")}\0`, "utf8").toString("base64"); + env.CMUX_AGENT_LAUNCH_CWD = cwdValue || process.cwd(); return env; } diff --git a/tests/test_opencode_server_entry.py b/tests/test_opencode_server_entry.py index e064b33b787e..652bd22b6e03 100644 --- a/tests/test_opencode_server_entry.py +++ b/tests/test_opencode_server_entry.py @@ -134,6 +134,20 @@ def session_plugin_source() -> str: // gets a new ctx and must subscribe again. await runScope({ ...ctx }, "ses_server_entry_reinit"); runs++; +// The replaced scope's hooks stay registered in OpenCode; they must not emit. +const stale = "ses_server_entry_stale"; +for (const event of [ + { type: "session.created", properties: { info: { id: stale, directory: "/tmp" } } }, + { type: "session.status", properties: { sessionID: stale, status: { type: "busy" } } }, + { type: "session.idle", properties: { sessionID: stale } }, +]) { + for (const hook of first) await hook.event({ event }); +} +// Hook processes are spawned synchronously inside event(); wait for them. +await waitFor(() => !fakeCmuxRunning(), "hook processes did not exit"); +if (frames.some((frame) => frame.params?.event?.session_id === `opencode-${stale}`)) { + throw new Error("replaced feed scope still emitted events"); +} const hookStops = hookLog().split("\n").filter((line) => line.includes("hooks enqueue opencode stop")); if (hookStops.length !== 2) throw new Error(`expected one stop hook per turn, got ${hookStops.length}: ${hookLog()}`); for (const hook of first) hook.dispose?.(); diff --git a/tests/test_opencode_v2_tui_bridge.py b/tests/test_opencode_v2_tui_bridge.py index 1beeeca493b0..e3371d9d113b 100755 --- a/tests/test_opencode_v2_tui_bridge.py +++ b/tests/test_opencode_v2_tui_bridge.py @@ -48,7 +48,9 @@ def main() -> int: if (mod.sessionBelongsToTUI(makeContext("a"), "child-b")) throw new Error("TUI A claimed TUI B session"); const closed = { ui: { router: { current: () => fixture.starterClosed.route }, tabs: { enabled: () => true, list: () => [] } }, data: { session: { root: (id) => fixture.roots[id] || id } } }; if (mod.sessionBelongsToTUI(closed, "child-a")) throw new Error("closed starter surface retained ownership"); -const dispatchEnvironment = { CMUX_SURFACE_ID: "surface-a", CMUX_WORKSPACE_ID: "workspace-a", CMUX_OPENCODE_HOOKS_DISABLED: "" }; +// A parent OpenCode's capture is inherited by an OpenCode it starts. +const parentLaunchArgv = Buffer.from("/parent/opencode\0-s\0parent-session\0", "utf8").toString("base64"); +const dispatchEnvironment = { CMUX_SURFACE_ID: "surface-a", CMUX_WORKSPACE_ID: "workspace-a", CMUX_OPENCODE_HOOKS_DISABLED: "", CMUX_AGENT_LAUNCH_KIND: "opencode", CMUX_AGENT_LAUNCH_EXECUTABLE: "/parent/opencode", CMUX_AGENT_LAUNCH_ARGV_B64: parentLaunchArgv }; let spawnCalls = 0; let spawnOptions; const fakeSpawn = (_command, _args, options) => { @@ -62,6 +64,7 @@ def main() -> int: if (spawnOptions?.env?.CMUX_AGENT_LAUNCH_KIND !== "opencode") throw new Error("session admission dropped launch kind"); if (!spawnOptions?.env?.CMUX_AGENT_LAUNCH_EXECUTABLE) throw new Error("session admission dropped launch executable"); if (!spawnOptions?.env?.CMUX_AGENT_LAUNCH_ARGV_B64) throw new Error("session admission dropped launch argv"); +if (spawnOptions.env.CMUX_AGENT_LAUNCH_ARGV_B64 === parentLaunchArgv) throw new Error("session admission reused a parent OpenCode launch capture"); const socketPath = "/tmp/cmux-opencode-v2-" + process.pid + ".sock"; try { await fs.unlink(socketPath); } catch (_) {} From b4413bc40a72b6ea5e6aebb120718067cc3a6d0e Mon Sep 17 00:00:00 2001 From: Austin Wang <38676809+austinywang@users.noreply.github.com> Date: Wed, 14 Oct 2026 01:10:31 -0700 Subject: [PATCH 17/20] test: cover raw OpenCode failure events in Feed Co-Authored-By: Claude Opus 5.5 --- cmuxTests/OpenCodeHookRegressionTests.swift | 37 +++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/cmuxTests/OpenCodeHookRegressionTests.swift b/cmuxTests/OpenCodeHookRegressionTests.swift index 06306b957530..9a42dcdf0abb 100644 --- a/cmuxTests/OpenCodeHookRegressionTests.swift +++ b/cmuxTests/OpenCodeHookRegressionTests.swift @@ -421,6 +421,43 @@ extension CLINotifyProcessIntegrationRegressionTests { XCTAssertEqual(feedEvent?["error"] as? String, "Model not found: unknown/foo") } + func testOpenCodeRawFailureEventFeedEventRetainsErrorState() throws { + let context = try makeClaudeHookContext(name: "opencode-raw-failure-feed") + defer { + Darwin.close(context.listenerFD) + unlink(context.socketPath) + try? FileManager.default.removeItem(at: context.root) + } + startAgentHookMockServerAccepting(context: context) + + let result = runAgentHook( + context: context, + agent: "opencode", + subcommand: "stop", + standardInput: #"{"session_id":"opencode-raw-error-feed","cwd":"/tmp/opencode","hook_event_name":"session.error","error":{"name":"UnknownError","data":{"message":"Model not found: unknown/foo"}}}"# + ) + XCTAssertFalse(result.timedOut, result.stderr) + XCTAssertEqual(result.status, 0, result.stderr) + + let deadline = Date().addingTimeInterval(5) + var feedEvent: [String: Any]? + while Date() < deadline, feedEvent == nil { + feedEvent = context.state.snapshot().compactMap { command -> [String: Any]? in + guard let payload = jsonObject(command), + payload["method"] as? String == "feed.push", + let params = payload["params"] as? [String: Any] else { return nil } + return params["event"] as? [String: Any] + }.first + if feedEvent == nil { + RunLoop.current.run(until: Date().addingTimeInterval(0.01)) + } + } + + XCTAssertEqual(feedEvent?["hook_event_name"] as? String, "Stop") + XCTAssertEqual(feedEvent?["is_error"] as? Bool, true) + XCTAssertEqual(feedEvent?["error"] as? String, "Model not found: unknown/foo") + } + func testOpenCodeStopFailureFeedEventRedactsCredentials() throws { let context = try makeClaudeHookContext(name: "opencode-stop-failure-redact") defer { From 60df02b90c3f3102e8094d2e34266af37b7c6a3a Mon Sep 17 00:00:00 2001 From: Austin Wang <38676809+austinywang@users.noreply.github.com> Date: Wed, 14 Oct 2026 01:11:07 -0700 Subject: [PATCH 18/20] fix: share OpenCode failure classification with Feed A raw session.error, session.execution.failed or session.next.step.failed stop made the notification an error but reached Feed as a successful Stop. Both paths now use one predicate. Co-Authored-By: Claude Opus 5.5 --- CLI/cmux.swift | 20 +++++++++++++------- 1 file changed, 13 insertions(+), 7 deletions(-) diff --git a/CLI/cmux.swift b/CLI/cmux.swift index b13aa6fdc83a..09e132e1f624 100644 --- a/CLI/cmux.swift +++ b/CLI/cmux.swift @@ -40495,12 +40495,7 @@ export default { let openCodeFailure: AgentHookNotificationSummary? = { guard def.name == "opencode" else { return nil } let event = reportedHookEventName(from: input)?.lowercased() ?? "" - let isFailure = event == "stopfailure" - || event.contains("execution.failed") - || event.contains("next.step.failed") - || event == "session.error" - || event == "error" - guard isFailure else { return nil } + guard isOpenCodeFailureHookEvent(event) else { return nil } let rawObject = input.rawObject ?? input.object ?? [:] return classifyAgentHookNotification( def: def, @@ -41796,7 +41791,7 @@ export default { let fallbackHookEventName = Self.feedEventName(forClaudeSubcommand: subcommand) let reportedEvent = reportedHookEventName(from: parsedInput) let isOpenCodeStopFailure = source == "opencode" - && reportedEvent.map { normalizedOpenCodeHookEventName($0) == "stopfailure" } == true + && reportedEvent.map(isOpenCodeFailureHookEvent) == true let hookEventName: String if isOpenCodeStopFailure { // OpenCode uses the Claude-compatible StopFailure discriminator in @@ -42151,6 +42146,17 @@ export default { return "fallback-\(String(digest.prefix(16)))" } + /// The notification and Feed paths share this classification, so a raw + /// OpenCode failure event is an error in both. + private func isOpenCodeFailureHookEvent(_ value: String) -> Bool { + let event = value.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() + return normalizedOpenCodeHookEventName(event) == "stopfailure" + || event.contains("execution.failed") + || event.contains("next.step.failed") + || event == "session.error" + || event == "error" + } + private func normalizedOpenCodeHookEventName(_ value: String) -> String { value .trimmingCharacters(in: .whitespacesAndNewlines) From ddd84e0108d7ae17387fe99588c1bc824865c0ae Mon Sep 17 00:00:00 2001 From: Austin Wang <38676809+austinywang@users.noreply.github.com> Date: Wed, 14 Oct 2026 01:14:02 -0700 Subject: [PATCH 19/20] test: cover OpenCode interrupts and concurrent plugin scopes Co-Authored-By: Claude Opus 5.5 --- tests/test_opencode_server_entry.py | 64 +++++++++++++++++++---------- 1 file changed, 42 insertions(+), 22 deletions(-) diff --git a/tests/test_opencode_server_entry.py b/tests/test_opencode_server_entry.py index 652bd22b6e03..3862e51d9d10 100644 --- a/tests/test_opencode_server_entry.py +++ b/tests/test_opencode_server_entry.py @@ -85,17 +85,15 @@ def session_plugin_source() -> str: } }; const waitFor = async (predicate, message) => { - const deadline = Date.now() + 5000; + const deadline = Date.now() + 30000; while (!predicate()) { if (Date.now() > deadline) throw new Error(message); await new Promise((resolve) => setTimeout(resolve, 20)); } }; -// Load the three cmux entries for one plugin scope and drive one turn. The -// session.deleted sentinel follows the duplicate-prone idle events: socket -// frames are ordered, and every hook process is spawned before the sentinel's. -const runScope = async (scopeCtx, sid) => { +// Load the three cmux entries for one plugin scope, as OpenCode does. +const loadScope = async (scopeCtx) => { const hooks = []; for (const file of ["cmux-feed.js", "cmux-session.js", path.join("cmux", "index.js")]) { const mod = await import(path.join(pluginDir, file)); @@ -104,37 +102,60 @@ def session_plugin_source() -> str: } const active = hooks.filter((hook) => hook && typeof hook.event === "function"); if (active.length === 0) throw new Error("no OpenCode server entry subscribed to events"); + return active; +}; + +let sessionEndsExpected = 0; +const sessionEnds = () => hookLog().split("\n").filter((line) => line.includes("opencode session-end")).length; +const stopHookLines = () => hookLog().split("\n").filter((line) => line.includes("hooks enqueue opencode stop")); + +// Drive one turn. The session.deleted sentinel follows the duplicate-prone +// idle events: socket frames are ordered, and every hook process is spawned +// before the sentinel's. +const runTurn = async (scope, sid, { midTurn = [] } = {}) => { const emit = async (event) => { - for (const hook of active) await hook.event({ event }); + for (const hook of scope) await hook.event({ event }); }; await emit({ type: "session.created", properties: { info: { id: sid, directory: "/tmp" } } }); await emit({ type: "session.status", properties: { sessionID: sid, status: { type: "busy" } } }); + for (const event of midTurn) await emit(event); await emit({ type: "session.status", properties: { sessionID: sid, status: { type: "idle" } } }); await emit({ type: "session.idle", properties: { sessionID: sid } }); await emit({ type: "session.deleted", properties: { info: { id: sid } } }); + sessionEndsExpected++; const forSession = (frame) => frame.params?.event?.session_id === `opencode-${sid}`; await waitFor( () => frames.some((frame) => forSession(frame) && frame.params.event.hook_event_name === "SessionEnd"), `feed sentinel never arrived for ${sid}: ${JSON.stringify(frames)}`, ); - const sessionEnds = () => hookLog().split("\n").filter((line) => line.includes("opencode session-end")).length; - await waitFor(() => sessionEnds() >= runs + 1, `session-end hook never ran for ${sid}`); + await waitFor(() => sessionEnds() >= sessionEndsExpected, `session-end hook never ran for ${sid}`); await waitFor(() => !fakeCmuxRunning(), "hook processes did not exit"); const stops = frames.filter((frame) => forSession(frame) && frame.params.event.hook_event_name === "Stop"); if (stops.length !== 1) throw new Error(`expected one feed Stop for ${sid}, got ${stops.length}: ${JSON.stringify(frames)}`); if (stops[0].params.event.surface_id !== "surface-server-entry") throw new Error("feed Stop lost the surface id"); - return active; + return stops[0]; }; -let runs = 0; -const first = await runScope(ctx, "ses_server_entry"); -runs++; -// OpenCode can reinitialize a plugin scope in the same process; the new scope -// gets a new ctx and must subscribe again. -await runScope({ ...ctx }, "ses_server_entry_reinit"); -runs++; -// The replaced scope's hooks stay registered in OpenCode; they must not emit. +const first = await loadScope(ctx); +// Every loader in one scope receives the same ctx; a repeat load is a no-op. +if ((await loadScope(ctx).catch(() => [])).length !== 0) throw new Error("duplicate loader in one scope subscribed"); +await runTurn(first, "ses_server_entry"); +// OpenCode keeps one scope per directory; a second live scope must not evict +// the first. +const second = await loadScope({ ...ctx, directory: "/tmp/other" }); +await runTurn(second, "ses_server_entry_second"); +await runTurn(first, "ses_server_entry_concurrent"); + +// Esc publishes session.error(MessageAbortedError) and then goes idle. +const aborted = await runTurn(first, "ses_server_entry_abort", { + midTurn: [{ type: "session.error", properties: { sessionID: "ses_server_entry_abort", error: { name: "MessageAbortedError", data: { message: "Aborted" } } } }], +}); +if (aborted.params.event.is_error) throw new Error("an interrupt was reported as a failed turn"); +if (stopHookLines().some((line) => line.includes("StopFailure"))) throw new Error("an interrupt sent a StopFailure hook"); + +// OpenCode disposes a torn-down scope's hooks; they must not emit afterwards. +for (const hook of first) await hook.dispose?.(); const stale = "ses_server_entry_stale"; for (const event of [ { type: "session.created", properties: { info: { id: stale, directory: "/tmp" } } }, @@ -146,11 +167,10 @@ def session_plugin_source() -> str: // Hook processes are spawned synchronously inside event(); wait for them. await waitFor(() => !fakeCmuxRunning(), "hook processes did not exit"); if (frames.some((frame) => frame.params?.event?.session_id === `opencode-${stale}`)) { - throw new Error("replaced feed scope still emitted events"); + throw new Error("a disposed feed scope still emitted events"); } -const hookStops = hookLog().split("\n").filter((line) => line.includes("hooks enqueue opencode stop")); -if (hookStops.length !== 2) throw new Error(`expected one stop hook per turn, got ${hookStops.length}: ${hookLog()}`); -for (const hook of first) hook.dispose?.(); +if (stopHookLines().length !== 4) throw new Error(`expected one stop hook per turn, got ${stopHookLines().length}: ${hookLog()}`); +for (const hook of second) await hook.dispose?.(); server.close(); console.log("PASS: OpenCode server entry delivers one completion"); process.exit(0); @@ -177,7 +197,7 @@ def main() -> int: (package_dir / "package.json").write_text('{"type":"module"}', encoding="utf-8") log_path = root / "cmux.log" fake_cmux = root / "cmux" - fake_cmux.write_text(f'#!/bin/sh\necho "$*" >> "{log_path}"\ncat >/dev/null\n', encoding="utf-8") + fake_cmux.write_text(f'#!/bin/sh\necho "$* $(cat)" >> "{log_path}"\n', encoding="utf-8") fake_cmux.chmod(0o755) socket_path = str(root / "cmux.sock") env = os.environ.copy() From 58f74d22f94d18ae7d93a06fabeecaeacab40f53 Mon Sep 17 00:00:00 2001 From: Austin Wang <38676809+austinywang@users.noreply.github.com> Date: Wed, 14 Oct 2026 01:14:03 -0700 Subject: [PATCH 20/20] fix: keep OpenCode interrupts and concurrent scopes out of failures OpenCode publishes session.error for a user interrupt (MessageAbortedError) and a recoverable context overflow (ContextOverflowError), then goes idle. These turned an Esc into a red error notification. The bridges now let the idle stop decide the outcome. OpenCode keeps one plugin scope per directory and disposes a scope's hooks on teardown, so dedupe only within one ctx instead of evicting the other live scope. Co-Authored-By: Claude Opus 5.5 --- CLI/cmux.swift | 30 +++++++++----- Resources/opencode-plugin.js | 40 +++++++++---------- Resources/opencode-tui-plugin.js | 6 +++ .../cmux-tui/assets/agent-hooks/opencode.js | 5 +++ 4 files changed, 52 insertions(+), 29 deletions(-) diff --git a/CLI/cmux.swift b/CLI/cmux.swift index 09e132e1f624..35c61026a8a7 100644 --- a/CLI/cmux.swift +++ b/CLI/cmux.swift @@ -36742,6 +36742,11 @@ function sendStop(ctx, event, failed = false) { }); } +// OpenCode publishes these through session.error without ending the turn: a +// user interrupt (Esc) then goes idle, and a context overflow compacts and +// continues. The idle stop that follows is the turn's outcome. +const NON_TERMINAL_SESSION_ERRORS = new Set(["MessageAbortedError", "ContextOverflowError"]); + const createCMUXSessionRestore = async (ctx) => { const handleEvent = async (event) => { trackMessage(event); @@ -36770,9 +36775,12 @@ const createCMUXSessionRestore = async (ctx) => { case "session.execution.interrupted": if (!isResumableInterruption(event)) sendStop(ctx, event); break; + case "session.error": + if (NON_TERMINAL_SESSION_ERRORS.has(props.error?.name)) break; + sendStop(ctx, event, true); + break; case "session.execution.failed": case "session.next.step.failed": - case "session.error": sendStop(ctx, event, true); break; case "session.deleted": @@ -36803,23 +36811,27 @@ function isTUIProcessServerContext(ctx) { return Boolean(ctx && typeof ctx === "object" && ctx.client && ctx.serverUrl && ctx.directory); } -const CMUX_SESSION_SERVER_OWNER_KEY = Symbol.for("cmux.session.server.owner"); +const CMUX_SESSION_SERVER_SCOPES_KEY = Symbol.for("cmux.session.server.scopes"); export default { id: "cmux.server", async server(ctx) { if (!isTUIProcessServerContext(ctx)) return {}; - // Every loader in one plugin scope receives the same ctx; a reinitialized - // scope receives a new one and must subscribe again. - const owner = globalThis[CMUX_SESSION_SERVER_OWNER_KEY] ||= { ctx: null }; - if (owner.ctx === ctx) return {}; - owner.ctx = ctx; + // Every loader in one plugin scope receives the same ctx. OpenCode keeps + // one scope per directory and disposes a scope's hooks when it tears it + // down, after which this scope must not send hooks. + const scopes = globalThis[CMUX_SESSION_SERVER_SCOPES_KEY] ||= new WeakSet(); + if (scopes.has(ctx)) return {}; + scopes.add(ctx); globalThis[CMUX_PLUGIN_INSTALLED_KEY] = true; const hooks = await createCMUXSessionRestore(ctx); - // OpenCode never disposes a scope's hooks, so a replaced scope goes quiet. + let disposed = false; return { event: async (input) => { - if (owner.ctx === ctx) await hooks.event(input); + if (!disposed) await hooks.event(input); + }, + dispose() { + disposed = true; }, }; }, diff --git a/Resources/opencode-plugin.js b/Resources/opencode-plugin.js index 41d291d4e60b..a476d2a30ae0 100644 --- a/Resources/opencode-plugin.js +++ b/Resources/opencode-plugin.js @@ -12,6 +12,17 @@ const DEFAULT_SOCKET = `${os.homedir()}/.config/cmux/cmux.sock`; const REPLY_TIMEOUT_MS = 120_000; const MAX_PLAN_BYTES = 128 * 1024; +// OpenCode publishes these through session.error without ending the turn: a +// user interrupt (Esc) then goes idle, and a context overflow compacts and +// continues. The idle stop that follows is the turn's outcome. +const NON_TERMINAL_SESSION_ERRORS = new Set(["MessageAbortedError", "ContextOverflowError"]); + +const isNonTerminalSessionError = (event) => { + if (event?.type !== "session.error") return false; + const props = event.properties || event.data || {}; + return NON_TERMINAL_SESSION_ERRORS.has(props.error?.name); +}; + const createCMUXFeed = async (ctx, options = {}) => { const environment = { ...process.env, ...options.environment }; const socketPath = environment.CMUX_SOCKET_PATH || DEFAULT_SOCKET; @@ -869,6 +880,7 @@ const createCMUXFeed = async (ctx, options = {}) => { case "session.execution.failed": case "session.next.step.failed": case "session.error": { + if (isNonTerminalSessionError(event)) break; const sid = sessionIdFromEvent(event); if (sid && shouldEmitStop(sid, "failure")) { const error = failureMessage(event); @@ -1093,11 +1105,8 @@ const createCMUXFeed = async (ctx, options = {}) => { export const CMUXFeed = createCMUXFeed; -const CMUX_FEED_SERVER_OWNER_KEY = Symbol.for("cmux.feed.server.owner"); +const CMUX_FEED_SERVER_SCOPES_KEY = Symbol.for("cmux.feed.server.scopes"); -// Released OpenCode calls `server(ctx)` inside each TUI process with the -// project server context. Old V2 snapshots called it from a shared service -// without that context, so only subscribe when it is present. const isTUIProcessServerContext = (ctx) => Boolean(ctx && typeof ctx === "object" && ctx.client && ctx.serverUrl && ctx.directory); @@ -1105,22 +1114,13 @@ export default { id: "cmux.server", async server(ctx) { if (!isTUIProcessServerContext(ctx)) return {}; - // cmux-feed.js and plugins/cmux/index.js both load this source. Every - // loader in one plugin scope receives the same ctx; a reinitialized scope - // receives a new one, which replaces the previous feed. - const owner = globalThis[CMUX_FEED_SERVER_OWNER_KEY] ||= { ctx: null, feed: null }; - if (owner.ctx === ctx) return {}; - const previous = owner.feed; - owner.ctx = ctx; - owner.feed = null; - previous?.dispose?.(); - const feed = await createCMUXFeed(ctx); - if (owner.ctx !== ctx) { - feed.dispose(); - return {}; - } - owner.feed = feed; - return feed; + // cmux-feed.js and plugins/cmux/index.js both load this source, and every + // loader in one plugin scope receives the same ctx. OpenCode keeps one + // scope per directory, and disposes a scope's hooks when it tears it down. + const scopes = globalThis[CMUX_FEED_SERVER_SCOPES_KEY] ||= new WeakSet(); + if (scopes.has(ctx)) return {}; + scopes.add(ctx); + return createCMUXFeed(ctx); }, // Compatibility alias for older V2 snapshots that called setup(). setup() { return () => {}; }, diff --git a/Resources/opencode-tui-plugin.js b/Resources/opencode-tui-plugin.js index 3cf2222ae310..63f1bea27898 100644 --- a/Resources/opencode-tui-plugin.js +++ b/Resources/opencode-tui-plugin.js @@ -207,6 +207,11 @@ export function dispatchSessionHook(eventName, payload, spawnImpl = spawn, baseE } } +// OpenCode publishes these through session.error without ending the turn: a +// user interrupt (Esc) then goes idle, and a context overflow compacts and +// continues. The idle stop that follows is the turn's outcome. +const NON_TERMINAL_SESSION_ERRORS = new Set(["MessageAbortedError", "ContextOverflowError"]); + function sessionEventName(event) { const data = properties(event); if (event?.type === "session.created") return "session-start"; @@ -215,6 +220,7 @@ function sessionEventName(event) { // OpenCode keeps an execution interrupted by shutdown and resumes it. if (event?.type === "session.execution.interrupted" && data.reason === "shutdown") return null; if (["session.execution.succeeded", "session.execution.interrupted"].includes(event?.type)) return "stop"; + if (event?.type === "session.error" && NON_TERMINAL_SESSION_ERRORS.has(data.error?.name)) return null; if (["session.execution.failed", "session.next.step.failed", "session.error"].includes(event?.type)) return "stop-failure"; if (event?.type === "session.idle") return "stop"; if (event?.type === "session.status" && statusType(data.status) === "idle") return "stop"; diff --git a/cmux-tui/crates/cmux-tui/assets/agent-hooks/opencode.js b/cmux-tui/crates/cmux-tui/assets/agent-hooks/opencode.js index de4013eaabe2..11b8ce0276e6 100644 --- a/cmux-tui/crates/cmux-tui/assets/agent-hooks/opencode.js +++ b/cmux-tui/crates/cmux-tui/assets/agent-hooks/opencode.js @@ -24,6 +24,7 @@ const events = new Set([ "question.replied", "question.rejected", ]); +const NON_TERMINAL_SESSION_ERRORS = new Set(["MessageAbortedError", "ContextOverflowError"]); const sessionRoots = new Map(); function topology(event) { @@ -67,6 +68,10 @@ const CmuxTuiJournal = async (context) => ({ // already records their visible bytes, so spawning one process per token // would add load without adding a semantic transition. if (!events.has(nativeEvent)) return; + // An interrupt (Esc) or a recoverable context overflow arrives as + // session.error but the turn continues to idle; it is not a failure. + const errorName = (event.properties || event.data || {}).error?.name; + if (nativeEvent === "session.error" && NON_TERMINAL_SESSION_ERRORS.has(errorName)) return; const sessionTopology = topology(event); emit(nativeEvent, { event,