Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
feat: add owner agent turn interrupt control (#675)
Gustavo Ye0b027599b1ac
diff --git a/src/daemon/agent-driver/src/adapters/claude/index.test.ts b/src/daemon/agent-driver/src/adapters/claude/index.test.tsindex 3b6b85f3e..9c5bc7f88 100644--- a/src/daemon/agent-driver/src/adapters/claude/index.test.ts+++ b/src/daemon/agent-driver/src/adapters/claude/index.test.ts@@ -113,4 +113,204 @@ describe("ClaudeDriver", () => {expect(write).toHaveBeenCalledWith(expect.stringContaining('"text":"hello"'));expect(write).toHaveBeenCalledWith(expect.stringContaining(`"uuid":"${receipt.slice("claude:".length)}"`));});++ it("interrupts an active turn with a native control request without signaling the process", async () => {+ const stdin = new PassThrough();+ const write = vi.spyOn(stdin, "write");+ const process = Object.assign(new EventEmitter(), {+ stdin,+ exitCode: null,+ signalCode: null,+ kill: vi.fn(() => true),+ });+ const driver = new ClaudeDriver();+ const receipt = driver.beginTurn();+ const root = receipt.slice("claude:".length);+ driver.normalizeLine(JSON.stringify({ type: "user", uuid: root, isReplay: true }));++ await expect(driver.interrupt(+ { requestId: "interrupt-1", reason: "owner_request" },+ process,+ )).resolves.toBe(true);++ expect(JSON.parse(String(write.mock.calls[0]![0]))).toEqual({+ type: "control_request",+ request_id: "interrupt-1",+ request: { subtype: "interrupt" },+ });+ expect(process.kill).not.toHaveBeenCalled();+ });++ it("defers a pre-root-ack interrupt until root replay and writes one native frame", async () => {+ const stdin = new PassThrough();+ const write = vi.spyOn(stdin, "write");+ const process = Object.assign(new EventEmitter(), {+ stdin,+ exitCode: null,+ signalCode: null,+ kill: vi.fn(() => true),+ });+ const driver = new ClaudeDriver();+ const receipt = driver.beginTurn();+ const root = receipt.slice("claude:".length);++ await expect(driver.interrupt(+ { requestId: "interrupt-before-ack", reason: "owner_request" },+ process,+ )).resolves.toBe(true);+ await expect(driver.interrupt(+ { requestId: "retry-before-ack", reason: "owner_request" },+ process,+ )).resolves.toBe(true);+ expect(write).not.toHaveBeenCalled();++ driver.normalizeLine(JSON.stringify({ type: "system", subtype: "init", session_id: "s1" }));+ expect(write).not.toHaveBeenCalled();+ driver.normalizeLine(JSON.stringify({ type: "user", uuid: root, isReplay: true }));+ expect(write).toHaveBeenCalledOnce();+ expect(JSON.parse(String(write.mock.calls[0]![0]))).toEqual({+ type: "control_request",+ request_id: "interrupt-before-ack",+ request: { subtype: "interrupt" },+ });+ expect(process.kill).not.toHaveBeenCalled();+ });++ it("accepts a B-owned terminal after Claude's ownerless interrupted A boundary", async () => {+ const stdin = new PassThrough();+ const process = Object.assign(new EventEmitter(), {+ stdin,+ exitCode: null,+ signalCode: null,+ kill: vi.fn(() => true),+ });+ const driver = new ClaudeDriver();+ const receipt = driver.beginTurn();+ const root = receipt.slice("claude:".length);+ const steering = JSON.parse(driver.encodeMessage("queued", null, { mode: "busy" }));+ driver.normalizeLine(JSON.stringify({ type: "user", uuid: root, isReplay: true }));+ await driver.interrupt({ requestId: "interrupt-queued", reason: "owner_request" }, process);++ expect(driver.normalizeLine(JSON.stringify({+ type: "result",+ subtype: "error_during_execution",+ terminal_reason: "aborted_tools",+ is_error: true,+ }))).toEqual([]);+ expect(driver.normalizeLine(JSON.stringify({ type: "user", uuid: steering.uuid, isReplay: true }))).toEqual([]);+ expect(driver.normalizeLine(JSON.stringify({+ type: "result",+ subtype: "success",+ terminal_reason: "completed",+ is_error: false,+ user_message_uuid: steering.uuid,+ }))).toEqual([{+ kind: "turn_end",+ sessionId: undefined,+ turnOwner: receipt,+ }]);+ expect(process.kill).not.toHaveBeenCalled();+ });++ it("ends an interrupted turn on Claude's ownerless aborted-streaming terminal", async () => {+ const stdin = new PassThrough();+ const process = Object.assign(new EventEmitter(), {+ stdin,+ exitCode: null,+ signalCode: null,+ kill: vi.fn(() => true),+ });+ const driver = new ClaudeDriver();+ const receipt = driver.beginTurn();+ const root = receipt.slice("claude:".length);+ const steering = JSON.parse(driver.encodeMessage("queued", null, { mode: "busy" }));++ expect(driver.normalizeLine(JSON.stringify({ type: "user", uuid: root, isReplay: true }))).toEqual([]);+ await expect(driver.interrupt(+ { requestId: "interrupt-1", reason: "owner_request" },+ process,+ )).resolves.toBe(true);+ expect(driver.normalizeLine(JSON.stringify({+ type: "result",+ subtype: "success",+ terminal_reason: "aborted_tools",+ user_message_uuid: root,+ }))).toEqual([]);+ expect(driver.normalizeLine(JSON.stringify({ type: "user", uuid: steering.uuid, isReplay: true }))).toEqual([]);+ expect(driver.normalizeLine(JSON.stringify({+ type: "user",+ uuid: "synthetic-interrupt",+ message: { role: "user", content: [{ type: "text", text: "[Request interrupted by user]" }] },+ }))).toEqual([]);++ const terminal = JSON.stringify({+ type: "result",+ subtype: "error_during_execution",+ is_error: true,+ terminal_reason: "aborted_streaming",+ });+ expect(driver.normalizeLine(terminal)).toEqual([{+ kind: "turn_end",+ sessionId: undefined,+ turnOwner: receipt,+ }]);+ expect(driver.normalizeLine(terminal)).toEqual([]);+ expect(process.kill).not.toHaveBeenCalled();+ });++ it("ends a pre-ack interrupt on Claude's ownerless aborted-tools terminal", async () => {+ const stdin = new PassThrough();+ const process = Object.assign(new EventEmitter(), {+ stdin,+ exitCode: null,+ signalCode: null,+ kill: vi.fn(() => true),+ });+ const driver = new ClaudeDriver();+ const receipt = driver.beginTurn();+ const root = receipt.slice("claude:".length);++ await expect(driver.interrupt(+ { requestId: "interrupt-before-root-ack", reason: "owner_request" },+ process,+ )).resolves.toBe(true);+ expect(driver.normalizeLine(JSON.stringify({ type: "user", uuid: root, isReplay: true }))).toEqual([]);+ expect(driver.normalizeLine(JSON.stringify({+ type: "user",+ uuid: "synthetic-interrupt",+ message: { role: "user", content: [{ type: "text", text: "[Request interrupted by user]" }] },+ }))).toEqual([]);++ const terminal = JSON.stringify({+ type: "result",+ subtype: "error_during_execution",+ is_error: true,+ terminal_reason: "aborted_tools",+ });+ expect(driver.normalizeLine(terminal)).toEqual([{+ kind: "turn_end",+ sessionId: undefined,+ turnOwner: receipt,+ }]);+ expect(driver.normalizeLine(terminal)).toEqual([]);+ expect(process.kill).not.toHaveBeenCalled();+ });++ it("does not send a control request when no Claude turn is active", async () => {+ const stdin = new PassThrough();+ const write = vi.spyOn(stdin, "write");+ const process = Object.assign(new EventEmitter(), {+ stdin,+ exitCode: null,+ signalCode: null,+ kill: vi.fn(() => true),+ });++ await expect(new ClaudeDriver().interrupt(+ { requestId: "interrupt-1", reason: "owner_request" },+ process,+ )).resolves.toBe(false);+ expect(write).not.toHaveBeenCalled();+ expect(process.kill).not.toHaveBeenCalled();+ });});diff --git a/src/daemon/agent-driver/src/adapters/claude/index.ts b/src/daemon/agent-driver/src/adapters/claude/index.tsindex ca229a489..49d84e2f0 100644--- a/src/daemon/agent-driver/src/adapters/claude/index.ts+++ b/src/daemon/agent-driver/src/adapters/claude/index.ts@@ -1,16 +1,17 @@/*** Claude Code driver — persistent stream-json process with gated steering.*- * Claude's stdin protocol accepts a stable UUID on every user frame and its- * terminal `result` reports the root `user_message_uuid`. That provider-owned- * receipt, rather than payload content or a process restart, binds a terminal- * to the logical turn that initiated it. Safe-boundary steering frames use- * fresh UUIDs while Claude keeps the root UUID on the eventual result.+ * Claude's stdin protocol accepts a stable UUID on every user frame. Normal+ * terminals report the segment's `user_message_uuid`; native interruption may+ * instead emit an ownerless interrupted segment boundary before queued frames+ * replay. The turn protocol binds either vendor sequence back to the logical+ * root receipt without restarting the persistent process.*/import type {- BackendAdapter, EncodeMessageOptions, AdapterLaunchContext, AdapterEvent, RuntimeLane,- RuntimeLaneOpenOptions, SpawnedProcess, ProbeResult,+ BackendAdapter, EncodeMessageOptions, AdapterLaunchContext, AdapterEvent, LaneInterruptInput, RuntimeLane,+ RuntimeLaneOpenOptions, SpawnedProcess, SpawnedProcessHandle, ProbeResult,} from "../../internal/adapter.js";+import { randomUUID } from "node:crypto";import { createProcessLane } from "../../controller/process-host.js";import { prepareCliTransport } from "../../internal/cliTransport.js";import { buildClaudeProviderIsolationEnv } from "./providerIsolation.js";@@ -41,8 +42,10 @@ export class ClaudeDriver implements BackendAdapter {private readonly turnProtocol = new ClaudeTurnProtocol();private readonly eventNormalizer = new ClaudeEventNormalizer(this.turnProtocol);+ private pendingInterrupt?: { input: LaneInterruptInput; process: SpawnedProcessHandle };beginTurn(): string {+ this.pendingInterrupt = undefined;const receipt = this.turnProtocol.beginTurn();this.eventNormalizer.beginTurn();return receipt;@@ -111,13 +114,54 @@ export class ClaudeDriver implements BackendAdapter {}normalizeLine(line: string): AdapterEvent[] {- return this.eventNormalizer.normalizeLine(line);+ const events = this.eventNormalizer.normalizeLine(line);+ this.flushPendingInterrupt();+ return events;}get currentSessionId(): string | null {return this.eventNormalizer.currentSessionId;}+ async interrupt(input: LaneInterruptInput, process: SpawnedProcessHandle): Promise<boolean> {+ const stdin = process.stdin;+ if (+ !this.turnProtocol.hasActiveTurn()+ || !stdin+ || stdin.destroyed+ || stdin.writableEnded+ || stdin.writable === false+ ) return false;+ this.turnProtocol.noteInterruptRequested();+ if (!this.turnProtocol.acceptsTurnWork()) {+ this.pendingInterrupt ??= { input, process };+ return true;+ }+ this.writeInterrupt(input, process);+ return true;+ }++ private writeInterrupt(input: LaneInterruptInput, process: SpawnedProcessHandle): void {+ process.stdin!.write(JSON.stringify({+ type: "control_request",+ request_id: input.requestId ?? randomUUID(),+ request: { subtype: "interrupt" },+ }) + "\n");+ }++ private flushPendingInterrupt(): void {+ const pending = this.pendingInterrupt;+ if (!pending || !this.turnProtocol.acceptsTurnWork()) return;+ this.pendingInterrupt = undefined;+ const stdin = pending.process.stdin;+ if (!stdin || stdin.destroyed || stdin.writableEnded || stdin.writable === false) return;+ try {+ this.writeInterrupt(pending.input, pending.process);+ } catch {+ // A concurrent process error/exit owns failure settlement.+ }+ }+/** Both idle and busy messages use the same stream-json user-message shape. */encodeMessage(text: string, sessionId: string | null, opts?: EncodeMessageOptions): string {const uuid = opts?.mode === "idle"diff --git a/src/daemon/agent-driver/src/adapters/claude/normalizer.ts b/src/daemon/agent-driver/src/adapters/claude/normalizer.tsindex bbc1c07b3..a57e21b8e 100644--- a/src/daemon/agent-driver/src/adapters/claude/normalizer.ts+++ b/src/daemon/agent-driver/src/adapters/claude/normalizer.ts@@ -25,6 +25,7 @@ const CLAUDE_RESULT_ERROR_CODES = new Map([["error_max_budget_usd", "claude.error_max_budget_usd"],["error_max_structured_output_retries", "claude.error_max_structured_output_retries"],]);+const CLAUDE_INTERRUPT_TERMINAL_REASONS = new Set(["aborted_streaming", "aborted_tools"]);const CLAUDE_USAGE_COMPONENTS = ["inputTokens","outputTokens",@@ -166,13 +167,21 @@ export class ClaudeEventNormalizer {const rawOwner = typeof event.user_message_uuid === "string" && event.user_message_uuid.length > 0? event.user_message_uuid: null;+ const interruptedTerminal = Boolean(+ this.turnProtocol+ && !rawOwner+ && event.subtype === "error_during_execution"+ && CLAUDE_INTERRUPT_TERMINAL_REASONS.has(event.terminal_reason)+ );const turnOwner = rawOwner? this.turnProtocol?.claimResult(rawOwner) ?? (this.turnProtocol ? null : `claude:${rawOwner}`)- : null;+ : interruptedTerminal+ ? this.turnProtocol!.claimInterruptedResult()+ : null;if (this.turnProtocol && !turnOwner) return;const usage = this.buildUsageTelemetry(event, rawOwner);if (usage) out.push(usage);- if (event.is_error || event.subtype === "error_during_execution") {+ if (!interruptedTerminal && (event.is_error || event.subtype === "error_during_execution")) {out.push({kind: "error",code: CLAUDE_RESULT_ERROR_CODES.get(event.subtype) ?? "claude.result_error",diff --git a/src/daemon/agent-driver/src/adapters/claude/turnProtocol.test.ts b/src/daemon/agent-driver/src/adapters/claude/turnProtocol.test.tsindex f4bfe8b41..58f52f9d0 100644--- a/src/daemon/agent-driver/src/adapters/claude/turnProtocol.test.ts+++ b/src/daemon/agent-driver/src/adapters/claude/turnProtocol.test.ts@@ -45,6 +45,44 @@ describe("ClaudeTurnProtocol", () => {expect(protocol.claimResult(root)).toBe(receipt);});+ it("claims Claude's ownerless native-interrupt terminal after queued input replays", () => {+ const protocol = new ClaudeTurnProtocol();+ const receipt = protocol.beginTurn();+ const root = uuidOf(receipt);+ const steering = protocol.steeringInputUuid();+ protocol.acknowledge(root);+ protocol.noteInterruptRequested();++ expect(protocol.claimResult(root)).toBeNull();+ expect(protocol.claimInterruptedResult()).toBeNull();+ protocol.acknowledge(steering);+ expect(protocol.claimInterruptedResult()).toBe(receipt);+ expect(protocol.claimInterruptedResult()).toBeNull();+ expect(protocol.claimResult(steering)).toBeNull();+ });++ it("promotes unreplayed steering after an ownerless interrupted segment boundary", () => {+ const protocol = new ClaudeTurnProtocol();+ const receipt = protocol.beginTurn();+ const root = uuidOf(receipt);+ const steering = protocol.steeringInputUuid();+ protocol.acknowledge(root);+ protocol.noteInterruptRequested();++ expect(protocol.claimInterruptedResult()).toBeNull();+ protocol.acknowledge(steering);+ expect(protocol.claimResult(steering)).toBe(receipt);+ expect(protocol.claimResult(steering)).toBeNull();+ });++ it("rejects ownerless terminals without a native interrupt request", () => {+ const protocol = new ClaudeTurnProtocol();+ const root = uuidOf(protocol.beginTurn());+ protocol.acknowledge(root);+ expect(protocol.claimInterruptedResult()).toBeNull();+ expect(protocol.claimResult(root)).toBe(`claude:${root}`);+ });+it("suppresses a stale prior-turn result after the next logical turn begins", () => {const protocol = new ClaudeTurnProtocol();const first = uuidOf(protocol.beginTurn());diff --git a/src/daemon/agent-driver/src/adapters/claude/turnProtocol.ts b/src/daemon/agent-driver/src/adapters/claude/turnProtocol.tsindex 98501a019..8df6b5cfa 100644--- a/src/daemon/agent-driver/src/adapters/claude/turnProtocol.ts+++ b/src/daemon/agent-driver/src/adapters/claude/turnProtocol.ts@@ -11,13 +11,16 @@ interface DeliveredInput {* Claude may emit a result before every stdin steering frame has been replayed* to stdout. Those not-yet-acknowledged frames become a follow-on provider* segment in the same persistent process. Only the result for the latest- * acknowledged follow-on UUID is the logical terminal.+ * acknowledged follow-on UUID is the logical terminal. Native interruption may+ * instead emit an ownerless interrupted boundary before queued frames replay,+ * so that exact path advances or claims the root receipt separately.*/export class ClaudeTurnProtocol {private rootUuid: string | null = null;private segmentOwnerUuid: string | null = null;private readonly delivered = new Map<string, DeliveredInput>();private awaitingFollowOn = false;+ private interruptRequested = false;private finalized = false;beginTurn(): string {@@ -27,6 +30,7 @@ export class ClaudeTurnProtocol {this.delivered.clear();this.delivered.set(uuid, { acknowledged: false, followOn: false });this.awaitingFollowOn = false;+ this.interruptRequested = false;this.finalized = false;return this.receipt(uuid);}@@ -54,6 +58,14 @@ export class ClaudeTurnProtocol {return this.delivered.get(this.rootUuid)?.acknowledged === true;}+ hasActiveTurn(): boolean {+ return this.rootUuid !== null && !this.finalized;+ }++ noteInterruptRequested(): void {+ if (this.hasActiveTurn()) this.interruptRequested = true;+ }+/** Returns the logical root receipt only when this is the final provider segment. */claimResult(userMessageUuid: string): string | null {if (this.finalized || !this.rootUuid || userMessageUuid !== this.segmentOwnerUuid) return null;@@ -70,6 +82,19 @@ export class ClaudeTurnProtocol {return this.receipt(this.rootUuid);}+ /** Claims or advances Claude's ownerless result emitted after a native interrupt. */+ claimInterruptedResult(): string | null {+ if (this.finalized || !this.rootUuid || !this.interruptRequested) return null;+ const unacknowledged = [...this.delivered.values()].filter((input) => !input.acknowledged);+ if (unacknowledged.length > 0) {+ this.awaitingFollowOn = true;+ for (const input of unacknowledged) input.followOn = true;+ return null;+ }+ this.finalized = true;+ return this.receipt(this.rootUuid);+ }+private receipt(uuid: string): string {return `claude:${uuid}`;}diff --git a/src/daemon/agent-driver/src/adapters/codex/index.test.ts b/src/daemon/agent-driver/src/adapters/codex/index.test.tsindex 6ed2126a6..b386deefe 100644--- a/src/daemon/agent-driver/src/adapters/codex/index.test.ts+++ b/src/daemon/agent-driver/src/adapters/codex/index.test.ts@@ -606,6 +606,61 @@ describe("CodexDriver encodeMessage — turn/steer expectedTurnId", () => {});});+describe("CodexDriver native turn interrupt", () => {+ it("interrupts the active turn over JSON-RPC without signaling the app-server", async () => {+ const driver = new CodexDriver();+ const { process: proc } = await driver.spawn(baseCtx());+ await Promise.resolve();+ driver.normalizeLine(threadStartResult("th_interrupt"));+ driver.normalizeLine(JSON.stringify({+ jsonrpc: "2.0",+ method: "turn/started",+ params: { threadId: "th_interrupt", turn: { id: "turn_active" } },+ }));++ await expect(driver.interrupt(+ { requestId: "owner-1", reason: "owner_request" },+ proc,+ )).resolves.toBe(true);+ const request = stdinWrites(proc)+ .map((write) => JSON.parse(write.trim()))+ .find((message) => message.method === "turn/interrupt");+ expect(request.params).toEqual({ threadId: "th_interrupt", turnId: "turn_active" });+ expect((proc as unknown as ReturnType<typeof simpleProcess>).kill).not.toHaveBeenCalled();+ });++ it("does not send an interrupt without an active turn or after its terminal event", async () => {+ const driver = new CodexDriver();+ const { process: proc } = await driver.spawn(baseCtx());+ await Promise.resolve();+ driver.normalizeLine(threadStartResult("th_interrupt"));+ await expect(driver.interrupt(+ { requestId: "before", reason: "owner_request" },+ proc,+ )).resolves.toBe(false);++ driver.normalizeLine(JSON.stringify({+ jsonrpc: "2.0",+ method: "turn/started",+ params: { threadId: "th_interrupt", turn: { id: "turn_done" } },+ }));+ driver.normalizeLine(JSON.stringify({+ jsonrpc: "2.0",+ method: "turn/completed",+ params: { threadId: "th_interrupt", turn: { id: "turn_done", status: "completed" } },+ }));+ await expect(driver.interrupt(+ { requestId: "after", reason: "owner_request" },+ proc,+ )).resolves.toBe(false);++ const interrupts = stdinWrites(proc)+ .map((write) => JSON.parse(write.trim()))+ .filter((message) => message.method === "turn/interrupt");+ expect(interrupts).toHaveLength(0);+ });+});+describe("CodexDriver live reasoning settings", () => {it("rejects an update when no live thread is available", async () => {await expect(new CodexDriver().updateSettings({ reasoningEffort: "high" })).resolves.toMatchObject({diff --git a/src/daemon/agent-driver/src/adapters/codex/index.ts b/src/daemon/agent-driver/src/adapters/codex/index.tsindex 0daf559d0..318c87c84 100644--- a/src/daemon/agent-driver/src/adapters/codex/index.ts+++ b/src/daemon/agent-driver/src/adapters/codex/index.ts@@ -14,8 +14,8 @@* `thread/resume` with the prior threadId). The thread id is the session id.*/import type {- BackendAdapter, EncodeMessageOptions, AdapterLaunchContext, AdapterEvent, RuntimeLane,- RuntimeLaneOpenOptions, SpawnedProcess,+ BackendAdapter, EncodeMessageOptions, AdapterLaunchContext, AdapterEvent, LaneInterruptInput, RuntimeLane,+ RuntimeLaneOpenOptions, SpawnedProcess, SpawnedProcessHandle,} from "../../internal/adapter.js";import type {AgentDriverError,@@ -532,6 +532,26 @@ export class CodexDriver implements BackendAdapter {return this.eventNormalizer.currentSessionId;}+ async interrupt(_input: LaneInterruptInput, process: SpawnedProcessHandle): Promise<boolean> {+ const threadId = this.eventNormalizer.currentSessionId;+ const turnId = this.eventNormalizer.currentTurnId;+ const stdin = process.stdin;+ if (+ !threadId+ || !turnId+ || !stdin+ || stdin.destroyed+ || stdin.writableEnded+ || stdin.writable === false+ ) return false;+ stdin.write(jsonRpcRequest(+ "turn/interrupt",+ { threadId, turnId },+ this.nextRequestId(),+ ) + "\n");+ return true;+ }+/** A `turn/start` RPC — the sole encoder for starting a fresh Codex turn. */private buildTurnStart(threadId: string, text: string): string {return jsonRpcRequest("turn/start", { threadId, input: [{ type: "text", text }] }, this.nextRequestId());diff --git a/src/daemon/agent-driver/src/adapters/codex/normalizer.test.ts b/src/daemon/agent-driver/src/adapters/codex/normalizer.test.tsindex b1c01ddbf..eeb34a305 100644--- a/src/daemon/agent-driver/src/adapters/codex/normalizer.test.ts+++ b/src/daemon/agent-driver/src/adapters/codex/normalizer.test.ts@@ -514,7 +514,6 @@ describe("CodexEventNormalizer — complete owned event family", () => {expect(n.normalizeLine(notify("thread/tokenUsage/updated", { threadId: "root", tokenUsage: {} }))).toEqual([]);expect(n.normalizeLine(notify("account/rateLimits/updated", { threadId: "root", rateLimits: {} }))).toEqual([]);expect(n.normalizeLine(notify("turn/completed", { threadId: "root", turn: { id: "turn", status: "interrupted" } }))).toEqual([- { kind: "error", code: "codex.turn_interrupted", message: "Codex turn interrupted" },{ kind: "turn_end", sessionId: "root", turnOwner: "codex:root:turn" },]);});diff --git a/src/daemon/agent-driver/src/adapters/codex/normalizer.ts b/src/daemon/agent-driver/src/adapters/codex/normalizer.tsindex 6028596a3..0b0ddb6f1 100644--- a/src/daemon/agent-driver/src/adapters/codex/normalizer.ts+++ b/src/daemon/agent-driver/src/adapters/codex/normalizer.ts@@ -337,9 +337,6 @@ export class CodexEventNormalizer {{ kind: "turn_end", sessionId: this.threadId ?? undefined, turnOwner: this.turnReceipt(params.threadId, params.turn.id) },];}- if (params.turn.status === "interrupted") {- return [{ kind: "error", code: "codex.turn_interrupted", message: "Codex turn interrupted" }, { kind: "turn_end", sessionId: this.threadId ?? undefined, turnOwner: this.turnReceipt(params.threadId, params.turn.id) }];- }return [{ kind: "turn_end", sessionId: this.threadId ?? undefined, turnOwner: this.turnReceipt(params.threadId, params.turn.id) }];case "error":diff --git a/src/daemon/agent-driver/src/controller/logical-session.test.ts b/src/daemon/agent-driver/src/controller/logical-session.test.tsindex 8a04a61b2..831b4e7ab 100644--- a/src/daemon/agent-driver/src/controller/logical-session.test.ts+++ b/src/daemon/agent-driver/src/controller/logical-session.test.ts@@ -18,8 +18,8 @@ import type {RuntimeSettingsUpdateResult,} from "../contract.js";import type {- BackendAdapter, BackendExecution, AdapterLaunchContext, AdapterEvent, LaneAdmission, LaneSendInput,- LaneStartInput, RuntimeLane, RuntimeLaneEventMap, RuntimeLaneOpenOptions,+ BackendAdapter, BackendExecution, AdapterLaunchContext, AdapterEvent, LaneAdmission, LaneInterruptInput,+ LaneSendInput, LaneStartInput, RuntimeLane, RuntimeLaneEventMap, RuntimeLaneOpenOptions, SpawnedProcessHandle,} from "../internal/adapter.js";import { createFakeAgentDriverHost } from "../testing/fake-host.js";import { runAgentDriverConformance } from "../testing/conformance.js";@@ -115,6 +115,9 @@ class FakeDriver implements BackendAdapter {return this.lane;}normalizeLine(line: string): AdapterEvent[] { return [JSON.parse(line) as AdapterEvent]; }+ async interrupt(_input: LaneInterruptInput, process: SpawnedProcessHandle): Promise<boolean> {+ return process.kill("SIGINT");+ }encodeMessage(text: string): string {this.writes.push(text);return this.rejectWrites ? "" : text;diff --git a/src/daemon/agent-driver/src/controller/process-host.test.ts b/src/daemon/agent-driver/src/controller/process-host.test.tsindex 81066be91..abf2d20b5 100644--- a/src/daemon/agent-driver/src/controller/process-host.test.ts+++ b/src/daemon/agent-driver/src/controller/process-host.test.ts@@ -38,6 +38,7 @@ function realSpawnDriver(): ProcessAdapterPrimitives<string, BackendConfig> {terminalOwnership: "lane_generation",},currentSessionId: null,+ interrupt: async () => false,spawn: async () => {const proc = spawn(process.execPath, ["-e", "setInterval(() => {}, 1000)"], {stdio: ["pipe", "pipe", "pipe"],@@ -362,16 +363,109 @@ describe("ProcessLane prompt admission ownership", () => {});describe("ProcessLane interrupt", () => {- it("sends SIGINT only while the process is open", async () => {+ it("delegates to an adapter-native interrupt without signaling the process", async () => {+ const { driver, kill } = controllableDriver(() => []);+ const interrupt = vi.fn(async () => true);+ driver.interrupt = interrupt;+ const session = new ProcessLane(driver, minimalCtx());+ await session.start({ text: "go" });++ await expect(session.interrupt({ requestId: "native-1", reason: "owner_request" })).resolves.toBe(true);+ expect(interrupt).toHaveBeenCalledWith(+ { requestId: "native-1", reason: "owner_request" },+ expect.objectContaining({ stdin: expect.anything() }),+ );+ expect(kill).not.toHaveBeenCalled();+ });++ it("delivers an interrupt that arrives while the process spawn is pending", async () => {+ const { driver, process: proc, kill } = controllableDriver(() => []);+ let releaseSpawn!: () => void;+ const spawnGate = new Promise<void>((resolve) => { releaseSpawn = resolve; });+ driver.spawn = async () => {+ await spawnGate;+ return { process: proc };+ };+ const interrupt = vi.fn(async () => true);+ driver.interrupt = interrupt;+ const session = new ProcessLane(driver, minimalCtx());++ const starting = session.start({ text: "go" });+ await Promise.resolve();+ const firstInterrupt = session.interrupt({ requestId: "during-spawn", reason: "owner_request" });+ const secondInterrupt = session.interrupt({ requestId: "retry-during-spawn", reason: "owner_request" });+ expect(interrupt).not.toHaveBeenCalled();++ releaseSpawn();+ await expect(firstInterrupt).resolves.toBe(true);+ await expect(secondInterrupt).resolves.toBe(true);+ await expect(starting).resolves.toMatchObject({ ok: true });+ expect(interrupt).toHaveBeenCalledOnce();+ expect(interrupt).toHaveBeenCalledWith(+ { requestId: "during-spawn", reason: "owner_request" },+ proc,+ );+ expect(kill).not.toHaveBeenCalled();+ });++ it("settles a pending interrupt when process spawn fails", async () => {+ const { driver } = controllableDriver(() => []);+ let releaseSpawn!: () => void;+ const spawnGate = new Promise<void>((resolve) => { releaseSpawn = resolve; });+ driver.spawn = async () => {+ await spawnGate;+ throw new Error("spawn failed");+ };+ const interrupt = vi.fn(async () => true);+ driver.interrupt = interrupt;+ const session = new ProcessLane(driver, minimalCtx());++ const starting = session.start({ text: "go" });+ await Promise.resolve();+ const interrupting = session.interrupt({ requestId: "during-failed-spawn" });+ releaseSpawn();++ await expect(interrupting).resolves.toBe(false);+ await expect(starting).rejects.toThrow("spawn failed");+ expect(interrupt).not.toHaveBeenCalled();+ });++ it("settles every waiter false when the lane stops before process spawn", async () => {+ const { driver, process: proc } = controllableDriver(() => []);+ let releaseSpawn!: () => void;+ const spawnGate = new Promise<void>((resolve) => { releaseSpawn = resolve; });+ driver.spawn = async () => {+ await spawnGate;+ return { process: proc };+ };+ const interrupt = vi.fn(async () => true);+ driver.interrupt = interrupt;+ const session = new ProcessLane(driver, minimalCtx());++ const starting = session.start({ text: "go" });+ await Promise.resolve();+ const firstInterrupt = session.interrupt({ requestId: "before-stop" });+ const secondInterrupt = session.interrupt({ requestId: "retry-before-stop" });+ await session.stop({ reason: "shutdown" });++ await expect(firstInterrupt).resolves.toBe(false);+ await expect(secondInterrupt).resolves.toBe(false);+ expect(interrupt).not.toHaveBeenCalled();+ releaseSpawn();+ await expect(starting).resolves.toMatchObject({ ok: true });+ await session.stop({ reason: "shutdown" });+ });++ it("does not signal the process when the adapter declines the interrupt", async () => {const { driver, process: proc, kill } = controllableDriver(() => []);const session = new ProcessLane(driver, minimalCtx());- await expect(session.interrupt()).resolves.toBe(false);+ await expect(session.interrupt({ requestId: "before-start" })).resolves.toBe(false);await session.start({ text: "go" });expect(session.signalCode).toBeNull();- await expect(session.interrupt()).resolves.toBe(true);- expect(kill).toHaveBeenCalledWith("SIGINT");+ await expect(session.interrupt({ requestId: "declined" })).resolves.toBe(false);+ expect(kill).not.toHaveBeenCalled();Object.assign(proc, { exitCode: 0 });- await expect(session.interrupt()).resolves.toBe(false);+ await expect(session.interrupt({ requestId: "after-exit" })).resolves.toBe(false);});});diff --git a/src/daemon/agent-driver/src/controller/process-host.ts b/src/daemon/agent-driver/src/controller/process-host.tsindex fe80c5b26..27e6e99e6 100644--- a/src/daemon/agent-driver/src/controller/process-host.ts+++ b/src/daemon/agent-driver/src/controller/process-host.ts@@ -15,6 +15,7 @@ import type {AdapterLaunchContext,BackendExecution,LaneAdmission,+ LaneInterruptInput,LaneSendInput,LaneStartInput,LaneStopInput,@@ -41,6 +42,13 @@ interface ProcessLaneOptions {promptAdmissionTimeoutMs?: number;}+interface PendingInterrupt {+ readonly input: LaneInterruptInput;+ readonly promise: Promise<boolean>;+ readonly resolve: (accepted: boolean) => void;+ readonly reject: (error: unknown) => void;+}+export interface ProcessAdapterPrimitives<Id extends string, Config> {readonly id: Id;readonly execution: BackendExecution;@@ -52,6 +60,7 @@ export interface ProcessAdapterPrimitives<Id extends string, Config> {sessionId: string | null,opts?: import("../internal/adapter.js").EncodeMessageOptions,): string | null;+ interrupt(input: LaneInterruptInput, process: SpawnedProcessHandle): Promise<boolean>;updateSettings?(input: RuntimeSettingsUpdate): Promise<RuntimeSettingsUpdateResult>;}@@ -64,6 +73,7 @@ export class ProcessLane<Id extends string = BuiltinBackendId, Config = BackendCprivate admissionSequence = 0;private activeTerminalReceipt?: string;private stopPromise?: Promise<void>;+ private pendingInterrupt?: PendingInterrupt;private pendingPromptAdmission?: {resolve(admission: LaneAdmission): void;timer?: ReturnType<typeof setTimeout>;@@ -116,12 +126,14 @@ export class ProcessLane<Id extends string = BuiltinBackendId, Config = BackendCtry {spawned = await this.driver.spawn(launchCtx);} catch (error) {+ this.settlePendingInterrupt(false);this.settlePendingPrompt({ ok: false, reason: "runtime_error", error: String(error) });throw error;}const { process: proc } = spawned;this.process = proc;this.attachProcess(proc);+ this.dispatchPendingInterrupt(proc);this.armPendingPromptTimeout();if (this.driver.execution.lifetime === "session" && !this.writableStdin(proc)) {const rejection = this.stdinUnavailableAdmission();@@ -221,6 +233,7 @@ export class ProcessLane<Id extends string = BuiltinBackendId, Config = BackendC}stop(opts: LaneStopInput = {}): Promise<void> {+ this.settlePendingInterrupt(false);this.settlePendingPrompt({ ok: false, reason: "closed", error: "runtime lane stopped before command admission" });if (!this.process) return Promise.resolve();this.stopPromise ??= this.stopProcess(opts);@@ -239,10 +252,36 @@ export class ProcessLane<Id extends string = BuiltinBackendId, Config = BackendC}}- async interrupt(): Promise<boolean> {+ async interrupt(input: LaneInterruptInput): Promise<boolean> {const proc = this.process;- if (!proc || this.closed) return false;- return proc.kill("SIGINT");+ if (!proc) {+ if (!this.started) return false;+ if (this.pendingInterrupt) return this.pendingInterrupt.promise;+ let resolve!: (accepted: boolean) => void;+ let reject!: (error: unknown) => void;+ const promise = new Promise<boolean>((res, rej) => {+ resolve = res;+ reject = rej;+ });+ this.pendingInterrupt = { input, promise, resolve, reject };+ return promise;+ }+ if (this.closed) return false;+ return this.driver.interrupt(input, proc);+ }++ private dispatchPendingInterrupt(proc: SpawnedProcessHandle): void {+ const pending = this.pendingInterrupt;+ if (!pending) return;+ this.pendingInterrupt = undefined;+ void this.driver.interrupt(pending.input, proc).then(pending.resolve, pending.reject);+ }++ private settlePendingInterrupt(accepted: boolean): void {+ const pending = this.pendingInterrupt;+ if (!pending) return;+ this.pendingInterrupt = undefined;+ pending.resolve(accepted);}updateSettings(input: RuntimeSettingsUpdate): Promise<RuntimeSettingsUpdateResult> {diff --git a/src/daemon/agent-driver/src/testing/builtin-session-conformance.test.ts b/src/daemon/agent-driver/src/testing/builtin-session-conformance.test.tsindex 6ddd50a3b..13a050809 100644--- a/src/daemon/agent-driver/src/testing/builtin-session-conformance.test.ts+++ b/src/daemon/agent-driver/src/testing/builtin-session-conformance.test.ts@@ -438,6 +438,25 @@ async function runPublicSessionLifecycle(backend: BuiltinBackendId): Promise<voiexpect(busy.status).toBe(backend === "pi" || backend === "opencode" || backend === "cursor" ? "accepted" : "queued");const interrupted = await session.interrupt({ requestId: "interrupt-1", reason: "conformance" });expect(interrupted.status).toBe("accepted");+ if (backend === "claude") {+ expect(harness.stdinMessages).not.toContainEqual(expect.objectContaining({+ type: "control_request",+ }));+ harness.replayClaudeInput(0);+ await settle();+ expect(harness.stdinMessages).toContainEqual({+ type: "control_request",+ request_id: "interrupt-1",+ request: { subtype: "interrupt" },+ });+ expect(harness.processes[0]!.kill).not.toHaveBeenCalled();+ } else if (backend === "codex") {+ expect(harness.stdinMessages).toContainEqual(expect.objectContaining({+ method: "turn/interrupt",+ params: { threadId: "codex-resumed", turnId: "codex-turn-1" },+ }));+ expect(harness.processes[0]!.kill).not.toHaveBeenCalled();+ }harness.completeTurn(1);await settle();@@ -464,6 +483,11 @@ async function runPublicSessionLifecycle(backend: BuiltinBackendId): Promise<voiawait settle();}+ if (backend === "claude" || backend === "codex") {+ expect(harness.processes).toHaveLength(1);+ expect(harness.processes[0]!.kill).not.toHaveBeenCalled();+ }+const stopping = session.stop({ reason: "shutdown", forceAfterMs: 25 });if (backend === "claude") harness.processes[0]!.finish();expect(await stopping).toMatchObject({ status: "accepted" });diff --git a/src/daemon/src/manager/agentRouter.test.ts b/src/daemon/src/manager/agentRouter.test.tsindex 1c93b4882..d2b353131 100644--- a/src/daemon/src/manager/agentRouter.test.ts+++ b/src/daemon/src/manager/agentRouter.test.ts@@ -39,6 +39,7 @@ function fakeManager(const resets: Array<{ agentId: string; rewakePrompt: string; launchId: string; barrierType?: string }> = [];const switches: Array<{ agentId: string; rewakePrompt: string; launchId: string }> = [];const order: string[] = [];+ const interrupt = vi.fn(async () => undefined);const statuses: Record<string, "idle" | "starting" | "running" | "stopping"> = { ...initialStatuses };const mgr = {register(agentId: string, launch?: { sessionId?: string; launchId?: string }) {@@ -62,6 +63,7 @@ function fakeManager(switches.push({ agentId, rewakePrompt: opts.rewakePrompt, launchId: opts.launchId });order.push(`switch:${agentId}`);},+ interrupt,stop() {},liveSessionReports: () => [],snapshot() {@@ -70,7 +72,7 @@ function fakeManager(return { agents };},} as unknown as AgentProcessManager;- return { mgr, delivers, registers, statuses, forgets, resets, switches, order };+ return { mgr, delivers, registers, statuses, forgets, resets, switches, interrupt, order };}/** Fake channel capturing acks + the command handler the router registers. */@@ -102,6 +104,19 @@ function fakeChannel() {return { ch, wakeAcks, readys, sessionErrors, typings, fire: (c: HostCommand) => handler?.(c) };}+describe("AgentRouter — agent:interrupt", () => {+ it("passes the one-way command to the manager", async () => {+ const { mgr, interrupt } = fakeManager();+ const { ch, fire } = fakeChannel();+ const router = new AgentRouter({ manager: mgr, channel: ch, runtimeReport: [{ id: "mock" }] });+ await router.start();++ await fire({ type: "agent:interrupt", agentId: "a1" });++ expect(interrupt).toHaveBeenCalledWith("a1");+ });+});+describe("AgentRouter — agent:wake", () => {it("registers the runtime config, delivers a generic notice, and acks the wake", async () => {const { mgr, delivers, registers } = fakeManager();diff --git a/src/daemon/src/manager/agentRouter.ts b/src/daemon/src/manager/agentRouter.tsindex ebbc70488..63239ffcb 100644--- a/src/daemon/src/manager/agentRouter.ts+++ b/src/daemon/src/manager/agentRouter.ts@@ -606,6 +606,10 @@ export class AgentRouter {}break;}+ case "agent:interrupt": {+ await this.opts.manager.interrupt(cmd.agentId);+ break;+ }case "agent:stop":this.log.info("agent:stop received", { agentId: cmd.agentId });try {diff --git a/src/daemon/src/manager/managerRuntime.test.ts b/src/daemon/src/manager/managerRuntime.test.tsindex 97e127ff5..6deb1b615 100644--- a/src/daemon/src/manager/managerRuntime.test.ts+++ b/src/daemon/src/manager/managerRuntime.test.ts@@ -303,6 +303,23 @@ function makeManager(opts: { logger?: Logger; tickIntervalMs?: number; idleTimeoreturn { mgr, session, onRuntimeSpawnFailed, onRuntimeSessionEstablished };}+describe("AgentProcessManager — running-turn interrupt", () => {+ it("interrupts the current session without deleting it", async () => {+ const { mgr } = makeManager();+ const session = fakeSession("interrupt-session");+ session.interrupt = vi.fn(async ({ requestId }) => ({ status: "accepted", requestId, turnId: "turn_1" }));+ (mgr as unknown as { sessions: Map<string, TestAgentSession> }).sessions.set("a1", session);++ await mgr.interrupt("a1");++ expect(session.interrupt).toHaveBeenCalledWith({+ requestId: expect.any(String),+ reason: "owner_request",+ });+ expect((mgr as unknown as { sessions: Map<string, TestAgentSession> }).sessions.get("a1")).toBe(session);+ });+});+function exactTimelineLifecycleStub() {return {barrierGeneration: () => 0,diff --git a/src/daemon/src/manager/managerRuntime.ts b/src/daemon/src/manager/managerRuntime.tsindex 9b2c18e42..488777b92 100644--- a/src/daemon/src/manager/managerRuntime.ts+++ b/src/daemon/src/manager/managerRuntime.ts@@ -836,6 +836,11 @@ export class AgentProcessManager {await session.stop({ reason: "owner_request", forceAfterMs: SESSION_STOP_GRACE_MS });if (this.sessions.get(agentId) === session) this.sessions.delete(agentId);}+ async interrupt(agentId: string): Promise<void> {+ const session = this.sessions.get(agentId);+ if (!session) return;+ await session.interrupt({ requestId: randomUUID(), reason: "owner_request" });+ }async stopAll(): Promise<void> {if (this.tickTimer) {clearInterval(this.tickTimer);diff --git a/src/shared/src/community-cli-contract.ts b/src/shared/src/community-cli-contract.tsindex 524fccad3..df31b9d7b 100644--- a/src/shared/src/community-cli-contract.ts+++ b/src/shared/src/community-cli-contract.ts@@ -754,6 +754,12 @@ export interface UnreadNotice {export const CONTROL_HEARTBEAT_CAPABILITY = "control-heartbeat-v1";+export const AgentInterruptRequestSchema = z.strictObject({+ type: z.literal("agent:interrupt"),+ agentId: z.string().min(1).max(128),+});+export type AgentInterruptRequest = z.infer<typeof AgentInterruptRequestSchema>;+/*** Commands the SERVER pushes DOWN to a host (daemon). This is the control plane —* distinct from the agent-initiated data plane (`ServerApi`). The server owns@@ -768,6 +774,7 @@ export const CONTROL_HEARTBEAT_CAPABILITY = "control-heartbeat-v1";*/export type HostCommand =| { type: "machine:heartbeat"; nonce: string }+ | AgentInterruptRequest| {type: "agent:wake";agentId: AgentId;@@ -1475,6 +1482,7 @@ export const HostCommandSchema = z.discriminatedUnion("type", [type: z.literal("agent:stop"),agentId: z.string().min(1),}),+ AgentInterruptRequestSchema,z.object({type: z.literal("agent:reset"),agentId: z.string().min(1),diff --git a/src/shared/src/index.ts b/src/shared/src/index.tsindex 90f3e4cfc..5f0649875 100644--- a/src/shared/src/index.ts+++ b/src/shared/src/index.ts@@ -473,6 +473,7 @@ export type {UpdateProfileRequest as CommunityCliUpdateProfileRequest,UpdateProfileResult as CommunityCliUpdateProfileResult,UnreadNotice,+ AgentInterruptRequest,HostCommand,HostReadyRuntime,HostReady,@@ -487,6 +488,7 @@ export type {} from "./community-cli-contract";export {CONTROL_HEARTBEAT_CAPABILITY,+ AgentInterruptRequestSchema,DM_SERVER,parseRef,formatRef,diff --git a/src/shared/test/community-cli-contract.test.ts b/src/shared/test/community-cli-contract.test.tsindex 83ce75364..811587c59 100644--- a/src/shared/test/community-cli-contract.test.ts+++ b/src/shared/test/community-cli-contract.test.ts@@ -6,6 +6,7 @@ import {formatSeq,parseSeq,DM_SERVER,+ AgentInterruptRequestSchema,HostCommandSchema,type HostCommand,} from "../src/community-cli-contract";@@ -19,6 +20,21 @@ describe("attachment thumbnail upload contract", () => {});});+describe("agent running-turn interrupt contract", () => {+ it("accepts the exact one-way command", () => {+ const request = { type: "agent:interrupt", agentId: "bot_1" };+ expect(HostCommandSchema.parse(request)).toEqual(request);+ expect(AgentInterruptRequestSchema.parse(request)).toEqual(request);+ });++ it("rejects missing, extra, empty, and overlong fields", () => {+ expect(AgentInterruptRequestSchema.safeParse({ type: "agent:interrupt" }).success).toBe(false);+ expect(AgentInterruptRequestSchema.safeParse({ type: "agent:interrupt", agentId: "bot_1", requestId: "x" }).success).toBe(false);+ expect(AgentInterruptRequestSchema.safeParse({ type: "agent:interrupt", agentId: "" }).success).toBe(false);+ expect(AgentInterruptRequestSchema.safeParse({ type: "agent:interrupt", agentId: "x".repeat(129) }).success).toBe(false);+ });+});+describe("parseRef", () => {it('parses "/studio#0042/general" as a plain channel ref', () => {expect(parseRef("/studio#0042/general")).toEqual({ server: "studio#0042", channel: "general" });diff --git a/src/web/src/components/community/channels/thread-split-view.test.ts b/src/web/src/components/community/channels/thread-split-view.test.tsnew file mode 100644index 000000000..29484e52d--- /dev/null+++ b/src/web/src/components/community/channels/thread-split-view.test.ts@@ -0,0 +1,74 @@+import { createElement } from "react"+import TestRenderer, { act } from "react-test-renderer"+import { describe, expect, it, vi } from "vitest"+import {+ THREAD_SPLIT_PANEL_MAX_WIDTH,+ THREAD_SPLIT_PANEL_MIN_WIDTH,+ ThreadSplitView,+} from "./thread-split-view"++const mocks = vi.hoisted(() => ({+ onLayoutChanged: vi.fn(),+}))++vi.mock("react-resizable-panels", () => ({+ useDefaultLayout: () => ({+ defaultLayout: { parent: 56, thread: 44 },+ onLayoutChanged: mocks.onLayoutChanged,+ }),+}))++vi.mock("@/components/ui/resizable", () => ({+ ResizablePanelGroup: (props: Record<string, unknown>) => createElement("panel-group", props),+ ResizablePanel: (props: Record<string, unknown>) => createElement("panel", props),+ ResizableHandle: (props: Record<string, unknown>) => createElement("panel-handle", props),+}))++describe("ThreadSplitView", () => {+ it("uses the shared persistent resize contract in split mode", () => {+ let renderer!: TestRenderer.ReactTestRenderer+ act(() => {+ renderer = TestRenderer.create(createElement(ThreadSplitView, {+ containerRef: vi.fn(),+ split: true,+ parent: createElement("parent-content"),+ thread: createElement("thread-content"),+ }))+ })++ expect(renderer.root.findByType("panel-group").props).toMatchObject({+ id: "community-thread-split-layout",+ orientation: "horizontal",+ defaultLayout: { parent: 56, thread: 44 },+ onLayoutChanged: mocks.onLayoutChanged,+ })+ const [parent, thread] = renderer.root.findAllByType("panel")+ expect(parent?.props).toMatchObject({ id: "parent", defaultSize: "56%", minSize: 320 })+ expect(thread?.props).toMatchObject({+ id: "thread",+ defaultSize: "44%",+ minSize: THREAD_SPLIT_PANEL_MIN_WIDTH,+ maxSize: THREAD_SPLIT_PANEL_MAX_WIDTH,+ })+ expect(renderer.root.findByType("panel-handle").props["aria-label"])+ .toBe("Resize thread panel")+ })++ it("keeps full mode single-pane without resize affordances", () => {+ let renderer!: TestRenderer.ReactTestRenderer+ act(() => {+ renderer = TestRenderer.create(createElement(ThreadSplitView, {+ containerRef: vi.fn(),+ split: false,+ parent: createElement("parent-content"),+ thread: createElement("thread-content"),+ }))+ })++ expect(renderer.root.findAllByType("panel-group")).toHaveLength(0)+ expect(renderer.root.findAllByType("panel-handle")).toHaveLength(0)+ expect(renderer.root.findAllByType("parent-content")).toHaveLength(0)+ expect(renderer.root.findByProps({ "aria-label": "Thread" }).props.className)+ .toContain("flex-1")+ })+})diff --git a/src/web/src/components/community/channels/thread-split-view.tsx b/src/web/src/components/community/channels/thread-split-view.tsxindex 751033660..91d10ebbe 100644--- a/src/web/src/components/community/channels/thread-split-view.tsx+++ b/src/web/src/components/community/channels/thread-split-view.tsx@@ -1,10 +1,27 @@/* Hallmark · modern-minimal · focused/utilitarian · inherited neutral palette* macrostructure: parallel-conversation-panel · pre-emit: P5 H5 E4 S5 R5 V4 · slop: pass*/+"use client"+import type { ReactNode, RefCallback } from "react"-import { cn } from "@/lib/utils"+import { useDefaultLayout } from "react-resizable-panels"+import {+ ResizableHandle,+ ResizablePanel,+ ResizablePanelGroup,+} from "@/components/ui/resizable"import { tid } from "@/lib/community/testids"+export const THREAD_SPLIT_PANEL_MIN_WIDTH = 360+export const THREAD_SPLIT_PANEL_MAX_WIDTH = 800++const threadSplitLayoutStorage = {+ getItem: (key: string) => typeof window === "undefined" ? null : window.localStorage.getItem(key),+ setItem: (key: string, value: string) => {+ if (typeof window !== "undefined") window.localStorage.setItem(key, value)+ },+}+export function ThreadSplitView({containerRef,split,@@ -16,6 +33,12 @@ export function ThreadSplitView({parent: ReactNodethread: ReactNode}) {+ const { defaultLayout, onLayoutChanged } = useDefaultLayout({+ id: "community-thread-split-layout",+ onlySaveAfterUserInteractions: true,+ storage: threadSplitLayoutStorage,+ })+return (<mainref={containerRef}@@ -23,27 +46,57 @@ export function ThreadSplitView({data-layout={split ? "split" : "full"}className="flex min-h-0 min-w-0 flex-1">- {split && (+ {split ? (+ <ResizablePanelGroup+ id="community-thread-split-layout"+ orientation="horizontal"+ defaultLayout={defaultLayout}+ onLayoutChanged={onLayoutChanged}+ className="min-h-0 flex-1"+ >+ <ResizablePanel+ id="parent"+ defaultSize="56%"+ minSize={320}+ className="flex min-h-0 min-w-0 flex-col"+ >+ <section+ data-testid={tid.threadSplitParent}+ aria-label="Parent conversation"+ className="flex min-h-0 min-w-0 flex-1 flex-col"+ >+ {parent}+ </section>+ </ResizablePanel>+ <ResizableHandle+ aria-label="Resize thread panel"+ className="bg-border/60"+ />+ <ResizablePanel+ id="thread"+ defaultSize="44%"+ minSize={THREAD_SPLIT_PANEL_MIN_WIDTH}+ maxSize={THREAD_SPLIT_PANEL_MAX_WIDTH}+ className="flex min-h-0 min-w-0 flex-col bg-background"+ >+ <section+ data-testid={tid.threadSplitPanel}+ aria-label="Thread panel"+ className="flex min-h-0 min-w-0 flex-1 flex-col"+ >+ {thread}+ </section>+ </ResizablePanel>+ </ResizablePanelGroup>+ ) : (<section- data-testid={tid.threadSplitParent}- aria-label="Parent conversation"- className="flex min-h-0 min-w-0 flex-1 flex-col"+ data-testid={tid.threadSplitPanel}+ aria-label="Thread"+ className="flex min-h-0 min-w-0 flex-1 flex-col bg-background">- {parent}+ {thread}</section>)}- <section- data-testid={tid.threadSplitPanel}- aria-label={split ? "Thread panel" : "Thread"}- className={cn(- "flex min-h-0 min-w-0 flex-col bg-background",- split- ? "w-[clamp(26rem,44%,32rem)] shrink-0 border-l border-border/60"- : "flex-1",- )}- >- {thread}- </section></main>)}diff --git a/src/web/src/components/community/social/bot-audit-preview.test.ts b/src/web/src/components/community/social/bot-audit-preview.test.tsindex 45e4ad6bb..a94286d58 100644--- a/src/web/src/components/community/social/bot-audit-preview.test.ts+++ b/src/web/src/components/community/social/bot-audit-preview.test.ts@@ -21,7 +21,11 @@ vi.mock("lucide-react", () => ({Lock: "lock-icon",}))-import { BotAuditPreview, isBotActivityActive } from "./bot-audit-preview"+import {+ BotAuditPreview,+ isBotActivityActive,+ isBotActivityRunning,+} from "./bot-audit-preview"const globalCss = readFileSync(new URL("../../../app/globals.css", import.meta.url), "utf8")@@ -58,6 +62,13 @@ describe("BotAuditPreview", () => {expect(isBotActivityActive("⚡", "Custom status")).toBe(false)})+ it("uses only true running presets for interrupt visibility", () => {+ expect(isBotActivityRunning("⚡", "Working on it")).toBe(true)+ expect(isBotActivityRunning("🌀", "Waking up")).toBe(false)+ expect(isBotActivityRunning("🌙", "Wrapping up")).toBe(false)+ expect(isBotActivityRunning("💤", "Idle")).toBe(false)+ })+it("defines an opacity-only double-beat with a static reduced-motion ring", () => {expect(globalCss).toContain(".bot-audit-active-heartbeat::before")expect(globalCss).toContain("animation: bot-audit-heartbeat 2s ease-in-out infinite")diff --git a/src/web/src/components/community/social/bot-audit-preview.tsx b/src/web/src/components/community/social/bot-audit-preview.tsxindex 587e13421..1467689f7 100644--- a/src/web/src/components/community/social/bot-audit-preview.tsx+++ b/src/web/src/components/community/social/bot-audit-preview.tsx@@ -31,7 +31,14 @@ export function isBotActivityActive(): boolean {return matchesStatus(emoji, text, BOT_ACTIVITY_PRESETS.starting)|| matchesStatus(emoji, text, BOT_ACTIVITY_PRESETS.stopping)- || RUNNING_PRESETS.some((pair) => matchesStatus(emoji, text, pair))+ || isBotActivityRunning(emoji, text)+}++export function isBotActivityRunning(+ emoji: string | null | undefined,+ text: string | null | undefined,+): boolean {+ return RUNNING_PRESETS.some((pair) => matchesStatus(emoji, text, pair))}export function BotAuditPreview({diff --git a/src/web/src/components/community/social/profile-card.test.ts b/src/web/src/components/community/social/profile-card.test.tsindex 08da3af5f..9cdbd19ab 100644--- a/src/web/src/components/community/social/profile-card.test.ts+++ b/src/web/src/components/community/social/profile-card.test.ts@@ -1,8 +1,9 @@import { createElement } from "react"import { renderToStaticMarkup } from "react-dom/server"+import TestRenderer, { act, type ReactTestRenderer } from "react-test-renderer"import { readFileSync } from "node:fs"import { QueryClient, QueryClientProvider } from "@tanstack/react-query"-import { describe, it, expect } from "vitest"+import { afterEach, describe, it, expect, vi } from "vitest"import {displayOwnerHandle,resolveAuditPreviewPlacement,@@ -13,7 +14,36 @@ import { ProfileCard } from "./profile-card"import { serializeBeamSeed } from "@/lib/avatar/seed-url"import type { Profile } from "@/components/community/social/profile-types"-function renderProfile(overrides: Partial<Profile> = {}) {+const mocks = vi.hoisted(() => ({+ profile: undefined as {+ statusEmoji?: string | null+ statusText?: string | null+ } | undefined,+ interruptAgent: vi.fn(),+}))++vi.mock("@/stores/community/ws", async (importOriginal) => ({+ ...await importOriginal<typeof import("@/stores/community/ws")>(),+ useCommunityProfile: () => mocks.profile,+}))++vi.mock("@/hooks/community/use-community-ws", () => ({+ communityWsInterruptAgent: mocks.interruptAgent,+}))++afterEach(() => {+ vi.useRealTimers()+ mocks.interruptAgent.mockReset()+ mocks.profile = undefined+})++function renderProfile(+ overrides: Partial<Profile> = {},+ activityStatus?: { emoji: string; text: string },+) {+ mocks.profile = activityStatus+ ? { statusEmoji: activityStatus.emoji, statusText: activityStatus.text }+ : undefinedconst queryClient = new QueryClient({defaultOptions: { queries: { retry: false } },})@@ -34,10 +64,51 @@ function renderProfile(overrides: Partial<Profile> = {}) {y: 0,bp: "desktop",onClose: () => undefined,+ activityStatusEmoji: activityStatus?.emoji,+ activityStatusText: activityStatus?.text,}),))}+function interactiveProfile(+ queryClient: QueryClient,+ activityStatus: { emoji: string; text: string },+) {+ mocks.profile = {+ statusEmoji: activityStatus.emoji,+ statusText: activityStatus.text,+ }+ return createElement(+ QueryClientProvider,+ { client: queryClient },+ createElement(ProfileCard, {+ embedded: true,+ data: {+ name: "Ren",+ userId: "agent_1",+ avatar: "R",+ about: "",+ mutual: 0,+ identity: {+ kind: "bot",+ ownerProfile: { id: "owner_1", handle: "Owner#0042" },+ ownedByViewer: true,+ },+ },+ x: 0,+ y: 0,+ bp: "desktop",+ onClose: () => undefined,+ }),+ )+}++function findInterruptButton(renderer: ReactTestRenderer) {+ return renderer.root.findAllByType("button").find((button) =>+ button.props["aria-label"] === "Stop current agent turn"+ || button.props["aria-label"] === "Stopping current agent turn")+}+describe("ProfileCard contextual metadata", () => {it("omits the badge when no context label exists", () => {const html = renderProfile()@@ -91,6 +162,93 @@ describe("ProfileCard contextual metadata", () => {expect(html).not.toContain("h-40")})+ it("shows Stop only for the owner while the bot is truly running", () => {+ const identity: Profile["identity"] = {+ kind: "bot",+ ownerProfile: { id: "owner_1", handle: "Owner#0042" },+ ownedByViewer: true,+ }+ const running = renderProfile({ identity }, { emoji: "⚡", text: "Working on it" })+ const starting = renderProfile({ identity }, { emoji: "🌀", text: "Waking up" })+ const nonowner = renderProfile({+ identity: { ...identity, ownedByViewer: false },+ }, { emoji: "⚡", text: "Working on it" })++ expect(running).toContain(">Stop</button>")+ expect(starting).not.toContain(">Stop</button>")+ expect(nonowner).not.toContain(">Stop</button>")+ })++ it("sends once and enters a disabled loading state until exact Idle arrives", async () => {+ vi.useFakeTimers()+ vi.setSystemTime(new Date("2026-09-01T00:00:00.000Z"))+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })+ let renderer: ReactTestRenderer+ await act(async () => {+ renderer = TestRenderer.create(interactiveProfile(+ queryClient,+ { emoji: "⚡", text: "Working on it" },+ ))+ })++ const stop = findInterruptButton(renderer!)+ expect(stop?.props.disabled).toBe(false)+ await act(async () => {+ stop?.props.onClick()+ })+ await act(async () => findInterruptButton(renderer!)?.props.onClick())++ expect(mocks.interruptAgent).toHaveBeenCalledTimes(1)+ expect(mocks.interruptAgent).toHaveBeenCalledWith("agent_1")+ expect(findInterruptButton(renderer!)?.props.disabled).toBe(true)+ expect(JSON.stringify(renderer!.toJSON())).toContain("Stopping…")++ await act(async () => {+ renderer!.update(interactiveProfile(+ queryClient,+ { emoji: "🌙", text: "Wrapping up" },+ ))+ })+ expect(findInterruptButton(renderer!)?.props.disabled).toBe(true)+ expect(JSON.stringify(renderer!.toJSON())).toContain("Stopping…")++ await act(async () => {+ renderer!.update(interactiveProfile(queryClient, { emoji: "💤", text: "Idle" }))+ })+ expect(findInterruptButton(renderer!)).toBeUndefined()++ await act(async () => {+ renderer!.update(interactiveProfile(+ queryClient,+ { emoji: "⚡", text: "Working on it" },+ ))+ })+ expect(findInterruptButton(renderer!)?.props.disabled).toBe(false)+ await act(async () => renderer!.unmount())+ })++ it("fails open after 10 seconds while the activity is still running", async () => {+ vi.useFakeTimers()+ vi.setSystemTime(new Date("2026-09-01T00:00:00.000Z"))+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })+ let renderer: ReactTestRenderer+ await act(async () => {+ renderer = TestRenderer.create(interactiveProfile(+ queryClient,+ { emoji: "⚡", text: "Working on it" },+ ))+ })+ await act(async () => findInterruptButton(renderer!)?.props.onClick())+ expect(findInterruptButton(renderer!)?.props.disabled).toBe(true)++ await act(async () => vi.advanceTimersByTime(9_999))+ expect(findInterruptButton(renderer!)?.props.disabled).toBe(true)+ await act(async () => vi.advanceTimersByTime(1))+ expect(findInterruptButton(renderer!)?.props.disabled).toBe(false)+ expect(JSON.stringify(renderer!.toJSON())).toContain("Stop")+ await act(async () => renderer!.unmount())+ })+it("wraps owner metadata and exposes a full accessible label while truncating long handles", () => {const handle = `${"VeryLongOwner".repeat(4)}#0042`const html = renderProfile({@@ -128,6 +286,8 @@ describe("ProfileCard contextual metadata", () => {expect(source).toContain('addEventListener("animationend", update)')expect(source).toContain("cardElement.offsetWidth")expect(source).toContain("previewElement.offsetWidth")+ expect(source).toContain("onClick={interruptAgent}")+ expect(source).toContain("communityWsInterruptAgent(data.userId)")})})diff --git a/src/web/src/components/community/social/profile-card.tsx b/src/web/src/components/community/social/profile-card.tsxindex 23b042ad5..d2b1b98b5 100644--- a/src/web/src/components/community/social/profile-card.tsx+++ b/src/web/src/components/community/social/profile-card.tsx@@ -1,7 +1,8 @@"use client"-import { useLayoutEffect, useRef, useState } from "react"-import { Bot, MessagesSquare, Shield, UserRound } from "lucide-react"+import { useEffect, useLayoutEffect, useRef, useState } from "react"+import { Bot, CircleStop, LoaderCircle, MessagesSquare, Shield, UserRound } from "lucide-react"+import { BOT_ACTIVITY_PRESETS } from "@alook/shared"import { Popover, PopoverTrigger, PopoverContent } from "@/components/ui/popover"import { Sheet, SheetClose, SheetContent, SheetTitle } from "@/components/ui/sheet"import { Badge } from "@/components/ui/badge"@@ -17,7 +18,8 @@ import type { Breakpoint } from "@/hooks/use-mobile"import { useCommunityProfile } from "@/stores/community/ws"import { avatarInitial } from "@/lib/community/avatar"import { tid } from "@/lib/community/testids"-import { BotAuditPreview, isBotActivityActive } from "./bot-audit-preview"+import { communityWsInterruptAgent } from "@/hooks/community/use-community-ws"+import { BotAuditPreview, isBotActivityActive, isBotActivityRunning } from "./bot-audit-preview"// Live cards resolve status from the global profile map. Seed props are used// only by static, id-less showcase cards.@@ -213,6 +215,7 @@ export function ProfileCard({ data, x, y, bp, onClose, onMessage, isSelf, onUpda}) {const [msg, setMsg] = useState("")const [open, setOpen] = useState(true)+ const [interruptPending, setInterruptPending] = useState(false)const mobile = bp === "mobile"const globalProfile = useCommunityProfile(data.userId)const liveStatus = data.userId@@ -223,6 +226,17 @@ export function ProfileCard({ data, x, y, bp, onClose, onMessage, isSelf, onUpda: undefinedconst { emoji: statusEmoji, text: statusText } = resolveCardStatus(liveStatus, initialStatusEmoji, initialStatusText)const activityStatus = resolveCardStatus(liveStatus, activityStatusEmoji, activityStatusText)+ const activityIdle = activityStatus.emoji === BOT_ACTIVITY_PRESETS.idle.emoji+ && activityStatus.text === BOT_ACTIVITY_PRESETS.idle.text+ useEffect(() => {+ if (!interruptPending) return+ if (activityIdle) {+ setInterruptPending(false)+ return+ }+ const timer = globalThis.setTimeout(() => setInterruptPending(false), 10_000)+ return () => globalThis.clearTimeout(timer)+ }, [activityIdle, interruptPending])const name = data.userId ? (globalProfile?.name ?? "Unknown") : (data.name ?? "Unknown")const avatar = data.userId? (globalProfile?.avatar ?? avatarInitial(name))@@ -248,6 +262,11 @@ export function ProfileCard({ data, x, y, bp, onClose, onMessage, isSelf, onUpdaif (mobile) onClose()else close()}+ const interruptAgent = () => {+ if (!data.userId || interruptPending) return+ setInterruptPending(true)+ communityWsInterruptAgent(data.userId)+ }const card = (<><div className="relative -m-2 mb-0 h-16 overflow-hidden rounded-t-lg">@@ -410,18 +429,35 @@ export function ProfileCard({ data, x, y, bp, onClose, onMessage, isSelf, onUpda</>)- const auditPreview = showAuditPreview && data.userId ? (- <BotAuditPreview- botId={data.userId}- active={isBotActivityActive(activityStatus.emoji, activityStatus.text)}- onOpen={() => onOpenBotAudit?.(data.userId!)}- />+ const secondaryCards = showAuditPreview && data.userId ? (+ <div className="flex w-full flex-col gap-2">+ <BotAuditPreview+ botId={data.userId}+ active={isBotActivityActive(activityStatus.emoji, activityStatus.text)}+ onOpen={() => onOpenBotAudit?.(data.userId!)}+ />+ {(isBotActivityRunning(activityStatus.emoji, activityStatus.text)+ || (interruptPending && !activityIdle)) && (+ <button+ type="button"+ onClick={interruptAgent}+ disabled={interruptPending}+ aria-label={interruptPending ? "Stopping current agent turn" : "Stop current agent turn"}+ className="flex h-11 w-full items-center justify-center gap-2 rounded-xl border border-destructive/40 bg-card px-3 text-sm font-medium text-destructive shadow-(--e1) transition-colors hover:bg-destructive/10 focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none disabled:cursor-wait disabled:bg-destructive/5 disabled:text-destructive/70"+ >+ {interruptPending+ ? <LoaderCircle className="size-4 animate-spin motion-reduce:animate-none" aria-hidden />+ : <CircleStop className="size-4" aria-hidden />}+ {interruptPending ? "Stopping…" : "Stop"}+ </button>+ )}+ </div>) : nullif (embedded)return (<div className="flex w-full flex-col gap-2">- {auditPreview}+ {secondaryCards}<div data-testid={tid.profileCard} className="w-full overflow-hidden rounded-xl border border-border bg-popover p-2 shadow-(--e2)">{card}</div></div>)@@ -445,7 +481,7 @@ export function ProfileCard({ data, x, y, bp, onClose, onMessage, isSelf, onUpda<SheetTitle className="sr-only">{name} profile</SheetTitle><SheetClose className="sr-only">Close profile</SheetClose><div className="flex flex-col gap-2">- {auditPreview}+ {secondaryCards}<div data-testid={tid.profileCard} className="overflow-hidden rounded-xl border border-border bg-popover p-2 shadow-(--e2)">{card}</div></div></SheetContent>@@ -462,7 +498,7 @@ export function ProfileCard({ data, x, y, bp, onClose, onMessage, isSelf, onUpdastyle={{ left: x, top: y }}/><PopoverContent ref={popoverRef} side="right" align="start" sideOffset={8} className="relative w-75 overflow-visible border-0 bg-transparent p-0 shadow-none">- {auditPreview && (+ {secondaryCards && (<divref={previewRef}data-testid={tid.botAuditPreviewDock}@@ -470,7 +506,7 @@ export function ProfileCard({ data, x, y, bp, onClose, onMessage, isSelf, onUpdaclassName="absolute w-full"style={{ left: previewPosition.left, top: previewPosition.top }}>- {auditPreview}+ {secondaryCards}</div>)}<div ref={cardRef} data-testid={tid.profileCard} className="overflow-hidden rounded-xl border border-border bg-popover p-2 shadow-(--e2)">diff --git a/src/web/src/hooks/community/use-community-ws.test.ts b/src/web/src/hooks/community/use-community-ws.test.tsindex c26f13e1f..c63e494a2 100644--- a/src/web/src/hooks/community/use-community-ws.test.ts+++ b/src/web/src/hooks/community/use-community-ws.test.ts@@ -98,6 +98,23 @@ describe("useCommunityWs — public helper contracts", () => {channelId: "ch_typing_contract",})})++ it("sends one interrupt frame through the mounted authenticated transport", async () => {+ const { communityWsInterruptAgent } = await import("./use-community-ws")++ communityWsInterruptAgent("bot_1")+ expect(getStableSend()).not.toHaveBeenCalled()++ await mountHook()+ flushEffects()+ communityWsInterruptAgent("bot_1")++ expect(getStableSend()).toHaveBeenCalledOnce()+ expect(getStableSend()).toHaveBeenCalledWith({+ type: "agent:interrupt",+ agentId: "bot_1",+ })+ })})describe("useCommunityWs — connection status publication", () => {diff --git a/src/web/src/hooks/community/use-community-ws.ts b/src/web/src/hooks/community/use-community-ws.tsindex d3b922379..eff5dbe84 100644--- a/src/web/src/hooks/community/use-community-ws.ts+++ b/src/web/src/hooks/community/use-community-ws.ts@@ -37,6 +37,7 @@ import {isCommunityBrowserEventBatchCandidate,isCommunityEventType,TYPING_INDICATOR_THROTTLE_MS,+ type AgentInterruptRequest,type CommunityWsEvent,} from "@alook/shared"import { trackCommunityWsFrameDropped } from "@/lib/analytics"@@ -181,6 +182,14 @@ export function communityWsReleaseSecondaryChannel(owner: symbol) {useCommunityStore.getState().releaseSecondaryChannel(owner)}+export function communityWsInterruptAgent(agentId: string) {+ if (!activeSend || !agentId) return+ activeSend({+ type: "agent:interrupt",+ agentId,+ } satisfies AgentInterruptRequest)+}+/*** Send a typing indicator. Client-side debounced at 8s per channelId (a DM is* a channel now, so its id is a channelId too). If no WS is connected, thediff --git a/src/web/src/test/e2e-ui/45-desktop-thread-split-view.spec.ts b/src/web/src/test/e2e-ui/45-desktop-thread-split-view.spec.tsindex 15ab649c0..4d5e62fe6 100644--- a/src/web/src/test/e2e-ui/45-desktop-thread-split-view.spec.ts+++ b/src/web/src/test/e2e-ui/45-desktop-thread-split-view.spec.ts@@ -8,6 +8,25 @@ import {} from "./_fixtures/seed"import { tid } from "./_fixtures/testids"+const THREAD_PANEL_MIN_WIDTH = 360+const THREAD_PANEL_MAX_WIDTH = 800++async function resizeThreadPanel(page: import("@playwright/test").Page, targetWidth: number) {+ const divider = page.getByRole("separator", { name: "Resize thread panel" })+ const thread = page.getByTestId(tid.threadSplitPanel)+ const [dividerBox, threadBox] = await Promise.all([+ divider.boundingBox(),+ thread.boundingBox(),+ ])+ if (!dividerBox || !threadBox) throw new Error("Thread split geometry is unavailable")++ const y = dividerBox.y + dividerBox.height / 2+ await page.mouse.move(dividerBox.x + dividerBox.width / 2, y)+ await page.mouse.down()+ await page.mouse.move(threadBox.x + threadBox.width - targetWidth, y, { steps: 8 })+ await page.mouse.up()+}+test.describe.serial("desktop thread split view", () => {let serverId: stringlet textChannelId: string@@ -32,6 +51,44 @@ test.describe.serial("desktop thread split view", () => {forumPostId = await seedForumThread("alice", forumId, forumTitle, "Forum reply")})+ test("resizes the thread panel within limits and restores the user layout", async ({ asUser }) => {+ const { page } = await asUser("alice")+ await page.setViewportSize({ width: 1600, height: 900 })+ await page.goto(`/c/channels/${serverId}/${threadId}`)++ const shell = page.getByTestId(tid.threadSplit)+ const parent = page.getByTestId(tid.threadSplitParent)+ const thread = page.getByTestId(tid.threadSplitPanel)+ await expect(shell).toHaveAttribute("data-layout", "split", { timeout: 20_000 })+ await expect(page.getByRole("separator", { name: "Resize thread panel" })).toBeVisible()+ const layoutWidth = Math.round(+ (await shell.locator('[data-slot="resizable-panel-group"]').boundingBox())?.width ?? 0,+ )++ await resizeThreadPanel(page, 200)+ await expect.poll(async () => Math.round((await thread.boundingBox())?.width ?? 0))+ .toBe(THREAD_PANEL_MIN_WIDTH)+ await expect(parent.getByText(parentBody, { exact: false })).toBeVisible()+ await expect(thread.getByText(threadBody, { exact: false })).toBeVisible()++ await resizeThreadPanel(page, 800)+ const expectedMaxWidth = Math.min(THREAD_PANEL_MAX_WIDTH, layoutWidth - 320)+ await expect.poll(async () => Math.abs(+ Math.round((await thread.boundingBox())?.width ?? 0) - expectedMaxWidth,+ )).toBeLessThanOrEqual(1)++ await resizeThreadPanel(page, 520)+ const savedWidth = Math.round((await thread.boundingBox())?.width ?? 0)+ expect(savedWidth).toBe(520)++ await page.goto(`/c/channels/${serverId}/${textChannelId}`)+ await expect(page.getByTestId(tid.threadSplitPanel)).toHaveCount(0)+ await page.goto(`/c/channels/${serverId}/${threadId}`)+ await expect(shell).toHaveAttribute("data-layout", "split", { timeout: 20_000 })+ await expect.poll(async () => Math.round((await thread.boundingBox())?.width ?? 0))+ .toBe(savedWidth)+ })+test("keeps parent and thread live, supports fullscreen/close, and falls back below the width threshold", async ({ asUser }, testInfo) => {test.setTimeout(120_000)const { page } = await asUser("alice")@@ -92,6 +149,7 @@ test.describe.serial("desktop thread split view", () => {await page.setViewportSize({ width: 1050, height: 900 })await expect(shell).toHaveAttribute("data-layout", "full")await expect(page.getByTestId(tid.threadSplitParent)).toHaveCount(0)+ await expect(page.getByRole("separator", { name: "Resize thread panel" })).toHaveCount(0)expect(await page.evaluate(() => document.documentElement.scrollWidth <= document.documentElement.clientWidth)).toBe(true)const narrowLight = testInfo.outputPath("1050-light-fallback.png")@@ -102,6 +160,7 @@ test.describe.serial("desktop thread split view", () => {await expect(shell).toHaveAttribute("data-layout", "full")await expect(page.getByTestId(tid.threadSplitFullscreen)).toHaveCount(0)await expect(page.getByTestId(tid.threadSplitClose)).toHaveCount(0)+ await expect(page.getByRole("separator", { name: "Resize thread panel" })).toHaveCount(0)expect(await page.evaluate(() => document.documentElement.scrollWidth <= document.documentElement.clientWidth)).toBe(true)const mobileLight = testInfo.outputPath("390-light-full.png")diff --git a/src/ws-do/src/ws-durable/agent-interrupt.test.ts b/src/ws-do/src/ws-durable/agent-interrupt.test.tsnew file mode 100644index 000000000..bb944eaeb--- /dev/null+++ b/src/ws-do/src/ws-durable/agent-interrupt.test.ts@@ -0,0 +1,88 @@+import { afterEach, beforeEach, describe, expect, it } from "vitest"+import { createMockWebSocket } from "../__mocks__/cf"+import {+ cleanupHarness,+ createDO,+ mockGetActiveDoNamesForMachine,+ mockGetBotBindingWithOwner,+ mockLogWarn,+ mockStubFetch,+ resetHarness,+} from "./test-harness"++const request = { type: "agent:interrupt", agentId: "bot_1" }+const binding = {+ machineId: "machine_1",+ runtime: "codex",+ ownerUserId: "owner_1",+ name: "Bot",+ discriminator: "0001",+}++describe("agent running-turn interrupt WS routing", () => {+ beforeEach(resetHarness)+ afterEach(cleanupHarness)++ function userSocket(userId = "owner_1") {+ const ws = createMockWebSocket()+ ws.serializeAttachment({ type: "user", userId, authenticated: true })+ return ws+ }++ it("does not forward a non-owner request", async () => {+ const { durable } = createDO()+ const ws = userSocket("other_1")+ mockGetBotBindingWithOwner.mockResolvedValue(binding)++ await durable.webSocketMessage(ws as unknown as WebSocket, JSON.stringify(request))++ expect(mockGetActiveDoNamesForMachine).not.toHaveBeenCalled()+ expect(mockStubFetch).not.toHaveBeenCalled()+ })++ it("logs a binding lookup failure without forwarding", async () => {+ const { durable } = createDO()+ const ws = userSocket()+ mockGetBotBindingWithOwner.mockRejectedValue(new Error("D1 unavailable"))++ await durable.webSocketMessage(ws as unknown as WebSocket, JSON.stringify(request))++ expect(mockGetActiveDoNamesForMachine).not.toHaveBeenCalled()+ expect(mockStubFetch).not.toHaveBeenCalled()+ expect(mockLogWarn).toHaveBeenCalledWith("agent interrupt routing failed", {+ agentId: "bot_1",+ err: "Error: D1 unavailable",+ })+ })++ it("forwards an owner request unchanged through the existing internal push", async () => {+ const { durable, env } = createDO()+ const ws = userSocket()+ mockGetBotBindingWithOwner.mockResolvedValue(binding)+ mockGetActiveDoNamesForMachine.mockResolvedValue(["do_1"])++ await durable.webSocketMessage(ws as unknown as WebSocket, JSON.stringify(request))++ expect(env.WS_DO.idFromName).toHaveBeenCalledWith("community-machine:do_1")+ const forwarded = mockStubFetch.mock.calls[0]![0] as Request+ expect(forwarded.url).toBe("http://internal/push")+ await expect(forwarded.json()).resolves.toEqual(request)+ expect(ws.send).not.toHaveBeenCalled()+ })++ it("continues to an active DO after a stale DO rejects", async () => {+ const { durable, env } = createDO()+ const ws = userSocket()+ mockGetBotBindingWithOwner.mockResolvedValue(binding)+ mockGetActiveDoNamesForMachine.mockResolvedValue(["stale", "active"])+ mockStubFetch.mockRejectedValueOnce(new Error("stale DO"))++ await durable.webSocketMessage(ws as unknown as WebSocket, JSON.stringify(request))++ expect(env.WS_DO.idFromName).toHaveBeenNthCalledWith(1, "community-machine:stale")+ expect(env.WS_DO.idFromName).toHaveBeenNthCalledWith(2, "community-machine:active")+ expect(mockStubFetch).toHaveBeenCalledTimes(2)+ const forwarded = mockStubFetch.mock.calls[1]![0] as Request+ await expect(forwarded.json()).resolves.toEqual(request)+ })+})diff --git a/src/ws-do/src/ws-durable/agent-interrupt.ts b/src/ws-do/src/ws-durable/agent-interrupt.tsnew file mode 100644index 000000000..fdf32e9eb--- /dev/null+++ b/src/ws-do/src/ws-durable/agent-interrupt.ts@@ -0,0 +1,47 @@+import {+ AgentInterruptRequestSchema,+ createDb,+ queries,+ withD1Retry,+} from "@alook/shared"+import type { UserConnectionState, WsDurableContext } from "./internal"++export async function handleUserAgentInterrupt(+ context: WsDurableContext,+ state: UserConnectionState,+ parsed: unknown,+): Promise<boolean> {+ if (!parsed || typeof parsed !== "object" || (parsed as { type?: unknown }).type !== "agent:interrupt") return false+ const request = AgentInterruptRequestSchema.safeParse(parsed)+ if (!request.success) return true++ try {+ const db = createDb(context.env.DB)+ const binding = await withD1Retry(+ () => queries.communityBot.getBotBindingWithOwner(db, request.data.agentId),+ { route: "ws-do:agent-interrupt-binding" },+ )+ if (!binding || binding.ownerUserId !== state.userId) return true+ const doNames = await withD1Retry(+ () => queries.communityMachine.getActiveDoNamesForMachine(db, binding.machineId),+ { route: "ws-do:agent-interrupt-machine" },+ )+ const body = JSON.stringify(request.data)+ for (const doName of doNames) {+ try {+ const stub = context.env.WS_DO.get(context.env.WS_DO.idFromName("community-machine:" + doName))+ await stub.fetch(new Request("http://internal/push", {+ method: "POST",+ headers: { "content-type": "application/json" },+ body,+ }))+ } catch (err) {+ context.log.warn("agent interrupt push failed", { agentId: request.data.agentId, doName, err: String(err) })+ }+ }+ if (doNames.length === 0) context.log.warn("agent interrupt route unavailable", { agentId: request.data.agentId })+ } catch (err) {+ context.log.warn("agent interrupt routing failed", { agentId: request.data.agentId, err: String(err) })+ }+ return true+}diff --git a/src/ws-do/src/ws-durable/test-harness.ts b/src/ws-do/src/ws-durable/test-harness.tsindex 9ac6342f1..15975c88f 100644--- a/src/ws-do/src/ws-durable/test-harness.ts+++ b/src/ws-do/src/ws-durable/test-harness.ts@@ -88,6 +88,7 @@ export const mockCreateDb = vi.fn().mockReturnValue({})export const mockHashCredential = vi.fn(async (bearer: string) => `hash:${bearer}`)export const mockFindCredentialByHash = vi.fn()export const mockGetMachineByIdForUser = vi.fn()+export const mockGetActiveDoNamesForMachine = vi.fn<(db: unknown, machineId: string) => Promise<string[]>>().mockResolvedValue([])export const mockUpsertMachineByMachineId = vi.fn()export const mockTouchMachineHeartbeat = vi.fn()export const mockMarkMachineOffline = vi.fn()@@ -383,6 +384,7 @@ vi.mock("@alook/shared", async () => {hashCredential: (bearer: string) => mockHashCredential(bearer),findCredentialByHash: (...a: any[]) => mockFindCredentialByHash(...a),getMachineByIdForUser: (...a: any[]) => mockGetMachineByIdForUser(...a),+ getActiveDoNamesForMachine: (...a: [unknown, string]) => mockGetActiveDoNamesForMachine(...a),toSummary: (row: any) => mockToSummary(row),isBotOnline: (...a: [unknown, string]) => mockIsBotOnline(...a),reconcileBotActivityFromRunningAgents: (...a: any[]) =>@@ -530,6 +532,8 @@ export function resetHarness() {mockResolveChannelRecipientUserIds.mockImplementation(resolveChannelRecipientUserIdsMock)mockWithD1Retry.mockImplementation(async <T>(fn: () => Promise<T>, _opts?: unknown): Promise<T> => fn())mockGetBotBinding.mockResolvedValue(null)+ mockGetBotBindingWithOwner.mockResolvedValue(null)+ mockGetActiveDoNamesForMachine.mockResolvedValue([])mockUpdateProfile.mockResolvedValue({})mockGetProfile.mockResolvedValue(null)mockReconcileBotActivityFromRunningAgents.mockResolvedValue([])diff --git a/src/ws-do/src/ws-durable/user-auth.ts b/src/ws-do/src/ws-durable/user-auth.tsindex 8ad923680..354b4fc05 100644--- a/src/ws-do/src/ws-durable/user-auth.ts+++ b/src/ws-do/src/ws-durable/user-auth.ts@@ -38,6 +38,7 @@ import {withCommunityDeliveryProgress,type CommunityDeliveryProgress,} from "./community-delivery-state"+import { handleUserAgentInterrupt } from "./agent-interrupt"export async function handleUserFetch(context: WsDurableContext,@@ -301,6 +302,7 @@ export async function handleWebSocketMessage(return}+ if (state.type === "user" && await handleUserAgentInterrupt(context, state, parsed)) returnif (state.type === "user" && handleClientTypingStart(context, state, parsed)) return}