fix(orchestrator): address late review findings

Co-authored-by: codex <[email protected]>
This commit is contained in:
Julius Marmingeandcodex committed 2026-07-29 03:38:48 +02:00
1 parent 936a798d9d
commit dbc836d591
27 files changed
+473 -60

No files matched your search

@@ -0,0 +1,15 @@
import { describe, expect, it } from "vite-plus/test";
import { threadWorkLogOverflowNoun } from "./thread-work-log-labels";
describe("thread work log overflow labels", () => {
it("describes tool-only groups as tool calls", () => {
expect(threadWorkLogOverflowNoun(true, 1)).toBe("tool call");
expect(threadWorkLogOverflowNoun(true, 2)).toBe("tool calls");
});
it("describes mixed groups as log entries", () => {
expect(threadWorkLogOverflowNoun(false, 1)).toBe("log entry");
expect(threadWorkLogOverflowNoun(false, 2)).toBe("log entries");
});
});
@@ -0,0 +1,9 @@
export function threadWorkLogOverflowNoun(
onlyToolRows: boolean,
count: number,
): "tool call" | "tool calls" | "log entry" | "log entries" {
if (onlyToolRows) {
return count === 1 ? "tool call" : "tool calls";
}
return count === 1 ? "log entry" : "log entries";
}
@@ -12,6 +12,7 @@ import type { ThreadFeedActivity } from "../../lib/threadActivity";
import Animated, { FadeIn } from "react-native-reanimated";
import { useV2ItemSupport } from "../../state/v2-item-support";
import { ThreadActivityInspector } from "./ThreadActivityInspector";
import { threadWorkLogOverflowNoun } from "./thread-work-log-labels";
const MAX_VISIBLE_WORK_LOG_ENTRIES = 1;
const WORK_LOG_LAYOUT_ANIMATION = {
@@ -191,6 +192,7 @@ export function ThreadWorkLog(props: {
hasOverflow && !props.expanded ? rows.slice(-MAX_VISIBLE_WORK_LOG_ENTRIES) : rows;
const hiddenCount = rows.length - visibleRows.length;
const onlyToolRows = rows.every((row) => row.toolLike);
const overflowNoun = threadWorkLogOverflowNoun(onlyToolRows, hiddenCount);
return (
<View className="-mx-1 mb-3 px-1 py-0.5">
@@ -327,8 +329,8 @@ export function ThreadWorkLog(props: {
accessibilityState={{ expanded: props.expanded }}
accessibilityLabel={
props.expanded
? "Show fewer tool calls"
: `Show ${hiddenCount} previous tool ${hiddenCount === 1 ? "call" : "calls"}`
? `Show fewer ${overflowNoun}`
: `Show ${hiddenCount} previous ${overflowNoun}`
}
hitSlop={4}
onPress={() => {
@@ -350,8 +352,8 @@ export function ThreadWorkLog(props: {
</View>
<Text className="font-t3-medium text-xs text-foreground opacity-80">
{props.expanded
? "Show fewer tool calls"
: `+${hiddenCount} previous tool ${hiddenCount === 1 ? "call" : "calls"}`}
? `Show fewer ${overflowNoun}`
: `+${hiddenCount} previous ${overflowNoun}`}
</Text>
</Pressable>
) : null}
@@ -368,13 +370,7 @@ export function ThreadWorkGroupToggle(props: {
}) {
const colorScheme = useColorScheme();
const pressedBackground = colorScheme === "dark" ? "rgba(255,255,255,0.05)" : "rgba(0,0,0,0.035)";
const noun = props.onlyToolActivities
? props.hiddenCount === 1
? "tool call"
: "tool calls"
: props.hiddenCount === 1
? "log entry"
: "log entries";
const noun = threadWorkLogOverflowNoun(props.onlyToolActivities, props.hiddenCount);
return (
<View className="-mx-1 mb-1 px-1">
@@ -2,7 +2,6 @@ import { useAtomValue } from "@effect/atom-react";
import { threadRuntimeIsActive } from "@t3tools/client-runtime/state/shell";
import {
deriveThreadActivityRun,
deriveThreadInterruptibleRunId,
deriveThreadRuntime,
} from "@t3tools/client-runtime/state/thread-execution";
import { useCallback, useEffect, useMemo } from "react";
@@ -150,7 +149,7 @@ export function useThreadComposerState() {
}, [selectedThreadActivityRun, selectedThreadSessionActivity, selectedThreadShell]);
const activeThreadBusy = threadRuntimeIsActive(selectedThreadRuntime);
const interruptibleRunId = deriveThreadInterruptibleRunId(selectedThreadProjection?.projection);
const interruptibleRunId = selectedThreadRuntime?.activeRunId ?? null;
const onSendMessage = useCallback(async () => {
if (!selectedThreadShell) {
@@ -0,0 +1,73 @@
// @effect-diagnostics nodeBuiltinImport:off
import * as NodeChildProcess from "node:child_process";
import * as NodeFS from "node:fs";
import * as NodeOS from "node:os";
import * as NodePath from "node:path";
import * as NodeURL from "node:url";
import { expect, it } from "vite-plus/test";
const replayAgentPath = NodeURL.fileURLToPath(new URL("./acp-replay-agent.ts", import.meta.url));
async function runRuntimeExit(status: "success" | "error" | "cancelled") {
const scratch = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-acp-replay-agent-"));
const statusPath = NodePath.join(scratch, "status.json");
const transcript = {
scenario: `${status}-runtime-exit`,
entries: [{ type: "runtime_exit", status }],
};
const child = NodeChildProcess.spawn(process.execPath, [replayAgentPath], {
env: {
...process.env,
T3_ACP_REPLAY_STATUS_PATH: statusPath,
T3_ACP_REPLAY_TRANSCRIPT: Buffer.from(JSON.stringify(transcript), "utf8").toString("base64"),
T3_ACP_REPLAY_WORKSPACE: scratch,
},
stdio: ["pipe", "pipe", "pipe"],
});
let stderr = "";
child.stderr.setEncoding("utf8");
child.stderr.on("data", (chunk: string) => {
stderr += chunk;
});
child.stdin.end();
try {
const code = await new Promise<number | null>((resolve, reject) => {
child.once("error", reject);
child.once("exit", resolve);
});
return {
code,
status: JSON.parse(NodeFS.readFileSync(statusPath, "utf8")) as unknown,
stderr,
transcript,
};
} finally {
NodeFS.rmSync(scratch, { recursive: true, force: true });
}
}
it("accepts a recorded cancelled runtime exit", async () => {
const result = await runRuntimeExit("cancelled");
expect(result.code, result.stderr).toBe(0);
expect(result.status).toEqual({
scenario: result.transcript.scenario,
cursor: 1,
total: 1,
});
});
it("still rejects a recorded error runtime exit", async () => {
const result = await runRuntimeExit("error");
expect(result.code).toBe(1);
expect(result.status).toMatchObject({
scenario: result.transcript.scenario,
cursor: 0,
total: 1,
failure: {
detail: "Recorded runtime exit was error",
cursor: 0,
},
});
});
+1 -1
View File
@@ -214,7 +214,7 @@ function flushInbound(): void {
const entry = transcript.entries[cursor];
if (entry === undefined || entry.type === "expect_outbound") return;
if (entry.type === "runtime_exit") {
if (entry.status !== "success") {
if (entry.status !== "success" && entry.status !== "cancelled") {
stopWithFailure(`Recorded runtime exit was ${entry.status ?? "unknown"}`, entry.error);
return;
}
@@ -2,6 +2,7 @@ import { assert, it } from "@effect/vitest";
import {
cursorReplayPromptsForWorkspace,
cursorReplayTranscriptCwd,
shouldSeedCursorReplayWorkspace,
} from "./cursorReplayRecordingWorkspace.ts";
@@ -33,3 +34,11 @@ it("never seeds files into an externally supplied workspace", () => {
}),
);
});
it("canonicalizes read-only tool paths to the stable fixture workspace", () => {
assert.equal(
cursorReplayTranscriptCwd("tool_call_read_only"),
"/tmp/claude-replay-tool_call_read_only",
);
assert.equal(cursorReplayTranscriptCwd("simple"), undefined);
});
@@ -1,3 +1,5 @@
import { TOOL_CALL_READ_ONLY_WORKSPACE_ROOT } from "../src/orchestration-v2/testkit/fixtures/shared.ts";
const SEEDED_CURSOR_REPLAY_SCENARIOS = new Set(["subagent", "tool_call_read_only", "todo_list"]);
export function cursorReplayPromptsForWorkspace(input: {
@@ -21,3 +23,7 @@ export function shouldSeedCursorReplayWorkspace(input: {
}): boolean {
return input.owned && SEEDED_CURSOR_REPLAY_SCENARIOS.has(input.scenario);
}
export function cursorReplayTranscriptCwd(scenario: string): string | undefined {
return scenario === "tool_call_read_only" ? TOOL_CALL_READ_ONLY_WORKSPACE_ROOT : undefined;
}
@@ -24,6 +24,7 @@ import {
} from "../src/orchestration-v2/testkit/fixtures/shared.ts";
import {
cursorReplayPromptsForWorkspace,
cursorReplayTranscriptCwd,
shouldSeedCursorReplayWorkspace,
} from "./cursorReplayRecordingWorkspace.ts";
@@ -158,6 +159,7 @@ if (!apiKey) {
const recording = RECORDINGS[scenario];
const workspace = await prepareWorkspace(scenario);
const transcriptCwd = cursorReplayTranscriptCwd(scenario);
const outputPath = readArgValue("--out") ?? new URL(recording.output, import.meta.url).pathname;
try {
@@ -184,6 +186,7 @@ try {
model: process.env.T3_CURSOR_REPLAY_MODEL ?? CURSOR_MODEL_SELECTION.model,
},
cwd: workspace.cwd,
...(transcriptCwd === undefined ? {} : { transcriptCwd }),
apiKey,
...("interactionMode" in recording ? { interactionMode: recording.interactionMode } : {}),
...("interruptAfterToolStart" in recording
@@ -6376,6 +6376,31 @@ describe("AcpAdapterV2", () => {
1,
"exactly one continuation must be offered after finalize for mid-turn unhandled completion",
);
const beforeWhitespace = yield* runtime.readThreadSnapshot({ providerThread });
yield* Queue.clear(events);
yield* sessionUpdateHandler!({
sessionId: "mock-session-1",
update: {
sessionUpdate: "agent_message_chunk",
content: { type: "text", text: " \n\t " },
},
});
const lateEvents: Array<ProviderAdapterV2Event> = [];
let lateEvent = yield* Queue.poll(events);
while (Option.isSome(lateEvent)) {
lateEvents.push(lateEvent.value);
lateEvent = yield* Queue.poll(events);
}
assert.isFalse(
lateEvents.some((event) => event.type === "message.updated"),
"whitespace-only late chunks must not append assistant history",
);
const afterWhitespace = yield* runtime.readThreadSnapshot({ providerThread });
assert.deepEqual(
afterWhitespace.messages,
beforeWhitespace.messages,
"whitespace-only late chunks must not mutate the loaded history snapshot",
);
}).pipe(Effect.provide(testLayer), Effect.scoped),
);
@@ -8874,6 +8899,18 @@ describe("acpPostSettleContinuationOfferEvidence", () => {
);
});
it("does not offer on whitespace-only assistant chunks", () => {
const notification = {
sessionId,
update: {
sessionUpdate: "agent_message_chunk" as const,
content: { type: "text" as const, text: " \n\t " },
},
};
assert.isFalse(acpPostSettleWakeEvidence(notification));
assert.isFalse(acpPostSettleContinuationOfferEvidence(notification));
});
it("buffers in-progress tool updates without offering", () => {
assert.isTrue(
acpPostSettleWakeEvidence({
@@ -1078,6 +1078,7 @@ export function acpPostSettleWakeEvidence(
) {
const text = update.content.text;
if ((flavor.extractBackgroundToolMutation?.(text) ?? []).length > 0) return false;
if (update.sessionUpdate === "agent_message_chunk" && text.trim().length === 0) return false;
if (/<monitor-event\b/i.test(text) || /Monitor\s+["']?[0-9a-f-]{8,}["']?\s+ended/i.test(text)) {
return false;
}
@@ -1103,7 +1104,7 @@ export function acpPostSettleContinuationOfferEvidence(
// Assistant text only. Thought/reasoning bursts alone must not open synthetic
// "Background task completed." runs (duplicate-run spam after monitors).
if (update.sessionUpdate === "agent_message_chunk") {
return update.content.type === "text" && update.content.text.length > 0;
return update.content.type === "text" && update.content.text.trim().length > 0;
}
if (update.sessionUpdate === "tool_call" || update.sessionUpdate === "tool_call_update") {
return parseSessionUpdateEvent(notification).events.some((event) => {
@@ -3118,7 +3119,11 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV
const lateMonitorChatter =
/<monitor-event\b/i.test(text) ||
/Monitor\s+["']?[0-9a-f-]{8,}["']?\s+ended/i.test(text);
if (lateBackgroundMutations.length === 0 && !lateMonitorChatter) {
if (
text.trim().length > 0 &&
lateBackgroundMutations.length === 0 &&
!lateMonitorChatter
) {
yield* appendLoadedHistory(
notification,
update.sessionUpdate === "user_message_chunk" ? "user" : "assistant",
@@ -727,6 +727,8 @@ export async function recordCursorAgentSdkReplayTranscript(input: {
readonly transcriptPrompts?: ReadonlyArray<string>;
readonly modelSelection: ModelSelection;
readonly cwd: string;
/** Stable fixture cwd used to sanitize runtime-only workspace paths in recorded updates. */
readonly transcriptCwd?: string;
readonly interactionMode?: "default" | "plan";
readonly apiKey?: string;
readonly interruptAfterToolStart?: boolean;
@@ -789,7 +791,7 @@ export async function recordCursorAgentSdkReplayTranscript(input: {
});
const replacements: ReadonlyArray<readonly [string, string]> = [
[input.cwd, `/tmp/cursor-replay-${input.scenario}`],
[input.cwd, input.transcriptCwd ?? `/tmp/cursor-replay-${input.scenario}`],
];
try {
@@ -91,8 +91,8 @@ it.layer(TestLayer)("LegacyV1ThreadImporter", (it) => {
'{"instanceId":"codex","model":"gpt-5.4"}',
'full-access',
'default',
'main',
'/tmp/legacy-project',
' main ',
' /tmp/legacy-project ',
NULL,
'2026-01-01T00:00:00.000Z',
'2026-01-04T00:00:00.000Z',
@@ -178,6 +178,8 @@ it.layer(TestLayer)("LegacyV1ThreadImporter", (it) => {
assert.isTrue(rebuilt.valid);
const shellProjection = yield* projections.getThreadProjection(threadId);
assert.equal(shellProjection.thread.historyOrigin, "v1_import");
assert.equal(shellProjection.thread.branch, "main");
assert.equal(shellProjection.thread.worktreePath, "/tmp/legacy-project");
const shellSnapshot = yield* projections.getShellSnapshot();
assert.equal(
shellSnapshot.threads.find((thread) => thread.id === threadId)?.historyOrigin,
@@ -150,6 +150,8 @@ function nullableDateTime(value: string | null): DateTime.Utc | null {
function importedThread(row: LegacyThreadRow): OrchestrationV2AppThread {
const threadId = ThreadId.make(row.thread_id);
const modelSelection = modelSelectionFor(row);
const branch = row.branch?.trim() || null;
const worktreePath = row.worktree_path?.trim() || null;
return {
createdBy: "system",
creationSource: "server",
@@ -160,8 +162,8 @@ function importedThread(row: LegacyThreadRow): OrchestrationV2AppThread {
modelSelection,
runtimeMode: runtimeModeFor(row.runtime_mode),
interactionMode: interactionModeFor(row.interaction_mode),
branch: row.branch?.trim() ? row.branch : null,
worktreePath: row.worktree_path?.trim() ? row.worktree_path : null,
branch,
worktreePath,
activeProviderThreadId: null,
historyOrigin: "v1_import",
lineage: {
@@ -84,6 +84,100 @@ it("includes imported runless history when selecting fork context through a run"
});
it.layer(TestLayer)("ProjectionStoreV2", (it) => {
it.effect("only exposes interruptible runs through the shell activeRunId", () =>
Effect.gen(function* () {
const projectionStore = yield* ProjectionStoreV2;
const now = yield* DateTime.now;
const threadId = ThreadId.make("thread:projection-shell-interruptible");
const projectId = ProjectId.make("project:projection-shell-interruptible");
const runId = RunId.make("run:projection-shell-interruptible");
const rootNodeId = NodeId.make("node:projection-shell-interruptible");
const run = {
id: runId,
threadId,
ordinal: 1,
providerInstanceId,
modelSelection,
providerThreadId: null,
userMessageId: MessageId.make("message:projection-shell-interruptible"),
rootNodeId,
activeAttemptId: null,
status: "running" as const,
requestedAt: now,
startedAt: now,
completedAt: null,
checkpointId: null,
contextHandoffId: null,
};
yield* projectionStore.apply({
id: EventId.make("event:projection-shell-interruptible:thread"),
type: "thread.created",
threadId,
occurredAt: now,
payload: {
createdBy: "user",
creationSource: "web",
id: threadId,
projectId,
title: "Interruptible shell run",
providerInstanceId,
modelSelection,
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
worktreePath: null,
activeProviderThreadId: null,
lineage: {
parentThreadId: null,
relationshipToParent: null,
rootThreadId: threadId,
},
forkedFrom: null,
createdAt: now,
updatedAt: now,
archivedAt: null,
settledOverride: null,
settledAt: null,
deletedAt: null,
},
});
yield* projectionStore.apply({
id: EventId.make("event:projection-shell-interruptible:running"),
type: "run.created",
threadId,
runId,
nodeId: rootNodeId,
driver,
occurredAt: now,
payload: run,
});
let shell = (yield* projectionStore.getShellSnapshot()).threads.find(
(thread) => thread.id === threadId,
);
assert.equal(shell?.status, "running");
assert.equal(shell?.activeRunId, runId);
yield* projectionStore.apply({
id: EventId.make("event:projection-shell-interruptible:waiting"),
type: "run.updated",
threadId,
runId,
nodeId: rootNodeId,
driver,
occurredAt: now,
payload: { ...run, status: "waiting" },
});
shell = (yield* projectionStore.getShellSnapshot()).threads.find(
(thread) => thread.id === threadId,
);
assert.equal(shell?.status, "waiting");
assert.isNull(shell?.activeRunId);
}),
);
it.effect("projects one shared provider session into multiple thread bindings", () =>
Effect.gen(function* () {
const projectionStore = yield* ProjectionStoreV2;
@@ -175,10 +269,12 @@ it.layer(TestLayer)("ProjectionStoreV2", (it) => {
[providerSessionId],
);
assert.deepEqual(
(yield* projectionStore.getShellSnapshot()).threads.map((thread) => ({
id: thread.id,
lastError: thread.lastError,
})),
(yield* projectionStore.getShellSnapshot()).threads
.filter((thread) => thread.id === firstThreadId || thread.id === secondThreadId)
.map((thread) => ({
id: thread.id,
lastError: thread.lastError,
})),
[
{ id: firstThreadId, lastError: "provider process exited" },
{ id: secondThreadId, lastError: "provider process exited" },
@@ -748,7 +748,7 @@ export function threadShellFromProjection(
const latestRun = projection.runs.at(-1) ?? null;
const activeRun =
projection.runs
.filter(isBlockingRunForShell)
.filter(isInterruptibleRunForShell)
.toSorted((left, right) => right.ordinal - left.ordinal)[0] ?? null;
const pendingRuntimeRequest =
projection.runtimeRequests
@@ -832,13 +832,8 @@ export function threadShellFromProjection(
};
}
function isBlockingRunForShell(run: OrchestrationV2ThreadProjection["runs"][number]): boolean {
return (
run.status === "preparing" ||
run.status === "starting" ||
run.status === "running" ||
run.status === "waiting"
);
function isInterruptibleRunForShell(run: OrchestrationV2ThreadProjection["runs"][number]): boolean {
return run.status === "preparing" || run.status === "starting" || run.status === "running";
}
type ShellThreadState = {
@@ -2108,7 +2103,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
SELECT r.run_id
FROM orchestration_v2_projection_runs r
WHERE r.thread_id = t.thread_id
AND r.status IN ('preparing', 'starting', 'running', 'waiting')
AND r.status IN ('preparing', 'starting', 'running')
ORDER BY r.ordinal DESC, r.run_id DESC
LIMIT 1
) AS active_run_id,
@@ -97,6 +97,46 @@ it("restarts compatible instances for workspace or runtime changes", () => {
);
});
it("preserves a rejected selection when the workspace also changes", () => {
assert.deepEqual(
decideProviderSessionTransition({
current: base,
target: {
...base,
modelSelection: { ...base.modelSelection, model: "gpt-5.2-codex" },
workspace: "/other",
available: true,
},
selectionTransition: {
type: "reject",
reason: "The active session cannot apply that model.",
},
}),
{ type: "reject", reason: "The active session cannot apply that model." },
);
});
it("preserves handoff and missing-classification outcomes across workspace changes", () => {
const target = {
...base,
modelSelection: { ...base.modelSelection, model: "gpt-5.2-codex" },
workspace: "/other",
available: true,
};
assert.deepEqual(
decideProviderSessionTransition({
current: base,
target,
selectionTransition: { type: "create_with_handoff" },
}),
{ type: "create_with_handoff" },
);
assert.deepEqual(decideProviderSessionTransition({ current: base, target }), {
type: "reject",
reason: "The provider adapter did not classify the selection change.",
});
});
it("uses portable handoff for incompatible continuation identities", () => {
assert.deepEqual(
decideProviderSessionTransition({
@@ -55,11 +55,27 @@ export function decideProviderSessionTransition(input: {
const instanceChanged = current.modelSelection.instanceId !== target.modelSelection.instanceId;
const runtimeChanged = current.runtimeMode !== target.runtimeMode;
const workspaceChanged = current.workspace !== target.workspace;
const selectionChanged = !modelSelectionsEqual(current.modelSelection, target.modelSelection);
if (selectionChanged && !instanceChanged) {
switch (input.selectionTransition?.type) {
case "create_with_handoff":
return { type: "create_with_handoff" };
case "reject":
return { type: "reject", reason: input.selectionTransition.reason };
case undefined:
return {
type: "reject",
reason: "The provider adapter did not classify the selection change.",
};
case "apply_on_next_turn":
case "restart_session":
break;
}
}
if (instanceChanged || runtimeChanged || workspaceChanged) {
return { type: "restart_and_resume" };
}
const selectionChanged = !modelSelectionsEqual(current.modelSelection, target.modelSelection);
if (selectionChanged) {
switch (input.selectionTransition?.type) {
case "apply_on_next_turn":
@@ -71,10 +87,7 @@ export function decideProviderSessionTransition(input: {
case "reject":
return { type: "reject", reason: input.selectionTransition.reason };
case undefined:
return {
type: "reject",
reason: "The provider adapter did not classify the selection change.",
};
return { type: "restart_and_resume" };
}
}
@@ -47,4 +47,18 @@ export function assertToolCallReadOnlyCursorOutput(
),
);
assert.isTrue(fileSearches.some((item) => JSON.stringify(item.results ?? []).includes("ES2022")));
const expectedPaths = [
"/tmp/claude-replay-tool_call_read_only/package.json",
"/tmp/claude-replay-tool_call_read_only/tsconfig.json",
];
assert.deepEqual(
fileSearches.map((item) => item.pattern).toSorted(),
expectedPaths,
"Cursor file_search patterns must match the files named in the recorded prompt",
);
assert.deepEqual(
fileSearches.flatMap((item) => item.results?.map((result) => result.fileName) ?? []).toSorted(),
expectedPaths,
"Cursor file_search paths must match the files named in the recorded prompt",
);
}
@@ -9,13 +9,13 @@
{"type":"emit_inbound","label":"token-delta","frame":{"type":"interaction.update","runId":"run-db8a1002-593e-4baf-9ed1-d837c14643ed","update":{"type":"token-delta","tokens":1}}}
{"type":"emit_inbound","label":"token-delta","frame":{"type":"interaction.update","runId":"run-db8a1002-593e-4baf-9ed1-d837c14643ed","update":{"type":"token-delta","tokens":2}}}
{"type":"emit_inbound","label":"token-delta","frame":{"type":"interaction.update","runId":"run-db8a1002-593e-4baf-9ed1-d837c14643ed","update":{"type":"token-delta","tokens":13}}}
{"type":"emit_inbound","label":"tool-call-started","frame":{"type":"interaction.update","runId":"run-db8a1002-593e-4baf-9ed1-d837c14643ed","update":{"type":"tool-call-started","callId":"tool_56c7e2fb-8a39-4b1d-8b28-31f47bd717e","toolCall":{"type":"read","args":{"path":"/tmp/cursor-replay-tool_call_read_only/package.json"}},"modelCallId":"fb59b086-fb0a-4263-ac27-2c53351e44ac-0-279u"}}}
{"type":"emit_inbound","label":"tool-call-started","frame":{"type":"interaction.update","runId":"run-db8a1002-593e-4baf-9ed1-d837c14643ed","update":{"type":"tool-call-started","callId":"tool_56c7e2fb-8a39-4b1d-8b28-31f47bd717e","toolCall":{"type":"read","args":{"path":"/tmp/claude-replay-tool_call_read_only/package.json"}},"modelCallId":"fb59b086-fb0a-4263-ac27-2c53351e44ac-0-279u"}}}
{"type":"emit_inbound","label":"token-delta","frame":{"type":"interaction.update","runId":"run-db8a1002-593e-4baf-9ed1-d837c14643ed","update":{"type":"token-delta","tokens":3}}}
{"type":"emit_inbound","label":"token-delta","frame":{"type":"interaction.update","runId":"run-db8a1002-593e-4baf-9ed1-d837c14643ed","update":{"type":"token-delta","tokens":13}}}
{"type":"emit_inbound","label":"tool-call-started","frame":{"type":"interaction.update","runId":"run-db8a1002-593e-4baf-9ed1-d837c14643ed","update":{"type":"tool-call-started","callId":"tool_a4c6ef64-f13c-4738-b527-1aad09b6185","toolCall":{"type":"read","args":{"path":"/tmp/cursor-replay-tool_call_read_only/tsconfig.json"}},"modelCallId":"fb59b086-fb0a-4263-ac27-2c53351e44ac-0-279u"}}}
{"type":"emit_inbound","label":"tool-call-completed","frame":{"type":"interaction.update","runId":"run-db8a1002-593e-4baf-9ed1-d837c14643ed","update":{"type":"tool-call-completed","callId":"tool_56c7e2fb-8a39-4b1d-8b28-31f47bd717e","toolCall":{"type":"read","args":{"path":"/tmp/cursor-replay-tool_call_read_only/package.json"},"result":{"status":"success","value":{"content":"{\"name\":\"cursor-read-only-fixture\",\"private\":true,\"scripts\":{\"typecheck\":\"tsc --noEmit\"}}","totalLines":1,"fileSize":89}}},"modelCallId":"fb59b086-fb0a-4263-ac27-2c53351e44ac-0-279u"}}}
{"type":"emit_inbound","label":"tool-call-started","frame":{"type":"interaction.update","runId":"run-db8a1002-593e-4baf-9ed1-d837c14643ed","update":{"type":"tool-call-started","callId":"tool_a4c6ef64-f13c-4738-b527-1aad09b6185","toolCall":{"type":"read","args":{"path":"/tmp/claude-replay-tool_call_read_only/tsconfig.json"}},"modelCallId":"fb59b086-fb0a-4263-ac27-2c53351e44ac-0-279u"}}}
{"type":"emit_inbound","label":"tool-call-completed","frame":{"type":"interaction.update","runId":"run-db8a1002-593e-4baf-9ed1-d837c14643ed","update":{"type":"tool-call-completed","callId":"tool_56c7e2fb-8a39-4b1d-8b28-31f47bd717e","toolCall":{"type":"read","args":{"path":"/tmp/claude-replay-tool_call_read_only/package.json"},"result":{"status":"success","value":{"content":"{\"name\":\"cursor-read-only-fixture\",\"private\":true,\"scripts\":{\"typecheck\":\"tsc --noEmit\"}}","totalLines":1,"fileSize":89}}},"modelCallId":"fb59b086-fb0a-4263-ac27-2c53351e44ac-0-279u"}}}
{"type":"emit_inbound","label":"token-delta","frame":{"type":"interaction.update","runId":"run-db8a1002-593e-4baf-9ed1-d837c14643ed","update":{"type":"token-delta","tokens":23}}}
{"type":"emit_inbound","label":"tool-call-completed","frame":{"type":"interaction.update","runId":"run-db8a1002-593e-4baf-9ed1-d837c14643ed","update":{"type":"tool-call-completed","callId":"tool_a4c6ef64-f13c-4738-b527-1aad09b6185","toolCall":{"type":"read","args":{"path":"/tmp/cursor-replay-tool_call_read_only/tsconfig.json"},"result":{"status":"success","value":{"content":"{\"compilerOptions\":{\"module\":\"ESNext\",\"strict\":true,\"target\":\"ES2022\"}}","totalLines":1,"fileSize":71}}},"modelCallId":"fb59b086-fb0a-4263-ac27-2c53351e44ac-0-279u"}}}
{"type":"emit_inbound","label":"tool-call-completed","frame":{"type":"interaction.update","runId":"run-db8a1002-593e-4baf-9ed1-d837c14643ed","update":{"type":"tool-call-completed","callId":"tool_a4c6ef64-f13c-4738-b527-1aad09b6185","toolCall":{"type":"read","args":{"path":"/tmp/claude-replay-tool_call_read_only/tsconfig.json"},"result":{"status":"success","value":{"content":"{\"compilerOptions\":{\"module\":\"ESNext\",\"strict\":true,\"target\":\"ES2022\"}}","totalLines":1,"fileSize":71}}},"modelCallId":"fb59b086-fb0a-4263-ac27-2c53351e44ac-0-279u"}}}
{"type":"emit_inbound","label":"token-delta","frame":{"type":"interaction.update","runId":"run-db8a1002-593e-4baf-9ed1-d837c14643ed","update":{"type":"token-delta","tokens":17}}}
{"type":"emit_inbound","label":"text-delta","frame":{"type":"interaction.update","runId":"run-db8a1002-593e-4baf-9ed1-d837c14643ed","update":{"type":"text-delta","text":"read"}}}
{"type":"emit_inbound","label":"token-delta","frame":{"type":"interaction.update","runId":"run-db8a1002-593e-4baf-9ed1-d837c14643ed","update":{"type":"token-delta","tokens":1}}}
@@ -392,6 +392,29 @@ describe("terminatePosixOwnedProcessTree", () => {
}),
);
it.live("reports persistent retryable removal failures as removal failures", () =>
Effect.gen(function* () {
const removeError = Object.assign(new Error("cgroup remains busy"), {
code: "EBUSY",
});
const lease: AcpLinuxCgroupLease = {
contains: () => false,
exists: () => true,
path: "/test/t3-acp-busy",
relativePath: "/test/t3-acp-busy",
kill: () => undefined,
populated: () => false,
remove: () => {
throw removeError;
},
};
const error = yield* Effect.flip(terminateLinuxCgroupLease(lease));
expect(error.detail).toBe("Failed to remove ACP cgroup /test/t3-acp-busy");
expect(error.cause).toBe(removeError);
}),
);
it("sends TERM only to the exact captured root while it remains in the child cgroup", () => {
const fixture = makeController({
processes: [server(), identity(100, process.pid, 100, 100, "owned")],
@@ -446,6 +446,7 @@ export function terminateLinuxCgroupLease(
detail: `Failed to ${name} ACP cgroup ${lease.path}`,
});
return Effect.gen(function* () {
let lastRemovalFailure: { readonly cause: unknown } | null = null;
for (let attempt = 0; attempt < 200; attempt += 1) {
if (!lease.exists()) return;
try {
@@ -470,23 +471,29 @@ export function terminateLinuxCgroupLease(
return yield* failure("read state for", cause);
}
if (populated) {
lastRemovalFailure = null;
yield* Effect.sleep("10 millis");
continue;
}
try {
lease.remove();
lastRemovalFailure = null;
} catch (cause) {
const code = (cause as NodeJS.ErrnoException | undefined)?.code;
if (code === "ENOENT" && !lease.exists()) return;
if (code !== "EBUSY" && code !== "ENOTEMPTY" && code !== "ENOENT") {
return yield* failure("remove", cause);
}
lastRemovalFailure = { cause };
}
if (!lease.exists()) return;
yield* Effect.sleep("10 millis");
}
if (lastRemovalFailure !== null) {
return yield* failure("remove", lastRemovalFailure.cause);
}
return yield* new AcpProcessGroupTerminationError({
detail: `ACP cgroup ${lease.path} remained populated after cgroup.kill`,
detail: `ACP cgroup ${lease.path} remained present after cgroup cleanup`,
});
}).pipe(withWallClock);
}
+1
View File
@@ -2377,6 +2377,7 @@ function ChatViewContent(props: ChatViewProps) {
: {
attempts: serverProjection.attempts,
nodes: serverProjection.nodes,
plans: serverProjection.plans,
}),
}),
[optimisticUserMessages, serverVisibleTurnItems, serverProjection, timelineAttachmentUrlById],
+74
View File
@@ -304,6 +304,80 @@ describe("V2 session presentation", () => {
}
});
it("uses projected plan status and file contents in timeline entries", () => {
const now = DateTime.makeUnsafe("2026-06-20T00:00:00.000Z");
const threadId = ThreadId.make("thread-timeline-artifacts");
const runId = RunId.make("run-timeline-artifacts");
const nodeId = NodeId.make("node-timeline-artifacts");
const planId = PlanId.make("plan-timeline-artifacts");
const base = {
threadId,
runId,
nodeId,
providerThreadId: null,
providerTurnId: null,
nativeItemRef: null,
parentItemId: null,
status: "completed" as const,
title: null,
startedAt: now,
completedAt: now,
updatedAt: now,
};
const planItem = {
...base,
id: TurnItemId.make("item-proposed-plan"),
ordinal: 0,
type: "proposed_plan" as const,
planId,
markdown: "Finished plan",
streaming: false,
} satisfies OrchestrationV2TurnItem;
const fileItem = {
...base,
id: TurnItemId.make("item-file-change"),
ordinal: 1,
type: "file_change" as const,
fileName: "src/example.ts",
newStr: "export const answer = 42;\n",
} satisfies OrchestrationV2TurnItem;
const visibleTurnItems: ReadonlyArray<OrchestrationV2ProjectedTurnItem> = [
planItem,
fileItem,
].map((item, position) => ({
position,
visibility: "local",
sourceThreadId: threadId,
sourceItemId: item.id,
item,
}));
const entries = deriveTimelineEntriesFromVisibleTurnItems({
visibleTurnItems,
optimisticMessages: [],
plans: [
{
id: planId,
threadId,
runId,
nodeId,
kind: "proposed_plan",
markdown: planItem.markdown,
status: "completed",
},
],
});
expect(entries[0]?.kind).toBe("proposed-plan");
if (entries[0]?.kind === "proposed-plan") {
expect(entries[0].proposedPlan.status).toBe("completed");
}
expect(entries[1]?.kind).toBe("work");
if (entries[1]?.kind === "work") {
expect(entries[1].entry.detail).toBe(fileItem.newStr);
}
});
it("resolves attempt identity through V2 execution nodes", () => {
const now = DateTime.makeUnsafe("2026-06-20T00:00:00.000Z");
const threadId = ThreadId.make("thread-attempts");
+8 -3
View File
@@ -411,15 +411,17 @@ function projectedWorkEntry(row: OrchestrationV2ProjectedTurnItem): WorkLogEntry
toolTitle: title ?? "Command",
toolData: item,
};
case "file_change":
case "file_change": {
const detail = item.diffStr ?? item.newStr;
return {
...common,
label: title ?? `Changed ${item.fileName}`,
changedFiles: [item.fileName],
...(item.diffStr ? { detail: item.diffStr } : {}),
...(detail ? { detail } : {}),
toolTitle: title ?? "File change",
toolData: item,
};
}
case "file_search":
return {
...common,
@@ -486,6 +488,7 @@ export function deriveTimelineEntriesFromVisibleTurnItems(input: {
readonly attachmentUrlById?: ReadonlyMap<string, string>;
readonly attempts?: ReadonlyArray<OrchestrationV2RunAttempt>;
readonly nodes?: ReadonlyArray<OrchestrationV2ExecutionNode>;
readonly plans?: ReadonlyArray<OrchestrationV2PlanArtifact>;
}): TimelineEntry[] {
const committedMessageIds = new Set<string>();
const entries: TimelineEntry[] = [];
@@ -493,6 +496,7 @@ export function deriveTimelineEntriesFromVisibleTurnItems(input: {
(input.attempts ?? []).map((attempt) => [attempt.rootNodeId, attempt] as const),
);
const nodeById = new Map((input.nodes ?? []).map((node) => [node.id, node] as const));
const planById = new Map((input.plans ?? []).map((plan) => [plan.id, plan] as const));
const resolveAttempt = (item: OrchestrationV2TurnItem): TimelineAttempt | undefined => {
if (item.nodeId === null || item.runId === null) return undefined;
@@ -551,11 +555,12 @@ export function deriveTimelineEntriesFromVisibleTurnItems(input: {
}
if (item.type === "proposed_plan") {
const plan = planById.get(item.planId);
const proposedPlan = {
id: item.planId,
runId: item.runId,
planMarkdown: item.markdown,
status: "active" as const,
status: plan?.kind === "proposed_plan" ? plan.status : ("active" as const),
createdAt,
updatedAt: DateTime.formatIso(item.updatedAt),
};
@@ -6,7 +6,6 @@ import { v2Projection } from "./orchestrationV2TestFixtures.ts";
import {
deriveLatestThreadRun,
deriveThreadActivityRun,
deriveThreadInterruptibleRunId,
deriveThreadRuntime,
threadRuntimeHasInterruptibleRun,
} from "./threadExecution.ts";
@@ -51,7 +50,6 @@ describe("thread execution presentation", () => {
activeRunId: runningRun.id,
});
expect(threadRuntimeHasInterruptibleRun(runtime)).toBe(true);
expect(deriveThreadInterruptibleRunId(projection)).toBe(runningRun.id);
});
it("does not expose a queued-only run as interruptible", () => {
@@ -69,7 +67,6 @@ describe("thread execution presentation", () => {
activeRunId: null,
});
expect(threadRuntimeHasInterruptibleRun(runtime)).toBe(false);
expect(deriveThreadInterruptibleRunId(projection)).toBeNull();
});
it("keeps checkpoint-wait activity visible without exposing a non-functional interrupt", () => {
@@ -87,7 +84,5 @@ describe("thread execution presentation", () => {
activeRunId: null,
});
expect(threadRuntimeHasInterruptibleRun(runtime)).toBe(false);
expect(deriveThreadInterruptibleRunId(projection)).toBeNull();
expect(deriveThreadInterruptibleRunId(null)).toBeNull();
});
});
@@ -78,14 +78,6 @@ export function deriveThreadRuntime(
};
}
export function deriveThreadInterruptibleRunId(
projection: OrchestrationV2ThreadProjection | null | undefined,
): ThreadRuntimeSummary["activeRunId"] {
return projection === null || projection === undefined
? null
: (deriveThreadRuntime(projection)?.activeRunId ?? null);
}
export function threadRuntimeHasInterruptibleRun(
runtime: ThreadRuntimeSummary | null | undefined,
): boolean {