@devries-cameron20 / t3code Mirror · read-only / commits / 3ce2145864
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 07:15 UTC

feat(fx): add safe CLI updates with cancellation compatibility (#29399)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: maria-rcks <maria@kuuro.net> Co-authored-by: Julius Marminge <51714798+juliusmarminge@users.noreply.github.com>

Jake Leventhal committed Nov 18, 2026 at 19:24 UTC 3ce2145864f1e8b822cc8dff9c8cfdf39d9e450b
25 files changed +1092 -38
apps/server/scripts/acp-mock-agent.ts
+39
@@ -1366,8 +1366,27 @@ const program = Effect.gen(function* () {
1366 status: "in_progress",
1367 },
1368 });
1369 + yield* agent.client.sessionUpdate({
1370 + sessionId: requestedSessionId,
1371 + update: {
1372 + sessionUpdate: "tool_call_update",
1373 + toolCallId: "native-failed-tool",
1374 + title: "Failing command",
1375 + kind: "execute",
1376 + status: "in_progress",
1377 + },
1378 + });
1379 yield* Deferred.await(nativeCancelRequested);
1380 yield* Deferred.await(nativeCancelRelease);
1381 + yield* agent.client.sessionUpdate({
1382 + sessionId: requestedSessionId,
1383 + update: {
1384 + sessionUpdate: "tool_call_update",
1385 + toolCallId: "native-failed-tool",
1386 + status: "failed",
1387 + content: [{ type: "content", content: { type: "text", text: "Permission denied" } }],
1388 + },
1389 + });
1390 yield* agent.client.sessionUpdate({
1391 sessionId: requestedSessionId,
1392 update: {
@@ -1377,6 +1396,26 @@ const program = Effect.gen(function* () {
1396 content: [{ type: "content", content: { type: "text", text: "Cancelled." } }],
1397 },
1398 });
1399 + yield* agent.client.sessionUpdate({
1400 + sessionId: requestedSessionId,
1401 + update: {
1402 + sessionUpdate: "tool_call_update",
1403 + toolCallId: "native-unseen-cancel-tool",
1404 + title: "Cancelled command",
1405 + kind: "execute",
1406 + status: "failed",
1407 + content: [{ type: "content", content: { type: "text", text: "Cancelled." } }],
1408 + },
1409 + });
1410 + // A later output-only update must not undo the interrupted status.
1411 + yield* agent.client.sessionUpdate({
1412 + sessionId: requestedSessionId,
1413 + update: {
1414 + sessionUpdate: "tool_call_update",
1415 + toolCallId: "native-cancel-tool",
1416 + content: [{ type: "content", content: { type: "text", text: "Cancelled. exit 130" } }],
1417 + },
1418 + });
1419 yield* agent.client.sessionUpdate({
1420 sessionId: requestedSessionId,
1421 update: {
apps/server/scripts/record-fx-acp-replay-fixture.ts
+3 -3
@@ -1,8 +1,8 @@
1 /**
2 - * Records an fx ACP replay transcript through the real orchestrator and
3 - * FxAdapterV2, teeing only the protocol logger. Run from apps/server with
4 - * fx 0.0.13 on PATH (or T3_FX_BIN); HOME stays the user's real login:
2 + * Records an fx ACP replay transcript through the real orchestrator and FxAdapterV2.
3 + * Run from apps/server with fx on PATH (or T3_FX_BIN), signed in under HOME:
4 * node scripts/record-fx-acp-replay-fixture.ts --scenario simple
5 + * fx 0.0.14+ saves each recorded mode as the default in ~/.fx/settings.json; restore it after.
6 */
7 import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
8 import * as NodeServices from "@effect/platform-node/NodeServices";
apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts
+66 -4
@@ -7440,6 +7440,26 @@ describe("AcpAdapterV2", () => {
7440 flavor: {
7441 driver: ACP_TEST_DRIVER,
7442 capabilities: AcpProviderCapabilitiesV2,
7443 + extractSubagentUpdate: (tool) =>
7444 + tool.toolCallId === "native-failed-tool"
7445 + ? {
7446 + nativeTaskId: tool.toolCallId,
7447 + childSessionId: null,
7448 + prompt: "Run a command",
7449 + title: null,
7450 + model: null,
7451 + status: tool.status === "failed" ? "failed" : "running",
7452 + result: tool.status === "failed" ? "Permission denied" : null,
7453 + suppressNormalTool: tool.status !== "failed",
7454 + }
7455 + : undefined,
7456 + isCancelledToolCall: Schema.is(
7457 + Schema.Struct({
7458 + update: Schema.Struct({
7459 + toolCallId: Schema.Literals(["native-cancel-tool", "native-unseen-cancel-tool"]),
7460 + }),
7461 + }),
7462 + ),
7463 makeRuntime: makeMockRuntime({
7464 childProcessSpawner,
7465 mockAgentPath: yield* bundledMockAgentPath,
@@ -7508,15 +7528,57 @@ describe("AcpAdapterV2", () => {
7528 );
7529 yield* native.current.request("_test/finish-cancel", {});
7530 yield* Fiber.join(interrupt);
7511 - const terminal = Option.getOrThrow(
7531 + const untilTerminal = Array.from(
7532 yield* runtime.events.pipe(
7513 - Stream.filter(
7533 + Stream.takeUntil(
7534 (event) => event.type === "turn.terminal" && event.providerTurnId === providerTurnId,
7535 ),
7516 - Stream.runHead,
7536 + Stream.runCollect,
7537 ),
7538 );
7519 - assert.equal(terminal.type === "turn.terminal" && terminal.status, "interrupted");
7539 + const terminal = untilTerminal.at(-1);
7540 + assert.equal(terminal?.type === "turn.terminal" && terminal.status, "interrupted");
7541 + // The agent fails the command Stop cut off, then updates its output.
7542 + const command = untilTerminal
7543 + .flatMap((event) =>
7544 + event.type === "turn_item.updated" &&
7545 + event.turnItem.nativeItemRef?.nativeId === "native-cancel-tool"
7546 + ? [event.turnItem]
7547 + : [],
7548 + )
7549 + .at(-1);
7550 + const unseenCommand = untilTerminal
7551 + .flatMap((event) =>
7552 + event.type === "turn_item.updated" &&
7553 + event.turnItem.nativeItemRef?.nativeId === "native-unseen-cancel-tool"
7554 + ? [event.turnItem]
7555 + : [],
7556 + )
7557 + .at(-1);
7558 + assert.equal(unseenCommand?.status, "interrupted");
7559 + assert.equal(command?.status, "interrupted");
7560 + assert.include(command?.type === "command_execution" ? command.output : "", "exit 130");
7561 + const failure = untilTerminal
7562 + .flatMap((event) =>
7563 + event.type === "turn_item.updated" &&
7564 + event.turnItem.nativeItemRef?.nativeId === "native-failed-tool"
7565 + ? [event.turnItem]
7566 + : [],
7567 + )
7568 + .at(-1);
7569 + assert.equal(failure?.status, "failed");
7570 + const subagent = untilTerminal
7571 + .flatMap((event) =>
7572 + event.type === "turn_item.updated" && event.turnItem.type === "subagent"
7573 + ? [event.turnItem]
7574 + : [],
7575 + )
7576 + .at(-1);
7577 + assert.equal(subagent?.status, "failed");
7578 + assert.include(
7579 + failure?.type === "command_execution" ? failure.output : "",
7580 + "Permission denied",
7581 + );
7582 yield* runtime.startTurn(
7583 makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now, ordinal: 2 }),
7584 );
apps/server/src/orchestration-v2/testkit/fixtures/fx_subagent_stop/fx_output.ts new
+40
@@ -0,0 +1,40 @@
1 +import { assert } from "@effect/vitest";
2 +import type { ProviderReplayTranscript } from "@t3tools/contracts";
3 +
4 +import type { OrchestratorV2ScenarioResult } from "../../OrchestratorScenario.ts";
5 +import {
6 + assertBaseProjection,
7 + assertSemanticProjectionIntegrity,
8 + assertUserMessagesInclude,
9 + FX_SUBAGENT_STOP_PROMPT,
10 + projectionFor,
11 +} from "../shared.ts";
12 +
13 +/** fx 0.0.15 fails a sub-agent that Stop cut off; T3 shows it, and its child thread, as interrupted. */
14 +export function assertFxSubagentStopOutput(
15 + result: OrchestratorV2ScenarioResult,
16 + transcript: ProviderReplayTranscript,
17 +) {
18 + assertBaseProjection({ result, transcript, runCount: 1, runStatuses: ["interrupted"] });
19 +
20 + const projection = projectionFor(result, transcript.scenario);
21 + assertSemanticProjectionIntegrity(projection);
22 + assertUserMessagesInclude(projection, [FX_SUBAGENT_STOP_PROMPT]);
23 + assert.notInclude(
24 + projection.turnItems.map((item) => item.type),
25 + "dynamic_tool",
26 + "the subagent call must not also show as a tool row",
27 + );
28 + assert.lengthOf(projection.subagents, 1);
29 + const subagent = projection.subagents[0]!;
30 + assert.equal(subagent.status, "interrupted");
31 + assert.include(subagent.prompt, "stopped.txt");
32 + assert.equal(subagent.result, "Cancelled", "fx's error, not its JSON envelope");
33 + if (subagent.childThreadId === null) throw new Error("The subagent has no child thread");
34 + assert.equal(
35 + result.projections.get(subagent.childThreadId)?.thread.lineage.parentThreadId,
36 + projection.thread.id,
37 + );
38 + assert.equal(projection.providerTurns[0]?.status, "interrupted");
39 + assert.equal(projection.providerThreads[0]?.status, "idle");
40 +}
apps/server/src/orchestration-v2/testkit/fixtures/fx_subagent_stop/fx_transcript.ndjson new
+41
@@ -0,0 +1,41 @@
1 +{"type":"transcript_start","provider":"fx","protocol":"acp.ndjson-jsonrpc","version":"1","scenario":"fx_subagent_stop","metadata":{"generatedBy":"live-fx-recorder","fxVersion":"0.0.15","normalization":"Session ids are fx-session-NN, the workspace is <workspace>, HOME is /home/fx-replay and the recording user is fx-replay. T3-owned prompt text, MCP servers and initialize params other than clientCapabilities and _meta are <any>. User skill names, emails and token-shaped strings are removed. Timestamps are kept as recorded.","droppedFrames":0}}
2 +{"type":"expect_outbound","label":"request:initialize","frame":{"kind":"request","method":"initialize","params":{"protocolVersion":2,"info":"<any>","capabilities":"<any>","clientCapabilities":{"fs":{"readTextFile":false,"writeTextFile":false},"terminal":false,"session":{"notices":{},"compaction":{}},"elicitation":{"form":{}}},"clientInfo":"<any>"}}}
3 +{"type":"emit_inbound","label":"response:initialize","frame":{"kind":"response","method":"initialize","result":{"protocolVersion":1,"agentCapabilities":{"loadSession":true,"promptCapabilities":{"image":true,"audio":false,"embeddedContext":true},"mcpCapabilities":{"http":true,"sse":false,"acp":false},"sessionCapabilities":{"list":{},"resume":{},"close":{},"systemPrompt":{}},"_meta":{"fx":{"steering":true}}},"agentInfo":{"name":"fx","title":"fx","version":"0.0.15"},"authMethods":[]}}}
4 +{"type":"expect_outbound","label":"request:session/new","frame":{"kind":"request","method":"session/new","params":{"cwd":"<workspace>","_meta":{"fx":{"profileMcpServers":true}},"mcpServers":"<any>"}}}
5 +{"type":"emit_inbound","label":"response:session/new","frame":{"kind":"response","method":"session/new","result":{"sessionId":"fx-session-01","configOptions":[{"id":"provider","name":"Provider","category":"model","type":"select","currentValue":"codex","options":[{"value":"gateway","name":"Vercel AI Gateway"},{"value":"codex","name":"Codex subscription"},{"value":"grok","name":"Grok subscription"}]},{"id":"model","name":"Model","category":"model","type":"select","currentValue":"gpt-6.1-sol","options":[{"value":"gpt-6.1-sol","name":"gpt-6.1-sol"},{"value":"gpt-6-astra","name":"gpt-6-astra"},{"value":"gpt-6.1-terra","name":"gpt-6.1-terra"},{"value":"gpt-6-sol","name":"gpt-6-sol"},{"value":"gpt-6-luna","name":"gpt-6-luna"},{"value":"gpt-5.6-sol","name":"gpt-5.6-sol"},{"value":"gpt-5.6-terra","name":"gpt-5.6-terra"},{"value":"gpt-5.6-luna","name":"gpt-5.6-luna"},{"value":"gpt-daybreak-blue-latest","name":"gpt-daybreak-blue-latest"}]},{"id":"mode","name":"Session Mode","description":"Controls how the agent requests permission","category":"mode","type":"select","currentValue":"ask","options":[{"value":"auto","name":"Auto","description":"Check actions with an automatic safety review instead of asking","_meta":{"fx":{"permissionMode":"auto"}}},{"value":"ask","name":"Ask","description":"Request permission before making any changes","_meta":{"fx":{"permissionMode":"ask"}}},{"value":"full-access","name":"Full access","description":"Run every action without asking, outside the sandbox","_meta":{"fx":{"permissionMode":"yolo"}}}]},{"id":"effort","name":"Reasoning Effort","description":"Controls how much the model thinks before responding","category":"thought_level","type":"select","currentValue":"auto","options":[{"value":"auto","name":"default"},{"value":"low","name":"low"},{"value":"medium","name":"medium"},{"value":"high","name":"high"},{"value":"xhigh","name":"xhigh"},{"value":"max","name":"max"},{"value":"ultra","name":"ultra"}]},{"id":"fast","name":"Fast Mode","description":"Uses the model's fast lane","category":"model","type":"select","currentValue":"false","options":[{"value":"false","name":"off"},{"value":"true","name":"on"}]}],"modes":{"currentModeId":"ask","availableModes":[{"id":"auto","name":"Auto","description":"Check actions with an automatic safety review instead of asking"},{"id":"ask","name":"Ask","description":"Request permission before making any changes"},{"id":"full-access","name":"Full access","description":"Run every action without asking, outside the sandbox"}]}}}}
6 +{"type":"emit_inbound","label":"notification:session/update:available_commands_update","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"fx-session-01","update":{"sessionUpdate":"available_commands_update","availableCommands":[]}}}}
7 +{"type":"expect_outbound","label":"request:session/set_config_option","frame":{"kind":"request","method":"session/set_config_option","params":{"sessionId":"fx-session-01","configId":"effort","value":"medium"}}}
8 +{"type":"emit_inbound","label":"response:session/set_config_option","frame":{"kind":"response","method":"session/set_config_option","result":{"configOptions":[{"id":"provider","name":"Provider","category":"model","type":"select","currentValue":"codex","options":[{"value":"gateway","name":"Vercel AI Gateway"},{"value":"codex","name":"Codex subscription"},{"value":"grok","name":"Grok subscription"}]},{"id":"model","name":"Model","category":"model","type":"select","currentValue":"gpt-6.1-sol","options":[{"value":"gpt-6.1-sol","name":"gpt-6.1-sol"},{"value":"gpt-6-astra","name":"gpt-6-astra"},{"value":"gpt-6.1-terra","name":"gpt-6.1-terra"},{"value":"gpt-6-sol","name":"gpt-6-sol"},{"value":"gpt-6-luna","name":"gpt-6-luna"},{"value":"gpt-5.6-sol","name":"gpt-5.6-sol"},{"value":"gpt-5.6-terra","name":"gpt-5.6-terra"},{"value":"gpt-5.6-luna","name":"gpt-5.6-luna"},{"value":"gpt-daybreak-blue-latest","name":"gpt-daybreak-blue-latest"}]},{"id":"mode","name":"Session Mode","description":"Controls how the agent requests permission","category":"mode","type":"select","currentValue":"ask","options":[{"value":"auto","name":"Auto","description":"Check actions with an automatic safety review instead of asking","_meta":{"fx":{"permissionMode":"auto"}}},{"value":"ask","name":"Ask","description":"Request permission before making any changes","_meta":{"fx":{"permissionMode":"ask"}}},{"value":"full-access","name":"Full access","description":"Run every action without asking, outside the sandbox","_meta":{"fx":{"permissionMode":"yolo"}}}]},{"id":"effort","name":"Reasoning Effort","description":"Controls how much the model thinks before responding","category":"thought_level","type":"select","currentValue":"medium","options":[{"value":"auto","name":"default"},{"value":"low","name":"low"},{"value":"medium","name":"medium"},{"value":"high","name":"high"},{"value":"xhigh","name":"xhigh"},{"value":"max","name":"max"},{"value":"ultra","name":"ultra"}]},{"id":"fast","name":"Fast Mode","description":"Uses the model's fast lane","category":"model","type":"select","currentValue":"false","options":[{"value":"false","name":"off"},{"value":"true","name":"on"}]}]}}}
9 +{"type":"expect_outbound","label":"request:session/set_config_option","frame":{"kind":"request","method":"session/set_config_option","params":{"sessionId":"fx-session-01","configId":"mode","value":"ask"}}}
10 +{"type":"emit_inbound","label":"response:session/set_config_option","frame":{"kind":"response","method":"session/set_config_option","result":{"configOptions":[{"id":"provider","name":"Provider","category":"model","type":"select","currentValue":"codex","options":[{"value":"gateway","name":"Vercel AI Gateway"},{"value":"codex","name":"Codex subscription"},{"value":"grok","name":"Grok subscription"}]},{"id":"model","name":"Model","category":"model","type":"select","currentValue":"gpt-6.1-sol","options":[{"value":"gpt-6.1-sol","name":"gpt-6.1-sol"},{"value":"gpt-6-astra","name":"gpt-6-astra"},{"value":"gpt-6.1-terra","name":"gpt-6.1-terra"},{"value":"gpt-6-sol","name":"gpt-6-sol"},{"value":"gpt-6-luna","name":"gpt-6-luna"},{"value":"gpt-5.6-sol","name":"gpt-5.6-sol"},{"value":"gpt-5.6-terra","name":"gpt-5.6-terra"},{"value":"gpt-5.6-luna","name":"gpt-5.6-luna"},{"value":"gpt-daybreak-blue-latest","name":"gpt-daybreak-blue-latest"}]},{"id":"mode","name":"Session Mode","description":"Controls how the agent requests permission","category":"mode","type":"select","currentValue":"ask","options":[{"value":"auto","name":"Auto","description":"Check actions with an automatic safety review instead of asking","_meta":{"fx":{"permissionMode":"auto"}}},{"value":"ask","name":"Ask","description":"Request permission before making any changes","_meta":{"fx":{"permissionMode":"ask"}}},{"value":"full-access","name":"Full access","description":"Run every action without asking, outside the sandbox","_meta":{"fx":{"permissionMode":"yolo"}}}]},{"id":"effort","name":"Reasoning Effort","description":"Controls how much the model thinks before responding","category":"thought_level","type":"select","currentValue":"medium","options":[{"value":"auto","name":"default"},{"value":"low","name":"low"},{"value":"medium","name":"medium"},{"value":"high","name":"high"},{"value":"xhigh","name":"xhigh"},{"value":"max","name":"max"},{"value":"ultra","name":"ultra"}]},{"id":"fast","name":"Fast Mode","description":"Uses the model's fast lane","category":"model","type":"select","currentValue":"false","options":[{"value":"false","name":"off"},{"value":"true","name":"on"}]}]}}}
11 +{"type":"expect_outbound","label":"request:session/prompt","frame":{"kind":"request","method":"session/prompt","params":{"sessionId":"fx-session-01","prompt":[{"type":"text","text":"<t3_code_instructions>\n<any>\n</t3_code_instructions>\n\n<user_request>\nUse exactly one subagent to create a file named stopped.txt containing STOP. Do not create the file yourself. Wait for the subagent, then reply DONE.\n</user_request>"}]}}}
12 +{"type":"emit_inbound","label":"notification:session/update:agent_message_chunk","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"fx-session-01","update":{"sessionUpdate":"agent_message_chunk","messageId":"0aed77e99fd86a770413f2ec005c9dee","content":{"type":"text","text":"I’ll have one"}}}}}
13 +{"type":"emit_inbound","label":"notification:session/update:agent_message_chunk","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"fx-session-01","update":{"sessionUpdate":"agent_message_chunk","messageId":"0aed77e99fd86a770413f2ec005c9dee","content":{"type":"text","text":" sub"}}}}}
14 +{"type":"emit_inbound","label":"notification:session/update:agent_message_chunk","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"fx-session-01","update":{"sessionUpdate":"agent_message_chunk","messageId":"0aed77e99fd86a770413f2ec005c9dee","content":{"type":"text","text":"agent"}}}}}
15 +{"type":"emit_inbound","label":"notification:session/update:agent_message_chunk","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"fx-session-01","update":{"sessionUpdate":"agent_message_chunk","messageId":"0aed77e99fd86a770413f2ec005c9dee","content":{"type":"text","text":" create"}}}}}
16 +{"type":"emit_inbound","label":"notification:session/update:agent_message_chunk","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"fx-session-01","update":{"sessionUpdate":"agent_message_chunk","messageId":"0aed77e99fd86a770413f2ec005c9dee","content":{"type":"text","text":" `"}}}}}
17 +{"type":"emit_inbound","label":"notification:session/update:agent_message_chunk","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"fx-session-01","update":{"sessionUpdate":"agent_message_chunk","messageId":"0aed77e99fd86a770413f2ec005c9dee","content":{"type":"text","text":"st"}}}}}
18 +{"type":"emit_inbound","label":"notification:session/update:agent_message_chunk","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"fx-session-01","update":{"sessionUpdate":"agent_message_chunk","messageId":"0aed77e99fd86a770413f2ec005c9dee","content":{"type":"text","text":"opped"}}}}}
19 +{"type":"emit_inbound","label":"notification:session/update:agent_message_chunk","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"fx-session-01","update":{"sessionUpdate":"agent_message_chunk","messageId":"0aed77e99fd86a770413f2ec005c9dee","content":{"type":"text","text":".txt"}}}}}
20 +{"type":"emit_inbound","label":"notification:session/update:agent_message_chunk","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"fx-session-01","update":{"sessionUpdate":"agent_message_chunk","messageId":"0aed77e99fd86a770413f2ec005c9dee","content":{"type":"text","text":"`"}}}}}
21 +{"type":"emit_inbound","label":"notification:session/update:agent_message_chunk","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"fx-session-01","update":{"sessionUpdate":"agent_message_chunk","messageId":"0aed77e99fd86a770413f2ec005c9dee","content":{"type":"text","text":" containing"}}}}}
22 +{"type":"emit_inbound","label":"notification:session/update:agent_message_chunk","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"fx-session-01","update":{"sessionUpdate":"agent_message_chunk","messageId":"0aed77e99fd86a770413f2ec005c9dee","content":{"type":"text","text":" `"}}}}}
23 +{"type":"emit_inbound","label":"notification:session/update:agent_message_chunk","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"fx-session-01","update":{"sessionUpdate":"agent_message_chunk","messageId":"0aed77e99fd86a770413f2ec005c9dee","content":{"type":"text","text":"STOP"}}}}}
24 +{"type":"emit_inbound","label":"notification:session/update:agent_message_chunk","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"fx-session-01","update":{"sessionUpdate":"agent_message_chunk","messageId":"0aed77e99fd86a770413f2ec005c9dee","content":{"type":"text","text":"`,"}}}}}
25 +{"type":"emit_inbound","label":"notification:session/update:agent_message_chunk","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"fx-session-01","update":{"sessionUpdate":"agent_message_chunk","messageId":"0aed77e99fd86a770413f2ec005c9dee","content":{"type":"text","text":" then"}}}}}
26 +{"type":"emit_inbound","label":"notification:session/update:agent_message_chunk","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"fx-session-01","update":{"sessionUpdate":"agent_message_chunk","messageId":"0aed77e99fd86a770413f2ec005c9dee","content":{"type":"text","text":" wait"}}}}}
27 +{"type":"emit_inbound","label":"notification:session/update:agent_message_chunk","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"fx-session-01","update":{"sessionUpdate":"agent_message_chunk","messageId":"0aed77e99fd86a770413f2ec005c9dee","content":{"type":"text","text":" for"}}}}}
28 +{"type":"emit_inbound","label":"notification:session/update:agent_message_chunk","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"fx-session-01","update":{"sessionUpdate":"agent_message_chunk","messageId":"0aed77e99fd86a770413f2ec005c9dee","content":{"type":"text","text":" it"}}}}}
29 +{"type":"emit_inbound","label":"notification:session/update:agent_message_chunk","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"fx-session-01","update":{"sessionUpdate":"agent_message_chunk","messageId":"0aed77e99fd86a770413f2ec005c9dee","content":{"type":"text","text":" to"}}}}}
30 +{"type":"emit_inbound","label":"notification:session/update:agent_message_chunk","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"fx-session-01","update":{"sessionUpdate":"agent_message_chunk","messageId":"0aed77e99fd86a770413f2ec005c9dee","content":{"type":"text","text":" finish"}}}}}
31 +{"type":"emit_inbound","label":"notification:session/update:agent_message_chunk","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"fx-session-01","update":{"sessionUpdate":"agent_message_chunk","messageId":"0aed77e99fd86a770413f2ec005c9dee","content":{"type":"text","text":".\n"}}}}}
32 +{"type":"emit_inbound","label":"notification:session/update:tool_call","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"fx-session-01","update":{"sessionUpdate":"tool_call","toolCallId":"call_77315bade0584581bc46d00bd72efcc7","name":"subagent","title":"Subagent · Create a file named stopped.txt in the current workspace containing exactly STOP (no newline). Use local tools to cre...","kind":"other","status":"pending","rawInput":{"action":"run","task":"Create a file named stopped.txt in the current workspace containing exactly STOP (no newline). Use local tools to create it and verify its contents. Do not spawn any subagents. Report completion."},"_meta":{"fx":{"toolCall":{"internal":false}}}}}}}
33 +{"type":"emit_inbound","label":"notification:session/update:tool_call_update","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"fx-session-01","update":{"sessionUpdate":"tool_call_update","toolCallId":"call_77315bade0584581bc46d00bd72efcc7","status":"in_progress"}}}}
34 +{"type":"expect_outbound","label":"notification:session/cancel","frame":{"kind":"notification","method":"session/cancel","params":{"sessionId":"fx-session-01"}}}
35 +{"type":"emit_inbound","label":"notification:session/update:tool_call_update","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"fx-session-01","update":{"sessionUpdate":"tool_call_update","toolCallId":"call_77315bade0584581bc46d00bd72efcc7","status":"failed","content":[{"type":"content","content":{"type":"text","text":"{\"error\":{\"type\":\"tool_execution_failed\",\"tool_name\":\"subagent\",\"message\":\"Tool execution failed\",\"details\":{\"error\":\"Cancelled\"}}}"}}]}}}}
36 +{"type":"emit_inbound","label":"notification:session/update:session_info_update","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"fx-session-01","update":{"sessionUpdate":"session_info_update","title":"Create stopped.txt via subagent","updatedAt":"2026-10-29T14:23:01Z"}}}}
37 +{"type":"emit_inbound","label":"notification:session/update:usage_update","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"fx-session-01","update":{"sessionUpdate":"usage_update","used":6410,"size":500000}}}}
38 +{"type":"emit_inbound","label":"response:session/prompt","frame":{"kind":"response","method":"session/prompt","result":{"stopReason":"cancelled","usage":{"inputTokens":6321,"outputTokens":89,"cacheReadTokens":3328,"cacheWriteTokens":0,"reasoningTokens":0}}}}
39 +{"type":"expect_outbound","label":"request:session/close","frame":{"kind":"request","method":"session/close","params":{"sessionId":"fx-session-01"}}}
40 +{"type":"emit_inbound","label":"response:session/close","frame":{"kind":"response","method":"session/close","result":{}}}
41 +{"type":"runtime_exit","status":"success"}
apps/server/src/orchestration-v2/testkit/fixtures/fx_subagent_stop/input.ts new
+15
@@ -0,0 +1,15 @@
1 +import { FX_SUBAGENT_STOP_PROMPT, type OrchestratorFixtureInput } from "../shared.ts";
2 +
3 +/**
4 + * Supervised: fx never forwards a sub-agent's permission request over ACP,
5 + * so the sub-agent waits until Stop.
6 + */
7 +export function fxSubagentStopInput(): OrchestratorFixtureInput {
8 + return {
9 + runtimeMode: "approval-required",
10 + steps: [
11 + { type: "message", text: FX_SUBAGENT_STOP_PROMPT },
12 + { type: "interrupt", targetRunIndex: 1, waitForTurnItemType: "subagent" },
13 + ],
14 + };
15 +}
apps/server/src/orchestration-v2/testkit/fixtures/index.ts
+26
@@ -227,9 +227,12 @@ import { fxEarlyStopInput } from "./fx_early_stop/input.ts";
227 import { assertFxEarlyStopOutput } from "./fx_early_stop/fx_output.ts";
228 import { fxSubagentInput } from "./fx_subagent/input.ts";
229 import { assertFxSubagentOutput } from "./fx_subagent/fx_output.ts";
230 +import { fxSubagentStopInput } from "./fx_subagent_stop/input.ts";
231 +import { assertFxSubagentStopOutput } from "./fx_subagent_stop/fx_output.ts";
232 import { assertTurnInterruptMidToolClaudeOutput } from "./turn_interrupt_mid_tool/claude_output.ts";
233 import { assertTurnInterruptMidToolCodexOutput } from "./turn_interrupt_mid_tool/codex_output.ts";
234 import { assertTurnInterruptMidToolCursorOutput } from "./turn_interrupt_mid_tool/cursor_output.ts";
235 +import { assertTurnInterruptMidToolFxOutput } from "./turn_interrupt_mid_tool/fx_output.ts";
236 import {
237 turnInterruptMidToolInput,
238 turnInterruptMidToolKiroInput,
@@ -1903,6 +1906,18 @@ export const ORCHESTRATOR_REPLAY_FIXTURES: ReadonlyArray<OrchestratorReplayFixtu
1906 },
1907 ],
1908 },
1909 + {
1910 + name: "fx_subagent_stop",
1911 + buildInput: fxSubagentStopInput,
1912 + providers: [
1913 + {
1914 + driver: ProviderDriverKind.make("fx"),
1915 + transcriptFile: new URL("./fx_subagent_stop/fx_transcript.ndjson", import.meta.url),
1916 + modelSelection: FX_MODEL_SELECTION,
1917 + assertOutput: assertFxSubagentStopOutput,
1918 + },
1919 + ],
1920 + },
1921 {
1922 name: "command_output_streaming",
1923 buildInput: commandOutputStreamingInput,
@@ -1962,6 +1977,17 @@ export const ORCHESTRATOR_REPLAY_FIXTURES: ReadonlyArray<OrchestratorReplayFixtu
1977 runtimePolicyOverride: WORKSPACE_NEVER_POLICY,
1978 assertOutput: assertTurnInterruptMidToolCursorOutput,
1979 },
1980 + {
1981 + driver: ProviderDriverKind.make("fx"),
1982 + transcriptFile: new URL("./turn_interrupt_mid_tool/fx_transcript.ndjson", import.meta.url),
1983 + modelSelection: FX_MODEL_SELECTION,
1984 + // fx asks before running the command; a workspace sandbox would deny it.
1985 + runtimePolicyOverride: {
1986 + approvalPolicy: "never",
1987 + sandboxPolicy: { type: "dangerFullAccess" },
1988 + },
1989 + assertOutput: assertTurnInterruptMidToolFxOutput,
1990 + },
1991 {
1992 driver: ProviderDriverKind.make("pi"),
1993 transcriptFile: new URL("./turn_interrupt_mid_tool/pi_transcript.ndjson", import.meta.url),
apps/server/src/orchestration-v2/testkit/fixtures/shared.ts
+2
@@ -102,6 +102,8 @@ export const OPENCODE2_COMMAND_PROMPT = "/hello WORLD";
102 export const OPENCODE2_SKILL_PROMPT = "Use $greet to say hi in three words.";
103 export const TURN_INTERRUPT_PROMPT =
104 "Do not answer immediately. First run the local shell command `sleep 30`, then respond with exactly: interrupt fixture should not finish naturally.";
105 +export const FX_SUBAGENT_STOP_PROMPT =
106 + "Use exactly one subagent to create a file named stopped.txt containing STOP. Do not create the file yourself. Wait for the subagent, then reply DONE.";
107 export const TURN_INTERRUPT_MID_TOOL_PROMPT =
108 "Run this exact local command: `node -e \"console.log('interrupt fixture tool started'); setTimeout(() => {}, 30000)\"`. Do not answer until it completes, then respond exactly: interrupt fixture should not finish naturally.";
109 const COMMAND_OUTPUT_STREAMING_COMMAND =
apps/server/src/orchestration-v2/testkit/fixtures/turn_interrupt_mid_tool/fx_output.ts new
+64
@@ -0,0 +1,64 @@
1 +import { assert } from "@effect/vitest";
2 +import type { ProviderReplayTranscript } from "@t3tools/contracts";
3 +
4 +import type { OrchestratorV2ScenarioResult } from "../../OrchestratorScenario.ts";
5 +import {
6 + assertBaseProjection,
7 + assertSemanticProjectionIntegrity,
8 + assertTurnItemTypes,
9 + assertUserMessagesInclude,
10 + assertVisibleTurnItemsMirrorLocalTurnItems,
11 + projectionFor,
12 + TURN_INTERRUPT_MID_TOOL_PROMPT,
13 +} from "../shared.ts";
14 +
15 +function acpFrame(entry: ProviderReplayTranscript["entries"][number]) {
16 + return entry.type === "runtime_exit"
17 + ? undefined
18 + : (entry.frame as {
19 + readonly method?: string;
20 + readonly params?: { readonly update?: { sessionUpdate?: string; status?: string } };
21 + });
22 +}
23 +
24 +/** fx 0.0.15 answers Stop by failing the running command itself; T3 still shows it interrupted. */
25 +export function assertTurnInterruptMidToolFxOutput(
26 + result: OrchestratorV2ScenarioResult,
27 + transcript: ProviderReplayTranscript,
28 +) {
29 + const cancelIndex = transcript.entries.findIndex(
30 + (entry) => entry.type === "expect_outbound" && acpFrame(entry)?.method === "session/cancel",
31 + );
32 + const failedAfterCancel = transcript.entries.findIndex(
33 + (entry, index) =>
34 + index > cancelIndex &&
35 + entry.type === "emit_inbound" &&
36 + acpFrame(entry)?.params?.update?.sessionUpdate === "tool_call_update" &&
37 + acpFrame(entry)?.params?.update?.status === "failed",
38 + );
39 + assert.isAtLeast(cancelIndex, 0);
40 + assert.isAbove(failedAfterCancel, cancelIndex, "fx fails the cut-off command after Stop");
41 + assertBaseProjection({ result, transcript, runCount: 1, runStatuses: ["interrupted"] });
42 +
43 + const projection = projectionFor(result, transcript.scenario);
44 + assertSemanticProjectionIntegrity(projection);
45 + assertVisibleTurnItemsMirrorLocalTurnItems(projection);
46 + assertTurnItemTypes(projection, [
47 + "user_message",
48 + "command_execution",
49 + "run_interrupt_request",
50 + "run_interrupt_result",
51 + ]);
52 + assertUserMessagesInclude(projection, [TURN_INTERRUPT_MID_TOOL_PROMPT]);
53 +
54 + const commandItem = projection.turnItems.find((item) => item.type === "command_execution");
55 + assert.isDefined(commandItem);
56 + assert.include(commandItem.input, "node -e");
57 + assert.equal(commandItem.status, "interrupted");
58 + assert.equal(
59 + projection.turnItems.find((item) => item.type === "run_interrupt_result")?.status,
60 + "interrupted",
61 + );
62 + assert.equal(projection.providerTurns[0]?.status, "interrupted");
63 + assert.equal(projection.providerThreads[0]?.status, "idle");
64 +}
apps/server/src/orchestration-v2/testkit/fixtures/turn_interrupt_mid_tool/fx_transcript.ndjson new
+33
@@ -0,0 +1,33 @@
1 +{"type":"transcript_start","provider":"fx","protocol":"acp.ndjson-jsonrpc","version":"1","scenario":"turn_interrupt_mid_tool","metadata":{"generatedBy":"live-fx-recorder","fxVersion":"0.0.15","normalization":"Session ids are fx-session-NN, the workspace is <workspace>, HOME is /home/fx-replay and the recording user is fx-replay. T3-owned prompt text, MCP servers and initialize params other than clientCapabilities and _meta are <any>. User skill names, emails and token-shaped strings are removed. Timestamps are kept as recorded.","droppedFrames":0}}
2 +{"type":"expect_outbound","label":"request:initialize","frame":{"kind":"request","method":"initialize","params":{"protocolVersion":2,"info":"<any>","capabilities":"<any>","clientCapabilities":{"fs":{"readTextFile":false,"writeTextFile":false},"terminal":false,"session":{"notices":{},"compaction":{}},"elicitation":{"form":{}}},"clientInfo":"<any>"}}}
3 +{"type":"emit_inbound","label":"response:initialize","frame":{"kind":"response","method":"initialize","result":{"protocolVersion":1,"agentCapabilities":{"loadSession":true,"promptCapabilities":{"image":true,"audio":false,"embeddedContext":true},"mcpCapabilities":{"http":true,"sse":false,"acp":false},"sessionCapabilities":{"list":{},"resume":{},"close":{},"systemPrompt":{}},"_meta":{"fx":{"steering":true}}},"agentInfo":{"name":"fx","title":"fx","version":"0.0.15"},"authMethods":[]}}}
4 +{"type":"expect_outbound","label":"request:session/new","frame":{"kind":"request","method":"session/new","params":{"cwd":"<workspace>","_meta":{"fx":{"profileMcpServers":true}},"mcpServers":"<any>"}}}
5 +{"type":"emit_inbound","label":"response:session/new","frame":{"kind":"response","method":"session/new","result":{"sessionId":"fx-session-01","configOptions":[{"id":"provider","name":"Provider","category":"model","type":"select","currentValue":"codex","options":[{"value":"gateway","name":"Vercel AI Gateway"},{"value":"codex","name":"Codex subscription"},{"value":"grok","name":"Grok subscription"}]},{"id":"model","name":"Model","category":"model","type":"select","currentValue":"gpt-6.1-sol","options":[{"value":"gpt-6.1-sol","name":"gpt-6.1-sol"},{"value":"gpt-6-astra","name":"gpt-6-astra"},{"value":"gpt-6.1-terra","name":"gpt-6.1-terra"},{"value":"gpt-6-sol","name":"gpt-6-sol"},{"value":"gpt-6-luna","name":"gpt-6-luna"},{"value":"gpt-5.6-sol","name":"gpt-5.6-sol"},{"value":"gpt-5.6-terra","name":"gpt-5.6-terra"},{"value":"gpt-5.6-luna","name":"gpt-5.6-luna"},{"value":"gpt-daybreak-blue-latest","name":"gpt-daybreak-blue-latest"}]},{"id":"mode","name":"Session Mode","description":"Controls how the agent requests permission","category":"mode","type":"select","currentValue":"auto","options":[{"value":"auto","name":"Auto","description":"Check actions with an automatic safety review instead of asking","_meta":{"fx":{"permissionMode":"auto"}}},{"value":"ask","name":"Ask","description":"Request permission before making any changes","_meta":{"fx":{"permissionMode":"ask"}}},{"value":"full-access","name":"Full access","description":"Run every action without asking, outside the sandbox","_meta":{"fx":{"permissionMode":"yolo"}}}]},{"id":"effort","name":"Reasoning Effort","description":"Controls how much the model thinks before responding","category":"thought_level","type":"select","currentValue":"auto","options":[{"value":"auto","name":"default"},{"value":"low","name":"low"},{"value":"medium","name":"medium"},{"value":"high","name":"high"},{"value":"xhigh","name":"xhigh"},{"value":"max","name":"max"},{"value":"ultra","name":"ultra"}]},{"id":"fast","name":"Fast Mode","description":"Uses the model's fast lane","category":"model","type":"select","currentValue":"false","options":[{"value":"false","name":"off"},{"value":"true","name":"on"}]}],"modes":{"currentModeId":"auto","availableModes":[{"id":"auto","name":"Auto","description":"Check actions with an automatic safety review instead of asking"},{"id":"ask","name":"Ask","description":"Request permission before making any changes"},{"id":"full-access","name":"Full access","description":"Run every action without asking, outside the sandbox"}]}}}}
6 +{"type":"emit_inbound","label":"notification:session/update:available_commands_update","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"fx-session-01","update":{"sessionUpdate":"available_commands_update","availableCommands":[]}}}}
7 +{"type":"expect_outbound","label":"request:session/set_config_option","frame":{"kind":"request","method":"session/set_config_option","params":{"sessionId":"fx-session-01","configId":"effort","value":"medium"}}}
8 +{"type":"emit_inbound","label":"response:session/set_config_option","frame":{"kind":"response","method":"session/set_config_option","result":{"configOptions":[{"id":"provider","name":"Provider","category":"model","type":"select","currentValue":"codex","options":[{"value":"gateway","name":"Vercel AI Gateway"},{"value":"codex","name":"Codex subscription"},{"value":"grok","name":"Grok subscription"}]},{"id":"model","name":"Model","category":"model","type":"select","currentValue":"gpt-6.1-sol","options":[{"value":"gpt-6.1-sol","name":"gpt-6.1-sol"},{"value":"gpt-6-astra","name":"gpt-6-astra"},{"value":"gpt-6.1-terra","name":"gpt-6.1-terra"},{"value":"gpt-6-sol","name":"gpt-6-sol"},{"value":"gpt-6-luna","name":"gpt-6-luna"},{"value":"gpt-5.6-sol","name":"gpt-5.6-sol"},{"value":"gpt-5.6-terra","name":"gpt-5.6-terra"},{"value":"gpt-5.6-luna","name":"gpt-5.6-luna"},{"value":"gpt-daybreak-blue-latest","name":"gpt-daybreak-blue-latest"}]},{"id":"mode","name":"Session Mode","description":"Controls how the agent requests permission","category":"mode","type":"select","currentValue":"auto","options":[{"value":"auto","name":"Auto","description":"Check actions with an automatic safety review instead of asking","_meta":{"fx":{"permissionMode":"auto"}}},{"value":"ask","name":"Ask","description":"Request permission before making any changes","_meta":{"fx":{"permissionMode":"ask"}}},{"value":"full-access","name":"Full access","description":"Run every action without asking, outside the sandbox","_meta":{"fx":{"permissionMode":"yolo"}}}]},{"id":"effort","name":"Reasoning Effort","description":"Controls how much the model thinks before responding","category":"thought_level","type":"select","currentValue":"medium","options":[{"value":"auto","name":"default"},{"value":"low","name":"low"},{"value":"medium","name":"medium"},{"value":"high","name":"high"},{"value":"xhigh","name":"xhigh"},{"value":"max","name":"max"},{"value":"ultra","name":"ultra"}]},{"id":"fast","name":"Fast Mode","description":"Uses the model's fast lane","category":"model","type":"select","currentValue":"false","options":[{"value":"false","name":"off"},{"value":"true","name":"on"}]}]}}}
9 +{"type":"expect_outbound","label":"request:session/set_config_option","frame":{"kind":"request","method":"session/set_config_option","params":{"sessionId":"fx-session-01","configId":"mode","value":"ask"}}}
10 +{"type":"emit_inbound","label":"response:session/set_config_option","frame":{"kind":"response","method":"session/set_config_option","result":{"configOptions":[{"id":"provider","name":"Provider","category":"model","type":"select","currentValue":"codex","options":[{"value":"gateway","name":"Vercel AI Gateway"},{"value":"codex","name":"Codex subscription"},{"value":"grok","name":"Grok subscription"}]},{"id":"model","name":"Model","category":"model","type":"select","currentValue":"gpt-6.1-sol","options":[{"value":"gpt-6.1-sol","name":"gpt-6.1-sol"},{"value":"gpt-6-astra","name":"gpt-6-astra"},{"value":"gpt-6.1-terra","name":"gpt-6.1-terra"},{"value":"gpt-6-sol","name":"gpt-6-sol"},{"value":"gpt-6-luna","name":"gpt-6-luna"},{"value":"gpt-5.6-sol","name":"gpt-5.6-sol"},{"value":"gpt-5.6-terra","name":"gpt-5.6-terra"},{"value":"gpt-5.6-luna","name":"gpt-5.6-luna"},{"value":"gpt-daybreak-blue-latest","name":"gpt-daybreak-blue-latest"}]},{"id":"mode","name":"Session Mode","description":"Controls how the agent requests permission","category":"mode","type":"select","currentValue":"ask","options":[{"value":"auto","name":"Auto","description":"Check actions with an automatic safety review instead of asking","_meta":{"fx":{"permissionMode":"auto"}}},{"value":"ask","name":"Ask","description":"Request permission before making any changes","_meta":{"fx":{"permissionMode":"ask"}}},{"value":"full-access","name":"Full access","description":"Run every action without asking, outside the sandbox","_meta":{"fx":{"permissionMode":"yolo"}}}]},{"id":"effort","name":"Reasoning Effort","description":"Controls how much the model thinks before responding","category":"thought_level","type":"select","currentValue":"medium","options":[{"value":"auto","name":"default"},{"value":"low","name":"low"},{"value":"medium","name":"medium"},{"value":"high","name":"high"},{"value":"xhigh","name":"xhigh"},{"value":"max","name":"max"},{"value":"ultra","name":"ultra"}]},{"id":"fast","name":"Fast Mode","description":"Uses the model's fast lane","category":"model","type":"select","currentValue":"false","options":[{"value":"false","name":"off"},{"value":"true","name":"on"}]}]}}}
11 +{"type":"expect_outbound","label":"request:session/prompt","frame":{"kind":"request","method":"session/prompt","params":{"sessionId":"fx-session-01","prompt":[{"type":"text","text":"<t3_code_instructions>\n<any>\n</t3_code_instructions>\n\n<user_request>\nRun this exact local command: `node -e \"console.log('interrupt fixture tool started'); setTimeout(() => {}, 30000)\"`. Do not answer until it completes, then respond exactly: interrupt fixture should not finish naturally.\n</user_request>"}]}}}
12 +{"type":"emit_inbound","label":"notification:session/update:agent_message_chunk","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"fx-session-01","update":{"sessionUpdate":"agent_message_chunk","messageId":"c6368a3ae8b2d57bec270c4e9afcaa54","content":{"type":"text","text":"I’ll run the"}}}}}
13 +{"type":"emit_inbound","label":"notification:session/update:agent_message_chunk","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"fx-session-01","update":{"sessionUpdate":"agent_message_chunk","messageId":"c6368a3ae8b2d57bec270c4e9afcaa54","content":{"type":"text","text":" exact"}}}}}
14 +{"type":"emit_inbound","label":"notification:session/update:agent_message_chunk","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"fx-session-01","update":{"sessionUpdate":"agent_message_chunk","messageId":"c6368a3ae8b2d57bec270c4e9afcaa54","content":{"type":"text","text":" command"}}}}}
15 +{"type":"emit_inbound","label":"notification:session/update:agent_message_chunk","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"fx-session-01","update":{"sessionUpdate":"agent_message_chunk","messageId":"c6368a3ae8b2d57bec270c4e9afcaa54","content":{"type":"text","text":" and"}}}}}
16 +{"type":"emit_inbound","label":"notification:session/update:agent_message_chunk","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"fx-session-01","update":{"sessionUpdate":"agent_message_chunk","messageId":"c6368a3ae8b2d57bec270c4e9afcaa54","content":{"type":"text","text":" wait"}}}}}
17 +{"type":"emit_inbound","label":"notification:session/update:agent_message_chunk","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"fx-session-01","update":{"sessionUpdate":"agent_message_chunk","messageId":"c6368a3ae8b2d57bec270c4e9afcaa54","content":{"type":"text","text":" for"}}}}}
18 +{"type":"emit_inbound","label":"notification:session/update:agent_message_chunk","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"fx-session-01","update":{"sessionUpdate":"agent_message_chunk","messageId":"c6368a3ae8b2d57bec270c4e9afcaa54","content":{"type":"text","text":" it"}}}}}
19 +{"type":"emit_inbound","label":"notification:session/update:agent_message_chunk","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"fx-session-01","update":{"sessionUpdate":"agent_message_chunk","messageId":"c6368a3ae8b2d57bec270c4e9afcaa54","content":{"type":"text","text":" to"}}}}}
20 +{"type":"emit_inbound","label":"notification:session/update:agent_message_chunk","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"fx-session-01","update":{"sessionUpdate":"agent_message_chunk","messageId":"c6368a3ae8b2d57bec270c4e9afcaa54","content":{"type":"text","text":" complete"}}}}}
21 +{"type":"emit_inbound","label":"notification:session/update:agent_message_chunk","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"fx-session-01","update":{"sessionUpdate":"agent_message_chunk","messageId":"c6368a3ae8b2d57bec270c4e9afcaa54","content":{"type":"text","text":".\n"}}}}}
22 +{"type":"emit_inbound","label":"notification:session/update:tool_call","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"fx-session-01","update":{"sessionUpdate":"tool_call","toolCallId":"call_573669dc43cb4393aeceab4ea77cffbb","name":"shell","title":"Running","kind":"execute","status":"pending","rawInput":{"action":"run","command":"node -e \"console.log('interrupt fixture tool started'); setTimeout(() => {}, 30000)\"","yield_time_ms":1000},"_meta":{"fx":{"toolCall":{"internal":false}}}}}}}
23 +{"type":"emit_inbound","label":"request:session/request_permission","frame":{"kind":"request","method":"session/request_permission","params":{"sessionId":"fx-session-01","toolCall":{"toolCallId":"call_573669dc43cb4393aeceab4ea77cffbb","name":"shell","title":"shell.run node -e \"console.log('interrupt fixture tool started'); setTimeout(() => {}, 30000)\"","kind":"execute","status":"pending","rawInput":{"action":"run","command":"node -e \"console.log('interrupt fixture tool started'); setTimeout(() => {}, 30000)\"","yield_time_ms":1000}},"options":[{"optionId":"allow_once","name":"Allow once","kind":"allow_once"},{"optionId":"allow_always","name":"Allow for this session","kind":"allow_always"},{"optionId":"reject_once","name":"Reject","kind":"reject_once"}]}}}
24 +{"type":"expect_outbound","label":"response:session/request_permission","frame":{"kind":"response","method":"session/request_permission","result":{"outcome":{"outcome":"selected","optionId":"allow_once"}}}}
25 +{"type":"emit_inbound","label":"notification:session/update:tool_call_update","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"fx-session-01","update":{"sessionUpdate":"tool_call_update","toolCallId":"call_573669dc43cb4393aeceab4ea77cffbb","status":"in_progress"}}}}
26 +{"type":"expect_outbound","label":"notification:session/cancel","frame":{"kind":"notification","method":"session/cancel","params":{"sessionId":"fx-session-01"}}}
27 +{"type":"emit_inbound","label":"notification:session/update:tool_call_update","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"fx-session-01","update":{"sessionUpdate":"tool_call_update","toolCallId":"call_573669dc43cb4393aeceab4ea77cffbb","status":"failed","content":[{"type":"content","content":{"type":"text","text":""}}],"command_result":{"kind":"command","command":"node -e \"console.log('interrupt fixture tool started'); setTimeout(() => {}, 30000)\"","cwd":"<workspace>","exit_code":null,"signal":null,"timed_out":false,"termination_indeterminate":true,"duration_ms":null,"stdout_bytes":0,"stderr_bytes":0,"truncated":false,"output_file":null,"stdout_file":null,"stderr_file":null}}}}}
28 +{"type":"emit_inbound","label":"notification:session/update:session_info_update","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"fx-session-01","update":{"sessionUpdate":"session_info_update","title":"Run Interrupt Fixture Tool Locally","updatedAt":"2026-10-29T14:22:39Z"}}}}
29 +{"type":"emit_inbound","label":"notification:session/update:usage_update","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"fx-session-01","update":{"sessionUpdate":"usage_update","used":6405,"size":500000}}}}
30 +{"type":"emit_inbound","label":"response:session/prompt","frame":{"kind":"response","method":"session/prompt","result":{"stopReason":"cancelled","usage":{"inputTokens":6336,"outputTokens":69,"cacheReadTokens":0,"cacheWriteTokens":0,"reasoningTokens":0}}}}
31 +{"type":"expect_outbound","label":"request:session/close","frame":{"kind":"request","method":"session/close","params":{"sessionId":"fx-session-01"}}}
32 +{"type":"emit_inbound","label":"response:session/close","frame":{"kind":"response","method":"session/close","result":{}}}
33 +{"type":"runtime_exit","status":"success"}
docs/user/providers-fx.md
+9 -1
@@ -15,8 +15,16 @@ T3 Code can run [fx](https://fx.sh). fx uses the login on the machine that runs
15
16 If `fx` is not on the server's `PATH`, set **Binary path** to the executable.
17
18 +T3 Code supports fx 0.0.13 and later. Use the latest release when you can; macOS needs version 15 or later for fx releases after 0.0.13.
19 +
20 Every fx instance on the same machine shares that machine's fx login. T3 Code does not keep a separate login per instance.
21
22 +## Update fx
23 +
24 +When a newer fx release is out, the fx card in **Settings → Providers** shows it. For standalone installs, **Update now** runs the instance's selected executable with `upgrade`, including one set in **Binary path**. For Homebrew's `fx-agent` formula, it uses the owning Homebrew installation to run `brew upgrade fx-agent` and checks Homebrew's release version. If that ownership cannot be confirmed, update through your package manager yourself. For mise-managed installs, T3 Code checks stable releases but leaves updates to your mise configuration. MacPorts and Nix installs are also left to their package manager.
25 +
26 +To update a standalone install manually, run `fx upgrade` on the server's machine. If **Binary path** is set, run that exact executable instead, for example `"/path/to/fx" upgrade`. Standalone version checks cover stable releases only; use the same manual command to get newer dev builds on fx's dev channel. On macOS 14 or earlier, which newer fx releases do not support, T3 Code does not offer fx updates.
27 +
28 ## Models and effort
29
30 The model picker lists **Default** first. That option runs the model `fx status` reports on the server's machine. A model set only for one project in fx's settings is not picked up, so choose it from the list instead. If the thread's fx backend does not offer that model, the thread keeps its current one. The other entries come from `fx models`. A custom model you add in the provider settings goes to fx as is, and fx reports an error if its backend does not offer it.
@@ -40,7 +48,7 @@ fx offers two composer modes.
48
49 T3 Code does not offer **Full access** or **Auto-accept edits** for fx. A thread already set to one of those runs in **Supervised**. Changing the permission mode restarts the connection and reloads the same fx session.
50
43 -On fx versions after [vercel-labs/fx#1189](https://github.com/vercel-labs/fx/pull/1189), fx saves the mode T3 Code sets as its default permission mode. T3 Code sets it each time it opens an fx thread, so fx in the terminal then starts in that thread's mode.
51 +On fx 0.0.14 and later, fx saves the mode T3 Code sets as its default permission mode. T3 Code sets it each time it opens an fx thread, so fx in the terminal then starts in that thread's mode.
52
53 A message steered into a running turn stops that turn, and fx answers the new message in the same session.
54
packages/effect-acp/src/protocol.test.ts
+33 -3
@@ -102,7 +102,7 @@ it.layer(NodeServices.layer)("effect-acp protocol", (it) => {
102 const notifications =
103 yield* Deferred.make<ReadonlyArray<AcpProtocol.AcpIncomingNotification>>();
104 yield* transport.incoming.pipe(
105 - Stream.take(2),
105 + Stream.take(3),
106 Stream.runCollect,
107 Effect.flatMap((notificationChunk) => Deferred.succeed(notifications, notificationChunk)),
108 Effect.forkScoped,
@@ -143,8 +143,29 @@ it.layer(NodeServices.layer)("effect-acp protocol", (it) => {
143 },
144 });
145
146 + const commandResult = {
147 + exit_code: null,
148 + signal: null,
149 + timed_out: false,
150 + termination_indeterminate: true,
151 + };
152 + const cancelledToolFrame = encoder.encode(
153 + `${encodeUnknownJsonString({
154 + jsonrpc: "2.0",
155 + method: "session/update",
156 + params: {
157 + sessionId: "session-1",
158 + update: {
159 + sessionUpdate: "tool_call_update",
160 + toolCallId: "cancelled-tool",
161 + status: "failed",
162 + command_result: commandResult,
163 + },
164 + },
165 + })}\n`,
166 + );
167 // Frames split across reads, with one read ending one frame and starting the next.
147 - const wire = new Uint8Array([...updateFrame, ...completionFrame]);
168 + const wire = new Uint8Array([...updateFrame, ...completionFrame, ...cancelledToolFrame]);
169 const splits = [10, updateFrame.length + 10, wire.length];
170 let start = 0;
171 for (const end of splits) {
@@ -152,9 +173,18 @@ it.layer(NodeServices.layer)("effect-acp protocol", (it) => {
173 start = end;
174 }
175
155 - const [update, completion] = yield* Deferred.await(notifications);
176 + const [update, completion, cancelledTool] = yield* Deferred.await(notifications);
177 assert.equal(update?._tag, "SessionUpdate");
178 assert.equal(completion?._tag, "ElicitationComplete");
179 + assert.deepEqual(cancelledTool?.params, {
180 + sessionId: "session-1",
181 + update: {
182 + sessionUpdate: "tool_call_update",
183 + toolCallId: "cancelled-tool",
184 + status: "failed",
185 + command_result: commandResult,
186 + },
187 + });
188 }),
189 );
190
packages/effect-acp/src/protocol.ts
+9
@@ -174,6 +174,15 @@ const decodeSessionUpdate = Schema.decodeUnknownEffect(
174 _meta: AcpSchema.UpdateSessionNotification.fields._meta,
175 }),
176 }),
177 + // fx reports command cancellation outside ACP's standard tool fields.
178 + Schema.Struct({
179 + ...AcpSchemaV1.SessionNotification.fields,
180 + update: Schema.Struct({
181 + ...AcpSchemaV1.ToolCallUpdate.fields,
182 + sessionUpdate: Schema.Literals(["tool_call", "tool_call_update"]),
183 + command_result: Schema.Json,
184 + }),
185 + }),
186 AcpSchema.UpdateSessionNotification,
187 AcpSchemaV1.SessionNotification,
188 ]),
packages/provider-acp/src/server/adapter.ts
+41 -6
@@ -560,6 +560,7 @@ export interface AcpAdapterV2Flavor {
560 ) => AcpAdapterV2SubagentUpdate | undefined;
561 readonly isProvisionalSubagentTool?: (toolCall: AcpToolCallState) => boolean;
562 readonly normalizeToolCall?: (toolCall: AcpToolCallState) => AcpToolCallState;
563 + readonly isCancelledToolCall?: (payload: unknown) => boolean;
564 readonly extractProposedPlanMarkdown?: (toolCall: AcpToolCallState) => string | undefined;
565 readonly extractBackgroundTaskId?: (toolCall: AcpToolCallState) => string | undefined;
566 /** Distinguishes commands from monitors when lifecycle notifications omit their kind. */
@@ -1487,6 +1488,8 @@ interface ActiveAcpTurn {
1488 contextUsage: ThreadTokenUsageSnapshot | null;
1489 nativeMetadata: OrchestrationV2ProviderThreadNativeMetadata | null;
1490 readonly tools: Map<string, AcpToolCallState & { readonly backgroundCommandTaskId?: string }>;
1491 + /** Tools the agent failed after Stop; later updates keep them interrupted. */
1492 + readonly stoppedToolCallIds: Set<string>;
1493 readonly toolUpdatesSkipped: Map<string, number>;
1494 readonly toolStartedAt: Map<string, DateTime.Utc>;
1495 readonly subagents: Map<string, ActiveAcpSubagent>;
@@ -3381,9 +3384,11 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
3384 context: ActiveAcpTurn,
3385 reported: AcpAdapterV2SubagentUpdate,
3386 ) {
3384 - // See stoppedToolStatus: after Stop, a failed subagent was interrupted.
3387 + // Providers with cancellation detection already classify their subagent failures.
3388 const update: AcpAdapterV2SubagentUpdate =
3386 - context.interrupted && reported.status === "failed"
3389 + flavor.isCancelledToolCall === undefined &&
3390 + context.interrupted &&
3391 + reported.status === "failed"
3392 ? { ...reported, status: "interrupted" }
3393 : reported;
3394 // Hydration uses a new toolCallId but references the original child by subagent_id or task id.
@@ -4059,6 +4064,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
4064 context: ActiveAcpTurn,
4065 incoming: AcpToolCallState,
4066 projectedStatus?: ProjectedToolStatus,
4067 + rawPayload?: unknown,
4068 ) => Effect.Effect<void> = () => Effect.void;
4069
4070 const markAwaitingBackgroundHydration =
@@ -4111,6 +4117,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
4117 context: ActiveAcpTurn,
4118 incoming: AcpToolCallState,
4119 projectedStatus?: ProjectedToolStatus,
4120 + rawPayload?: unknown,
4121 ) {
4122 if (context.assistant.current?.sourceMessageId == null)
4123 yield* closeTextStream(context, "assistant");
@@ -4151,6 +4158,24 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
4158 ? toolCall
4159 : { ...toolCall, backgroundCommandTaskId },
4160 );
4161 + // A failure racing Stop needs the provider's cancellation signal before relabeling it.
4162 + const previousStatus = previous === undefined ? undefined : toolStatus(previous.status);
4163 + if (
4164 + context.interrupted &&
4165 + toolCall.status === "failed" &&
4166 + flavor.isCancelledToolCall?.(rawPayload) === true &&
4167 + (previousStatus === undefined ||
4168 + previousStatus === "pending" ||
4169 + previousStatus === "running" ||
4170 + previousStatus === "waiting")
4171 + ) {
4172 + context.stoppedToolCallIds.add(toolCall.toolCallId);
4173 + }
4174 + const stoppedStatus =
4175 + projectedStatus ??
4176 + (toolCall.status === "failed" && context.stoppedToolCallIds.has(toolCall.toolCallId)
4177 + ? "interrupted"
4178 + : undefined);
4179 if (
4180 followsAgentWorkState &&
4181 projectedStatus === undefined &&
@@ -4258,7 +4283,12 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
4283 ? undefined
4284 : extractSubagentUpdate(toolCall);
4285 if (subagentUpdate !== undefined) {
4261 - yield* emitSubagent(context, subagentUpdate);
4286 + yield* emitSubagent(
4287 + context,
4288 + stoppedStatus === "interrupted" && subagentUpdate.status === "failed"
4289 + ? { ...subagentUpdate, status: "interrupted" }
4290 + : subagentUpdate,
4291 + );
4292 if (followsAgentWorkState) yield* syncNativeChildren(context);
4293 if (subagentUpdate.suppressNormalTool !== false) {
4294 yield* rearmDeferredFinalize(context);
@@ -4266,7 +4296,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
4296 }
4297 }
4298 if (
4269 - projectedStatus === undefined &&
4299 + stoppedStatus === undefined &&
4300 !shouldPersistToolUpdate(
4301 context,
4302 toolCall.toolCallId,
@@ -4279,7 +4309,11 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
4309 return;
4310 }
4311 const status =
4282 - projectedStatus ?? stoppedToolStatus(context, toolCall) ?? toolStatus(toolCall.status);
4312 + stoppedStatus ??
4313 + (flavor.isCancelledToolCall === undefined
4314 + ? stoppedToolStatus(context, toolCall)
4315 + : undefined) ??
4316 + toolStatus(toolCall.status);
4317 const now = yield* DateTime.now;
4318 const nativeItemId = `${context.nativeThreadId}:tool:${toolCall.toolCallId}`;
4319 const ordinal = yield* resolveItemOrdinal(context, nativeItemId);
@@ -5905,7 +5939,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
5939 const parsed = parseSessionUpdateEvent(notification);
5940 for (const event of parsed.events) {
5941 if (event._tag === "ToolCallUpdated") {
5908 - yield* emitTool(context, event.toolCall);
5942 + yield* emitTool(context, event.toolCall, undefined, event.rawPayload);
5943 } else if (event._tag === "PlanUpdated") {
5944 yield* emitPlan(context, event.payload, update.sessionUpdate !== "plan");
5945 } else if (event._tag === "NoticeReceived") {
@@ -8689,6 +8723,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
8723 contextUsage: rememberedContextUsage ?? turnInput.providerThread.contextUsage ?? null,
8724 nativeMetadata: initialNativeMetadata,
8725 tools: new Map(),
8726 + stoppedToolCallIds: new Set(),
8727 toolUpdatesSkipped: new Map(),
8728 toolStartedAt: new Map(),
8729 subagents: new Map(),
packages/provider-core/src/server/maintenanceResolver.test.ts
+17 -5
@@ -1616,7 +1616,11 @@ it.layer(
1616 nativePackageToolUpdate,
1617 {
1618 binaryPath: "native-package-tool",
1619 - env: { PATH: nativeBinDir },
1619 + env: {
1620 + PATH: nativeBinDir,
1621 + MISE_SHIMS_DIR: nativeBinDir,
1622 + MISE_SYSTEM_SHIMS_DIR: nativeBinDir,
1623 + },
1624 },
1625 ).pipe(
1626 Effect.provideService(HostProcess.Platform, "darwin"),
@@ -1636,10 +1640,10 @@ it.layer(
1640 }),
1641 );
1642
1639 - it.effect.each(["wrapper", "symlink"])(
1643 + it.effect.each(["wrapper", "symlink", "custom-data"])(
1644 "keeps a mise-owned %s in a native install location manual-only",
1645 (launcher, { skip }) => {
1642 - if (windowsHost || (launcher === "symlink" && !symlinksSupported)) skip();
1646 + if (windowsHost || (launcher !== "wrapper" && !symlinksSupported)) skip();
1647 return Effect.gen(function* () {
1648 const tempDir = yield* makeTempDir("t3-native-mise");
1649 const nativePath = NodePath.join(tempDir, ".local", "bin", "native-package-tool");
@@ -1652,7 +1656,7 @@ it.layer(
1656 } else {
1657 const target = NodePath.join(
1658 tempDir,
1655 - "mise",
1659 + launcher === "custom-data" ? "managed-tools" : "mise",
1660 "installs",
1661 "native-package-tool",
1662 "1.0.0",
@@ -1665,7 +1669,15 @@ it.layer(
1669
1670 const capabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(
1671 nativePackageToolUpdate,
1668 - { binaryPath: nativePath, env: { PATH: "" } },
1672 + {
1673 + binaryPath: nativePath,
1674 + env: {
1675 + PATH: "",
1676 + ...(launcher === "custom-data"
1677 + ? { MISE_DATA_DIR: NodePath.join(tempDir, "managed-tools") }
1678 + : {}),
1679 + },
1680 + },
1681 ).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn));
1682
1683 expect(capabilities.update).toBeNull();
packages/provider-core/src/server/maintenanceResolver.ts
+26 -4
@@ -255,12 +255,32 @@ function isYarnGlobalCommandPath(commandPath: string): boolean {
255 * Paths mise owns. npm globals under mise's own Node belong to npm, which proves their prefix.
256 * A command wrapper is a symlink to the `mise` binary, which dispatches on argv[0].
257 */
258 -function isMiseCommandPath(commandPath: string): boolean {
258 +function isMiseCommandPath(commandPath: string, env: NodeJS.ProcessEnv): boolean {
259 const normalized = normalizeCommandPath(commandPath);
260 + const dir = (root: string | undefined, ...segments: ReadonlyArray<string>) =>
261 + root ? [normalizeCommandPath(root).replace(/\/+$/, ""), ...segments].join("/") : undefined;
262 + // `MISE_DATA_DIR` and friends move mise's layout off its usual `/mise/` paths.
263 + const installRoots = [
264 + dir(env.MISE_DATA_DIR, "installs"),
265 + dir(env.MISE_DATA_DIR, "i"),
266 + dir(env.MISE_SYSTEM_DATA_DIR, "installs"),
267 + dir(env.MISE_INSTALLS_DIR),
268 + dir(env.MISE_INSTALL_STORE_DIR),
269 + dir(env.MISE_SYSTEM_INSTALLS_DIR),
270 + ];
271 + const otherRoots = [
272 + dir(env.MISE_DATA_DIR, "shims"),
273 + dir(env.MISE_DATA_DIR, "command-wrappers"),
274 + dir(env.MISE_SYSTEM_DATA_DIR, "shims"),
275 + ];
276 + const under = (root: string | undefined) =>
277 + root !== undefined && normalized.startsWith(`${root}/`);
278 return (
279 (normalized.includes("/mise/installs/") && !normalized.includes("/mise/installs/node/")) ||
280 normalized.includes("/mise/shims/") ||
263 - normalized.includes("/mise/command-wrappers/")
281 + normalized.includes("/mise/command-wrappers/") ||
282 + installRoots.some((root) => under(root) && !under(dir(root, "node"))) ||
283 + otherRoots.some(under)
284 );
285 }
286
@@ -626,7 +646,9 @@ export const resolveMiseProviderMaintenance = Effect.fn("resolveMiseProviderMain
646 const commandPaths = [context.resolvedCommandPath, context.realCommandPath];
647 const isShim = isMiseExecutablePath(context.realCommandPath);
648 const looksMise =
629 - isShim || commandPaths.some(isMiseCommandPath) || (yield* isMiseWrapperScript(context));
649 + isShim ||
650 + commandPaths.some((commandPath) => isMiseCommandPath(commandPath, context.env)) ||
651 + (yield* isMiseWrapperScript(context));
652 const manual = (installPath: string) =>
653 makeManualOnlyProviderMaintenanceCapabilities({ ...owner, installPath });
654 const notOwned = (installPath: string) => (looksMise ? manual(installPath) : null);
@@ -1090,7 +1112,7 @@ const isMiseWrapperScript = Effect.fn("isMiseWrapperScript")(function* (
1112 * or null when it does not. MacPorts prefixes are root-owned and its Claude port disables
1113 * `claude update`, so neither npm nor the native updater can upgrade these installs.
1114 */
1093 -const resolveMacPortsOwner = Effect.fn("resolveMacPortsOwner")(function* (
1115 +export const resolveMacPortsOwner = Effect.fn("resolveMacPortsOwner")(function* (
1116 context: ProviderMaintenanceResolutionContext,
1117 ) {
1118 if (context.platform === "win32") return null;
packages/provider-fx/src/server/acpSupport.test.ts
+134 -1
@@ -3,7 +3,7 @@ import type * as EffectAcpSchema from "effect-acp/compat";
3
4 import { ProviderAdapterV2RuntimePolicy } from "@t3tools/provider-core/server/ProviderAdapter";
5
6 -import { fxPermissionDisposition } from "./acpSupport.ts";
6 +import { fxPermissionDisposition, fxToolCallWasCancelled } from "./acpSupport.ts";
7
8 const editRequest = {
9 sessionId: "fx-session-01",
@@ -31,3 +31,136 @@ describe("fx permission prompts", () => {
31 );
32 });
33 });
34 +
35 +describe("fx cancellation failures", () => {
36 + const diff = { type: "diff", path: "notes.txt", oldText: "old", newText: "new" };
37 + const terminal = { type: "terminal", terminalId: "fx-terminal" };
38 +
39 + it.each([
40 + { content: ["Cancelled"], cancelled: true },
41 + { content: ["Cancelled."], cancelled: true },
42 + { content: ['{"error":{"details":{"error":"Cancelled"}}}'], cancelled: true },
43 + {
44 + content: ['{"error":{"tool":"shell","code":"Cancelled","retryable":false}}'],
45 + cancelled: true,
46 + },
47 + {
48 + content: ['{"error":{"tool":"shell","code":"PermissionDenied","retryable":false}}'],
49 + cancelled: false,
50 + },
51 + { content: ['{"error":{"details":{"error":"Permission denied"}}}'], cancelled: false },
52 + { content: ["Command failed"], cancelled: false },
53 + { content: [""], cancelled: false },
54 + { content: ["Cancelled"], followingItems: [diff], cancelled: true },
55 + { content: ["Cancelled"], precedingItems: [diff], cancelled: false },
56 + {
57 + content: ['{"error":{"details":{"error":"Permission denied"}}}', "Cancelled"],
58 + cancelled: false,
59 + },
60 + {
61 + content: ["Command failed", '{"error":{"details":{"error":"Cancelled"}}}'],
62 + cancelled: false,
63 + },
64 + {
65 + content: ["Cancelled", '{"error":{"details":{"error":"Permission denied"}}}'],
66 + cancelled: true,
67 + },
68 + ])(
69 + "recognizes $content as cancellation: $cancelled",
70 + ({ content, cancelled, precedingItems = [], followingItems = [] }) => {
71 + assert.equal(
72 + fxToolCallWasCancelled({
73 + update: {
74 + content: [
75 + ...precedingItems,
76 + ...content.map((text) => ({ content: { text } })),
77 + ...followingItems,
78 + ],
79 + },
80 + }),
81 + cancelled,
82 + );
83 + },
84 + );
85 +
86 + it.each([
87 + {
88 + exit_code: null,
89 + signal: null,
90 + timed_out: false,
91 + termination_indeterminate: true,
92 + content: "",
93 + cancelled: true,
94 + },
95 + {
96 + exit_code: null,
97 + signal: null,
98 + timed_out: false,
99 + termination_indeterminate: true,
100 + content:
101 + '{"error":{"type":"tool_execution_failed","message":"Command started, but its final process status could not be confirmed",',
102 + followingContent: ["Cancelled"],
103 + cancelled: false,
104 + },
105 + {
106 + exit_code: null,
107 + signal: null,
108 + timed_out: false,
109 + termination_indeterminate: true,
110 + content: '{"error":{"message":"Permission denied","details":{"error":"Permission denied"}}}',
111 + followingItems: [terminal],
112 + cancelled: false,
113 + },
114 + {
115 + exit_code: null,
116 + signal: null,
117 + timed_out: false,
118 + termination_indeterminate: true,
119 + content: '{"error":{"type":"tool_execution_failed","message":"clipped",',
120 + followingItems: [diff],
121 + cancelled: false,
122 + },
123 + {
124 + exit_code: null,
125 + signal: null,
126 + timed_out: false,
127 + termination_indeterminate: true,
128 + content: "Still processing",
129 + followingContent: ['{"error":{"message":"Permission denied"}}'],
130 + followingItems: [diff],
131 + cancelled: false,
132 + },
133 + {
134 + exit_code: 1,
135 + signal: null,
136 + timed_out: false,
137 + termination_indeterminate: false,
138 + content: "",
139 + cancelled: false,
140 + },
141 + {
142 + exit_code: null,
143 + signal: null,
144 + timed_out: true,
145 + termination_indeterminate: true,
146 + content: "",
147 + cancelled: false,
148 + },
149 + ])(
150 + "recognizes a command result with exit $exit_code, timeout $timed_out",
151 + ({ cancelled, content, followingContent = [], followingItems = [], ...commandResult }) => {
152 + assert.equal(
153 + fxToolCallWasCancelled({
154 + update: {
155 + command_result: commandResult,
156 + content: [
157 + ...[content, ...followingContent].map((text) => ({ content: { text } })),
158 + ...followingItems,
159 + ],
160 + },
161 + }),
162 + cancelled,
163 + );
164 + },
165 + );
166 +});
packages/provider-fx/src/server/acpSupport.ts
+54
@@ -10,6 +10,8 @@ import { getModelSelectionStringOptionValue } from "@t3tools/shared/model";
10 import type * as SecureRandom from "effect/crypto/SecureRandom";
11 import * as Effect from "effect/Effect";
12 import * as Layer from "effect/Layer";
13 +import * as Option from "effect/Option";
14 +import * as Schema from "effect/Schema";
15 import type * as Scope from "effect/Scope";
16 import type * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
17 import * as EffectAcpErrors from "effect-acp/errors";
@@ -59,6 +61,58 @@ export const FX_ACP_CANCEL_BEHAVIOR = "wait-for-prompt" as const;
61 /** fx inherits the user's `~/.fx/mcp.json` servers only when session setup asks for them. */
62 export const FX_SESSION_META = { fx: { profileMcpServers: true } };
63
64 +const isCancelledFxCommand = Schema.is(
65 + Schema.Struct({
66 + update: Schema.Struct({
67 + command_result: Schema.Struct({
68 + exit_code: Schema.Null,
69 + signal: Schema.Null,
70 + timed_out: Schema.Literal(false),
71 + termination_indeterminate: Schema.Literal(true),
72 + }),
73 + }),
74 + }),
75 +);
76 +const decodeFxToolUpdate = Schema.decodeUnknownOption(
77 + Schema.Struct({
78 + update: Schema.Struct({ content: Schema.Array(Schema.Unknown) }),
79 + }),
80 +);
81 +const decodeFxContentText = Schema.decodeUnknownOption(
82 + Schema.Struct({ content: Schema.Struct({ text: Schema.String }) }),
83 +);
84 +const decodeFxCancelledError = Schema.decodeUnknownOption(
85 + Schema.fromJsonString(
86 + Schema.Struct({
87 + error: Schema.Union([
88 + Schema.Struct({ details: Schema.Struct({ error: Schema.Literal("Cancelled") }) }),
89 + Schema.Struct({ code: Schema.Literal("Cancelled") }),
90 + ]),
91 + }),
92 + ),
93 +);
94 +
95 +export function fxToolCallWasCancelled(payload: unknown): boolean {
96 + const update = decodeFxToolUpdate(payload);
97 + const texts = Option.isSome(update)
98 + ? update.value.update.content.map(
99 + (item) => Option.getOrUndefined(decodeFxContentText(item))?.content.text,
100 + )
101 + : [];
102 + const firstText = texts[0];
103 + if (
104 + firstText !== undefined &&
105 + (/^Cancelled\.?$/.test(firstText) || Option.isSome(decodeFxCancelledError(firstText)))
106 + ) {
107 + return true;
108 + }
109 + // fx also uses indeterminate status for real failures, whose error JSON can be clipped.
110 + return (
111 + isCancelledFxCommand(payload) &&
112 + texts.every((text) => text === undefined || !/^\s*\{\s*"error"\s*:/.test(text))
113 + );
114 +}
115 +
116 /**
117 * Supervised runs fx's `ask` mode and Auto its automatic review. An explicit
118 * approval or sandbox policy must not launch automatic review, which would
packages/provider-fx/src/server/adapter.ts
+26 -1
@@ -22,6 +22,7 @@ import {
22 FX_SESSION_META,
23 fxPermissionDisposition,
24 FX_MODE_CONFIG_ID,
25 + fxToolCallWasCancelled,
26 fxSessionModeForPolicy,
27 makeFxAcpRuntime,
28 withFxSessionMode,
@@ -99,6 +100,17 @@ const decodeFxSubagentResult = Schema.decodeUnknownOption(
100 ),
101 );
102 const decodeJsonString = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.String));
103 +const decodeFxToolError = Schema.decodeUnknownOption(
104 + Schema.fromJsonString(
105 + Schema.Struct({
106 + error: Schema.Struct({
107 + message: Schema.optional(Schema.String),
108 + code: Schema.optional(Schema.String),
109 + details: Schema.optional(Schema.Struct({ error: Schema.optional(Schema.String) })),
110 + }),
111 + }),
112 + ),
113 +);
114
115 /**
116 * fx clips every tool result to 199 bytes, so a long sub-agent reply arrives
@@ -130,6 +142,10 @@ function extractFxSubagentUpdate(tool: AcpToolCallState): AcpAdapterV2SubagentUp
142 const request = "request" in input.value ? input.value.request : input.value;
143 const text = Option.getOrUndefined(decodeFxToolContent(tool.data.content))?.[0]?.content.text;
144 const outcome = text === undefined ? undefined : fxSubagentOutcome(text);
145 + // A failed call carries fx's error envelope, e.g. `Cancelled` after Stop.
146 + const failure = Option.getOrUndefined(
147 + text === undefined ? Option.none() : decodeFxToolError(text),
148 + )?.error;
149 const status =
150 tool.status === "completed"
151 ? outcome?.ok === false
@@ -145,7 +161,15 @@ function extractFxSubagentUpdate(tool: AcpToolCallState): AcpAdapterV2SubagentUp
161 title: request.action === "message" ? request.agent : null,
162 model: request.model ?? null,
163 status,
148 - result: status === "running" ? null : (outcome?.result ?? text ?? null),
164 + result:
165 + status === "running"
166 + ? null
167 + : (outcome?.result ??
168 + failure?.details?.error ??
169 + failure?.message ??
170 + failure?.code ??
171 + text ??
172 + null),
173 };
174 }
175
@@ -195,6 +219,7 @@ function makeFxAcpAdapterFlavor(options: FxAdapterV2Options): AcpAdapterV2Flavor
219 sessionModeForPolicy: fxSessionModeForPolicy,
220 permissionDisposition: fxPermissionDisposition,
221 extractSubagentUpdate: extractFxSubagentUpdate,
222 + isCancelledToolCall: fxToolCallWasCancelled,
223 ...(options.assertComplete === undefined ? {} : { assertComplete: options.assertComplete }),
224 };
225 }
packages/provider-fx/src/server/driver.test.ts
+9
@@ -5,9 +5,11 @@ import { ProviderInstanceId } from "@t3tools/contracts";
5 import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
6 import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
7 import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers";
8 +import * as ProviderLatestVersions from "@t3tools/provider-core/server/ProviderLatestVersions";
9 import * as TestProviderHost from "@t3tools/provider-testing/TestProviderHost";
10 import * as HostProcess from "@t3tools/shared/HostProcess";
11 import * as Effect from "effect/Effect";
12 +import * as HttpClient from "effect/http/HttpClient";
13 import * as Layer from "effect/Layer";
14 import * as Path from "effect/Path";
15 import * as Schema from "effect/Schema";
@@ -25,12 +27,19 @@ const layerTest = TestProviderHost.layer({ runBackgroundWork: false }).pipe(
27 Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
28 Layer.provideMerge(IdAllocator.layer),
29 Layer.provideMerge(McpProviderSessions.layer),
30 + Layer.provideMerge(ProviderLatestVersions.layer),
31 Layer.provideMerge(
32 Layer.succeed(
33 ProviderEventLoggers.ProviderEventLoggers,
34 ProviderEventLoggers.NoOpProviderEventLoggers,
35 ),
36 ),
37 + Layer.provideMerge(
38 + Layer.succeed(
39 + HttpClient.HttpClient,
40 + HttpClient.make(() => Effect.die("Unexpected HTTP request")),
41 + ),
42 + ),
43 );
44
45 /** Records each spawned command and answers only `--version`. */
packages/provider-fx/src/server/driver.ts
+37 -9
@@ -6,9 +6,11 @@ import * as Effect from "effect/Effect";
6 import * as FileSystem from "effect/FileSystem";
7 import * as Path from "effect/Path";
8 import * as Schema from "effect/Schema";
9 +import * as HttpClient from "effect/http/HttpClient";
10 import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
11
12 import type * as ProviderHost from "@t3tools/provider-core/server/ProviderHost";
13 +import * as ProviderLatestVersions from "@t3tools/provider-core/server/ProviderLatestVersions";
14 import { type FxAdapterV2DriverEnv, makeFxAdapterV2Driver } from "./adapter.ts";
15 import { ProviderDriverError } from "@t3tools/provider-core/server/errors";
16 import {
@@ -26,7 +28,12 @@ import { withInstanceIdentity } from "@t3tools/provider-core/server/instanceIden
28 import { mergeProviderInstanceEnvironment } from "@t3tools/provider-core/server/instanceEnvironment";
29 import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion";
30 import { discoverFxSkills } from "./skills.ts";
29 -import { makeManualOnlyProviderMaintenanceCapabilities } from "@t3tools/provider-core/server/maintenanceResolver";
31 +import {
32 + enrichProviderSnapshotWithVersionAdvisory,
33 + makeCachedProviderMaintenanceResolution,
34 + resolveProviderMaintenanceCapabilitiesEffect,
35 +} from "@t3tools/provider-core/server/maintenanceResolver";
36 +import { fetchLatestFxVersion, makeFxMaintenance } from "./maintenance.ts";
37 import {
38 haveProviderSnapshotSettingsChanged,
39 makeProviderSnapshotSettingsSource,
@@ -36,12 +43,6 @@ import type { ProviderTextGeneration } from "@t3tools/provider-core/server/textG
43 import { FX_DRIVER_KIND } from "./acpSupport.ts";
44
45 const decodeFxSettings = Schema.decodeSync(FxSettings);
39 -// fx installs from its own setup script and updates with `fx upgrade`; there
40 -// is no npm package to read a latest version from.
41 -const MAINTENANCE = makeManualOnlyProviderMaintenanceCapabilities({
42 - provider: FX_DRIVER_KIND,
43 - packageName: null,
44 -});
46
47 // See `supportsTextGeneration` in status.ts.
48 const unsupportedTextGeneration: ProviderTextGeneration = (() => {
@@ -67,8 +68,10 @@ export type FxDriverEnv =
68 | ChildProcessSpawner.ChildProcessSpawner
69 | SecureRandom.SecureRandom
70 | FileSystem.FileSystem
71 + | HttpClient.HttpClient
72 | Path.Path
71 - | ProviderHost.ProviderHost;
73 + | ProviderHost.ProviderHost
74 + | ProviderLatestVersions.ProviderLatestVersions;
75
76 export const FxDriver: ProviderDriver<FxSettings, FxDriverEnv> = {
77 driverKind: FX_DRIVER_KIND,
@@ -89,6 +92,8 @@ export const FxDriver: ProviderDriver<FxSettings, FxDriverEnv> = {
92 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
93 const fileSystem = yield* FileSystem.FileSystem;
94 const path = yield* Path.Path;
95 + const httpClient = yield* HttpClient.HttpClient;
96 + const latestVersions = yield* ProviderLatestVersions.ProviderLatestVersions;
97 const processEnv = yield* mergeProviderInstanceEnvironment(
98 environment,
99 yield* HostProcess.Environment,
@@ -109,9 +114,21 @@ export const FxDriver: ProviderDriver<FxSettings, FxDriverEnv> = {
114 enabled,
115 binaryPath: expandHomePath(config.binaryPath, yield* HostProcess.HomeDirectory),
116 } satisfies FxSettings;
117 + const resolveMaintenance = yield* makeCachedProviderMaintenanceResolution(
118 + resolveProviderMaintenanceCapabilitiesEffect(
119 + makeFxMaintenance(
120 + fetchLatestFxVersion().pipe(Effect.provideService(HttpClient.HttpClient, httpClient)),
121 + ),
122 + { binaryPath: effectiveConfig.binaryPath, env: processEnv },
123 + ).pipe(
124 + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
125 + Effect.provideService(FileSystem.FileSystem, fileSystem),
126 + Effect.provideService(Path.Path, path),
127 + ),
128 + );
129 const snapshotSettings = yield* makeProviderSnapshotSettingsSource(effectiveConfig);
130 const snapshot = yield* makeManagedServerProvider<ProviderSnapshotSettings<FxSettings>>({
114 - resolveMaintenance: () => Effect.succeed(MAINTENANCE),
131 + resolveMaintenance,
132 getSettings: snapshotSettings.getSettings,
133 streamSettings: snapshotSettings.streamSettings,
134 haveSettingsChanged: haveProviderSnapshotSettingsChanged,
@@ -121,6 +138,17 @@ export const FxDriver: ProviderDriver<FxSettings, FxDriverEnv> = {
138 Effect.map(stampIdentity),
139 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
140 ),
141 + enrichSnapshot: ({ settings, snapshot: currentSnapshot, publishSnapshot }) =>
142 + resolveMaintenance().pipe(
143 + Effect.flatMap((maintenanceCapabilities) =>
144 + enrichProviderSnapshotWithVersionAdvisory(currentSnapshot, maintenanceCapabilities, {
145 + enableProviderUpdateChecks: settings.enableProviderUpdateChecks,
146 + }),
147 + ),
148 + Effect.flatMap(publishSnapshot),
149 + Effect.provideService(HttpClient.HttpClient, httpClient),
150 + Effect.provideService(ProviderLatestVersions.ProviderLatestVersions, latestVersions),
151 + ),
152 }).pipe(
153 Effect.mapError(
154 (cause) =>
packages/provider-fx/src/server/maintenance.test.ts new
+278
@@ -0,0 +1,278 @@
1 +import * as NodeServices from "@effect/platform-node/NodeServices";
2 +import { expect, it } from "@effect/vitest";
3 +import { ProviderDriverKind, ProviderInstanceId, type ServerProvider } from "@t3tools/contracts";
4 +import * as Effect from "effect/Effect";
5 +import * as FileSystem from "effect/FileSystem";
6 +import * as Layer from "effect/Layer";
7 +import * as Path from "effect/Path";
8 +import * as Sink from "effect/Sink";
9 +import * as Stream from "effect/Stream";
10 +import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
11 +import * as HostProcess from "@t3tools/shared/HostProcess";
12 +import * as HttpClient from "effect/http/HttpClient";
13 +import * as HttpClientResponse from "effect/http/HttpClientResponse";
14 +
15 +import * as ProviderLatestVersions from "@t3tools/provider-core/server/ProviderLatestVersions";
16 +import { enrichProviderSnapshotWithVersionAdvisory } from "@t3tools/provider-core/server/maintenanceResolver";
17 +import { fetchLatestFxVersion, makeFxMaintenance } from "./maintenance.ts";
18 +
19 +const snapshot: ServerProvider = {
20 + instanceId: ProviderInstanceId.make("fx"),
21 + driver: ProviderDriverKind.make("fx"),
22 + enabled: true,
23 + installed: true,
24 + version: "0.0.13",
25 + status: "ready",
26 + auth: { status: "authenticated" },
27 + checkedAt: "2026-10-29T00:00:00.000Z",
28 + models: [],
29 + skills: [],
30 + slashCommands: [],
31 +};
32 +
33 +const serving = (response: Response) =>
34 + HttpClient.make((request) => Effect.succeed(HttpClientResponse.fromWeb(request, response)));
35 +
36 +const maintenanceLayer = Layer.merge(
37 + NodeServices.layer,
38 + Layer.succeed(HostProcess.KernelRelease, "24.0.0"),
39 +);
40 +
41 +it.layer(maintenanceLayer)("fx maintenance", (it) => {
42 + it.effect("uses the owning Homebrew installation and otherwise stays manual-only", () =>
43 + Effect.gen(function* () {
44 + const fs = yield* FileSystem.FileSystem;
45 + const path = yield* Path.Path;
46 + const prefix = yield* fs
47 + .makeTempDirectoryScoped({ prefix: "t3-fx-brew-" })
48 + .pipe(Effect.flatMap((directory) => fs.realPath(directory)));
49 + const brewPath = path.join(prefix, "bin", "brew");
50 + yield* fs.makeDirectory(path.dirname(brewPath), { recursive: true });
51 + yield* fs.writeFileString(brewPath, "");
52 + let reportedPrefix = prefix;
53 + const spawner = ChildProcessSpawner.make((command) => {
54 + if (command._tag !== "StandardCommand") return Effect.die("Expected a brew probe");
55 + const output =
56 + command.args[0] === "--prefix"
57 + ? reportedPrefix
58 + : JSON.stringify({ formulae: [{ versions: { stable: "0.0.14" } }] });
59 + return Effect.succeed(
60 + ChildProcessSpawner.makeHandle({
61 + pid: ChildProcessSpawner.ProcessId(1),
62 + exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(0)),
63 + isRunning: Effect.succeed(false),
64 + kill: () => Effect.void,
65 + unref: Effect.succeed(Effect.void),
66 + stdin: Sink.drain,
67 + stdout: Stream.encodeText(Stream.make(output)),
68 + stderr: Stream.empty,
69 + all: Stream.empty,
70 + getInputFd: () => Sink.drain,
71 + getOutputFd: () => Stream.empty,
72 + }),
73 + );
74 + });
75 + const context = {
76 + binaryPath: path.join(prefix, "bin", "fx"),
77 + resolvedCommandPath: path.join(prefix, "bin", "fx"),
78 + realCommandPath: path.join(prefix, "Cellar", "fx-agent", "0.0.13", "bin", "fx"),
79 + platform: "darwin" as const,
80 + env: { PATH: "" },
81 + };
82 + const resolver = makeFxMaintenance(Effect.die("Homebrew must not use fx's release channel"));
83 + const capabilities = yield* resolver
84 + .resolve(context)
85 + .pipe(
86 + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
87 + Effect.provideService(HostProcess.Platform, "darwin"),
88 + );
89 + expect(capabilities.update).toMatchObject({
90 + executable: brewPath,
91 + args: ["upgrade", "fx-agent"],
92 + lockKey: "homebrew",
93 + });
94 + expect(yield* capabilities.lookupLatestVersion!).toBe("0.0.14");
95 +
96 + reportedPrefix = path.join(prefix, "another-installation");
97 + expect(
98 + (yield* resolver
99 + .resolve(context)
100 + .pipe(
101 + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
102 + Effect.provideService(HostProcess.Platform, "darwin"),
103 + )).update,
104 + ).toBeNull();
105 + yield* fs.remove(brewPath);
106 + expect((yield* resolver.resolve(context)).update).toBeNull();
107 + expect(
108 + (yield* resolver.resolve({
109 + ...context,
110 + realCommandPath: path.join(prefix, "Cellar", "mise", "1.0.0", "bin", "fx"),
111 + })).update,
112 + ).toBeNull();
113 + }).pipe(Effect.scoped),
114 + );
115 +
116 + it.effect("offers `fx upgrade` on the instance's own binary once a newer release is out", () =>
117 + Effect.gen(function* () {
118 + const binaryPath = "/opt/tools/custom fx";
119 + const capabilities = yield* makeFxMaintenance(
120 + fetchLatestFxVersion().pipe(
121 + Effect.provideService(HttpClient.HttpClient, serving(new Response("v0.0.15\n"))),
122 + ),
123 + ).resolve({
124 + binaryPath,
125 + resolvedCommandPath: binaryPath,
126 + realCommandPath: "/opt/tools/fx-real",
127 + platform: "darwin",
128 + env: { HOME: "/home/fx" },
129 + });
130 + expect(capabilities.update).toMatchObject({
131 + executable: binaryPath,
132 + args: ["upgrade"],
133 + command: `'${binaryPath}' upgrade`,
134 + lockKey: "fx:/opt/tools/fx-real",
135 + env: { HOME: "/home/fx" },
136 + });
137 +
138 + const enriched = yield* enrichProviderSnapshotWithVersionAdvisory(snapshot, capabilities, {
139 + enableProviderUpdateChecks: true,
140 + }).pipe(
141 + Effect.provideService(HttpClient.HttpClient, serving(new Response("unused"))),
142 + Effect.provide(ProviderLatestVersions.layer),
143 + );
144 + expect(enriched.versionAdvisory).toMatchObject({
145 + status: "behind_latest",
146 + currentVersion: "0.0.13",
147 + latestVersion: "0.0.15",
148 + canUpdate: true,
149 + updateCommand: `'${binaryPath}' upgrade`,
150 + });
151 +
152 + const resolver = makeFxMaintenance(Effect.succeed("0.0.15"));
153 + const fs = yield* FileSystem.FileSystem;
154 + const path = yield* Path.Path;
155 + const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-fx-mise-" });
156 + const wrapperPath = path.join(directory, "fx");
157 + for (const { managedPath, env } of [
158 + { managedPath: "/home/fx/.local/share/mise/installs/fx/0.0.15/bin/fx", env: {} },
159 + { managedPath: "/home/fx/.local/share/mise/shims/fx", env: {} },
160 + { managedPath: "/home/fx/.local/share/mise/command-wrappers/fx", env: {} },
161 + {
162 + managedPath: "/opt/tools/installs/fx/0.0.15/bin/fx",
163 + env: { MISE_DATA_DIR: "/opt/tools/" },
164 + },
165 + {
166 + managedPath: "/opt/versions/fx/0.0.15/bin/fx",
167 + env: { MISE_INSTALLS_DIR: "/opt/versions" },
168 + },
169 + {
170 + managedPath: "/opt/store/fx-abc/bin/fx",
171 + env: { MISE_INSTALL_STORE_DIR: "/opt/store" },
172 + },
173 + {
174 + managedPath: "/opt/system/installs/fx/0.0.15/bin/fx",
175 + env: { MISE_SYSTEM_DATA_DIR: "/opt/system" },
176 + },
177 + {
178 + managedPath: "/opt/system-installs/fx/0.0.15/bin/fx",
179 + env: { MISE_SYSTEM_INSTALLS_DIR: "/opt/system-installs" },
180 + },
181 + ]) {
182 + for (const paths of [
183 + { resolvedCommandPath: managedPath, realCommandPath: binaryPath },
184 + { resolvedCommandPath: binaryPath, realCommandPath: managedPath },
185 + ]) {
186 + const managed = yield* resolver.resolve({
187 + binaryPath,
188 + ...paths,
189 + platform: "linux",
190 + env,
191 + });
192 + expect(managed.update).toBeNull();
193 + const managedSnapshot = yield* enrichProviderSnapshotWithVersionAdvisory(
194 + snapshot,
195 + managed,
196 + {
197 + enableProviderUpdateChecks: true,
198 + },
199 + ).pipe(
200 + Effect.provideService(HttpClient.HttpClient, serving(new Response("unused"))),
201 + Effect.provide(ProviderLatestVersions.layer),
202 + );
203 + expect(managedSnapshot.versionAdvisory).toMatchObject({
204 + status: "behind_latest",
205 + latestVersion: "0.0.15",
206 + canUpdate: false,
207 + });
208 + expect(managed.installPath).toBe(paths.realCommandPath);
209 + }
210 + }
211 + for (const command of ["x", "exec"]) {
212 + yield* fs.writeFileString(wrapperPath, `#!/bin/sh\nexec mise ${command} -- fx "$@"\n`);
213 + const managed = yield* resolver.resolve({
214 + binaryPath: wrapperPath,
215 + resolvedCommandPath: wrapperPath,
216 + realCommandPath: wrapperPath,
217 + platform: "linux",
218 + env: { MISE_SHIMS_DIR: directory, MISE_SYSTEM_SHIMS_DIR: directory },
219 + });
220 + expect(managed.update).toBeNull();
221 + expect(managed.installPath).toBe(wrapperPath);
222 + expect(yield* managed.lookupLatestVersion!).toBe("0.0.15");
223 + }
224 + yield* fs.writeFileString(wrapperPath, "#!/bin/sh\nexit 0\n");
225 + expect(
226 + (yield* resolver.resolve({
227 + binaryPath: wrapperPath,
228 + resolvedCommandPath: wrapperPath,
229 + realCommandPath: wrapperPath,
230 + platform: "linux",
231 + env: { MISE_SHIMS_DIR: directory, MISE_SYSTEM_SHIMS_DIR: directory },
232 + })).update,
233 + ).not.toBeNull();
234 + const outsideMise = "/opt/tools-extra/installs/fx/0.0.15/bin/fx";
235 + expect(
236 + (yield* resolver.resolve({
237 + binaryPath: outsideMise,
238 + resolvedCommandPath: outsideMise,
239 + realCommandPath: outsideMise,
240 + platform: "linux",
241 + env: { MISE_DATA_DIR: "/opt/tools" },
242 + })).update,
243 + ).not.toBeNull();
244 + }).pipe(Effect.scoped),
245 + );
246 +
247 + it.effect("leaves the latest version unknown when the release file is unusable", () =>
248 + Effect.gen(function* () {
249 + for (const response of [
250 + new Response("<html>not found</html>"),
251 + new Response("v0.0.15", { status: 503 }),
252 + ]) {
253 + const latest = yield* fetchLatestFxVersion().pipe(
254 + Effect.provideService(HttpClient.HttpClient, serving(response)),
255 + );
256 + expect(latest).toBeNull();
257 + }
258 + expect((yield* makeFxMaintenance(Effect.succeed("0.0.15")).resolve(null)).update).toBeNull();
259 + }),
260 + );
261 +
262 + it.effect("offers no update or latest version on macOS 14, which newer fx cannot run on", () =>
263 + Effect.gen(function* () {
264 + const binaryPath = "/opt/tools/fx";
265 + const capabilities = yield* makeFxMaintenance(Effect.succeed("0.0.15"))
266 + .resolve({
267 + binaryPath,
268 + resolvedCommandPath: binaryPath,
269 + realCommandPath: binaryPath,
270 + platform: "darwin",
271 + env: {},
272 + })
273 + .pipe(Effect.provideService(HostProcess.KernelRelease, "23.6.0"));
274 + expect(capabilities.update).toBeNull();
275 + expect(capabilities.lookupLatestVersion).toBeUndefined();
276 + }),
277 + );
278 +});
packages/provider-fx/src/server/maintenance.ts new
+83
@@ -0,0 +1,83 @@
1 +import * as HostProcess from "@t3tools/shared/HostProcess";
2 +import * as Effect from "effect/Effect";
3 +import * as HttpClient from "effect/http/HttpClient";
4 +import * as HttpClientRequest from "effect/http/HttpClientRequest";
5 +
6 +import {
7 + homebrewOwnershipFromCommandPath,
8 + isNixStoreCommandPath,
9 + makeManualOnlyProviderMaintenanceCapabilities,
10 + makeProviderMaintenanceCapabilities,
11 + resolveHomebrewProviderMaintenance,
12 + resolveMacPortsOwner,
13 + resolveMiseProviderMaintenance,
14 + type ProviderMaintenanceCapabilitiesResolver,
15 +} from "@t3tools/provider-core/server/maintenanceResolver";
16 +import { FX_DRIVER_KIND } from "./acpSupport.ts";
17 +
18 +/** The stable release `fx upgrade` and fx's setup script install. */
19 +const FX_LATEST_RELEASE_URL = "https://releases.fx.sh/latest.txt";
20 +
21 +export const fetchLatestFxVersion = Effect.fn("fetchLatestFxVersion")(function* () {
22 + const client = yield* HttpClient.HttpClient;
23 + return yield* client.execute(HttpClientRequest.get(FX_LATEST_RELEASE_URL)).pipe(
24 + Effect.flatMap((response) =>
25 + response.status >= 200 && response.status < 300 ? response.text : Effect.succeed(""),
26 + ),
27 + Effect.map((body) => body.trim().match(/^v?(\d+\.\d+\.\d+)$/)?.[1] ?? null),
28 + Effect.timeout(4_000),
29 + Effect.orElseSucceed(() => null),
30 + );
31 +});
32 +
33 +// fx after 0.0.13 needs Darwin 24, but its updater does not check the host version.
34 +export const makeFxMaintenance = (
35 + lookupLatestVersion: Effect.Effect<string | null>,
36 +): ProviderMaintenanceCapabilitiesResolver => ({
37 + resolve: Effect.fn("FxMaintenance.resolve")(function* (context) {
38 + const input = { provider: FX_DRIVER_KIND, packageName: null };
39 + const manualOnly = makeManualOnlyProviderMaintenanceCapabilities(input);
40 + if (
41 + context === null ||
42 + (context.platform === "darwin" && Number.parseInt(yield* HostProcess.KernelRelease, 10) < 24)
43 + ) {
44 + return manualOnly;
45 + }
46 + // fx has no mise registry tool, so a mise-owned install stays manual-only.
47 + if (yield* resolveMiseProviderMaintenance(input, undefined, context)) {
48 + return makeManualOnlyProviderMaintenanceCapabilities({
49 + ...input,
50 + installPath: context.realCommandPath,
51 + lookupLatestVersion,
52 + });
53 + }
54 + if ([context.resolvedCommandPath, context.realCommandPath].some(isNixStoreCommandPath)) {
55 + return makeManualOnlyProviderMaintenanceCapabilities({
56 + ...input,
57 + installPath: context.realCommandPath,
58 + });
59 + }
60 + const macPortsName = yield* resolveMacPortsOwner(context);
61 + if (macPortsName !== null) {
62 + return makeManualOnlyProviderMaintenanceCapabilities({
63 + ...input,
64 + installPath: context.realCommandPath,
65 + ...(macPortsName ? { manualCommand: `sudo port upgrade ${macPortsName}` } : {}),
66 + });
67 + }
68 + const homebrew = homebrewOwnershipFromCommandPath(context.realCommandPath);
69 + if (homebrew) {
70 + if (homebrew.kind !== "formula" || homebrew.name !== "fx-agent") return manualOnly;
71 + return (yield* resolveHomebrewProviderMaintenance(input, homebrew, context)) ?? manualOnly;
72 + }
73 + return makeProviderMaintenanceCapabilities({
74 + ...input,
75 + updateExecutable: context.resolvedCommandPath,
76 + updateArgs: ["upgrade"],
77 + updateLockKey: `fx:${context.realCommandPath}`,
78 + platform: context.platform,
79 + env: context.env,
80 + lookupLatestVersion,
81 + });
82 + }),
83 +});
packages/provider-fx/src/server/status.ts
-1
@@ -79,7 +79,6 @@ const snapshot = (
79 listed?: ReadonlyArray<string>,
80 ): ServerProviderDraft => ({
81 ...buildServerProvider({
82 - // Gives the snapshot its version advisory; fx runs no enrichment pass.
82 driver: FX_DRIVER_KIND,
83 presentation: FX_PRESENTATION,
84 enabled: settings.enabled,
packages/shared/src/HostProcess.ts
+7
@@ -16,6 +16,13 @@ export const Architecture = Context.Reference<NodeJS.Architecture>(
16 },
17 );
18
19 +export const KernelRelease = Context.Reference<string>(
20 + "@t3tools/shared/HostProcess/KernelRelease",
21 + {
22 + defaultValue: () => NodeOS.release(),
23 + },
24 +);
25 +
26 export const LinuxLibc = Context.Reference<"gnu" | "musl">(
27 "@t3tools/shared/HostProcess/LinuxLibc",
28 {