diff --git a/apps/mobile/src/features/threads/ThreadComposer.tsx b/apps/mobile/src/features/threads/ThreadComposer.tsx index ce4e4b7fb0e4b..1153ad498b88a 100644 --- a/apps/mobile/src/features/threads/ThreadComposer.tsx +++ b/apps/mobile/src/features/threads/ThreadComposer.tsx @@ -173,6 +173,8 @@ function useCompactComposerEditor(text: ScaledTextRole, value: string) { const editorStyle = useAnimatedStyle(() => ({ position: "absolute", overflow: "hidden", + // The compact slot is unknown until its first layout, so the editor would draw over the + button. + opacity: isExpanded || editorWidth.value > 0 ? 1 : 0, height, ...(isExpanded ? { left: 14, right: 14 } diff --git a/apps/mobile/src/features/threads/ThreadFeed.tsx b/apps/mobile/src/features/threads/ThreadFeed.tsx index aa551bd291569..d3786eb4932aa 100644 --- a/apps/mobile/src/features/threads/ThreadFeed.tsx +++ b/apps/mobile/src/features/threads/ThreadFeed.tsx @@ -3465,9 +3465,15 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { headerMaterialVisibleRef.current = visible; onHeaderMaterialVisibilityChange?.(visible); }; + const feedThreadKey = scopedThreadKey(props.environmentId, props.threadId); + const [loadedListKey, setLoadedListKey] = useState(null); + // LegendList hides rows until it has scrolled to the end, but not its header. + const settling = props.feed.length > 0 && loadedListKey !== feedThreadKey; const handleMetricsChange = () => { const state = listRef.current?.getState(); - if (state) onIsAtEndChange?.(state.isAtEnd); + // Offset 0 before the first positioning, and the gaps while rows measure in, are not the + // user leaving the end; only a scroll away stops end following. + if (state) onIsAtEndChange?.(settling || state.isAtEnd || state.isFollowingEnd); }; const handleScroll = (event: NativeSyntheticEvent) => { reportHeaderMaterialVisibility( @@ -3482,6 +3488,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { handleMetricsChange(); const stops = [ state.listen("isAtEnd", handleMetricsChange), + state.listen("isFollowingEnd", handleMetricsChange), state.listen("totalSize", handleMetricsChange), state.listen("footerSize", handleMetricsChange), state.listen("headerSize", handleMetricsChange), @@ -3490,7 +3497,6 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { for (const stop of stops) stop(); }; }, [listRef, handleMetricsChange]); - const feedThreadKey = scopedThreadKey(props.environmentId, props.threadId); const [workGroupScrollPositions] = useState( () => new Map(), ); @@ -3498,7 +3504,6 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { // Opening at a message: once the filled list has loaded, the render that sees // the jump unfolds a run hiding the message and stops following the end, so // the committed list holds the target row with end maintenance off. - const [loadedListKey, setLoadedListKey] = useState(null); const { jumpToMessageId } = props; const jumpReady = !!jumpToMessageId && loadedListKey === feedThreadKey; if (jumpReady && revealedMessageId !== jumpToMessageId) { @@ -3993,7 +3998,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { onScroll={handleScroll} scrollEventThrottle={16} ListHeaderComponent={ - <> + {usesNativeAutomaticInsets ? null : } {setupAnchorIndex < 0 && props.worktreeSetup ? ( @@ -4003,7 +4008,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { {props.historyControls ? ( ) : null} - + } ListFooterComponent={ props.pendingHandoff ? ( diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts index c52cb3900f253..43cddbef31e11 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts @@ -3384,19 +3384,30 @@ describe("AcpAdapterV2", () => { yield* replay("user_message_chunk", "u1", "lo"); yield* replay("agent_message_chunk", "a1", "hi"); yield* replay("user_message_chunk", "u2", "next"); - yield* replay("agent_message_chunk", "a1", " there"); + yield* replay("agent_message_chunk", "a1", " "); + yield* replay("agent_message_chunk", "a1", "there"); + yield* replay("agent_message_chunk", "a3", "\t"); + yield* replay("agent_message_chunk", "a3", "code"); + yield* replay("agent_message_chunk", "a4", "\n\n"); const first = yield* runtime.readThreadSnapshot({ providerThread }); yield* replay("agent_message_chunk", "a2", "done"); - yield* replay("user_message_chunk", "u2", " one"); + yield* replay("user_message_chunk", "u2", "\n"); + yield* replay("user_message_chunk", "u2", "\tone"); const second = yield* runtime.readThreadSnapshot({ providerThread }); const texts = (snapshot: typeof first) => snapshot.messages.map((message) => `${message.role}:${message.text}`); - assert.deepEqual(texts(first), ["user:hello", "assistant:hi there", "user:next"]); + assert.deepEqual(texts(first), [ + "user:hello", + "assistant:hi there", + "user:next", + "assistant:\tcode", + ]); assert.deepEqual(texts(second), [ "user:hello", "assistant:hi there", - "user:next one", + "user:next\n\tone", + "assistant:\tcode", "assistant:done", ]); }).pipe(Effect.provide(layerTest), Effect.scoped), diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/multi_turn/pi_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/multi_turn/pi_transcript.ndjson index 5841abd415c1d..7203e22530de3 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/multi_turn/pi_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/multi_turn/pi_transcript.ndjson @@ -41,6 +41,8 @@ {"type":"emit_inbound","label":"response:get_entries","frame":{"id":"t3-7","type":"response","command":"get_entries","success":true,"data":{"entries":[{"type":"model_change","id":"5e37f535","parentId":"f3bce6ef","timestamp":"2026-01-01T00:00:00.437Z","provider":"openrouter","modelId":"deepseek/deepseek-v4-flash"},{"type":"session_info","id":"16d089a9","parentId":"5e37f535","timestamp":"2026-01-01T00:00:00.440Z","name":"Replay fixture: multi_turn"},{"type":"message","id":"ea6f5949","parentId":"16d089a9","timestamp":"2026-01-01T00:00:00.448Z","message":{"role":"system","content":"","sections":{"preamble":"","tools":"","rules":"","docs":"","cwd":""},"timestamp":1790898591750,"toolsAdded":[{"name":"read","description":"Read the contents of a file. Supports text files and images (jpg, png, gif, webp, bmp). Images are sent as attachments. For text files, output is truncated to 2000 lines or 50KB (whichever is hit first). Use offset/limit for large files. When you need the full file, continue with offset until complete.","parameters":{"type":"object","required":["path"],"properties":{"path":{"type":"string","description":"Path to the file to read (relative or absolute)"},"offset":{"type":"number","description":"Line number to start reading from (1-indexed)"},"limit":{"type":"number","description":"Maximum number of lines to read"}}},"constrainedSampling":{"type":"json_schema","strict":"prefer"}},{"name":"bash","description":"Execute a bash command in the current working directory. Returns stdout and stderr. Output is truncated to last 2000 lines or 50KB (whichever is hit first). If truncated, full output is saved to a temp file. Optionally provide a timeout in seconds.","parameters":{"type":"object","required":["command"],"properties":{"command":{"type":"string","description":"Shell command to execute"},"timeout":{"type":"number","description":"Timeout in seconds (optional, no default timeout)"}}},"constrainedSampling":{"type":"json_schema","strict":"prefer"}},{"name":"edit","description":"Edit a single file using exact text replacement. Every edits[].oldText must match a unique, non-overlapping region of the original file. If two changes affect the same block or nearby lines, merge them into one edit instead of emitting overlapping edits. Do not include large unchanged regions just to connect distant changes.","parameters":{"type":"object","required":["path","edits"],"properties":{"path":{"type":"string","description":"Path to the file to edit (relative or absolute)"},"edits":{"type":"array","items":{"type":"object","required":["oldText","newText"],"properties":{"oldText":{"type":"string","description":"Exact text for one targeted replacement. It must be unique in the original file and must not overlap with any other edits[].oldText in the same call."},"newText":{"type":"string","description":"Replacement text for this targeted edit."}}},"description":"One or more targeted replacements. Each edit is matched against the original file, not incrementally. Do not include overlapping or nested edits. If two changes touch the same block or nearby lines, merge them into one edit instead."}}},"constrainedSampling":{"type":"json_schema","strict":"prefer"}},{"name":"write","description":"Write content to a file. Creates the file if it doesn't exist, overwrites if it does. Automatically creates parent directories.","parameters":{"type":"object","required":["path","content"],"properties":{"path":{"type":"string","description":"Path to the file to write (relative or absolute)"},"content":{"type":"string","description":"Content to write to the file"}}},"constrainedSampling":{"type":"json_schema","strict":"prefer"}}]}},{"type":"message","id":"ff895990","parentId":"ea6f5949","timestamp":"2026-01-01T00:00:00.448Z","message":{"role":"user","content":[{"type":"text","text":"Respond with exactly: first fixture turn complete"}],"timestamp":1767225600444}},{"type":"message","id":"5c0d3865","parentId":"ff895990","timestamp":"2026-01-01T00:00:01.723Z","message":{"role":"assistant","content":[{"type":"thinking","thinking":"The user wants me to respond with exactly: \"first fixture turn complete\"","thinkingSignature":""},{"type":"text","text":"first fixture turn complete"}],"api":"openai-completions","provider":"openrouter","model":"deepseek/deepseek-v4-flash","usage":{"input":1787,"output":21,"cacheRead":0,"cacheWrite":0,"reasoning":18,"totalTokens":1808,"cost":{"input":0.00007480382,"output":0.0000017581199999999999,"cacheRead":0,"cacheWrite":0,"total":0.00007656194}},"stopReason":"stop","timestamp":1767225600465,"responseId":"gen-1790898592-RtbvUBJEB0AHaUCPMqrg","rawStopReason":"stop","thinkingLevel":"high"}}],"leafId":"5c0d3865"}}} {"type":"expect_outbound","label":"get_session_stats","frame":{"type":"get_session_stats","id":"t3-8"}} {"type":"emit_inbound","label":"response:get_session_stats","frame":{"id":"t3-8","type":"response","command":"get_session_stats","success":true,"data":{"sessionFile":"/pi-sessions/session-1.jsonl","sessionId":"00000000-0000-4000-8000-000000000002","userMessages":1,"assistantMessages":1,"toolCalls":0,"toolResults":0,"totalMessages":3,"tokens":{"input":1787,"output":21,"cacheRead":0,"cacheWrite":0,"total":1808},"cost":0.00007656194,"contextUsage":{"tokens":1808,"contextWindow":1048576,"percent":0.17242431640625}}}} +{"type":"expect_outbound","label":"get_state","frame":{"type":"get_state","id":"t3-1000"}} +{"type":"emit_inbound","label":"response:get_state","frame":{"id":"t3-1000","type":"response","command":"get_state","success":true,"data":{"model":{"type":"chat","id":"deepseek/deepseek-v4-flash","name":"DeepSeek: DeepSeek V4 Flash 0423","api":"openai-completions","baseUrl":"https://openrouter.ai/api/v1","provider":"openrouter","reasoning":true,"thinkingLevelMap":{"off":"none","minimal":null,"low":null,"medium":null,"high":"high","xhigh":"xhigh","max":null},"input":["text"],"cost":{"input":0.04186,"output":0.08372,"cacheRead":0.008372,"cacheWrite":0},"contextWindow":1048576,"maxTokens":131072,"compat":{"supportsDeveloperRole":false,"thinkingFormat":"openrouter","supportsStrictMode":true,"sendSessionAffinityHeaders":true,"requiresReasoningContentOnAssistantMessages":true}},"thinkingLevel":"high","isStreaming":false,"isCompacting":false,"steeringMode":"one-at-a-time","followUpMode":"one-at-a-time","sessionFile":"/pi-sessions/session-1.jsonl","sessionId":"00000000-0000-4000-8000-000000000002","sessionName":"Replay fixture: multi_turn","autoCompactionEnabled":true,"messageCount":3,"pendingMessageCount":0}}} {"type":"expect_outbound","label":"prompt","frame":{"type":"prompt","message":"Respond with exactly: second fixture turn complete","streamingBehavior":"steer"}} {"type":"emit_inbound","label":"response:prompt","frame":{"type":"response","command":"prompt","success":true,"data":{"disposition":"started"}}} {"type":"emit_inbound","label":"agent_start","frame":{"type":"agent_start"}} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/pi_compaction/pi_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/pi_compaction/pi_transcript.ndjson index 39243d970f6d9..c7cdd0173ed88 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/pi_compaction/pi_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/pi_compaction/pi_transcript.ndjson @@ -44,6 +44,8 @@ {"type":"emit_inbound","label":"response:get_entries","frame":{"id":"t3-7","type":"response","command":"get_entries","success":true,"data":{"entries":[{"type":"model_change","id":"2650a6dd","parentId":"88d9853d","timestamp":"2026-01-01T00:00:00.460Z","provider":"openrouter","modelId":"deepseek/deepseek-v4-flash"},{"type":"session_info","id":"b93ec51b","parentId":"2650a6dd","timestamp":"2026-01-01T00:00:00.466Z","name":"Replay fixture: pi_compaction"},{"type":"message","id":"22b953a8","parentId":"b93ec51b","timestamp":"2026-01-01T00:00:00.478Z","message":{"role":"system","content":"","sections":{"preamble":"","tools":"","rules":"","docs":"","cwd":""},"timestamp":1790898591700,"toolsAdded":[{"name":"read","description":"Read the contents of a file. Supports text files and images (jpg, png, gif, webp, bmp). Images are sent as attachments. For text files, output is truncated to 2000 lines or 50KB (whichever is hit first). Use offset/limit for large files. When you need the full file, continue with offset until complete.","parameters":{"type":"object","required":["path"],"properties":{"path":{"type":"string","description":"Path to the file to read (relative or absolute)"},"offset":{"type":"number","description":"Line number to start reading from (1-indexed)"},"limit":{"type":"number","description":"Maximum number of lines to read"}}},"constrainedSampling":{"type":"json_schema","strict":"prefer"}},{"name":"bash","description":"Execute a bash command in the current working directory. Returns stdout and stderr. Output is truncated to last 2000 lines or 50KB (whichever is hit first). If truncated, full output is saved to a temp file. Optionally provide a timeout in seconds.","parameters":{"type":"object","required":["command"],"properties":{"command":{"type":"string","description":"Shell command to execute"},"timeout":{"type":"number","description":"Timeout in seconds (optional, no default timeout)"}}},"constrainedSampling":{"type":"json_schema","strict":"prefer"}},{"name":"edit","description":"Edit a single file using exact text replacement. Every edits[].oldText must match a unique, non-overlapping region of the original file. If two changes affect the same block or nearby lines, merge them into one edit instead of emitting overlapping edits. Do not include large unchanged regions just to connect distant changes.","parameters":{"type":"object","required":["path","edits"],"properties":{"path":{"type":"string","description":"Path to the file to edit (relative or absolute)"},"edits":{"type":"array","items":{"type":"object","required":["oldText","newText"],"properties":{"oldText":{"type":"string","description":"Exact text for one targeted replacement. It must be unique in the original file and must not overlap with any other edits[].oldText in the same call."},"newText":{"type":"string","description":"Replacement text for this targeted edit."}}},"description":"One or more targeted replacements. Each edit is matched against the original file, not incrementally. Do not include overlapping or nested edits. If two changes touch the same block or nearby lines, merge them into one edit instead."}}},"constrainedSampling":{"type":"json_schema","strict":"prefer"}},{"name":"write","description":"Write content to a file. Creates the file if it doesn't exist, overwrites if it does. Automatically creates parent directories.","parameters":{"type":"object","required":["path","content"],"properties":{"path":{"type":"string","description":"Path to the file to write (relative or absolute)"},"content":{"type":"string","description":"Content to write to the file"}}},"constrainedSampling":{"type":"json_schema","strict":"prefer"}}]}},{"type":"message","id":"dc5da04b","parentId":"22b953a8","timestamp":"2026-01-01T00:00:00.478Z","message":{"role":"user","content":[{"type":"text","text":"Remember the opaque marker compaction-marker-4Z7Q for later. Respond with exactly: compaction marker stored"}],"timestamp":1767225600474}},{"type":"message","id":"9923aaa9","parentId":"dc5da04b","timestamp":"2026-01-01T00:00:01.844Z","message":{"role":"assistant","content":[{"type":"thinking","thinking":"The user wants me to remember the opaque marker \"compaction-marker-4Z7Q\" and respond with exactly \"compaction marker stored\".","thinkingSignature":""},{"type":"text","text":"compaction marker stored"}],"api":"openai-completions","provider":"openrouter","model":"deepseek/deepseek-v4-flash","usage":{"input":1803,"output":36,"cacheRead":0,"cacheWrite":0,"reasoning":32,"totalTokens":1839,"cost":{"input":0.00007547358,"output":0.0000030139199999999998,"cacheRead":0,"cacheWrite":0,"total":0.0000784875}},"stopReason":"stop","timestamp":1767225600495,"responseId":"gen-1790898592-uinD76Ni7S1SCFQBzPIp","rawStopReason":"stop","thinkingLevel":"high"}}],"leafId":"9923aaa9"}}} {"type":"expect_outbound","label":"get_session_stats","frame":{"type":"get_session_stats","id":"t3-8"}} {"type":"emit_inbound","label":"response:get_session_stats","frame":{"id":"t3-8","type":"response","command":"get_session_stats","success":true,"data":{"sessionFile":"/pi-sessions/session-1.jsonl","sessionId":"00000000-0000-4000-8000-000000000002","userMessages":1,"assistantMessages":1,"toolCalls":0,"toolResults":0,"totalMessages":3,"tokens":{"input":1803,"output":36,"cacheRead":0,"cacheWrite":0,"total":1839},"cost":0.0000784875,"contextUsage":{"tokens":1839,"contextWindow":1048576,"percent":0.17538070678710938}}}} +{"type":"expect_outbound","label":"get_state","frame":{"type":"get_state","id":"t3-1000"}} +{"type":"emit_inbound","label":"response:get_state","frame":{"id":"t3-1000","type":"response","command":"get_state","success":true,"data":{"model":{"type":"chat","id":"deepseek/deepseek-v4-flash","name":"DeepSeek: DeepSeek V4 Flash 0423","api":"openai-completions","baseUrl":"https://openrouter.ai/api/v1","provider":"openrouter","reasoning":true,"thinkingLevelMap":{"off":"none","minimal":null,"low":null,"medium":null,"high":"high","xhigh":"xhigh","max":null},"input":["text"],"cost":{"input":0.04186,"output":0.08372,"cacheRead":0.008372,"cacheWrite":0},"contextWindow":1048576,"maxTokens":131072,"compat":{"supportsDeveloperRole":false,"thinkingFormat":"openrouter","supportsStrictMode":true,"sendSessionAffinityHeaders":true,"requiresReasoningContentOnAssistantMessages":true}},"thinkingLevel":"high","isStreaming":false,"isCompacting":false,"steeringMode":"one-at-a-time","followUpMode":"one-at-a-time","sessionFile":"/pi-sessions/session-1.jsonl","sessionId":"00000000-0000-4000-8000-000000000002","sessionName":"Replay fixture: pi_compaction","autoCompactionEnabled":true,"messageCount":3,"pendingMessageCount":0}}} {"type":"expect_outbound","label":"compact","frame":{"type":"compact","customInstructions":"keep the opaque marker compaction-marker-4Z7Q"}} {"type":"emit_inbound","label":"compaction_start","frame":{"type":"compaction_start","reason":"manual"}} {"type":"emit_inbound","label":"compaction_end","frame":{"type":"compaction_end","reason":"manual","aborted":false,"willRetry":false,"errorMessage":"Compaction failed: Nothing to compact (session too small)"}} @@ -56,6 +58,8 @@ {"type":"emit_inbound","label":"response:get_entries","frame":{"id":"t3-11","type":"response","command":"get_entries","success":true,"data":{"entries":[],"leafId":"9923aaa9"}}} {"type":"expect_outbound","label":"get_session_stats","frame":{"type":"get_session_stats","id":"t3-12"}} {"type":"emit_inbound","label":"response:get_session_stats","frame":{"id":"t3-12","type":"response","command":"get_session_stats","success":true,"data":{"sessionFile":"/pi-sessions/session-1.jsonl","sessionId":"00000000-0000-4000-8000-000000000002","userMessages":1,"assistantMessages":1,"toolCalls":0,"toolResults":0,"totalMessages":3,"tokens":{"input":1803,"output":36,"cacheRead":0,"cacheWrite":0,"total":1839},"cost":0.0000784875,"contextUsage":{"tokens":1839,"contextWindow":1048576,"percent":0.17538070678710938}}}} +{"type":"expect_outbound","label":"get_state","frame":{"type":"get_state","id":"t3-1001"}} +{"type":"emit_inbound","label":"response:get_state","frame":{"id":"t3-1001","type":"response","command":"get_state","success":true,"data":{"model":{"type":"chat","id":"deepseek/deepseek-v4-flash","name":"DeepSeek: DeepSeek V4 Flash 0423","api":"openai-completions","baseUrl":"https://openrouter.ai/api/v1","provider":"openrouter","reasoning":true,"thinkingLevelMap":{"off":"none","minimal":null,"low":null,"medium":null,"high":"high","xhigh":"xhigh","max":null},"input":["text"],"cost":{"input":0.04186,"output":0.08372,"cacheRead":0.008372,"cacheWrite":0},"contextWindow":1048576,"maxTokens":131072,"compat":{"supportsDeveloperRole":false,"thinkingFormat":"openrouter","supportsStrictMode":true,"sendSessionAffinityHeaders":true,"requiresReasoningContentOnAssistantMessages":true}},"thinkingLevel":"high","isStreaming":false,"isCompacting":false,"steeringMode":"one-at-a-time","followUpMode":"one-at-a-time","sessionFile":"/pi-sessions/session-1.jsonl","sessionId":"00000000-0000-4000-8000-000000000002","sessionName":"Replay fixture: pi_compaction","autoCompactionEnabled":true,"messageCount":3,"pendingMessageCount":0}}} {"type":"expect_outbound","label":"prompt","frame":{"type":"prompt","message":"Respond with exactly: second compaction fixture turn","streamingBehavior":"steer"}} {"type":"emit_inbound","label":"response:prompt","frame":{"type":"response","command":"prompt","success":true,"data":{"disposition":"started"}}} {"type":"emit_inbound","label":"agent_start","frame":{"type":"agent_start"}} @@ -82,6 +86,8 @@ {"type":"emit_inbound","label":"response:get_entries","frame":{"id":"t3-14","type":"response","command":"get_entries","success":true,"data":{"entries":[{"type":"message","id":"de423e78","parentId":"9923aaa9","timestamp":"2026-01-01T00:00:02.437Z","message":{"role":"user","content":[{"type":"text","text":"Respond with exactly: second compaction fixture turn"}],"timestamp":1767225602435}},{"type":"message","id":"70c802be","parentId":"de423e78","timestamp":"2026-01-01T00:00:03.192Z","message":{"role":"assistant","content":[{"type":"thinking","thinking":"The user wants me to respond with exactly \"second compaction fixture turn\".","thinkingSignature":""},{"type":"text","text":"second compaction fixture turn"}],"api":"openai-completions","provider":"openrouter","model":"deepseek/deepseek-v4-flash","usage":{"input":58,"output":20,"cacheRead":1792,"cacheWrite":0,"reasoning":19,"totalTokens":1870,"cost":{"input":0.00000242788,"output":0.0000016744,"cacheRead":0.000015002623999999998,"cacheWrite":0,"total":0.000019104903999999998}},"stopReason":"stop","timestamp":1767225602438,"responseId":"gen-1790898593-ijLmDH6S1P8UCX8xelRy","rawStopReason":"stop","thinkingLevel":"high"}}],"leafId":"70c802be"}}} {"type":"expect_outbound","label":"get_session_stats","frame":{"type":"get_session_stats","id":"t3-15"}} {"type":"emit_inbound","label":"response:get_session_stats","frame":{"id":"t3-15","type":"response","command":"get_session_stats","success":true,"data":{"sessionFile":"/pi-sessions/session-1.jsonl","sessionId":"00000000-0000-4000-8000-000000000002","userMessages":2,"assistantMessages":2,"toolCalls":0,"toolResults":0,"totalMessages":5,"tokens":{"input":1861,"output":56,"cacheRead":1792,"cacheWrite":0,"total":3709},"cost":0.00009759240400000001,"contextUsage":{"tokens":1870,"contextWindow":1048576,"percent":0.17833709716796875}}}} +{"type":"expect_outbound","label":"get_state","frame":{"type":"get_state","id":"t3-1002"}} +{"type":"emit_inbound","label":"response:get_state","frame":{"id":"t3-1002","type":"response","command":"get_state","success":true,"data":{"model":{"type":"chat","id":"deepseek/deepseek-v4-flash","name":"DeepSeek: DeepSeek V4 Flash 0423","api":"openai-completions","baseUrl":"https://openrouter.ai/api/v1","provider":"openrouter","reasoning":true,"thinkingLevelMap":{"off":"none","minimal":null,"low":null,"medium":null,"high":"high","xhigh":"xhigh","max":null},"input":["text"],"cost":{"input":0.04186,"output":0.08372,"cacheRead":0.008372,"cacheWrite":0},"contextWindow":1048576,"maxTokens":131072,"compat":{"supportsDeveloperRole":false,"thinkingFormat":"openrouter","supportsStrictMode":true,"sendSessionAffinityHeaders":true,"requiresReasoningContentOnAssistantMessages":true}},"thinkingLevel":"high","isStreaming":false,"isCompacting":false,"steeringMode":"one-at-a-time","followUpMode":"one-at-a-time","sessionFile":"/pi-sessions/session-1.jsonl","sessionId":"00000000-0000-4000-8000-000000000002","sessionName":"Replay fixture: pi_compaction","autoCompactionEnabled":true,"messageCount":5,"pendingMessageCount":0}}} {"type":"expect_outbound","label":"prompt","frame":{"type":"prompt","message":"Respond with exactly: third compaction fixture turn","streamingBehavior":"steer"}} {"type":"emit_inbound","label":"response:prompt","frame":{"type":"response","command":"prompt","success":true,"data":{"disposition":"started"}}} {"type":"emit_inbound","label":"agent_start","frame":{"type":"agent_start"}} @@ -108,6 +114,8 @@ {"type":"emit_inbound","label":"response:get_entries","frame":{"id":"t3-17","type":"response","command":"get_entries","success":true,"data":{"entries":[{"type":"message","id":"2f434373","parentId":"70c802be","timestamp":"2026-01-01T00:00:03.593Z","message":{"role":"user","content":[{"type":"text","text":"Respond with exactly: third compaction fixture turn"}],"timestamp":1767225603592}},{"type":"message","id":"705e1e5c","parentId":"2f434373","timestamp":"2026-01-01T00:00:04.181Z","message":{"role":"assistant","content":[{"type":"thinking","thinking":"The user wants me to respond with exactly \"third compaction fixture turn\".","thinkingSignature":""},{"type":"text","text":"third compaction fixture turn"}],"api":"openai-completions","provider":"openrouter","model":"deepseek/deepseek-v4-flash","usage":{"input":89,"output":20,"cacheRead":1792,"cacheWrite":0,"reasoning":19,"totalTokens":1901,"cost":{"input":0.00000372554,"output":0.0000016744,"cacheRead":0.000015002623999999998,"cacheWrite":0,"total":0.000020402563999999998}},"stopReason":"stop","timestamp":1767225603598,"responseId":"gen-1790898594-VqYDa0EHiaTKcdke18Tb","rawStopReason":"stop","thinkingLevel":"high"}}],"leafId":"705e1e5c"}}} {"type":"expect_outbound","label":"get_session_stats","frame":{"type":"get_session_stats","id":"t3-18"}} {"type":"emit_inbound","label":"response:get_session_stats","frame":{"id":"t3-18","type":"response","command":"get_session_stats","success":true,"data":{"sessionFile":"/pi-sessions/session-1.jsonl","sessionId":"00000000-0000-4000-8000-000000000002","userMessages":3,"assistantMessages":3,"toolCalls":0,"toolResults":0,"totalMessages":7,"tokens":{"input":1950,"output":76,"cacheRead":3584,"cacheWrite":0,"total":5610},"cost":0.000117994968,"contextUsage":{"tokens":1901,"contextWindow":1048576,"percent":0.18129348754882812}}}} +{"type":"expect_outbound","label":"get_state","frame":{"type":"get_state","id":"t3-1003"}} +{"type":"emit_inbound","label":"response:get_state","frame":{"id":"t3-1003","type":"response","command":"get_state","success":true,"data":{"model":{"type":"chat","id":"deepseek/deepseek-v4-flash","name":"DeepSeek: DeepSeek V4 Flash 0423","api":"openai-completions","baseUrl":"https://openrouter.ai/api/v1","provider":"openrouter","reasoning":true,"thinkingLevelMap":{"off":"none","minimal":null,"low":null,"medium":null,"high":"high","xhigh":"xhigh","max":null},"input":["text"],"cost":{"input":0.04186,"output":0.08372,"cacheRead":0.008372,"cacheWrite":0},"contextWindow":1048576,"maxTokens":131072,"compat":{"supportsDeveloperRole":false,"thinkingFormat":"openrouter","supportsStrictMode":true,"sendSessionAffinityHeaders":true,"requiresReasoningContentOnAssistantMessages":true}},"thinkingLevel":"high","isStreaming":false,"isCompacting":false,"steeringMode":"one-at-a-time","followUpMode":"one-at-a-time","sessionFile":"/pi-sessions/session-1.jsonl","sessionId":"00000000-0000-4000-8000-000000000002","sessionName":"Replay fixture: pi_compaction","autoCompactionEnabled":true,"messageCount":7,"pendingMessageCount":0}}} {"type":"expect_outbound","label":"compact","frame":{"type":"compact"}} {"type":"emit_inbound","label":"compaction_start","frame":{"type":"compaction_start","reason":"manual"}} {"type":"emit_inbound","label":"compaction_end","frame":{"type":"compaction_end","reason":"manual","result":{"summary":"## Goal\nThe user asked the assistant to remember the opaque marker \"compaction-marker-4Z7Q\" for later use in the conversation.\n\n## Constraints & Preferences\n- The assistant was required to respond with exactly \"compaction marker stored\" (which it did).\n\n## Progress\n### Done\n- [x] Acknowledged and stored the marker \"compaction-marker-4Z7Q\"\n- [x] Responded with exactly \"compaction marker stored\"\n\n### In Progress\n- (none)\n\n### Blocked\n- (none)\n\n## Key Decisions\n- **Remember the marker**: The value \"compaction-marker-4Z7Q\" is to be retained as the opaque marker for later reference.\n\n## Next Steps\n1. When the user later references \"the marker\" or asks to use it, recall that the marker value is \"compaction-marker-4Z7Q\".\n2. Use this marker in whatever context the user requests (e.g., compaction operations).\n\n## Critical Context\n- Opaque marker value: **compaction-marker-4Z7Q**\n\n---\n\n**Turn Context (split turn):**\n\n# Conversation Summary\n\n## Original Request\nThe user asked the assistant to \"Respond with exactly: second compaction fixture turn\" — i.e., to reply using only that exact phrase.\n\n## Progress So Far\n- The user issued a single directive requiring a verbatim response of the phrase \"second compaction fixture turn.\"\n- No additional work, decisions, or content has been provided in this segment.\n\n## Context Needed to Continue\n- The required exact response text is: **second compaction fixture turn**\n- The user's instruction is to output nothing beyond that exact phrase.","firstKeptEntryId":"70c802be","tokensBefore":1901,"estimatedTokensAfter":1890,"usage":{"input":0,"output":1003,"cacheRead":693,"cacheWrite":0,"reasoning":660,"totalTokens":1696,"cost":{"input":0,"output":0.00008397116,"cacheRead":0.000005801795999999999,"cacheWrite":0,"total":0.000089772956}},"details":{"readFiles":[],"modifiedFiles":[]}},"aborted":false,"willRetry":false}} @@ -120,6 +128,8 @@ {"type":"emit_inbound","label":"response:get_entries","frame":{"id":"t3-21","type":"response","command":"get_entries","success":true,"data":{"entries":[{"type":"compaction","id":"f5058450","parentId":"705e1e5c","timestamp":"2026-01-01T00:00:34.035Z","summary":"## Goal\nThe user asked the assistant to remember the opaque marker \"compaction-marker-4Z7Q\" for later use in the conversation.\n\n## Constraints & Preferences\n- The assistant was required to respond with exactly \"compaction marker stored\" (which it did).\n\n## Progress\n### Done\n- [x] Acknowledged and stored the marker \"compaction-marker-4Z7Q\"\n- [x] Responded with exactly \"compaction marker stored\"\n\n### In Progress\n- (none)\n\n### Blocked\n- (none)\n\n## Key Decisions\n- **Remember the marker**: The value \"compaction-marker-4Z7Q\" is to be retained as the opaque marker for later reference.\n\n## Next Steps\n1. When the user later references \"the marker\" or asks to use it, recall that the marker value is \"compaction-marker-4Z7Q\".\n2. Use this marker in whatever context the user requests (e.g., compaction operations).\n\n## Critical Context\n- Opaque marker value: **compaction-marker-4Z7Q**\n\n---\n\n**Turn Context (split turn):**\n\n# Conversation Summary\n\n## Original Request\nThe user asked the assistant to \"Respond with exactly: second compaction fixture turn\" — i.e., to reply using only that exact phrase.\n\n## Progress So Far\n- The user issued a single directive requiring a verbatim response of the phrase \"second compaction fixture turn.\"\n- No additional work, decisions, or content has been provided in this segment.\n\n## Context Needed to Continue\n- The required exact response text is: **second compaction fixture turn**\n- The user's instruction is to output nothing beyond that exact phrase.","firstKeptEntryId":"70c802be","tokensBefore":1901,"details":{"readFiles":[],"modifiedFiles":[]},"usage":{"input":0,"output":1003,"cacheRead":693,"cacheWrite":0,"reasoning":660,"totalTokens":1696,"cost":{"input":0,"output":0.00008397116,"cacheRead":0.000005801795999999999,"cacheWrite":0,"total":0.000089772956}},"fromHook":false,"systemMessage":{"role":"system","content":"","sections":{"preamble":"","tools":"","rules":"","docs":"","cwd":""},"toolsAdded":[{"name":"read","description":"Read the contents of a file. Supports text files and images (jpg, png, gif, webp, bmp). Images are sent as attachments. For text files, output is truncated to 2000 lines or 50KB (whichever is hit first). Use offset/limit for large files. When you need the full file, continue with offset until complete.","parameters":{"type":"object","required":["path"],"properties":{"path":{"type":"string","description":"Path to the file to read (relative or absolute)"},"offset":{"type":"number","description":"Line number to start reading from (1-indexed)"},"limit":{"type":"number","description":"Maximum number of lines to read"}}},"constrainedSampling":{"type":"json_schema","strict":"prefer"}},{"name":"bash","description":"Execute a bash command in the current working directory. Returns stdout and stderr. Output is truncated to last 2000 lines or 50KB (whichever is hit first). If truncated, full output is saved to a temp file. Optionally provide a timeout in seconds.","parameters":{"type":"object","required":["command"],"properties":{"command":{"type":"string","description":"Shell command to execute"},"timeout":{"type":"number","description":"Timeout in seconds (optional, no default timeout)"}}},"constrainedSampling":{"type":"json_schema","strict":"prefer"}},{"name":"edit","description":"Edit a single file using exact text replacement. Every edits[].oldText must match a unique, non-overlapping region of the original file. If two changes affect the same block or nearby lines, merge them into one edit instead of emitting overlapping edits. Do not include large unchanged regions just to connect distant changes.","parameters":{"type":"object","required":["path","edits"],"properties":{"path":{"type":"string","description":"Path to the file to edit (relative or absolute)"},"edits":{"type":"array","items":{"type":"object","required":["oldText","newText"],"properties":{"oldText":{"type":"string","description":"Exact text for one targeted replacement. It must be unique in the original file and must not overlap with any other edits[].oldText in the same call."},"newText":{"type":"string","description":"Replacement text for this targeted edit."}}},"description":"One or more targeted replacements. Each edit is matched against the original file, not incrementally. Do not include overlapping or nested edits. If two changes touch the same block or nearby lines, merge them into one edit instead."}}},"constrainedSampling":{"type":"json_schema","strict":"prefer"}},{"name":"write","description":"Write content to a file. Creates the file if it doesn't exist, overwrites if it does. Automatically creates parent directories.","parameters":{"type":"object","required":["path","content"],"properties":{"path":{"type":"string","description":"Path to the file to write (relative or absolute)"},"content":{"type":"string","description":"Content to write to the file"}}},"constrainedSampling":{"type":"json_schema","strict":"prefer"}}],"timestamp":1790898625260}}],"leafId":"f5058450"}}} {"type":"expect_outbound","label":"get_session_stats","frame":{"type":"get_session_stats","id":"t3-22"}} {"type":"emit_inbound","label":"response:get_session_stats","frame":{"id":"t3-22","type":"response","command":"get_session_stats","success":true,"data":{"sessionFile":"/pi-sessions/session-1.jsonl","sessionId":"00000000-0000-4000-8000-000000000002","userMessages":3,"assistantMessages":3,"toolCalls":0,"toolResults":0,"totalMessages":7,"tokens":{"input":1950,"output":1079,"cacheRead":4277,"cacheWrite":0,"total":7306},"cost":0.000207767924,"contextUsage":{"tokens":null,"contextWindow":1048576,"percent":null}}}} +{"type":"expect_outbound","label":"get_state","frame":{"type":"get_state","id":"t3-1004"}} +{"type":"emit_inbound","label":"response:get_state","frame":{"id":"t3-1004","type":"response","command":"get_state","success":true,"data":{"model":{"type":"chat","id":"deepseek/deepseek-v4-flash","name":"DeepSeek: DeepSeek V4 Flash 0423","api":"openai-completions","baseUrl":"https://openrouter.ai/api/v1","provider":"openrouter","reasoning":true,"thinkingLevelMap":{"off":"none","minimal":null,"low":null,"medium":null,"high":"high","xhigh":"xhigh","max":null},"input":["text"],"cost":{"input":0.04186,"output":0.08372,"cacheRead":0.008372,"cacheWrite":0},"contextWindow":1048576,"maxTokens":131072,"compat":{"supportsDeveloperRole":false,"thinkingFormat":"openrouter","supportsStrictMode":true,"sendSessionAffinityHeaders":true,"requiresReasoningContentOnAssistantMessages":true}},"thinkingLevel":"high","isStreaming":false,"isCompacting":false,"steeringMode":"one-at-a-time","followUpMode":"one-at-a-time","sessionFile":"/pi-sessions/session-1.jsonl","sessionId":"00000000-0000-4000-8000-000000000002","sessionName":"Replay fixture: pi_compaction","autoCompactionEnabled":true,"messageCount":5,"pendingMessageCount":0}}} {"type":"expect_outbound","label":"prompt","frame":{"type":"prompt","message":"Return the opaque marker I asked you to remember. Respond with only the marker.","streamingBehavior":"steer"}} {"type":"emit_inbound","label":"response:prompt","frame":{"type":"response","command":"prompt","success":true,"data":{"disposition":"started"}}} {"type":"emit_inbound","label":"agent_start","frame":{"type":"agent_start"}} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/thread_rollback/pi_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/thread_rollback/pi_transcript.ndjson index 479c7ca6b57e7..9960205b1f1f9 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/thread_rollback/pi_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/thread_rollback/pi_transcript.ndjson @@ -52,6 +52,8 @@ {"type":"emit_inbound","label":"response:get_entries","frame":{"id":"t3-7","type":"response","command":"get_entries","success":true,"data":{"entries":[{"type":"model_change","id":"cc15a6b4","parentId":"00c31b78","timestamp":"2026-01-01T00:00:00.344Z","provider":"openrouter","modelId":"deepseek/deepseek-v4-flash"},{"type":"session_info","id":"2c1dcf96","parentId":"cc15a6b4","timestamp":"2026-01-01T00:00:00.349Z","name":"Replay fixture: thread_rollback"},{"type":"message","id":"aca5528d","parentId":"2c1dcf96","timestamp":"2026-01-01T00:00:00.357Z","message":{"role":"system","content":"","sections":{"preamble":"","tools":"","rules":"","docs":"","cwd":""},"timestamp":1790898591831,"toolsAdded":[{"name":"read","description":"Read the contents of a file. Supports text files and images (jpg, png, gif, webp, bmp). Images are sent as attachments. For text files, output is truncated to 2000 lines or 50KB (whichever is hit first). Use offset/limit for large files. When you need the full file, continue with offset until complete.","parameters":{"type":"object","required":["path"],"properties":{"path":{"type":"string","description":"Path to the file to read (relative or absolute)"},"offset":{"type":"number","description":"Line number to start reading from (1-indexed)"},"limit":{"type":"number","description":"Maximum number of lines to read"}}},"constrainedSampling":{"type":"json_schema","strict":"prefer"}},{"name":"bash","description":"Execute a bash command in the current working directory. Returns stdout and stderr. Output is truncated to last 2000 lines or 50KB (whichever is hit first). If truncated, full output is saved to a temp file. Optionally provide a timeout in seconds.","parameters":{"type":"object","required":["command"],"properties":{"command":{"type":"string","description":"Shell command to execute"},"timeout":{"type":"number","description":"Timeout in seconds (optional, no default timeout)"}}},"constrainedSampling":{"type":"json_schema","strict":"prefer"}},{"name":"edit","description":"Edit a single file using exact text replacement. Every edits[].oldText must match a unique, non-overlapping region of the original file. If two changes affect the same block or nearby lines, merge them into one edit instead of emitting overlapping edits. Do not include large unchanged regions just to connect distant changes.","parameters":{"type":"object","required":["path","edits"],"properties":{"path":{"type":"string","description":"Path to the file to edit (relative or absolute)"},"edits":{"type":"array","items":{"type":"object","required":["oldText","newText"],"properties":{"oldText":{"type":"string","description":"Exact text for one targeted replacement. It must be unique in the original file and must not overlap with any other edits[].oldText in the same call."},"newText":{"type":"string","description":"Replacement text for this targeted edit."}}},"description":"One or more targeted replacements. Each edit is matched against the original file, not incrementally. Do not include overlapping or nested edits. If two changes touch the same block or nearby lines, merge them into one edit instead."}}},"constrainedSampling":{"type":"json_schema","strict":"prefer"}},{"name":"write","description":"Write content to a file. Creates the file if it doesn't exist, overwrites if it does. Automatically creates parent directories.","parameters":{"type":"object","required":["path","content"],"properties":{"path":{"type":"string","description":"Path to the file to write (relative or absolute)"},"content":{"type":"string","description":"Content to write to the file"}}},"constrainedSampling":{"type":"json_schema","strict":"prefer"}}]}},{"type":"message","id":"70559bb2","parentId":"aca5528d","timestamp":"2026-01-01T00:00:00.357Z","message":{"role":"user","content":[{"type":"text","text":"Respond with exactly: rollback fixture first turn complete"}],"timestamp":1767225600354}},{"type":"message","id":"c906b4e2","parentId":"70559bb2","timestamp":"2026-01-01T00:00:02.034Z","message":{"role":"assistant","content":[{"type":"thinking","thinking":"The user is asking me to respond with exactly: \"rollback fixture first turn complete\"\n\nLet me check if there are any rollback-related fixtures or tests in the workspace first, as this seems like a test instruction.","thinkingSignature":""},{"type":"text","text":"rollback fixture first turn complete"}],"api":"openai-completions","provider":"openrouter","model":"deepseek/deepseek-v4-flash","usage":{"input":1791,"output":52,"cacheRead":0,"cacheWrite":0,"reasoning":54,"totalTokens":1843,"cost":{"input":0.00007497126,"output":0.00000435344,"cacheRead":0,"cacheWrite":0,"total":0.0000793247}},"stopReason":"stop","timestamp":1767225600369,"responseId":"gen-1790898592-a7T4i6GUUneRyLxy0gtp","rawStopReason":"stop","thinkingLevel":"high"}}],"leafId":"c906b4e2"}}} {"type":"expect_outbound","label":"get_session_stats","frame":{"type":"get_session_stats","id":"t3-8"}} {"type":"emit_inbound","label":"response:get_session_stats","frame":{"id":"t3-8","type":"response","command":"get_session_stats","success":true,"data":{"sessionFile":"/pi-sessions/session-1.jsonl","sessionId":"00000000-0000-4000-8000-000000000002","userMessages":1,"assistantMessages":1,"toolCalls":0,"toolResults":0,"totalMessages":3,"tokens":{"input":1791,"output":52,"cacheRead":0,"cacheWrite":0,"total":1843},"cost":0.0000793247,"contextUsage":{"tokens":1843,"contextWindow":1048576,"percent":0.17576217651367188}}}} +{"type":"expect_outbound","label":"get_state","frame":{"type":"get_state","id":"t3-1000"}} +{"type":"emit_inbound","label":"response:get_state","frame":{"id":"t3-1000","type":"response","command":"get_state","success":true,"data":{"model":{"type":"chat","id":"deepseek/deepseek-v4-flash","name":"DeepSeek: DeepSeek V4 Flash 0423","api":"openai-completions","baseUrl":"https://openrouter.ai/api/v1","provider":"openrouter","reasoning":true,"thinkingLevelMap":{"off":"none","minimal":null,"low":null,"medium":null,"high":"high","xhigh":"xhigh","max":null},"input":["text"],"cost":{"input":0.04186,"output":0.08372,"cacheRead":0.008372,"cacheWrite":0},"contextWindow":1048576,"maxTokens":131072,"compat":{"supportsDeveloperRole":false,"thinkingFormat":"openrouter","supportsStrictMode":true,"sendSessionAffinityHeaders":true,"requiresReasoningContentOnAssistantMessages":true}},"thinkingLevel":"high","isStreaming":false,"isCompacting":false,"steeringMode":"one-at-a-time","followUpMode":"one-at-a-time","sessionFile":"/pi-sessions/session-1.jsonl","sessionId":"00000000-0000-4000-8000-000000000002","sessionName":"Replay fixture: thread_rollback","autoCompactionEnabled":true,"messageCount":3,"pendingMessageCount":0}}} {"type":"expect_outbound","label":"prompt","frame":{"type":"prompt","message":"Respond with exactly: rollback fixture second turn complete","streamingBehavior":"steer"}} {"type":"emit_inbound","label":"response:prompt","frame":{"type":"response","command":"prompt","success":true,"data":{"disposition":"started"}}} {"type":"emit_inbound","label":"agent_start","frame":{"type":"agent_start"}} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/thread_rollback_after_stop/pi_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/thread_rollback_after_stop/pi_transcript.ndjson index 8d79e25dcb13c..17da2a9bada5b 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/thread_rollback_after_stop/pi_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/thread_rollback_after_stop/pi_transcript.ndjson @@ -42,6 +42,8 @@ {"type":"emit_inbound","label":"response:get_entries","frame":{"id":"t3-7","type":"response","command":"get_entries","success":true,"data":{"entries":[{"type":"model_change","id":"7aecf566","parentId":"10e2239d","timestamp":"2026-01-01T00:00:00.359Z","provider":"openrouter","modelId":"deepseek/deepseek-v4-flash"},{"type":"session_info","id":"5e1135b5","parentId":"7aecf566","timestamp":"2026-01-01T00:00:00.363Z","name":"Replay fixture: thread_rollback_after_stop"},{"type":"message","id":"66a686a0","parentId":"5e1135b5","timestamp":"2026-01-01T00:00:00.371Z","message":{"role":"system","content":"","sections":{"preamble":"","tools":"","rules":"","docs":"","cwd":""},"timestamp":1790898591965,"toolsAdded":[{"name":"read","description":"Read the contents of a file. Supports text files and images (jpg, png, gif, webp, bmp). Images are sent as attachments. For text files, output is truncated to 2000 lines or 50KB (whichever is hit first). Use offset/limit for large files. When you need the full file, continue with offset until complete.","parameters":{"type":"object","required":["path"],"properties":{"path":{"type":"string","description":"Path to the file to read (relative or absolute)"},"offset":{"type":"number","description":"Line number to start reading from (1-indexed)"},"limit":{"type":"number","description":"Maximum number of lines to read"}}},"constrainedSampling":{"type":"json_schema","strict":"prefer"}},{"name":"bash","description":"Execute a bash command in the current working directory. Returns stdout and stderr. Output is truncated to last 2000 lines or 50KB (whichever is hit first). If truncated, full output is saved to a temp file. Optionally provide a timeout in seconds.","parameters":{"type":"object","required":["command"],"properties":{"command":{"type":"string","description":"Shell command to execute"},"timeout":{"type":"number","description":"Timeout in seconds (optional, no default timeout)"}}},"constrainedSampling":{"type":"json_schema","strict":"prefer"}},{"name":"edit","description":"Edit a single file using exact text replacement. Every edits[].oldText must match a unique, non-overlapping region of the original file. If two changes affect the same block or nearby lines, merge them into one edit instead of emitting overlapping edits. Do not include large unchanged regions just to connect distant changes.","parameters":{"type":"object","required":["path","edits"],"properties":{"path":{"type":"string","description":"Path to the file to edit (relative or absolute)"},"edits":{"type":"array","items":{"type":"object","required":["oldText","newText"],"properties":{"oldText":{"type":"string","description":"Exact text for one targeted replacement. It must be unique in the original file and must not overlap with any other edits[].oldText in the same call."},"newText":{"type":"string","description":"Replacement text for this targeted edit."}}},"description":"One or more targeted replacements. Each edit is matched against the original file, not incrementally. Do not include overlapping or nested edits. If two changes touch the same block or nearby lines, merge them into one edit instead."}}},"constrainedSampling":{"type":"json_schema","strict":"prefer"}},{"name":"write","description":"Write content to a file. Creates the file if it doesn't exist, overwrites if it does. Automatically creates parent directories.","parameters":{"type":"object","required":["path","content"],"properties":{"path":{"type":"string","description":"Path to the file to write (relative or absolute)"},"content":{"type":"string","description":"Content to write to the file"}}},"constrainedSampling":{"type":"json_schema","strict":"prefer"}}]}},{"type":"message","id":"0d296cbc","parentId":"66a686a0","timestamp":"2026-01-01T00:00:00.372Z","message":{"role":"user","content":[{"type":"text","text":"Respond with exactly: rollback fixture first turn complete"}],"timestamp":1767225600369}},{"type":"message","id":"b184b5a8","parentId":"0d296cbc","timestamp":"2026-01-01T00:00:01.622Z","message":{"role":"assistant","content":[{"type":"thinking","thinking":"The user wants me to respond with exactly \"rollback fixture first turn complete\".","thinkingSignature":""},{"type":"text","text":"rollback fixture first turn complete"}],"api":"openai-completions","provider":"openrouter","model":"deepseek/deepseek-v4-flash","usage":{"input":1795,"output":24,"cacheRead":0,"cacheWrite":0,"reasoning":21,"totalTokens":1819,"cost":{"input":0.00007513869999999999,"output":0.00000200928,"cacheRead":0,"cacheWrite":0,"total":0.00007714798}},"stopReason":"stop","timestamp":1767225600386,"responseId":"gen-1790898592-vpyqfefcvhCaD41XnfZc","rawStopReason":"stop","thinkingLevel":"high"}}],"leafId":"b184b5a8"}}} {"type":"expect_outbound","label":"get_session_stats","frame":{"type":"get_session_stats","id":"t3-8"}} {"type":"emit_inbound","label":"response:get_session_stats","frame":{"id":"t3-8","type":"response","command":"get_session_stats","success":true,"data":{"sessionFile":"/pi-sessions/session-1.jsonl","sessionId":"00000000-0000-4000-8000-000000000002","userMessages":1,"assistantMessages":1,"toolCalls":0,"toolResults":0,"totalMessages":3,"tokens":{"input":1795,"output":24,"cacheRead":0,"cacheWrite":0,"total":1819},"cost":0.00007714798,"contextUsage":{"tokens":1819,"contextWindow":1048576,"percent":0.17347335815429688}}}} +{"type":"expect_outbound","label":"get_state","frame":{"type":"get_state","id":"t3-1000"}} +{"type":"emit_inbound","label":"response:get_state","frame":{"id":"t3-1000","type":"response","command":"get_state","success":true,"data":{"model":{"type":"chat","id":"deepseek/deepseek-v4-flash","name":"DeepSeek: DeepSeek V4 Flash 0423","api":"openai-completions","baseUrl":"https://openrouter.ai/api/v1","provider":"openrouter","reasoning":true,"thinkingLevelMap":{"off":"none","minimal":null,"low":null,"medium":null,"high":"high","xhigh":"xhigh","max":null},"input":["text"],"cost":{"input":0.04186,"output":0.08372,"cacheRead":0.008372,"cacheWrite":0},"contextWindow":1048576,"maxTokens":131072,"compat":{"supportsDeveloperRole":false,"thinkingFormat":"openrouter","supportsStrictMode":true,"sendSessionAffinityHeaders":true,"requiresReasoningContentOnAssistantMessages":true}},"thinkingLevel":"high","isStreaming":false,"isCompacting":false,"steeringMode":"one-at-a-time","followUpMode":"one-at-a-time","sessionFile":"/pi-sessions/session-1.jsonl","sessionId":"00000000-0000-4000-8000-000000000002","sessionName":"Replay fixture: thread_rollback_after_stop","autoCompactionEnabled":true,"messageCount":3,"pendingMessageCount":0}}} {"type":"expect_outbound","label":"prompt","frame":{"type":"prompt","message":"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.","streamingBehavior":"steer"}} {"type":"emit_inbound","label":"response:prompt","frame":{"type":"response","command":"prompt","success":true,"data":{"disposition":"started"}}} {"type":"emit_inbound","label":"agent_start","frame":{"type":"agent_start"}} diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index ff14154dccb8f..83bd2f63883e7 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -2225,14 +2225,17 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) }); const handleSubmitMessage = (event: React.MouseEvent) => { event.preventDefault(); + const running = phase === "running" || phase === "connecting"; + const alternateModifier = event.metaKey || event.ctrlKey; submitComposer( event, resolveComposerDispatchMode({ - running: phase === "running" || phase === "connecting", - alternateModifier: event.metaKey || event.ctrlKey, + running, + alternateModifier, activeTurnDefault: followUpBehavior, canSteer, }), + running && alternateModifier ? "alternate" : undefined, ); }; const handleSubmitMessageStable = useStableCallback(handleSubmitMessage); diff --git a/apps/web/src/components/chat/ModelPickerContent.tsx b/apps/web/src/components/chat/ModelPickerContent.tsx index 00ae66675191f..e9a884fde6a17 100644 --- a/apps/web/src/components/chat/ModelPickerContent.tsx +++ b/apps/web/src/components/chat/ModelPickerContent.tsx @@ -66,6 +66,7 @@ import { type ProviderInstanceEntry, } from "../../providerInstances"; import { providerModelKey, sortProviderModelItems } from "../../modelOrdering"; +import { hasRuntimeModelCatalog } from "../../providerModels"; type ModelPickerItem = { slug: string; @@ -113,9 +114,7 @@ function shouldIncludeModelPickerOption(input: { if (isProviderInstancePickerReady(input.entry)) return true; return ( input.entry.enabled && - (input.entry.driverKind === "opencode" || - input.entry.driverKind === "antigravity" || - input.entry.driverKind === "cursor") && + hasRuntimeModelCatalog(input.entry.driverKind) && input.entry.instanceId === input.activeInstanceId && input.option.slug === input.activeModel && input.option.isUnavailable === true diff --git a/apps/web/src/components/chat/TraitsPicker.tsx b/apps/web/src/components/chat/TraitsPicker.tsx index 4cff71c95ca57..48913f3730675 100644 --- a/apps/web/src/components/chat/TraitsPicker.tsx +++ b/apps/web/src/components/chat/TraitsPicker.tsx @@ -34,7 +34,7 @@ import { MenuTrigger, } from "../ui/menu"; import { useComposerDraftStore, DraftId } from "../../composerDraftStore"; -import { getProviderModelCapabilities } from "../../providerModels"; +import { getProviderModelCapabilities, keepsUnavailableModelOptions } from "../../providerModels"; import { cn } from "~/lib/utils"; import { Badge } from "../ui/badge"; import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; @@ -122,7 +122,7 @@ function getSelectedTraits( ) { const caps = getProviderModelCapabilities(models, model, provider, includePlanAgent); const modelIsUnavailable = - (provider === "opencode" || provider === "cursor") && + keepsUnavailableModelOptions(provider, model) && !models.some((candidate) => candidate.slug === normalizeModelSlug(model, provider)); const descriptors = modelIsUnavailable ? buildUnavailableModelOptionDescriptors( diff --git a/apps/web/src/components/chat/composerProviderState.test.tsx b/apps/web/src/components/chat/composerProviderState.test.tsx index 4a97c898a6712..a1c4e65930236 100644 --- a/apps/web/src/components/chat/composerProviderState.test.tsx +++ b/apps/web/src/components/chat/composerProviderState.test.tsx @@ -147,25 +147,38 @@ describe("getComposerProviderState", () => { expect(state.modelOptionsForDispatch).toEqual(selections(["agent", "build"])); }); - it("preserves explicit options when the selected model is absent from the catalog", () => { - const state = getComposerProviderState({ - provider: ProviderDriverKind.make("opencode"), + it.each([ + { + driver: "opencode", model: "opencode/kimi-k3", - models: [ - { - slug: "opencode/big-pickle", - name: "Big Pickle", - isCustom: false, - capabilities: {}, - }, - ], - modelOptions: selections(["variant", "max"], ["agent", "build"]), - }); + catalogModel: "opencode/big-pickle", + options: selections(["variant", "max"], ["agent", "build"]), + }, + { + driver: "pi", + model: "anthropic/claude-sonnet-4", + catalogModel: "default", + options: selections(["thinking", "high"]), + }, + { + driver: "acpRegistry", + model: "gateway/chosen-model", + catalogModel: "default", + options: selections(["reasoning", "high"]), + }, + ])( + "preserves explicit $driver options when the selected model is absent from the catalog", + ({ driver, model, catalogModel, options }) => { + const state = getComposerProviderState({ + provider: ProviderDriverKind.make(driver), + model, + models: [{ slug: catalogModel, name: catalogModel, isCustom: false, capabilities: {} }], + modelOptions: options, + }); - expect(state.modelOptionsForDispatch).toEqual( - selections(["variant", "max"], ["agent", "build"]), - ); - }); + expect(state.modelOptionsForDispatch).toEqual(options); + }, + ); it("validates options for a known model selected through a legacy alias", () => { const state = getComposerProviderState({ diff --git a/apps/web/src/components/chat/composerProviderState.tsx b/apps/web/src/components/chat/composerProviderState.tsx index 06b403b082913..b8d4bdad4b382 100644 --- a/apps/web/src/components/chat/composerProviderState.tsx +++ b/apps/web/src/components/chat/composerProviderState.tsx @@ -17,7 +17,7 @@ import { } from "@t3tools/shared/model"; import type { DraftId } from "../../composerDraftStore"; -import { getProviderModelCapabilities } from "../../providerModels"; +import { getProviderModelCapabilities, keepsUnavailableModelOptions } from "../../providerModels"; import { getReasoningTraitStep, type PromptUltrathink, @@ -86,7 +86,7 @@ export function getComposerProviderState(input: ComposerProviderStateInput): Com promptInjectionState = "none", includePlanAgent, } = input; - if (provider === "opencode" || provider === "cursor") { + if (keepsUnavailableModelOptions(provider, model)) { const normalizedModel = normalizeModelSlug(model, provider); const modelIsInCatalog = models.some((candidate) => candidate.slug === normalizedModel); if (!modelIsInCatalog) { diff --git a/apps/web/src/components/chat/useComposerSend.ts b/apps/web/src/components/chat/useComposerSend.ts index 72e6f3bf792c0..93ff79432708c 100644 --- a/apps/web/src/components/chat/useComposerSend.ts +++ b/apps/web/src/components/chat/useComposerSend.ts @@ -660,6 +660,7 @@ export function useComposerSend(input: ComposerSendInput) { replyTo, }, setThreadError, + { dispatchMode, submissionIntent }, ); return; } diff --git a/apps/web/src/components/chat/useQueuedRunEdit.browser.test.tsx b/apps/web/src/components/chat/useQueuedRunEdit.browser.test.tsx index 28785ecd768af..a88da51cce16e 100644 --- a/apps/web/src/components/chat/useQueuedRunEdit.browser.test.tsx +++ b/apps/web/src/components/chat/useQueuedRunEdit.browser.test.tsx @@ -33,12 +33,15 @@ import { readAttachmentUpload, useAttachmentUploadStore } from "../../lib/attach interface RunStatus { readonly id: RunId; readonly status: string; + readonly activeAttemptId?: string; } const mocks = await vi.hoisted(async () => { const { Atom } = await import("effect/reactivity"); return { editQueuedRun: vi.fn<(value: unknown) => Promise<{ readonly _tag: "Success" | "Failure" }>>(), + promoteQueuedRun: vi.fn<(value: unknown) => Promise<{ readonly _tag: "Success" }>>(), + promoteCommand: {}, // The projection's runs per thread, written by each test to stand in for the server. threadRuns: Atom.family((_key: string) => Atom.make | null>(null).pipe(Atom.keepAlive), @@ -47,7 +50,8 @@ const mocks = await vi.hoisted(async () => { }); vi.mock("../../state/use-atom-command", () => ({ - useAtomCommand: () => mocks.editQueuedRun, + useAtomCommand: (command: unknown) => + command === mocks.promoteCommand ? mocks.promoteQueuedRun : mocks.editQueuedRun, })); vi.mock("../../hooks/useSettings", () => ({ @@ -63,13 +67,35 @@ vi.mock("../../state/threads", async () => { threadEnvironment: { snapshotAtom: () => Atom.make(null), editQueuedRun: {}, + promoteQueuedRun: mocks.promoteCommand, }, environmentThreadDetails: { statusAtom: () => Atom.make("ready"), quietThreadAtom: (ref: ScopedThreadRef) => Atom.make((get) => { const runs = get(mocks.threadRuns(key(ref))); - return runs === null ? null : { projection: { runs } }; + if (runs === null) return null; + // A Claude-like session whose running turn takes steering. + return { + projection: { + thread: { id: ref.threadId, activeProviderThreadId: null }, + runs, + messages: [], + providerThreads: [], + providerSessions: [ + { + id: "session", + status: "running", + capabilities: { turns: { supportsActiveSteering: true } }, + }, + ], + providerTurns: runs.flatMap((run) => + run.activeAttemptId + ? [{ runAttemptId: run.activeAttemptId, status: "running" }] + : [], + ), + }, + }; }), }, environmentThreadShells: { @@ -151,6 +177,7 @@ function view( function setup() { mocks.editQueuedRun.mockReset(); + mocks.promoteQueuedRun.mockReset(); useAttachmentUploadStore.setState({ uploadsByImageId: {} }); useComposerDraftStore.setState({ draftsByThreadKey: {}, draftThreadsByThreadKey: {} }); setRuns(THREAD_A, "queued"); @@ -247,6 +274,42 @@ describe("useQueuedRunEdit", () => { }, ); + it.each([ + // Cmd+Enter or Cmd-click with Queue as the default: save, then steer. + { dispatchMode: "steer", submissionIntent: "alternate", steers: true }, + // Enter or the Update button with Steer as the default: save in place only. + { dispatchMode: "steer", submissionIntent: "foreground", steers: false }, + // Cmd+Enter with Steer as the default queues, so the message stays queued. + { dispatchMode: "queue", submissionIntent: "alternate", steers: false }, + ] as const)( + "a saved edit sent as $submissionIntent/$dispatchMode steers: $steers", + async (submission) => { + const { hook } = setup(); + mocks.editQueuedRun.mockResolvedValue({ _tag: "Success" }); + mocks.promoteQueuedRun.mockResolvedValue({ _tag: "Success" }); + const activeRun = RunId.make("run-active"); + appAtomRegistry.set(mocks.threadRuns(runsKey(THREAD_A)), [ + { id: activeRun, status: "running", activeAttemptId: "attempt-1" }, + { id: RUN, status: "queued" }, + ]); + await using _screen = await render(view(THREAD_A, "queued", hook)); + await beginChangedEdit(hook); + await act(() => requireHook(hook).saveEdit(savedContent("changed"), () => {}, submission)); + expect(mocks.editQueuedRun).toHaveBeenCalledOnce(); + if (!submission.steers) { + expect(mocks.promoteQueuedRun).not.toHaveBeenCalled(); + return; + } + expect(mocks.promoteQueuedRun).toHaveBeenCalledExactlyOnceWith({ + environmentId: ENV, + input: { threadId: THREAD_A.threadId, queuedRunId: RUN, targetRunId: activeRun }, + }); + expect(mocks.editQueuedRun.mock.invocationCallOrder[0]).toBeLessThan( + mocks.promoteQueuedRun.mock.invocationCallOrder[0]!, + ); + }, + ); + it("saves an effort-only prompt without claiming removed attachments remain", async () => { const { hook } = setup(); mocks.editQueuedRun.mockResolvedValue({ _tag: "Success" }); diff --git a/apps/web/src/components/chat/useQueuedRunEdit.ts b/apps/web/src/components/chat/useQueuedRunEdit.ts index d5cb8505a013e..35a4947a34c26 100644 --- a/apps/web/src/components/chat/useQueuedRunEdit.ts +++ b/apps/web/src/components/chat/useQueuedRunEdit.ts @@ -3,7 +3,9 @@ import { makeQueuedRunEditStore, makeQueuedRunsAtom, } from "@t3tools/client-runtime/queued-run-edit"; +import type { ComposerDispatchMode } from "@t3tools/client-runtime/state/composer-dispatch"; import type { ThreadStructure } from "@t3tools/client-runtime/state/shell"; +import { deriveThreadQueueWorkflowState } from "@t3tools/client-runtime/state/thread-workflows"; import { PROVIDER_SEND_TURN_MAX_ATTACHMENTS, type ChatAttachment, @@ -49,6 +51,7 @@ import { } from "../../lib/composerContextReferences"; import { readFileAsDataUrl } from "../../lib/imageCompression"; import type { TerminalContextDraft } from "../../lib/terminalContext"; +import type { ComposerSubmissionIntent } from "../../composer-logic"; import type { ReviewCommentContext } from "../../reviewCommentContext"; import { appAtomRegistry } from "../../rpc/atomRegistry"; import { environmentServerConfigsAtom } from "../../state/server"; @@ -217,6 +220,7 @@ export function useQueuedRunEdit(input: { composerRef, } = input; const editQueuedRunCommand = useEditQueuedRunCommand(); + const promoteQueuedRun = useAtomCommand(threadEnvironment.promoteQueuedRun); const editKey = scopedThreadKey(routeThreadRef); const storedEdit = useAtomValue(queuedRunEdits.atom)[editKey] ?? null; const editing = activeThreadId === null ? null : storedEdit; @@ -343,9 +347,39 @@ export function useQueuedRunEdit(input: { })); }); + // The same move as the queued row's "Send now" while a turn runs. + const steerSavedRun = async (edited: EditingQueuedRun) => { + const projection = appAtomRegistry.get( + environmentThreadDetails.quietThreadAtom({ environmentId, threadId: edited.threadId }), + )?.projection; + if (!projection) return; + const workflow = deriveThreadQueueWorkflowState(projection); + const queued = workflow.queuedRuns.find(({ run }) => run.id === edited.runId); + if ( + queued === undefined || + workflow.activeRun === null || + !workflow.canPromoteToSteer || + (queued.run.freshContext === true && !workflow.promoteSkipsCompaction) + ) { + return; + } + await promoteQueuedRun({ + environmentId, + input: { + threadId: edited.threadId, + queuedRunId: edited.runId, + targetRunId: workflow.activeRun.id, + }, + }); + }; + const saveEdit = async ( content: QueuedRunEditContent, setThreadError: (threadId: ThreadId, error: string | null) => void, + submission?: { + readonly dispatchMode: ComposerDispatchMode; + readonly submissionIntent: ComposerSubmissionIntent; + }, ) => { if (editing === null || isSaving) return; const newAttachments = [...content.images, ...content.files]; @@ -420,6 +454,11 @@ export function useQueuedRunEdit(input: { clearEditDraft(editing.runId); composerRef.current?.resetCursorState(); focusComposerSoon(); + // A plain submit means "Update queued message"; only the opposite-action shortcut or + // modifier-click asks to steer, as it does for a new follow-up. + if (submission?.submissionIntent === "alternate" && submission.dispatchMode === "steer") { + await steerSavedRun(editing); + } }; return { diff --git a/apps/web/src/composer-rich-text.test.ts b/apps/web/src/composer-rich-text.test.ts index 00c5a44b90809..330acaac2069d 100644 --- a/apps/web/src/composer-rich-text.test.ts +++ b/apps/web/src/composer-rich-text.test.ts @@ -7,6 +7,9 @@ describe("composer rich text markdown", () => { for (const text of [ "plain text", "snake_case", + "ملفٌ_اول و ملفٌ_ثاني", + "файл_один и файл_два", + "𐐀_𐐁_𐐂 and 𠀀_𠀁_𠀂", "unmatched **", "** spaced **", "\\*literal\\*", @@ -72,6 +75,8 @@ describe("composer rich text markdown", () => { ["__see src/__a.ts__(optional)", "see src/__a.ts", "bold", "(optional)"], ["_see src/_a.ts_.", "see src/_a.ts", "italic", "."], ["_notes.md_ here", "notes.md", "italic", " here"], + ["_файл_один.py_ now", "файл_один.py", "italic", " now"], + ["_my_file.py is broken_ now", "my_file.py is broken", "italic", " now"], ["_e.g._ this", "e.g.", "italic", " this"], ["_and_/or", "and", "italic", "/or"], ] as const) { diff --git a/apps/web/src/composer-rich-text.ts b/apps/web/src/composer-rich-text.ts index 80d7679492f4a..a0f4340c324a3 100644 --- a/apps/web/src/composer-rich-text.ts +++ b/apps/web/src/composer-rich-text.ts @@ -28,6 +28,9 @@ const PATH_TOKEN = /(?:[\p{L}\p{N}_/.:@%+=&?#-]|(? { while (body[end] === "_") end += 1; if (start > 0) { literal.add(match.index + start); - closesInside ||= !/\w/.test(body[end]!); + closesInside ||= !WORD_CHARACTER_AFTER.test(body.slice(end, end + 2)); } start = body.indexOf("_", end); } @@ -118,8 +121,10 @@ function parseInlineMarkdownPieces(text: string): SourcePiece[] { } const before = text[index - 1] ?? ""; const after = text[end] ?? ""; - const canClose = before !== "" && !/\s/.test(before) && (char !== "_" || !/\w/.test(after)); - const canOpen = after !== "" && !/\s/.test(after) && (char !== "_" || !/\w/.test(before)); + const wordAfter = WORD_CHARACTER_AFTER.test(text.slice(end, end + 2)); + const wordBefore = WORD_CHARACTER_BEFORE.test(text.slice(Math.max(0, index - 2), index)); + const canClose = before !== "" && !/\s/.test(before) && (char !== "_" || !wordAfter); + const canOpen = after !== "" && !/\s/.test(after) && (char !== "_" || !wordBefore); while (index < end) { const top = stack.at(-1); const opensNestedBold = diff --git a/apps/web/src/modelSelection.test.ts b/apps/web/src/modelSelection.test.ts index 70a763f379bab..7df4c4d339a9e 100644 --- a/apps/web/src/modelSelection.test.ts +++ b/apps/web/src/modelSelection.test.ts @@ -394,6 +394,16 @@ describe("instance-scoped model selection", () => { }); describe.each([ + { + driverName: "pi", + availableModel: "default", + missingModel: "anthropic/claude-sonnet-4", + }, + { + driverName: "acpRegistry", + availableModel: "default", + missingModel: "gateway/chosen-model", + }, { driverName: "opencode", availableModel: "opencode/big-pickle", @@ -662,66 +672,61 @@ describe("instance-scoped model selection", () => { } }); - it("resolves the Antigravity default marker without creating an unavailable model", () => { - const instanceId = ProviderInstanceId.make("antigravity_work"); - const nativeModel = "gemini-3.1-pro"; - const base = provider({ - provider: ProviderDriverKind.make("antigravity"), - instanceId, - models: [nativeModel], - }); - const liveProvider = { - ...base, - models: base.models.map((model) => ({ - ...model, - isDefault: true, - aliases: [ANTIGRAVITY_DEFAULT_MODEL], - })), - }; - const settings = settingsWithProviderInstances(); - - expect( - getAppModelOptionsForInstance( - settings, - deriveProviderInstanceEntries([liveProvider])[0]!, - ANTIGRAVITY_DEFAULT_MODEL, - ).map((model) => model.slug), - ).toEqual([nativeModel]); - expect( - resolveAppModelSelectionForInstance( + it.each([ + { driver: "antigravity", marker: ANTIGRAVITY_DEFAULT_MODEL, nativeModel: "gemini-3.1-pro" }, + { driver: "acpRegistry", marker: "default", nativeModel: "agent-model" }, + ])( + "resolves the $driver default marker without creating an unavailable model", + ({ driver, marker, nativeModel }) => { + const instanceId = ProviderInstanceId.make(`${driver}_work`); + const base = provider({ + provider: ProviderDriverKind.make(driver), instanceId, - settings, - [liveProvider], - ANTIGRAVITY_DEFAULT_MODEL, - { + models: [nativeModel], + }); + const liveProvider = { + ...base, + models: base.models.map((model) => ({ + ...model, + isDefault: true, + ...(driver === "antigravity" ? { aliases: [marker] } : {}), + })), + }; + const settings = settingsWithProviderInstances(); + + expect( + getAppModelOptionsForInstance( + settings, + deriveProviderInstanceEntries([liveProvider])[0]!, + marker, + ).map((model) => model.slug), + ).toEqual([nativeModel]); + expect( + resolveAppModelSelectionForInstance(instanceId, settings, [liveProvider], marker, { preserveUnavailableSelection: true, - }, - ), - ).toBe(nativeModel); + }), + ).toBe(nativeModel); - const hiddenSettings: UnifiedSettings = { - ...settings, - providerModelPreferences: { - [instanceId]: { hiddenModels: [nativeModel], modelOrder: [] }, - }, - }; - expect( - resolveAppModelSelectionForInstance( - instanceId, - hiddenSettings, - [liveProvider], - ANTIGRAVITY_DEFAULT_MODEL, - { preserveUnavailableSelection: true }, - ), - ).toBeNull(); - expect( - getAppModelOptionsForInstance( - settings, - deriveProviderInstanceEntries([{ ...base, models: [] }])[0]!, - ANTIGRAVITY_DEFAULT_MODEL, - ), - ).toEqual([]); - }); + const hiddenSettings: UnifiedSettings = { + ...settings, + providerModelPreferences: { + [instanceId]: { hiddenModels: [nativeModel], modelOrder: [] }, + }, + }; + expect( + resolveAppModelSelectionForInstance(instanceId, hiddenSettings, [liveProvider], marker, { + preserveUnavailableSelection: true, + }), + ).toBeNull(); + expect( + getAppModelOptionsForInstance( + settings, + deriveProviderInstanceEntries([{ ...base, models: [] }])[0]!, + marker, + ), + ).toEqual([]); + }, + ); it("preserves saved options through dispatch when the model is absent from the catalog", () => { const instanceId = ProviderInstanceId.make("opencode"); diff --git a/apps/web/src/modelSelection.ts b/apps/web/src/modelSelection.ts index 3f566afe19223..ff8ac2b1a80eb 100644 --- a/apps/web/src/modelSelection.ts +++ b/apps/web/src/modelSelection.ts @@ -1,5 +1,4 @@ import { - ANTIGRAVITY_DEFAULT_MODEL, DEFAULT_TEXT_GENERATION_MODEL, DEFAULT_TEXT_GENERATION_MODEL_BY_PROVIDER, defaultInstanceIdForDriver, @@ -26,6 +25,8 @@ import * as Result from "effect/Result"; import { getDefaultServerModel, getProviderModels, + hasRuntimeModelCatalog, + isRuntimeModelDefaultAlias, resolveSelectableProvider, } from "./providerModels"; import { ModelEsque } from "./components/chat/providerIconUtils"; @@ -80,12 +81,10 @@ function appendUnavailableDynamicModelSelection( selectedModel: string | null | undefined, hiddenModels: ReadonlyArray, ): AppModelOption[] { - if (provider !== "opencode" && provider !== "antigravity" && provider !== "cursor") { - return options; - } + if (!hasRuntimeModelCatalog(provider)) return options; const slug = normalizeCustomModelSlug(selectedModel); if (!slug) return options; - if (provider === "antigravity" && slug === ANTIGRAVITY_DEFAULT_MODEL) return options; + if (isRuntimeModelDefaultAlias(provider, slug)) return options; if (resolveSelectableModel(provider, slug, rawModels) !== null) return options; if (hiddenModels.includes(slug)) return options; @@ -282,19 +281,14 @@ export function resolveAppModelSelectionForInstance( if (resolvedSelection) { return resolvedSelection; } - if ( - resolutionOptions?.preserveUnavailableSelection && - (entry.driverKind === "opencode" || - entry.driverKind === "antigravity" || - entry.driverKind === "cursor") - ) { + if (resolutionOptions?.preserveUnavailableSelection && hasRuntimeModelCatalog(entry.driverKind)) { const unavailableSelection = normalizeCustomModelSlug(selectedModel); const hiddenModels = readInstanceModelPreferences(settings, entry.instanceId).hiddenModels; if ( unavailableSelection && !hiddenModels.includes(unavailableSelection) && resolveSelectableModel(entry.driverKind, selectedModel, entry.models) === null && - (entry.driverKind !== "antigravity" || unavailableSelection !== ANTIGRAVITY_DEFAULT_MODEL) + !isRuntimeModelDefaultAlias(entry.driverKind, unavailableSelection) ) { return unavailableSelection; } diff --git a/apps/web/src/providerModels.ts b/apps/web/src/providerModels.ts index 0d3229718cb7d..0db7a420d8e61 100644 --- a/apps/web/src/providerModels.ts +++ b/apps/web/src/providerModels.ts @@ -14,6 +14,41 @@ const EMPTY_CAPABILITIES: ModelCapabilities = createModelCapabilities({ optionDescriptors: [], }); const DEFAULT_DRIVER_KIND = ProviderDriverKind.make("codex"); +const RUNTIME_MODEL_CATALOG_DRIVERS: ReadonlySet = new Set([ + "opencode", + "antigravity", + "cursor", + "pi", + "acpRegistry", +]); + +// These drivers discover models at runtime, so a refresh can briefly omit a model the user chose. +export function hasRuntimeModelCatalog(provider: ProviderDriverKind): boolean { + return RUNTIME_MODEL_CATALOG_DRIVERS.has(provider); +} + +// These markers follow the session's current model rather than naming an unavailable model. +export function isRuntimeModelDefaultAlias( + provider: ProviderDriverKind, + model: string | null | undefined, +): boolean { + return ( + (provider === "antigravity" || provider === "acpRegistry") && + model === DEFAULT_MODEL_BY_PROVIDER[provider] + ); +} + +// Antigravity lists its default model only as an alias, which a slug lookup would call missing. +export function keepsUnavailableModelOptions( + provider: ProviderDriverKind, + model: string | null | undefined, +): boolean { + return ( + provider !== "antigravity" && + !isRuntimeModelDefaultAlias(provider, model) && + hasRuntimeModelCatalog(provider) + ); +} export function formatProviderDriverKindLabel(provider: ProviderDriverKind): string { return provider diff --git a/packages/provider-acp-registry/src/server/driver.test.ts b/packages/provider-acp-registry/src/server/driver.test.ts index 524d29dbccfd2..b49e884b0ee24 100644 --- a/packages/provider-acp-registry/src/server/driver.test.ts +++ b/packages/provider-acp-registry/src/server/driver.test.ts @@ -9,6 +9,7 @@ import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions"; import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers"; import * as TestProviderHost from "@t3tools/provider-testing/TestProviderHost"; +import { toCustomModelSetting } from "@t3tools/shared/model"; import { AcpRegistrySettings } from "../settings.ts"; import { describe, expect, it } from "@effect/vitest"; import * as Effect from "effect/Effect"; @@ -102,6 +103,28 @@ function providerWithModels( } describe("acpRegistrySnapshotReadiness", () => { + it("keeps the custom model display name and options saved by the Settings editor", () => { + const fastMode = { id: "fast", label: "Fast mode", type: "boolean" } as const; + const snapshot = buildCheckedAcpRegistrySnapshot({ + ...identity, + settings: decodeSettings({ + agentId: "test-agent", + customModels: [ + toCustomModelSetting({ + slug: "gateway/my-model", + name: "My model", + capabilities: { optionDescriptors: [fastMode] }, + }), + ], + }), + checkedAt: "2026-08-13T10:00:00.000Z", + inspection: { status: "ready", agentId: "test-agent", version: "1.0.0", distribution: "npx" }, + }); + const model = snapshot.models.find((entry) => entry.slug === "gateway/my-model"); + expect(model?.name).toBe("My model"); + expect(model?.capabilities?.optionDescriptors).toEqual([fastMode]); + }); + it("shows the version reported by a local ACP agent", () => { const probe = acpRegistryProbeResult(identity.instanceId, { sessionId: "test-session", diff --git a/packages/provider-acp-registry/src/server/driver.ts b/packages/provider-acp-registry/src/server/driver.ts index 63a7502d13097..12b3685b4722a 100644 --- a/packages/provider-acp-registry/src/server/driver.ts +++ b/packages/provider-acp-registry/src/server/driver.ts @@ -5,6 +5,7 @@ import { TextGenerationError, type AcpRegistryOperationError, type AcpRegistryProbeModel, + type CustomModelSetting, type ServerProvider, type ServerProviderModel, } from "@t3tools/contracts"; @@ -97,7 +98,7 @@ export function isAcpRegistryCacheValid( export function updateAcpRegistryEnrichmentCache(input: { readonly cache: AcpRegistryEnrichmentCache; readonly configuration: AcpRegistryLiveConfiguration; - readonly customModels: ReadonlyArray; + readonly customModels: ReadonlyArray; readonly now: number; }): AcpRegistryEnrichmentCache { const { cache, configuration, customModels, now } = input; @@ -157,7 +158,7 @@ function modelsFromDiscovery( "models" | "currentModelId" | "configOptions" | "modelOptionIds" > | undefined, - customModels: ReadonlyArray, + customModels: ReadonlyArray, previousModels: ReadonlyArray = [], ): ReadonlyArray { const discovered = discovery?.models ?? []; @@ -349,7 +350,7 @@ export function applyAcpRegistryAvailableCommands( export function applyAcpRegistryLiveConfiguration( provider: ServerProvider, configuration: AcpRegistryLiveConfiguration, - customModels: ReadonlyArray, + customModels: ReadonlyArray, previousModels: ReadonlyArray = provider.models, ): ServerProvider { const { message: _staleProbeMessage, ...snapshot } = provider; diff --git a/packages/provider-acp-registry/src/settings.ts b/packages/provider-acp-registry/src/settings.ts index 7d5b4173d512f..aba9f5f9db5ac 100644 --- a/packages/provider-acp-registry/src/settings.ts +++ b/packages/provider-acp-registry/src/settings.ts @@ -1,4 +1,4 @@ -import { TrimmedString, makeProviderSettingsSchema } from "@t3tools/contracts"; +import { CustomModelSetting, TrimmedString, makeProviderSettingsSchema } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; import * as Schema from "effect/Schema"; @@ -58,7 +58,7 @@ export const AcpRegistrySettings = makeProviderSettingsSchema( Schema.withDecodingDefault(Effect.succeed("auto")), Schema.annotateKey({ providerSettingsForm: { hidden: true } }), ), - customModels: Schema.Array(Schema.String).pipe( + customModels: Schema.Array(CustomModelSetting).pipe( Schema.withDecodingDefault(Effect.succeed([])), Schema.annotateKey({ providerSettingsForm: { hidden: true } }), ), diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index 01bfafd68b11d..a9bcc4a16bf58 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -5539,11 +5539,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const lateMonitorChatter = / 0 && - lateBackgroundMutations.length === 0 && - !lateMonitorChatter - ) { + if (lateBackgroundMutations.length === 0 && !lateMonitorChatter) { yield* appendLoadedHistory( notification, update.sessionUpdate === "user_message_chunk" @@ -9766,7 +9762,10 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const state = yield* Ref.get(snapshot); const messages = state.order.flatMap((key) => { const message = state.messages.get(key); - return message === undefined ? [] : [message]; + return message === undefined || + (message.text.trim().length === 0 && message.attachments.length === 0) + ? [] + : [message]; }); const now = yield* DateTime.now; return { diff --git a/packages/provider-core/src/server/textGenerationUtils.test.ts b/packages/provider-core/src/server/textGenerationUtils.test.ts index 885e09c4fe77b..516d38418fba7 100644 --- a/packages/provider-core/src/server/textGenerationUtils.test.ts +++ b/packages/provider-core/src/server/textGenerationUtils.test.ts @@ -22,6 +22,17 @@ describe("sanitizeCommitSubject", () => { }); describe("sanitizeThreadTitle", () => { + it.each([ + { raw: '"Fix login redirect"', expected: "Fix login redirect" }, + { raw: `"Fix user's login"`, expected: "Fix user's login" }, + { raw: "Explain `vp check`", expected: "Explain `vp check`" }, + { raw: '"Open in" menu ignores Finder', expected: '"Open in" menu ignores Finder' }, + { raw: 'Rename "foo" to "bar"', expected: 'Rename "foo" to "bar"' }, + { raw: '"Open in" ignores "Finder"', expected: '"Open in" ignores "Finder"' }, + ])("unwraps only a quote pair around the whole title: $raw", ({ raw, expected }) => { + expect(sanitizeThreadTitle(raw)).toBe(expected); + }); + it.each([ { name: "a split surrogate pair", prefixLength: 116, character: "🚀", retained: "" }, { name: "a complete surrogate pair", prefixLength: 115, character: "🚀", retained: "🚀" }, diff --git a/packages/provider-core/src/server/textGenerationUtils.ts b/packages/provider-core/src/server/textGenerationUtils.ts index d2afb675ae936..9d08dd963317c 100644 --- a/packages/provider-core/src/server/textGenerationUtils.ts +++ b/packages/provider-core/src/server/textGenerationUtils.ts @@ -64,7 +64,7 @@ export function sanitizeThreadTitle(raw: string): string { .trim() .split(/\r?\n/g)[0] ?.trim() - .replace(/^['"`]+|['"`]+$/g, "") + .replace(/^(['"`])((?:(?!\1).)*)\1$/, "$2") .trim() .replace(/\s+/g, " "); diff --git a/packages/provider-pi/src/server/adapter.test.ts b/packages/provider-pi/src/server/adapter.test.ts index ae7aab45d5d6b..187a452099419 100644 --- a/packages/provider-pi/src/server/adapter.test.ts +++ b/packages/provider-pi/src/server/adapter.test.ts @@ -180,6 +180,11 @@ interface FakePi { readonly allRequests: () => ReadonlyArray; readonly promptThinkingLevels: ReadonlyArray; readonly promptModels: ReadonlyArray; + /** Simulates a native extension changing Pi's active selection. */ + readonly changeNatively: (change: { + readonly model?: string; + readonly thinking?: string; + }) => void; /** T3 extension's service tier as each prompt was sent; Pi resets it with each session. */ readonly promptServiceTiers: ReadonlyArray; /** Pi reloads extensions without the adapter seeing it, e.g. a user extension's ctx.newSession(). */ @@ -281,6 +286,15 @@ const makeFakePi: Effect.Effect = Effect.gen(function* () { ...base, data: { ...recordedIdleState(sessionFile), + thinkingLevel, + ...(currentModel === "default" + ? {} + : { + model: { + provider: currentModel.slice(0, currentModel.indexOf("/")), + id: currentModel.slice(currentModel.indexOf("/") + 1), + }, + }), isStreaming: isStreaming ?? false, ...stateQueue.shift(), }, @@ -432,6 +446,10 @@ const makeFakePi: Effect.Effect = Effect.gen(function* () { }, promptThinkingLevels, promptModels, + changeNatively: (change) => { + currentModel = change.model ?? currentModel; + thinkingLevel = change.thinking ?? thinkingLevel; + }, promptServiceTiers, reloadExtensions: (newSessionFile) => { serviceTier = null; @@ -3881,6 +3899,50 @@ describe("PiAdapterV2", () => { }).pipe(Effect.scoped, Effect.provide(layerTest)), ); + it.effect.each([ + { change: { model: "openai/model-b", thinking: "minimal" }, setModels: 2 }, + { change: { thinking: "minimal" }, setModels: 1 }, + ])( + "reapplies the selection after an extension changes it natively (%o)", + ({ change, setModels }) => + Effect.gen(function* () { + const fake = yield* makeFakePi; + const { runtime, takeEvent } = yield* openRuntime(fake); + const selection: ModelSelection = { + instanceId: PI_INSTANCE_ID, + model: "anthropic/model-a", + options: [{ id: "thinking", value: "high" }], + }; + const providerThread = yield* runtime.ensureThread({ + threadId: THREAD_ID, + modelSelection: selection, + runtimePolicy, + }); + yield* startTurn( + runtime, + providerThread, + "anthropic/model-a", + [], + "/preset fast", + selection, + ); + yield* fake.takeRequest("prompt"); + yield* fake.emit({ type: "agent_start" }); + fake.changeNatively(change); + yield* fake.emit({ type: "agent_settled" }); + yield* takeEvent((event) => event.type === "turn.terminal"); + + yield* startTurn(runtime, providerThread, "anthropic/model-a", [], "Next", selection, 2); + yield* fake.takeRequest("prompt"); + assert.deepEqual(fake.promptModels, ["anthropic/model-a", "anthropic/model-a"]); + assert.deepEqual(fake.promptThinkingLevels, ["high", "high"]); + assert.equal( + fake.allRequests().filter((request) => request["type"] === "set_model").length, + setModels, + ); + }).pipe(Effect.scoped, Effect.provide(layerTest)), + ); + it.effect("records the model Pi reports on the completed provider turn", () => Effect.gen(function* () { const fake = yield* makeFakePi; diff --git a/packages/provider-pi/src/server/adapter.ts b/packages/provider-pi/src/server/adapter.ts index 626ddbd4ce5e9..56f02760efe4f 100644 --- a/packages/provider-pi/src/server/adapter.ts +++ b/packages/provider-pi/src/server/adapter.ts @@ -3072,6 +3072,18 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( const applySelection = Effect.fnUntraced(function* (modelSelection: ModelSelection) { const thinking = getModelSelectionStringOptionValue(modelSelection, "thinking"); + // pi.setModel and /preset can change the model without an RPC event. + // Confirm cached selections against Pi before skipping them. + const modelCached = + modelSelection.model !== PI_INHERIT_MODEL_SLUG && modelSelection.model === appliedModel; + let modelDrifted = false; + if (modelCached || (thinking !== undefined && thinking === appliedThinking)) { + const state = yield* request({ type: "get_state" }); + const stateModel = recordField(state, "model"); + const piModel = `${recordString(stateModel, "provider")}/${recordString(stateModel, "id")}`; + modelDrifted = modelCached && piModel !== appliedModel; + appliedThinking = recordString(state, "thinkingLevel") ?? null; + } if (modelSelection.model === PI_INHERIT_MODEL_SLUG) { if (appliedModel !== null && baselineModel !== null) { const restoredModel = yield* request({ type: "set_model", ...baselineModel }); @@ -3094,7 +3106,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( yield* request({ type: "set_thinking_level", level: baselineThinking }); appliedThinking = baselineThinking; } - } else if (modelSelection.model !== appliedModel) { + } else if (modelDrifted || modelSelection.model !== appliedModel) { // Extensions and models.json edits can add providers after the first discovery. if (findReportedPiModel(modelSelection.model, discoveredModels) === undefined) { yield* discoverModels(); diff --git a/scripts/scenarios/pi-catalog-gap-keeps-chosen-model.e2e.ts b/scripts/scenarios/pi-catalog-gap-keeps-chosen-model.e2e.ts new file mode 100644 index 0000000000000..7a8aa3b6d4082 --- /dev/null +++ b/scripts/scenarios/pi-catalog-gap-keeps-chosen-model.e2e.ts @@ -0,0 +1,65 @@ +// @effect-diagnostics nodeBuiltinImport:off - the scenario writes a fake Pi CLI and its settings. +import * as NodeFSP from "node:fs/promises"; +import * as NodePath from "node:path"; + +import { expect } from "e2e"; + +import { T3_HOME } from "../e2e.config.ts"; +import { makeState, runPromise, test, WEB } from "./t3.ts"; + +const CHOSEN_MODEL = "anthropic/claude-sonnet-4"; +// A supported Pi whose RPC discovery fails, so its catalog falls back to the "default" alias. +const FAKE_PI = `#!/bin/sh +if [ "$1" = "--version" ]; then echo "0.84.3"; exit 0; fi +echo "scenario Pi cannot list models" >&2 +exit 1 +`; + +test( + "A Pi model chosen in Settings is still the one sent while Pi cannot list its models", + WEB, + async ({ t3, app, screen, browser }) => { + const project = await t3.project("demo"); + const fakePi = NodePath.join(T3_HOME, "bin/fake-pi"); + const settingsPath = NodePath.join(T3_HOME, "userdata/settings.json"); + const originalSettings = await NodeFSP.readFile(settingsPath, "utf8"); + const settings = JSON.parse(originalSettings); + try { + await NodeFSP.writeFile(fakePi, FAKE_PI, { mode: 0o755 }); + settings.providerInstances.pi = { + driver: "pi", + enabled: true, + config: { binaryPath: fakePi }, + }; + settings.defaultModelSelection = { instanceId: "pi", model: CHOSEN_MODEL }; + await NodeFSP.writeFile(settingsPath, JSON.stringify(settings)); + + await t3.open(); + // The composer shows a Pi model once the settings watcher has enabled Pi. + await expect(browser.locator("[data-chat-provider-model-picker-label]").first()).toHaveText( + /sonnet|default/i, + { timeout: 60_000 }, + ); + await app.screenshot("composer"); + + await screen.getByRole("textbox").fill("Which model is this?"); + await screen.getByRole("textbox").press("Enter"); + const { cli } = makeState(T3_HOME); + await expect + .poll( + async () => { + const listed = await runPromise( + cli(["thread", "list", "--project", project, "--json"]), + ); + const threads = JSON.parse(listed.stdout) as Array<{ model: string }>; + return threads[0]?.model ?? null; + }, + { timeout: 30_000 }, + ) + .toBe(CHOSEN_MODEL); + } finally { + await NodeFSP.writeFile(settingsPath, originalSettings); + await NodeFSP.rm(fakePi, { force: true }); + } + }, +);