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/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 15636bddca43..35c61026a8a7 100644 --- a/CLI/cmux.swift +++ b/CLI/cmux.swift @@ -36459,6 +36459,7 @@ function sessionState(sessionId) { lastUserMessage: null, assistantPreamble: null, cwd: null, + lastStopKind: null, updatedAt: Date.now(), }); } @@ -36494,6 +36495,57 @@ 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 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); +} + +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; +} + +// 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 +// reclassified, so a later failure or idle for the same turn is dropped. +function shouldSendStop(sessionId, kind) { + const state = sessionState(sessionId); + if (state.lastStopKind) return false; + state.lastStopKind = kind; + return true; +} + function contextForSession(sessionId) { const state = sessionState(sessionId); const context = {}; @@ -36546,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) { @@ -36588,13 +36642,16 @@ function base64NulSeparated(values) { function hookEnvironment(cwd) { const env = { ...process.env }; delete env.AMP_API_KEY; - if (!env.CMUX_AGENT_LAUNCH_ARGV_B64) { - 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; } @@ -36665,29 +36722,66 @@ function trackMessage(event) { } } +// Busy status carries no turn identity; prompts and user messages own it. +function resetTurnFromEvent(event) { + const props = eventProperties(event); + 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) { + 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 } : {}), + }); +} + +// 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); + resetTurnFromEvent(event); const props = eventProperties(event); switch (event && event.type) { case "session.created": + beginTurn(sessionIdFor(event)); 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": + 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": + sendStop(ctx, event, true); break; case "session.deleted": sendHook("session-end", ctx, event); @@ -36710,11 +36804,37 @@ 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); +} + +const CMUX_SESSION_SERVER_SCOPES_KEY = Symbol.for("cmux.session.server.scopes"); + 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 {}; }, + async server(ctx) { + if (!isTUIProcessServerContext(ctx)) return {}; + // 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); + let disposed = false; + return { + event: async (input) => { + if (!disposed) await hooks.event(input); + }, + dispose() { + disposed = true; + }, + }; + }, // Compatibility alias for older V2 snapshots that called setup(). setup() { return () => {}; }, }; @@ -40384,6 +40504,18 @@ export default { ) return summary.status == .error ? summary : nil }() + let openCodeFailure: AgentHookNotificationSummary? = { + guard def.name == "opencode" else { return nil } + let event = reportedHookEventName(from: input)?.lowercased() ?? "" + guard isOpenCodeFailureHookEvent(event) else { return nil } + let rawObject = input.rawObject ?? input.object ?? [:] + return classifyAgentHookNotification( + def: def, + signal: event, + message: openCodeFailureMessage(from: rawObject) ?? "", + 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) @@ -40410,8 +40542,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", @@ -40422,6 +40556,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( @@ -40438,7 +40573,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 = { @@ -40629,7 +40764,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, @@ -40804,6 +40939,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" { @@ -41655,9 +41802,17 @@ export default { ) { let fallbackHookEventName = Self.feedEventName(forClaudeSubcommand: subcommand) let reportedEvent = reportedHookEventName(from: parsedInput) + let isOpenCodeStopFailure = source == "opencode" + && reportedEvent.map(isOpenCodeFailureHookEvent) == 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 @@ -41743,6 +41898,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) @@ -41994,6 +42158,51 @@ 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) + .replacingOccurrences(of: "_", with: "") + .replacingOccurrences(of: "-", with: "") + .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"]) { + 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 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. /// Both native Feed hooks and wrapper hooks call this with the raw payload. private func enrichStopFeedEvent( 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( diff --git a/Resources/opencode-plugin.js b/Resources/opencode-plugin.js index 2d00ad80cd31..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; @@ -84,6 +95,52 @@ 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; + }; + + // 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); + if (isObject(raw)) { + 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); + }; + const normalizeText = (value, max = 1000) => { if (typeof value !== "string") return null; const normalized = value.replace(/\s+/g, " ").trim(); @@ -98,11 +155,25 @@ const createCMUXFeed = async (ctx, options = {}) => { lastUserMessage: null, assistantPreamble: null, cwd: null, + lastStopKind: null, }); } return sessions.get(key); }; + // 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 = {}; @@ -711,6 +782,15 @@ const createCMUXFeed = async (ctx, options = {}) => { return null; }; + 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) return false; + state.lastStopKind = kind; + return true; + }; + const pushBlocking = (event, requestId) => { const reply = new Promise((resolve) => { let timeout; @@ -767,6 +847,7 @@ const createCMUXFeed = async (ctx, options = {}) => { const props = eventProperties(event); const info = props.info || {}; const sid = sessionIdFromProperties(props) || "unknown"; + 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, { @@ -777,19 +858,38 @@ 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") { + beginTurn(sid); + 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 (isResumableInterruption(event)) break; + 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": { + if (isNonTerminalSessionError(event)) break; + 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 +898,25 @@ 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; } + // Admission queues a prompt behind the running turn; promotion and + // execution start are when it actually runs. + case "session.next.prompted": + case "session.execution.started": { + const sid = sessionIdFromEvent(event); + if (sid) beginTurn(sid); + break; + } case "session.deleted": { const sid = sessionIdFromProperties(eventProperties(event)); if (!sid) break; @@ -999,10 +1105,23 @@ const createCMUXFeed = async (ctx, options = {}) => { export const CMUXFeed = createCMUXFeed; +const CMUX_FEED_SERVER_SCOPES_KEY = Symbol.for("cmux.feed.server.scopes"); + +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, 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 45b0bbca8567..63f1bea27898 100644 --- a/Resources/opencode-tui-plugin.js +++ b/Resources/opencode-tui-plugin.js @@ -10,6 +10,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); @@ -51,6 +56,28 @@ 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 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; +} + function rootFor(ctx, id) { try { return ctx?.data?.session?.root?.(id) || id; } catch (_) { return id; } } @@ -130,8 +157,13 @@ function resolveExecutable(name) { function launchArgv() { const raw = Array.isArray(process.argv) ? process.argv.map(String) : []; if (raw.length === 0) return [resolveExecutable("opencode")]; - const worker = (value) => String(value).replaceAll("\\", "/").includes("/$bunfs/") && String(value).endsWith("/tui/worker.js"); - const filtered = raw.filter((value, index) => index === 0 || !worker(value)); + // 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. + const bunVirtual = (value) => { + const normalized = String(value).replaceAll("\\", "/"); + return normalized.includes("/$bunfs/") || normalized.includes("/~BUN/"); + }; + const filtered = raw.filter((value, index) => index === 0 || !bunVirtual(value)); const first = path.basename(filtered[0] || "").toLowerCase(); if (first.includes("opencode") || first.includes("open-code")) return filtered; const tail = filtered.slice(1); @@ -142,13 +174,16 @@ function launchArgv() { function launchEnvironment(cwdValue, baseEnvironment = process.env) { const env = { ...baseEnvironment, CMUXTERM_CLI_RESPONSE_TIMEOUT_SEC: "1" }; delete env.AMP_API_KEY; - if (!env.CMUX_AGENT_LAUNCH_ARGV_B64) { - 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; } @@ -172,17 +207,51 @@ 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"; 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; + // 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" && (data.status?.type || data.status?.status || data.status) === "idle") return "stop"; + if (event?.type === "session.status" && statusType(data.status) === "idle") return "stop"; 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, 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 stopped = new Set(); + return { + begin(id) { stopped.delete(id); }, + settle(id) { + if (stopped.has(id)) return false; + stopped.add(id); + return true; + }, + end(id) { stopped.delete(id); }, + }; +} + function reportError(ctx, _error) { try { const toast = ctx?.ui?.toast?.show; @@ -195,33 +264,44 @@ function reportError(ctx, _error) { } catch (_) {} } -async function deliverEvent(ctx, feed, event, id, environment) { +async function deliverEvent(ctx, feed, event, id, environment, turns) { const hook = sessionEventName(event); - if (hook) { - dispatchSessionHook(hook, { + let admittedHook = hook; + if (hook === "session-end") turns.end(id); + if ((hook === "stop" || hook === "stop-failure") && !turns.settle(id)) admittedHook = null; + 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. await feed.event({ event, ownedSessionId: id }); } -async function handleEvent(ctx, ownership, feed, details, environment, retrySessionStart) { +async function handleEvent(ctx, ownership, feed, details, environment, retrySessionStart, turns) { const event = details?.event || details; 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); return; } if (hook === "session-start") retrySessionStart?.cancel(id); - await deliverEvent(ctx, feed, event, id, environment); + await deliverEvent(ctx, feed, event, id, environment, turns); } // The expiry bounds memory for sessions that never become visible. It only @@ -231,6 +311,7 @@ const SESSION_START_QUEUE_TTL_MS = 30_000; export async function createCMUXTUIBridge(ctx, options = {}) { const environment = { ...process.env, ...options.environment }; let disposed = false; + const turns = createTurnLedger(); // Keep missed session-start events until the TUI reports a route/tab change. // The nested map lets session-end and delivery cancel one session in O(1). const pending = new Map(); @@ -252,7 +333,7 @@ export async function createCMUXTUIBridge(ctx, options = {}) { void handleEvent(ctx, ownership, feed, event, environment, { cancel: cancelPending, enqueue: enqueueSessionStart, - }).catch((error) => reportError(ctx, error)); + }, turns).catch((error) => reportError(ctx, error)); } } }; @@ -287,7 +368,7 @@ export async function createCMUXTUIBridge(ctx, options = {}) { void handleEvent(ctx, ownership, feed, incoming, environment, { cancel: cancelPending, enqueue: enqueueSessionStart, - }).catch((error) => reportError(ctx, error)); + }, turns).catch((error) => reportError(ctx, error)); }; const stop = ctx.data.listen(onEvent); const disposeReactive = createRoot((dispose) => { 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..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() }); @@ -297,6 +305,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", @@ -327,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, @@ -959,6 +986,40 @@ 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 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"] { + 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..11b8ce0276e6 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", @@ -19,10 +24,11 @@ const events = new Set([ "question.replied", "question.rejected", ]); +const NON_TERMINAL_SESSION_ERRORS = new Set(["MessageAbortedError", "ContextOverflowError"]); 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 {}; @@ -62,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, diff --git a/cmuxTests/OpenCodeHookRegressionTests.swift b/cmuxTests/OpenCodeHookRegressionTests.swift index 88b81026516a..9a42dcdf0abb 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 @@ -82,7 +128,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)") @@ -247,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"); } }); @@ -288,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)); @@ -332,3 +382,117 @@ 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") + } + + 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 { + 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 ") + } +} diff --git a/tests/test-execution.toml b/tests/test-execution.toml index dd70912a932a..6c13d617b9ec 100644 --- a/tests/test-execution.toml +++ b/tests/test-execution.toml @@ -1729,6 +1729,11 @@ 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 = "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" lane = "linux-guard" diff --git a/tests/test_opencode_plugin_install.py b/tests/test_opencode_plugin_install.py index f2f161dfe7fb..6da9907e305a 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" @@ -250,6 +251,71 @@ 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.error", + properties: { + sessionID: "opencode-session-test", + error: { name: "UnknownError", data: { message: "provider failed" } } + } + } +}); +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" } + } +}); +// 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: sid, role: "user" } } } +}); +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: sid, error: { name: "UnknownError", data: { message: "late failure" } } } + } +}; +await v1Hooks.event(userMessage("msg-turn-2")); +await v1Hooks.event(busy); +await v1Hooks.event(idle); +await v1Hooks.event(userMessage("msg-turn-2")); +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], @@ -267,8 +333,17 @@ 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 "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") - 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}") @@ -276,6 +351,18 @@ 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") != 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"') != 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: + 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}") + 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 diff --git a/tests/test_opencode_server_entry.py b/tests/test_opencode_server_entry.py new file mode 100644 index 000000000000..3862e51d9d10 --- /dev/null +++ b/tests/test_opencode_server_entry.py @@ -0,0 +1,232 @@ +#!/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, 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"); + +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 { execFileSync } = await import("node:child_process"); +const hookLog = () => (fs.existsSync(logPath) ? fs.readFileSync(logPath, "utf8") : ""); +const fakeCmuxRunning = () => { + try { + execFileSync("pgrep", ["-f", fakeCmux], { stdio: "ignore" }); + return true; + } catch (_) { + return false; + } +}; +const waitFor = async (predicate, message) => { + 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, 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)); + 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"); + 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 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)}`, + ); + 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 stops[0]; +}; + +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" } } }, + { 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("a disposed feed scope still emitted events"); +} +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); +''' + + +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 "$* $(cat)" >> "{log_path}"\n', encoding="utf-8") + fake_cmux.chmod(0o755) + socket_path = str(root / "cmux.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, "fakeCmux": str(fake_cmux)} + ), + ) + 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()) diff --git a/tests/test_opencode_v2_tui_bridge.py b/tests/test_opencode_v2_tui_bridge.py index b67adc629b68..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 (_) {} @@ -194,6 +197,12 @@ def main() -> int: if (observed.some((event) => event.session_id === "opencode-child-stale" && event.hook_event_name === "SessionStart")) throw new Error("ended queued session-start was replayed"); liveA.setRoute(routeA); liveA.setTabs(tabsA); +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" } } }); 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" } } }); @@ -254,7 +263,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 !== 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"); if (stop?.surface_id !== "surface-b" || stop?.workspace_id !== "workspace-b") throw new Error("second TUI Feed event was routed to the first surface"); @@ -267,6 +281,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();