History

Add remote review diff plumbing

- Move review diff parsing and highlighting into shared mobile diff modules - Add review service and wire server, web, and mobile around remote review selection

Julius Marminge committed 6 months ago

Commit 92368021 parent 0c1ccda54 files · +1297 −11345Browse files

Unified · Split

54 files
  1. apps/mobile/package.json +1 −1
  2. apps/mobile/src/app/debug/native-review-diff.tsx +0 −528
  3. apps/mobile/src/app/debug/syntax-highlight.tsx +0 −1059
  4. apps/mobile/src/app/index.tsx +0 −5
  5. apps/mobile/src/features/debug/fixtures/README.md +0 −13
  6. apps/mobile/src/features/debug/fixtures/current-working-review.diff +0 −3208
  7. apps/mobile/src/features/debug/fixtures/review-large.diff +0 −3208
  8. apps/mobile/src/features/debug/fixtures/review-medium.diff +0 −1955
  9. apps/mobile/src/features/debug/fixtures/review-small.diff +0 −155
  10. apps/mobile/src/features/debug/fixtures/reviewDiffFixtures.ts +0 −238
  11. apps/mobile/src/features/debug/fixtures/reviewDiffXlFixture.ts +0 −4
  12. apps/mobile/src/features/debug/native-review-diff/nativeReviewDiffParser.test.ts +0 −156
  13. apps/mobile/src/features/debug/native-review-diff/nativeReviewDiffParser.ts +0 −549
  14. apps/mobile/src/features/diffs/nativeReviewDiffHighlighter.ts +2 −2
  15. apps/mobile/src/features/diffs/nativeReviewDiffSurface.test.ts +4 −4
  16. apps/mobile/src/features/diffs/nativeReviewDiffSurface.ts +0 −6
  17. apps/mobile/src/features/diffs/nativeReviewDiffTypes.ts +17 −0
  18. apps/mobile/src/features/review/ReviewSheet.tsx +4 −4
  19. apps/mobile/src/features/review/nativeReviewDiffAdapter.test.ts +1 −0
  20. apps/mobile/src/features/review/nativeReviewDiffAdapter.ts +2 −5
  21. apps/mobile/src/features/review/reviewCommentSelection.test.ts +21 −0
  22. apps/mobile/src/features/review/reviewCommentSelection.ts +92 −16
  23. apps/mobile/src/features/review/reviewModel.test.ts +16 −5
  24. apps/mobile/src/features/review/reviewModel.ts +5 −5
  25. apps/mobile/src/features/review/reviewState.ts +3 −3
  26. apps/mobile/src/features/threads/ThreadComposer.tsx +7 −0
  27. apps/mobile/src/features/threads/ThreadDetailScreen.tsx +4 −1
  28. apps/mobile/src/features/threads/ThreadFeed.tsx +298 −34
  29. apps/server/src/git/GitWorkflowService.ts +0 −9
  30. apps/server/src/review/ReviewService.ts +63 −0
  31. apps/server/src/server.test.ts +27 −10
  32. apps/server/src/server.ts +7 −0
  33. apps/server/src/vcs/GitVcsDriver.ts +5 −5
  34. apps/server/src/vcs/GitVcsDriverCore.ts +73 −32
  35. apps/server/src/vcs/VcsDriver.ts +5 −0
  36. apps/server/src/ws.ts +5 −3
  37. apps/web/src/components/ChatView.browser.tsx +1 −0
  38. apps/web/src/components/DiffPanel.tsx +8 −74
  39. apps/web/src/components/chat/MessagesTimeline.test.tsx +58 −0
  40. apps/web/src/components/chat/MessagesTimeline.tsx +182 −1
  41. apps/web/src/environmentApi.ts +3 −1
  42. apps/web/src/environments/runtime/connection.test.ts +3 −1
  43. apps/web/src/environments/runtime/service.threadSubscriptions.test.ts +3 −1
  44. apps/web/src/lib/diffRendering.ts +73 −0
  45. apps/web/src/localApi.test.ts +3 −1
  46. apps/web/src/reviewCommentContext.test.ts +77 −0
  47. apps/web/src/reviewCommentContext.ts +154 −0
  48. bun.lock +5 −5
  49. packages/client-runtime/src/wsRpcClient.ts +7 −3
  50. packages/contracts/src/git.ts +0 −24
  51. packages/contracts/src/index.ts +1 −0
  52. packages/contracts/src/ipc.ts +4 −3
  53. packages/contracts/src/review.ts +35 −0
  54. packages/contracts/src/rpc.ts +18 −8
apps/mobile/package.json+1−1
@@ -39,7 +39,7 @@ · 38 unmodified lines
39 "@effect/atom-react": "catalog:",39 "@effect/atom-react": "catalog:",
40 "@expo-google-fonts/dm-sans": "^0.4.2",40 "@expo-google-fonts/dm-sans": "^0.4.2",
41 "@legendapp/list": "3.0.0-beta.44",41 "@legendapp/list": "3.0.0-beta.44",
42 "@pierre/diffs": "^1.1.0-beta.16",42 "@pierre/diffs": "catalog:",
43 "@react-native-menu/menu": "^2.0.0",43 "@react-native-menu/menu": "^2.0.0",
44 "@shikijs/core": "3.23.0",44 "@shikijs/core": "3.23.0",
45 "@shikijs/engine-javascript": "3.23.0",45 "@shikijs/engine-javascript": "3.23.0",
apps/mobile/src/app/debug/native-review-diff.tsx+0−528
@@ -1,528 +0,0 @@
1import Stack from "expo-router/stack";
2import { useCallback, useEffect, useMemo, useRef, useState } from "react";
3import {
4 type LayoutChangeEvent,
5 StyleSheet,
6 Text as NativeText,
7 type NativeSyntheticEvent,
8 useColorScheme,
9 View,
10} from "react-native";
11import {
12 debugReviewDiffFixtures,
13 type DebugReviewDiffFixtureId,
14} from "../../features/debug/fixtures/reviewDiffFixtures";
15import {
16 getResolvedNativeReviewDiffModuleName,
17 type NativeReviewDiffStyle,
18 type NativeReviewDiffTheme,
19 resolveNativeReviewDiffView,
20} from "../../features/debug/native-review-diff/nativeReviewDiffModule";
21import {
22 highlightNativeReviewDiffVisibleRows,
23 streamNativeReviewDiffTokens,
24 type NativeReviewDiffHighlightEngine,
25} from "../../features/debug/native-review-diff/nativeReviewDiffHighlighter";
26import {
27 getNativeReviewDiffFixture,
28 parseNativeReviewDiffFixture,
29} from "../../features/debug/native-review-diff/nativeReviewDiffParser";
30import {
31 getPierreTerminalTheme,
32 type TerminalAppearanceScheme,
33} from "../../features/terminal/terminalTheme";
34
35const NATIVE_DEBUG_ROW_HEIGHT = 20;
36const NATIVE_DEBUG_CONTENT_WIDTH = 2800;
37const NATIVE_DEBUG_STYLE = {
38 rowHeight: NATIVE_DEBUG_ROW_HEIGHT,
39 contentWidth: NATIVE_DEBUG_CONTENT_WIDTH,
40 changeBarWidth: 4,
41 gutterWidth: 46,
42 codePadding: 7,
43 textVerticalInset: 2,
44 fileHeaderHeight: 56,
45 fileHeaderHorizontalMargin: 8,
46 fileHeaderVerticalMargin: 6,
47 fileHeaderCornerRadius: 10,
48 fileHeaderHorizontalPadding: 10,
49 fileHeaderPathRightPadding: 118,
50 fileHeaderCountColumnWidth: 38,
51 fileHeaderCountGap: 5,
52 codeFontSize: 11,
53 codeFontWeight: "regular",
54 lineNumberFontSize: 10,
55 lineNumberFontWeight: "regular",
56 hunkFontSize: 11,
57 hunkFontWeight: "medium",
58 fileHeaderFontSize: 11,
59 fileHeaderFontWeight: "semibold",
60 fileHeaderMetaFontSize: 10,
61 fileHeaderMetaFontWeight: "semibold",
62 fileHeaderSubtextFontSize: 11,
63 fileHeaderSubtextFontWeight: "medium",
64 fileHeaderStatusFontSize: 9,
65 fileHeaderStatusFontWeight: "bold",
66 emptyStateFontSize: 12,
67 emptyStateFontWeight: "medium",
68} satisfies NativeReviewDiffStyle;
69
70function createNativeReviewDiffTheme(scheme: TerminalAppearanceScheme): NativeReviewDiffTheme {
71 const terminalTheme = getPierreTerminalTheme(scheme);
72 const [, terminalRed, , , terminalBlue] = terminalTheme.palette;
73
74 if (scheme === "dark") {
75 return {
76 background: terminalTheme.background,
77 text: terminalTheme.foreground,
78 mutedText: terminalTheme.mutedForeground,
79 headerBackground: terminalTheme.background,
80 border: terminalTheme.border,
81 hunkBackground: "#071f28",
82 hunkText: terminalBlue ?? "#009fff",
83 addBackground: "#0d2f28",
84 deleteBackground: "#391415",
85 addBar: "#00cab1",
86 deleteBar: terminalRed ?? "#ff2e3f",
87 addText: "#5ECC71",
88 deleteText: "#FF6762",
89 };
90 }
91
92 return {
93 background: "#ffffff",
94 text: "#070707",
95 mutedText: terminalTheme.mutedForeground,
96 headerBackground: "#ffffff",
97 border: terminalTheme.border,
98 hunkBackground: "#e0f2ff",
99 hunkText: terminalBlue ?? "#009fff",
100 addBackground: "#e5f8f5",
101 deleteBackground: "#ffe6e7",
102 addBar: "#00cab1",
103 deleteBar: terminalRed ?? "#ff2e3f",
104 addText: "#199F43",
105 deleteText: "#D52C36",
106 };
107}
108
109export default function NativeReviewDiffDebugRoute() {
110 const colorScheme = useColorScheme() === "dark" ? "dark" : "light";
111 const [fixtureId, setFixtureId] = useState<DebugReviewDiffFixtureId>("large");
112 const [highlightEngine, setHighlightEngine] = useState<NativeReviewDiffHighlightEngine>("native");
113 const [collapsedFileIds, setCollapsedFileIds] = useState<ReadonlyArray<string>>([]);
114 const [viewedFileIds, setViewedFileIds] = useState<ReadonlyArray<string>>([]);
115 const fixture = getNativeReviewDiffFixture(fixtureId);
116 const parsed = useMemo(() => parseNativeReviewDiffFixture(fixture), [fixture]);
117 const effectiveHighlightEngine: NativeReviewDiffHighlightEngine =
118 fixtureId === "xl" && highlightEngine === "native" ? "javascript" : highlightEngine;
119 const useVisibleOnlyHighlighting = fixtureId === "xl";
120 const debugTheme = useMemo(() => createNativeReviewDiffTheme(colorScheme), [colorScheme]);
121 const rowsJson = useMemo(() => JSON.stringify(parsed.rows), [parsed.rows]);
122 const collapsedFileIdsJson = useMemo(() => JSON.stringify(collapsedFileIds), [collapsedFileIds]);
123 const viewedFileIdsJson = useMemo(() => JSON.stringify(viewedFileIds), [viewedFileIds]);
124 const themeJson = useMemo(() => JSON.stringify(debugTheme), [debugTheme]);
125 const styleJson = useMemo(() => JSON.stringify(NATIVE_DEBUG_STYLE), []);
126 const tokensResetKey = `${fixtureId}:${colorScheme}:${effectiveHighlightEngine}`;
127 const [tokensPatchJson, setTokensPatchJson] = useState(
128 JSON.stringify({ resetKey: "", tokensByRowId: {} }),
129 );
130 const highlightedRowIdsRef = useRef<Set<string>>(new Set());
131 const visibleRangeRef = useRef({ firstRowIndex: 0, lastRowIndex: 80 });
132 const visibleChunkIndexRef = useRef(0);
133 const useVisibleOnlyHighlightingRef = useRef(useVisibleOnlyHighlighting);
134 const [visibleHighlightRequest, setVisibleHighlightRequest] = useState(0);
135 const NativeReviewDiffView = resolveNativeReviewDiffView();
136 const handleSelectFixture = useCallback((nextFixtureId: DebugReviewDiffFixtureId) => {
137 setFixtureId(nextFixtureId);
138 }, []);
139 useEffect(() => {
140 useVisibleOnlyHighlightingRef.current = useVisibleOnlyHighlighting;
141 }, [useVisibleOnlyHighlighting]);
142 useEffect(() => {
143 setCollapsedFileIds([]);
144 setViewedFileIds([]);
145 }, [fixtureId]);
146 useEffect(() => {
147 const abortController = new AbortController();
148 highlightedRowIdsRef.current = new Set();
149 visibleChunkIndexRef.current = 0;
150 setTokensPatchJson(JSON.stringify({ resetKey: tokensResetKey, tokensByRowId: {} }));
151 if (useVisibleOnlyHighlighting) {
152 setVisibleHighlightRequest((request) => request + 1);
153 console.log("[debug-native-diff] visible-only highlight start", {
154 fixture: fixtureId,
155 files: parsed.files.length,
156 rows: parsed.rows.length,
157 scheme: colorScheme,
158 effectiveEngine: effectiveHighlightEngine,
159 requestedEngine: highlightEngine,
160 });
161 return () => abortController.abort();
162 }
163
164 void (async () => {
165 const startedAt = performance.now();
166 console.log("[debug-native-diff] highlight start", {
167 fixture: fixtureId,
168 files: parsed.files.length,
169 rows: parsed.rows.length,
170 scheme: colorScheme,
171 effectiveEngine: effectiveHighlightEngine,
172 requestedEngine: highlightEngine,
173 });
174
175 try {
176 const engine = await streamNativeReviewDiffTokens({
177 files: parsed.files,
178 rows: parsed.rows,
179 scheme: colorScheme,
180 engine: effectiveHighlightEngine,
181 signal: abortController.signal,
182 onChunk: (chunk) => {
183 if (abortController.signal.aborted) {
184 return;
185 }
186
187 setTokensPatchJson(JSON.stringify({ resetKey: tokensResetKey, ...chunk }));
188 if (chunk.chunkIndex < 5 || chunk.chunkIndex % 10 === 0) {
189 console.log("[debug-native-diff] highlight chunk", {
190 chunkIndex: chunk.chunkIndex,
191 durationMs: chunk.durationMs,
192 filePath: chunk.filePath,
193 lineCount: chunk.lineCount,
194 });
195 }
196 },
197 });
198
199 if (!abortController.signal.aborted) {
200 console.log("[debug-native-diff] highlight complete", {
201 durationMs: Math.round(performance.now() - startedAt),
202 engine,
203 fixture: fixtureId,
204 effectiveEngine: effectiveHighlightEngine,
205 requestedEngine: highlightEngine,
206 });
207 }
208 } catch (error) {
209 if (!abortController.signal.aborted) {
210 console.warn("[debug-native-diff] highlight failed", {
211 error: error instanceof Error ? error.message : String(error),
212 });
213 }
214 }
215 })();
216
217 return () => abortController.abort();
218 }, [
219 colorScheme,
220 effectiveHighlightEngine,
221 fixtureId,
222 highlightEngine,
223 parsed.files,
224 parsed.rows,
225 tokensResetKey,
226 useVisibleOnlyHighlighting,
227 ]);
228 useEffect(() => {
229 if (!useVisibleOnlyHighlighting) {
230 return;
231 }
232
233 const abortController = new AbortController();
234 const requestRange = visibleRangeRef.current;
235
236 void (async () => {
237 try {
238 const result = await highlightNativeReviewDiffVisibleRows({
239 files: parsed.files,
240 rows: parsed.rows,
241 scheme: colorScheme,
242 engine: effectiveHighlightEngine,
243 firstRowIndex: requestRange.firstRowIndex,
244 lastRowIndex: requestRange.lastRowIndex,
245 alreadyHighlightedRowIds: highlightedRowIdsRef.current,
246 signal: abortController.signal,
247 });
248
249 if (abortController.signal.aborted || result.rowCount === 0) {
250 return;
251 }
252
253 for (const rowId of Object.keys(result.tokensByRowId)) {
254 highlightedRowIdsRef.current.add(rowId);
255 }
256
257 const chunkIndex = visibleChunkIndexRef.current;
258 visibleChunkIndexRef.current += 1;
259 setTokensPatchJson(
260 JSON.stringify({
261 resetKey: tokensResetKey,
262 chunkIndex,
263 fileId: "visible",
264 filePath: "visible rows",
265 language: "diff",
266 lineCount: result.rowCount,
267 durationMs: result.durationMs,
268 tokensByRowId: result.tokensByRowId,
269 }),
270 );
271 if (chunkIndex < 2 || chunkIndex % 10 === 0) {
272 console.log("[debug-native-diff] visible highlight chunk", {
273 chunkIndex,
274 durationMs: result.durationMs,
275 highlightedRows: result.rowCount,
276 firstRowIndex: requestRange.firstRowIndex,
277 lastRowIndex: requestRange.lastRowIndex,
278 });
279 }
280 } catch (error) {
281 if (!abortController.signal.aborted) {
282 console.warn("[debug-native-diff] visible highlight failed", {
283 error: error instanceof Error ? error.message : String(error),
284 });
285 }
286 }
287 })();
288
289 return () => abortController.abort();
290 }, [
291 colorScheme,
292 effectiveHighlightEngine,
293 parsed.files,
294 parsed.rows,
295 tokensResetKey,
296 useVisibleOnlyHighlighting,
297 visibleHighlightRequest,
298 ]);
299 useEffect(() => {
300 console.log("[debug-native-diff] native view availability", {
301 available: NativeReviewDiffView != null,
302 moduleName: getResolvedNativeReviewDiffModuleName(),
303 rowsJsonLength: rowsJson.length,
304 });
305 }, [NativeReviewDiffView, rowsJson.length]);
306 const handleNativeContainerLayout = useCallback((event: LayoutChangeEvent) => {
307 const { height, width } = event.nativeEvent.layout;
308 console.log("[debug-native-diff] native container layout", {
309 height: Math.round(height),
310 width: Math.round(width),
311 });
312 }, []);
313 const handleNativeLayout = useCallback((event: LayoutChangeEvent) => {
314 const { height, width } = event.nativeEvent.layout;
315 console.log("[debug-native-diff] native view layout", {
316 height: Math.round(height),
317 width: Math.round(width),
318 });
319 }, []);
320 const handleNativeDebug = useCallback((event: NativeSyntheticEvent<Record<string, unknown>>) => {
321 const payload = event.nativeEvent;
322 const message = payload.message;
323
324 if (
325 useVisibleOnlyHighlightingRef.current &&
326 (message === "draw-metrics" || message === "visible-range") &&
327 typeof payload.firstRowIndex === "number" &&
328 typeof payload.lastRowIndex === "number"
329 ) {
330 const previousRange = visibleRangeRef.current;
331 const nextRange = {
332 firstRowIndex: payload.firstRowIndex,
333 lastRowIndex: payload.lastRowIndex,
334 };
335 const movedRows =
336 Math.abs(nextRange.firstRowIndex - previousRange.firstRowIndex) +
337 Math.abs(nextRange.lastRowIndex - previousRange.lastRowIndex);
338
339 visibleRangeRef.current = nextRange;
340 if (movedRows >= 20) {
341 setVisibleHighlightRequest((request) => request + 1);
342 }
343 }
344 }, []);
345 const handleToggleFile = useCallback(
346 (event: NativeSyntheticEvent<{ readonly fileId?: string }>) => {
347 const { fileId } = event.nativeEvent;
348 if (!fileId) {
349 return;
350 }
351
352 setCollapsedFileIds((current) =>
353 current.includes(fileId) ? current.filter((id) => id !== fileId) : [...current, fileId],
354 );
355 },
356 [],
357 );
358 const handleToggleViewedFile = useCallback(
359 (event: NativeSyntheticEvent<{ readonly fileId?: string }>) => {
360 const { fileId } = event.nativeEvent;
361 if (!fileId) {
362 return;
363 }
364
365 setViewedFileIds((current) => {
366 if (current.includes(fileId)) {
367 return current.filter((id) => id !== fileId);
368 }
369
370 setCollapsedFileIds((collapsed) =>
371 collapsed.includes(fileId) ? collapsed : [...collapsed, fileId],
372 );
373 return [...current, fileId];
374 });
375 },
376 [],
377 );
378
379 return (
380 <>
381 <Stack.Screen
382 options={{
383 headerShown: true,
384 headerShadowVisible: false,
385 headerStyle: { backgroundColor: debugTheme.background },
386 headerTintColor: debugTheme.text,
387 headerTitleAlign: "center",
388 title: "",
389 headerTitle: () => (
390 <View style={{ alignItems: "center", maxWidth: 240 }}>
391 <NativeText
392 numberOfLines={1}
393 style={{
394 color: debugTheme.text,
395 fontFamily: "DMSans_700Bold",
396 fontSize: 13,
397 lineHeight: 16,
398 }}
399 >
400 Native review diff
401 </NativeText>
402 <NativeText
403 numberOfLines={1}
404 style={{
405 color: debugTheme.mutedText,
406 fontFamily: "DMSans_700Bold",
407 fontSize: 11,
408 lineHeight: 14,
409 }}
410 >
411 {parsed.files.length} files · {parsed.rows.length} rows · +{parsed.additions} -
412 {parsed.deletions} · {effectiveHighlightEngine === "native" ? "native" : "JS"}
413 {fixtureId === "xl" && highlightEngine === "native" ? " fallback" : ""}
414 </NativeText>
415 </View>
416 ),
417 }}
418 />
419
420 <Stack.Toolbar placement="right">
421 <Stack.Toolbar.Menu
422 icon="line.3.horizontal.decrease.circle"
423 title="Diff debug options"
424 separateBackground
425 >
426 <Stack.Toolbar.Menu icon="sparkles" inline title="Highlighter engine">
427 <Stack.Toolbar.Label>Highlighter engine</Stack.Toolbar.Label>
428 {(["native", "javascript"] as const).map((engine) => {
429 const isSelected = engine === highlightEngine;
430 return (
431 <Stack.Toolbar.MenuAction
432 key={engine}
433 icon="circle"
434 isOn={isSelected}
435 onPress={() => setHighlightEngine(engine)}
436 subtitle={
437 engine === "native" && fixtureId === "xl"
438 ? "XL currently falls back after native engine crash"
439 : engine === "native"
440 ? "react-native-shiki-engine"
441 : "JavaScript regex engine"
442 }
443 >
444 <Stack.Toolbar.Label>
445 {engine === "native" ? "Native" : "JavaScript"}
446 </Stack.Toolbar.Label>
447 </Stack.Toolbar.MenuAction>
448 );
449 })}
450 </Stack.Toolbar.Menu>
451
452 <Stack.Toolbar.Menu icon="doc.text" inline title="Fixture">
453 <Stack.Toolbar.Label>Fixture</Stack.Toolbar.Label>
454 {debugReviewDiffFixtures.map((candidate) => {
455 const isSelected = candidate.id === fixtureId;
456 return (
457 <Stack.Toolbar.MenuAction
458 key={candidate.id}
459 icon="doc.text"
460 isOn={isSelected}
461 onPress={() => handleSelectFixture(candidate.id)}
462 subtitle={`${candidate.lineCount} patch lines`}
463 >
464 <Stack.Toolbar.Label>{candidate.label}</Stack.Toolbar.Label>
465 </Stack.Toolbar.MenuAction>
466 );
467 })}
468 </Stack.Toolbar.Menu>
469 </Stack.Toolbar.Menu>
470 </Stack.Toolbar>
471
472 <View
473 className="relative flex-1"
474 style={{ backgroundColor: debugTheme.background }}
475 collapsable={false}
476 onLayout={handleNativeContainerLayout}
477 >
478 {NativeReviewDiffView ? (
479 <NativeReviewDiffView
480 key={fixtureId}
481 collapsable={false}
482 testID="native-review-diff-view"
483 style={StyleSheet.absoluteFillObject}
484 appearanceScheme={colorScheme}
485 contentWidth={NATIVE_DEBUG_CONTENT_WIDTH}
486 collapsedFileIdsJson={collapsedFileIdsJson}
487 rowHeight={NATIVE_DEBUG_ROW_HEIGHT}
488 rowsJson={rowsJson}
489 styleJson={styleJson}
490 themeJson={themeJson}
491 tokensResetKey={tokensResetKey}
492 tokensPatchJson={tokensPatchJson}
493 viewedFileIdsJson={viewedFileIdsJson}
494 onDebug={handleNativeDebug}
495 onLayout={handleNativeLayout}
496 onToggleFile={handleToggleFile}
497 onToggleViewedFile={handleToggleViewedFile}
498 />
499 ) : (
500 <View className="flex-1 items-center justify-center px-8">
501 <NativeText
502 style={{
503 color: debugTheme.text,
504 fontFamily: "DMSans_700Bold",
505 fontSize: 14,
506 textAlign: "center",
507 }}
508 >
509 Native review diff view is not available in this build.
510 </NativeText>
511 <NativeText
512 style={{
513 color: debugTheme.mutedText,
514 fontFamily: "DMSans_400Regular",
515 fontSize: 12,
516 marginTop: 8,
517 textAlign: "center",
518 }}
519 >
520 Expected native view manager: T3ReviewDiffSurface. Rebuild the current iOS development
521 client with `bun ios` after native module changes.
522 </NativeText>
523 </View>
524 )}
525 </View>
526 </>
527 );
528}
apps/mobile/src/app/debug/syntax-highlight.tsx+0−1059
@@ -1,1059 +0,0 @@
1import { createHighlighterCore, type HighlighterCore } from "@shikijs/core";
2import { createJavaScriptRegexEngine } from "@shikijs/engine-javascript";
3import bashLanguage from "@shikijs/langs/bash";
4import diffLanguage from "@shikijs/langs/diff";
5import javascriptLanguage from "@shikijs/langs/javascript";
6import jsonLanguage from "@shikijs/langs/json";
7import jsxLanguage from "@shikijs/langs/jsx";
8import tsxLanguage from "@shikijs/langs/tsx";
9import typescriptLanguage from "@shikijs/langs/typescript";
10import yamlLanguage from "@shikijs/langs/yaml";
11import githubDarkDefault from "@shikijs/themes/github-dark-default";
12import githubLightDefault from "@shikijs/themes/github-light-default";
13import Stack from "expo-router/stack";
14import {
15 memo,
16 type ReactElement,
17 useCallback,
18 useEffect,
19 useMemo,
20 useRef,
21 useState,
22 useSyncExternalStore,
23} from "react";
24import {
25 Animated,
26 FlatList,
27 PanResponder,
28 Pressable,
29 ScrollView,
30 Text as NativeText,
31 type ListRenderItemInfo,
32 useColorScheme,
33 useWindowDimensions,
34 View,
35} from "react-native";
36import { useSafeAreaInsets } from "react-native-safe-area-context";
37
38import { AppText as Text } from "../../components/AppText";
39import {
40 debugReviewDiffFixtures,
41 type DebugReviewDiffFixture,
42 type DebugReviewDiffFixtureId,
43} from "../../features/debug/fixtures/reviewDiffFixtures";
44import { cn } from "../../lib/cn";
45import { useThemeColor } from "../../lib/useThemeColor";
46
47type DebugHighlightEngine = "native" | "javascript";
48type DebugDiffChange = "context" | "add" | "delete";
49type DebugDiffLanguage =
50 | "bash"
51 | "diff"
52 | "javascript"
53 | "json"
54 | "jsx"
55 | "tsx"
56 | "typescript"
57 | "yaml";
58
59type DebugToken = {
60 readonly content: string;
61 readonly color: string | null;
62 readonly fontStyle: number | null;
63};
64
65type DebugDiffFile = {
66 readonly id: string;
67 readonly path: string;
68 readonly language: DebugDiffLanguage;
69 readonly additions: number;
70 readonly deletions: number;
71};
72
73type DebugDiffFileHeaderRow = {
74 readonly kind: "file";
75 readonly id: string;
76 readonly fileId: string;
77 readonly filePath: string;
78 readonly language: DebugDiffLanguage;
79 readonly additions: number;
80 readonly deletions: number;
81};
82
83type DebugDiffHunkRow = {
84 readonly kind: "hunk";
85 readonly id: string;
86 readonly fileId: string;
87 readonly text: string;
88};
89
90type DebugDiffCodeRow = {
91 readonly kind: "line";
92 readonly id: string;
93 readonly fileId: string;
94 readonly change: DebugDiffChange;
95 readonly oldLineNumber: number | null;
96 readonly newLineNumber: number | null;
97 readonly content: string;
98 readonly highlightChunkId: string;
99 readonly indexInHighlightChunk: number;
100};
101
102type DebugDiffRow = DebugDiffFileHeaderRow | DebugDiffHunkRow | DebugDiffCodeRow;
103
104type DebugHighlightChunk = {
105 readonly id: string;
106 readonly fileId: string;
107 readonly language: DebugDiffLanguage;
108 readonly rows: ReadonlyArray<DebugDiffCodeRow>;
109};
110
111type DebugParsedDiff = {
112 readonly files: ReadonlyArray<DebugDiffFile>;
113 readonly rows: ReadonlyArray<DebugDiffRow>;
114 readonly highlightChunks: ReadonlyArray<DebugHighlightChunk>;
115 readonly additions: number;
116 readonly deletions: number;
117};
118
119type DebugHighlighterHandle = {
120 readonly engine: DebugHighlightEngine;
121 readonly tokenize: (
122 code: string,
123 options: { readonly lang: DebugDiffLanguage; readonly theme: string },
124 ) => ReadonlyArray<ReadonlyArray<DebugToken>>;
125};
126
127const DEBUG_HIGHLIGHT_CHUNK_SIZE = 500;
128const DEBUG_DIFF_ROW_HEIGHT = 28;
129const DEBUG_CHANGE_BAR_WIDTH = 4;
130const DEBUG_GUTTER_WIDTH = 58;
131const DEBUG_STICKY_WIDTH = DEBUG_CHANGE_BAR_WIDTH + DEBUG_GUTTER_WIDTH;
132const DEBUG_CONTENT_WIDTH = 3_000;
133const DEBUG_DELETE_STRIPE_COUNT = DEBUG_DIFF_ROW_HEIGHT / 2;
134const DEBUG_MONO_FONT_FAMILY = "BerkeleyMono-Regular";
135const DEBUG_CODE_TEXT_STYLE = {
136 fontFamily: DEBUG_MONO_FONT_FAMILY,
137 fontStyle: "normal" as const,
138 fontWeight: "700" as const,
139};
140const DEBUG_DELETE_STRIPE_INDICES = Array.from(
141 { length: DEBUG_DELETE_STRIPE_COUNT },
142 (_, index) => index,
143);
144const DEBUG_THEME_NAME_BY_SCHEME = {
145 dark: "github-dark-default",
146 light: "github-light-default",
147} as const;
148
149const DEBUG_LANGUAGES = [
150 bashLanguage,
151 diffLanguage,
152 javascriptLanguage,
153 jsonLanguage,
154 jsxLanguage,
155 tsxLanguage,
156 typescriptLanguage,
157 yamlLanguage,
158] satisfies Parameters<typeof createHighlighterCore>[0]["langs"];
159
160let nativeHighlighterPromise: Promise<DebugHighlighterHandle> | null = null;
161let javascriptHighlighterPromise: Promise<DebugHighlighterHandle> | null = null;
162
163class DebugTokenStore {
164 private readonly fileVersions = new Map<string, number>();
165 private readonly listenersByFileId = new Map<string, Set<() => void>>();
166 private resetVersion = 0;
167 private readonly tokensByChunkId = new Map<string, ReadonlyArray<ReadonlyArray<DebugToken>>>();
168
169 getFileVersion(fileId: string): string {
170 return `${this.resetVersion}:${this.fileVersions.get(fileId) ?? 0}`;
171 }
172
173 getTokens(chunkId: string): ReadonlyArray<ReadonlyArray<DebugToken>> | null {
174 return this.tokensByChunkId.get(chunkId) ?? null;
175 }
176
177 reset(): void {
178 this.tokensByChunkId.clear();
179 this.fileVersions.clear();
180 this.resetVersion += 1;
181 this.listenersByFileId.forEach((listeners) => {
182 listeners.forEach((listener) => listener());
183 });
184 }
185
186 setChunk(chunk: DebugHighlightChunk, tokens: ReadonlyArray<ReadonlyArray<DebugToken>>): void {
187 this.tokensByChunkId.set(chunk.id, tokens);
188 this.fileVersions.set(chunk.fileId, (this.fileVersions.get(chunk.fileId) ?? 0) + 1);
189 this.listenersByFileId.get(chunk.fileId)?.forEach((listener) => listener());
190 }
191
192 subscribeFile(fileId: string, listener: () => void): () => void {
193 let listeners = this.listenersByFileId.get(fileId);
194 if (!listeners) {
195 listeners = new Set();
196 this.listenersByFileId.set(fileId, listeners);
197 }
198
199 listeners.add(listener);
200 return () => {
201 listeners?.delete(listener);
202 if (listeners?.size === 0) {
203 this.listenersByFileId.delete(fileId);
204 }
205 };
206 }
207}
208
209class DebugHorizontalOffsetStore {
210 private readonly offsetsByFileId = new Map<string, number>();
211 private readonly valuesByFileId = new Map<string, Animated.Value>();
212
213 getOffset(fileId: string): number {
214 return this.offsetsByFileId.get(fileId) ?? 0;
215 }
216
217 getValue(fileId: string): Animated.Value {
218 let value = this.valuesByFileId.get(fileId);
219 if (!value) {
220 value = new Animated.Value(-this.getOffset(fileId));
221 this.valuesByFileId.set(fileId, value);
222 }
223 return value;
224 }
225
226 reset(): void {
227 this.valuesByFileId.forEach((value) => value.stopAnimation());
228 this.valuesByFileId.clear();
229 this.offsetsByFileId.clear();
230 }
231
232 setOffset(fileId: string, offset: number): void {
233 this.offsetsByFileId.set(fileId, offset);
234 this.getValue(fileId).setValue(-offset);
235 }
236}
237
238function waitForNextFrame(): Promise<void> {
239 return new Promise((resolve) => setTimeout(resolve, 0));
240}
241
242function normalizeTokens(
243 tokenLines: ReadonlyArray<ReadonlyArray<{ content: string; color?: string; fontStyle?: number }>>,
244): ReadonlyArray<ReadonlyArray<DebugToken>> {
245 return tokenLines.map((line) =>
246 line.map((token) => ({
247 content: token.content,
248 color: token.color ?? null,
249 fontStyle: token.fontStyle ?? null,
250 })),
251 );
252}
253
254async function createNativeDebugHighlighter(): Promise<DebugHighlighterHandle> {
255 const nativeEngineModule = await import("react-native-shiki-engine");
256 if (!nativeEngineModule.isNativeEngineAvailable()) {
257 throw new Error("Native Shiki engine is not available in this build.");
258 }
259
260 const highlighter = await createHighlighterCore({
261 langs: DEBUG_LANGUAGES,
262 themes: [githubLightDefault, githubDarkDefault],
263 engine: nativeEngineModule.createNativeEngine(),
264 });
265
266 return {
267 engine: "native",
268 tokenize: (code, options) => normalizeTokens(highlighter.codeToTokensBase(code, options)),
269 };
270}
271
272async function createJavascriptDebugHighlighter(): Promise<DebugHighlighterHandle> {
273 const highlighter: HighlighterCore = await createHighlighterCore({
274 langs: DEBUG_LANGUAGES,
275 themes: [githubLightDefault, githubDarkDefault],
276 engine: createJavaScriptRegexEngine(),
277 });
278
279 return {
280 engine: "javascript",
281 tokenize: (code, options) => normalizeTokens(highlighter.codeToTokensBase(code, options)),
282 };
283}
284
285async function getDebugHighlighter(engine: DebugHighlightEngine): Promise<DebugHighlighterHandle> {
286 if (engine === "native") {
287 nativeHighlighterPromise ??= createNativeDebugHighlighter();
288 return nativeHighlighterPromise;
289 }
290
291 javascriptHighlighterPromise ??= createJavascriptDebugHighlighter();
292 return javascriptHighlighterPromise;
293}
294
295function getDiffPathFromHeader(line: string): string {
296 const match = line.match(/^diff --git a\/(.+) b\/(.+)$/);
297 return match?.[2] ?? line.replace(/^diff --git /, "");
298}
299
300function getLanguageForPath(filePath: string): DebugDiffLanguage {
301 const normalizedPath = filePath.toLowerCase();
302 if (normalizedPath.endsWith(".tsx")) return "tsx";
303 if (normalizedPath.endsWith(".ts")) return "typescript";
304 if (normalizedPath.endsWith(".jsx")) return "jsx";
305 if (normalizedPath.endsWith(".js") || normalizedPath.endsWith(".cjs")) return "javascript";
306 if (normalizedPath.endsWith(".json") || normalizedPath.endsWith(".jsonc")) return "json";
307 if (normalizedPath.endsWith(".yml") || normalizedPath.endsWith(".yaml")) return "yaml";
308 if (
309 normalizedPath.endsWith(".sh") ||
310 normalizedPath.includes("/bin/") ||
311 normalizedPath.includes("shell")
312 ) {
313 return "bash";
314 }
315 return "diff";
316}
317
318function parseHunkLineNumbers(line: string): { oldLine: number; newLine: number } | null {
319 const match = line.match(/^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/);
320 if (!match) {
321 return null;
322 }
323 return {
324 oldLine: Number(match[1]),
325 newLine: Number(match[2]),
326 };
327}
328
329function makeChunkId(fileId: string, chunkIndex: number): string {
330 return `${fileId}:chunk:${chunkIndex}`;
331}
332
333function parseDebugDiffFixture(fixture: DebugReviewDiffFixture): DebugParsedDiff {
334 const startedAt = performance.now();
335 const rows: DebugDiffRow[] = [];
336 const files = new Map<
337 string,
338 { path: string; language: DebugDiffLanguage; additions: number; deletions: number }
339 >();
340 const fileLineRows = new Map<string, DebugDiffCodeRow[]>();
341 const rawLines = fixture.diff.split(/\r?\n/);
342
343 let currentFileId: string | null = null;
344 let currentOldLine: number | null = null;
345 let currentNewLine: number | null = null;
346
347 function ensureCurrentFile(filePath: string): string {
348 const fileId = `file:${files.size}:${filePath}`;
349 files.set(fileId, {
350 path: filePath,
351 language: getLanguageForPath(filePath),
352 additions: 0,
353 deletions: 0,
354 });
355 fileLineRows.set(fileId, []);
356 rows.push({
357 kind: "file",
358 id: `${fileId}:header`,
359 fileId,
360 filePath,
361 language: getLanguageForPath(filePath),
362 additions: 0,
363 deletions: 0,
364 });
365 return fileId;
366 }
367
368 for (let index = 0; index < rawLines.length; index += 1) {
369 const rawLine = rawLines[index] ?? "";
370 if (rawLine.startsWith("diff --git ")) {
371 currentFileId = ensureCurrentFile(getDiffPathFromHeader(rawLine));
372 currentOldLine = null;
373 currentNewLine = null;
374 continue;
375 }
376
377 if (!currentFileId) {
378 continue;
379 }
380
381 if (rawLine.startsWith("@@ ")) {
382 const parsedLineNumbers = parseHunkLineNumbers(rawLine);
383 currentOldLine = parsedLineNumbers?.oldLine ?? null;
384 currentNewLine = parsedLineNumbers?.newLine ?? null;
385 rows.push({
386 kind: "hunk",
387 id: `${currentFileId}:hunk:${index}`,
388 fileId: currentFileId,
389 text: rawLine,
390 });
391 continue;
392 }
393
394 if (rawLine.startsWith("+++") || rawLine.startsWith("---")) {
395 continue;
396 }
397
398 const marker = rawLine[0];
399 if (marker !== " " && marker !== "+" && marker !== "-") {
400 continue;
401 }
402
403 const file = files.get(currentFileId);
404 if (!file) {
405 continue;
406 }
407
408 const change: DebugDiffChange = marker === "+" ? "add" : marker === "-" ? "delete" : "context";
409 const oldLineNumber = change === "add" ? null : currentOldLine;
410 const newLineNumber = change === "delete" ? null : currentNewLine;
411 const lineRows = fileLineRows.get(currentFileId) ?? [];
412 const chunkIndex = Math.floor(lineRows.length / DEBUG_HIGHLIGHT_CHUNK_SIZE);
413 const codeRow: DebugDiffCodeRow = {
414 kind: "line",
415 id: `${currentFileId}:line:${index}`,
416 fileId: currentFileId,
417 change,
418 oldLineNumber,
419 newLineNumber,
420 content: rawLine.slice(1),
421 highlightChunkId: makeChunkId(currentFileId, chunkIndex),
422 indexInHighlightChunk: lineRows.length % DEBUG_HIGHLIGHT_CHUNK_SIZE,
423 };
424
425 rows.push(codeRow);
426 lineRows.push(codeRow);
427 fileLineRows.set(currentFileId, lineRows);
428
429 if (change === "add") {
430 files.set(currentFileId, { ...file, additions: file.additions + 1 });
431 currentNewLine = currentNewLine === null ? null : currentNewLine + 1;
432 continue;
433 }
434
435 if (change === "delete") {
436 files.set(currentFileId, { ...file, deletions: file.deletions + 1 });
437 currentOldLine = currentOldLine === null ? null : currentOldLine + 1;
438 continue;
439 }
440
441 currentOldLine = currentOldLine === null ? null : currentOldLine + 1;
442 currentNewLine = currentNewLine === null ? null : currentNewLine + 1;
443 }
444
445 const fileSummaries = Array.from(files, ([id, file]) => ({ id, ...file }));
446 const fileSummaryById = new Map(fileSummaries.map((file) => [file.id, file]));
447 const rowsWithFileStats = rows.map((row): DebugDiffRow => {
448 if (row.kind !== "file") {
449 return row;
450 }
451 const file = fileSummaryById.get(row.fileId);
452 return {
453 kind: row.kind,
454 id: row.id,
455 fileId: row.fileId,
456 filePath: row.filePath,
457 language: row.language,
458 additions: file?.additions ?? row.additions,
459 deletions: file?.deletions ?? row.deletions,
460 };
461 });
462 const highlightChunks: DebugHighlightChunk[] = [];
463 fileLineRows.forEach((lineRows, fileId) => {
464 const file = fileSummaryById.get(fileId);
465 if (!file) {
466 return;
467 }
468 for (
469 let startIndex = 0;
470 startIndex < lineRows.length;
471 startIndex += DEBUG_HIGHLIGHT_CHUNK_SIZE
472 ) {
473 const chunkIndex = startIndex / DEBUG_HIGHLIGHT_CHUNK_SIZE;
474 highlightChunks.push({
475 id: makeChunkId(fileId, chunkIndex),
476 fileId,
477 language: file.language,
478 rows: lineRows.slice(startIndex, startIndex + DEBUG_HIGHLIGHT_CHUNK_SIZE),
479 });
480 }
481 });
482
483 const parsed = {
484 files: fileSummaries,
485 rows: rowsWithFileStats,
486 highlightChunks,
487 additions: fileSummaries.reduce((total, file) => total + file.additions, 0),
488 deletions: fileSummaries.reduce((total, file) => total + file.deletions, 0),
489 };
490
491 console.log("[debug-diff-scratch] parse", {
492 durationMs: Math.round(performance.now() - startedAt),
493 fixture: fixture.id,
494 files: parsed.files.length,
495 highlightChunks: parsed.highlightChunks.length,
496 rows: parsed.rows.length,
497 });
498
499 return parsed;
500}
501
502const TokenText = memo(function TokenText(props: {
503 readonly content: string;
504 readonly tokens: ReadonlyArray<DebugToken> | null;
505}) {
506 if (!props.tokens) {
507 return (
508 <NativeText
509 numberOfLines={1}
510 className="text-[13px] leading-[18px] text-foreground"
511 style={DEBUG_CODE_TEXT_STYLE}
512 >
513 {props.content || " "}
514 </NativeText>
515 );
516 }
517
518 let tokenOffset = 0;
519
520 return (
521 <NativeText
522 numberOfLines={1}
523 className="text-[13px] leading-[18px] text-foreground"
524 style={DEBUG_CODE_TEXT_STYLE}
525 >
526 {props.tokens.map((token) => {
527 const tokenKey = `${tokenOffset}:${token.content.length}:${token.color ?? ""}:${token.fontStyle ?? ""}`;
528 tokenOffset += token.content.length;
529
530 return (
531 <NativeText
532 key={tokenKey}
533 style={{
534 ...DEBUG_CODE_TEXT_STYLE,
535 color: token.color ?? undefined,
536 }}
537 >
538 {token.content}
539 </NativeText>
540 );
541 })}
542 </NativeText>
543 );
544});
545
546function changeRowClassName(change: DebugDiffChange): string {
547 if (change === "add") return "bg-emerald-500/10";
548 if (change === "delete") return "bg-rose-500/10";
549 return "bg-card";
550}
551
552const DebugChangeBar = memo(function DebugChangeBar(props: { readonly change: DebugDiffChange }) {
553 if (props.change === "delete") {
554 return (
555 <View className="overflow-hidden" style={{ width: DEBUG_CHANGE_BAR_WIDTH }}>
556 {DEBUG_DELETE_STRIPE_INDICES.map((index) => (
557 <View key={index}>
558 <View className="bg-rose-400" style={{ height: 1, width: DEBUG_CHANGE_BAR_WIDTH }} />
559 <View style={{ height: 1, width: DEBUG_CHANGE_BAR_WIDTH }} />
560 </View>
561 ))}
562 </View>
563 );
564 }
565
566 if (props.change === "add") {
567 return <View className="bg-emerald-400" style={{ width: DEBUG_CHANGE_BAR_WIDTH }} />;
568 }
569
570 return <View style={{ width: DEBUG_CHANGE_BAR_WIDTH }} />;
571});
572
573const DebugDiffFileHeader = memo(function DebugDiffFileHeader(props: {
574 readonly header: DebugDiffFileHeaderRow;
575 readonly width: number;
576}) {
577 return (
578 <View
579 className="flex-row items-center border-b border-border bg-card px-3"
580 style={{ height: DEBUG_DIFF_ROW_HEIGHT, width: props.width }}
581 >
582 <Text className="min-w-0 flex-1 text-[13px] font-t3-bold text-foreground" numberOfLines={1}>
583 {props.header.filePath}
584 </Text>
585 <Text className="ml-2 text-[12px] font-t3-bold text-rose-500">-{props.header.deletions}</Text>
586 <Text className="ml-2 text-[12px] font-t3-bold text-emerald-500">
587 +{props.header.additions}
588 </Text>
589 </View>
590 );
591});
592
593const DebugDiffStickyCell = memo(function DebugDiffStickyCell(props: {
594 readonly item: DebugDiffHunkRow | DebugDiffCodeRow;
595}) {
596 if (props.item.kind === "hunk") {
597 return (
598 <View
599 className="border-b border-sky-500/10 bg-sky-500/12"
600 style={{ height: DEBUG_DIFF_ROW_HEIGHT, width: DEBUG_STICKY_WIDTH }}
601 />
602 );
603 }
604
605 const displayLineNumber = props.item.newLineNumber ?? props.item.oldLineNumber ?? "";
606
607 return (
608 <View
609 className={cn("flex-row", changeRowClassName(props.item.change))}
610 style={{ height: DEBUG_DIFF_ROW_HEIGHT, width: DEBUG_STICKY_WIDTH }}
611 >
612 <DebugChangeBar change={props.item.change} />
613 <View className="items-end justify-center pr-2" style={{ width: DEBUG_GUTTER_WIDTH }}>
614 <NativeText
615 className="text-[11px] text-foreground-muted"
616 numberOfLines={1}
617 style={DEBUG_CODE_TEXT_STYLE}
618 >
619 {displayLineNumber}
620 </NativeText>
621 </View>
622 </View>
623 );
624});
625
626const DebugDiffCodeCell = memo(function DebugDiffCodeCell(props: {
627 readonly item: DebugDiffHunkRow | DebugDiffCodeRow;
628 readonly tokens: ReadonlyArray<DebugToken> | null;
629}) {
630 const { item } = props;
631
632 if (item.kind === "hunk") {
633 return (
634 <View
635 className="justify-center border-b border-sky-500/10 bg-sky-500/12 px-2"
636 style={{ height: DEBUG_DIFF_ROW_HEIGHT, width: DEBUG_CONTENT_WIDTH }}
637 >
638 <NativeText
639 numberOfLines={1}
640 className="text-[13px] leading-[18px] text-sky-700 dark:text-sky-300"
641 style={DEBUG_CODE_TEXT_STYLE}
642 >
643 {item.text}
644 </NativeText>
645 </View>
646 );
647 }
648
649 return (
650 <View
651 className={cn("justify-center px-2", changeRowClassName(item.change))}
652 style={{ height: DEBUG_DIFF_ROW_HEIGHT, width: DEBUG_CONTENT_WIDTH }}
653 >
654 <TokenText content={item.content} tokens={props.tokens} />
655 </View>
656 );
657});
658
659const DebugHorizontalCodeViewport = memo(function DebugHorizontalCodeViewport(props: {
660 readonly children: ReactElement;
661 readonly fileId: string;
662 readonly horizontalOffset: Animated.Value;
663 readonly onActivateFile: (fileId: string) => void;
664 readonly viewportWidth: number;
665}) {
666 return (
667 <View
668 onTouchStart={() => props.onActivateFile(props.fileId)}
669 style={{ overflow: "hidden", width: props.viewportWidth }}
670 >
671 <Animated.View style={{ transform: [{ translateX: props.horizontalOffset }] }}>
672 {props.children}
673 </Animated.View>
674 </View>
675 );
676});
677
678const DebugDiffLineRowView = memo(function DebugDiffLineRowView(props: {
679 readonly horizontalOffset: Animated.Value;
680 readonly onActivateFile: (fileId: string) => void;
681 readonly row: DebugDiffCodeRow;
682 readonly tokenStore: DebugTokenStore;
683 readonly viewportWidth: number;
684}) {
685 useSyncExternalStore(
686 useCallback(
687 (listener) => props.tokenStore.subscribeFile(props.row.fileId, listener),
688 [props.row.fileId, props.tokenStore],
689 ),
690 useCallback(
691 () => props.tokenStore.getFileVersion(props.row.fileId),
692 [props.row.fileId, props.tokenStore],
693 ),
694 useCallback(
695 () => props.tokenStore.getFileVersion(props.row.fileId),
696 [props.row.fileId, props.tokenStore],
697 ),
698 );
699
700 return (
701 <View className="flex-row" style={{ height: DEBUG_DIFF_ROW_HEIGHT }}>
702 <DebugDiffStickyCell item={props.row} />
703 <DebugHorizontalCodeViewport
704 fileId={props.row.fileId}
705 horizontalOffset={props.horizontalOffset}
706 onActivateFile={props.onActivateFile}
707 viewportWidth={props.viewportWidth}
708 >
709 <DebugDiffCodeCell
710 item={props.row}
711 tokens={
712 props.tokenStore.getTokens(props.row.highlightChunkId)?.[
713 props.row.indexInHighlightChunk
714 ] ?? null
715 }
716 />
717 </DebugHorizontalCodeViewport>
718 </View>
719 );
720});
721
722const DebugDiffFlatRowView = memo(function DebugDiffFlatRowView(props: {
723 readonly horizontalOffsetStore: DebugHorizontalOffsetStore;
724 readonly onActivateFile: (fileId: string) => void;
725 readonly row: DebugDiffRow;
726 readonly tokenStore: DebugTokenStore;
727 readonly width: number;
728}) {
729 if (props.row.kind === "file") {
730 return <DebugDiffFileHeader header={props.row} width={props.width} />;
731 }
732
733 const viewportWidth = Math.max(0, props.width - DEBUG_STICKY_WIDTH);
734
735 if (props.row.kind === "hunk") {
736 const horizontalOffset = props.horizontalOffsetStore.getValue(props.row.fileId);
737 return (
738 <View className="flex-row" style={{ height: DEBUG_DIFF_ROW_HEIGHT, width: props.width }}>
739 <DebugDiffStickyCell item={props.row} />
740 <View
741 onTouchStart={() => props.onActivateFile(props.row.fileId)}
742 style={{ overflow: "hidden", width: viewportWidth }}
743 >
744 <Animated.View style={{ transform: [{ translateX: horizontalOffset }] }}>
745 <DebugDiffCodeCell item={props.row} tokens={null} />
746 </Animated.View>
747 </View>
748 </View>
749 );
750 }
751
752 return (
753 <DebugDiffLineRowView
754 horizontalOffset={props.horizontalOffsetStore.getValue(props.row.fileId)}
755 onActivateFile={props.onActivateFile}
756 row={props.row}
757 tokenStore={props.tokenStore}
758 viewportWidth={viewportWidth}
759 />
760 );
761});
762
763function EngineToggle(props: {
764 readonly engine: DebugHighlightEngine;
765 readonly onChangeEngine: (engine: DebugHighlightEngine) => void;
766}) {
767 return (
768 <View className="flex-row rounded-full bg-subtle p-1">
769 {(["native", "javascript"] as const).map((engine) => {
770 const selected = props.engine === engine;
771 return (
772 <Pressable
773 key={engine}
774 className={cn("rounded-full px-3 py-1.5", selected && "bg-card")}
775 onPress={() => props.onChangeEngine(engine)}
776 >
777 <Text
778 className={cn(
779 "text-[12px] font-t3-bold",
780 selected ? "text-foreground" : "text-foreground-muted",
781 )}
782 >
783 {engine === "javascript" ? "JS" : "Native"}
784 </Text>
785 </Pressable>
786 );
787 })}
788 </View>
789 );
790}
791
792function FixtureToggle(props: {
793 readonly fixtureId: DebugReviewDiffFixtureId;
794 readonly onChangeFixture: (fixtureId: DebugReviewDiffFixtureId) => void;
795}) {
796 return (
797 <ScrollView horizontal showsHorizontalScrollIndicator={false}>
798 <View className="flex-row gap-2">
799 {debugReviewDiffFixtures.map((fixture) => {
800 const selected = props.fixtureId === fixture.id;
801 return (
802 <Pressable
803 key={fixture.id}
804 className={cn(
805 "rounded-full border border-border px-3 py-1.5",
806 selected ? "bg-foreground" : "bg-card",
807 )}
808 onPress={() => props.onChangeFixture(fixture.id)}
809 >
810 <Text
811 className={cn(
812 "text-[12px] font-t3-bold",
813 selected ? "text-sheet" : "text-foreground",
814 )}
815 >
816 {fixture.label}
817 </Text>
818 </Pressable>
819 );
820 })}
821 </View>
822 </ScrollView>
823 );
824}
825
826export default function SyntaxHighlightDebugRoute() {
827 const insets = useSafeAreaInsets();
828 const { width } = useWindowDimensions();
829 const colorScheme = useColorScheme();
830 const headerIcon = String(useThemeColor("--color-icon"));
831 const themeName = DEBUG_THEME_NAME_BY_SCHEME[colorScheme === "dark" ? "dark" : "light"];
832 const [engine, setEngine] = useState<DebugHighlightEngine>("native");
833 const [fixtureId, setFixtureId] = useState<DebugReviewDiffFixtureId>("small");
834 const [status, setStatus] = useState("Idle");
835 const renderStartRef = useRef<number | null>(null);
836 const generationRef = useRef(0);
837 const tokenStore = useMemo(() => new DebugTokenStore(), []);
838 const horizontalOffsetStore = useMemo(() => new DebugHorizontalOffsetStore(), []);
839 const activeHorizontalFileIdRef = useRef<string | null>(null);
840 const horizontalDragStartRef = useRef(0);
841
842 const fixture = useMemo(
843 () =>
844 debugReviewDiffFixtures.find((candidate) => candidate.id === fixtureId) ??
845 debugReviewDiffFixtures[0],
846 [fixtureId],
847 );
848 const parsedDiff = useMemo(() => parseDebugDiffFixture(fixture), [fixture]);
849 useEffect(() => {
850 const generation = generationRef.current + 1;
851 generationRef.current = generation;
852 renderStartRef.current = performance.now();
853 tokenStore.reset();
854 horizontalOffsetStore.reset();
855 setStatus("Initializing highlighter");
856
857 void (async () => {
858 try {
859 const highlighterStartedAt = performance.now();
860 const highlighter = await getDebugHighlighter(engine);
861 if (generation !== generationRef.current) {
862 return;
863 }
864
865 console.log("[debug-diff-scratch] initialize", {
866 durationMs: Math.round(performance.now() - highlighterStartedAt),
867 engine: highlighter.engine,
868 });
869
870 let firstChunkMs: number | null = null;
871 const totalStartedAt = performance.now();
872 setStatus(`Streaming ${parsedDiff.highlightChunks.length.toLocaleString()} chunks`);
873
874 for (let chunkIndex = 0; chunkIndex < parsedDiff.highlightChunks.length; chunkIndex += 1) {
875 if (generation !== generationRef.current) {
876 return;
877 }
878
879 const chunk = parsedDiff.highlightChunks[chunkIndex];
880 if (!chunk) {
881 continue;
882 }
883
884 const chunkCode = chunk.rows.map((line) => line.content).join("\n");
885 const chunkStartedAt = performance.now();
886 const chunkTokens = highlighter.tokenize(chunkCode, {
887 lang: chunk.language,
888 theme: themeName,
889 });
890 const chunkMs = performance.now() - chunkStartedAt;
891
892 if (firstChunkMs === null) {
893 firstChunkMs = performance.now() - totalStartedAt;
894 console.log("[debug-diff-scratch] first chunk", {
895 durationMs: Math.round(firstChunkMs),
896 engine,
897 fixture: fixture.id,
898 language: chunk.language,
899 lineCount: chunkTokens.length,
900 });
901 }
902
903 tokenStore.setChunk(chunk, chunkTokens);
904
905 console.log("[debug-diff-scratch] chunk", {
906 chunkIndex,
907 chunkMs: Math.round(chunkMs),
908 engine,
909 fixture: fixture.id,
910 language: chunk.language,
911 lineCount: chunkTokens.length,
912 });
913
914 await waitForNextFrame();
915 }
916
917 console.log("[debug-diff-scratch] complete", {
918 durationMs: Math.round(performance.now() - totalStartedAt),
919 engine,
920 fixture: fixture.id,
921 rows: parsedDiff.rows.length,
922 });
923 setStatus(`Complete with ${engine}`);
924 } catch (error) {
925 console.error("[debug-diff-scratch] failed", {
926 engine,
927 message: error instanceof Error ? error.message : String(error),
928 });
929 setStatus(error instanceof Error ? error.message : "Highlight failed");
930 }
931 })();
932 }, [
933 engine,
934 fixture.id,
935 parsedDiff.highlightChunks,
936 parsedDiff.rows.length,
937 themeName,
938 horizontalOffsetStore,
939 tokenStore,
940 ]);
941
942 useEffect(() => {
943 if (renderStartRef.current === null) {
944 return;
945 }
946
947 const startedAt = renderStartRef.current;
948 renderStartRef.current = null;
949 const commitMs = performance.now() - startedAt;
950 requestAnimationFrame(() => {
951 console.log("[debug-diff-scratch] render", {
952 commitMs: Math.round(commitMs),
953 paintMs: Math.round(performance.now() - startedAt),
954 });
955 });
956 });
957
958 const onActivateHorizontalFile = useCallback((fileId: string) => {
959 activeHorizontalFileIdRef.current = fileId;
960 }, []);
961
962 const maxHorizontalOffset = Math.max(
963 0,
964 DEBUG_CONTENT_WIDTH - Math.max(0, width - DEBUG_STICKY_WIDTH),
965 );
966 const horizontalPanResponder = useMemo(
967 () =>
968 PanResponder.create({
969 onMoveShouldSetPanResponder: (_event, gestureState) => {
970 const horizontalDistance = Math.abs(gestureState.dx);
971 const verticalDistance = Math.abs(gestureState.dy);
972 return horizontalDistance > 8 && horizontalDistance > verticalDistance * 1.25;
973 },
974 onPanResponderGrant: () => {
975 const fileId = activeHorizontalFileIdRef.current;
976 horizontalDragStartRef.current = fileId ? horizontalOffsetStore.getOffset(fileId) : 0;
977 },
978 onPanResponderMove: (_event, gestureState) => {
979 const fileId = activeHorizontalFileIdRef.current;
980 if (!fileId) {
981 return;
982 }
983 const nextOffset = Math.min(
984 Math.max(horizontalDragStartRef.current - gestureState.dx, 0),
985 maxHorizontalOffset,
986 );
987 horizontalOffsetStore.setOffset(fileId, nextOffset);
988 },
989 onPanResponderTerminationRequest: () => true,
990 }),
991 [horizontalOffsetStore, maxHorizontalOffset],
992 );
993
994 const renderItem = useCallback(
995 ({ item }: ListRenderItemInfo<DebugDiffRow>) => (
996 <DebugDiffFlatRowView
997 horizontalOffsetStore={horizontalOffsetStore}
998 onActivateFile={onActivateHorizontalFile}
999 row={item}
1000 tokenStore={tokenStore}
1001 width={width}
1002 />
1003 ),
1004 [horizontalOffsetStore, onActivateHorizontalFile, tokenStore, width],
1005 );
1006
1007 return (
1008 <View className="flex-1 bg-sheet">
1009 <Stack.Screen
1010 options={{
1011 headerShown: true,
1012 headerTitle: "Diff Scratch",
1013 headerTintColor: headerIcon,
1014 headerTransparent: true,
1015 headerShadowVisible: false,
1016 gestureEnabled: false,
1017 }}
1018 />
1019
1020 <View
1021 className="gap-3 border-b border-border bg-sheet px-3 pb-3"
1022 style={{ paddingTop: insets.top + 56 }}
1023 >
1024 <View className="flex-row items-center justify-between gap-3">
1025 <View className="min-w-0 flex-1">
1026 <Text className="text-[13px] font-t3-bold text-foreground">Diff streaming scratch</Text>
1027 <Text className="text-[11px] text-foreground-muted" numberOfLines={1}>
1028 {fixture.label} · {parsedDiff.files.length} files · {parsedDiff.rows.length} rows ·{" "}
1029 {status}
1030 </Text>
1031 </View>
1032 <EngineToggle engine={engine} onChangeEngine={setEngine} />
1033 </View>
1034 <FixtureToggle fixtureId={fixtureId} onChangeFixture={setFixtureId} />
1035 </View>
1036
1037 <View className="flex-1" {...horizontalPanResponder.panHandlers}>
1038 <FlatList
1039 style={{ flex: 1, width }}
1040 data={parsedDiff.rows}
1041 renderItem={renderItem}
1042 keyExtractor={(item) => item.id}
1043 getItemLayout={(_, index) => ({
1044 length: DEBUG_DIFF_ROW_HEIGHT,
1045 offset: DEBUG_DIFF_ROW_HEIGHT * index,
1046 index,
1047 })}
1048 initialNumToRender={28}
1049 maxToRenderPerBatch={32}
1050 updateCellsBatchingPeriod={24}
1051 windowSize={7}
1052 removeClippedSubviews
1053 keyboardShouldPersistTaps="handled"
1054 contentContainerStyle={{ paddingBottom: Math.max(insets.bottom, 18) + 18 }}
1055 />
1056 </View>
1057 </View>
1058 );
1059}
apps/mobile/src/app/index.tsx+0−5
@@ -78,11 +78,6 @@ export default function HomeRouteScreen() { · 77 unmodified lines
78 </Stack.Toolbar>78 </Stack.Toolbar>
79 79
80 <Stack.Toolbar placement="right">80 <Stack.Toolbar placement="right">
81 <Stack.Toolbar.Button
82 icon="ladybug"
83 onPress={() => router.push("/debug/native-review-diff")}
84 separateBackground
85 />
86 <Stack.Toolbar.Button81 <Stack.Toolbar.Button
87 icon="network"82 icon="network"
88 onPress={() => router.push("/connections")}83 onPress={() => router.push("/connections")}
apps/mobile/src/features/debug/fixtures/README.md+0−13
@@ -1,13 +0,0 @@
1# Debug Fixtures
2
3These patch fixtures snapshot review-rendering worktree diffs used to develop
4the scratch review renderer. Keep them deterministic so the debug route can test
5parsing, chunked syntax highlighting, and virtualization without depending on
6the current repo state.
7
8- `review-small.diff`: 155 lines, narrow model/rendering changes.
9- `review-medium.diff`: 1,955 lines, review screen and highlighter changes.
10- `review-large.diff`: 3,208 lines, broad current worktree snapshot excluding
11 this fixture directory.
12- `current-working-review.diff`: alias of `review-large.diff` for quick loading
13 while iterating.
apps/mobile/src/features/debug/fixtures/current-working-review.diff+0−3208
@@ -1,3208 +0,0 @@
1diff --git a/apps/mobile/package.json b/apps/mobile/package.json
2index 08329e1d4..36ac93a0f 100644
3--- a/apps/mobile/package.json
4+++ b/apps/mobile/package.json
5@@ -30,6 +30,7 @@
6 "config:dev": "APP_VARIANT=development expo config",
7 "config:preview": "APP_VARIANT=preview expo config",
8 "config:prod": "APP_VARIANT=production expo config",
9+ "profile:android:hermes": "mkdir -p profiles/review && react-native profile-hermes profiles/review",
10 "test": "vitest run",
11 "typecheck": "tsc --noEmit"
12 },
13diff --git a/apps/mobile/src/app/index.tsx b/apps/mobile/src/app/index.tsx
14index f153db701..f6095c051 100644
15--- a/apps/mobile/src/app/index.tsx
16+++ b/apps/mobile/src/app/index.tsx
17@@ -43,28 +43,50 @@ export default function HomeRouteScreen() {
18 headerTintColor: iconColor,
19 headerTitle: "",
20 headerRight: () => (
21- <Pressable
22- onPress={() => router.push("/connections")}
23- hitSlop={8}
24- style={{
25- flexDirection: "row",
26- alignItems: "center",
27- gap: 8,
28- paddingHorizontal: 4,
29- paddingVertical: 4,
30- }}
31- >
32- <ConnectionStatusDot state={connectionState} pulse={hasRemoteActivity} size={7} />
33- <RNText
34+ <View style={{ flexDirection: "row", alignItems: "center", gap: 12 }}>
35+ <Pressable
36+ onPress={() => router.push("/debug/syntax-highlight")}
37+ hitSlop={8}
38 style={{
39- fontFamily: "DMSans_700Bold",
40- fontSize: 12,
41- color: secondaryFg,
42+ borderRadius: 999,
43+ backgroundColor: isDark ? "rgba(255,255,255,0.06)" : "rgba(0,0,0,0.06)",
44+ paddingHorizontal: 10,
45+ paddingVertical: 5,
46 }}
47 >
48- {CONNECTION_LABEL[connectionState]}
49- </RNText>
50- </Pressable>
51+ <RNText
52+ style={{
53+ fontFamily: "DMSans_700Bold",
54+ fontSize: 12,
55+ color: secondaryFg,
56+ }}
57+ >
58+ Debug
59+ </RNText>
60+ </Pressable>
61+ <Pressable
62+ onPress={() => router.push("/connections")}
63+ hitSlop={8}
64+ style={{
65+ flexDirection: "row",
66+ alignItems: "center",
67+ gap: 8,
68+ paddingHorizontal: 4,
69+ paddingVertical: 4,
70+ }}
71+ >
72+ <ConnectionStatusDot state={connectionState} pulse={hasRemoteActivity} size={7} />
73+ <RNText
74+ style={{
75+ fontFamily: "DMSans_700Bold",
76+ fontSize: 12,
77+ color: secondaryFg,
78+ }}
79+ >
80+ {CONNECTION_LABEL[connectionState]}
81+ </RNText>
82+ </Pressable>
83+ </View>
84 ),
85 headerSearchBarOptions: {
86 placeholder: "Search threads",
87diff --git a/apps/mobile/src/app/threads/[environmentId]/[threadId]/review.tsx b/apps/mobile/src/app/threads/[environmentId]/[threadId]/review.tsx
88index 84c48c6ed..ee993ee7c 100644
89--- a/apps/mobile/src/app/threads/[environmentId]/[threadId]/review.tsx
90+++ b/apps/mobile/src/app/threads/[environmentId]/[threadId]/review.tsx
91@@ -1,5 +1,10 @@
92+import { ReviewHighlighterProvider } from "../../../../features/review/ReviewHighlighterProvider";
93 import { ReviewSheet } from "../../../../features/review/ReviewSheet";
94
95 export default function ReviewRoute() {
96- return <ReviewSheet />;
97+ return (
98+ <ReviewHighlighterProvider>
99+ <ReviewSheet />
100+ </ReviewHighlighterProvider>
101+ );
102 }
103diff --git a/apps/mobile/src/features/review/ReviewCommentComposerSheet.tsx b/apps/mobile/src/features/review/ReviewCommentComposerSheet.tsx
104index 076a2286d..9a173224a 100644
105--- a/apps/mobile/src/features/review/ReviewCommentComposerSheet.tsx
106+++ b/apps/mobile/src/features/review/ReviewCommentComposerSheet.tsx
107@@ -2,15 +2,8 @@ import { useLocalSearchParams, useRouter } from "expo-router";
108 import { SymbolView } from "expo-symbols";
109 import { TextInputWrapper } from "expo-paste-input";
110 import { useEffect, useMemo, useState } from "react";
111-import {
112- KeyboardAvoidingView,
113- Platform,
114- Pressable,
115- ScrollView,
116- View,
117- useColorScheme,
118- useWindowDimensions,
119-} from "react-native";
120+import { Pressable, ScrollView, View, useColorScheme, useWindowDimensions } from "react-native";
121+import { KeyboardStickyView } from "react-native-keyboard-controller";
122 import { useSafeAreaInsets } from "react-native-safe-area-context";
123 import ImageViewing from "react-native-image-viewing";
124
125@@ -34,6 +27,7 @@ import {
126 import {
127 changeTone,
128 DiffTokenText,
129+ REVIEW_DIFF_LINE_HEIGHT,
130 REVIEW_MONO_FONT_FAMILY,
131 ReviewChangeBar,
132 } from "./reviewDiffRendering";
133@@ -44,7 +38,6 @@ import {
134 } from "./shikiReviewHighlighter";
135
136 const REVIEW_COMMENT_PREVIEW_MAX_LINES = 5;
137-const REVIEW_COMMENT_LINE_HEIGHT = 26;
138
139 export function ReviewCommentComposerSheet() {
140 const router = useRouter();
141@@ -84,8 +77,8 @@ export function ReviewCommentComposerSheet() {
142 ? `Lines ${firstNumber}-${lastNumber}`
143 : `${selectedLines.length} lines selected`;
144 const previewHeight = Math.max(
145- Math.min(selectedLines.length, REVIEW_COMMENT_PREVIEW_MAX_LINES) * REVIEW_COMMENT_LINE_HEIGHT,
146- REVIEW_COMMENT_LINE_HEIGHT,
147+ Math.min(selectedLines.length, REVIEW_COMMENT_PREVIEW_MAX_LINES) * REVIEW_DIFF_LINE_HEIGHT,
148+ REVIEW_DIFF_LINE_HEIGHT,
149 );
150 const previewViewportWidth = Math.max(width - 40, 280);
151 const handleNativePaste = useNativePaste((uris) => {
152@@ -143,17 +136,13 @@ export function ReviewCommentComposerSheet() {
153 }
154
155 return (
156- <KeyboardAvoidingView
157- behavior={Platform.OS === "ios" ? "padding" : "height"}
158- keyboardVerticalOffset={Platform.OS === "ios" ? 12 : 0}
159- style={{ flex: 1 }}
160- >
161+ <View style={{ flex: 1 }}>
162 <View
163 style={{
164 flex: 1,
165 paddingHorizontal: 20,
166 paddingTop: 8,
167- paddingBottom: Math.max(insets.bottom, 18) + 18,
168+ paddingBottom: Math.max(insets.bottom, 18) + 82,
169 }}
170 >
171 <View className="flex-row items-center justify-between py-2">
172@@ -219,7 +208,7 @@ export function ReviewCommentComposerSheet() {
173 <View
174 key={line.id}
175 className={cn("flex-row items-start", changeTone(line.change))}
176- style={{ height: REVIEW_COMMENT_LINE_HEIGHT }}
177+ style={{ height: REVIEW_DIFF_LINE_HEIGHT }}
178 >
179 <ReviewChangeBar change={line.change} />
180 <Text
181@@ -280,35 +269,41 @@ export function ReviewCommentComposerSheet() {
182 ) : null}
183 </View>
184 </View>
185-
186- <View className="flex-row items-center gap-3 pt-1">
187- <ControlPill icon="plus" onPress={() => void handlePickImages()} />
188- <View className="flex-1" />
189- <ControlPill
190- icon="arrow.up"
191- label="Comment"
192- variant="primary"
193- disabled={!canSubmit}
194- onPress={() => {
195- if (!target || !environmentId || !threadId || commentText.trim().length === 0) {
196- return;
197- }
198-
199- appendReviewCommentToDraft({
200- environmentId,
201- threadId,
202- text: formatReviewCommentContext(target, commentText),
203- attachments,
204- });
205- setAttachments([]);
206- clearReviewCommentTarget();
207- router.dismiss();
208- }}
209- />
210- </View>
211 </View>
212 )}
213 </View>
214+ {target ? (
215+ <KeyboardStickyView style={{ position: "absolute", bottom: 0, left: 0, right: 0 }}>
216+ <View
217+ className="flex-row items-center gap-3 bg-sheet px-5 pt-3"
218+ style={{ paddingBottom: Math.max(insets.bottom, 18) }}
219+ >
220+ <ControlPill icon="plus" onPress={() => void handlePickImages()} />
221+ <View className="flex-1" />
222+ <ControlPill
223+ icon="arrow.up"
224+ label="Comment"
225+ variant="primary"
226+ disabled={!canSubmit}
227+ onPress={() => {
228+ if (!target || !environmentId || !threadId || commentText.trim().length === 0) {
229+ return;
230+ }
231+
232+ appendReviewCommentToDraft({
233+ environmentId,
234+ threadId,
235+ text: formatReviewCommentContext(target, commentText),
236+ attachments,
237+ });
238+ setAttachments([]);
239+ clearReviewCommentTarget();
240+ router.dismiss();
241+ }}
242+ />
243+ </View>
244+ </KeyboardStickyView>
245+ ) : null}
246 <ImageViewing
247 images={previewImageUri ? [{ uri: previewImageUri }] : []}
248 imageIndex={0}
249@@ -317,6 +312,6 @@ export function ReviewCommentComposerSheet() {
250 swipeToCloseEnabled
251 doubleTapToZoomEnabled
252 />
253- </KeyboardAvoidingView>
254+ </View>
255 );
256 }
257diff --git a/apps/mobile/src/features/review/ReviewSheet.tsx b/apps/mobile/src/features/review/ReviewSheet.tsx
258index 82c28e81e..e148a8da2 100644
259--- a/apps/mobile/src/features/review/ReviewSheet.tsx
260+++ b/apps/mobile/src/features/review/ReviewSheet.tsx
261@@ -1,17 +1,31 @@
262 import { EnvironmentId, ThreadId, type OrchestrationCheckpointSummary } from "@t3tools/contracts";
263+import { Gesture, GestureDetector } from "react-native-gesture-handler";
264+import Animated, {
265+ makeMutable,
266+ type SharedValue,
267+ useAnimatedStyle,
268+ useSharedValue,
269+} from "react-native-reanimated";
270 import { useLocalSearchParams, useRouter } from "expo-router";
271 import Stack from "expo-router/stack";
272 import { SymbolView } from "expo-symbols";
273-import { memo, type ReactElement, useCallback, useEffect, useMemo, useRef, useState } from "react";
274+import {
275+ memo,
276+ type ReactElement,
277+ useCallback,
278+ useDeferredValue,
279+ useEffect,
280+ useMemo,
281+ useRef,
282+ useState,
283+} from "react";
284 import {
285 ActivityIndicator,
286 FlatList,
287- InteractionManager,
288 type ListRenderItemInfo,
289 Pressable,
290 ScrollView,
291 Text as NativeText,
292- type ViewToken,
293 useColorScheme,
294 useWindowDimensions,
295 View,
296@@ -32,6 +46,7 @@ import {
297 setReviewTurnDiff,
298 updateReviewExpandedFileIds,
299 updateReviewRevealedLargeFileIds,
300+ updateReviewViewedFileIds,
301 useReviewCacheForThread,
302 } from "./reviewState";
303 import {
304@@ -45,11 +60,12 @@ import {
305 type ReviewParsedDiff,
306 type ReviewRenderableFile,
307 type ReviewRenderableLineRow,
308+ type ReviewRenderableRow,
309 } from "./reviewModel";
310 import {
311 clearReviewHighlightFileCache,
312 getCachedHighlightedReviewFile,
313- highlightReviewFile,
314+ streamHighlightReviewFile,
315 type ReviewDiffTheme,
316 type ReviewHighlightedFile,
317 type ReviewHighlightedToken,
318@@ -67,9 +83,12 @@ import {
319 import {
320 changeTone,
321 DiffTokenText,
322+ REVIEW_DIFF_LINE_HEIGHT,
323 REVIEW_MONO_FONT_FAMILY,
324 ReviewChangeBar,
325 } from "./reviewDiffRendering";
326+import { markReviewEvent, measureReviewWork } from "./reviewPerf";
327+import { useReviewHighlighterStatus } from "./ReviewHighlighterProvider";
328
329 interface PendingCommentSelection {
330 readonly sectionTitle: string;
331@@ -87,14 +106,21 @@ interface ReviewLineActionInput {
332
333 const IOS_NAV_BAR_HEIGHT = 44;
334 const REVIEW_HEADER_SPACING = 0;
335-const REVIEW_LINE_GUTTER_WIDTH = 62;
336+const REVIEW_CHANGE_BAR_WIDTH = 5;
337+const REVIEW_MIN_LINE_NUMBER_WIDTH = 27;
338+const REVIEW_LINE_NUMBER_DIGIT_WIDTH_ESTIMATE = 8;
339+const REVIEW_LINE_NUMBER_HORIZONTAL_PADDING = 6;
340 const REVIEW_CHARACTER_WIDTH_ESTIMATE = 8.4;
341 const REVIEW_MAX_CONTENT_WIDTH = 4_800;
342-const REVIEW_INITIAL_HIGHLIGHT_FILE_COUNT = 2;
343-const REVIEW_HIGHLIGHT_BACKTRACK_COUNT = 0;
344-const REVIEW_HIGHLIGHT_LOOKAHEAD_COUNT = 1;
345+const REVIEW_HUNK_ROW_HEIGHT = 35;
346+const REVIEW_FILE_HEADER_HEIGHT = 43;
347+const REVIEW_SUPPRESSED_ROW_HEIGHT = 92;
348 const loggedMissingReviewTokenKeys = new Set<string>();
349
350+function waitForReviewDelay(durationMs: number): Promise<void> {
351+ return new Promise((resolve) => setTimeout(resolve, durationMs));
352+}
353+
354 function isReviewDiffDebugLoggingEnabled(): boolean {
355 return typeof __DEV__ !== "undefined" ? __DEV__ : false;
356 }
357@@ -113,33 +139,27 @@ function logReviewDiffDiagnostic(message: string, details?: Record<string, unkno
358 }
359
360 function getFileHeaderChrome(changeType: ReviewRenderableFile["changeType"]): {
361- readonly rail: string;
362 readonly dot: string;
363 } {
364 switch (changeType) {
365 case "new":
366 return {
367- rail: "bg-emerald-400",
368 dot: "bg-emerald-400",
369 };
370 case "deleted":
371 return {
372- rail: "bg-rose-400",
373 dot: "bg-rose-400",
374 };
375 case "rename-pure":
376 return {
377- rail: "bg-amber-400",
378 dot: "bg-amber-400",
379 };
380 case "rename-changed":
381 return {
382- rail: "bg-sky-400",
383 dot: "bg-sky-400",
384 };
385 default:
386 return {
387- rail: "bg-sky-400",
388 dot: "bg-sky-400",
389 };
390 }
391@@ -159,51 +179,72 @@ function formatHeaderDiffSummary(parsedDiff: ReviewParsedDiff): {
392 };
393 }
394
395-function computeReviewListContentWidth(
396- items: ReadonlyArray<ReviewListItem>,
397+function computeReviewFileContentWidth(
398+ rows: ReadonlyArray<ReviewRenderableRow>,
399 viewportWidth: number,
400+ gutterWidth: number,
401 ): number {
402 let maxTextLength = 0;
403
404- items.forEach((item) => {
405- switch (item.kind) {
406- case "file-header":
407- maxTextLength = Math.max(
408- maxTextLength,
409- item.file.path.length,
410- item.file.previousPath?.length ?? 0,
411- );
412- break;
413- case "file-suppressed":
414- maxTextLength = Math.max(maxTextLength, item.message.length, item.actionLabel?.length ?? 0);
415- break;
416- case "hunk":
417- maxTextLength = Math.max(
418- maxTextLength,
419- item.row.header.length + (item.row.context ? item.row.context.length + 1 : 0),
420- );
421- break;
422- case "line":
423- maxTextLength = Math.max(maxTextLength, item.row.content.length);
424- break;
425+ rows.forEach((row) => {
426+ if (row.kind === "hunk") {
427+ maxTextLength = Math.max(
428+ maxTextLength,
429+ row.header.length + (row.context ? row.context.length + 1 : 0),
430+ );
431+ return;
432 }
433+
434+ maxTextLength = Math.max(maxTextLength, row.content.length);
435 });
436
437 return Math.max(
438- viewportWidth,
439+ Math.max(0, viewportWidth - gutterWidth),
440 Math.min(
441 REVIEW_MAX_CONTENT_WIDTH,
442- Math.ceil(REVIEW_LINE_GUTTER_WIDTH + 48 + maxTextLength * REVIEW_CHARACTER_WIDTH_ESTIMATE),
443+ Math.ceil(48 + maxTextLength * REVIEW_CHARACTER_WIDTH_ESTIMATE),
444 ),
445 );
446 }
447
448+function computeReviewFileGutterWidth(rows: ReadonlyArray<ReviewRenderableRow>): number {
449+ let maxLineNumber = 0;
450+
451+ rows.forEach((row) => {
452+ if (row.kind !== "line") {
453+ return;
454+ }
455+
456+ maxLineNumber = Math.max(maxLineNumber, row.oldLineNumber ?? 0, row.newLineNumber ?? 0);
457+ });
458+
459+ const digitCount = Math.max(1, String(maxLineNumber).length);
460+ const lineNumberWidth = Math.max(
461+ REVIEW_MIN_LINE_NUMBER_WIDTH,
462+ digitCount * REVIEW_LINE_NUMBER_DIGIT_WIDTH_ESTIMATE + REVIEW_LINE_NUMBER_HORIZONTAL_PADDING,
463+ );
464+
465+ return REVIEW_CHANGE_BAR_WIDTH + lineNumberWidth;
466+}
467+
468 function getDefaultExpandedFileIds(
469 files: ReadonlyArray<ReviewRenderableFile>,
470 ): ReadonlyArray<string> {
471 return files.map((file) => file.id);
472 }
473
474+function getValidReviewExpandedFileIds(
475+ files: ReadonlyArray<ReviewRenderableFile>,
476+ cachedExpandedFileIds: ReadonlyArray<string> | undefined,
477+): ReadonlyArray<string> {
478+ if (cachedExpandedFileIds === undefined) {
479+ return getDefaultExpandedFileIds(files);
480+ }
481+
482+ const fileIdSet = new Set(files.map((file) => file.id));
483+ return cachedExpandedFileIds.filter((id) => fileIdSet.has(id));
484+}
485+
486 function getHighlightedTokensForLine(
487 line: ReviewRenderableLineRow,
488 highlightedFile: ReviewHighlightedFile | null,
489@@ -252,16 +293,13 @@ const ReviewLineRow = memo(function ReviewLineRow(props: {
490 delayLongPress={220}
491 onLongPress={props.onStartRangeSelection}
492 onPress={props.onComment}
493- style={{ minWidth: props.viewportWidth }}
494+ style={{
495+ height: REVIEW_DIFF_LINE_HEIGHT,
496+ width: props.viewportWidth,
497+ overflow: "hidden",
498+ }}
499 >
500- <ReviewChangeBar change={props.line.change} />
501- <Text
502- className="w-9 py-1 pr-1 text-right text-[11px] font-t3-medium text-foreground-muted"
503- style={{ fontFamily: REVIEW_MONO_FONT_FAMILY }}
504- >
505- {lineNumber ?? ""}
506- </Text>
507- <View className="min-w-0 flex-1 shrink-0 px-1 py-1">
508+ <View className="min-w-0 flex-1 shrink-0 px-1 py-1" style={{ width: props.viewportWidth }}>
509 <DiffTokenText
510 tokens={props.tokens}
511 fallback={props.line.content}
512@@ -272,62 +310,135 @@ const ReviewLineRow = memo(function ReviewLineRow(props: {
513 );
514 });
515
516+const ReviewLineGutter = memo(function ReviewLineGutter(props: {
517+ readonly change: ReviewRenderableLineRow["change"];
518+ readonly gutterWidth: number;
519+ readonly lineNumber: number | null;
520+}) {
521+ const lineNumberWidth = Math.max(0, props.gutterWidth - REVIEW_CHANGE_BAR_WIDTH);
522+
523+ return (
524+ <View className={cn("flex-row", changeTone(props.change))} style={{ width: props.gutterWidth }}>
525+ <ReviewChangeBar change={props.change} />
526+ <Text
527+ className="py-1 pr-1 text-right text-[11px] font-t3-medium text-foreground-muted"
528+ style={[{ fontFamily: REVIEW_MONO_FONT_FAMILY }, { width: lineNumberWidth }]}
529+ >
530+ {props.lineNumber ?? ""}
531+ </Text>
532+ </View>
533+ );
534+});
535+
536+const ReviewHunkGutter = memo(function ReviewHunkGutter(props: { readonly gutterWidth: number }) {
537+ return (
538+ <View
539+ className="border-b border-border/60 bg-sky-500/10"
540+ style={{ width: props.gutterWidth }}
541+ />
542+ );
543+});
544+
545 const ReviewFileCard = memo(function ReviewFileCard(props: {
546 readonly file: ReviewRenderableFile;
547 readonly fileId: string;
548 readonly expanded: boolean;
549+ readonly viewed: boolean;
550 readonly viewportWidth: number;
551 readonly onToggleFile: (fileId: string) => void;
552+ readonly onToggleViewed: (fileId: string) => void;
553 }) {
554- const chrome = getFileHeaderChrome(props.file.changeType);
555+ const { expanded, file, fileId, onToggleFile, onToggleViewed, viewed, viewportWidth } = props;
556+ const chrome = getFileHeaderChrome(file.changeType);
557+ const iconColor = String(useThemeColor("--color-icon-muted"));
558+ const handleToggleFile = useCallback(() => {
559+ onToggleFile(fileId);
560+ }, [fileId, onToggleFile]);
561+ const handleToggleViewed = useCallback(() => {
562+ onToggleViewed(fileId);
563+ }, [fileId, onToggleViewed]);
564
565 return (
566 <View
567- className="border-b border-border/70 bg-card"
568- style={{
569- zIndex: 1,
570- width: props.viewportWidth,
571- shadowColor: "#000000",
572- shadowOpacity: 0.08,
573- shadowRadius: 10,
574- shadowOffset: { width: 0, height: 6 },
575- elevation: 4,
576- }}
577+ className="border-b border-border bg-card"
578+ style={{ height: REVIEW_FILE_HEADER_HEIGHT, overflow: "hidden", width: viewportWidth }}
579 >
580- <Pressable className="flex-row items-center" onPress={() => props.onToggleFile(props.fileId)}>
581- <View className={cn("w-1 self-stretch", chrome.rail)} />
582- <View className="flex-1 flex-row items-center px-3 py-1.5">
583- <View className="size-7 items-center justify-center rounded-full bg-subtle">
584- <SymbolView
585- name={props.expanded ? "chevron.down" : "chevron.right"}
586- size={12}
587- tintColor="#8a8a8a"
588- type="monochrome"
589- />
590- </View>
591- <View className="ml-2 min-w-0 flex-1 flex-row items-center gap-2">
592- <View className={cn("size-2 rounded-full", chrome.dot)} />
593- <View className="min-w-0 flex-1">
594- <Text className="font-mono text-[13px] leading-[18px] text-foreground">
595- {props.file.path}
596+ <View className="min-h-[42px] flex-row items-center gap-1.5 px-2">
597+ <Pressable
598+ className="size-9 items-center justify-center"
599+ accessibilityRole="button"
600+ accessibilityLabel={expanded ? "Collapse file" : "Expand file"}
601+ hitSlop={{ bottom: 8, left: 8, right: 8, top: 8 }}
602+ onTouchEnd={handleToggleFile}
603+ >
604+ <SymbolView
605+ name={expanded ? "chevron.down" : "chevron.right"}
606+ size={13}
607+ tintColor={iconColor}
608+ type="monochrome"
609+ />
610+ </Pressable>
611+ <Pressable
612+ className="min-w-0 flex-1 flex-row items-center gap-2 py-2"
613+ accessibilityRole="button"
614+ accessibilityLabel={expanded ? "Collapse file" : "Expand file"}
615+ onTouchEnd={handleToggleFile}
616+ >
617+ <View className={cn("size-2.5 rounded-full", chrome.dot)} />
618+ <View className="min-w-0 flex-1">
619+ <Text
620+ className="font-mono text-[13px] leading-[18px] text-foreground"
621+ numberOfLines={1}
622+ >
623+ {file.path}
624+ </Text>
625+ {file.previousPath && file.previousPath !== file.path ? (
626+ <Text
627+ className="font-mono text-[10px] leading-[14px] text-foreground-muted"
628+ numberOfLines={1}
629+ >
630+ {file.previousPath}
631 </Text>
632- {props.file.previousPath && props.file.previousPath !== props.file.path ? (
633- <Text className="font-mono text-[10px] leading-[14px] text-foreground-muted">
634- {props.file.previousPath}
635- </Text>
636+ ) : null}
637+ </View>
638+ </Pressable>
639+ <View className="flex-row items-center justify-end gap-1.5">
640+ <Text className="font-mono text-[12px] font-t3-bold text-rose-400">
641+ -{file.deletions}
642+ </Text>
643+ <Text className="font-mono text-[12px] font-t3-bold text-emerald-400">
644+ +{file.additions}
645+ </Text>
646+ <Pressable
647+ className="ml-0.5 min-h-[40px] min-w-[82px] flex-row items-center justify-center gap-1.5 px-1.5"
648+ accessibilityRole="checkbox"
649+ accessibilityState={{ checked: viewed }}
650+ accessibilityLabel={viewed ? "Mark file as unviewed" : "Mark file as viewed"}
651+ hitSlop={{ bottom: 8, left: 4, right: 8, top: 8 }}
652+ onTouchEnd={handleToggleViewed}
653+ >
654+ <View
655+ className={cn(
656+ "size-[18px] items-center justify-center rounded border",
657+ viewed ? "border-sky-500 bg-sky-500" : "border-icon-muted",
658+ )}
659+ >
660+ {viewed ? (
661+ <SymbolView name="checkmark" size={11} tintColor="#ffffff" type="monochrome" />
662 ) : null}
663 </View>
664- </View>
665- <View className="ml-3 flex-row items-center justify-end gap-2">
666- <Text className="font-mono text-[12px] font-t3-bold text-emerald-600 dark:text-emerald-300">
667- +{props.file.additions}
668- </Text>
669- <Text className="font-mono text-[12px] font-t3-bold text-rose-600 dark:text-rose-300">
670- -{props.file.deletions}
671+ <Text
672+ className={cn(
673+ "text-[12px] font-t3-medium",
674+ viewed ? "text-foreground" : "text-foreground-muted",
675+ )}
676+ numberOfLines={1}
677+ >
678+ Viewed
679 </Text>
680- </View>
681+ </Pressable>
682 </View>
683- </Pressable>
684+ </View>
685 </View>
686 );
687 });
688@@ -342,7 +453,11 @@ const ReviewFileSuppressedBody = memo(function ReviewFileSuppressedBody(props: {
689 return (
690 <View
691 className="gap-2 border-b border-border bg-card px-4 py-3"
692- style={{ minWidth: props.viewportWidth }}
693+ style={{
694+ height: REVIEW_SUPPRESSED_ROW_HEIGHT,
695+ overflow: "hidden",
696+ width: props.viewportWidth,
697+ }}
698 >
699 <Text className="text-[12px] leading-[18px] text-foreground-muted">{props.message}</Text>
700 {props.actionLabel && props.onLoadDiffFile ? (
701@@ -364,10 +479,13 @@ const ReviewHunkRow = memo(function ReviewHunkRow(props: {
702 }) {
703 return (
704 <View
705- className="border-b border-border/60 bg-sky-500/10 px-2 py-2"
706- style={{ minWidth: props.viewportWidth }}
707+ className="border-b border-border/60 bg-sky-500/10 py-2"
708+ style={{ height: REVIEW_HUNK_ROW_HEIGHT, width: props.viewportWidth, overflow: "hidden" }}
709 >
710- <Text className="font-mono text-[12px] leading-[18px] text-sky-700 dark:text-sky-300">
711+ <Text
712+ className="px-2 font-mono text-[12px] leading-[18px] text-sky-700 dark:text-sky-300"
713+ numberOfLines={1}
714+ >
715 {props.header}
716 {props.context ? ` ${props.context}` : ""}
717 </Text>
718@@ -375,6 +493,61 @@ const ReviewHunkRow = memo(function ReviewHunkRow(props: {
719 );
720 });
721
722+const ReviewCodePanRow = memo(function ReviewCodePanRow(props: {
723+ readonly contentWidth: number;
724+ readonly horizontalOffset: SharedValue<number>;
725+ readonly gutterWidth?: number;
726+ readonly viewportWidth: number;
727+ readonly leftGutter?: ReactElement;
728+ readonly children: ReactElement;
729+}) {
730+ const {
731+ children,
732+ contentWidth,
733+ gutterWidth = 0,
734+ horizontalOffset,
735+ leftGutter,
736+ viewportWidth,
737+ } = props;
738+ const dragStartOffset = useSharedValue(0);
739+ const visibleContentWidth = leftGutter ? viewportWidth - gutterWidth : viewportWidth;
740+ const maxOffset = Math.max(0, contentWidth - visibleContentWidth);
741+
742+ const panGesture = useMemo(
743+ () =>
744+ Gesture.Pan()
745+ .activeOffsetX([-8, 8])
746+ .failOffsetY([-10, 10])
747+ .onBegin(() => {
748+ dragStartOffset.value = horizontalOffset.value;
749+ })
750+ .onUpdate((event) => {
751+ "worklet";
752+ const nextOffset = dragStartOffset.value - event.translationX;
753+ horizontalOffset.value = Math.min(maxOffset, Math.max(0, nextOffset));
754+ }),
755+ [dragStartOffset, horizontalOffset, maxOffset],
756+ );
757+
758+ const contentStyle = useAnimatedStyle(
759+ () => ({
760+ transform: [{ translateX: -horizontalOffset.value }],
761+ }),
762+ [horizontalOffset],
763+ );
764+
765+ return (
766+ <GestureDetector gesture={panGesture}>
767+ <View style={{ flexDirection: "row", overflow: "hidden", width: viewportWidth }}>
768+ {leftGutter ?? null}
769+ <View style={{ flex: 1, overflow: "hidden" }}>
770+ <Animated.View style={[{ width: contentWidth }, contentStyle]}>{children}</Animated.View>
771+ </View>
772+ </View>
773+ </GestureDetector>
774+ );
775+});
776+
777 const ReviewNotice = memo(function ReviewNotice(props: { readonly notice: string }) {
778 return (
779 <View className="border-b border-amber-200 bg-amber-50 px-4 py-3 dark:border-amber-900/60 dark:bg-amber-950/40">
780@@ -454,15 +627,19 @@ export function ReviewSheet() {
781 const [highlightedFilesById, setHighlightedFilesById] = useState<
782 Record<string, ReviewHighlightedFile | null>
783 >({});
784- const [visibleFileIds, setVisibleFileIds] = useState<ReadonlyArray<string>>([]);
785+ const deferredHighlightedFilesById = useDeferredValue(highlightedFilesById);
786+ const [localExpandedFileIdsBySection, setLocalExpandedFileIdsBySection] = useState<
787+ Record<string, ReadonlyArray<string>>
788+ >({});
789+ const [localViewedFileIdsBySection, setLocalViewedFileIdsBySection] = useState<
790+ Record<string, ReadonlyArray<string>>
791+ >({});
792 const activeCommentTarget = useReviewCommentTarget();
793 const selectedTheme = (colorScheme === "dark" ? "dark" : "light") satisfies ReviewDiffTheme;
794- const highlightQueueRef = useRef<string[]>([]);
795- const highlightRequestedFileIdsRef = useRef<Set<string>>(new Set());
796- const highlightQueueGenerationRef = useRef(0);
797- const highlightQueueActiveRef = useRef(false);
798- const highlightableFilesByIdRef = useRef<ReadonlyMap<string, ReviewRenderableFile>>(new Map());
799- const selectedThemeRef = useRef<ReviewDiffTheme>(selectedTheme);
800+ const reviewHighlighter = useReviewHighlighterStatus();
801+ const highlightRunIdRef = useRef(0);
802+ const highlightableFilesRef = useRef<ReadonlyArray<ReviewRenderableFile>>([]);
803+ const horizontalOffsetByFileIdRef = useRef<Map<string, SharedValue<number>>>(new Map());
804 const { selectedThreadCwd } = useSelectedThreadWorktree();
805
806 const cwd = selectedThreadCwd;
807@@ -498,11 +675,13 @@ export function ReviewSheet() {
808 const topContentInset = insets.top + IOS_NAV_BAR_HEIGHT;
809 const parsedDiff = useMemo(
810 () =>
811- getCachedReviewParsedDiff({
812- threadKey: reviewCache.threadKey,
813- sectionId: selectedSection?.id ?? null,
814- diff: selectedSection?.diff,
815- }),
816+ measureReviewWork("parse-diff", () =>
817+ getCachedReviewParsedDiff({
818+ threadKey: reviewCache.threadKey,
819+ sectionId: selectedSection?.id ?? null,
820+ diff: selectedSection?.diff,
821+ }),
822+ ),
823 [reviewCache.threadKey, selectedSection?.diff, selectedSection?.id],
824 );
825 const headerDiffSummary = useMemo(() => formatHeaderDiffSummary(parsedDiff), [parsedDiff]);
826@@ -510,14 +689,53 @@ export function ReviewSheet() {
827 () => countReviewCommentContexts(draftMessage),
828 [draftMessage],
829 );
830+ const viewportWidth = Math.max(width, 280);
831+
832+ useEffect(() => {
833+ if (!selectedSection?.id || parsedDiff.kind !== "files") {
834+ return;
835+ }
836+
837+ setLocalExpandedFileIdsBySection((current) => {
838+ if (current[selectedSection.id] !== undefined) {
839+ return current;
840+ }
841+
842+ return {
843+ ...current,
844+ [selectedSection.id]: getValidReviewExpandedFileIds(
845+ parsedDiff.files,
846+ reviewCache.expandedFileIdsBySection[selectedSection.id],
847+ ),
848+ };
849+ });
850+
851+ setLocalViewedFileIdsBySection((current) => {
852+ if (current[selectedSection.id] !== undefined) {
853+ return current;
854+ }
855+
856+ return {
857+ ...current,
858+ [selectedSection.id]: reviewCache.viewedFileIdsBySection[selectedSection.id] ?? [],
859+ };
860+ });
861+ }, [
862+ parsedDiff,
863+ reviewCache.expandedFileIdsBySection,
864+ reviewCache.viewedFileIdsBySection,
865+ selectedSection?.id,
866+ ]);
867
868 const expandedFileIds = useMemo(
869 () =>
870 selectedSection?.id && parsedDiff.kind === "files"
871- ? (reviewCache.expandedFileIdsBySection[selectedSection.id] ??
872- getDefaultExpandedFileIds(parsedDiff.files))
873+ ? getValidReviewExpandedFileIds(
874+ parsedDiff.files,
875+ localExpandedFileIdsBySection[selectedSection.id],
876+ )
877 : [],
878- [parsedDiff, reviewCache.expandedFileIdsBySection, selectedSection?.id],
879+ [localExpandedFileIdsBySection, parsedDiff, selectedSection?.id],
880 );
881 const revealedLargeFileIds = useMemo(
882 () =>
883@@ -526,47 +744,96 @@ export function ReviewSheet() {
884 : [],
885 [reviewCache.revealedLargeFileIdsBySection, selectedSection?.id],
886 );
887+ const viewedFileIds = useMemo(
888+ () => (selectedSection?.id ? (localViewedFileIdsBySection[selectedSection.id] ?? []) : []),
889+ [localViewedFileIdsBySection, selectedSection?.id],
890+ );
891+ const viewedFileIdSet = useMemo(() => new Set(viewedFileIds), [viewedFileIds]);
892 const reviewListItems = useMemo(
893 () =>
894 selectedSection && parsedDiff.kind === "files"
895- ? buildReviewListItems({
896- files: parsedDiff.files,
897- expandedFileIds,
898- revealedLargeFileIds,
899- })
900+ ? measureReviewWork("build-list-items", () =>
901+ buildReviewListItems({
902+ files: parsedDiff.files,
903+ expandedFileIds,
904+ revealedLargeFileIds,
905+ }),
906+ )
907 : [],
908 [expandedFileIds, parsedDiff, revealedLargeFileIds, selectedSection],
909 );
910- const reviewFileById = useMemo(() => {
911+ const reviewLineRowsByFileId = useMemo(() => {
912 if (parsedDiff.kind !== "files") {
913- return new Map<string, ReviewRenderableFile>();
914+ return new Map<string, ReadonlyArray<ReviewRenderableLineRow>>();
915 }
916
917- return new Map(parsedDiff.files.map((file) => [file.id, file] as const));
918+ return measureReviewWork(
919+ "index-line-rows",
920+ () =>
921+ new Map(
922+ parsedDiff.files.map((file) => [
923+ file.id,
924+ file.rows.filter((row): row is ReviewRenderableLineRow => row.kind === "line"),
925+ ]),
926+ ),
927+ );
928 }, [parsedDiff]);
929- const reviewLineRowsByFileId = useMemo(() => {
930+ const reviewContentWidthByFileId = useMemo(() => {
931 if (parsedDiff.kind !== "files") {
932- return new Map<string, ReadonlyArray<ReviewRenderableLineRow>>();
933+ return new Map<string, number>();
934+ }
935+
936+ return measureReviewWork(
937+ "measure-file-widths",
938+ () =>
939+ new Map(
940+ parsedDiff.files.map((file) => [
941+ file.id,
942+ computeReviewFileContentWidth(
943+ file.rows,
944+ viewportWidth,
945+ computeReviewFileGutterWidth(file.rows),
946+ ),
947+ ]),
948+ ),
949+ );
950+ }, [parsedDiff, viewportWidth]);
951+ const reviewGutterWidthByFileId = useMemo(() => {
952+ if (parsedDiff.kind !== "files") {
953+ return new Map<string, number>();
954 }
955
956 return new Map(
957- parsedDiff.files.map((file) => [
958- file.id,
959- file.rows.filter((row): row is ReviewRenderableLineRow => row.kind === "line"),
960- ]),
961+ parsedDiff.files.map((file) => [file.id, computeReviewFileGutterWidth(file.rows)]),
962 );
963 }, [parsedDiff]);
964- const reviewLineIndexByRowId = useMemo(() => {
965- const map = new Map<string, number>();
966+ const getReviewFileHorizontalOffset = useCallback((fileId: string) => {
967+ let offset = horizontalOffsetByFileIdRef.current.get(fileId);
968+ if (!offset) {
969+ offset = makeMutable(0);
970+ horizontalOffsetByFileIdRef.current.set(fileId, offset);
971+ }
972
973- reviewLineRowsByFileId.forEach((rows) => {
974- rows.forEach((row, index) => {
975- map.set(row.id, index);
976- });
977- });
978+ return offset;
979+ }, []);
980+ useEffect(() => {
981+ const knownFileIds =
982+ parsedDiff.kind === "files" ? new Set(parsedDiff.files.map((file) => file.id)) : new Set();
983
984- return map;
985- }, [reviewLineRowsByFileId]);
986+ horizontalOffsetByFileIdRef.current.forEach((offset, fileId) => {
987+ if (!knownFileIds.has(fileId)) {
988+ horizontalOffsetByFileIdRef.current.delete(fileId);
989+ return;
990+ }
991+
992+ const contentWidth = reviewContentWidthByFileId.get(fileId) ?? viewportWidth;
993+ const gutterWidth = reviewGutterWidthByFileId.get(fileId) ?? 0;
994+ offset.value = Math.min(
995+ offset.value,
996+ Math.max(0, contentWidth - (viewportWidth - gutterWidth)),
997+ );
998+ });
999+ }, [parsedDiff, reviewContentWidthByFileId, reviewGutterWidthByFileId, viewportWidth]);
1000 const highlightableFiles = useMemo(() => {
1001 if (parsedDiff.kind !== "files") {
1002 return [] as ReadonlyArray<ReviewRenderableFile>;
1003@@ -587,59 +854,13 @@ export function ReviewSheet() {
1004 );
1005 });
1006 }, [expandedFileIds, parsedDiff, revealedLargeFileIds]);
1007- const highlightableFileIds = useMemo(
1008- () => new Set(highlightableFiles.map((file) => file.id)),
1009+ const highlightableFilesKey = useMemo(
1010+ () => highlightableFiles.map((file) => `${file.id}:${file.cacheKey}`).join("\n"),
1011 [highlightableFiles],
1012 );
1013- const priorityHighlightFileIds = useMemo(() => {
1014- if (parsedDiff.kind !== "files" || highlightableFiles.length === 0) {
1015- return [] as ReadonlyArray<string>;
1016- }
1017-
1018- const fileIdsInPriorityOrder =
1019- visibleFileIds.length > 0
1020- ? visibleFileIds.filter((fileId) => highlightableFileIds.has(fileId))
1021- : parsedDiff.files
1022- .slice(0, REVIEW_INITIAL_HIGHLIGHT_FILE_COUNT)
1023- .map((file) => file.id)
1024- .filter((fileId) => highlightableFileIds.has(fileId));
1025-
1026- if (fileIdsInPriorityOrder.length === 0) {
1027- return [] as ReadonlyArray<string>;
1028- }
1029-
1030- const firstVisibleIndex = parsedDiff.files.findIndex(
1031- (file) => file.id === fileIdsInPriorityOrder[0],
1032- );
1033- const lastVisibleIndex = parsedDiff.files.findIndex(
1034- (file) => file.id === fileIdsInPriorityOrder[fileIdsInPriorityOrder.length - 1],
1035- );
1036-
1037- if (firstVisibleIndex < 0 || lastVisibleIndex < 0) {
1038- return fileIdsInPriorityOrder;
1039- }
1040-
1041- const startIndex = Math.max(0, firstVisibleIndex - REVIEW_HIGHLIGHT_BACKTRACK_COUNT);
1042- const endIndex = Math.min(
1043- parsedDiff.files.length - 1,
1044- lastVisibleIndex + REVIEW_HIGHLIGHT_LOOKAHEAD_COUNT,
1045- );
1046-
1047- const queuedIds: string[] = [];
1048- for (let index = startIndex; index <= endIndex; index += 1) {
1049- const fileId = parsedDiff.files[index]?.id;
1050- if (fileId && highlightableFileIds.has(fileId)) {
1051- queuedIds.push(fileId);
1052- }
1053- }
1054-
1055- return queuedIds;
1056- }, [highlightableFileIds, highlightableFiles.length, parsedDiff, visibleFileIds]);
1057- const viewportWidth = Math.max(width, 280);
1058- const reviewListContentWidth = useMemo(
1059- () => computeReviewListContentWidth(reviewListItems, viewportWidth),
1060- [reviewListItems, viewportWidth],
1061- );
1062+ useEffect(() => {
1063+ highlightableFilesRef.current = highlightableFiles;
1064+ }, [highlightableFiles]);
1065 const loadGitDiffs = useCallback(async () => {
1066 if (!cwd) {
1067 return;
1068@@ -714,100 +935,6 @@ export function ReviewSheet() {
1069 void loadGitDiffs();
1070 }, [loadGitDiffs]);
1071
1072- useEffect(() => {
1073- selectedThemeRef.current = selectedTheme;
1074- }, [selectedTheme]);
1075-
1076- useEffect(() => {
1077- highlightableFilesByIdRef.current = new Map(highlightableFiles.map((file) => [file.id, file]));
1078- }, [highlightableFiles]);
1079-
1080- const startHighlightQueueRunner = useCallback(function startHighlightQueueRunner() {
1081- if (highlightQueueActiveRef.current) {
1082- return;
1083- }
1084-
1085- const generation = highlightQueueGenerationRef.current;
1086- highlightQueueActiveRef.current = true;
1087-
1088- void (async () => {
1089- try {
1090- while (generation === highlightQueueGenerationRef.current) {
1091- const nextFileId = highlightQueueRef.current.shift();
1092- if (!nextFileId) {
1093- break;
1094- }
1095-
1096- const file = highlightableFilesByIdRef.current.get(nextFileId);
1097- if (!file) {
1098- continue;
1099- }
1100-
1101- const theme = selectedThemeRef.current;
1102- const cached = getCachedHighlightedReviewFile(file, theme);
1103- if (cached) {
1104- logReviewDiffDiagnostic("using cached highlighted file", {
1105- fileId: file.id,
1106- filePath: file.path,
1107- theme,
1108- });
1109- setHighlightedFilesById((current) =>
1110- current[file.id] === cached ? current : { ...current, [file.id]: cached },
1111- );
1112- continue;
1113- }
1114-
1115- logReviewDiffDiagnostic("requesting highlighted file", {
1116- fileId: file.id,
1117- filePath: file.path,
1118- theme,
1119- });
1120-
1121- try {
1122- await new Promise<void>((resolve) => {
1123- InteractionManager.runAfterInteractions(() => resolve());
1124- });
1125- const result = await highlightReviewFile(file, theme);
1126- if (generation !== highlightQueueGenerationRef.current) {
1127- logReviewDiffDiagnostic("discarding highlighted file after cancellation", {
1128- fileId: file.id,
1129- filePath: file.path,
1130- });
1131- return;
1132- }
1133-
1134- logReviewDiffDiagnostic("received highlighted file", {
1135- fileId: file.id,
1136- filePath: file.path,
1137- additionLines: result.additionLines.length,
1138- deletionLines: result.deletionLines.length,
1139- });
1140- setHighlightedFilesById((current) => {
1141- if (current[file.id] === result) {
1142- return current;
1143- }
1144- return { ...current, [file.id]: result };
1145- });
1146- } catch (error) {
1147- logReviewDiffDiagnostic("highlight request failed", {
1148- fileId: file.id,
1149- filePath: file.path,
1150- error: error instanceof Error ? error.message : String(error),
1151- });
1152- }
1153- }
1154- } finally {
1155- highlightQueueActiveRef.current = false;
1156- if (
1157- generation === highlightQueueGenerationRef.current &&
1158- highlightQueueRef.current.length > 0
1159- ) {
1160- startHighlightQueueRunner();
1161- }
1162- }
1163- })();
1164- }, []);
1165-
1166 useEffect(() => {
1167 if (reviewSections.length === 0) {
1168 return;
1169@@ -854,15 +981,15 @@ export function ReviewSheet() {
1170 }
1171
1172 updateReviewExpandedFileIds(reviewCache.threadKey, selectedSection.id, (existing) => {
1173- if (existing !== undefined) {
1174- const validIds = existing.filter((id) => parsedDiff.files.some((file) => file.id === id));
1175- if (validIds.length === existing.length) {
1176- return existing;
1177- }
1178- return validIds;
1179+ const validIds = getValidReviewExpandedFileIds(parsedDiff.files, existing);
1180+ if (
1181+ existing !== undefined &&
1182+ validIds.length === existing.length &&
1183+ validIds.every((id, index) => id === existing[index])
1184+ ) {
1185+ return existing;
1186 }
1187-
1188- return getDefaultExpandedFileIds(parsedDiff.files);
1189+ return validIds;
1190 });
1191 }, [parsedDiff, reviewCache.threadKey, selectedSection?.id]);
1192
1193@@ -887,11 +1014,7 @@ export function ReviewSheet() {
1194
1195 useEffect(() => {
1196 setHighlightedFilesById({});
1197- setVisibleFileIds([]);
1198- highlightQueueGenerationRef.current += 1;
1199- highlightQueueRef.current = [];
1200- highlightRequestedFileIdsRef.current = new Set();
1201- highlightQueueActiveRef.current = false;
1202+ highlightRunIdRef.current += 1;
1203 clearReviewHighlightFileCache();
1204 loggedMissingReviewTokenKeys.clear();
1205 logReviewDiffDiagnostic("reset highlighted files", {
1206@@ -905,15 +1028,23 @@ export function ReviewSheet() {
1207 return;
1208 }
1209
1210+ markReviewEvent("parsed-diff-ready", {
1211+ sectionId: selectedSection?.id ?? null,
1212+ fileCount: parsedDiff.fileCount,
1213+ additions: parsedDiff.additions,
1214+ deletions: parsedDiff.deletions,
1215+ renderedItems: reviewListItems.length,
1216+ });
1217 logReviewDiffDiagnostic("parsed diff files", {
1218 selectedSectionId: selectedSection?.id ?? null,
1219 fileCount: parsedDiff.fileCount,
1220 renderableFileCount: parsedDiff.files.length,
1221 });
1222- }, [parsedDiff, selectedSection?.id]);
1223+ }, [parsedDiff, reviewListItems.length, selectedSection?.id]);
1224
1225 useEffect(() => {
1226- if (priorityHighlightFileIds.length === 0) {
1227+ const files = highlightableFilesRef.current;
1228+ if (files.length === 0) {
1229 logReviewDiffDiagnostic("no highlightable files", {
1230 selectedSectionId: selectedSection?.id ?? null,
1231 parsedDiffKind: parsedDiff.kind,
1232@@ -922,33 +1053,98 @@ export function ReviewSheet() {
1233 return;
1234 }
1235
1236- const queuedFileIds: string[] = [];
1237- priorityHighlightFileIds.forEach((fileId) => {
1238- if (highlightRequestedFileIdsRef.current.has(fileId)) {
1239- return;
1240- }
1241-
1242- const file = highlightableFilesByIdRef.current.get(fileId);
1243- if (!file) {
1244- return;
1245- }
1246-
1247- highlightRequestedFileIdsRef.current.add(fileId);
1248- highlightQueueRef.current.push(fileId);
1249- queuedFileIds.push(fileId);
1250- });
1251-
1252- if (queuedFileIds.length === 0) {
1253+ if (reviewHighlighter.status !== "ready") {
1254+ logReviewDiffDiagnostic("waiting for highlighter provider", {
1255+ selectedSectionId: selectedSection?.id ?? null,
1256+ status: reviewHighlighter.status,
1257+ error: reviewHighlighter.error,
1258+ });
1259 return;
1260 }
1261
1262- logReviewDiffDiagnostic("scheduling file highlights", {
1263+ const runId = highlightRunIdRef.current;
1264+ let cancelled = false;
1265+
1266+ logReviewDiffDiagnostic("streaming file highlights", {
1267 selectedSectionId: selectedSection?.id ?? null,
1268- fileCount: queuedFileIds.length,
1269- fileIds: queuedFileIds,
1270+ fileCount: files.length,
1271 });
1272- startHighlightQueueRunner();
1273- }, [parsedDiff.kind, priorityHighlightFileIds, selectedSection?.id, startHighlightQueueRunner]);
1274+
1275+ void (async () => {
1276+ for (const file of files) {
1277+ if (cancelled || runId !== highlightRunIdRef.current) {
1278+ return;
1279+ }
1280+
1281+ const cached = getCachedHighlightedReviewFile(file, selectedTheme);
1282+ if (cached) {
1283+ setHighlightedFilesById((current) =>
1284+ current[file.id] === cached ? current : { ...current, [file.id]: cached },
1285+ );
1286+ continue;
1287+ }
1288+
1289+ logReviewDiffDiagnostic("requesting highlighted file", {
1290+ fileId: file.id,
1291+ filePath: file.path,
1292+ theme: selectedTheme,
1293+ });
1294+
1295+ try {
1296+ const highlightStartedAt = performance.now();
1297+ const result = await streamHighlightReviewFile(file, selectedTheme, (progress) => {
1298+ if (cancelled || runId !== highlightRunIdRef.current) {
1299+ return;
1300+ }
1301+
1302+ if (!progress.complete) {
1303+ return;
1304+ }
1305+
1306+ logReviewDiffDiagnostic("received streamed highlighted file", {
1307+ fileId: file.id,
1308+ filePath: file.path,
1309+ highlightedLineCount: progress.highlightedLineCount,
1310+ durationMs: Math.round(performance.now() - highlightStartedAt),
1311+ });
1312+ });
1313+
1314+ if (cancelled || runId !== highlightRunIdRef.current) {
1315+ return;
1316+ }
1317+
1318+ logReviewDiffDiagnostic("received highlighted file", {
1319+ fileId: file.id,
1320+ filePath: file.path,
1321+ additionLines: result.additionLines.length,
1322+ deletionLines: result.deletionLines.length,
1323+ });
1324+ setHighlightedFilesById((current) =>
1325+ current[file.id] === result ? current : { ...current, [file.id]: result },
1326+ );
1327+ } catch (error) {
1328+ logReviewDiffDiagnostic("highlight request failed", {
1329+ fileId: file.id,
1330+ filePath: file.path,
1331+ error: error instanceof Error ? error.message : String(error),
1332+ });
1333+ }
1334+
1335+ await waitForReviewDelay(0);
1336+ }
1337+ })();
1338+
1339+ return () => {
1340+ cancelled = true;
1341+ };
1342+ }, [
1343+ highlightableFilesKey,
1344+ parsedDiff.kind,
1345+ reviewHighlighter.error,
1346+ reviewHighlighter.status,
1347+ selectedSection?.id,
1348+ selectedTheme,
1349+ ]);
1350
1351 const refreshSelectedSection = useCallback(async () => {
1352 if (!selectedSection) {
1353@@ -968,20 +1164,68 @@ export function ReviewSheet() {
1354
1355 const handleToggleExpandedFile = useCallback(
1356 (fileId: string) => {
1357- if (!reviewCache.threadKey || !selectedSection?.id || parsedDiff.kind !== "files") {
1358+ if (!selectedSection?.id || parsedDiff.kind !== "files") {
1359 return;
1360 }
1361
1362- updateReviewExpandedFileIds(reviewCache.threadKey, selectedSection.id, (existing) => {
1363- const currentIds = existing ?? getDefaultExpandedFileIds(parsedDiff.files);
1364- return currentIds.includes(fileId)
1365+ const sectionId = selectedSection.id;
1366+
1367+ setLocalExpandedFileIdsBySection((current) => {
1368+ const currentIds = getValidReviewExpandedFileIds(parsedDiff.files, current[sectionId]);
1369+ const nextIds = currentIds.includes(fileId)
1370 ? currentIds.filter((id) => id !== fileId)
1371 : [...currentIds, fileId];
1372+
1373+ return {
1374+ ...current,
1375+ [sectionId]: nextIds,
1376+ };
1377 });
1378+
1379+ if (reviewCache.threadKey) {
1380+ updateReviewExpandedFileIds(reviewCache.threadKey, sectionId, (existing) => {
1381+ const currentIds = getValidReviewExpandedFileIds(parsedDiff.files, existing);
1382+ return currentIds.includes(fileId)
1383+ ? currentIds.filter((id) => id !== fileId)
1384+ : [...currentIds, fileId];
1385+ });
1386+ }
1387 },
1388 [parsedDiff, reviewCache.threadKey, selectedSection?.id],
1389 );
1390
1391+ const handleToggleViewedFile = useCallback(
1392+ (fileId: string) => {
1393+ if (!selectedSection?.id) {
1394+ return;
1395+ }
1396+
1397+ const sectionId = selectedSection.id;
1398+
1399+ setLocalViewedFileIdsBySection((current) => {
1400+ const currentIds = current[sectionId] ?? [];
1401+ const nextIds = currentIds.includes(fileId)
1402+ ? currentIds.filter((id) => id !== fileId)
1403+ : [...currentIds, fileId];
1404+
1405+ return {
1406+ ...current,
1407+ [sectionId]: nextIds,
1408+ };
1409+ });
1410+
1411+ if (reviewCache.threadKey) {
1412+ updateReviewViewedFileIds(reviewCache.threadKey, sectionId, (existing) => {
1413+ const currentIds = existing ?? [];
1414+ return currentIds.includes(fileId)
1415+ ? currentIds.filter((id) => id !== fileId)
1416+ : [...currentIds, fileId];
1417+ });
1418+ }
1419+ },
1420+ [reviewCache.threadKey, selectedSection?.id],
1421+ );
1422+
1423 const handleRevealLargeDiff = useCallback(
1424 (fileId: string) => {
1425 if (!reviewCache.threadKey || !selectedSection?.id) {
1426@@ -1080,35 +1324,6 @@ export function ReviewSheet() {
1427
1428 return <>{children}</>;
1429 }, [error, parsedDiffNotice]);
1430- const stickyHeaderIndices = useMemo(() => {
1431- const itemOffset = listHeader ? 1 : 0;
1432-
1433- return reviewListItems.flatMap((item, index) =>
1434- item.kind === "file-header" ? [index + itemOffset] : [],
1435- );
1436- }, [listHeader, reviewListItems]);
1437-
1438- const viewabilityConfigRef = useRef({
1439- itemVisiblePercentThreshold: 10,
1440- });
1441- const onViewableItemsChangedRef = useRef(
1442- ({
1443- viewableItems,
1444- }: {
1445- readonly viewableItems: Array<ViewToken<ReviewListItem>>;
1446- readonly changed: Array<ViewToken<ReviewListItem>>;
1447- }) => {
1448- const nextVisibleFileIds = Array.from(
1449- new Set(
1450- viewableItems
1451- .filter((token) => token.isViewable && token.item !== undefined)
1452- .map((token) => token.item.fileId),
1453- ),
1454- );
1455-
1456- setVisibleFileIds(nextVisibleFileIds);
1457- },
1458- );
1459
1460 const renderReviewListItem = useCallback(
1461 ({ item }: ListRenderItemInfo<ReviewListItem>) => {
1462@@ -1116,112 +1331,142 @@ export function ReviewSheet() {
1463 return null;
1464 }
1465
1466+ let renderedItem: ReactElement | null = null;
1467 switch (item.kind) {
1468 case "file-header":
1469- return (
1470+ renderedItem = (
1471 <ReviewFileCard
1472 file={item.file}
1473 fileId={item.fileId}
1474 expanded={item.expanded}
1475- viewportWidth={reviewListContentWidth}
1476+ viewed={viewedFileIdSet.has(item.fileId)}
1477+ viewportWidth={viewportWidth}
1478 onToggleFile={handleToggleExpandedFile}
1479+ onToggleViewed={handleToggleViewedFile}
1480 />
1481 );
1482+ break;
1483 case "file-suppressed":
1484- return (
1485+ renderedItem = (
1486 <ReviewFileSuppressedBody
1487 message={item.message}
1488 actionLabel={item.actionLabel}
1489 fileId={item.fileId}
1490- viewportWidth={reviewListContentWidth}
1491+ viewportWidth={viewportWidth}
1492 onLoadDiffFile={handleRevealLargeDiff}
1493 />
1494 );
1495- case "hunk":
1496- return (
1497- <ReviewHunkRow
1498- header={item.row.header}
1499- context={item.row.context}
1500- viewportWidth={reviewListContentWidth}
1501- />
1502+ break;
1503+ case "hunk": {
1504+ const contentWidth = reviewContentWidthByFileId.get(item.fileId) ?? viewportWidth;
1505+ const gutterWidth = reviewGutterWidthByFileId.get(item.fileId) ?? 0;
1506+
1507+ renderedItem = (
1508+ <ReviewCodePanRow
1509+ key={item.id}
1510+ contentWidth={contentWidth}
1511+ gutterWidth={gutterWidth}
1512+ horizontalOffset={getReviewFileHorizontalOffset(item.fileId)}
1513+ leftGutter={<ReviewHunkGutter gutterWidth={gutterWidth} />}
1514+ viewportWidth={viewportWidth}
1515+ >
1516+ <ReviewHunkRow
1517+ header={item.row.header}
1518+ context={item.row.context}
1519+ viewportWidth={contentWidth}
1520+ />
1521+ </ReviewCodePanRow>
1522 );
1523+ break;
1524+ }
1525 case "line": {
1526- const file = reviewFileById.get(item.fileId);
1527- if (!file) {
1528- return null;
1529- }
1530-
1531- const fileLineRows = reviewLineRowsByFileId.get(file.id) ?? [];
1532- const lineIndex = reviewLineIndexByRowId.get(item.row.id);
1533- if (lineIndex === undefined) {
1534- return null;
1535- }
1536-
1537+ const fileLineRows = reviewLineRowsByFileId.get(item.file.id) ?? [];
1538 const pendingSelectionForFile =
1539 pendingCommentSelection &&
1540 pendingCommentSelection.sectionTitle === selectedSection.title &&
1541- pendingCommentSelection.filePath === file.path
1542+ pendingCommentSelection.filePath === item.file.path
1543 ? pendingCommentSelection
1544 : null;
1545 const selectedTargetForFile =
1546 activeCommentTarget &&
1547 activeCommentTarget.sectionTitle === selectedSection.title &&
1548- activeCommentTarget.filePath === file.path
1549+ activeCommentTarget.filePath === item.file.path
1550 ? activeCommentTarget
1551 : null;
1552 const highlightedFile =
1553- highlightedFilesById[file.id] ??
1554- getCachedHighlightedReviewFile(file, selectedTheme) ??
1555+ deferredHighlightedFilesById[item.file.id] ??
1556+ getCachedHighlightedReviewFile(item.file, selectedTheme) ??
1557 null;
1558+ const contentWidth = reviewContentWidthByFileId.get(item.fileId) ?? viewportWidth;
1559+ const gutterWidth = reviewGutterWidthByFileId.get(item.fileId) ?? 0;
1560
1561 if (highlightedFile === null) {
1562- const missingTokenKey = `${selectedSection.id}:${file.id}`;
1563+ const missingTokenKey = `${selectedSection.id}:${item.file.id}`;
1564 if (!loggedMissingReviewTokenKeys.has(missingTokenKey)) {
1565 loggedMissingReviewTokenKeys.add(missingTokenKey);
1566 logReviewDiffDiagnostic("rendering file without tokens", {
1567 sectionId: selectedSection.id,
1568- fileId: file.id,
1569- filePath: file.path,
1570- highlightedFileKnownInState: highlightedFilesById[file.id] !== undefined,
1571+ fileId: item.file.id,
1572+ filePath: item.file.path,
1573+ highlightedFileKnownInState:
1574+ deferredHighlightedFilesById[item.file.id] !== undefined,
1575 });
1576 }
1577 }
1578
1579 const selectionState =
1580- pendingSelectionForFile?.anchorIndex === lineIndex
1581+ pendingSelectionForFile?.anchorIndex === item.lineIndex
1582 ? ("anchor" as const)
1583 : selectedTargetForFile &&
1584- lineIndex >= selectedTargetForFile.startIndex &&
1585- lineIndex <= selectedTargetForFile.endIndex
1586+ item.lineIndex >= selectedTargetForFile.startIndex &&
1587+ item.lineIndex <= selectedTargetForFile.endIndex
1588 ? ("selected" as const)
1589 : null;
1590
1591- return (
1592- <ReviewLineRow
1593- line={item.row}
1594- tokens={getHighlightedTokensForLine(item.row, highlightedFile)}
1595- viewportWidth={reviewListContentWidth}
1596- selectionState={selectionState}
1597- onComment={() =>
1598- handlePressLine({
1599- sectionTitle: selectedSection.title,
1600- filePath: file.path,
1601- lines: fileLineRows,
1602- lineIndex,
1603- })
1604- }
1605- onStartRangeSelection={() =>
1606- handleStartRangeSelection({
1607- sectionTitle: selectedSection.title,
1608- filePath: file.path,
1609- lines: fileLineRows,
1610- lineIndex,
1611- })
1612+ renderedItem = (
1613+ <ReviewCodePanRow
1614+ key={item.id}
1615+ contentWidth={contentWidth}
1616+ gutterWidth={gutterWidth}
1617+ horizontalOffset={getReviewFileHorizontalOffset(item.fileId)}
1618+ leftGutter={
1619+ <ReviewLineGutter
1620+ change={item.row.change}
1621+ gutterWidth={gutterWidth}
1622+ lineNumber={getReviewUnifiedLineNumber(item.row)}
1623+ />
1624 }
1625- />
1626+ viewportWidth={viewportWidth}
1627+ >
1628+ <ReviewLineRow
1629+ line={item.row}
1630+ tokens={getHighlightedTokensForLine(item.row, highlightedFile)}
1631+ viewportWidth={contentWidth}
1632+ selectionState={selectionState}
1633+ onComment={() =>
1634+ handlePressLine({
1635+ sectionTitle: selectedSection.title,
1636+ filePath: item.file.path,
1637+ lines: fileLineRows,
1638+ lineIndex: item.lineIndex,
1639+ })
1640+ }
1641+ onStartRangeSelection={() =>
1642+ handleStartRangeSelection({
1643+ sectionTitle: selectedSection.title,
1644+ filePath: item.file.path,
1645+ lines: fileLineRows,
1646+ lineIndex: item.lineIndex,
1647+ })
1648+ }
1649+ />
1650+ </ReviewCodePanRow>
1651 );
1652+ break;
1653 }
1654 }
1655+
1656+ return renderedItem;
1657 },
1658 [
1659 activeCommentTarget,
1660@@ -1229,14 +1474,17 @@ export function ReviewSheet() {
1661 handleRevealLargeDiff,
1662 handleStartRangeSelection,
1663 handleToggleExpandedFile,
1664- highlightedFilesById,
1665+ handleToggleViewedFile,
1666+ getReviewFileHorizontalOffset,
1667+ deferredHighlightedFilesById,
1668 pendingCommentSelection,
1669- reviewFileById,
1670- reviewLineIndexByRowId,
1671+ reviewContentWidthByFileId,
1672+ reviewGutterWidthByFileId,
1673 reviewLineRowsByFileId,
1674- reviewListContentWidth,
1675 selectedSection,
1676 selectedTheme,
1677+ viewedFileIdSet,
1678+ viewportWidth,
1679 ],
1680 );
1681
1682@@ -1374,27 +1622,20 @@ export function ReviewSheet() {
1683 <View className="flex-1 bg-sheet">
1684 {selectedSection && parsedDiff.kind === "files" ? (
1685 <FlatList
1686- style={{ flex: 1 }}
1687+ style={{ flex: 1, width: viewportWidth }}
1688 contentInsetAdjustmentBehavior="never"
1689- contentInset={{ top: topContentInset }}
1690- contentOffset={{ x: 0, y: -topContentInset }}
1691- scrollIndicatorInsets={{ top: topContentInset }}
1692 data={reviewListItems}
1693 renderItem={renderReviewListItem}
1694 keyExtractor={(item) => item.id}
1695+ initialNumToRender={20}
1696+ maxToRenderPerBatch={20}
1697+ updateCellsBatchingPeriod={16}
1698+ windowSize={5}
1699+ removeClippedSubviews={false}
1700 keyboardShouldPersistTaps="handled"
1701 ListHeaderComponent={listHeader}
1702- stickyHeaderIndices={stickyHeaderIndices}
1703- removeClippedSubviews={false}
1704- initialNumToRender={24}
1705- maxToRenderPerBatch={16}
1706- updateCellsBatchingPeriod={16}
1707- windowSize={10}
1708- scrollEventThrottle={16}
1709- onViewableItemsChanged={onViewableItemsChangedRef.current}
1710- viewabilityConfig={viewabilityConfigRef.current}
1711 contentContainerStyle={{
1712- paddingTop: REVIEW_HEADER_SPACING,
1713+ paddingTop: topContentInset + REVIEW_HEADER_SPACING,
1714 paddingBottom: Math.max(insets.bottom, 18) + 18,
1715 }}
1716 />
1717diff --git a/apps/mobile/src/features/review/reviewDiffRendering.tsx b/apps/mobile/src/features/review/reviewDiffRendering.tsx
1718index d61924a62..3f2ae0160 100644
1719--- a/apps/mobile/src/features/review/reviewDiffRendering.tsx
1720+++ b/apps/mobile/src/features/review/reviewDiffRendering.tsx
1721@@ -11,6 +11,9 @@ export const REVIEW_MONO_FONT_FAMILY = Platform.select({
1722 default: "monospace",
1723 });
1724
1725+export const REVIEW_DIFF_LINE_HEIGHT = 26;
1726+const REVIEW_DELETE_STRIPE_COUNT = REVIEW_DIFF_LINE_HEIGHT / 2;
1727+
1728 export function renderVisibleWhitespace(value: string): string {
1729 const expandedTabs = value.replace(/\t/g, " ");
1730 return expandedTabs.replace(/^( +)/, (leading) => leading.replaceAll(" ", "\u00A0"));
1731@@ -37,10 +40,13 @@ function diffHighlightColor(change: ReviewRenderableLineRow["change"]): string |
1732 export function ReviewChangeBar(props: { readonly change: ReviewRenderableLineRow["change"] }) {
1733 if (props.change === "delete") {
1734 return (
1735- <View className="w-[5px] self-stretch overflow-hidden">
1736- <View className="flex-1 justify-between">
1737- {Array.from({ length: 6 }, (_, index) => (
1738- <View key={index} className="h-[2px] w-[5px] bg-rose-400" />
1739+ <View className="w-[5px] overflow-hidden" style={{ height: REVIEW_DIFF_LINE_HEIGHT }}>
1740+ <View>
1741+ {Array.from({ length: REVIEW_DELETE_STRIPE_COUNT }, (_, index) => (
1742+ <View key={index}>
1743+ <View className="w-[5px] bg-rose-400" style={{ height: 1 }} />
1744+ <View style={{ height: 1 }} />
1745+ </View>
1746 ))}
1747 </View>
1748 </View>
1749@@ -48,7 +54,7 @@ export function ReviewChangeBar(props: { readonly change: ReviewRenderableLineRo
1750 }
1751
1752 return (
1753- <View className="w-[5px] self-stretch overflow-hidden">
1754+ <View className="w-[5px] overflow-hidden" style={{ height: REVIEW_DIFF_LINE_HEIGHT }}>
1755 <View className={cn("h-full w-[5px] flex-1", changeBarTone(props.change))} />
1756 </View>
1757 );
1758@@ -63,6 +69,7 @@ export function DiffTokenText(props: {
1759 if (!props.tokens || props.tokens.length === 0) {
1760 return (
1761 <NativeText
1762+ numberOfLines={1}
1763 selectable
1764 className={cn("text-[13px] leading-[17px] font-medium text-foreground", props.className)}
1765 style={{ fontFamily: REVIEW_MONO_FONT_FAMILY }}
1766@@ -74,6 +81,7 @@ export function DiffTokenText(props: {
1767
1768 return (
1769 <NativeText
1770+ numberOfLines={1}
1771 selectable
1772 className={cn("text-[13px] leading-[17px] font-medium text-foreground", props.className)}
1773 style={{ fontFamily: REVIEW_MONO_FONT_FAMILY }}
1774diff --git a/apps/mobile/src/features/review/reviewHighlighterEngine.test.ts b/apps/mobile/src/features/review/reviewHighlighterEngine.test.ts
1775index d63a7a67c..5449fc6bf 100644
1776--- a/apps/mobile/src/features/review/reviewHighlighterEngine.test.ts
1777+++ b/apps/mobile/src/features/review/reviewHighlighterEngine.test.ts
1778@@ -6,9 +6,9 @@ import {
1779 } from "./reviewHighlighterEngine";
1780
1781 describe("resolveReviewHighlighterEnginePreference", () => {
1782- it("defaults invalid values to javascript", () => {
1783- expect(resolveReviewHighlighterEnginePreference(undefined)).toBe("javascript");
1784- expect(resolveReviewHighlighterEnginePreference("bogus")).toBe("javascript");
1785+ it("defaults invalid values to native", () => {
1786+ expect(resolveReviewHighlighterEnginePreference(undefined)).toBe("native");
1787+ expect(resolveReviewHighlighterEnginePreference("bogus")).toBe("native");
1788 });
1789
1790 it("accepts supported values", () => {
1791diff --git a/apps/mobile/src/features/review/reviewHighlighterEngine.ts b/apps/mobile/src/features/review/reviewHighlighterEngine.ts
1792index 5ef9f055a..428768537 100644
1793--- a/apps/mobile/src/features/review/reviewHighlighterEngine.ts
1794+++ b/apps/mobile/src/features/review/reviewHighlighterEngine.ts
1795@@ -11,7 +11,7 @@ export function resolveReviewHighlighterEnginePreference(
1796 case "native":
1797 return "native";
1798 default:
1799- return "javascript";
1800+ return "native";
1801 }
1802 }
1803
1804diff --git a/apps/mobile/src/features/review/reviewModel.test.ts b/apps/mobile/src/features/review/reviewModel.test.ts
1805index a24a99ceb..69a6e7261 100644
1806--- a/apps/mobile/src/features/review/reviewModel.test.ts
1807+++ b/apps/mobile/src/features/review/reviewModel.test.ts
1808@@ -238,7 +238,7 @@ describe("buildReviewParsedDiff", () => {
1809 });
1810 });
1811
1812- it("flattens expanded files into virtualizable review items", () => {
1813+ it("flattens expanded file rows into virtualized review items", () => {
1814 const file = makeRenderableFile({
1815 path: "apps/mobile/src/a.ts",
1816 rows: [
1817@@ -270,8 +270,19 @@ describe("buildReviewParsedDiff", () => {
1818
1819 expect(items).toEqual([
1820 expect.objectContaining({ kind: "file-header", fileId: file.id, expanded: true }),
1821- expect.objectContaining({ kind: "hunk", fileId: file.id, row: file.rows[0] }),
1822- expect.objectContaining({ kind: "line", fileId: file.id, row: file.rows[1] }),
1823+ expect.objectContaining({
1824+ kind: "hunk",
1825+ fileId: file.id,
1826+ file,
1827+ row: file.rows[0],
1828+ }),
1829+ expect.objectContaining({
1830+ kind: "line",
1831+ fileId: file.id,
1832+ file,
1833+ row: file.rows[1],
1834+ lineIndex: 0,
1835+ }),
1836 ]);
1837 });
1838
1839diff --git a/apps/mobile/src/features/review/reviewModel.ts b/apps/mobile/src/features/review/reviewModel.ts
1840index 27e6d7ae4..1cfbf358c 100644
1841--- a/apps/mobile/src/features/review/reviewModel.ts
1842+++ b/apps/mobile/src/features/review/reviewModel.ts
1843@@ -72,6 +72,7 @@ export interface ReviewHunkListItem {
1844 readonly kind: "hunk";
1845 readonly id: string;
1846 readonly fileId: string;
1847+ readonly file: ReviewRenderableFile;
1848 readonly row: ReviewRenderableHunkRow;
1849 }
1850
1851@@ -79,7 +80,9 @@ export interface ReviewLineListItem {
1852 readonly kind: "line";
1853 readonly id: string;
1854 readonly fileId: string;
1855+ readonly file: ReviewRenderableFile;
1856 readonly row: ReviewRenderableLineRow;
1857+ readonly lineIndex: number;
1858 }
1859
1860 export type ReviewListItem =
1861@@ -308,7 +311,7 @@ export function getReviewFilePreviewState(file: ReviewRenderableFile): ReviewFil
1862 }
1863
1864 // The flattened review list item model is inspired by pierre/diffs' iterator-first
1865-// virtualization architecture, adapted here for React Native and LegendList.
1866+// virtualization architecture, adapted here for React Native virtualization.
1867 // Original project: https://github.com/pingdotgg/pierre/tree/main/packages/diffs
1868 // Reference files:
1869 // - src/utils/iterateOverDiff.ts
1870@@ -350,12 +353,14 @@ export function buildReviewListItems(input: {
1871 }
1872 }
1873
1874- file.rows.forEach((row) => {
1875+ let lineIndex = 0;
1876+ file.rows.forEach((row, rowIndex) => {
1877 if (row.kind === "hunk") {
1878 items.push({
1879 kind: "hunk",
1880- id: row.id,
1881+ id: `${file.id}:row:${rowIndex}:${row.id}`,
1882 fileId: file.id,
1883+ file,
1884 row,
1885 });
1886 return;
1887@@ -363,10 +368,13 @@ export function buildReviewListItems(input: {
1888
1889 items.push({
1890 kind: "line",
1891- id: row.id,
1892+ id: `${file.id}:row:${rowIndex}:${row.id}`,
1893 fileId: file.id,
1894+ file,
1895 row,
1896+ lineIndex,
1897 });
1898+ lineIndex += 1;
1899 });
1900 });
1901
1902diff --git a/apps/mobile/src/features/review/reviewState.ts b/apps/mobile/src/features/review/reviewState.ts
1903index 06134db7d..c116f93fe 100644
1904--- a/apps/mobile/src/features/review/reviewState.ts
1905+++ b/apps/mobile/src/features/review/reviewState.ts
1906@@ -64,6 +64,13 @@ const reviewRevealedLargeFileIdsByThreadKeyAtom = Atom.family((threadKey: string
1907 ),
1908 );
1909
1910+const reviewViewedFileIdsByThreadKeyAtom = Atom.family((threadKey: string) =>
1911+ Atom.make(EMPTY_REVIEW_SECTION_FILE_IDS).pipe(
1912+ Atom.keepAlive,
1913+ Atom.withLabel(`mobile:review:viewed-file-ids:${threadKey}`),
1914+ ),
1915+);
1916+
1917 const reviewParsedDiffBySectionCacheKeyAtom = Atom.family((cacheKey: string) =>
1918 Atom.make<{ readonly diff: string | null; readonly parsed: ReviewParsedDiff } | null>(null).pipe(
1919 Atom.keepAlive,
1920@@ -110,6 +117,9 @@ export function useReviewCacheForThread(input: {
1921 ? reviewRevealedLargeFileIdsByThreadKeyAtom(threadKey)
1922 : EMPTY_REVIEW_SECTION_FILE_IDS_ATOM,
1923 );
1924+ const viewedFileIdsBySection = useAtomValue(
1925+ threadKey ? reviewViewedFileIdsByThreadKeyAtom(threadKey) : EMPTY_REVIEW_SECTION_FILE_IDS_ATOM,
1926+ );
1927
1928 return {
1929 threadKey,
1930@@ -118,6 +128,7 @@ export function useReviewCacheForThread(input: {
1931 selectedSectionId,
1932 expandedFileIdsBySection,
1933 revealedLargeFileIdsBySection,
1934+ viewedFileIdsBySection,
1935 };
1936 }
1937
1938@@ -169,6 +180,20 @@ export function updateReviewRevealedLargeFileIds(
1939 });
1940 }
1941
1942+export function updateReviewViewedFileIds(
1943+ threadKey: string,
1944+ sectionId: string,
1945+ update: (current: ReadonlyArray<string> | undefined) => ReadonlyArray<string> | undefined,
1946+): void {
1947+ const atom = reviewViewedFileIdsByThreadKeyAtom(threadKey);
1948+ const current = appAtomRegistry.get(atom);
1949+ const nextValue = update(current[sectionId]);
1950+ appAtomRegistry.set(atom, {
1951+ ...current,
1952+ [sectionId]: nextValue,
1953+ });
1954+}
1955+
1956 export function getCachedReviewParsedDiff(input: {
1957 readonly threadKey: string | null;
1958 readonly sectionId: string | null;
1959diff --git a/apps/mobile/src/features/review/shikiReviewHighlighter.test.ts b/apps/mobile/src/features/review/shikiReviewHighlighter.test.ts
1960index 05b5c9213..402d00668 100644
1961--- a/apps/mobile/src/features/review/shikiReviewHighlighter.test.ts
1962+++ b/apps/mobile/src/features/review/shikiReviewHighlighter.test.ts
1963@@ -24,7 +24,7 @@ function makeRenderableFile(
1964 describe("highlightReviewFile", () => {
1965 it("preserves one highlighted token row per diff line even without trailing newlines", async () => {
1966 const file = makeRenderableFile({
1967- path: "apps/mobile/src/example.test.ts",
1968+ path: "apps/mobile/src/example.txt",
1969 additionLines: [
1970 'const items = ["a"];',
1971 'expect(items).toEqual(["a"]);',
1972@@ -36,15 +36,23 @@ describe("highlightReviewFile", () => {
1973 const highlighted = await highlightReviewFile(file, "light");
1974
1975 expect(highlighted.additionLines).toHaveLength(file.additionLines.length);
1976- expect(highlighted.additionLines[0]?.some((token) => token.content === "const")).toBe(true);
1977- expect(highlighted.additionLines[1]?.some((token) => token.content === "expect")).toBe(true);
1978- expect(highlighted.additionLines[2]?.some((token) => token.content === "const")).toBe(true);
1979- expect(highlighted.additionLines[3]?.some((token) => token.content === "expect")).toBe(true);
1980+ expect(highlighted.additionLines[0]?.map((token) => token.content).join("")).toBe(
1981+ file.additionLines[0],
1982+ );
1983+ expect(highlighted.additionLines[1]?.map((token) => token.content).join("")).toBe(
1984+ file.additionLines[1],
1985+ );
1986+ expect(highlighted.additionLines[2]?.map((token) => token.content).join("")).toBe(
1987+ file.additionLines[2],
1988+ );
1989+ expect(highlighted.additionLines[3]?.map((token) => token.content).join("")).toBe(
1990+ file.additionLines[3],
1991+ );
1992 });
1993
1994 it("adds word-alt diff emphasis for paired deletion and addition lines", async () => {
1995 const file = makeRenderableFile({
1996- path: "apps/mobile/src/example-inline-diff.test.ts",
1997+ path: "apps/mobile/src/example-inline-diff.txt",
1998 additionLines: ["const after = 2;"],
1999 deletionLines: ["const before = 1;"],
2000 rows: [
2001@@ -82,7 +90,7 @@ describe("highlightReviewFile", () => {
2002 it("falls back to plain tokens for very long lines", async () => {
2003 const longLine = `const value = "${"a".repeat(1_100)}";`;
2004 const file = makeRenderableFile({
2005- path: "apps/mobile/src/example-long-line.ts",
2006+ path: "apps/mobile/src/example-long-line.txt",
2007 additionLines: [longLine],
2008 rows: [
2009 {
2010diff --git a/apps/mobile/src/features/review/shikiReviewHighlighter.ts b/apps/mobile/src/features/review/shikiReviewHighlighter.ts
2011index f7a5c4125..eb6bf6973 100644
2012--- a/apps/mobile/src/features/review/shikiReviewHighlighter.ts
2013+++ b/apps/mobile/src/features/review/shikiReviewHighlighter.ts
2014@@ -1,5 +1,14 @@
2015 import { createHighlighterCore, type HighlighterCore } from "@shikijs/core";
2016 import { createJavaScriptRegexEngine } from "@shikijs/engine-javascript";
2017+import bashLanguage from "@shikijs/langs/bash";
2018+import javascriptLanguage from "@shikijs/langs/javascript";
2019+import jsonLanguage from "@shikijs/langs/json";
2020+import jsxLanguage from "@shikijs/langs/jsx";
2021+import tsxLanguage from "@shikijs/langs/tsx";
2022+import typescriptLanguage from "@shikijs/langs/typescript";
2023+import yamlLanguage from "@shikijs/langs/yaml";
2024+import githubDarkDefault from "@shikijs/themes/github-dark-default";
2025+import githubLightDefault from "@shikijs/themes/github-light-default";
2026 import { getFiletypeFromFileName } from "@pierre/diffs/utils";
2027
2028 import {
2029@@ -11,6 +20,7 @@ import type { ReviewRenderableFile, ReviewRenderableLineRow } from "./reviewMode
2030 import { applyDiffRangesToTokens, computeWordAltDiffRanges } from "./reviewWordDiffs";
2031
2032 export type ReviewDiffTheme = "light" | "dark";
2033+export type { ReviewHighlighterEngine };
2034
2035 export interface ReviewHighlightedToken {
2036 content: string;
2037@@ -24,12 +34,19 @@ export interface ReviewHighlightedFile {
2038 readonly deletionLines: ReadonlyArray<ReadonlyArray<ReviewHighlightedToken>>;
2039 }
2040
2041+export interface ReviewHighlightFileProgress {
2042+ readonly highlightedFile: ReviewHighlightedFile;
2043+ readonly complete: boolean;
2044+ readonly highlightedLineCount: number;
2045+}
2046+
2047 const SHIKI_THEME_NAME_BY_SCHEME = {
2048 light: "github-light-default",
2049 dark: "github-dark-default",
2050 } as const;
2051 const REVIEW_HIGHLIGHTER_ENGINE_ENV_VALUE =
2052- process.env.EXPO_PUBLIC_REVIEW_HIGHLIGHTER_ENGINE ?? "javascript";
2053+ process.env.EXPO_PUBLIC_REVIEW_HIGHLIGHTER_ENGINE ??
2054+ (process.env.NODE_ENV === "test" ? "javascript" : "native");
2055 const REVIEW_HIGHLIGHTER_ENGINE_PREFERENCE = resolveReviewHighlighterEnginePreference(
2056 REVIEW_HIGHLIGHTER_ENGINE_ENV_VALUE,
2057 );
2058@@ -38,12 +55,30 @@ const REVIEW_HIGHLIGHTER_DISABLE_RESULT_CACHE = resolveReviewHighlighterBooleanF
2059 false,
2060 );
2061 const REVIEW_HIGHLIGHT_RESULT_CACHE_LIMIT = 8;
2062-const REVIEW_HIGHLIGHT_CHUNK_LINE_THRESHOLD = 40;
2063-const REVIEW_HIGHLIGHT_CHUNK_SIZE = 20;
2064+const REVIEW_HIGHLIGHT_CHUNK_LINE_THRESHOLD = 8;
2065+const REVIEW_HIGHLIGHT_CHUNK_SIZE = 200;
2066 const REVIEW_TOKENIZE_MAX_LINE_LENGTH = 1_000;
2067 const highlightCache = new Map<string, Promise<ReviewHighlightedFile>>();
2068 const resolvedHighlightCache = new Map<string, ReviewHighlightedFile>();
2069-const loadedLanguages = new Set<string>(["text"]);
2070+const REVIEW_INITIAL_LANGUAGE_MODULES = [
2071+ bashLanguage,
2072+ javascriptLanguage,
2073+ jsonLanguage,
2074+ jsxLanguage,
2075+ tsxLanguage,
2076+ typescriptLanguage,
2077+ yamlLanguage,
2078+] satisfies Parameters<typeof createHighlighterCore>[0]["langs"];
2079+const loadedLanguages = new Set<string>([
2080+ "text",
2081+ "bash",
2082+ "javascript",
2083+ "json",
2084+ "jsx",
2085+ "tsx",
2086+ "typescript",
2087+ "yaml",
2088+]);
2089 const languageLoadingPromises = new Map<string, Promise<boolean>>();
2090 const languageImports: Partial<Record<string, () => Promise<unknown>>> = {
2091 javascript: () => import("@shikijs/langs/javascript"),
2092@@ -215,21 +250,13 @@ function joinPatchLines(lines: ReadonlyArray<string>): string {
2093
2094 function waitForNextFrame(): Promise<void> {
2095 return new Promise((resolve) => {
2096- if (typeof requestAnimationFrame === "function") {
2097- requestAnimationFrame(() => resolve());
2098- return;
2099- }
2100-
2101 setTimeout(resolve, 0);
2102 });
2103 }
2104
2105 async function getHighlighter(): Promise<HighlighterCore> {
2106 if (!highlighterPromise) {
2107- const configuredHighlighterPromise = Promise.all([
2108- import("@shikijs/themes/github-light-default"),
2109- import("@shikijs/themes/github-dark-default"),
2110- ]).then(async ([lightThemeModule, darkThemeModule]) => {
2111+ const configuredHighlighterPromise = (async () => {
2112 let nativeEngineAvailable = false;
2113
2114 logReviewHighlighterDiagnostic("initializing", {
2115@@ -238,12 +265,11 @@ async function getHighlighter(): Promise<HighlighterCore> {
2116 resultCacheDisabled: REVIEW_HIGHLIGHTER_DISABLE_RESULT_CACHE,
2117 });
2118
2119- const themes = [lightThemeModule.default, darkThemeModule.default];
2120+ const themes = [githubLightDefault, githubDarkDefault];
2121
2122 if (REVIEW_HIGHLIGHTER_ENGINE_PREFERENCE !== "javascript") {
2123 try {
2124 const nativeEngineModule = await import("react-native-shiki-engine");
2125- logReviewHighlighterDiagnostic("imported react-native-shiki-engine");
2126 nativeEngineAvailable = nativeEngineModule.isNativeEngineAvailable();
2127 logReviewHighlighterDiagnostic("checked native engine availability", {
2128 nativeEngineAvailable,
2129@@ -253,7 +279,7 @@ async function getHighlighter(): Promise<HighlighterCore> {
2130 logReviewHighlighterDiagnostic("creating native regex engine");
2131 const highlighter = await createHighlighterCore({
2132 themes,
2133- langs: [],
2134+ langs: REVIEW_INITIAL_LANGUAGE_MODULES,
2135 engine: nativeEngineModule.createNativeEngine(),
2136 });
2137 logReviewHighlighterDiagnostic("using native engine");
2138@@ -281,7 +307,7 @@ async function getHighlighter(): Promise<HighlighterCore> {
2139 );
2140 const highlighter = await createHighlighterCore({
2141 themes,
2142- langs: [],
2143+ langs: REVIEW_INITIAL_LANGUAGE_MODULES,
2144 engine: createJavaScriptRegexEngine(),
2145 });
2146 logReviewHighlighterDiagnostic("using javascript engine", {
2147@@ -291,7 +317,7 @@ async function getHighlighter(): Promise<HighlighterCore> {
2148 highlighter,
2149 engine,
2150 };
2151- });
2152+ })();
2153
2154 highlighterPromise = configuredHighlighterPromise
2155 .then((result) => result.highlighter)
2156@@ -316,11 +342,52 @@ export async function getActiveReviewHighlighterEngine(): Promise<ReviewHighligh
2157 return activeHighlighterEnginePromise ?? Promise.resolve("javascript");
2158 }
2159
2160+export async function prepareReviewHighlighter(): Promise<void> {
2161+ await getHighlighter();
2162+}
2163+
2164+export async function prepareReviewHighlighterLanguages(
2165+ languages: ReadonlyArray<string>,
2166+): Promise<void> {
2167+ const highlighter = await getHighlighter();
2168+ await Promise.all(
2169+ languages.map(async (language) => {
2170+ const candidate = resolveLanguageAlias(language);
2171+ if (candidate === "text" || !(candidate in languageImports)) {
2172+ return;
2173+ }
2174+
2175+ await loadSingleLanguage(highlighter, candidate);
2176+ }),
2177+ );
2178+}
2179+
2180 function resolveLanguageAlias(language: string): string {
2181 const normalized = language.toLowerCase();
2182 return languageAliases[normalized] ?? normalized;
2183 }
2184
2185+function resolveLoadedLanguageFromPath(
2186+ path: string,
2187+ languageHint: string | null = null,
2188+): string | null {
2189+ const detectedLanguage = languageHint ?? getFiletypeFromFileName(path);
2190+ if (!detectedLanguage) {
2191+ return "text";
2192+ }
2193+
2194+ const candidate = resolveLanguageAlias(detectedLanguage);
2195+ if (candidate === "text" || candidate === "ansi") {
2196+ return "text";
2197+ }
2198+
2199+ if (!(candidate in languageImports)) {
2200+ return "text";
2201+ }
2202+
2203+ return loadedLanguages.has(candidate) ? candidate : null;
2204+}
2205+
2206 async function loadSingleLanguage(
2207 highlighter: HighlighterCore,
2208 language: string,
2209@@ -360,6 +427,11 @@ async function resolveLanguageFromPath(
2210 path: string,
2211 languageHint: string | null = null,
2212 ): Promise<string> {
2213+ const loadedLanguage = resolveLoadedLanguageFromPath(path, languageHint);
2214+ if (loadedLanguage) {
2215+ return loadedLanguage;
2216+ }
2217+
2218 const detectedLanguage = languageHint ?? getFiletypeFromFileName(path);
2219 if (!detectedLanguage) {
2220 return "text";
2221@@ -374,8 +446,12 @@ async function resolveLanguageFromPath(
2222 return "text";
2223 }
2224
2225+ if (loadedLanguages.has(candidate)) {
2226+ return candidate;
2227+ }
2228+
2229 const highlighter = await getHighlighter();
2230- const loaded = await loadSingleLanguage(highlighter, resolveLanguageAlias(candidate));
2231+ const loaded = await loadSingleLanguage(highlighter, candidate);
2232 if (!loaded) {
2233 return "text";
2234 }
2235@@ -384,7 +460,10 @@ async function resolveLanguageFromPath(
2236 }
2237
2238 async function resolveLanguage(file: ReviewRenderableFile): Promise<string> {
2239- return resolveLanguageFromPath(file.path, file.languageHint);
2240+ return (
2241+ resolveLoadedLanguageFromPath(file.path, file.languageHint) ??
2242+ (await resolveLanguageFromPath(file.path, file.languageHint))
2243+ );
2244 }
2245
2246 function normalizeHighlightedLines(
2247@@ -399,6 +478,18 @@ function normalizeHighlightedLines(
2248 );
2249 }
2250
2251+function makePlainHighlightedLines(
2252+ lines: ReadonlyArray<string>,
2253+): ReadonlyArray<ReadonlyArray<ReviewHighlightedToken>> {
2254+ return lines.map((line) => [
2255+ {
2256+ content: stripTrailingNewline(line),
2257+ color: null,
2258+ fontStyle: null,
2259+ },
2260+ ]);
2261+}
2262+
2263 function applyWordAltDiffHighlightsToFile(
2264 file: ReviewRenderableFile,
2265 highlighted: ReviewHighlightedFile,
2266@@ -594,6 +685,67 @@ async function highlightLines(
2267 return highlightedLines;
2268 }
2269
2270+async function highlightPatchLinesInChunks(input: {
2271+ readonly lines: ReadonlyArray<string>;
2272+ readonly language: string;
2273+ readonly theme: string;
2274+ readonly onChunk: (
2275+ startIndex: number,
2276+ tokens: ReadonlyArray<ReadonlyArray<ReviewHighlightedToken>>,
2277+ ) => void;
2278+}): Promise<ReadonlyArray<ReadonlyArray<ReviewHighlightedToken>>> {
2279+ if (input.lines.length === 0) {
2280+ return [];
2281+ }
2282+
2283+ const highlighter = await getHighlighter();
2284+ const highlightedLines: Array<ReadonlyArray<ReviewHighlightedToken>> = [];
2285+
2286+ for (
2287+ let startIndex = 0;
2288+ startIndex < input.lines.length;
2289+ startIndex += REVIEW_HIGHLIGHT_CHUNK_SIZE
2290+ ) {
2291+ const lineChunk = input.lines.slice(startIndex, startIndex + REVIEW_HIGHLIGHT_CHUNK_SIZE);
2292+ const chunkTokens: Array<ReadonlyArray<ReviewHighlightedToken>> = [];
2293+ const tokenizableLines: string[] = [];
2294+ const tokenizableIndexes: number[] = [];
2295+
2296+ lineChunk.forEach((line, index) => {
2297+ const strippedLine = stripTrailingNewline(line);
2298+ if (strippedLine.length > REVIEW_TOKENIZE_MAX_LINE_LENGTH) {
2299+ chunkTokens[index] = [{ content: strippedLine, color: null, fontStyle: null }];
2300+ return;
2301+ }
2302+
2303+ tokenizableIndexes.push(index);
2304+ tokenizableLines.push(strippedLine);
2305+ });
2306+
2307+ if (tokenizableLines.length > 0) {
2308+ const tokenLines = highlighter.codeToTokensBase(tokenizableLines.join("\n"), {
2309+ lang: input.language,
2310+ theme: input.theme,
2311+ });
2312+ const normalizedTokenLines = normalizeHighlightedLines(tokenLines);
2313+
2314+ tokenizableIndexes.forEach((chunkIndex, tokenIndex) => {
2315+ chunkTokens[chunkIndex] = normalizedTokenLines[tokenIndex] ?? [];
2316+ });
2317+ }
2318+
2319+ const completedChunk = lineChunk.map((_, index) => chunkTokens[index] ?? []);
2320+ highlightedLines.push(...completedChunk);
2321+ input.onChunk(startIndex, completedChunk);
2322+
2323+ if (startIndex + REVIEW_HIGHLIGHT_CHUNK_SIZE < input.lines.length) {
2324+ await waitForNextFrame();
2325+ }
2326+ }
2327+
2328+ return highlightedLines;
2329+}
2330+
2331 function getHighlightCacheKey(file: ReviewRenderableFile, theme: ReviewDiffTheme): string {
2332 return `${SHIKI_THEME_NAME_BY_SCHEME[theme]}:${file.cacheKey}`;
2333 }
2334@@ -667,7 +819,28 @@ export async function highlightReviewFile(
2335 deletionLineCount: file.deletionLines.length,
2336 rowCount: file.rows.length,
2337 });
2338- const language = await resolveLanguage(file);
2339+ const loadedLanguage = resolveLoadedLanguageFromPath(file.path, file.languageHint);
2340+ const language = loadedLanguage ?? (await resolveLanguage(file));
2341+ if (language === "text") {
2342+ const highlighted = applyWordAltDiffHighlightsToFile(file, {
2343+ additionLines: makePlainHighlightedLines(file.additionLines),
2344+ deletionLines: makePlainHighlightedLines(file.deletionLines),
2345+ });
2346+ if (!REVIEW_HIGHLIGHTER_DISABLE_RESULT_CACHE) {
2347+ storeResolvedHighlightedFile(cacheKey, highlighted);
2348+ }
2349+ logReviewHighlighterDiagnostic("file highlight complete", {
2350+ fileId: file.id,
2351+ filePath: file.path,
2352+ theme,
2353+ language,
2354+ highlightedAdditionLineCount: highlighted.additionLines.length,
2355+ highlightedDeletionLineCount: highlighted.deletionLines.length,
2356+ durationMs: Date.now() - startedAt,
2357+ });
2358+ return highlighted;
2359+ }
2360+
2361 const additionLines = await highlightLines(
2362 joinPatchLines(file.additionLines),
2363 language,
2364@@ -707,6 +880,113 @@ export async function highlightReviewFile(
2365 });
2366 }
2367
2368+export async function streamHighlightReviewFile(
2369+ file: ReviewRenderableFile,
2370+ theme: ReviewDiffTheme,
2371+ onProgress: (progress: ReviewHighlightFileProgress) => void,
2372+): Promise<ReviewHighlightedFile> {
2373+ const shikiTheme = SHIKI_THEME_NAME_BY_SCHEME[theme];
2374+ const cacheKey = getHighlightCacheKey(file, theme);
2375+ if (!REVIEW_HIGHLIGHTER_DISABLE_RESULT_CACHE) {
2376+ const resolved = resolvedHighlightCache.get(cacheKey);
2377+ if (resolved) {
2378+ onProgress({
2379+ highlightedFile: resolved,
2380+ complete: true,
2381+ highlightedLineCount: resolved.additionLines.length + resolved.deletionLines.length,
2382+ });
2383+ return resolved;
2384+ }
2385+ }
2386+
2387+ const startedAt = Date.now();
2388+ logReviewHighlighterDiagnostic("file stream highlight start", {
2389+ fileId: file.id,
2390+ filePath: file.path,
2391+ theme,
2392+ additionLineCount: file.additionLines.length,
2393+ deletionLineCount: file.deletionLines.length,
2394+ rowCount: file.rows.length,
2395+ });
2396+
2397+ const loadedLanguage = resolveLoadedLanguageFromPath(file.path, file.languageHint);
2398+ const language = loadedLanguage ?? (await resolveLanguage(file));
2399+ if (language === "text") {
2400+ const highlighted = applyWordAltDiffHighlightsToFile(file, {
2401+ additionLines: makePlainHighlightedLines(file.additionLines),
2402+ deletionLines: makePlainHighlightedLines(file.deletionLines),
2403+ });
2404+ if (!REVIEW_HIGHLIGHTER_DISABLE_RESULT_CACHE) {
2405+ storeResolvedHighlightedFile(cacheKey, highlighted);
2406+ }
2407+ onProgress({
2408+ highlightedFile: highlighted,
2409+ complete: true,
2410+ highlightedLineCount: highlighted.additionLines.length + highlighted.deletionLines.length,
2411+ });
2412+ logReviewHighlighterDiagnostic("file stream highlight complete", {
2413+ fileId: file.id,
2414+ filePath: file.path,
2415+ theme,
2416+ language,
2417+ highlightedAdditionLineCount: highlighted.additionLines.length,
2418+ highlightedDeletionLineCount: highlighted.deletionLines.length,
2419+ highlightedLineCount: highlighted.additionLines.length + highlighted.deletionLines.length,
2420+ durationMs: Date.now() - startedAt,
2421+ });
2422+ return highlighted;
2423+ }
2424+
2425+ const additionLines: Array<ReadonlyArray<ReviewHighlightedToken>> = [];
2426+ const deletionLines: Array<ReadonlyArray<ReviewHighlightedToken>> = [];
2427+ let highlightedLineCount = 0;
2428+
2429+ await highlightPatchLinesInChunks({
2430+ lines: file.additionLines,
2431+ language,
2432+ theme: shikiTheme,
2433+ onChunk: (startIndex, tokens) => {
2434+ tokens.forEach((lineTokens, index) => {
2435+ additionLines[startIndex + index] = lineTokens;
2436+ });
2437+ highlightedLineCount += tokens.length;
2438+ },
2439+ });
2440+ await waitForNextFrame();
2441+ await highlightPatchLinesInChunks({
2442+ lines: file.deletionLines,
2443+ language,
2444+ theme: shikiTheme,
2445+ onChunk: (startIndex, tokens) => {
2446+ tokens.forEach((lineTokens, index) => {
2447+ deletionLines[startIndex + index] = lineTokens;
2448+ });
2449+ highlightedLineCount += tokens.length;
2450+ },
2451+ });
2452+
2453+ const highlighted = applyWordAltDiffHighlightsToFile(file, { additionLines, deletionLines });
2454+ if (!REVIEW_HIGHLIGHTER_DISABLE_RESULT_CACHE) {
2455+ storeResolvedHighlightedFile(cacheKey, highlighted);
2456+ }
2457+ onProgress({
2458+ highlightedFile: highlighted,
2459+ complete: true,
2460+ highlightedLineCount,
2461+ });
2462+ logReviewHighlighterDiagnostic("file stream highlight complete", {
2463+ fileId: file.id,
2464+ filePath: file.path,
2465+ theme,
2466+ language,
2467+ highlightedAdditionLineCount: highlighted.additionLines.length,
2468+ highlightedDeletionLineCount: highlighted.deletionLines.length,
2469+ highlightedLineCount,
2470+ durationMs: Date.now() - startedAt,
2471+ });
2472+ return highlighted;
2473+}
2474+
2475 export async function highlightReviewSelectedLines(input: {
2476 readonly filePath: string;
2477 readonly lines: ReadonlyArray<ReviewRenderableLineRow>;
2478@@ -717,7 +997,9 @@ export async function highlightReviewSelectedLines(input: {
2479 return {};
2480 }
2481
2482- const language = await resolveLanguageFromPath(input.filePath, input.languageHint ?? null);
2483+ const loadedLanguage = resolveLoadedLanguageFromPath(input.filePath, input.languageHint ?? null);
2484+ const language =
2485+ loadedLanguage ?? (await resolveLanguageFromPath(input.filePath, input.languageHint ?? null));
2486 const shikiTheme = SHIKI_THEME_NAME_BY_SCHEME[input.theme];
2487 const additionLikeLines = input.lines
2488 .filter((line) => line.change !== "delete")
2489diff --git a/apps/mobile/docs/review-profiling.md b/apps/mobile/docs/review-profiling.md
2490new file mode 100644
2491index 000000000..6977eaf6e
2492--- /dev/null
2493+++ b/apps/mobile/docs/review-profiling.md
2494@@ -0,0 +1,80 @@
2495+# Review Screen Profiling
2496+
2497+Use this when the mobile review screen is slow or crashes while opening large diffs.
2498+
2499+## Preferred Capture: React Native DevTools Performance
2500+
2501+This app is on Expo SDK 55 / React Native 0.83 with Hermes, so the best first trace is the React Native DevTools Performance recording. The review screen also emits `t3.review.*` user timing marks in development builds so the trace can show parse, list-building, row indexing, and syntax-highlighting work.
2502+
2503+1. Start the development client:
2504+
2505+ ```sh
2506+ cd apps/mobile
2507+ bun dev:client
2508+ ```
2509+
2510+2. Open the app in the iOS Simulator or on the device using the development client.
2511+
2512+3. In the terminal running Expo, press `j` to open React Native DevTools.
2513+
2514+4. In DevTools, open the `Performance` panel.
2515+
2516+5. Start recording.
2517+
2518+6. In the app, reproduce the slow path:
2519+ - Navigate to the thread.
2520+ - Open `Files Changed`.
2521+ - Select the largest review source.
2522+ - Expand a few large files or tap `Load diff`.
2523+ - Scroll until the app is clearly slow or until just before it crashes.
2524+
2525+7. Stop recording.
2526+
2527+8. Export or save the Performance recording as a JSON trace.
2528+
2529+Send that exported trace file here. Also include the device/simulator model and whether it was iOS or Android.
2530+
2531+## Android Fallback: Hermes Sampling Profile
2532+
2533+Use this if the app crashes before DevTools can export a trace, or if we need deeper JavaScript stack samples.
2534+
2535+1. Run Android dev client:
2536+
2537+ ```sh
2538+ cd apps/mobile
2539+ bun android:dev
2540+ bun dev:client
2541+ ```
2542+
2543+2. Open the developer menu from the Expo terminal with `d`.
2544+
2545+3. Select `Enable Sampling Profiler`.
2546+
2547+4. Reproduce the review-screen slowdown.
2548+
2549+5. Open the developer menu again with `d`.
2550+
2551+6. Select `Disable Sampling Profiler`.
2552+
2553+7. Pull and convert the Hermes profile:
2554+
2555+ ```sh
2556+ cd apps/mobile
2557+ mkdir -p profiles/review
2558+ bunx react-native profile-hermes profiles/review
2559+ ```
2560+
2561+8. Send the generated Chrome trace/profile file from `apps/mobile/profiles/review`.
2562+
2563+For the development app variant, the Android package is `com.t3tools.t3code.dev`.
2564+
2565+## What To Capture
2566+
2567+For the first trace, do not optimize the repro. We want the slowest realistic case:
2568+
2569+- A diff with many files and large line counts.
2570+- At least one `Load diff` action for a suppressed large diff.
2571+- One vertical scroll pass after the content appears.
2572+- One horizontal scroll of a long file, if that is part of the slowdown.
2573+
2574+If the app crashes, note the last visible action before the crash and attach device logs if available.
2575diff --git a/apps/mobile/src/app/debug/syntax-highlight.tsx b/apps/mobile/src/app/debug/syntax-highlight.tsx
2576new file mode 100644
2577index 000000000..c2a36d126
2578--- /dev/null
2579+++ b/apps/mobile/src/app/debug/syntax-highlight.tsx
2580@@ -0,0 +1,423 @@
2581+import { createHighlighterCore, type HighlighterCore } from "@shikijs/core";
2582+import { createJavaScriptRegexEngine } from "@shikijs/engine-javascript";
2583+import typescriptLanguage from "@shikijs/langs/typescript";
2584+import githubDarkDefault from "@shikijs/themes/github-dark-default";
2585+import githubLightDefault from "@shikijs/themes/github-light-default";
2586+import Stack from "expo-router/stack";
2587+import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";
2588+import {
2589+ FlatList,
2590+ Pressable,
2591+ Text as NativeText,
2592+ type ListRenderItemInfo,
2593+ useColorScheme,
2594+ useWindowDimensions,
2595+ View,
2596+} from "react-native";
2597+import { useSafeAreaInsets } from "react-native-safe-area-context";
2598+
2599+import { AppText as Text } from "../../components/AppText";
2600+import { cn } from "../../lib/cn";
2601+import { useThemeColor } from "../../lib/useThemeColor";
2602+
2603+type DebugHighlightEngine = "native" | "javascript";
2604+
2605+type DebugToken = {
2606+ readonly content: string;
2607+ readonly color: string | null;
2608+ readonly fontStyle: number | null;
2609+};
2610+
2611+type DebugLine = {
2612+ readonly id: string;
2613+ readonly chunkIndex: number;
2614+ readonly indexInChunk: number;
2615+ readonly lineNumber: number;
2616+ readonly content: string;
2617+};
2618+
2619+type DebugHighlighterHandle = {
2620+ readonly engine: DebugHighlightEngine;
2621+ readonly tokenize: (
2622+ code: string,
2623+ options: { readonly lang: string; readonly theme: string },
2624+ ) => ReadonlyArray<ReadonlyArray<DebugToken>>;
2625+};
2626+
2627+const DEBUG_LINE_COUNT = 10_000;
2628+const DEBUG_CHUNK_SIZE = 500;
2629+const DEBUG_LINE_HEIGHT = 24;
2630+const DEBUG_GUTTER_WIDTH = 58;
2631+const DEBUG_CONTENT_WIDTH = 3_200;
2632+const DEBUG_MONO_FONT_FAMILY = "BerkeleyMono-Regular";
2633+const DEBUG_THEME_NAME_BY_SCHEME = {
2634+ dark: "github-dark-default",
2635+ light: "github-light-default",
2636+} as const;
2637+
2638+let nativeHighlighterPromise: Promise<DebugHighlighterHandle> | null = null;
2639+let javascriptHighlighterPromise: Promise<DebugHighlighterHandle> | null = null;
2640+
2641+function waitForNextFrame(): Promise<void> {
2642+ return new Promise((resolve) => setTimeout(resolve, 0));
2643+}
2644+
2645+function normalizeTokens(
2646+ tokenLines: ReadonlyArray<ReadonlyArray<{ content: string; color?: string; fontStyle?: number }>>,
2647+): ReadonlyArray<ReadonlyArray<DebugToken>> {
2648+ return tokenLines.map((line) =>
2649+ line.map((token) => ({
2650+ content: token.content,
2651+ color: token.color ?? null,
2652+ fontStyle: token.fontStyle ?? null,
2653+ })),
2654+ );
2655+}
2656+
2657+function makeDebugCodeLine(index: number): string {
2658+ const label = `generatedLine${String(index).padStart(5, "0")}`;
2659+ switch (index % 8) {
2660+ case 0:
2661+ return `export async function ${label}(input: { value: number; name: string }) {`;
2662+ case 1:
2663+ return ` const normalized = input.name.trim().toLowerCase();`;
2664+ case 2:
2665+ return ` const result = await Promise.resolve({ id: "${label}", score: input.value * ${index + 1} });`;
2666+ case 3:
2667+ return ` if (result.score > ${index * 17}) return normalized + ":" + result.id;`;
2668+ case 4:
2669+ return ` return [normalized, String(result.score), "${"x".repeat((index % 24) + 8)}"].join("/");`;
2670+ case 5:
2671+ return `}`;
2672+ case 6:
2673+ return `type ${label}Record = Readonly<{ id: string; createdAt: Date; tags: string[] }>;`;
2674+ default:
2675+ return `const ${label}: ${label}Record = { id: "${label}", createdAt: new Date(), tags: ["debug", "highlight"] };`;
2676+ }
2677+}
2678+
2679+function makeDebugLines(): ReadonlyArray<DebugLine> {
2680+ return Array.from({ length: DEBUG_LINE_COUNT }, (_, index) => ({
2681+ id: `line:${index + 1}`,
2682+ chunkIndex: Math.floor(index / DEBUG_CHUNK_SIZE),
2683+ indexInChunk: index % DEBUG_CHUNK_SIZE,
2684+ lineNumber: index + 1,
2685+ content: makeDebugCodeLine(index + 1),
2686+ }));
2687+}
2688+
2689+async function createNativeDebugHighlighter(): Promise<DebugHighlighterHandle> {
2690+ const nativeEngineModule = await import("react-native-shiki-engine");
2691+ if (!nativeEngineModule.isNativeEngineAvailable()) {
2692+ throw new Error("Native Shiki engine is not available in this build.");
2693+ }
2694+
2695+ const highlighter = await createHighlighterCore({
2696+ langs: [typescriptLanguage],
2697+ themes: [githubLightDefault, githubDarkDefault],
2698+ engine: nativeEngineModule.createNativeEngine(),
2699+ });
2700+
2701+ return {
2702+ engine: "native",
2703+ tokenize: (code, options) => normalizeTokens(highlighter.codeToTokensBase(code, options)),
2704+ };
2705+}
2706+
2707+async function createJavascriptDebugHighlighter(): Promise<DebugHighlighterHandle> {
2708+ const highlighter: HighlighterCore = await createHighlighterCore({
2709+ langs: [typescriptLanguage],
2710+ themes: [githubLightDefault, githubDarkDefault],
2711+ engine: createJavaScriptRegexEngine(),
2712+ });
2713+
2714+ return {
2715+ engine: "javascript",
2716+ tokenize: (code, options) => normalizeTokens(highlighter.codeToTokensBase(code, options)),
2717+ };
2718+}
2719+
2720+async function getDebugHighlighter(engine: DebugHighlightEngine): Promise<DebugHighlighterHandle> {
2721+ if (engine === "native") {
2722+ nativeHighlighterPromise ??= createNativeDebugHighlighter();
2723+ return nativeHighlighterPromise;
2724+ }
2725+
2726+ javascriptHighlighterPromise ??= createJavascriptDebugHighlighter();
2727+ return javascriptHighlighterPromise;
2728+}
2729+
2730+const TokenText = memo(function TokenText(props: {
2731+ readonly content: string;
2732+ readonly tokens: ReadonlyArray<DebugToken> | null;
2733+}) {
2734+ if (!props.tokens) {
2735+ return (
2736+ <NativeText
2737+ numberOfLines={1}
2738+ className="text-[13px] font-medium leading-[18px] text-foreground"
2739+ style={{ fontFamily: DEBUG_MONO_FONT_FAMILY }}
2740+ >
2741+ {props.content}
2742+ </NativeText>
2743+ );
2744+ }
2745+
2746+ let tokenOffset = 0;
2747+
2748+ return (
2749+ <NativeText
2750+ numberOfLines={1}
2751+ className="text-[13px] font-medium leading-[18px] text-foreground"
2752+ style={{ fontFamily: DEBUG_MONO_FONT_FAMILY }}
2753+ >
2754+ {props.tokens.map((token) => {
2755+ const tokenKey = `${tokenOffset}:${token.content.length}:${token.color ?? ""}:${token.fontStyle ?? ""}`;
2756+ tokenOffset += token.content.length;
2757+ const fontWeight =
2758+ token.fontStyle !== null && (token.fontStyle & 2) === 2
2759+ ? ("700" as const)
2760+ : ("500" as const);
2761+ const fontStyle =
2762+ token.fontStyle !== null && (token.fontStyle & 1) === 1
2763+ ? ("italic" as const)
2764+ : ("normal" as const);
2765+
2766+ return (
2767+ <NativeText
2768+ key={tokenKey}
2769+ style={{
2770+ color: token.color ?? undefined,
2771+ fontFamily: DEBUG_MONO_FONT_FAMILY,
2772+ fontStyle,
2773+ fontWeight,
2774+ }}
2775+ >
2776+ {token.content}
2777+ </NativeText>
2778+ );
2779+ })}
2780+ </NativeText>
2781+ );
2782+});
2783+
2784+const DebugCodeLineRow = memo(function DebugCodeLineRow(props: {
2785+ readonly item: DebugLine;
2786+ readonly tokens: ReadonlyArray<DebugToken> | null;
2787+ readonly width: number;
2788+}) {
2789+ return (
2790+ <View className="flex-row bg-card" style={{ height: DEBUG_LINE_HEIGHT, width: props.width }}>
2791+ <View className="items-end justify-center pr-2" style={{ width: DEBUG_GUTTER_WIDTH }}>
2792+ <Text className="font-mono text-[11px] text-foreground-muted">{props.item.lineNumber}</Text>
2793+ </View>
2794+ <View className="justify-center px-2" style={{ width: DEBUG_CONTENT_WIDTH }}>
2795+ <TokenText content={props.item.content} tokens={props.tokens} />
2796+ </View>
2797+ </View>
2798+ );
2799+});
2800+
2801+function EngineToggle(props: {
2802+ readonly engine: DebugHighlightEngine;
2803+ readonly onChangeEngine: (engine: DebugHighlightEngine) => void;
2804+}) {
2805+ return (
2806+ <View className="flex-row rounded-full bg-subtle p-1">
2807+ {(["native", "javascript"] as const).map((engine) => {
2808+ const selected = props.engine === engine;
2809+ return (
2810+ <Pressable
2811+ key={engine}
2812+ className={cn("rounded-full px-3 py-1.5", selected && "bg-card")}
2813+ onPress={() => props.onChangeEngine(engine)}
2814+ >
2815+ <Text
2816+ className={cn(
2817+ "text-[12px] font-t3-bold",
2818+ selected ? "text-foreground" : "text-foreground-muted",
2819+ )}
2820+ >
2821+ {engine === "javascript" ? "JS" : "Native"}
2822+ </Text>
2823+ </Pressable>
2824+ );
2825+ })}
2826+ </View>
2827+ );
2828+}
2829+
2830+export default function SyntaxHighlightDebugRoute() {
2831+ const insets = useSafeAreaInsets();
2832+ const { width } = useWindowDimensions();
2833+ const colorScheme = useColorScheme();
2834+ const headerIcon = String(useThemeColor("--color-icon"));
2835+ const themeName = DEBUG_THEME_NAME_BY_SCHEME[colorScheme === "dark" ? "dark" : "light"];
2836+ const [engine, setEngine] = useState<DebugHighlightEngine>("native");
2837+ const [tokensByChunkIndex, setTokensByChunkIndex] = useState<
2838+ Record<number, ReadonlyArray<ReadonlyArray<DebugToken>>>
2839+ >({});
2840+ const [status, setStatus] = useState("Idle");
2841+ const renderStartRef = useRef<number | null>(null);
2842+ const generationRef = useRef(0);
2843+ const lines = useMemo(() => makeDebugLines(), []);
2844+
2845+ useEffect(() => {
2846+ const generation = generationRef.current + 1;
2847+ generationRef.current = generation;
2848+ renderStartRef.current = performance.now();
2849+ setTokensByChunkIndex({});
2850+ setStatus("Initializing highlighter");
2851+
2852+ void (async () => {
2853+ try {
2854+ const highlighterStartedAt = performance.now();
2855+ const highlighter = await getDebugHighlighter(engine);
2856+ if (generation !== generationRef.current) {
2857+ return;
2858+ }
2859+
2860+ console.log("[debug-syntax-scratch] initialize", {
2861+ durationMs: Math.round(performance.now() - highlighterStartedAt),
2862+ engine: highlighter.engine,
2863+ });
2864+
2865+ let firstChunkMs: number | null = null;
2866+ const totalStartedAt = performance.now();
2867+ setStatus(`Streaming ${DEBUG_LINE_COUNT.toLocaleString()} lines`);
2868+
2869+ for (let startIndex = 0; startIndex < lines.length; startIndex += DEBUG_CHUNK_SIZE) {
2870+ if (generation !== generationRef.current) {
2871+ return;
2872+ }
2873+
2874+ const chunkLines = lines.slice(startIndex, startIndex + DEBUG_CHUNK_SIZE);
2875+ const chunkCode = chunkLines.map((line) => line.content).join("\n");
2876+ const chunkStartedAt = performance.now();
2877+ const chunkTokens = highlighter.tokenize(chunkCode, {
2878+ lang: "typescript",
2879+ theme: themeName,
2880+ });
2881+ const chunkMs = performance.now() - chunkStartedAt;
2882+
2883+ if (firstChunkMs === null) {
2884+ firstChunkMs = performance.now() - totalStartedAt;
2885+ console.log("[debug-syntax-scratch] first chunk", {
2886+ chunkSize: DEBUG_CHUNK_SIZE,
2887+ durationMs: Math.round(firstChunkMs),
2888+ engine,
2889+ lineCount: chunkTokens.length,
2890+ });
2891+ }
2892+
2893+ setTokensByChunkIndex((current) => ({
2894+ ...current,
2895+ [startIndex / DEBUG_CHUNK_SIZE]: chunkTokens,
2896+ }));
2897+ setStatus(
2898+ `Streamed ${Math.min(startIndex + DEBUG_CHUNK_SIZE, lines.length).toLocaleString()} / ${lines.length.toLocaleString()} lines`,
2899+ );
2900+
2901+ console.log("[debug-syntax-scratch] chunk", {
2902+ chunkIndex: startIndex / DEBUG_CHUNK_SIZE,
2903+ chunkMs: Math.round(chunkMs),
2904+ engine,
2905+ lineCount: chunkTokens.length,
2906+ });
2907+
2908+ await waitForNextFrame();
2909+ }
2910+
2911+ console.log("[debug-syntax-scratch] complete", {
2912+ durationMs: Math.round(performance.now() - totalStartedAt),
2913+ engine,
2914+ lineCount: lines.length,
2915+ });
2916+ setStatus(`Complete with ${engine}`);
2917+ } catch (error) {
2918+ console.error("[debug-syntax-scratch] failed", {
2919+ engine,
2920+ message: error instanceof Error ? error.message : String(error),
2921+ });
2922+ setStatus(error instanceof Error ? error.message : "Highlight failed");
2923+ }
2924+ })();
2925+ }, [engine, lines, themeName]);
2926+
2927+ useEffect(() => {
2928+ if (renderStartRef.current === null) {
2929+ return;
2930+ }
2931+
2932+ const startedAt = renderStartRef.current;
2933+ renderStartRef.current = null;
2934+ const commitMs = performance.now() - startedAt;
2935+ requestAnimationFrame(() => {
2936+ console.log("[debug-syntax-scratch] render", {
2937+ commitMs: Math.round(commitMs),
2938+ paintMs: Math.round(performance.now() - startedAt),
2939+ });
2940+ });
2941+ });
2942+
2943+ const renderItem = useCallback(
2944+ ({ item }: ListRenderItemInfo<DebugLine>) => (
2945+ <DebugCodeLineRow
2946+ item={item}
2947+ tokens={tokensByChunkIndex[item.chunkIndex]?.[item.indexInChunk] ?? null}
2948+ width={width}
2949+ />
2950+ ),
2951+ [tokensByChunkIndex, width],
2952+ );
2953+
2954+ return (
2955+ <View className="flex-1 bg-sheet">
2956+ <Stack.Screen
2957+ options={{
2958+ headerShown: true,
2959+ headerTitle: "Syntax Scratch",
2960+ headerTintColor: headerIcon,
2961+ headerTransparent: true,
2962+ headerShadowVisible: false,
2963+ }}
2964+ />
2965+
2966+ <View
2967+ className="border-b border-border bg-sheet px-3 pb-3"
2968+ style={{ paddingTop: insets.top + 56 }}
2969+ >
2970+ <View className="flex-row items-center justify-between gap-3">
2971+ <View className="min-w-0 flex-1">
2972+ <Text className="text-[13px] font-t3-bold text-foreground">
2973+ Shiki streaming baseline
2974+ </Text>
2975+ <Text className="text-[11px] text-foreground-muted" numberOfLines={1}>
2976+ {status}
2977+ </Text>
2978+ </View>
2979+ <EngineToggle engine={engine} onChangeEngine={setEngine} />
2980+ </View>
2981+ </View>
2982+
2983+ <FlatList
2984+ style={{ flex: 1, width }}
2985+ data={lines}
2986+ renderItem={renderItem}
2987+ keyExtractor={(item) => item.id}
2988+ getItemLayout={(_, index) => ({
2989+ length: DEBUG_LINE_HEIGHT,
2990+ offset: DEBUG_LINE_HEIGHT * index,
2991+ index,
2992+ })}
2993+ initialNumToRender={40}
2994+ maxToRenderPerBatch={80}
2995+ updateCellsBatchingPeriod={16}
2996+ windowSize={9}
2997+ removeClippedSubviews
2998+ keyboardShouldPersistTaps="handled"
2999+ contentContainerStyle={{ paddingBottom: Math.max(insets.bottom, 18) + 18 }}
3000+ />
3001+ </View>
3002+ );
3003+}
3004diff --git a/apps/mobile/src/features/review/ReviewHighlighterProvider.tsx b/apps/mobile/src/features/review/ReviewHighlighterProvider.tsx
3005new file mode 100644
3006index 000000000..095201929
3007--- /dev/null
3008+++ b/apps/mobile/src/features/review/ReviewHighlighterProvider.tsx
3009@@ -0,0 +1,110 @@
3010+import { createContext, type ReactNode, useContext, useEffect, useMemo, useState } from "react";
3011+
3012+import {
3013+ getActiveReviewHighlighterEngine,
3014+ prepareReviewHighlighter,
3015+ prepareReviewHighlighterLanguages,
3016+ type ReviewHighlighterEngine,
3017+} from "./shikiReviewHighlighter";
3018+
3019+type ReviewHighlighterStatus = "idle" | "initializing" | "ready" | "error";
3020+
3021+interface ReviewHighlighterContextValue {
3022+ readonly engine: ReviewHighlighterEngine | null;
3023+ readonly error: string | null;
3024+ readonly status: ReviewHighlighterStatus;
3025+}
3026+
3027+const ReviewHighlighterContext = createContext<ReviewHighlighterContextValue>({
3028+ engine: null,
3029+ error: null,
3030+ status: "idle",
3031+});
3032+
3033+const REVIEW_INITIAL_LANGUAGES = [
3034+ "typescript",
3035+ "tsx",
3036+ "javascript",
3037+ "jsx",
3038+ "json",
3039+ "yaml",
3040+ "bash",
3041+] as const;
3042+
3043+function isReviewHighlighterProviderDebugLoggingEnabled(): boolean {
3044+ return typeof __DEV__ !== "undefined" ? __DEV__ : false;
3045+}
3046+
3047+function logReviewHighlighterProviderDiagnostic(
3048+ message: string,
3049+ details?: Record<string, unknown>,
3050+): void {
3051+ if (!isReviewHighlighterProviderDebugLoggingEnabled()) {
3052+ return;
3053+ }
3054+
3055+ if (details) {
3056+ console.log(`[review-highlighter-provider] ${message}`, details);
3057+ return;
3058+ }
3059+
3060+ console.log(`[review-highlighter-provider] ${message}`);
3061+}
3062+
3063+export function ReviewHighlighterProvider(props: { readonly children: ReactNode }) {
3064+ const [value, setValue] = useState<ReviewHighlighterContextValue>({
3065+ engine: null,
3066+ error: null,
3067+ status: "idle",
3068+ });
3069+
3070+ useEffect(() => {
3071+ let cancelled = false;
3072+
3073+ setValue({ engine: null, error: null, status: "initializing" });
3074+
3075+ void (async () => {
3076+ const startedAt = performance.now();
3077+ try {
3078+ await prepareReviewHighlighter();
3079+ await prepareReviewHighlighterLanguages(REVIEW_INITIAL_LANGUAGES);
3080+ const engine = await getActiveReviewHighlighterEngine();
3081+
3082+ if (cancelled) {
3083+ return;
3084+ }
3085+
3086+ const durationMs = Math.round(performance.now() - startedAt);
3087+ logReviewHighlighterProviderDiagnostic("initialized", {
3088+ durationMs,
3089+ engine,
3090+ });
3091+ setValue({ engine, error: null, status: "ready" });
3092+ } catch (error) {
3093+ if (cancelled) {
3094+ return;
3095+ }
3096+
3097+ const message = error instanceof Error ? error.message : String(error);
3098+ logReviewHighlighterProviderDiagnostic("initialization failed", { error: message });
3099+ setValue({ engine: null, error: message, status: "error" });
3100+ }
3101+ })();
3102+
3103+ return () => {
3104+ cancelled = true;
3105+ };
3106+ }, []);
3107+
3108+ const contextValue = useMemo(() => value, [value]);
3109+
3110+ return (
3111+ <ReviewHighlighterContext.Provider value={contextValue}>
3112+ {props.children}
3113+ </ReviewHighlighterContext.Provider>
3114+ );
3115+}
3116+
3117+export function useReviewHighlighterStatus(): ReviewHighlighterContextValue {
3118+ return useContext(ReviewHighlighterContext);
3119+}
3120diff --git a/apps/mobile/src/features/review/reviewPerf.ts b/apps/mobile/src/features/review/reviewPerf.ts
3121new file mode 100644
3122index 000000000..2ae1095b1
3123--- /dev/null
3124+++ b/apps/mobile/src/features/review/reviewPerf.ts
3125@@ -0,0 +1,83 @@
3126+interface ReviewPerformanceLike {
3127+ readonly now?: () => number;
3128+ readonly mark?: (name: string) => void;
3129+ readonly measure?: (name: string, startMark: string, endMark: string) => void;
3130+ readonly clearMarks?: (name?: string) => void;
3131+ readonly clearMeasures?: (name?: string) => void;
3132+}
3133+
3134+const REVIEW_PERF_PREFIX = "t3.review";
3135+let reviewPerfSequence = 0;
3136+
3137+function getPerformance(): ReviewPerformanceLike | null {
3138+ const candidate = (globalThis as { readonly performance?: ReviewPerformanceLike }).performance;
3139+ return candidate ?? null;
3140+}
3141+
3142+export function isReviewPerfEnabled(): boolean {
3143+ return typeof __DEV__ !== "undefined" ? __DEV__ : false;
3144+}
3145+
3146+export function measureReviewWork<T>(name: string, callback: () => T): T {
3147+ if (!isReviewPerfEnabled()) {
3148+ return callback();
3149+ }
3150+
3151+ const perf = getPerformance();
3152+ const marker = `${REVIEW_PERF_PREFIX}.${name}.${reviewPerfSequence++}`;
3153+ const startMark = `${marker}.start`;
3154+ const endMark = `${marker}.end`;
3155+ const startedAt = perf?.now?.() ?? Date.now();
3156+
3157+ perf?.mark?.(startMark);
3158+ try {
3159+ return callback();
3160+ } finally {
3161+ const durationMs = (perf?.now?.() ?? Date.now()) - startedAt;
3162+ perf?.mark?.(endMark);
3163+ perf?.measure?.(`${REVIEW_PERF_PREFIX}.${name}`, startMark, endMark);
3164+ perf?.clearMarks?.(startMark);
3165+ perf?.clearMarks?.(endMark);
3166+ console.log(`[review-perf] ${name}`, { durationMs: Number(durationMs.toFixed(2)) });
3167+ }
3168+}
3169+
3170+export async function measureReviewAsyncWork<T>(
3171+ name: string,
3172+ callback: () => Promise<T>,
3173+): Promise<T> {
3174+ if (!isReviewPerfEnabled()) {
3175+ return callback();
3176+ }
3177+
3178+ const perf = getPerformance();
3179+ const marker = `${REVIEW_PERF_PREFIX}.${name}.${reviewPerfSequence++}`;
3180+ const startMark = `${marker}.start`;
3181+ const endMark = `${marker}.end`;
3182+ const startedAt = perf?.now?.() ?? Date.now();
3183+
3184+ perf?.mark?.(startMark);
3185+ try {
3186+ return await callback();
3187+ } finally {
3188+ const durationMs = (perf?.now?.() ?? Date.now()) - startedAt;
3189+ perf?.mark?.(endMark);
3190+ perf?.measure?.(`${REVIEW_PERF_PREFIX}.${name}`, startMark, endMark);
3191+ perf?.clearMarks?.(startMark);
3192+ perf?.clearMarks?.(endMark);
3193+ console.log(`[review-perf] ${name}`, { durationMs: Number(durationMs.toFixed(2)) });
3194+ }
3195+}
3196+
3197+export function markReviewEvent(name: string, details?: Record<string, unknown>): void {
3198+ if (!isReviewPerfEnabled()) {
3199+ return;
3200+ }
3201+
3202+ getPerformance()?.mark?.(`${REVIEW_PERF_PREFIX}.${name}`);
3203+ if (details) {
3204+ console.log(`[review-perf] ${name}`, details);
3205+ return;
3206+ }
3207+ console.log(`[review-perf] ${name}`);
3208+}
apps/mobile/src/features/debug/fixtures/review-large.diff+0−3208
@@ -1,3208 +0,0 @@
1diff --git a/apps/mobile/package.json b/apps/mobile/package.json
2index 08329e1d4..36ac93a0f 100644
3--- a/apps/mobile/package.json
4+++ b/apps/mobile/package.json
5@@ -30,6 +30,7 @@
6 "config:dev": "APP_VARIANT=development expo config",
7 "config:preview": "APP_VARIANT=preview expo config",
8 "config:prod": "APP_VARIANT=production expo config",
9+ "profile:android:hermes": "mkdir -p profiles/review && react-native profile-hermes profiles/review",
10 "test": "vitest run",
11 "typecheck": "tsc --noEmit"
12 },
13diff --git a/apps/mobile/src/app/index.tsx b/apps/mobile/src/app/index.tsx
14index f153db701..f6095c051 100644
15--- a/apps/mobile/src/app/index.tsx
16+++ b/apps/mobile/src/app/index.tsx
17@@ -43,28 +43,50 @@ export default function HomeRouteScreen() {
18 headerTintColor: iconColor,
19 headerTitle: "",
20 headerRight: () => (
21- <Pressable
22- onPress={() => router.push("/connections")}
23- hitSlop={8}
24- style={{
25- flexDirection: "row",
26- alignItems: "center",
27- gap: 8,
28- paddingHorizontal: 4,
29- paddingVertical: 4,
30- }}
31- >
32- <ConnectionStatusDot state={connectionState} pulse={hasRemoteActivity} size={7} />
33- <RNText
34+ <View style={{ flexDirection: "row", alignItems: "center", gap: 12 }}>
35+ <Pressable
36+ onPress={() => router.push("/debug/syntax-highlight")}
37+ hitSlop={8}
38 style={{
39- fontFamily: "DMSans_700Bold",
40- fontSize: 12,
41- color: secondaryFg,
42+ borderRadius: 999,
43+ backgroundColor: isDark ? "rgba(255,255,255,0.06)" : "rgba(0,0,0,0.06)",
44+ paddingHorizontal: 10,
45+ paddingVertical: 5,
46 }}
47 >
48- {CONNECTION_LABEL[connectionState]}
49- </RNText>
50- </Pressable>
51+ <RNText
52+ style={{
53+ fontFamily: "DMSans_700Bold",
54+ fontSize: 12,
55+ color: secondaryFg,
56+ }}
57+ >
58+ Debug
59+ </RNText>
60+ </Pressable>
61+ <Pressable
62+ onPress={() => router.push("/connections")}
63+ hitSlop={8}
64+ style={{
65+ flexDirection: "row",
66+ alignItems: "center",
67+ gap: 8,
68+ paddingHorizontal: 4,
69+ paddingVertical: 4,
70+ }}
71+ >
72+ <ConnectionStatusDot state={connectionState} pulse={hasRemoteActivity} size={7} />
73+ <RNText
74+ style={{
75+ fontFamily: "DMSans_700Bold",
76+ fontSize: 12,
77+ color: secondaryFg,
78+ }}
79+ >
80+ {CONNECTION_LABEL[connectionState]}
81+ </RNText>
82+ </Pressable>
83+ </View>
84 ),
85 headerSearchBarOptions: {
86 placeholder: "Search threads",
87diff --git a/apps/mobile/src/app/threads/[environmentId]/[threadId]/review.tsx b/apps/mobile/src/app/threads/[environmentId]/[threadId]/review.tsx
88index 84c48c6ed..ee993ee7c 100644
89--- a/apps/mobile/src/app/threads/[environmentId]/[threadId]/review.tsx
90+++ b/apps/mobile/src/app/threads/[environmentId]/[threadId]/review.tsx
91@@ -1,5 +1,10 @@
92+import { ReviewHighlighterProvider } from "../../../../features/review/ReviewHighlighterProvider";
93 import { ReviewSheet } from "../../../../features/review/ReviewSheet";
94
95 export default function ReviewRoute() {
96- return <ReviewSheet />;
97+ return (
98+ <ReviewHighlighterProvider>
99+ <ReviewSheet />
100+ </ReviewHighlighterProvider>
101+ );
102 }
103diff --git a/apps/mobile/src/features/review/ReviewCommentComposerSheet.tsx b/apps/mobile/src/features/review/ReviewCommentComposerSheet.tsx
104index 076a2286d..9a173224a 100644
105--- a/apps/mobile/src/features/review/ReviewCommentComposerSheet.tsx
106+++ b/apps/mobile/src/features/review/ReviewCommentComposerSheet.tsx
107@@ -2,15 +2,8 @@ import { useLocalSearchParams, useRouter } from "expo-router";
108 import { SymbolView } from "expo-symbols";
109 import { TextInputWrapper } from "expo-paste-input";
110 import { useEffect, useMemo, useState } from "react";
111-import {
112- KeyboardAvoidingView,
113- Platform,
114- Pressable,
115- ScrollView,
116- View,
117- useColorScheme,
118- useWindowDimensions,
119-} from "react-native";
120+import { Pressable, ScrollView, View, useColorScheme, useWindowDimensions } from "react-native";
121+import { KeyboardStickyView } from "react-native-keyboard-controller";
122 import { useSafeAreaInsets } from "react-native-safe-area-context";
123 import ImageViewing from "react-native-image-viewing";
124
125@@ -34,6 +27,7 @@ import {
126 import {
127 changeTone,
128 DiffTokenText,
129+ REVIEW_DIFF_LINE_HEIGHT,
130 REVIEW_MONO_FONT_FAMILY,
131 ReviewChangeBar,
132 } from "./reviewDiffRendering";
133@@ -44,7 +38,6 @@ import {
134 } from "./shikiReviewHighlighter";
135
136 const REVIEW_COMMENT_PREVIEW_MAX_LINES = 5;
137-const REVIEW_COMMENT_LINE_HEIGHT = 26;
138
139 export function ReviewCommentComposerSheet() {
140 const router = useRouter();
141@@ -84,8 +77,8 @@ export function ReviewCommentComposerSheet() {
142 ? `Lines ${firstNumber}-${lastNumber}`
143 : `${selectedLines.length} lines selected`;
144 const previewHeight = Math.max(
145- Math.min(selectedLines.length, REVIEW_COMMENT_PREVIEW_MAX_LINES) * REVIEW_COMMENT_LINE_HEIGHT,
146- REVIEW_COMMENT_LINE_HEIGHT,
147+ Math.min(selectedLines.length, REVIEW_COMMENT_PREVIEW_MAX_LINES) * REVIEW_DIFF_LINE_HEIGHT,
148+ REVIEW_DIFF_LINE_HEIGHT,
149 );
150 const previewViewportWidth = Math.max(width - 40, 280);
151 const handleNativePaste = useNativePaste((uris) => {
152@@ -143,17 +136,13 @@ export function ReviewCommentComposerSheet() {
153 }
154
155 return (
156- <KeyboardAvoidingView
157- behavior={Platform.OS === "ios" ? "padding" : "height"}
158- keyboardVerticalOffset={Platform.OS === "ios" ? 12 : 0}
159- style={{ flex: 1 }}
160- >
161+ <View style={{ flex: 1 }}>
162 <View
163 style={{
164 flex: 1,
165 paddingHorizontal: 20,
166 paddingTop: 8,
167- paddingBottom: Math.max(insets.bottom, 18) + 18,
168+ paddingBottom: Math.max(insets.bottom, 18) + 82,
169 }}
170 >
171 <View className="flex-row items-center justify-between py-2">
172@@ -219,7 +208,7 @@ export function ReviewCommentComposerSheet() {
173 <View
174 key={line.id}
175 className={cn("flex-row items-start", changeTone(line.change))}
176- style={{ height: REVIEW_COMMENT_LINE_HEIGHT }}
177+ style={{ height: REVIEW_DIFF_LINE_HEIGHT }}
178 >
179 <ReviewChangeBar change={line.change} />
180 <Text
181@@ -280,35 +269,41 @@ export function ReviewCommentComposerSheet() {
182 ) : null}
183 </View>
184 </View>
185-
186- <View className="flex-row items-center gap-3 pt-1">
187- <ControlPill icon="plus" onPress={() => void handlePickImages()} />
188- <View className="flex-1" />
189- <ControlPill
190- icon="arrow.up"
191- label="Comment"
192- variant="primary"
193- disabled={!canSubmit}
194- onPress={() => {
195- if (!target || !environmentId || !threadId || commentText.trim().length === 0) {
196- return;
197- }
198-
199- appendReviewCommentToDraft({
200- environmentId,
201- threadId,
202- text: formatReviewCommentContext(target, commentText),
203- attachments,
204- });
205- setAttachments([]);
206- clearReviewCommentTarget();
207- router.dismiss();
208- }}
209- />
210- </View>
211 </View>
212 )}
213 </View>
214+ {target ? (
215+ <KeyboardStickyView style={{ position: "absolute", bottom: 0, left: 0, right: 0 }}>
216+ <View
217+ className="flex-row items-center gap-3 bg-sheet px-5 pt-3"
218+ style={{ paddingBottom: Math.max(insets.bottom, 18) }}
219+ >
220+ <ControlPill icon="plus" onPress={() => void handlePickImages()} />
221+ <View className="flex-1" />
222+ <ControlPill
223+ icon="arrow.up"
224+ label="Comment"
225+ variant="primary"
226+ disabled={!canSubmit}
227+ onPress={() => {
228+ if (!target || !environmentId || !threadId || commentText.trim().length === 0) {
229+ return;
230+ }
231+
232+ appendReviewCommentToDraft({
233+ environmentId,
234+ threadId,
235+ text: formatReviewCommentContext(target, commentText),
236+ attachments,
237+ });
238+ setAttachments([]);
239+ clearReviewCommentTarget();
240+ router.dismiss();
241+ }}
242+ />
243+ </View>
244+ </KeyboardStickyView>
245+ ) : null}
246 <ImageViewing
247 images={previewImageUri ? [{ uri: previewImageUri }] : []}
248 imageIndex={0}
249@@ -317,6 +312,6 @@ export function ReviewCommentComposerSheet() {
250 swipeToCloseEnabled
251 doubleTapToZoomEnabled
252 />
253- </KeyboardAvoidingView>
254+ </View>
255 );
256 }
257diff --git a/apps/mobile/src/features/review/ReviewSheet.tsx b/apps/mobile/src/features/review/ReviewSheet.tsx
258index 82c28e81e..e148a8da2 100644
259--- a/apps/mobile/src/features/review/ReviewSheet.tsx
260+++ b/apps/mobile/src/features/review/ReviewSheet.tsx
261@@ -1,17 +1,31 @@
262 import { EnvironmentId, ThreadId, type OrchestrationCheckpointSummary } from "@t3tools/contracts";
263+import { Gesture, GestureDetector } from "react-native-gesture-handler";
264+import Animated, {
265+ makeMutable,
266+ type SharedValue,
267+ useAnimatedStyle,
268+ useSharedValue,
269+} from "react-native-reanimated";
270 import { useLocalSearchParams, useRouter } from "expo-router";
271 import Stack from "expo-router/stack";
272 import { SymbolView } from "expo-symbols";
273-import { memo, type ReactElement, useCallback, useEffect, useMemo, useRef, useState } from "react";
274+import {
275+ memo,
276+ type ReactElement,
277+ useCallback,
278+ useDeferredValue,
279+ useEffect,
280+ useMemo,
281+ useRef,
282+ useState,
283+} from "react";
284 import {
285 ActivityIndicator,
286 FlatList,
287- InteractionManager,
288 type ListRenderItemInfo,
289 Pressable,
290 ScrollView,
291 Text as NativeText,
292- type ViewToken,
293 useColorScheme,
294 useWindowDimensions,
295 View,
296@@ -32,6 +46,7 @@ import {
297 setReviewTurnDiff,
298 updateReviewExpandedFileIds,
299 updateReviewRevealedLargeFileIds,
300+ updateReviewViewedFileIds,
301 useReviewCacheForThread,
302 } from "./reviewState";
303 import {
304@@ -45,11 +60,12 @@ import {
305 type ReviewParsedDiff,
306 type ReviewRenderableFile,
307 type ReviewRenderableLineRow,
308+ type ReviewRenderableRow,
309 } from "./reviewModel";
310 import {
311 clearReviewHighlightFileCache,
312 getCachedHighlightedReviewFile,
313- highlightReviewFile,
314+ streamHighlightReviewFile,
315 type ReviewDiffTheme,
316 type ReviewHighlightedFile,
317 type ReviewHighlightedToken,
318@@ -67,9 +83,12 @@ import {
319 import {
320 changeTone,
321 DiffTokenText,
322+ REVIEW_DIFF_LINE_HEIGHT,
323 REVIEW_MONO_FONT_FAMILY,
324 ReviewChangeBar,
325 } from "./reviewDiffRendering";
326+import { markReviewEvent, measureReviewWork } from "./reviewPerf";
327+import { useReviewHighlighterStatus } from "./ReviewHighlighterProvider";
328
329 interface PendingCommentSelection {
330 readonly sectionTitle: string;
331@@ -87,14 +106,21 @@ interface ReviewLineActionInput {
332
333 const IOS_NAV_BAR_HEIGHT = 44;
334 const REVIEW_HEADER_SPACING = 0;
335-const REVIEW_LINE_GUTTER_WIDTH = 62;
336+const REVIEW_CHANGE_BAR_WIDTH = 5;
337+const REVIEW_MIN_LINE_NUMBER_WIDTH = 27;
338+const REVIEW_LINE_NUMBER_DIGIT_WIDTH_ESTIMATE = 8;
339+const REVIEW_LINE_NUMBER_HORIZONTAL_PADDING = 6;
340 const REVIEW_CHARACTER_WIDTH_ESTIMATE = 8.4;
341 const REVIEW_MAX_CONTENT_WIDTH = 4_800;
342-const REVIEW_INITIAL_HIGHLIGHT_FILE_COUNT = 2;
343-const REVIEW_HIGHLIGHT_BACKTRACK_COUNT = 0;
344-const REVIEW_HIGHLIGHT_LOOKAHEAD_COUNT = 1;
345+const REVIEW_HUNK_ROW_HEIGHT = 35;
346+const REVIEW_FILE_HEADER_HEIGHT = 43;
347+const REVIEW_SUPPRESSED_ROW_HEIGHT = 92;
348 const loggedMissingReviewTokenKeys = new Set<string>();
349
350+function waitForReviewDelay(durationMs: number): Promise<void> {
351+ return new Promise((resolve) => setTimeout(resolve, durationMs));
352+}
353+
354 function isReviewDiffDebugLoggingEnabled(): boolean {
355 return typeof __DEV__ !== "undefined" ? __DEV__ : false;
356 }
357@@ -113,33 +139,27 @@ function logReviewDiffDiagnostic(message: string, details?: Record<string, unkno
358 }
359
360 function getFileHeaderChrome(changeType: ReviewRenderableFile["changeType"]): {
361- readonly rail: string;
362 readonly dot: string;
363 } {
364 switch (changeType) {
365 case "new":
366 return {
367- rail: "bg-emerald-400",
368 dot: "bg-emerald-400",
369 };
370 case "deleted":
371 return {
372- rail: "bg-rose-400",
373 dot: "bg-rose-400",
374 };
375 case "rename-pure":
376 return {
377- rail: "bg-amber-400",
378 dot: "bg-amber-400",
379 };
380 case "rename-changed":
381 return {
382- rail: "bg-sky-400",
383 dot: "bg-sky-400",
384 };
385 default:
386 return {
387- rail: "bg-sky-400",
388 dot: "bg-sky-400",
389 };
390 }
391@@ -159,51 +179,72 @@ function formatHeaderDiffSummary(parsedDiff: ReviewParsedDiff): {
392 };
393 }
394
395-function computeReviewListContentWidth(
396- items: ReadonlyArray<ReviewListItem>,
397+function computeReviewFileContentWidth(
398+ rows: ReadonlyArray<ReviewRenderableRow>,
399 viewportWidth: number,
400+ gutterWidth: number,
401 ): number {
402 let maxTextLength = 0;
403
404- items.forEach((item) => {
405- switch (item.kind) {
406- case "file-header":
407- maxTextLength = Math.max(
408- maxTextLength,
409- item.file.path.length,
410- item.file.previousPath?.length ?? 0,
411- );
412- break;
413- case "file-suppressed":
414- maxTextLength = Math.max(maxTextLength, item.message.length, item.actionLabel?.length ?? 0);
415- break;
416- case "hunk":
417- maxTextLength = Math.max(
418- maxTextLength,
419- item.row.header.length + (item.row.context ? item.row.context.length + 1 : 0),
420- );
421- break;
422- case "line":
423- maxTextLength = Math.max(maxTextLength, item.row.content.length);
424- break;
425+ rows.forEach((row) => {
426+ if (row.kind === "hunk") {
427+ maxTextLength = Math.max(
428+ maxTextLength,
429+ row.header.length + (row.context ? row.context.length + 1 : 0),
430+ );
431+ return;
432 }
433+
434+ maxTextLength = Math.max(maxTextLength, row.content.length);
435 });
436
437 return Math.max(
438- viewportWidth,
439+ Math.max(0, viewportWidth - gutterWidth),
440 Math.min(
441 REVIEW_MAX_CONTENT_WIDTH,
442- Math.ceil(REVIEW_LINE_GUTTER_WIDTH + 48 + maxTextLength * REVIEW_CHARACTER_WIDTH_ESTIMATE),
443+ Math.ceil(48 + maxTextLength * REVIEW_CHARACTER_WIDTH_ESTIMATE),
444 ),
445 );
446 }
447
448+function computeReviewFileGutterWidth(rows: ReadonlyArray<ReviewRenderableRow>): number {
449+ let maxLineNumber = 0;
450+
451+ rows.forEach((row) => {
452+ if (row.kind !== "line") {
453+ return;
454+ }
455+
456+ maxLineNumber = Math.max(maxLineNumber, row.oldLineNumber ?? 0, row.newLineNumber ?? 0);
457+ });
458+
459+ const digitCount = Math.max(1, String(maxLineNumber).length);
460+ const lineNumberWidth = Math.max(
461+ REVIEW_MIN_LINE_NUMBER_WIDTH,
462+ digitCount * REVIEW_LINE_NUMBER_DIGIT_WIDTH_ESTIMATE + REVIEW_LINE_NUMBER_HORIZONTAL_PADDING,
463+ );
464+
465+ return REVIEW_CHANGE_BAR_WIDTH + lineNumberWidth;
466+}
467+
468 function getDefaultExpandedFileIds(
469 files: ReadonlyArray<ReviewRenderableFile>,
470 ): ReadonlyArray<string> {
471 return files.map((file) => file.id);
472 }
473
474+function getValidReviewExpandedFileIds(
475+ files: ReadonlyArray<ReviewRenderableFile>,
476+ cachedExpandedFileIds: ReadonlyArray<string> | undefined,
477+): ReadonlyArray<string> {
478+ if (cachedExpandedFileIds === undefined) {
479+ return getDefaultExpandedFileIds(files);
480+ }
481+
482+ const fileIdSet = new Set(files.map((file) => file.id));
483+ return cachedExpandedFileIds.filter((id) => fileIdSet.has(id));
484+}
485+
486 function getHighlightedTokensForLine(
487 line: ReviewRenderableLineRow,
488 highlightedFile: ReviewHighlightedFile | null,
489@@ -252,16 +293,13 @@ const ReviewLineRow = memo(function ReviewLineRow(props: {
490 delayLongPress={220}
491 onLongPress={props.onStartRangeSelection}
492 onPress={props.onComment}
493- style={{ minWidth: props.viewportWidth }}
494+ style={{
495+ height: REVIEW_DIFF_LINE_HEIGHT,
496+ width: props.viewportWidth,
497+ overflow: "hidden",
498+ }}
499 >
500- <ReviewChangeBar change={props.line.change} />
501- <Text
502- className="w-9 py-1 pr-1 text-right text-[11px] font-t3-medium text-foreground-muted"
503- style={{ fontFamily: REVIEW_MONO_FONT_FAMILY }}
504- >
505- {lineNumber ?? ""}
506- </Text>
507- <View className="min-w-0 flex-1 shrink-0 px-1 py-1">
508+ <View className="min-w-0 flex-1 shrink-0 px-1 py-1" style={{ width: props.viewportWidth }}>
509 <DiffTokenText
510 tokens={props.tokens}
511 fallback={props.line.content}
512@@ -272,62 +310,135 @@ const ReviewLineRow = memo(function ReviewLineRow(props: {
513 );
514 });
515
516+const ReviewLineGutter = memo(function ReviewLineGutter(props: {
517+ readonly change: ReviewRenderableLineRow["change"];
518+ readonly gutterWidth: number;
519+ readonly lineNumber: number | null;
520+}) {
521+ const lineNumberWidth = Math.max(0, props.gutterWidth - REVIEW_CHANGE_BAR_WIDTH);
522+
523+ return (
524+ <View className={cn("flex-row", changeTone(props.change))} style={{ width: props.gutterWidth }}>
525+ <ReviewChangeBar change={props.change} />
526+ <Text
527+ className="py-1 pr-1 text-right text-[11px] font-t3-medium text-foreground-muted"
528+ style={[{ fontFamily: REVIEW_MONO_FONT_FAMILY }, { width: lineNumberWidth }]}
529+ >
530+ {props.lineNumber ?? ""}
531+ </Text>
532+ </View>
533+ );
534+});
535+
536+const ReviewHunkGutter = memo(function ReviewHunkGutter(props: { readonly gutterWidth: number }) {
537+ return (
538+ <View
539+ className="border-b border-border/60 bg-sky-500/10"
540+ style={{ width: props.gutterWidth }}
541+ />
542+ );
543+});
544+
545 const ReviewFileCard = memo(function ReviewFileCard(props: {
546 readonly file: ReviewRenderableFile;
547 readonly fileId: string;
548 readonly expanded: boolean;
549+ readonly viewed: boolean;
550 readonly viewportWidth: number;
551 readonly onToggleFile: (fileId: string) => void;
552+ readonly onToggleViewed: (fileId: string) => void;
553 }) {
554- const chrome = getFileHeaderChrome(props.file.changeType);
555+ const { expanded, file, fileId, onToggleFile, onToggleViewed, viewed, viewportWidth } = props;
556+ const chrome = getFileHeaderChrome(file.changeType);
557+ const iconColor = String(useThemeColor("--color-icon-muted"));
558+ const handleToggleFile = useCallback(() => {
559+ onToggleFile(fileId);
560+ }, [fileId, onToggleFile]);
561+ const handleToggleViewed = useCallback(() => {
562+ onToggleViewed(fileId);
563+ }, [fileId, onToggleViewed]);
564
565 return (
566 <View
567- className="border-b border-border/70 bg-card"
568- style={{
569- zIndex: 1,
570- width: props.viewportWidth,
571- shadowColor: "#000000",
572- shadowOpacity: 0.08,
573- shadowRadius: 10,
574- shadowOffset: { width: 0, height: 6 },
575- elevation: 4,
576- }}
577+ className="border-b border-border bg-card"
578+ style={{ height: REVIEW_FILE_HEADER_HEIGHT, overflow: "hidden", width: viewportWidth }}
579 >
580- <Pressable className="flex-row items-center" onPress={() => props.onToggleFile(props.fileId)}>
581- <View className={cn("w-1 self-stretch", chrome.rail)} />
582- <View className="flex-1 flex-row items-center px-3 py-1.5">
583- <View className="size-7 items-center justify-center rounded-full bg-subtle">
584- <SymbolView
585- name={props.expanded ? "chevron.down" : "chevron.right"}
586- size={12}
587- tintColor="#8a8a8a"
588- type="monochrome"
589- />
590- </View>
591- <View className="ml-2 min-w-0 flex-1 flex-row items-center gap-2">
592- <View className={cn("size-2 rounded-full", chrome.dot)} />
593- <View className="min-w-0 flex-1">
594- <Text className="font-mono text-[13px] leading-[18px] text-foreground">
595- {props.file.path}
596+ <View className="min-h-[42px] flex-row items-center gap-1.5 px-2">
597+ <Pressable
598+ className="size-9 items-center justify-center"
599+ accessibilityRole="button"
600+ accessibilityLabel={expanded ? "Collapse file" : "Expand file"}
601+ hitSlop={{ bottom: 8, left: 8, right: 8, top: 8 }}
602+ onTouchEnd={handleToggleFile}
603+ >
604+ <SymbolView
605+ name={expanded ? "chevron.down" : "chevron.right"}
606+ size={13}
607+ tintColor={iconColor}
608+ type="monochrome"
609+ />
610+ </Pressable>
611+ <Pressable
612+ className="min-w-0 flex-1 flex-row items-center gap-2 py-2"
613+ accessibilityRole="button"
614+ accessibilityLabel={expanded ? "Collapse file" : "Expand file"}
615+ onTouchEnd={handleToggleFile}
616+ >
617+ <View className={cn("size-2.5 rounded-full", chrome.dot)} />
618+ <View className="min-w-0 flex-1">
619+ <Text
620+ className="font-mono text-[13px] leading-[18px] text-foreground"
621+ numberOfLines={1}
622+ >
623+ {file.path}
624+ </Text>
625+ {file.previousPath && file.previousPath !== file.path ? (
626+ <Text
627+ className="font-mono text-[10px] leading-[14px] text-foreground-muted"
628+ numberOfLines={1}
629+ >
630+ {file.previousPath}
631 </Text>
632- {props.file.previousPath && props.file.previousPath !== props.file.path ? (
633- <Text className="font-mono text-[10px] leading-[14px] text-foreground-muted">
634- {props.file.previousPath}
635- </Text>
636+ ) : null}
637+ </View>
638+ </Pressable>
639+ <View className="flex-row items-center justify-end gap-1.5">
640+ <Text className="font-mono text-[12px] font-t3-bold text-rose-400">
641+ -{file.deletions}
642+ </Text>
643+ <Text className="font-mono text-[12px] font-t3-bold text-emerald-400">
644+ +{file.additions}
645+ </Text>
646+ <Pressable
647+ className="ml-0.5 min-h-[40px] min-w-[82px] flex-row items-center justify-center gap-1.5 px-1.5"
648+ accessibilityRole="checkbox"
649+ accessibilityState={{ checked: viewed }}
650+ accessibilityLabel={viewed ? "Mark file as unviewed" : "Mark file as viewed"}
651+ hitSlop={{ bottom: 8, left: 4, right: 8, top: 8 }}
652+ onTouchEnd={handleToggleViewed}
653+ >
654+ <View
655+ className={cn(
656+ "size-[18px] items-center justify-center rounded border",
657+ viewed ? "border-sky-500 bg-sky-500" : "border-icon-muted",
658+ )}
659+ >
660+ {viewed ? (
661+ <SymbolView name="checkmark" size={11} tintColor="#ffffff" type="monochrome" />
662 ) : null}
663 </View>
664- </View>
665- <View className="ml-3 flex-row items-center justify-end gap-2">
666- <Text className="font-mono text-[12px] font-t3-bold text-emerald-600 dark:text-emerald-300">
667- +{props.file.additions}
668- </Text>
669- <Text className="font-mono text-[12px] font-t3-bold text-rose-600 dark:text-rose-300">
670- -{props.file.deletions}
671+ <Text
672+ className={cn(
673+ "text-[12px] font-t3-medium",
674+ viewed ? "text-foreground" : "text-foreground-muted",
675+ )}
676+ numberOfLines={1}
677+ >
678+ Viewed
679 </Text>
680- </View>
681+ </Pressable>
682 </View>
683- </Pressable>
684+ </View>
685 </View>
686 );
687 });
688@@ -342,7 +453,11 @@ const ReviewFileSuppressedBody = memo(function ReviewFileSuppressedBody(props: {
689 return (
690 <View
691 className="gap-2 border-b border-border bg-card px-4 py-3"
692- style={{ minWidth: props.viewportWidth }}
693+ style={{
694+ height: REVIEW_SUPPRESSED_ROW_HEIGHT,
695+ overflow: "hidden",
696+ width: props.viewportWidth,
697+ }}
698 >
699 <Text className="text-[12px] leading-[18px] text-foreground-muted">{props.message}</Text>
700 {props.actionLabel && props.onLoadDiffFile ? (
701@@ -364,10 +479,13 @@ const ReviewHunkRow = memo(function ReviewHunkRow(props: {
702 }) {
703 return (
704 <View
705- className="border-b border-border/60 bg-sky-500/10 px-2 py-2"
706- style={{ minWidth: props.viewportWidth }}
707+ className="border-b border-border/60 bg-sky-500/10 py-2"
708+ style={{ height: REVIEW_HUNK_ROW_HEIGHT, width: props.viewportWidth, overflow: "hidden" }}
709 >
710- <Text className="font-mono text-[12px] leading-[18px] text-sky-700 dark:text-sky-300">
711+ <Text
712+ className="px-2 font-mono text-[12px] leading-[18px] text-sky-700 dark:text-sky-300"
713+ numberOfLines={1}
714+ >
715 {props.header}
716 {props.context ? ` ${props.context}` : ""}
717 </Text>
718@@ -375,6 +493,61 @@ const ReviewHunkRow = memo(function ReviewHunkRow(props: {
719 );
720 });
721
722+const ReviewCodePanRow = memo(function ReviewCodePanRow(props: {
723+ readonly contentWidth: number;
724+ readonly horizontalOffset: SharedValue<number>;
725+ readonly gutterWidth?: number;
726+ readonly viewportWidth: number;
727+ readonly leftGutter?: ReactElement;
728+ readonly children: ReactElement;
729+}) {
730+ const {
731+ children,
732+ contentWidth,
733+ gutterWidth = 0,
734+ horizontalOffset,
735+ leftGutter,
736+ viewportWidth,
737+ } = props;
738+ const dragStartOffset = useSharedValue(0);
739+ const visibleContentWidth = leftGutter ? viewportWidth - gutterWidth : viewportWidth;
740+ const maxOffset = Math.max(0, contentWidth - visibleContentWidth);
741+
742+ const panGesture = useMemo(
743+ () =>
744+ Gesture.Pan()
745+ .activeOffsetX([-8, 8])
746+ .failOffsetY([-10, 10])
747+ .onBegin(() => {
748+ dragStartOffset.value = horizontalOffset.value;
749+ })
750+ .onUpdate((event) => {
751+ "worklet";
752+ const nextOffset = dragStartOffset.value - event.translationX;
753+ horizontalOffset.value = Math.min(maxOffset, Math.max(0, nextOffset));
754+ }),
755+ [dragStartOffset, horizontalOffset, maxOffset],
756+ );
757+
758+ const contentStyle = useAnimatedStyle(
759+ () => ({
760+ transform: [{ translateX: -horizontalOffset.value }],
761+ }),
762+ [horizontalOffset],
763+ );
764+
765+ return (
766+ <GestureDetector gesture={panGesture}>
767+ <View style={{ flexDirection: "row", overflow: "hidden", width: viewportWidth }}>
768+ {leftGutter ?? null}
769+ <View style={{ flex: 1, overflow: "hidden" }}>
770+ <Animated.View style={[{ width: contentWidth }, contentStyle]}>{children}</Animated.View>
771+ </View>
772+ </View>
773+ </GestureDetector>
774+ );
775+});
776+
777 const ReviewNotice = memo(function ReviewNotice(props: { readonly notice: string }) {
778 return (
779 <View className="border-b border-amber-200 bg-amber-50 px-4 py-3 dark:border-amber-900/60 dark:bg-amber-950/40">
780@@ -454,15 +627,19 @@ export function ReviewSheet() {
781 const [highlightedFilesById, setHighlightedFilesById] = useState<
782 Record<string, ReviewHighlightedFile | null>
783 >({});
784- const [visibleFileIds, setVisibleFileIds] = useState<ReadonlyArray<string>>([]);
785+ const deferredHighlightedFilesById = useDeferredValue(highlightedFilesById);
786+ const [localExpandedFileIdsBySection, setLocalExpandedFileIdsBySection] = useState<
787+ Record<string, ReadonlyArray<string>>
788+ >({});
789+ const [localViewedFileIdsBySection, setLocalViewedFileIdsBySection] = useState<
790+ Record<string, ReadonlyArray<string>>
791+ >({});
792 const activeCommentTarget = useReviewCommentTarget();
793 const selectedTheme = (colorScheme === "dark" ? "dark" : "light") satisfies ReviewDiffTheme;
794- const highlightQueueRef = useRef<string[]>([]);
795- const highlightRequestedFileIdsRef = useRef<Set<string>>(new Set());
796- const highlightQueueGenerationRef = useRef(0);
797- const highlightQueueActiveRef = useRef(false);
798- const highlightableFilesByIdRef = useRef<ReadonlyMap<string, ReviewRenderableFile>>(new Map());
799- const selectedThemeRef = useRef<ReviewDiffTheme>(selectedTheme);
800+ const reviewHighlighter = useReviewHighlighterStatus();
801+ const highlightRunIdRef = useRef(0);
802+ const highlightableFilesRef = useRef<ReadonlyArray<ReviewRenderableFile>>([]);
803+ const horizontalOffsetByFileIdRef = useRef<Map<string, SharedValue<number>>>(new Map());
804 const { selectedThreadCwd } = useSelectedThreadWorktree();
805
806 const cwd = selectedThreadCwd;
807@@ -498,11 +675,13 @@ export function ReviewSheet() {
808 const topContentInset = insets.top + IOS_NAV_BAR_HEIGHT;
809 const parsedDiff = useMemo(
810 () =>
811- getCachedReviewParsedDiff({
812- threadKey: reviewCache.threadKey,
813- sectionId: selectedSection?.id ?? null,
814- diff: selectedSection?.diff,
815- }),
816+ measureReviewWork("parse-diff", () =>
817+ getCachedReviewParsedDiff({
818+ threadKey: reviewCache.threadKey,
819+ sectionId: selectedSection?.id ?? null,
820+ diff: selectedSection?.diff,
821+ }),
822+ ),
823 [reviewCache.threadKey, selectedSection?.diff, selectedSection?.id],
824 );
825 const headerDiffSummary = useMemo(() => formatHeaderDiffSummary(parsedDiff), [parsedDiff]);
826@@ -510,14 +689,53 @@ export function ReviewSheet() {
827 () => countReviewCommentContexts(draftMessage),
828 [draftMessage],
829 );
830+ const viewportWidth = Math.max(width, 280);
831+
832+ useEffect(() => {
833+ if (!selectedSection?.id || parsedDiff.kind !== "files") {
834+ return;
835+ }
836+
837+ setLocalExpandedFileIdsBySection((current) => {
838+ if (current[selectedSection.id] !== undefined) {
839+ return current;
840+ }
841+
842+ return {
843+ ...current,
844+ [selectedSection.id]: getValidReviewExpandedFileIds(
845+ parsedDiff.files,
846+ reviewCache.expandedFileIdsBySection[selectedSection.id],
847+ ),
848+ };
849+ });
850+
851+ setLocalViewedFileIdsBySection((current) => {
852+ if (current[selectedSection.id] !== undefined) {
853+ return current;
854+ }
855+
856+ return {
857+ ...current,
858+ [selectedSection.id]: reviewCache.viewedFileIdsBySection[selectedSection.id] ?? [],
859+ };
860+ });
861+ }, [
862+ parsedDiff,
863+ reviewCache.expandedFileIdsBySection,
864+ reviewCache.viewedFileIdsBySection,
865+ selectedSection?.id,
866+ ]);
867
868 const expandedFileIds = useMemo(
869 () =>
870 selectedSection?.id && parsedDiff.kind === "files"
871- ? (reviewCache.expandedFileIdsBySection[selectedSection.id] ??
872- getDefaultExpandedFileIds(parsedDiff.files))
873+ ? getValidReviewExpandedFileIds(
874+ parsedDiff.files,
875+ localExpandedFileIdsBySection[selectedSection.id],
876+ )
877 : [],
878- [parsedDiff, reviewCache.expandedFileIdsBySection, selectedSection?.id],
879+ [localExpandedFileIdsBySection, parsedDiff, selectedSection?.id],
880 );
881 const revealedLargeFileIds = useMemo(
882 () =>
883@@ -526,47 +744,96 @@ export function ReviewSheet() {
884 : [],
885 [reviewCache.revealedLargeFileIdsBySection, selectedSection?.id],
886 );
887+ const viewedFileIds = useMemo(
888+ () => (selectedSection?.id ? (localViewedFileIdsBySection[selectedSection.id] ?? []) : []),
889+ [localViewedFileIdsBySection, selectedSection?.id],
890+ );
891+ const viewedFileIdSet = useMemo(() => new Set(viewedFileIds), [viewedFileIds]);
892 const reviewListItems = useMemo(
893 () =>
894 selectedSection && parsedDiff.kind === "files"
895- ? buildReviewListItems({
896- files: parsedDiff.files,
897- expandedFileIds,
898- revealedLargeFileIds,
899- })
900+ ? measureReviewWork("build-list-items", () =>
901+ buildReviewListItems({
902+ files: parsedDiff.files,
903+ expandedFileIds,
904+ revealedLargeFileIds,
905+ }),
906+ )
907 : [],
908 [expandedFileIds, parsedDiff, revealedLargeFileIds, selectedSection],
909 );
910- const reviewFileById = useMemo(() => {
911+ const reviewLineRowsByFileId = useMemo(() => {
912 if (parsedDiff.kind !== "files") {
913- return new Map<string, ReviewRenderableFile>();
914+ return new Map<string, ReadonlyArray<ReviewRenderableLineRow>>();
915 }
916
917- return new Map(parsedDiff.files.map((file) => [file.id, file] as const));
918+ return measureReviewWork(
919+ "index-line-rows",
920+ () =>
921+ new Map(
922+ parsedDiff.files.map((file) => [
923+ file.id,
924+ file.rows.filter((row): row is ReviewRenderableLineRow => row.kind === "line"),
925+ ]),
926+ ),
927+ );
928 }, [parsedDiff]);
929- const reviewLineRowsByFileId = useMemo(() => {
930+ const reviewContentWidthByFileId = useMemo(() => {
931 if (parsedDiff.kind !== "files") {
932- return new Map<string, ReadonlyArray<ReviewRenderableLineRow>>();
933+ return new Map<string, number>();
934+ }
935+
936+ return measureReviewWork(
937+ "measure-file-widths",
938+ () =>
939+ new Map(
940+ parsedDiff.files.map((file) => [
941+ file.id,
942+ computeReviewFileContentWidth(
943+ file.rows,
944+ viewportWidth,
945+ computeReviewFileGutterWidth(file.rows),
946+ ),
947+ ]),
948+ ),
949+ );
950+ }, [parsedDiff, viewportWidth]);
951+ const reviewGutterWidthByFileId = useMemo(() => {
952+ if (parsedDiff.kind !== "files") {
953+ return new Map<string, number>();
954 }
955
956 return new Map(
957- parsedDiff.files.map((file) => [
958- file.id,
959- file.rows.filter((row): row is ReviewRenderableLineRow => row.kind === "line"),
960- ]),
961+ parsedDiff.files.map((file) => [file.id, computeReviewFileGutterWidth(file.rows)]),
962 );
963 }, [parsedDiff]);
964- const reviewLineIndexByRowId = useMemo(() => {
965- const map = new Map<string, number>();
966+ const getReviewFileHorizontalOffset = useCallback((fileId: string) => {
967+ let offset = horizontalOffsetByFileIdRef.current.get(fileId);
968+ if (!offset) {
969+ offset = makeMutable(0);
970+ horizontalOffsetByFileIdRef.current.set(fileId, offset);
971+ }
972
973- reviewLineRowsByFileId.forEach((rows) => {
974- rows.forEach((row, index) => {
975- map.set(row.id, index);
976- });
977- });
978+ return offset;
979+ }, []);
980+ useEffect(() => {
981+ const knownFileIds =
982+ parsedDiff.kind === "files" ? new Set(parsedDiff.files.map((file) => file.id)) : new Set();
983
984- return map;
985- }, [reviewLineRowsByFileId]);
986+ horizontalOffsetByFileIdRef.current.forEach((offset, fileId) => {
987+ if (!knownFileIds.has(fileId)) {
988+ horizontalOffsetByFileIdRef.current.delete(fileId);
989+ return;
990+ }
991+
992+ const contentWidth = reviewContentWidthByFileId.get(fileId) ?? viewportWidth;
993+ const gutterWidth = reviewGutterWidthByFileId.get(fileId) ?? 0;
994+ offset.value = Math.min(
995+ offset.value,
996+ Math.max(0, contentWidth - (viewportWidth - gutterWidth)),
997+ );
998+ });
999+ }, [parsedDiff, reviewContentWidthByFileId, reviewGutterWidthByFileId, viewportWidth]);
1000 const highlightableFiles = useMemo(() => {
1001 if (parsedDiff.kind !== "files") {
1002 return [] as ReadonlyArray<ReviewRenderableFile>;
1003@@ -587,59 +854,13 @@ export function ReviewSheet() {
1004 );
1005 });
1006 }, [expandedFileIds, parsedDiff, revealedLargeFileIds]);
1007- const highlightableFileIds = useMemo(
1008- () => new Set(highlightableFiles.map((file) => file.id)),
1009+ const highlightableFilesKey = useMemo(
1010+ () => highlightableFiles.map((file) => `${file.id}:${file.cacheKey}`).join("\n"),
1011 [highlightableFiles],
1012 );
1013- const priorityHighlightFileIds = useMemo(() => {
1014- if (parsedDiff.kind !== "files" || highlightableFiles.length === 0) {
1015- return [] as ReadonlyArray<string>;
1016- }
1017-
1018- const fileIdsInPriorityOrder =
1019- visibleFileIds.length > 0
1020- ? visibleFileIds.filter((fileId) => highlightableFileIds.has(fileId))
1021- : parsedDiff.files
1022- .slice(0, REVIEW_INITIAL_HIGHLIGHT_FILE_COUNT)
1023- .map((file) => file.id)
1024- .filter((fileId) => highlightableFileIds.has(fileId));
1025-
1026- if (fileIdsInPriorityOrder.length === 0) {
1027- return [] as ReadonlyArray<string>;
1028- }
1029-
1030- const firstVisibleIndex = parsedDiff.files.findIndex(
1031- (file) => file.id === fileIdsInPriorityOrder[0],
1032- );
1033- const lastVisibleIndex = parsedDiff.files.findIndex(
1034- (file) => file.id === fileIdsInPriorityOrder[fileIdsInPriorityOrder.length - 1],
1035- );
1036-
1037- if (firstVisibleIndex < 0 || lastVisibleIndex < 0) {
1038- return fileIdsInPriorityOrder;
1039- }
1040-
1041- const startIndex = Math.max(0, firstVisibleIndex - REVIEW_HIGHLIGHT_BACKTRACK_COUNT);
1042- const endIndex = Math.min(
1043- parsedDiff.files.length - 1,
1044- lastVisibleIndex + REVIEW_HIGHLIGHT_LOOKAHEAD_COUNT,
1045- );
1046-
1047- const queuedIds: string[] = [];
1048- for (let index = startIndex; index <= endIndex; index += 1) {
1049- const fileId = parsedDiff.files[index]?.id;
1050- if (fileId && highlightableFileIds.has(fileId)) {
1051- queuedIds.push(fileId);
1052- }
1053- }
1054-
1055- return queuedIds;
1056- }, [highlightableFileIds, highlightableFiles.length, parsedDiff, visibleFileIds]);
1057- const viewportWidth = Math.max(width, 280);
1058- const reviewListContentWidth = useMemo(
1059- () => computeReviewListContentWidth(reviewListItems, viewportWidth),
1060- [reviewListItems, viewportWidth],
1061- );
1062+ useEffect(() => {
1063+ highlightableFilesRef.current = highlightableFiles;
1064+ }, [highlightableFiles]);
1065 const loadGitDiffs = useCallback(async () => {
1066 if (!cwd) {
1067 return;
1068@@ -714,100 +935,6 @@ export function ReviewSheet() {
1069 void loadGitDiffs();
1070 }, [loadGitDiffs]);
1071
1072- useEffect(() => {
1073- selectedThemeRef.current = selectedTheme;
1074- }, [selectedTheme]);
1075-
1076- useEffect(() => {
1077- highlightableFilesByIdRef.current = new Map(highlightableFiles.map((file) => [file.id, file]));
1078- }, [highlightableFiles]);
1079-
1080- const startHighlightQueueRunner = useCallback(function startHighlightQueueRunner() {
1081- if (highlightQueueActiveRef.current) {
1082- return;
1083- }
1084-
1085- const generation = highlightQueueGenerationRef.current;
1086- highlightQueueActiveRef.current = true;
1087-
1088- void (async () => {
1089- try {
1090- while (generation === highlightQueueGenerationRef.current) {
1091- const nextFileId = highlightQueueRef.current.shift();
1092- if (!nextFileId) {
1093- break;
1094- }
1095-
1096- const file = highlightableFilesByIdRef.current.get(nextFileId);
1097- if (!file) {
1098- continue;
1099- }
1100-
1101- const theme = selectedThemeRef.current;
1102- const cached = getCachedHighlightedReviewFile(file, theme);
1103- if (cached) {
1104- logReviewDiffDiagnostic("using cached highlighted file", {
1105- fileId: file.id,
1106- filePath: file.path,
1107- theme,
1108- });
1109- setHighlightedFilesById((current) =>
1110- current[file.id] === cached ? current : { ...current, [file.id]: cached },
1111- );
1112- continue;
1113- }
1114-
1115- logReviewDiffDiagnostic("requesting highlighted file", {
1116- fileId: file.id,
1117- filePath: file.path,
1118- theme,
1119- });
1120-
1121- try {
1122- await new Promise<void>((resolve) => {
1123- InteractionManager.runAfterInteractions(() => resolve());
1124- });
1125- const result = await highlightReviewFile(file, theme);
1126- if (generation !== highlightQueueGenerationRef.current) {
1127- logReviewDiffDiagnostic("discarding highlighted file after cancellation", {
1128- fileId: file.id,
1129- filePath: file.path,
1130- });
1131- return;
1132- }
1133-
1134- logReviewDiffDiagnostic("received highlighted file", {
1135- fileId: file.id,
1136- filePath: file.path,
1137- additionLines: result.additionLines.length,
1138- deletionLines: result.deletionLines.length,
1139- });
1140- setHighlightedFilesById((current) => {
1141- if (current[file.id] === result) {
1142- return current;
1143- }
1144- return { ...current, [file.id]: result };
1145- });
1146- } catch (error) {
1147- logReviewDiffDiagnostic("highlight request failed", {
1148- fileId: file.id,
1149- filePath: file.path,
1150- error: error instanceof Error ? error.message : String(error),
1151- });
1152- }
1153- }
1154- } finally {
1155- highlightQueueActiveRef.current = false;
1156- if (
1157- generation === highlightQueueGenerationRef.current &&
1158- highlightQueueRef.current.length > 0
1159- ) {
1160- startHighlightQueueRunner();
1161- }
1162- }
1163- })();
1164- }, []);
1165-
1166 useEffect(() => {
1167 if (reviewSections.length === 0) {
1168 return;
1169@@ -854,15 +981,15 @@ export function ReviewSheet() {
1170 }
1171
1172 updateReviewExpandedFileIds(reviewCache.threadKey, selectedSection.id, (existing) => {
1173- if (existing !== undefined) {
1174- const validIds = existing.filter((id) => parsedDiff.files.some((file) => file.id === id));
1175- if (validIds.length === existing.length) {
1176- return existing;
1177- }
1178- return validIds;
1179+ const validIds = getValidReviewExpandedFileIds(parsedDiff.files, existing);
1180+ if (
1181+ existing !== undefined &&
1182+ validIds.length === existing.length &&
1183+ validIds.every((id, index) => id === existing[index])
1184+ ) {
1185+ return existing;
1186 }
1187-
1188- return getDefaultExpandedFileIds(parsedDiff.files);
1189+ return validIds;
1190 });
1191 }, [parsedDiff, reviewCache.threadKey, selectedSection?.id]);
1192
1193@@ -887,11 +1014,7 @@ export function ReviewSheet() {
1194
1195 useEffect(() => {
1196 setHighlightedFilesById({});
1197- setVisibleFileIds([]);
1198- highlightQueueGenerationRef.current += 1;
1199- highlightQueueRef.current = [];
1200- highlightRequestedFileIdsRef.current = new Set();
1201- highlightQueueActiveRef.current = false;
1202+ highlightRunIdRef.current += 1;
1203 clearReviewHighlightFileCache();
1204 loggedMissingReviewTokenKeys.clear();
1205 logReviewDiffDiagnostic("reset highlighted files", {
1206@@ -905,15 +1028,23 @@ export function ReviewSheet() {
1207 return;
1208 }
1209
1210+ markReviewEvent("parsed-diff-ready", {
1211+ sectionId: selectedSection?.id ?? null,
1212+ fileCount: parsedDiff.fileCount,
1213+ additions: parsedDiff.additions,
1214+ deletions: parsedDiff.deletions,
1215+ renderedItems: reviewListItems.length,
1216+ });
1217 logReviewDiffDiagnostic("parsed diff files", {
1218 selectedSectionId: selectedSection?.id ?? null,
1219 fileCount: parsedDiff.fileCount,
1220 renderableFileCount: parsedDiff.files.length,
1221 });
1222- }, [parsedDiff, selectedSection?.id]);
1223+ }, [parsedDiff, reviewListItems.length, selectedSection?.id]);
1224
1225 useEffect(() => {
1226- if (priorityHighlightFileIds.length === 0) {
1227+ const files = highlightableFilesRef.current;
1228+ if (files.length === 0) {
1229 logReviewDiffDiagnostic("no highlightable files", {
1230 selectedSectionId: selectedSection?.id ?? null,
1231 parsedDiffKind: parsedDiff.kind,
1232@@ -922,33 +1053,98 @@ export function ReviewSheet() {
1233 return;
1234 }
1235
1236- const queuedFileIds: string[] = [];
1237- priorityHighlightFileIds.forEach((fileId) => {
1238- if (highlightRequestedFileIdsRef.current.has(fileId)) {
1239- return;
1240- }
1241-
1242- const file = highlightableFilesByIdRef.current.get(fileId);
1243- if (!file) {
1244- return;
1245- }
1246-
1247- highlightRequestedFileIdsRef.current.add(fileId);
1248- highlightQueueRef.current.push(fileId);
1249- queuedFileIds.push(fileId);
1250- });
1251-
1252- if (queuedFileIds.length === 0) {
1253+ if (reviewHighlighter.status !== "ready") {
1254+ logReviewDiffDiagnostic("waiting for highlighter provider", {
1255+ selectedSectionId: selectedSection?.id ?? null,
1256+ status: reviewHighlighter.status,
1257+ error: reviewHighlighter.error,
1258+ });
1259 return;
1260 }
1261
1262- logReviewDiffDiagnostic("scheduling file highlights", {
1263+ const runId = highlightRunIdRef.current;
1264+ let cancelled = false;
1265+
1266+ logReviewDiffDiagnostic("streaming file highlights", {
1267 selectedSectionId: selectedSection?.id ?? null,
1268- fileCount: queuedFileIds.length,
1269- fileIds: queuedFileIds,
1270+ fileCount: files.length,
1271 });
1272- startHighlightQueueRunner();
1273- }, [parsedDiff.kind, priorityHighlightFileIds, selectedSection?.id, startHighlightQueueRunner]);
1274+
1275+ void (async () => {
1276+ for (const file of files) {
1277+ if (cancelled || runId !== highlightRunIdRef.current) {
1278+ return;
1279+ }
1280+
1281+ const cached = getCachedHighlightedReviewFile(file, selectedTheme);
1282+ if (cached) {
1283+ setHighlightedFilesById((current) =>
1284+ current[file.id] === cached ? current : { ...current, [file.id]: cached },
1285+ );
1286+ continue;
1287+ }
1288+
1289+ logReviewDiffDiagnostic("requesting highlighted file", {
1290+ fileId: file.id,
1291+ filePath: file.path,
1292+ theme: selectedTheme,
1293+ });
1294+
1295+ try {
1296+ const highlightStartedAt = performance.now();
1297+ const result = await streamHighlightReviewFile(file, selectedTheme, (progress) => {
1298+ if (cancelled || runId !== highlightRunIdRef.current) {
1299+ return;
1300+ }
1301+
1302+ if (!progress.complete) {
1303+ return;
1304+ }
1305+
1306+ logReviewDiffDiagnostic("received streamed highlighted file", {
1307+ fileId: file.id,
1308+ filePath: file.path,
1309+ highlightedLineCount: progress.highlightedLineCount,
1310+ durationMs: Math.round(performance.now() - highlightStartedAt),
1311+ });
1312+ });
1313+
1314+ if (cancelled || runId !== highlightRunIdRef.current) {
1315+ return;
1316+ }
1317+
1318+ logReviewDiffDiagnostic("received highlighted file", {
1319+ fileId: file.id,
1320+ filePath: file.path,
1321+ additionLines: result.additionLines.length,
1322+ deletionLines: result.deletionLines.length,
1323+ });
1324+ setHighlightedFilesById((current) =>
1325+ current[file.id] === result ? current : { ...current, [file.id]: result },
1326+ );
1327+ } catch (error) {
1328+ logReviewDiffDiagnostic("highlight request failed", {
1329+ fileId: file.id,
1330+ filePath: file.path,
1331+ error: error instanceof Error ? error.message : String(error),
1332+ });
1333+ }
1334+
1335+ await waitForReviewDelay(0);
1336+ }
1337+ })();
1338+
1339+ return () => {
1340+ cancelled = true;
1341+ };
1342+ }, [
1343+ highlightableFilesKey,
1344+ parsedDiff.kind,
1345+ reviewHighlighter.error,
1346+ reviewHighlighter.status,
1347+ selectedSection?.id,
1348+ selectedTheme,
1349+ ]);
1350
1351 const refreshSelectedSection = useCallback(async () => {
1352 if (!selectedSection) {
1353@@ -968,20 +1164,68 @@ export function ReviewSheet() {
1354
1355 const handleToggleExpandedFile = useCallback(
1356 (fileId: string) => {
1357- if (!reviewCache.threadKey || !selectedSection?.id || parsedDiff.kind !== "files") {
1358+ if (!selectedSection?.id || parsedDiff.kind !== "files") {
1359 return;
1360 }
1361
1362- updateReviewExpandedFileIds(reviewCache.threadKey, selectedSection.id, (existing) => {
1363- const currentIds = existing ?? getDefaultExpandedFileIds(parsedDiff.files);
1364- return currentIds.includes(fileId)
1365+ const sectionId = selectedSection.id;
1366+
1367+ setLocalExpandedFileIdsBySection((current) => {
1368+ const currentIds = getValidReviewExpandedFileIds(parsedDiff.files, current[sectionId]);
1369+ const nextIds = currentIds.includes(fileId)
1370 ? currentIds.filter((id) => id !== fileId)
1371 : [...currentIds, fileId];
1372+
1373+ return {
1374+ ...current,
1375+ [sectionId]: nextIds,
1376+ };
1377 });
1378+
1379+ if (reviewCache.threadKey) {
1380+ updateReviewExpandedFileIds(reviewCache.threadKey, sectionId, (existing) => {
1381+ const currentIds = getValidReviewExpandedFileIds(parsedDiff.files, existing);
1382+ return currentIds.includes(fileId)
1383+ ? currentIds.filter((id) => id !== fileId)
1384+ : [...currentIds, fileId];
1385+ });
1386+ }
1387 },
1388 [parsedDiff, reviewCache.threadKey, selectedSection?.id],
1389 );
1390
1391+ const handleToggleViewedFile = useCallback(
1392+ (fileId: string) => {
1393+ if (!selectedSection?.id) {
1394+ return;
1395+ }
1396+
1397+ const sectionId = selectedSection.id;
1398+
1399+ setLocalViewedFileIdsBySection((current) => {
1400+ const currentIds = current[sectionId] ?? [];
1401+ const nextIds = currentIds.includes(fileId)
1402+ ? currentIds.filter((id) => id !== fileId)
1403+ : [...currentIds, fileId];
1404+
1405+ return {
1406+ ...current,
1407+ [sectionId]: nextIds,
1408+ };
1409+ });
1410+
1411+ if (reviewCache.threadKey) {
1412+ updateReviewViewedFileIds(reviewCache.threadKey, sectionId, (existing) => {
1413+ const currentIds = existing ?? [];
1414+ return currentIds.includes(fileId)
1415+ ? currentIds.filter((id) => id !== fileId)
1416+ : [...currentIds, fileId];
1417+ });
1418+ }
1419+ },
1420+ [reviewCache.threadKey, selectedSection?.id],
1421+ );
1422+
1423 const handleRevealLargeDiff = useCallback(
1424 (fileId: string) => {
1425 if (!reviewCache.threadKey || !selectedSection?.id) {
1426@@ -1080,35 +1324,6 @@ export function ReviewSheet() {
1427
1428 return <>{children}</>;
1429 }, [error, parsedDiffNotice]);
1430- const stickyHeaderIndices = useMemo(() => {
1431- const itemOffset = listHeader ? 1 : 0;
1432-
1433- return reviewListItems.flatMap((item, index) =>
1434- item.kind === "file-header" ? [index + itemOffset] : [],
1435- );
1436- }, [listHeader, reviewListItems]);
1437-
1438- const viewabilityConfigRef = useRef({
1439- itemVisiblePercentThreshold: 10,
1440- });
1441- const onViewableItemsChangedRef = useRef(
1442- ({
1443- viewableItems,
1444- }: {
1445- readonly viewableItems: Array<ViewToken<ReviewListItem>>;
1446- readonly changed: Array<ViewToken<ReviewListItem>>;
1447- }) => {
1448- const nextVisibleFileIds = Array.from(
1449- new Set(
1450- viewableItems
1451- .filter((token) => token.isViewable && token.item !== undefined)
1452- .map((token) => token.item.fileId),
1453- ),
1454- );
1455-
1456- setVisibleFileIds(nextVisibleFileIds);
1457- },
1458- );
1459
1460 const renderReviewListItem = useCallback(
1461 ({ item }: ListRenderItemInfo<ReviewListItem>) => {
1462@@ -1116,112 +1331,142 @@ export function ReviewSheet() {
1463 return null;
1464 }
1465
1466+ let renderedItem: ReactElement | null = null;
1467 switch (item.kind) {
1468 case "file-header":
1469- return (
1470+ renderedItem = (
1471 <ReviewFileCard
1472 file={item.file}
1473 fileId={item.fileId}
1474 expanded={item.expanded}
1475- viewportWidth={reviewListContentWidth}
1476+ viewed={viewedFileIdSet.has(item.fileId)}
1477+ viewportWidth={viewportWidth}
1478 onToggleFile={handleToggleExpandedFile}
1479+ onToggleViewed={handleToggleViewedFile}
1480 />
1481 );
1482+ break;
1483 case "file-suppressed":
1484- return (
1485+ renderedItem = (
1486 <ReviewFileSuppressedBody
1487 message={item.message}
1488 actionLabel={item.actionLabel}
1489 fileId={item.fileId}
1490- viewportWidth={reviewListContentWidth}
1491+ viewportWidth={viewportWidth}
1492 onLoadDiffFile={handleRevealLargeDiff}
1493 />
1494 );
1495- case "hunk":
1496- return (
1497- <ReviewHunkRow
1498- header={item.row.header}
1499- context={item.row.context}
1500- viewportWidth={reviewListContentWidth}
1501- />
1502+ break;
1503+ case "hunk": {
1504+ const contentWidth = reviewContentWidthByFileId.get(item.fileId) ?? viewportWidth;
1505+ const gutterWidth = reviewGutterWidthByFileId.get(item.fileId) ?? 0;
1506+
1507+ renderedItem = (
1508+ <ReviewCodePanRow
1509+ key={item.id}
1510+ contentWidth={contentWidth}
1511+ gutterWidth={gutterWidth}
1512+ horizontalOffset={getReviewFileHorizontalOffset(item.fileId)}
1513+ leftGutter={<ReviewHunkGutter gutterWidth={gutterWidth} />}
1514+ viewportWidth={viewportWidth}
1515+ >
1516+ <ReviewHunkRow
1517+ header={item.row.header}
1518+ context={item.row.context}
1519+ viewportWidth={contentWidth}
1520+ />
1521+ </ReviewCodePanRow>
1522 );
1523+ break;
1524+ }
1525 case "line": {
1526- const file = reviewFileById.get(item.fileId);
1527- if (!file) {
1528- return null;
1529- }
1530-
1531- const fileLineRows = reviewLineRowsByFileId.get(file.id) ?? [];
1532- const lineIndex = reviewLineIndexByRowId.get(item.row.id);
1533- if (lineIndex === undefined) {
1534- return null;
1535- }
1536-
1537+ const fileLineRows = reviewLineRowsByFileId.get(item.file.id) ?? [];
1538 const pendingSelectionForFile =
1539 pendingCommentSelection &&
1540 pendingCommentSelection.sectionTitle === selectedSection.title &&
1541- pendingCommentSelection.filePath === file.path
1542+ pendingCommentSelection.filePath === item.file.path
1543 ? pendingCommentSelection
1544 : null;
1545 const selectedTargetForFile =
1546 activeCommentTarget &&
1547 activeCommentTarget.sectionTitle === selectedSection.title &&
1548- activeCommentTarget.filePath === file.path
1549+ activeCommentTarget.filePath === item.file.path
1550 ? activeCommentTarget
1551 : null;
1552 const highlightedFile =
1553- highlightedFilesById[file.id] ??
1554- getCachedHighlightedReviewFile(file, selectedTheme) ??
1555+ deferredHighlightedFilesById[item.file.id] ??
1556+ getCachedHighlightedReviewFile(item.file, selectedTheme) ??
1557 null;
1558+ const contentWidth = reviewContentWidthByFileId.get(item.fileId) ?? viewportWidth;
1559+ const gutterWidth = reviewGutterWidthByFileId.get(item.fileId) ?? 0;
1560
1561 if (highlightedFile === null) {
1562- const missingTokenKey = `${selectedSection.id}:${file.id}`;
1563+ const missingTokenKey = `${selectedSection.id}:${item.file.id}`;
1564 if (!loggedMissingReviewTokenKeys.has(missingTokenKey)) {
1565 loggedMissingReviewTokenKeys.add(missingTokenKey);
1566 logReviewDiffDiagnostic("rendering file without tokens", {
1567 sectionId: selectedSection.id,
1568- fileId: file.id,
1569- filePath: file.path,
1570- highlightedFileKnownInState: highlightedFilesById[file.id] !== undefined,
1571+ fileId: item.file.id,
1572+ filePath: item.file.path,
1573+ highlightedFileKnownInState:
1574+ deferredHighlightedFilesById[item.file.id] !== undefined,
1575 });
1576 }
1577 }
1578
1579 const selectionState =
1580- pendingSelectionForFile?.anchorIndex === lineIndex
1581+ pendingSelectionForFile?.anchorIndex === item.lineIndex
1582 ? ("anchor" as const)
1583 : selectedTargetForFile &&
1584- lineIndex >= selectedTargetForFile.startIndex &&
1585- lineIndex <= selectedTargetForFile.endIndex
1586+ item.lineIndex >= selectedTargetForFile.startIndex &&
1587+ item.lineIndex <= selectedTargetForFile.endIndex
1588 ? ("selected" as const)
1589 : null;
1590
1591- return (
1592- <ReviewLineRow
1593- line={item.row}
1594- tokens={getHighlightedTokensForLine(item.row, highlightedFile)}
1595- viewportWidth={reviewListContentWidth}
1596- selectionState={selectionState}
1597- onComment={() =>
1598- handlePressLine({
1599- sectionTitle: selectedSection.title,
1600- filePath: file.path,
1601- lines: fileLineRows,
1602- lineIndex,
1603- })
1604- }
1605- onStartRangeSelection={() =>
1606- handleStartRangeSelection({
1607- sectionTitle: selectedSection.title,
1608- filePath: file.path,
1609- lines: fileLineRows,
1610- lineIndex,
1611- })
1612+ renderedItem = (
1613+ <ReviewCodePanRow
1614+ key={item.id}
1615+ contentWidth={contentWidth}
1616+ gutterWidth={gutterWidth}
1617+ horizontalOffset={getReviewFileHorizontalOffset(item.fileId)}
1618+ leftGutter={
1619+ <ReviewLineGutter
1620+ change={item.row.change}
1621+ gutterWidth={gutterWidth}
1622+ lineNumber={getReviewUnifiedLineNumber(item.row)}
1623+ />
1624 }
1625- />
1626+ viewportWidth={viewportWidth}
1627+ >
1628+ <ReviewLineRow
1629+ line={item.row}
1630+ tokens={getHighlightedTokensForLine(item.row, highlightedFile)}
1631+ viewportWidth={contentWidth}
1632+ selectionState={selectionState}
1633+ onComment={() =>
1634+ handlePressLine({
1635+ sectionTitle: selectedSection.title,
1636+ filePath: item.file.path,
1637+ lines: fileLineRows,
1638+ lineIndex: item.lineIndex,
1639+ })
1640+ }
1641+ onStartRangeSelection={() =>
1642+ handleStartRangeSelection({
1643+ sectionTitle: selectedSection.title,
1644+ filePath: item.file.path,
1645+ lines: fileLineRows,
1646+ lineIndex: item.lineIndex,
1647+ })
1648+ }
1649+ />
1650+ </ReviewCodePanRow>
1651 );
1652+ break;
1653 }
1654 }
1655+
1656+ return renderedItem;
1657 },
1658 [
1659 activeCommentTarget,
1660@@ -1229,14 +1474,17 @@ export function ReviewSheet() {
1661 handleRevealLargeDiff,
1662 handleStartRangeSelection,
1663 handleToggleExpandedFile,
1664- highlightedFilesById,
1665+ handleToggleViewedFile,
1666+ getReviewFileHorizontalOffset,
1667+ deferredHighlightedFilesById,
1668 pendingCommentSelection,
1669- reviewFileById,
1670- reviewLineIndexByRowId,
1671+ reviewContentWidthByFileId,
1672+ reviewGutterWidthByFileId,
1673 reviewLineRowsByFileId,
1674- reviewListContentWidth,
1675 selectedSection,
1676 selectedTheme,
1677+ viewedFileIdSet,
1678+ viewportWidth,
1679 ],
1680 );
1681
1682@@ -1374,27 +1622,20 @@ export function ReviewSheet() {
1683 <View className="flex-1 bg-sheet">
1684 {selectedSection && parsedDiff.kind === "files" ? (
1685 <FlatList
1686- style={{ flex: 1 }}
1687+ style={{ flex: 1, width: viewportWidth }}
1688 contentInsetAdjustmentBehavior="never"
1689- contentInset={{ top: topContentInset }}
1690- contentOffset={{ x: 0, y: -topContentInset }}
1691- scrollIndicatorInsets={{ top: topContentInset }}
1692 data={reviewListItems}
1693 renderItem={renderReviewListItem}
1694 keyExtractor={(item) => item.id}
1695+ initialNumToRender={20}
1696+ maxToRenderPerBatch={20}
1697+ updateCellsBatchingPeriod={16}
1698+ windowSize={5}
1699+ removeClippedSubviews={false}
1700 keyboardShouldPersistTaps="handled"
1701 ListHeaderComponent={listHeader}
1702- stickyHeaderIndices={stickyHeaderIndices}
1703- removeClippedSubviews={false}
1704- initialNumToRender={24}
1705- maxToRenderPerBatch={16}
1706- updateCellsBatchingPeriod={16}
1707- windowSize={10}
1708- scrollEventThrottle={16}
1709- onViewableItemsChanged={onViewableItemsChangedRef.current}
1710- viewabilityConfig={viewabilityConfigRef.current}
1711 contentContainerStyle={{
1712- paddingTop: REVIEW_HEADER_SPACING,
1713+ paddingTop: topContentInset + REVIEW_HEADER_SPACING,
1714 paddingBottom: Math.max(insets.bottom, 18) + 18,
1715 }}
1716 />
1717diff --git a/apps/mobile/src/features/review/reviewDiffRendering.tsx b/apps/mobile/src/features/review/reviewDiffRendering.tsx
1718index d61924a62..3f2ae0160 100644
1719--- a/apps/mobile/src/features/review/reviewDiffRendering.tsx
1720+++ b/apps/mobile/src/features/review/reviewDiffRendering.tsx
1721@@ -11,6 +11,9 @@ export const REVIEW_MONO_FONT_FAMILY = Platform.select({
1722 default: "monospace",
1723 });
1724
1725+export const REVIEW_DIFF_LINE_HEIGHT = 26;
1726+const REVIEW_DELETE_STRIPE_COUNT = REVIEW_DIFF_LINE_HEIGHT / 2;
1727+
1728 export function renderVisibleWhitespace(value: string): string {
1729 const expandedTabs = value.replace(/\t/g, " ");
1730 return expandedTabs.replace(/^( +)/, (leading) => leading.replaceAll(" ", "\u00A0"));
1731@@ -37,10 +40,13 @@ function diffHighlightColor(change: ReviewRenderableLineRow["change"]): string |
1732 export function ReviewChangeBar(props: { readonly change: ReviewRenderableLineRow["change"] }) {
1733 if (props.change === "delete") {
1734 return (
1735- <View className="w-[5px] self-stretch overflow-hidden">
1736- <View className="flex-1 justify-between">
1737- {Array.from({ length: 6 }, (_, index) => (
1738- <View key={index} className="h-[2px] w-[5px] bg-rose-400" />
1739+ <View className="w-[5px] overflow-hidden" style={{ height: REVIEW_DIFF_LINE_HEIGHT }}>
1740+ <View>
1741+ {Array.from({ length: REVIEW_DELETE_STRIPE_COUNT }, (_, index) => (
1742+ <View key={index}>
1743+ <View className="w-[5px] bg-rose-400" style={{ height: 1 }} />
1744+ <View style={{ height: 1 }} />
1745+ </View>
1746 ))}
1747 </View>
1748 </View>
1749@@ -48,7 +54,7 @@ export function ReviewChangeBar(props: { readonly change: ReviewRenderableLineRo
1750 }
1751
1752 return (
1753- <View className="w-[5px] self-stretch overflow-hidden">
1754+ <View className="w-[5px] overflow-hidden" style={{ height: REVIEW_DIFF_LINE_HEIGHT }}>
1755 <View className={cn("h-full w-[5px] flex-1", changeBarTone(props.change))} />
1756 </View>
1757 );
1758@@ -63,6 +69,7 @@ export function DiffTokenText(props: {
1759 if (!props.tokens || props.tokens.length === 0) {
1760 return (
1761 <NativeText
1762+ numberOfLines={1}
1763 selectable
1764 className={cn("text-[13px] leading-[17px] font-medium text-foreground", props.className)}
1765 style={{ fontFamily: REVIEW_MONO_FONT_FAMILY }}
1766@@ -74,6 +81,7 @@ export function DiffTokenText(props: {
1767
1768 return (
1769 <NativeText
1770+ numberOfLines={1}
1771 selectable
1772 className={cn("text-[13px] leading-[17px] font-medium text-foreground", props.className)}
1773 style={{ fontFamily: REVIEW_MONO_FONT_FAMILY }}
1774diff --git a/apps/mobile/src/features/review/reviewHighlighterEngine.test.ts b/apps/mobile/src/features/review/reviewHighlighterEngine.test.ts
1775index d63a7a67c..5449fc6bf 100644
1776--- a/apps/mobile/src/features/review/reviewHighlighterEngine.test.ts
1777+++ b/apps/mobile/src/features/review/reviewHighlighterEngine.test.ts
1778@@ -6,9 +6,9 @@ import {
1779 } from "./reviewHighlighterEngine";
1780
1781 describe("resolveReviewHighlighterEnginePreference", () => {
1782- it("defaults invalid values to javascript", () => {
1783- expect(resolveReviewHighlighterEnginePreference(undefined)).toBe("javascript");
1784- expect(resolveReviewHighlighterEnginePreference("bogus")).toBe("javascript");
1785+ it("defaults invalid values to native", () => {
1786+ expect(resolveReviewHighlighterEnginePreference(undefined)).toBe("native");
1787+ expect(resolveReviewHighlighterEnginePreference("bogus")).toBe("native");
1788 });
1789
1790 it("accepts supported values", () => {
1791diff --git a/apps/mobile/src/features/review/reviewHighlighterEngine.ts b/apps/mobile/src/features/review/reviewHighlighterEngine.ts
1792index 5ef9f055a..428768537 100644
1793--- a/apps/mobile/src/features/review/reviewHighlighterEngine.ts
1794+++ b/apps/mobile/src/features/review/reviewHighlighterEngine.ts
1795@@ -11,7 +11,7 @@ export function resolveReviewHighlighterEnginePreference(
1796 case "native":
1797 return "native";
1798 default:
1799- return "javascript";
1800+ return "native";
1801 }
1802 }
1803
1804diff --git a/apps/mobile/src/features/review/reviewModel.test.ts b/apps/mobile/src/features/review/reviewModel.test.ts
1805index a24a99ceb..69a6e7261 100644
1806--- a/apps/mobile/src/features/review/reviewModel.test.ts
1807+++ b/apps/mobile/src/features/review/reviewModel.test.ts
1808@@ -238,7 +238,7 @@ describe("buildReviewParsedDiff", () => {
1809 });
1810 });
1811
1812- it("flattens expanded files into virtualizable review items", () => {
1813+ it("flattens expanded file rows into virtualized review items", () => {
1814 const file = makeRenderableFile({
1815 path: "apps/mobile/src/a.ts",
1816 rows: [
1817@@ -270,8 +270,19 @@ describe("buildReviewParsedDiff", () => {
1818
1819 expect(items).toEqual([
1820 expect.objectContaining({ kind: "file-header", fileId: file.id, expanded: true }),
1821- expect.objectContaining({ kind: "hunk", fileId: file.id, row: file.rows[0] }),
1822- expect.objectContaining({ kind: "line", fileId: file.id, row: file.rows[1] }),
1823+ expect.objectContaining({
1824+ kind: "hunk",
1825+ fileId: file.id,
1826+ file,
1827+ row: file.rows[0],
1828+ }),
1829+ expect.objectContaining({
1830+ kind: "line",
1831+ fileId: file.id,
1832+ file,
1833+ row: file.rows[1],
1834+ lineIndex: 0,
1835+ }),
1836 ]);
1837 });
1838
1839diff --git a/apps/mobile/src/features/review/reviewModel.ts b/apps/mobile/src/features/review/reviewModel.ts
1840index 27e6d7ae4..1cfbf358c 100644
1841--- a/apps/mobile/src/features/review/reviewModel.ts
1842+++ b/apps/mobile/src/features/review/reviewModel.ts
1843@@ -72,6 +72,7 @@ export interface ReviewHunkListItem {
1844 readonly kind: "hunk";
1845 readonly id: string;
1846 readonly fileId: string;
1847+ readonly file: ReviewRenderableFile;
1848 readonly row: ReviewRenderableHunkRow;
1849 }
1850
1851@@ -79,7 +80,9 @@ export interface ReviewLineListItem {
1852 readonly kind: "line";
1853 readonly id: string;
1854 readonly fileId: string;
1855+ readonly file: ReviewRenderableFile;
1856 readonly row: ReviewRenderableLineRow;
1857+ readonly lineIndex: number;
1858 }
1859
1860 export type ReviewListItem =
1861@@ -308,7 +311,7 @@ export function getReviewFilePreviewState(file: ReviewRenderableFile): ReviewFil
1862 }
1863
1864 // The flattened review list item model is inspired by pierre/diffs' iterator-first
1865-// virtualization architecture, adapted here for React Native and LegendList.
1866+// virtualization architecture, adapted here for React Native virtualization.
1867 // Original project: https://github.com/pingdotgg/pierre/tree/main/packages/diffs
1868 // Reference files:
1869 // - src/utils/iterateOverDiff.ts
1870@@ -350,12 +353,14 @@ export function buildReviewListItems(input: {
1871 }
1872 }
1873
1874- file.rows.forEach((row) => {
1875+ let lineIndex = 0;
1876+ file.rows.forEach((row, rowIndex) => {
1877 if (row.kind === "hunk") {
1878 items.push({
1879 kind: "hunk",
1880- id: row.id,
1881+ id: `${file.id}:row:${rowIndex}:${row.id}`,
1882 fileId: file.id,
1883+ file,
1884 row,
1885 });
1886 return;
1887@@ -363,10 +368,13 @@ export function buildReviewListItems(input: {
1888
1889 items.push({
1890 kind: "line",
1891- id: row.id,
1892+ id: `${file.id}:row:${rowIndex}:${row.id}`,
1893 fileId: file.id,
1894+ file,
1895 row,
1896+ lineIndex,
1897 });
1898+ lineIndex += 1;
1899 });
1900 });
1901
1902diff --git a/apps/mobile/src/features/review/reviewState.ts b/apps/mobile/src/features/review/reviewState.ts
1903index 06134db7d..c116f93fe 100644
1904--- a/apps/mobile/src/features/review/reviewState.ts
1905+++ b/apps/mobile/src/features/review/reviewState.ts
1906@@ -64,6 +64,13 @@ const reviewRevealedLargeFileIdsByThreadKeyAtom = Atom.family((threadKey: string
1907 ),
1908 );
1909
1910+const reviewViewedFileIdsByThreadKeyAtom = Atom.family((threadKey: string) =>
1911+ Atom.make(EMPTY_REVIEW_SECTION_FILE_IDS).pipe(
1912+ Atom.keepAlive,
1913+ Atom.withLabel(`mobile:review:viewed-file-ids:${threadKey}`),
1914+ ),
1915+);
1916+
1917 const reviewParsedDiffBySectionCacheKeyAtom = Atom.family((cacheKey: string) =>
1918 Atom.make<{ readonly diff: string | null; readonly parsed: ReviewParsedDiff } | null>(null).pipe(
1919 Atom.keepAlive,
1920@@ -110,6 +117,9 @@ export function useReviewCacheForThread(input: {
1921 ? reviewRevealedLargeFileIdsByThreadKeyAtom(threadKey)
1922 : EMPTY_REVIEW_SECTION_FILE_IDS_ATOM,
1923 );
1924+ const viewedFileIdsBySection = useAtomValue(
1925+ threadKey ? reviewViewedFileIdsByThreadKeyAtom(threadKey) : EMPTY_REVIEW_SECTION_FILE_IDS_ATOM,
1926+ );
1927
1928 return {
1929 threadKey,
1930@@ -118,6 +128,7 @@ export function useReviewCacheForThread(input: {
1931 selectedSectionId,
1932 expandedFileIdsBySection,
1933 revealedLargeFileIdsBySection,
1934+ viewedFileIdsBySection,
1935 };
1936 }
1937
1938@@ -169,6 +180,20 @@ export function updateReviewRevealedLargeFileIds(
1939 });
1940 }
1941
1942+export function updateReviewViewedFileIds(
1943+ threadKey: string,
1944+ sectionId: string,
1945+ update: (current: ReadonlyArray<string> | undefined) => ReadonlyArray<string> | undefined,
1946+): void {
1947+ const atom = reviewViewedFileIdsByThreadKeyAtom(threadKey);
1948+ const current = appAtomRegistry.get(atom);
1949+ const nextValue = update(current[sectionId]);
1950+ appAtomRegistry.set(atom, {
1951+ ...current,
1952+ [sectionId]: nextValue,
1953+ });
1954+}
1955+
1956 export function getCachedReviewParsedDiff(input: {
1957 readonly threadKey: string | null;
1958 readonly sectionId: string | null;
1959diff --git a/apps/mobile/src/features/review/shikiReviewHighlighter.test.ts b/apps/mobile/src/features/review/shikiReviewHighlighter.test.ts
1960index 05b5c9213..402d00668 100644
1961--- a/apps/mobile/src/features/review/shikiReviewHighlighter.test.ts
1962+++ b/apps/mobile/src/features/review/shikiReviewHighlighter.test.ts
1963@@ -24,7 +24,7 @@ function makeRenderableFile(
1964 describe("highlightReviewFile", () => {
1965 it("preserves one highlighted token row per diff line even without trailing newlines", async () => {
1966 const file = makeRenderableFile({
1967- path: "apps/mobile/src/example.test.ts",
1968+ path: "apps/mobile/src/example.txt",
1969 additionLines: [
1970 'const items = ["a"];',
1971 'expect(items).toEqual(["a"]);',
1972@@ -36,15 +36,23 @@ describe("highlightReviewFile", () => {
1973 const highlighted = await highlightReviewFile(file, "light");
1974
1975 expect(highlighted.additionLines).toHaveLength(file.additionLines.length);
1976- expect(highlighted.additionLines[0]?.some((token) => token.content === "const")).toBe(true);
1977- expect(highlighted.additionLines[1]?.some((token) => token.content === "expect")).toBe(true);
1978- expect(highlighted.additionLines[2]?.some((token) => token.content === "const")).toBe(true);
1979- expect(highlighted.additionLines[3]?.some((token) => token.content === "expect")).toBe(true);
1980+ expect(highlighted.additionLines[0]?.map((token) => token.content).join("")).toBe(
1981+ file.additionLines[0],
1982+ );
1983+ expect(highlighted.additionLines[1]?.map((token) => token.content).join("")).toBe(
1984+ file.additionLines[1],
1985+ );
1986+ expect(highlighted.additionLines[2]?.map((token) => token.content).join("")).toBe(
1987+ file.additionLines[2],
1988+ );
1989+ expect(highlighted.additionLines[3]?.map((token) => token.content).join("")).toBe(
1990+ file.additionLines[3],
1991+ );
1992 });
1993
1994 it("adds word-alt diff emphasis for paired deletion and addition lines", async () => {
1995 const file = makeRenderableFile({
1996- path: "apps/mobile/src/example-inline-diff.test.ts",
1997+ path: "apps/mobile/src/example-inline-diff.txt",
1998 additionLines: ["const after = 2;"],
1999 deletionLines: ["const before = 1;"],
2000 rows: [
2001@@ -82,7 +90,7 @@ describe("highlightReviewFile", () => {
2002 it("falls back to plain tokens for very long lines", async () => {
2003 const longLine = `const value = "${"a".repeat(1_100)}";`;
2004 const file = makeRenderableFile({
2005- path: "apps/mobile/src/example-long-line.ts",
2006+ path: "apps/mobile/src/example-long-line.txt",
2007 additionLines: [longLine],
2008 rows: [
2009 {
2010diff --git a/apps/mobile/src/features/review/shikiReviewHighlighter.ts b/apps/mobile/src/features/review/shikiReviewHighlighter.ts
2011index f7a5c4125..eb6bf6973 100644
2012--- a/apps/mobile/src/features/review/shikiReviewHighlighter.ts
2013+++ b/apps/mobile/src/features/review/shikiReviewHighlighter.ts
2014@@ -1,5 +1,14 @@
2015 import { createHighlighterCore, type HighlighterCore } from "@shikijs/core";
2016 import { createJavaScriptRegexEngine } from "@shikijs/engine-javascript";
2017+import bashLanguage from "@shikijs/langs/bash";
2018+import javascriptLanguage from "@shikijs/langs/javascript";
2019+import jsonLanguage from "@shikijs/langs/json";
2020+import jsxLanguage from "@shikijs/langs/jsx";
2021+import tsxLanguage from "@shikijs/langs/tsx";
2022+import typescriptLanguage from "@shikijs/langs/typescript";
2023+import yamlLanguage from "@shikijs/langs/yaml";
2024+import githubDarkDefault from "@shikijs/themes/github-dark-default";
2025+import githubLightDefault from "@shikijs/themes/github-light-default";
2026 import { getFiletypeFromFileName } from "@pierre/diffs/utils";
2027
2028 import {
2029@@ -11,6 +20,7 @@ import type { ReviewRenderableFile, ReviewRenderableLineRow } from "./reviewMode
2030 import { applyDiffRangesToTokens, computeWordAltDiffRanges } from "./reviewWordDiffs";
2031
2032 export type ReviewDiffTheme = "light" | "dark";
2033+export type { ReviewHighlighterEngine };
2034
2035 export interface ReviewHighlightedToken {
2036 content: string;
2037@@ -24,12 +34,19 @@ export interface ReviewHighlightedFile {
2038 readonly deletionLines: ReadonlyArray<ReadonlyArray<ReviewHighlightedToken>>;
2039 }
2040
2041+export interface ReviewHighlightFileProgress {
2042+ readonly highlightedFile: ReviewHighlightedFile;
2043+ readonly complete: boolean;
2044+ readonly highlightedLineCount: number;
2045+}
2046+
2047 const SHIKI_THEME_NAME_BY_SCHEME = {
2048 light: "github-light-default",
2049 dark: "github-dark-default",
2050 } as const;
2051 const REVIEW_HIGHLIGHTER_ENGINE_ENV_VALUE =
2052- process.env.EXPO_PUBLIC_REVIEW_HIGHLIGHTER_ENGINE ?? "javascript";
2053+ process.env.EXPO_PUBLIC_REVIEW_HIGHLIGHTER_ENGINE ??
2054+ (process.env.NODE_ENV === "test" ? "javascript" : "native");
2055 const REVIEW_HIGHLIGHTER_ENGINE_PREFERENCE = resolveReviewHighlighterEnginePreference(
2056 REVIEW_HIGHLIGHTER_ENGINE_ENV_VALUE,
2057 );
2058@@ -38,12 +55,30 @@ const REVIEW_HIGHLIGHTER_DISABLE_RESULT_CACHE = resolveReviewHighlighterBooleanF
2059 false,
2060 );
2061 const REVIEW_HIGHLIGHT_RESULT_CACHE_LIMIT = 8;
2062-const REVIEW_HIGHLIGHT_CHUNK_LINE_THRESHOLD = 40;
2063-const REVIEW_HIGHLIGHT_CHUNK_SIZE = 20;
2064+const REVIEW_HIGHLIGHT_CHUNK_LINE_THRESHOLD = 8;
2065+const REVIEW_HIGHLIGHT_CHUNK_SIZE = 200;
2066 const REVIEW_TOKENIZE_MAX_LINE_LENGTH = 1_000;
2067 const highlightCache = new Map<string, Promise<ReviewHighlightedFile>>();
2068 const resolvedHighlightCache = new Map<string, ReviewHighlightedFile>();
2069-const loadedLanguages = new Set<string>(["text"]);
2070+const REVIEW_INITIAL_LANGUAGE_MODULES = [
2071+ bashLanguage,
2072+ javascriptLanguage,
2073+ jsonLanguage,
2074+ jsxLanguage,
2075+ tsxLanguage,
2076+ typescriptLanguage,
2077+ yamlLanguage,
2078+] satisfies Parameters<typeof createHighlighterCore>[0]["langs"];
2079+const loadedLanguages = new Set<string>([
2080+ "text",
2081+ "bash",
2082+ "javascript",
2083+ "json",
2084+ "jsx",
2085+ "tsx",
2086+ "typescript",
2087+ "yaml",
2088+]);
2089 const languageLoadingPromises = new Map<string, Promise<boolean>>();
2090 const languageImports: Partial<Record<string, () => Promise<unknown>>> = {
2091 javascript: () => import("@shikijs/langs/javascript"),
2092@@ -215,21 +250,13 @@ function joinPatchLines(lines: ReadonlyArray<string>): string {
2093
2094 function waitForNextFrame(): Promise<void> {
2095 return new Promise((resolve) => {
2096- if (typeof requestAnimationFrame === "function") {
2097- requestAnimationFrame(() => resolve());
2098- return;
2099- }
2100-
2101 setTimeout(resolve, 0);
2102 });
2103 }
2104
2105 async function getHighlighter(): Promise<HighlighterCore> {
2106 if (!highlighterPromise) {
2107- const configuredHighlighterPromise = Promise.all([
2108- import("@shikijs/themes/github-light-default"),
2109- import("@shikijs/themes/github-dark-default"),
2110- ]).then(async ([lightThemeModule, darkThemeModule]) => {
2111+ const configuredHighlighterPromise = (async () => {
2112 let nativeEngineAvailable = false;
2113
2114 logReviewHighlighterDiagnostic("initializing", {
2115@@ -238,12 +265,11 @@ async function getHighlighter(): Promise<HighlighterCore> {
2116 resultCacheDisabled: REVIEW_HIGHLIGHTER_DISABLE_RESULT_CACHE,
2117 });
2118
2119- const themes = [lightThemeModule.default, darkThemeModule.default];
2120+ const themes = [githubLightDefault, githubDarkDefault];
2121
2122 if (REVIEW_HIGHLIGHTER_ENGINE_PREFERENCE !== "javascript") {
2123 try {
2124 const nativeEngineModule = await import("react-native-shiki-engine");
2125- logReviewHighlighterDiagnostic("imported react-native-shiki-engine");
2126 nativeEngineAvailable = nativeEngineModule.isNativeEngineAvailable();
2127 logReviewHighlighterDiagnostic("checked native engine availability", {
2128 nativeEngineAvailable,
2129@@ -253,7 +279,7 @@ async function getHighlighter(): Promise<HighlighterCore> {
2130 logReviewHighlighterDiagnostic("creating native regex engine");
2131 const highlighter = await createHighlighterCore({
2132 themes,
2133- langs: [],
2134+ langs: REVIEW_INITIAL_LANGUAGE_MODULES,
2135 engine: nativeEngineModule.createNativeEngine(),
2136 });
2137 logReviewHighlighterDiagnostic("using native engine");
2138@@ -281,7 +307,7 @@ async function getHighlighter(): Promise<HighlighterCore> {
2139 );
2140 const highlighter = await createHighlighterCore({
2141 themes,
2142- langs: [],
2143+ langs: REVIEW_INITIAL_LANGUAGE_MODULES,
2144 engine: createJavaScriptRegexEngine(),
2145 });
2146 logReviewHighlighterDiagnostic("using javascript engine", {
2147@@ -291,7 +317,7 @@ async function getHighlighter(): Promise<HighlighterCore> {
2148 highlighter,
2149 engine,
2150 };
2151- });
2152+ })();
2153
2154 highlighterPromise = configuredHighlighterPromise
2155 .then((result) => result.highlighter)
2156@@ -316,11 +342,52 @@ export async function getActiveReviewHighlighterEngine(): Promise<ReviewHighligh
2157 return activeHighlighterEnginePromise ?? Promise.resolve("javascript");
2158 }
2159
2160+export async function prepareReviewHighlighter(): Promise<void> {
2161+ await getHighlighter();
2162+}
2163+
2164+export async function prepareReviewHighlighterLanguages(
2165+ languages: ReadonlyArray<string>,
2166+): Promise<void> {
2167+ const highlighter = await getHighlighter();
2168+ await Promise.all(
2169+ languages.map(async (language) => {
2170+ const candidate = resolveLanguageAlias(language);
2171+ if (candidate === "text" || !(candidate in languageImports)) {
2172+ return;
2173+ }
2174+
2175+ await loadSingleLanguage(highlighter, candidate);
2176+ }),
2177+ );
2178+}
2179+
2180 function resolveLanguageAlias(language: string): string {
2181 const normalized = language.toLowerCase();
2182 return languageAliases[normalized] ?? normalized;
2183 }
2184
2185+function resolveLoadedLanguageFromPath(
2186+ path: string,
2187+ languageHint: string | null = null,
2188+): string | null {
2189+ const detectedLanguage = languageHint ?? getFiletypeFromFileName(path);
2190+ if (!detectedLanguage) {
2191+ return "text";
2192+ }
2193+
2194+ const candidate = resolveLanguageAlias(detectedLanguage);
2195+ if (candidate === "text" || candidate === "ansi") {
2196+ return "text";
2197+ }
2198+
2199+ if (!(candidate in languageImports)) {
2200+ return "text";
2201+ }
2202+
2203+ return loadedLanguages.has(candidate) ? candidate : null;
2204+}
2205+
2206 async function loadSingleLanguage(
2207 highlighter: HighlighterCore,
2208 language: string,
2209@@ -360,6 +427,11 @@ async function resolveLanguageFromPath(
2210 path: string,
2211 languageHint: string | null = null,
2212 ): Promise<string> {
2213+ const loadedLanguage = resolveLoadedLanguageFromPath(path, languageHint);
2214+ if (loadedLanguage) {
2215+ return loadedLanguage;
2216+ }
2217+
2218 const detectedLanguage = languageHint ?? getFiletypeFromFileName(path);
2219 if (!detectedLanguage) {
2220 return "text";
2221@@ -374,8 +446,12 @@ async function resolveLanguageFromPath(
2222 return "text";
2223 }
2224
2225+ if (loadedLanguages.has(candidate)) {
2226+ return candidate;
2227+ }
2228+
2229 const highlighter = await getHighlighter();
2230- const loaded = await loadSingleLanguage(highlighter, resolveLanguageAlias(candidate));
2231+ const loaded = await loadSingleLanguage(highlighter, candidate);
2232 if (!loaded) {
2233 return "text";
2234 }
2235@@ -384,7 +460,10 @@ async function resolveLanguageFromPath(
2236 }
2237
2238 async function resolveLanguage(file: ReviewRenderableFile): Promise<string> {
2239- return resolveLanguageFromPath(file.path, file.languageHint);
2240+ return (
2241+ resolveLoadedLanguageFromPath(file.path, file.languageHint) ??
2242+ (await resolveLanguageFromPath(file.path, file.languageHint))
2243+ );
2244 }
2245
2246 function normalizeHighlightedLines(
2247@@ -399,6 +478,18 @@ function normalizeHighlightedLines(
2248 );
2249 }
2250
2251+function makePlainHighlightedLines(
2252+ lines: ReadonlyArray<string>,
2253+): ReadonlyArray<ReadonlyArray<ReviewHighlightedToken>> {
2254+ return lines.map((line) => [
2255+ {
2256+ content: stripTrailingNewline(line),
2257+ color: null,
2258+ fontStyle: null,
2259+ },
2260+ ]);
2261+}
2262+
2263 function applyWordAltDiffHighlightsToFile(
2264 file: ReviewRenderableFile,
2265 highlighted: ReviewHighlightedFile,
2266@@ -594,6 +685,67 @@ async function highlightLines(
2267 return highlightedLines;
2268 }
2269
2270+async function highlightPatchLinesInChunks(input: {
2271+ readonly lines: ReadonlyArray<string>;
2272+ readonly language: string;
2273+ readonly theme: string;
2274+ readonly onChunk: (
2275+ startIndex: number,
2276+ tokens: ReadonlyArray<ReadonlyArray<ReviewHighlightedToken>>,
2277+ ) => void;
2278+}): Promise<ReadonlyArray<ReadonlyArray<ReviewHighlightedToken>>> {
2279+ if (input.lines.length === 0) {
2280+ return [];
2281+ }
2282+
2283+ const highlighter = await getHighlighter();
2284+ const highlightedLines: Array<ReadonlyArray<ReviewHighlightedToken>> = [];
2285+
2286+ for (
2287+ let startIndex = 0;
2288+ startIndex < input.lines.length;
2289+ startIndex += REVIEW_HIGHLIGHT_CHUNK_SIZE
2290+ ) {
2291+ const lineChunk = input.lines.slice(startIndex, startIndex + REVIEW_HIGHLIGHT_CHUNK_SIZE);
2292+ const chunkTokens: Array<ReadonlyArray<ReviewHighlightedToken>> = [];
2293+ const tokenizableLines: string[] = [];
2294+ const tokenizableIndexes: number[] = [];
2295+
2296+ lineChunk.forEach((line, index) => {
2297+ const strippedLine = stripTrailingNewline(line);
2298+ if (strippedLine.length > REVIEW_TOKENIZE_MAX_LINE_LENGTH) {
2299+ chunkTokens[index] = [{ content: strippedLine, color: null, fontStyle: null }];
2300+ return;
2301+ }
2302+
2303+ tokenizableIndexes.push(index);
2304+ tokenizableLines.push(strippedLine);
2305+ });
2306+
2307+ if (tokenizableLines.length > 0) {
2308+ const tokenLines = highlighter.codeToTokensBase(tokenizableLines.join("\n"), {
2309+ lang: input.language,
2310+ theme: input.theme,
2311+ });
2312+ const normalizedTokenLines = normalizeHighlightedLines(tokenLines);
2313+
2314+ tokenizableIndexes.forEach((chunkIndex, tokenIndex) => {
2315+ chunkTokens[chunkIndex] = normalizedTokenLines[tokenIndex] ?? [];
2316+ });
2317+ }
2318+
2319+ const completedChunk = lineChunk.map((_, index) => chunkTokens[index] ?? []);
2320+ highlightedLines.push(...completedChunk);
2321+ input.onChunk(startIndex, completedChunk);
2322+
2323+ if (startIndex + REVIEW_HIGHLIGHT_CHUNK_SIZE < input.lines.length) {
2324+ await waitForNextFrame();
2325+ }
2326+ }
2327+
2328+ return highlightedLines;
2329+}
2330+
2331 function getHighlightCacheKey(file: ReviewRenderableFile, theme: ReviewDiffTheme): string {
2332 return `${SHIKI_THEME_NAME_BY_SCHEME[theme]}:${file.cacheKey}`;
2333 }
2334@@ -667,7 +819,28 @@ export async function highlightReviewFile(
2335 deletionLineCount: file.deletionLines.length,
2336 rowCount: file.rows.length,
2337 });
2338- const language = await resolveLanguage(file);
2339+ const loadedLanguage = resolveLoadedLanguageFromPath(file.path, file.languageHint);
2340+ const language = loadedLanguage ?? (await resolveLanguage(file));
2341+ if (language === "text") {
2342+ const highlighted = applyWordAltDiffHighlightsToFile(file, {
2343+ additionLines: makePlainHighlightedLines(file.additionLines),
2344+ deletionLines: makePlainHighlightedLines(file.deletionLines),
2345+ });
2346+ if (!REVIEW_HIGHLIGHTER_DISABLE_RESULT_CACHE) {
2347+ storeResolvedHighlightedFile(cacheKey, highlighted);
2348+ }
2349+ logReviewHighlighterDiagnostic("file highlight complete", {
2350+ fileId: file.id,
2351+ filePath: file.path,
2352+ theme,
2353+ language,
2354+ highlightedAdditionLineCount: highlighted.additionLines.length,
2355+ highlightedDeletionLineCount: highlighted.deletionLines.length,
2356+ durationMs: Date.now() - startedAt,
2357+ });
2358+ return highlighted;
2359+ }
2360+
2361 const additionLines = await highlightLines(
2362 joinPatchLines(file.additionLines),
2363 language,
2364@@ -707,6 +880,113 @@ export async function highlightReviewFile(
2365 });
2366 }
2367
2368+export async function streamHighlightReviewFile(
2369+ file: ReviewRenderableFile,
2370+ theme: ReviewDiffTheme,
2371+ onProgress: (progress: ReviewHighlightFileProgress) => void,
2372+): Promise<ReviewHighlightedFile> {
2373+ const shikiTheme = SHIKI_THEME_NAME_BY_SCHEME[theme];
2374+ const cacheKey = getHighlightCacheKey(file, theme);
2375+ if (!REVIEW_HIGHLIGHTER_DISABLE_RESULT_CACHE) {
2376+ const resolved = resolvedHighlightCache.get(cacheKey);
2377+ if (resolved) {
2378+ onProgress({
2379+ highlightedFile: resolved,
2380+ complete: true,
2381+ highlightedLineCount: resolved.additionLines.length + resolved.deletionLines.length,
2382+ });
2383+ return resolved;
2384+ }
2385+ }
2386+
2387+ const startedAt = Date.now();
2388+ logReviewHighlighterDiagnostic("file stream highlight start", {
2389+ fileId: file.id,
2390+ filePath: file.path,
2391+ theme,
2392+ additionLineCount: file.additionLines.length,
2393+ deletionLineCount: file.deletionLines.length,
2394+ rowCount: file.rows.length,
2395+ });
2396+
2397+ const loadedLanguage = resolveLoadedLanguageFromPath(file.path, file.languageHint);
2398+ const language = loadedLanguage ?? (await resolveLanguage(file));
2399+ if (language === "text") {
2400+ const highlighted = applyWordAltDiffHighlightsToFile(file, {
2401+ additionLines: makePlainHighlightedLines(file.additionLines),
2402+ deletionLines: makePlainHighlightedLines(file.deletionLines),
2403+ });
2404+ if (!REVIEW_HIGHLIGHTER_DISABLE_RESULT_CACHE) {
2405+ storeResolvedHighlightedFile(cacheKey, highlighted);
2406+ }
2407+ onProgress({
2408+ highlightedFile: highlighted,
2409+ complete: true,
2410+ highlightedLineCount: highlighted.additionLines.length + highlighted.deletionLines.length,
2411+ });
2412+ logReviewHighlighterDiagnostic("file stream highlight complete", {
2413+ fileId: file.id,
2414+ filePath: file.path,
2415+ theme,
2416+ language,
2417+ highlightedAdditionLineCount: highlighted.additionLines.length,
2418+ highlightedDeletionLineCount: highlighted.deletionLines.length,
2419+ highlightedLineCount: highlighted.additionLines.length + highlighted.deletionLines.length,
2420+ durationMs: Date.now() - startedAt,
2421+ });
2422+ return highlighted;
2423+ }
2424+
2425+ const additionLines: Array<ReadonlyArray<ReviewHighlightedToken>> = [];
2426+ const deletionLines: Array<ReadonlyArray<ReviewHighlightedToken>> = [];
2427+ let highlightedLineCount = 0;
2428+
2429+ await highlightPatchLinesInChunks({
2430+ lines: file.additionLines,
2431+ language,
2432+ theme: shikiTheme,
2433+ onChunk: (startIndex, tokens) => {
2434+ tokens.forEach((lineTokens, index) => {
2435+ additionLines[startIndex + index] = lineTokens;
2436+ });
2437+ highlightedLineCount += tokens.length;
2438+ },
2439+ });
2440+ await waitForNextFrame();
2441+ await highlightPatchLinesInChunks({
2442+ lines: file.deletionLines,
2443+ language,
2444+ theme: shikiTheme,
2445+ onChunk: (startIndex, tokens) => {
2446+ tokens.forEach((lineTokens, index) => {
2447+ deletionLines[startIndex + index] = lineTokens;
2448+ });
2449+ highlightedLineCount += tokens.length;
2450+ },
2451+ });
2452+
2453+ const highlighted = applyWordAltDiffHighlightsToFile(file, { additionLines, deletionLines });
2454+ if (!REVIEW_HIGHLIGHTER_DISABLE_RESULT_CACHE) {
2455+ storeResolvedHighlightedFile(cacheKey, highlighted);
2456+ }
2457+ onProgress({
2458+ highlightedFile: highlighted,
2459+ complete: true,
2460+ highlightedLineCount,
2461+ });
2462+ logReviewHighlighterDiagnostic("file stream highlight complete", {
2463+ fileId: file.id,
2464+ filePath: file.path,
2465+ theme,
2466+ language,
2467+ highlightedAdditionLineCount: highlighted.additionLines.length,
2468+ highlightedDeletionLineCount: highlighted.deletionLines.length,
2469+ highlightedLineCount,
2470+ durationMs: Date.now() - startedAt,
2471+ });
2472+ return highlighted;
2473+}
2474+
2475 export async function highlightReviewSelectedLines(input: {
2476 readonly filePath: string;
2477 readonly lines: ReadonlyArray<ReviewRenderableLineRow>;
2478@@ -717,7 +997,9 @@ export async function highlightReviewSelectedLines(input: {
2479 return {};
2480 }
2481
2482- const language = await resolveLanguageFromPath(input.filePath, input.languageHint ?? null);
2483+ const loadedLanguage = resolveLoadedLanguageFromPath(input.filePath, input.languageHint ?? null);
2484+ const language =
2485+ loadedLanguage ?? (await resolveLanguageFromPath(input.filePath, input.languageHint ?? null));
2486 const shikiTheme = SHIKI_THEME_NAME_BY_SCHEME[input.theme];
2487 const additionLikeLines = input.lines
2488 .filter((line) => line.change !== "delete")
2489diff --git a/apps/mobile/docs/review-profiling.md b/apps/mobile/docs/review-profiling.md
2490new file mode 100644
2491index 000000000..6977eaf6e
2492--- /dev/null
2493+++ b/apps/mobile/docs/review-profiling.md
2494@@ -0,0 +1,80 @@
2495+# Review Screen Profiling
2496+
2497+Use this when the mobile review screen is slow or crashes while opening large diffs.
2498+
2499+## Preferred Capture: React Native DevTools Performance
2500+
2501+This app is on Expo SDK 55 / React Native 0.83 with Hermes, so the best first trace is the React Native DevTools Performance recording. The review screen also emits `t3.review.*` user timing marks in development builds so the trace can show parse, list-building, row indexing, and syntax-highlighting work.
2502+
2503+1. Start the development client:
2504+
2505+ ```sh
2506+ cd apps/mobile
2507+ bun dev:client
2508+ ```
2509+
2510+2. Open the app in the iOS Simulator or on the device using the development client.
2511+
2512+3. In the terminal running Expo, press `j` to open React Native DevTools.
2513+
2514+4. In DevTools, open the `Performance` panel.
2515+
2516+5. Start recording.
2517+
2518+6. In the app, reproduce the slow path:
2519+ - Navigate to the thread.
2520+ - Open `Files Changed`.
2521+ - Select the largest review source.
2522+ - Expand a few large files or tap `Load diff`.
2523+ - Scroll until the app is clearly slow or until just before it crashes.
2524+
2525+7. Stop recording.
2526+
2527+8. Export or save the Performance recording as a JSON trace.
2528+
2529+Send that exported trace file here. Also include the device/simulator model and whether it was iOS or Android.
2530+
2531+## Android Fallback: Hermes Sampling Profile
2532+
2533+Use this if the app crashes before DevTools can export a trace, or if we need deeper JavaScript stack samples.
2534+
2535+1. Run Android dev client:
2536+
2537+ ```sh
2538+ cd apps/mobile
2539+ bun android:dev
2540+ bun dev:client
2541+ ```
2542+
2543+2. Open the developer menu from the Expo terminal with `d`.
2544+
2545+3. Select `Enable Sampling Profiler`.
2546+
2547+4. Reproduce the review-screen slowdown.
2548+
2549+5. Open the developer menu again with `d`.
2550+
2551+6. Select `Disable Sampling Profiler`.
2552+
2553+7. Pull and convert the Hermes profile:
2554+
2555+ ```sh
2556+ cd apps/mobile
2557+ mkdir -p profiles/review
2558+ bunx react-native profile-hermes profiles/review
2559+ ```
2560+
2561+8. Send the generated Chrome trace/profile file from `apps/mobile/profiles/review`.
2562+
2563+For the development app variant, the Android package is `com.t3tools.t3code.dev`.
2564+
2565+## What To Capture
2566+
2567+For the first trace, do not optimize the repro. We want the slowest realistic case:
2568+
2569+- A diff with many files and large line counts.
2570+- At least one `Load diff` action for a suppressed large diff.
2571+- One vertical scroll pass after the content appears.
2572+- One horizontal scroll of a long file, if that is part of the slowdown.
2573+
2574+If the app crashes, note the last visible action before the crash and attach device logs if available.
2575diff --git a/apps/mobile/src/app/debug/syntax-highlight.tsx b/apps/mobile/src/app/debug/syntax-highlight.tsx
2576new file mode 100644
2577index 000000000..c2a36d126
2578--- /dev/null
2579+++ b/apps/mobile/src/app/debug/syntax-highlight.tsx
2580@@ -0,0 +1,423 @@
2581+import { createHighlighterCore, type HighlighterCore } from "@shikijs/core";
2582+import { createJavaScriptRegexEngine } from "@shikijs/engine-javascript";
2583+import typescriptLanguage from "@shikijs/langs/typescript";
2584+import githubDarkDefault from "@shikijs/themes/github-dark-default";
2585+import githubLightDefault from "@shikijs/themes/github-light-default";
2586+import Stack from "expo-router/stack";
2587+import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";
2588+import {
2589+ FlatList,
2590+ Pressable,
2591+ Text as NativeText,
2592+ type ListRenderItemInfo,
2593+ useColorScheme,
2594+ useWindowDimensions,
2595+ View,
2596+} from "react-native";
2597+import { useSafeAreaInsets } from "react-native-safe-area-context";
2598+
2599+import { AppText as Text } from "../../components/AppText";
2600+import { cn } from "../../lib/cn";
2601+import { useThemeColor } from "../../lib/useThemeColor";
2602+
2603+type DebugHighlightEngine = "native" | "javascript";
2604+
2605+type DebugToken = {
2606+ readonly content: string;
2607+ readonly color: string | null;
2608+ readonly fontStyle: number | null;
2609+};
2610+
2611+type DebugLine = {
2612+ readonly id: string;
2613+ readonly chunkIndex: number;
2614+ readonly indexInChunk: number;
2615+ readonly lineNumber: number;
2616+ readonly content: string;
2617+};
2618+
2619+type DebugHighlighterHandle = {
2620+ readonly engine: DebugHighlightEngine;
2621+ readonly tokenize: (
2622+ code: string,
2623+ options: { readonly lang: string; readonly theme: string },
2624+ ) => ReadonlyArray<ReadonlyArray<DebugToken>>;
2625+};
2626+
2627+const DEBUG_LINE_COUNT = 10_000;
2628+const DEBUG_CHUNK_SIZE = 500;
2629+const DEBUG_LINE_HEIGHT = 24;
2630+const DEBUG_GUTTER_WIDTH = 58;
2631+const DEBUG_CONTENT_WIDTH = 3_200;
2632+const DEBUG_MONO_FONT_FAMILY = "BerkeleyMono-Regular";
2633+const DEBUG_THEME_NAME_BY_SCHEME = {
2634+ dark: "github-dark-default",
2635+ light: "github-light-default",
2636+} as const;
2637+
2638+let nativeHighlighterPromise: Promise<DebugHighlighterHandle> | null = null;
2639+let javascriptHighlighterPromise: Promise<DebugHighlighterHandle> | null = null;
2640+
2641+function waitForNextFrame(): Promise<void> {
2642+ return new Promise((resolve) => setTimeout(resolve, 0));
2643+}
2644+
2645+function normalizeTokens(
2646+ tokenLines: ReadonlyArray<ReadonlyArray<{ content: string; color?: string; fontStyle?: number }>>,
2647+): ReadonlyArray<ReadonlyArray<DebugToken>> {
2648+ return tokenLines.map((line) =>
2649+ line.map((token) => ({
2650+ content: token.content,
2651+ color: token.color ?? null,
2652+ fontStyle: token.fontStyle ?? null,
2653+ })),
2654+ );
2655+}
2656+
2657+function makeDebugCodeLine(index: number): string {
2658+ const label = `generatedLine${String(index).padStart(5, "0")}`;
2659+ switch (index % 8) {
2660+ case 0:
2661+ return `export async function ${label}(input: { value: number; name: string }) {`;
2662+ case 1:
2663+ return ` const normalized = input.name.trim().toLowerCase();`;
2664+ case 2:
2665+ return ` const result = await Promise.resolve({ id: "${label}", score: input.value * ${index + 1} });`;
2666+ case 3:
2667+ return ` if (result.score > ${index * 17}) return normalized + ":" + result.id;`;
2668+ case 4:
2669+ return ` return [normalized, String(result.score), "${"x".repeat((index % 24) + 8)}"].join("/");`;
2670+ case 5:
2671+ return `}`;
2672+ case 6:
2673+ return `type ${label}Record = Readonly<{ id: string; createdAt: Date; tags: string[] }>;`;
2674+ default:
2675+ return `const ${label}: ${label}Record = { id: "${label}", createdAt: new Date(), tags: ["debug", "highlight"] };`;
2676+ }
2677+}
2678+
2679+function makeDebugLines(): ReadonlyArray<DebugLine> {
2680+ return Array.from({ length: DEBUG_LINE_COUNT }, (_, index) => ({
2681+ id: `line:${index + 1}`,
2682+ chunkIndex: Math.floor(index / DEBUG_CHUNK_SIZE),
2683+ indexInChunk: index % DEBUG_CHUNK_SIZE,
2684+ lineNumber: index + 1,
2685+ content: makeDebugCodeLine(index + 1),
2686+ }));
2687+}
2688+
2689+async function createNativeDebugHighlighter(): Promise<DebugHighlighterHandle> {
2690+ const nativeEngineModule = await import("react-native-shiki-engine");
2691+ if (!nativeEngineModule.isNativeEngineAvailable()) {
2692+ throw new Error("Native Shiki engine is not available in this build.");
2693+ }
2694+
2695+ const highlighter = await createHighlighterCore({
2696+ langs: [typescriptLanguage],
2697+ themes: [githubLightDefault, githubDarkDefault],
2698+ engine: nativeEngineModule.createNativeEngine(),
2699+ });
2700+
2701+ return {
2702+ engine: "native",
2703+ tokenize: (code, options) => normalizeTokens(highlighter.codeToTokensBase(code, options)),
2704+ };
2705+}
2706+
2707+async function createJavascriptDebugHighlighter(): Promise<DebugHighlighterHandle> {
2708+ const highlighter: HighlighterCore = await createHighlighterCore({
2709+ langs: [typescriptLanguage],
2710+ themes: [githubLightDefault, githubDarkDefault],
2711+ engine: createJavaScriptRegexEngine(),
2712+ });
2713+
2714+ return {
2715+ engine: "javascript",
2716+ tokenize: (code, options) => normalizeTokens(highlighter.codeToTokensBase(code, options)),
2717+ };
2718+}
2719+
2720+async function getDebugHighlighter(engine: DebugHighlightEngine): Promise<DebugHighlighterHandle> {
2721+ if (engine === "native") {
2722+ nativeHighlighterPromise ??= createNativeDebugHighlighter();
2723+ return nativeHighlighterPromise;
2724+ }
2725+
2726+ javascriptHighlighterPromise ??= createJavascriptDebugHighlighter();
2727+ return javascriptHighlighterPromise;
2728+}
2729+
2730+const TokenText = memo(function TokenText(props: {
2731+ readonly content: string;
2732+ readonly tokens: ReadonlyArray<DebugToken> | null;
2733+}) {
2734+ if (!props.tokens) {
2735+ return (
2736+ <NativeText
2737+ numberOfLines={1}
2738+ className="text-[13px] font-medium leading-[18px] text-foreground"
2739+ style={{ fontFamily: DEBUG_MONO_FONT_FAMILY }}
2740+ >
2741+ {props.content}
2742+ </NativeText>
2743+ );
2744+ }
2745+
2746+ let tokenOffset = 0;
2747+
2748+ return (
2749+ <NativeText
2750+ numberOfLines={1}
2751+ className="text-[13px] font-medium leading-[18px] text-foreground"
2752+ style={{ fontFamily: DEBUG_MONO_FONT_FAMILY }}
2753+ >
2754+ {props.tokens.map((token) => {
2755+ const tokenKey = `${tokenOffset}:${token.content.length}:${token.color ?? ""}:${token.fontStyle ?? ""}`;
2756+ tokenOffset += token.content.length;
2757+ const fontWeight =
2758+ token.fontStyle !== null && (token.fontStyle & 2) === 2
2759+ ? ("700" as const)
2760+ : ("500" as const);
2761+ const fontStyle =
2762+ token.fontStyle !== null && (token.fontStyle & 1) === 1
2763+ ? ("italic" as const)
2764+ : ("normal" as const);
2765+
2766+ return (
2767+ <NativeText
2768+ key={tokenKey}
2769+ style={{
2770+ color: token.color ?? undefined,
2771+ fontFamily: DEBUG_MONO_FONT_FAMILY,
2772+ fontStyle,
2773+ fontWeight,
2774+ }}
2775+ >
2776+ {token.content}
2777+ </NativeText>
2778+ );
2779+ })}
2780+ </NativeText>
2781+ );
2782+});
2783+
2784+const DebugCodeLineRow = memo(function DebugCodeLineRow(props: {
2785+ readonly item: DebugLine;
2786+ readonly tokens: ReadonlyArray<DebugToken> | null;
2787+ readonly width: number;
2788+}) {
2789+ return (
2790+ <View className="flex-row bg-card" style={{ height: DEBUG_LINE_HEIGHT, width: props.width }}>
2791+ <View className="items-end justify-center pr-2" style={{ width: DEBUG_GUTTER_WIDTH }}>
2792+ <Text className="font-mono text-[11px] text-foreground-muted">{props.item.lineNumber}</Text>
2793+ </View>
2794+ <View className="justify-center px-2" style={{ width: DEBUG_CONTENT_WIDTH }}>
2795+ <TokenText content={props.item.content} tokens={props.tokens} />
2796+ </View>
2797+ </View>
2798+ );
2799+});
2800+
2801+function EngineToggle(props: {
2802+ readonly engine: DebugHighlightEngine;
2803+ readonly onChangeEngine: (engine: DebugHighlightEngine) => void;
2804+}) {
2805+ return (
2806+ <View className="flex-row rounded-full bg-subtle p-1">
2807+ {(["native", "javascript"] as const).map((engine) => {
2808+ const selected = props.engine === engine;
2809+ return (
2810+ <Pressable
2811+ key={engine}
2812+ className={cn("rounded-full px-3 py-1.5", selected && "bg-card")}
2813+ onPress={() => props.onChangeEngine(engine)}
2814+ >
2815+ <Text
2816+ className={cn(
2817+ "text-[12px] font-t3-bold",
2818+ selected ? "text-foreground" : "text-foreground-muted",
2819+ )}
2820+ >
2821+ {engine === "javascript" ? "JS" : "Native"}
2822+ </Text>
2823+ </Pressable>
2824+ );
2825+ })}
2826+ </View>
2827+ );
2828+}
2829+
2830+export default function SyntaxHighlightDebugRoute() {
2831+ const insets = useSafeAreaInsets();
2832+ const { width } = useWindowDimensions();
2833+ const colorScheme = useColorScheme();
2834+ const headerIcon = String(useThemeColor("--color-icon"));
2835+ const themeName = DEBUG_THEME_NAME_BY_SCHEME[colorScheme === "dark" ? "dark" : "light"];
2836+ const [engine, setEngine] = useState<DebugHighlightEngine>("native");
2837+ const [tokensByChunkIndex, setTokensByChunkIndex] = useState<
2838+ Record<number, ReadonlyArray<ReadonlyArray<DebugToken>>>
2839+ >({});
2840+ const [status, setStatus] = useState("Idle");
2841+ const renderStartRef = useRef<number | null>(null);
2842+ const generationRef = useRef(0);
2843+ const lines = useMemo(() => makeDebugLines(), []);
2844+
2845+ useEffect(() => {
2846+ const generation = generationRef.current + 1;
2847+ generationRef.current = generation;
2848+ renderStartRef.current = performance.now();
2849+ setTokensByChunkIndex({});
2850+ setStatus("Initializing highlighter");
2851+
2852+ void (async () => {
2853+ try {
2854+ const highlighterStartedAt = performance.now();
2855+ const highlighter = await getDebugHighlighter(engine);
2856+ if (generation !== generationRef.current) {
2857+ return;
2858+ }
2859+
2860+ console.log("[debug-syntax-scratch] initialize", {
2861+ durationMs: Math.round(performance.now() - highlighterStartedAt),
2862+ engine: highlighter.engine,
2863+ });
2864+
2865+ let firstChunkMs: number | null = null;
2866+ const totalStartedAt = performance.now();
2867+ setStatus(`Streaming ${DEBUG_LINE_COUNT.toLocaleString()} lines`);
2868+
2869+ for (let startIndex = 0; startIndex < lines.length; startIndex += DEBUG_CHUNK_SIZE) {
2870+ if (generation !== generationRef.current) {
2871+ return;
2872+ }
2873+
2874+ const chunkLines = lines.slice(startIndex, startIndex + DEBUG_CHUNK_SIZE);
2875+ const chunkCode = chunkLines.map((line) => line.content).join("\n");
2876+ const chunkStartedAt = performance.now();
2877+ const chunkTokens = highlighter.tokenize(chunkCode, {
2878+ lang: "typescript",
2879+ theme: themeName,
2880+ });
2881+ const chunkMs = performance.now() - chunkStartedAt;
2882+
2883+ if (firstChunkMs === null) {
2884+ firstChunkMs = performance.now() - totalStartedAt;
2885+ console.log("[debug-syntax-scratch] first chunk", {
2886+ chunkSize: DEBUG_CHUNK_SIZE,
2887+ durationMs: Math.round(firstChunkMs),
2888+ engine,
2889+ lineCount: chunkTokens.length,
2890+ });
2891+ }
2892+
2893+ setTokensByChunkIndex((current) => ({
2894+ ...current,
2895+ [startIndex / DEBUG_CHUNK_SIZE]: chunkTokens,
2896+ }));
2897+ setStatus(
2898+ `Streamed ${Math.min(startIndex + DEBUG_CHUNK_SIZE, lines.length).toLocaleString()} / ${lines.length.toLocaleString()} lines`,
2899+ );
2900+
2901+ console.log("[debug-syntax-scratch] chunk", {
2902+ chunkIndex: startIndex / DEBUG_CHUNK_SIZE,
2903+ chunkMs: Math.round(chunkMs),
2904+ engine,
2905+ lineCount: chunkTokens.length,
2906+ });
2907+
2908+ await waitForNextFrame();
2909+ }
2910+
2911+ console.log("[debug-syntax-scratch] complete", {
2912+ durationMs: Math.round(performance.now() - totalStartedAt),
2913+ engine,
2914+ lineCount: lines.length,
2915+ });
2916+ setStatus(`Complete with ${engine}`);
2917+ } catch (error) {
2918+ console.error("[debug-syntax-scratch] failed", {
2919+ engine,
2920+ message: error instanceof Error ? error.message : String(error),
2921+ });
2922+ setStatus(error instanceof Error ? error.message : "Highlight failed");
2923+ }
2924+ })();
2925+ }, [engine, lines, themeName]);
2926+
2927+ useEffect(() => {
2928+ if (renderStartRef.current === null) {
2929+ return;
2930+ }
2931+
2932+ const startedAt = renderStartRef.current;
2933+ renderStartRef.current = null;
2934+ const commitMs = performance.now() - startedAt;
2935+ requestAnimationFrame(() => {
2936+ console.log("[debug-syntax-scratch] render", {
2937+ commitMs: Math.round(commitMs),
2938+ paintMs: Math.round(performance.now() - startedAt),
2939+ });
2940+ });
2941+ });
2942+
2943+ const renderItem = useCallback(
2944+ ({ item }: ListRenderItemInfo<DebugLine>) => (
2945+ <DebugCodeLineRow
2946+ item={item}
2947+ tokens={tokensByChunkIndex[item.chunkIndex]?.[item.indexInChunk] ?? null}
2948+ width={width}
2949+ />
2950+ ),
2951+ [tokensByChunkIndex, width],
2952+ );
2953+
2954+ return (
2955+ <View className="flex-1 bg-sheet">
2956+ <Stack.Screen
2957+ options={{
2958+ headerShown: true,
2959+ headerTitle: "Syntax Scratch",
2960+ headerTintColor: headerIcon,
2961+ headerTransparent: true,
2962+ headerShadowVisible: false,
2963+ }}
2964+ />
2965+
2966+ <View
2967+ className="border-b border-border bg-sheet px-3 pb-3"
2968+ style={{ paddingTop: insets.top + 56 }}
2969+ >
2970+ <View className="flex-row items-center justify-between gap-3">
2971+ <View className="min-w-0 flex-1">
2972+ <Text className="text-[13px] font-t3-bold text-foreground">
2973+ Shiki streaming baseline
2974+ </Text>
2975+ <Text className="text-[11px] text-foreground-muted" numberOfLines={1}>
2976+ {status}
2977+ </Text>
2978+ </View>
2979+ <EngineToggle engine={engine} onChangeEngine={setEngine} />
2980+ </View>
2981+ </View>
2982+
2983+ <FlatList
2984+ style={{ flex: 1, width }}
2985+ data={lines}
2986+ renderItem={renderItem}
2987+ keyExtractor={(item) => item.id}
2988+ getItemLayout={(_, index) => ({
2989+ length: DEBUG_LINE_HEIGHT,
2990+ offset: DEBUG_LINE_HEIGHT * index,
2991+ index,
2992+ })}
2993+ initialNumToRender={40}
2994+ maxToRenderPerBatch={80}
2995+ updateCellsBatchingPeriod={16}
2996+ windowSize={9}
2997+ removeClippedSubviews
2998+ keyboardShouldPersistTaps="handled"
2999+ contentContainerStyle={{ paddingBottom: Math.max(insets.bottom, 18) + 18 }}
3000+ />
3001+ </View>
3002+ );
3003+}
3004diff --git a/apps/mobile/src/features/review/ReviewHighlighterProvider.tsx b/apps/mobile/src/features/review/ReviewHighlighterProvider.tsx
3005new file mode 100644
3006index 000000000..095201929
3007--- /dev/null
3008+++ b/apps/mobile/src/features/review/ReviewHighlighterProvider.tsx
3009@@ -0,0 +1,110 @@
3010+import { createContext, type ReactNode, useContext, useEffect, useMemo, useState } from "react";
3011+
3012+import {
3013+ getActiveReviewHighlighterEngine,
3014+ prepareReviewHighlighter,
3015+ prepareReviewHighlighterLanguages,
3016+ type ReviewHighlighterEngine,
3017+} from "./shikiReviewHighlighter";
3018+
3019+type ReviewHighlighterStatus = "idle" | "initializing" | "ready" | "error";
3020+
3021+interface ReviewHighlighterContextValue {
3022+ readonly engine: ReviewHighlighterEngine | null;
3023+ readonly error: string | null;
3024+ readonly status: ReviewHighlighterStatus;
3025+}
3026+
3027+const ReviewHighlighterContext = createContext<ReviewHighlighterContextValue>({
3028+ engine: null,
3029+ error: null,
3030+ status: "idle",
3031+});
3032+
3033+const REVIEW_INITIAL_LANGUAGES = [
3034+ "typescript",
3035+ "tsx",
3036+ "javascript",
3037+ "jsx",
3038+ "json",
3039+ "yaml",
3040+ "bash",
3041+] as const;
3042+
3043+function isReviewHighlighterProviderDebugLoggingEnabled(): boolean {
3044+ return typeof __DEV__ !== "undefined" ? __DEV__ : false;
3045+}
3046+
3047+function logReviewHighlighterProviderDiagnostic(
3048+ message: string,
3049+ details?: Record<string, unknown>,
3050+): void {
3051+ if (!isReviewHighlighterProviderDebugLoggingEnabled()) {
3052+ return;
3053+ }
3054+
3055+ if (details) {
3056+ console.log(`[review-highlighter-provider] ${message}`, details);
3057+ return;
3058+ }
3059+
3060+ console.log(`[review-highlighter-provider] ${message}`);
3061+}
3062+
3063+export function ReviewHighlighterProvider(props: { readonly children: ReactNode }) {
3064+ const [value, setValue] = useState<ReviewHighlighterContextValue>({
3065+ engine: null,
3066+ error: null,
3067+ status: "idle",
3068+ });
3069+
3070+ useEffect(() => {
3071+ let cancelled = false;
3072+
3073+ setValue({ engine: null, error: null, status: "initializing" });
3074+
3075+ void (async () => {
3076+ const startedAt = performance.now();
3077+ try {
3078+ await prepareReviewHighlighter();
3079+ await prepareReviewHighlighterLanguages(REVIEW_INITIAL_LANGUAGES);
3080+ const engine = await getActiveReviewHighlighterEngine();
3081+
3082+ if (cancelled) {
3083+ return;
3084+ }
3085+
3086+ const durationMs = Math.round(performance.now() - startedAt);
3087+ logReviewHighlighterProviderDiagnostic("initialized", {
3088+ durationMs,
3089+ engine,
3090+ });
3091+ setValue({ engine, error: null, status: "ready" });
3092+ } catch (error) {
3093+ if (cancelled) {
3094+ return;
3095+ }
3096+
3097+ const message = error instanceof Error ? error.message : String(error);
3098+ logReviewHighlighterProviderDiagnostic("initialization failed", { error: message });
3099+ setValue({ engine: null, error: message, status: "error" });
3100+ }
3101+ })();
3102+
3103+ return () => {
3104+ cancelled = true;
3105+ };
3106+ }, []);
3107+
3108+ const contextValue = useMemo(() => value, [value]);
3109+
3110+ return (
3111+ <ReviewHighlighterContext.Provider value={contextValue}>
3112+ {props.children}
3113+ </ReviewHighlighterContext.Provider>
3114+ );
3115+}
3116+
3117+export function useReviewHighlighterStatus(): ReviewHighlighterContextValue {
3118+ return useContext(ReviewHighlighterContext);
3119+}
3120diff --git a/apps/mobile/src/features/review/reviewPerf.ts b/apps/mobile/src/features/review/reviewPerf.ts
3121new file mode 100644
3122index 000000000..2ae1095b1
3123--- /dev/null
3124+++ b/apps/mobile/src/features/review/reviewPerf.ts
3125@@ -0,0 +1,83 @@
3126+interface ReviewPerformanceLike {
3127+ readonly now?: () => number;
3128+ readonly mark?: (name: string) => void;
3129+ readonly measure?: (name: string, startMark: string, endMark: string) => void;
3130+ readonly clearMarks?: (name?: string) => void;
3131+ readonly clearMeasures?: (name?: string) => void;
3132+}
3133+
3134+const REVIEW_PERF_PREFIX = "t3.review";
3135+let reviewPerfSequence = 0;
3136+
3137+function getPerformance(): ReviewPerformanceLike | null {
3138+ const candidate = (globalThis as { readonly performance?: ReviewPerformanceLike }).performance;
3139+ return candidate ?? null;
3140+}
3141+
3142+export function isReviewPerfEnabled(): boolean {
3143+ return typeof __DEV__ !== "undefined" ? __DEV__ : false;
3144+}
3145+
3146+export function measureReviewWork<T>(name: string, callback: () => T): T {
3147+ if (!isReviewPerfEnabled()) {
3148+ return callback();
3149+ }
3150+
3151+ const perf = getPerformance();
3152+ const marker = `${REVIEW_PERF_PREFIX}.${name}.${reviewPerfSequence++}`;
3153+ const startMark = `${marker}.start`;
3154+ const endMark = `${marker}.end`;
3155+ const startedAt = perf?.now?.() ?? Date.now();
3156+
3157+ perf?.mark?.(startMark);
3158+ try {
3159+ return callback();
3160+ } finally {
3161+ const durationMs = (perf?.now?.() ?? Date.now()) - startedAt;
3162+ perf?.mark?.(endMark);
3163+ perf?.measure?.(`${REVIEW_PERF_PREFIX}.${name}`, startMark, endMark);
3164+ perf?.clearMarks?.(startMark);
3165+ perf?.clearMarks?.(endMark);
3166+ console.log(`[review-perf] ${name}`, { durationMs: Number(durationMs.toFixed(2)) });
3167+ }
3168+}
3169+
3170+export async function measureReviewAsyncWork<T>(
3171+ name: string,
3172+ callback: () => Promise<T>,
3173+): Promise<T> {
3174+ if (!isReviewPerfEnabled()) {
3175+ return callback();
3176+ }
3177+
3178+ const perf = getPerformance();
3179+ const marker = `${REVIEW_PERF_PREFIX}.${name}.${reviewPerfSequence++}`;
3180+ const startMark = `${marker}.start`;
3181+ const endMark = `${marker}.end`;
3182+ const startedAt = perf?.now?.() ?? Date.now();
3183+
3184+ perf?.mark?.(startMark);
3185+ try {
3186+ return await callback();
3187+ } finally {
3188+ const durationMs = (perf?.now?.() ?? Date.now()) - startedAt;
3189+ perf?.mark?.(endMark);
3190+ perf?.measure?.(`${REVIEW_PERF_PREFIX}.${name}`, startMark, endMark);
3191+ perf?.clearMarks?.(startMark);
3192+ perf?.clearMarks?.(endMark);
3193+ console.log(`[review-perf] ${name}`, { durationMs: Number(durationMs.toFixed(2)) });
3194+ }
3195+}
3196+
3197+export function markReviewEvent(name: string, details?: Record<string, unknown>): void {
3198+ if (!isReviewPerfEnabled()) {
3199+ return;
3200+ }
3201+
3202+ getPerformance()?.mark?.(`${REVIEW_PERF_PREFIX}.${name}`);
3203+ if (details) {
3204+ console.log(`[review-perf] ${name}`, details);
3205+ return;
3206+ }
3207+ console.log(`[review-perf] ${name}`);
3208+}
apps/mobile/src/features/debug/fixtures/review-medium.diff+0−1955
@@ -1,1955 +0,0 @@
1diff --git a/apps/mobile/src/app/threads/[environmentId]/[threadId]/review.tsx b/apps/mobile/src/app/threads/[environmentId]/[threadId]/review.tsx
2index 84c48c6ed..ee993ee7c 100644
3--- a/apps/mobile/src/app/threads/[environmentId]/[threadId]/review.tsx
4+++ b/apps/mobile/src/app/threads/[environmentId]/[threadId]/review.tsx
5@@ -1,5 +1,10 @@
6+import { ReviewHighlighterProvider } from "../../../../features/review/ReviewHighlighterProvider";
7 import { ReviewSheet } from "../../../../features/review/ReviewSheet";
8
9 export default function ReviewRoute() {
10- return <ReviewSheet />;
11+ return (
12+ <ReviewHighlighterProvider>
13+ <ReviewSheet />
14+ </ReviewHighlighterProvider>
15+ );
16 }
17diff --git a/apps/mobile/src/features/review/ReviewSheet.tsx b/apps/mobile/src/features/review/ReviewSheet.tsx
18index 82c28e81e..e148a8da2 100644
19--- a/apps/mobile/src/features/review/ReviewSheet.tsx
20+++ b/apps/mobile/src/features/review/ReviewSheet.tsx
21@@ -1,17 +1,31 @@
22 import { EnvironmentId, ThreadId, type OrchestrationCheckpointSummary } from "@t3tools/contracts";
23+import { Gesture, GestureDetector } from "react-native-gesture-handler";
24+import Animated, {
25+ makeMutable,
26+ type SharedValue,
27+ useAnimatedStyle,
28+ useSharedValue,
29+} from "react-native-reanimated";
30 import { useLocalSearchParams, useRouter } from "expo-router";
31 import Stack from "expo-router/stack";
32 import { SymbolView } from "expo-symbols";
33-import { memo, type ReactElement, useCallback, useEffect, useMemo, useRef, useState } from "react";
34+import {
35+ memo,
36+ type ReactElement,
37+ useCallback,
38+ useDeferredValue,
39+ useEffect,
40+ useMemo,
41+ useRef,
42+ useState,
43+} from "react";
44 import {
45 ActivityIndicator,
46 FlatList,
47- InteractionManager,
48 type ListRenderItemInfo,
49 Pressable,
50 ScrollView,
51 Text as NativeText,
52- type ViewToken,
53 useColorScheme,
54 useWindowDimensions,
55 View,
56@@ -32,6 +46,7 @@ import {
57 setReviewTurnDiff,
58 updateReviewExpandedFileIds,
59 updateReviewRevealedLargeFileIds,
60+ updateReviewViewedFileIds,
61 useReviewCacheForThread,
62 } from "./reviewState";
63 import {
64@@ -45,11 +60,12 @@ import {
65 type ReviewParsedDiff,
66 type ReviewRenderableFile,
67 type ReviewRenderableLineRow,
68+ type ReviewRenderableRow,
69 } from "./reviewModel";
70 import {
71 clearReviewHighlightFileCache,
72 getCachedHighlightedReviewFile,
73- highlightReviewFile,
74+ streamHighlightReviewFile,
75 type ReviewDiffTheme,
76 type ReviewHighlightedFile,
77 type ReviewHighlightedToken,
78@@ -67,9 +83,12 @@ import {
79 import {
80 changeTone,
81 DiffTokenText,
82+ REVIEW_DIFF_LINE_HEIGHT,
83 REVIEW_MONO_FONT_FAMILY,
84 ReviewChangeBar,
85 } from "./reviewDiffRendering";
86+import { markReviewEvent, measureReviewWork } from "./reviewPerf";
87+import { useReviewHighlighterStatus } from "./ReviewHighlighterProvider";
88
89 interface PendingCommentSelection {
90 readonly sectionTitle: string;
91@@ -87,14 +106,21 @@ interface ReviewLineActionInput {
92
93 const IOS_NAV_BAR_HEIGHT = 44;
94 const REVIEW_HEADER_SPACING = 0;
95-const REVIEW_LINE_GUTTER_WIDTH = 62;
96+const REVIEW_CHANGE_BAR_WIDTH = 5;
97+const REVIEW_MIN_LINE_NUMBER_WIDTH = 27;
98+const REVIEW_LINE_NUMBER_DIGIT_WIDTH_ESTIMATE = 8;
99+const REVIEW_LINE_NUMBER_HORIZONTAL_PADDING = 6;
100 const REVIEW_CHARACTER_WIDTH_ESTIMATE = 8.4;
101 const REVIEW_MAX_CONTENT_WIDTH = 4_800;
102-const REVIEW_INITIAL_HIGHLIGHT_FILE_COUNT = 2;
103-const REVIEW_HIGHLIGHT_BACKTRACK_COUNT = 0;
104-const REVIEW_HIGHLIGHT_LOOKAHEAD_COUNT = 1;
105+const REVIEW_HUNK_ROW_HEIGHT = 35;
106+const REVIEW_FILE_HEADER_HEIGHT = 43;
107+const REVIEW_SUPPRESSED_ROW_HEIGHT = 92;
108 const loggedMissingReviewTokenKeys = new Set<string>();
109
110+function waitForReviewDelay(durationMs: number): Promise<void> {
111+ return new Promise((resolve) => setTimeout(resolve, durationMs));
112+}
113+
114 function isReviewDiffDebugLoggingEnabled(): boolean {
115 return typeof __DEV__ !== "undefined" ? __DEV__ : false;
116 }
117@@ -113,33 +139,27 @@ function logReviewDiffDiagnostic(message: string, details?: Record<string, unkno
118 }
119
120 function getFileHeaderChrome(changeType: ReviewRenderableFile["changeType"]): {
121- readonly rail: string;
122 readonly dot: string;
123 } {
124 switch (changeType) {
125 case "new":
126 return {
127- rail: "bg-emerald-400",
128 dot: "bg-emerald-400",
129 };
130 case "deleted":
131 return {
132- rail: "bg-rose-400",
133 dot: "bg-rose-400",
134 };
135 case "rename-pure":
136 return {
137- rail: "bg-amber-400",
138 dot: "bg-amber-400",
139 };
140 case "rename-changed":
141 return {
142- rail: "bg-sky-400",
143 dot: "bg-sky-400",
144 };
145 default:
146 return {
147- rail: "bg-sky-400",
148 dot: "bg-sky-400",
149 };
150 }
151@@ -159,51 +179,72 @@ function formatHeaderDiffSummary(parsedDiff: ReviewParsedDiff): {
152 };
153 }
154
155-function computeReviewListContentWidth(
156- items: ReadonlyArray<ReviewListItem>,
157+function computeReviewFileContentWidth(
158+ rows: ReadonlyArray<ReviewRenderableRow>,
159 viewportWidth: number,
160+ gutterWidth: number,
161 ): number {
162 let maxTextLength = 0;
163
164- items.forEach((item) => {
165- switch (item.kind) {
166- case "file-header":
167- maxTextLength = Math.max(
168- maxTextLength,
169- item.file.path.length,
170- item.file.previousPath?.length ?? 0,
171- );
172- break;
173- case "file-suppressed":
174- maxTextLength = Math.max(maxTextLength, item.message.length, item.actionLabel?.length ?? 0);
175- break;
176- case "hunk":
177- maxTextLength = Math.max(
178- maxTextLength,
179- item.row.header.length + (item.row.context ? item.row.context.length + 1 : 0),
180- );
181- break;
182- case "line":
183- maxTextLength = Math.max(maxTextLength, item.row.content.length);
184- break;
185+ rows.forEach((row) => {
186+ if (row.kind === "hunk") {
187+ maxTextLength = Math.max(
188+ maxTextLength,
189+ row.header.length + (row.context ? row.context.length + 1 : 0),
190+ );
191+ return;
192 }
193+
194+ maxTextLength = Math.max(maxTextLength, row.content.length);
195 });
196
197 return Math.max(
198- viewportWidth,
199+ Math.max(0, viewportWidth - gutterWidth),
200 Math.min(
201 REVIEW_MAX_CONTENT_WIDTH,
202- Math.ceil(REVIEW_LINE_GUTTER_WIDTH + 48 + maxTextLength * REVIEW_CHARACTER_WIDTH_ESTIMATE),
203+ Math.ceil(48 + maxTextLength * REVIEW_CHARACTER_WIDTH_ESTIMATE),
204 ),
205 );
206 }
207
208+function computeReviewFileGutterWidth(rows: ReadonlyArray<ReviewRenderableRow>): number {
209+ let maxLineNumber = 0;
210+
211+ rows.forEach((row) => {
212+ if (row.kind !== "line") {
213+ return;
214+ }
215+
216+ maxLineNumber = Math.max(maxLineNumber, row.oldLineNumber ?? 0, row.newLineNumber ?? 0);
217+ });
218+
219+ const digitCount = Math.max(1, String(maxLineNumber).length);
220+ const lineNumberWidth = Math.max(
221+ REVIEW_MIN_LINE_NUMBER_WIDTH,
222+ digitCount * REVIEW_LINE_NUMBER_DIGIT_WIDTH_ESTIMATE + REVIEW_LINE_NUMBER_HORIZONTAL_PADDING,
223+ );
224+
225+ return REVIEW_CHANGE_BAR_WIDTH + lineNumberWidth;
226+}
227+
228 function getDefaultExpandedFileIds(
229 files: ReadonlyArray<ReviewRenderableFile>,
230 ): ReadonlyArray<string> {
231 return files.map((file) => file.id);
232 }
233
234+function getValidReviewExpandedFileIds(
235+ files: ReadonlyArray<ReviewRenderableFile>,
236+ cachedExpandedFileIds: ReadonlyArray<string> | undefined,
237+): ReadonlyArray<string> {
238+ if (cachedExpandedFileIds === undefined) {
239+ return getDefaultExpandedFileIds(files);
240+ }
241+
242+ const fileIdSet = new Set(files.map((file) => file.id));
243+ return cachedExpandedFileIds.filter((id) => fileIdSet.has(id));
244+}
245+
246 function getHighlightedTokensForLine(
247 line: ReviewRenderableLineRow,
248 highlightedFile: ReviewHighlightedFile | null,
249@@ -252,16 +293,13 @@ const ReviewLineRow = memo(function ReviewLineRow(props: {
250 delayLongPress={220}
251 onLongPress={props.onStartRangeSelection}
252 onPress={props.onComment}
253- style={{ minWidth: props.viewportWidth }}
254+ style={{
255+ height: REVIEW_DIFF_LINE_HEIGHT,
256+ width: props.viewportWidth,
257+ overflow: "hidden",
258+ }}
259 >
260- <ReviewChangeBar change={props.line.change} />
261- <Text
262- className="w-9 py-1 pr-1 text-right text-[11px] font-t3-medium text-foreground-muted"
263- style={{ fontFamily: REVIEW_MONO_FONT_FAMILY }}
264- >
265- {lineNumber ?? ""}
266- </Text>
267- <View className="min-w-0 flex-1 shrink-0 px-1 py-1">
268+ <View className="min-w-0 flex-1 shrink-0 px-1 py-1" style={{ width: props.viewportWidth }}>
269 <DiffTokenText
270 tokens={props.tokens}
271 fallback={props.line.content}
272@@ -272,62 +310,135 @@ const ReviewLineRow = memo(function ReviewLineRow(props: {
273 );
274 });
275
276+const ReviewLineGutter = memo(function ReviewLineGutter(props: {
277+ readonly change: ReviewRenderableLineRow["change"];
278+ readonly gutterWidth: number;
279+ readonly lineNumber: number | null;
280+}) {
281+ const lineNumberWidth = Math.max(0, props.gutterWidth - REVIEW_CHANGE_BAR_WIDTH);
282+
283+ return (
284+ <View className={cn("flex-row", changeTone(props.change))} style={{ width: props.gutterWidth }}>
285+ <ReviewChangeBar change={props.change} />
286+ <Text
287+ className="py-1 pr-1 text-right text-[11px] font-t3-medium text-foreground-muted"
288+ style={[{ fontFamily: REVIEW_MONO_FONT_FAMILY }, { width: lineNumberWidth }]}
289+ >
290+ {props.lineNumber ?? ""}
291+ </Text>
292+ </View>
293+ );
294+});
295+
296+const ReviewHunkGutter = memo(function ReviewHunkGutter(props: { readonly gutterWidth: number }) {
297+ return (
298+ <View
299+ className="border-b border-border/60 bg-sky-500/10"
300+ style={{ width: props.gutterWidth }}
301+ />
302+ );
303+});
304+
305 const ReviewFileCard = memo(function ReviewFileCard(props: {
306 readonly file: ReviewRenderableFile;
307 readonly fileId: string;
308 readonly expanded: boolean;
309+ readonly viewed: boolean;
310 readonly viewportWidth: number;
311 readonly onToggleFile: (fileId: string) => void;
312+ readonly onToggleViewed: (fileId: string) => void;
313 }) {
314- const chrome = getFileHeaderChrome(props.file.changeType);
315+ const { expanded, file, fileId, onToggleFile, onToggleViewed, viewed, viewportWidth } = props;
316+ const chrome = getFileHeaderChrome(file.changeType);
317+ const iconColor = String(useThemeColor("--color-icon-muted"));
318+ const handleToggleFile = useCallback(() => {
319+ onToggleFile(fileId);
320+ }, [fileId, onToggleFile]);
321+ const handleToggleViewed = useCallback(() => {
322+ onToggleViewed(fileId);
323+ }, [fileId, onToggleViewed]);
324
325 return (
326 <View
327- className="border-b border-border/70 bg-card"
328- style={{
329- zIndex: 1,
330- width: props.viewportWidth,
331- shadowColor: "#000000",
332- shadowOpacity: 0.08,
333- shadowRadius: 10,
334- shadowOffset: { width: 0, height: 6 },
335- elevation: 4,
336- }}
337+ className="border-b border-border bg-card"
338+ style={{ height: REVIEW_FILE_HEADER_HEIGHT, overflow: "hidden", width: viewportWidth }}
339 >
340- <Pressable className="flex-row items-center" onPress={() => props.onToggleFile(props.fileId)}>
341- <View className={cn("w-1 self-stretch", chrome.rail)} />
342- <View className="flex-1 flex-row items-center px-3 py-1.5">
343- <View className="size-7 items-center justify-center rounded-full bg-subtle">
344- <SymbolView
345- name={props.expanded ? "chevron.down" : "chevron.right"}
346- size={12}
347- tintColor="#8a8a8a"
348- type="monochrome"
349- />
350- </View>
351- <View className="ml-2 min-w-0 flex-1 flex-row items-center gap-2">
352- <View className={cn("size-2 rounded-full", chrome.dot)} />
353- <View className="min-w-0 flex-1">
354- <Text className="font-mono text-[13px] leading-[18px] text-foreground">
355- {props.file.path}
356+ <View className="min-h-[42px] flex-row items-center gap-1.5 px-2">
357+ <Pressable
358+ className="size-9 items-center justify-center"
359+ accessibilityRole="button"
360+ accessibilityLabel={expanded ? "Collapse file" : "Expand file"}
361+ hitSlop={{ bottom: 8, left: 8, right: 8, top: 8 }}
362+ onTouchEnd={handleToggleFile}
363+ >
364+ <SymbolView
365+ name={expanded ? "chevron.down" : "chevron.right"}
366+ size={13}
367+ tintColor={iconColor}
368+ type="monochrome"
369+ />
370+ </Pressable>
371+ <Pressable
372+ className="min-w-0 flex-1 flex-row items-center gap-2 py-2"
373+ accessibilityRole="button"
374+ accessibilityLabel={expanded ? "Collapse file" : "Expand file"}
375+ onTouchEnd={handleToggleFile}
376+ >
377+ <View className={cn("size-2.5 rounded-full", chrome.dot)} />
378+ <View className="min-w-0 flex-1">
379+ <Text
380+ className="font-mono text-[13px] leading-[18px] text-foreground"
381+ numberOfLines={1}
382+ >
383+ {file.path}
384+ </Text>
385+ {file.previousPath && file.previousPath !== file.path ? (
386+ <Text
387+ className="font-mono text-[10px] leading-[14px] text-foreground-muted"
388+ numberOfLines={1}
389+ >
390+ {file.previousPath}
391 </Text>
392- {props.file.previousPath && props.file.previousPath !== props.file.path ? (
393- <Text className="font-mono text-[10px] leading-[14px] text-foreground-muted">
394- {props.file.previousPath}
395- </Text>
396+ ) : null}
397+ </View>
398+ </Pressable>
399+ <View className="flex-row items-center justify-end gap-1.5">
400+ <Text className="font-mono text-[12px] font-t3-bold text-rose-400">
401+ -{file.deletions}
402+ </Text>
403+ <Text className="font-mono text-[12px] font-t3-bold text-emerald-400">
404+ +{file.additions}
405+ </Text>
406+ <Pressable
407+ className="ml-0.5 min-h-[40px] min-w-[82px] flex-row items-center justify-center gap-1.5 px-1.5"
408+ accessibilityRole="checkbox"
409+ accessibilityState={{ checked: viewed }}
410+ accessibilityLabel={viewed ? "Mark file as unviewed" : "Mark file as viewed"}
411+ hitSlop={{ bottom: 8, left: 4, right: 8, top: 8 }}
412+ onTouchEnd={handleToggleViewed}
413+ >
414+ <View
415+ className={cn(
416+ "size-[18px] items-center justify-center rounded border",
417+ viewed ? "border-sky-500 bg-sky-500" : "border-icon-muted",
418+ )}
419+ >
420+ {viewed ? (
421+ <SymbolView name="checkmark" size={11} tintColor="#ffffff" type="monochrome" />
422 ) : null}
423 </View>
424- </View>
425- <View className="ml-3 flex-row items-center justify-end gap-2">
426- <Text className="font-mono text-[12px] font-t3-bold text-emerald-600 dark:text-emerald-300">
427- +{props.file.additions}
428- </Text>
429- <Text className="font-mono text-[12px] font-t3-bold text-rose-600 dark:text-rose-300">
430- -{props.file.deletions}
431+ <Text
432+ className={cn(
433+ "text-[12px] font-t3-medium",
434+ viewed ? "text-foreground" : "text-foreground-muted",
435+ )}
436+ numberOfLines={1}
437+ >
438+ Viewed
439 </Text>
440- </View>
441+ </Pressable>
442 </View>
443- </Pressable>
444+ </View>
445 </View>
446 );
447 });
448@@ -342,7 +453,11 @@ const ReviewFileSuppressedBody = memo(function ReviewFileSuppressedBody(props: {
449 return (
450 <View
451 className="gap-2 border-b border-border bg-card px-4 py-3"
452- style={{ minWidth: props.viewportWidth }}
453+ style={{
454+ height: REVIEW_SUPPRESSED_ROW_HEIGHT,
455+ overflow: "hidden",
456+ width: props.viewportWidth,
457+ }}
458 >
459 <Text className="text-[12px] leading-[18px] text-foreground-muted">{props.message}</Text>
460 {props.actionLabel && props.onLoadDiffFile ? (
461@@ -364,10 +479,13 @@ const ReviewHunkRow = memo(function ReviewHunkRow(props: {
462 }) {
463 return (
464 <View
465- className="border-b border-border/60 bg-sky-500/10 px-2 py-2"
466- style={{ minWidth: props.viewportWidth }}
467+ className="border-b border-border/60 bg-sky-500/10 py-2"
468+ style={{ height: REVIEW_HUNK_ROW_HEIGHT, width: props.viewportWidth, overflow: "hidden" }}
469 >
470- <Text className="font-mono text-[12px] leading-[18px] text-sky-700 dark:text-sky-300">
471+ <Text
472+ className="px-2 font-mono text-[12px] leading-[18px] text-sky-700 dark:text-sky-300"
473+ numberOfLines={1}
474+ >
475 {props.header}
476 {props.context ? ` ${props.context}` : ""}
477 </Text>
478@@ -375,6 +493,61 @@ const ReviewHunkRow = memo(function ReviewHunkRow(props: {
479 );
480 });
481
482+const ReviewCodePanRow = memo(function ReviewCodePanRow(props: {
483+ readonly contentWidth: number;
484+ readonly horizontalOffset: SharedValue<number>;
485+ readonly gutterWidth?: number;
486+ readonly viewportWidth: number;
487+ readonly leftGutter?: ReactElement;
488+ readonly children: ReactElement;
489+}) {
490+ const {
491+ children,
492+ contentWidth,
493+ gutterWidth = 0,
494+ horizontalOffset,
495+ leftGutter,
496+ viewportWidth,
497+ } = props;
498+ const dragStartOffset = useSharedValue(0);
499+ const visibleContentWidth = leftGutter ? viewportWidth - gutterWidth : viewportWidth;
500+ const maxOffset = Math.max(0, contentWidth - visibleContentWidth);
501+
502+ const panGesture = useMemo(
503+ () =>
504+ Gesture.Pan()
505+ .activeOffsetX([-8, 8])
506+ .failOffsetY([-10, 10])
507+ .onBegin(() => {
508+ dragStartOffset.value = horizontalOffset.value;
509+ })
510+ .onUpdate((event) => {
511+ "worklet";
512+ const nextOffset = dragStartOffset.value - event.translationX;
513+ horizontalOffset.value = Math.min(maxOffset, Math.max(0, nextOffset));
514+ }),
515+ [dragStartOffset, horizontalOffset, maxOffset],
516+ );
517+
518+ const contentStyle = useAnimatedStyle(
519+ () => ({
520+ transform: [{ translateX: -horizontalOffset.value }],
521+ }),
522+ [horizontalOffset],
523+ );
524+
525+ return (
526+ <GestureDetector gesture={panGesture}>
527+ <View style={{ flexDirection: "row", overflow: "hidden", width: viewportWidth }}>
528+ {leftGutter ?? null}
529+ <View style={{ flex: 1, overflow: "hidden" }}>
530+ <Animated.View style={[{ width: contentWidth }, contentStyle]}>{children}</Animated.View>
531+ </View>
532+ </View>
533+ </GestureDetector>
534+ );
535+});
536+
537 const ReviewNotice = memo(function ReviewNotice(props: { readonly notice: string }) {
538 return (
539 <View className="border-b border-amber-200 bg-amber-50 px-4 py-3 dark:border-amber-900/60 dark:bg-amber-950/40">
540@@ -454,15 +627,19 @@ export function ReviewSheet() {
541 const [highlightedFilesById, setHighlightedFilesById] = useState<
542 Record<string, ReviewHighlightedFile | null>
543 >({});
544- const [visibleFileIds, setVisibleFileIds] = useState<ReadonlyArray<string>>([]);
545+ const deferredHighlightedFilesById = useDeferredValue(highlightedFilesById);
546+ const [localExpandedFileIdsBySection, setLocalExpandedFileIdsBySection] = useState<
547+ Record<string, ReadonlyArray<string>>
548+ >({});
549+ const [localViewedFileIdsBySection, setLocalViewedFileIdsBySection] = useState<
550+ Record<string, ReadonlyArray<string>>
551+ >({});
552 const activeCommentTarget = useReviewCommentTarget();
553 const selectedTheme = (colorScheme === "dark" ? "dark" : "light") satisfies ReviewDiffTheme;
554- const highlightQueueRef = useRef<string[]>([]);
555- const highlightRequestedFileIdsRef = useRef<Set<string>>(new Set());
556- const highlightQueueGenerationRef = useRef(0);
557- const highlightQueueActiveRef = useRef(false);
558- const highlightableFilesByIdRef = useRef<ReadonlyMap<string, ReviewRenderableFile>>(new Map());
559- const selectedThemeRef = useRef<ReviewDiffTheme>(selectedTheme);
560+ const reviewHighlighter = useReviewHighlighterStatus();
561+ const highlightRunIdRef = useRef(0);
562+ const highlightableFilesRef = useRef<ReadonlyArray<ReviewRenderableFile>>([]);
563+ const horizontalOffsetByFileIdRef = useRef<Map<string, SharedValue<number>>>(new Map());
564 const { selectedThreadCwd } = useSelectedThreadWorktree();
565
566 const cwd = selectedThreadCwd;
567@@ -498,11 +675,13 @@ export function ReviewSheet() {
568 const topContentInset = insets.top + IOS_NAV_BAR_HEIGHT;
569 const parsedDiff = useMemo(
570 () =>
571- getCachedReviewParsedDiff({
572- threadKey: reviewCache.threadKey,
573- sectionId: selectedSection?.id ?? null,
574- diff: selectedSection?.diff,
575- }),
576+ measureReviewWork("parse-diff", () =>
577+ getCachedReviewParsedDiff({
578+ threadKey: reviewCache.threadKey,
579+ sectionId: selectedSection?.id ?? null,
580+ diff: selectedSection?.diff,
581+ }),
582+ ),
583 [reviewCache.threadKey, selectedSection?.diff, selectedSection?.id],
584 );
585 const headerDiffSummary = useMemo(() => formatHeaderDiffSummary(parsedDiff), [parsedDiff]);
586@@ -510,14 +689,53 @@ export function ReviewSheet() {
587 () => countReviewCommentContexts(draftMessage),
588 [draftMessage],
589 );
590+ const viewportWidth = Math.max(width, 280);
591+
592+ useEffect(() => {
593+ if (!selectedSection?.id || parsedDiff.kind !== "files") {
594+ return;
595+ }
596+
597+ setLocalExpandedFileIdsBySection((current) => {
598+ if (current[selectedSection.id] !== undefined) {
599+ return current;
600+ }
601+
602+ return {
603+ ...current,
604+ [selectedSection.id]: getValidReviewExpandedFileIds(
605+ parsedDiff.files,
606+ reviewCache.expandedFileIdsBySection[selectedSection.id],
607+ ),
608+ };
609+ });
610+
611+ setLocalViewedFileIdsBySection((current) => {
612+ if (current[selectedSection.id] !== undefined) {
613+ return current;
614+ }
615+
616+ return {
617+ ...current,
618+ [selectedSection.id]: reviewCache.viewedFileIdsBySection[selectedSection.id] ?? [],
619+ };
620+ });
621+ }, [
622+ parsedDiff,
623+ reviewCache.expandedFileIdsBySection,
624+ reviewCache.viewedFileIdsBySection,
625+ selectedSection?.id,
626+ ]);
627
628 const expandedFileIds = useMemo(
629 () =>
630 selectedSection?.id && parsedDiff.kind === "files"
631- ? (reviewCache.expandedFileIdsBySection[selectedSection.id] ??
632- getDefaultExpandedFileIds(parsedDiff.files))
633+ ? getValidReviewExpandedFileIds(
634+ parsedDiff.files,
635+ localExpandedFileIdsBySection[selectedSection.id],
636+ )
637 : [],
638- [parsedDiff, reviewCache.expandedFileIdsBySection, selectedSection?.id],
639+ [localExpandedFileIdsBySection, parsedDiff, selectedSection?.id],
640 );
641 const revealedLargeFileIds = useMemo(
642 () =>
643@@ -526,47 +744,96 @@ export function ReviewSheet() {
644 : [],
645 [reviewCache.revealedLargeFileIdsBySection, selectedSection?.id],
646 );
647+ const viewedFileIds = useMemo(
648+ () => (selectedSection?.id ? (localViewedFileIdsBySection[selectedSection.id] ?? []) : []),
649+ [localViewedFileIdsBySection, selectedSection?.id],
650+ );
651+ const viewedFileIdSet = useMemo(() => new Set(viewedFileIds), [viewedFileIds]);
652 const reviewListItems = useMemo(
653 () =>
654 selectedSection && parsedDiff.kind === "files"
655- ? buildReviewListItems({
656- files: parsedDiff.files,
657- expandedFileIds,
658- revealedLargeFileIds,
659- })
660+ ? measureReviewWork("build-list-items", () =>
661+ buildReviewListItems({
662+ files: parsedDiff.files,
663+ expandedFileIds,
664+ revealedLargeFileIds,
665+ }),
666+ )
667 : [],
668 [expandedFileIds, parsedDiff, revealedLargeFileIds, selectedSection],
669 );
670- const reviewFileById = useMemo(() => {
671+ const reviewLineRowsByFileId = useMemo(() => {
672 if (parsedDiff.kind !== "files") {
673- return new Map<string, ReviewRenderableFile>();
674+ return new Map<string, ReadonlyArray<ReviewRenderableLineRow>>();
675 }
676
677- return new Map(parsedDiff.files.map((file) => [file.id, file] as const));
678+ return measureReviewWork(
679+ "index-line-rows",
680+ () =>
681+ new Map(
682+ parsedDiff.files.map((file) => [
683+ file.id,
684+ file.rows.filter((row): row is ReviewRenderableLineRow => row.kind === "line"),
685+ ]),
686+ ),
687+ );
688 }, [parsedDiff]);
689- const reviewLineRowsByFileId = useMemo(() => {
690+ const reviewContentWidthByFileId = useMemo(() => {
691 if (parsedDiff.kind !== "files") {
692- return new Map<string, ReadonlyArray<ReviewRenderableLineRow>>();
693+ return new Map<string, number>();
694+ }
695+
696+ return measureReviewWork(
697+ "measure-file-widths",
698+ () =>
699+ new Map(
700+ parsedDiff.files.map((file) => [
701+ file.id,
702+ computeReviewFileContentWidth(
703+ file.rows,
704+ viewportWidth,
705+ computeReviewFileGutterWidth(file.rows),
706+ ),
707+ ]),
708+ ),
709+ );
710+ }, [parsedDiff, viewportWidth]);
711+ const reviewGutterWidthByFileId = useMemo(() => {
712+ if (parsedDiff.kind !== "files") {
713+ return new Map<string, number>();
714 }
715
716 return new Map(
717- parsedDiff.files.map((file) => [
718- file.id,
719- file.rows.filter((row): row is ReviewRenderableLineRow => row.kind === "line"),
720- ]),
721+ parsedDiff.files.map((file) => [file.id, computeReviewFileGutterWidth(file.rows)]),
722 );
723 }, [parsedDiff]);
724- const reviewLineIndexByRowId = useMemo(() => {
725- const map = new Map<string, number>();
726+ const getReviewFileHorizontalOffset = useCallback((fileId: string) => {
727+ let offset = horizontalOffsetByFileIdRef.current.get(fileId);
728+ if (!offset) {
729+ offset = makeMutable(0);
730+ horizontalOffsetByFileIdRef.current.set(fileId, offset);
731+ }
732
733- reviewLineRowsByFileId.forEach((rows) => {
734- rows.forEach((row, index) => {
735- map.set(row.id, index);
736- });
737- });
738+ return offset;
739+ }, []);
740+ useEffect(() => {
741+ const knownFileIds =
742+ parsedDiff.kind === "files" ? new Set(parsedDiff.files.map((file) => file.id)) : new Set();
743
744- return map;
745- }, [reviewLineRowsByFileId]);
746+ horizontalOffsetByFileIdRef.current.forEach((offset, fileId) => {
747+ if (!knownFileIds.has(fileId)) {
748+ horizontalOffsetByFileIdRef.current.delete(fileId);
749+ return;
750+ }
751+
752+ const contentWidth = reviewContentWidthByFileId.get(fileId) ?? viewportWidth;
753+ const gutterWidth = reviewGutterWidthByFileId.get(fileId) ?? 0;
754+ offset.value = Math.min(
755+ offset.value,
756+ Math.max(0, contentWidth - (viewportWidth - gutterWidth)),
757+ );
758+ });
759+ }, [parsedDiff, reviewContentWidthByFileId, reviewGutterWidthByFileId, viewportWidth]);
760 const highlightableFiles = useMemo(() => {
761 if (parsedDiff.kind !== "files") {
762 return [] as ReadonlyArray<ReviewRenderableFile>;
763@@ -587,59 +854,13 @@ export function ReviewSheet() {
764 );
765 });
766 }, [expandedFileIds, parsedDiff, revealedLargeFileIds]);
767- const highlightableFileIds = useMemo(
768- () => new Set(highlightableFiles.map((file) => file.id)),
769+ const highlightableFilesKey = useMemo(
770+ () => highlightableFiles.map((file) => `${file.id}:${file.cacheKey}`).join("\n"),
771 [highlightableFiles],
772 );
773- const priorityHighlightFileIds = useMemo(() => {
774- if (parsedDiff.kind !== "files" || highlightableFiles.length === 0) {
775- return [] as ReadonlyArray<string>;
776- }
777-
778- const fileIdsInPriorityOrder =
779- visibleFileIds.length > 0
780- ? visibleFileIds.filter((fileId) => highlightableFileIds.has(fileId))
781- : parsedDiff.files
782- .slice(0, REVIEW_INITIAL_HIGHLIGHT_FILE_COUNT)
783- .map((file) => file.id)
784- .filter((fileId) => highlightableFileIds.has(fileId));
785-
786- if (fileIdsInPriorityOrder.length === 0) {
787- return [] as ReadonlyArray<string>;
788- }
789-
790- const firstVisibleIndex = parsedDiff.files.findIndex(
791- (file) => file.id === fileIdsInPriorityOrder[0],
792- );
793- const lastVisibleIndex = parsedDiff.files.findIndex(
794- (file) => file.id === fileIdsInPriorityOrder[fileIdsInPriorityOrder.length - 1],
795- );
796-
797- if (firstVisibleIndex < 0 || lastVisibleIndex < 0) {
798- return fileIdsInPriorityOrder;
799- }
800-
801- const startIndex = Math.max(0, firstVisibleIndex - REVIEW_HIGHLIGHT_BACKTRACK_COUNT);
802- const endIndex = Math.min(
803- parsedDiff.files.length - 1,
804- lastVisibleIndex + REVIEW_HIGHLIGHT_LOOKAHEAD_COUNT,
805- );
806-
807- const queuedIds: string[] = [];
808- for (let index = startIndex; index <= endIndex; index += 1) {
809- const fileId = parsedDiff.files[index]?.id;
810- if (fileId && highlightableFileIds.has(fileId)) {
811- queuedIds.push(fileId);
812- }
813- }
814-
815- return queuedIds;
816- }, [highlightableFileIds, highlightableFiles.length, parsedDiff, visibleFileIds]);
817- const viewportWidth = Math.max(width, 280);
818- const reviewListContentWidth = useMemo(
819- () => computeReviewListContentWidth(reviewListItems, viewportWidth),
820- [reviewListItems, viewportWidth],
821- );
822+ useEffect(() => {
823+ highlightableFilesRef.current = highlightableFiles;
824+ }, [highlightableFiles]);
825 const loadGitDiffs = useCallback(async () => {
826 if (!cwd) {
827 return;
828@@ -714,100 +935,6 @@ export function ReviewSheet() {
829 void loadGitDiffs();
830 }, [loadGitDiffs]);
831
832- useEffect(() => {
833- selectedThemeRef.current = selectedTheme;
834- }, [selectedTheme]);
835-
836- useEffect(() => {
837- highlightableFilesByIdRef.current = new Map(highlightableFiles.map((file) => [file.id, file]));
838- }, [highlightableFiles]);
839-
840- const startHighlightQueueRunner = useCallback(function startHighlightQueueRunner() {
841- if (highlightQueueActiveRef.current) {
842- return;
843- }
844-
845- const generation = highlightQueueGenerationRef.current;
846- highlightQueueActiveRef.current = true;
847-
848- void (async () => {
849- try {
850- while (generation === highlightQueueGenerationRef.current) {
851- const nextFileId = highlightQueueRef.current.shift();
852- if (!nextFileId) {
853- break;
854- }
855-
856- const file = highlightableFilesByIdRef.current.get(nextFileId);
857- if (!file) {
858- continue;
859- }
860-
861- const theme = selectedThemeRef.current;
862- const cached = getCachedHighlightedReviewFile(file, theme);
863- if (cached) {
864- logReviewDiffDiagnostic("using cached highlighted file", {
865- fileId: file.id,
866- filePath: file.path,
867- theme,
868- });
869- setHighlightedFilesById((current) =>
870- current[file.id] === cached ? current : { ...current, [file.id]: cached },
871- );
872- continue;
873- }
874-
875- logReviewDiffDiagnostic("requesting highlighted file", {
876- fileId: file.id,
877- filePath: file.path,
878- theme,
879- });
880-
881- try {
882- await new Promise<void>((resolve) => {
883- InteractionManager.runAfterInteractions(() => resolve());
884- });
885- const result = await highlightReviewFile(file, theme);
886- if (generation !== highlightQueueGenerationRef.current) {
887- logReviewDiffDiagnostic("discarding highlighted file after cancellation", {
888- fileId: file.id,
889- filePath: file.path,
890- });
891- return;
892- }
893-
894- logReviewDiffDiagnostic("received highlighted file", {
895- fileId: file.id,
896- filePath: file.path,
897- additionLines: result.additionLines.length,
898- deletionLines: result.deletionLines.length,
899- });
900- setHighlightedFilesById((current) => {
901- if (current[file.id] === result) {
902- return current;
903- }
904- return { ...current, [file.id]: result };
905- });
906- } catch (error) {
907- logReviewDiffDiagnostic("highlight request failed", {
908- fileId: file.id,
909- filePath: file.path,
910- error: error instanceof Error ? error.message : String(error),
911- });
912- }
913- }
914- } finally {
915- highlightQueueActiveRef.current = false;
916- if (
917- generation === highlightQueueGenerationRef.current &&
918- highlightQueueRef.current.length > 0
919- ) {
920- startHighlightQueueRunner();
921- }
922- }
923- })();
924- }, []);
925-
926 useEffect(() => {
927 if (reviewSections.length === 0) {
928 return;
929@@ -854,15 +981,15 @@ export function ReviewSheet() {
930 }
931
932 updateReviewExpandedFileIds(reviewCache.threadKey, selectedSection.id, (existing) => {
933- if (existing !== undefined) {
934- const validIds = existing.filter((id) => parsedDiff.files.some((file) => file.id === id));
935- if (validIds.length === existing.length) {
936- return existing;
937- }
938- return validIds;
939+ const validIds = getValidReviewExpandedFileIds(parsedDiff.files, existing);
940+ if (
941+ existing !== undefined &&
942+ validIds.length === existing.length &&
943+ validIds.every((id, index) => id === existing[index])
944+ ) {
945+ return existing;
946 }
947-
948- return getDefaultExpandedFileIds(parsedDiff.files);
949+ return validIds;
950 });
951 }, [parsedDiff, reviewCache.threadKey, selectedSection?.id]);
952
953@@ -887,11 +1014,7 @@ export function ReviewSheet() {
954
955 useEffect(() => {
956 setHighlightedFilesById({});
957- setVisibleFileIds([]);
958- highlightQueueGenerationRef.current += 1;
959- highlightQueueRef.current = [];
960- highlightRequestedFileIdsRef.current = new Set();
961- highlightQueueActiveRef.current = false;
962+ highlightRunIdRef.current += 1;
963 clearReviewHighlightFileCache();
964 loggedMissingReviewTokenKeys.clear();
965 logReviewDiffDiagnostic("reset highlighted files", {
966@@ -905,15 +1028,23 @@ export function ReviewSheet() {
967 return;
968 }
969
970+ markReviewEvent("parsed-diff-ready", {
971+ sectionId: selectedSection?.id ?? null,
972+ fileCount: parsedDiff.fileCount,
973+ additions: parsedDiff.additions,
974+ deletions: parsedDiff.deletions,
975+ renderedItems: reviewListItems.length,
976+ });
977 logReviewDiffDiagnostic("parsed diff files", {
978 selectedSectionId: selectedSection?.id ?? null,
979 fileCount: parsedDiff.fileCount,
980 renderableFileCount: parsedDiff.files.length,
981 });
982- }, [parsedDiff, selectedSection?.id]);
983+ }, [parsedDiff, reviewListItems.length, selectedSection?.id]);
984
985 useEffect(() => {
986- if (priorityHighlightFileIds.length === 0) {
987+ const files = highlightableFilesRef.current;
988+ if (files.length === 0) {
989 logReviewDiffDiagnostic("no highlightable files", {
990 selectedSectionId: selectedSection?.id ?? null,
991 parsedDiffKind: parsedDiff.kind,
992@@ -922,33 +1053,98 @@ export function ReviewSheet() {
993 return;
994 }
995
996- const queuedFileIds: string[] = [];
997- priorityHighlightFileIds.forEach((fileId) => {
998- if (highlightRequestedFileIdsRef.current.has(fileId)) {
999- return;
1000- }
1001-
1002- const file = highlightableFilesByIdRef.current.get(fileId);
1003- if (!file) {
1004- return;
1005- }
1006-
1007- highlightRequestedFileIdsRef.current.add(fileId);
1008- highlightQueueRef.current.push(fileId);
1009- queuedFileIds.push(fileId);
1010- });
1011-
1012- if (queuedFileIds.length === 0) {
1013+ if (reviewHighlighter.status !== "ready") {
1014+ logReviewDiffDiagnostic("waiting for highlighter provider", {
1015+ selectedSectionId: selectedSection?.id ?? null,
1016+ status: reviewHighlighter.status,
1017+ error: reviewHighlighter.error,
1018+ });
1019 return;
1020 }
1021
1022- logReviewDiffDiagnostic("scheduling file highlights", {
1023+ const runId = highlightRunIdRef.current;
1024+ let cancelled = false;
1025+
1026+ logReviewDiffDiagnostic("streaming file highlights", {
1027 selectedSectionId: selectedSection?.id ?? null,
1028- fileCount: queuedFileIds.length,
1029- fileIds: queuedFileIds,
1030+ fileCount: files.length,
1031 });
1032- startHighlightQueueRunner();
1033- }, [parsedDiff.kind, priorityHighlightFileIds, selectedSection?.id, startHighlightQueueRunner]);
1034+
1035+ void (async () => {
1036+ for (const file of files) {
1037+ if (cancelled || runId !== highlightRunIdRef.current) {
1038+ return;
1039+ }
1040+
1041+ const cached = getCachedHighlightedReviewFile(file, selectedTheme);
1042+ if (cached) {
1043+ setHighlightedFilesById((current) =>
1044+ current[file.id] === cached ? current : { ...current, [file.id]: cached },
1045+ );
1046+ continue;
1047+ }
1048+
1049+ logReviewDiffDiagnostic("requesting highlighted file", {
1050+ fileId: file.id,
1051+ filePath: file.path,
1052+ theme: selectedTheme,
1053+ });
1054+
1055+ try {
1056+ const highlightStartedAt = performance.now();
1057+ const result = await streamHighlightReviewFile(file, selectedTheme, (progress) => {
1058+ if (cancelled || runId !== highlightRunIdRef.current) {
1059+ return;
1060+ }
1061+
1062+ if (!progress.complete) {
1063+ return;
1064+ }
1065+
1066+ logReviewDiffDiagnostic("received streamed highlighted file", {
1067+ fileId: file.id,
1068+ filePath: file.path,
1069+ highlightedLineCount: progress.highlightedLineCount,
1070+ durationMs: Math.round(performance.now() - highlightStartedAt),
1071+ });
1072+ });
1073+
1074+ if (cancelled || runId !== highlightRunIdRef.current) {
1075+ return;
1076+ }
1077+
1078+ logReviewDiffDiagnostic("received highlighted file", {
1079+ fileId: file.id,
1080+ filePath: file.path,
1081+ additionLines: result.additionLines.length,
1082+ deletionLines: result.deletionLines.length,
1083+ });
1084+ setHighlightedFilesById((current) =>
1085+ current[file.id] === result ? current : { ...current, [file.id]: result },
1086+ );
1087+ } catch (error) {
1088+ logReviewDiffDiagnostic("highlight request failed", {
1089+ fileId: file.id,
1090+ filePath: file.path,
1091+ error: error instanceof Error ? error.message : String(error),
1092+ });
1093+ }
1094+
1095+ await waitForReviewDelay(0);
1096+ }
1097+ })();
1098+
1099+ return () => {
1100+ cancelled = true;
1101+ };
1102+ }, [
1103+ highlightableFilesKey,
1104+ parsedDiff.kind,
1105+ reviewHighlighter.error,
1106+ reviewHighlighter.status,
1107+ selectedSection?.id,
1108+ selectedTheme,
1109+ ]);
1110
1111 const refreshSelectedSection = useCallback(async () => {
1112 if (!selectedSection) {
1113@@ -968,20 +1164,68 @@ export function ReviewSheet() {
1114
1115 const handleToggleExpandedFile = useCallback(
1116 (fileId: string) => {
1117- if (!reviewCache.threadKey || !selectedSection?.id || parsedDiff.kind !== "files") {
1118+ if (!selectedSection?.id || parsedDiff.kind !== "files") {
1119 return;
1120 }
1121
1122- updateReviewExpandedFileIds(reviewCache.threadKey, selectedSection.id, (existing) => {
1123- const currentIds = existing ?? getDefaultExpandedFileIds(parsedDiff.files);
1124- return currentIds.includes(fileId)
1125+ const sectionId = selectedSection.id;
1126+
1127+ setLocalExpandedFileIdsBySection((current) => {
1128+ const currentIds = getValidReviewExpandedFileIds(parsedDiff.files, current[sectionId]);
1129+ const nextIds = currentIds.includes(fileId)
1130 ? currentIds.filter((id) => id !== fileId)
1131 : [...currentIds, fileId];
1132+
1133+ return {
1134+ ...current,
1135+ [sectionId]: nextIds,
1136+ };
1137 });
1138+
1139+ if (reviewCache.threadKey) {
1140+ updateReviewExpandedFileIds(reviewCache.threadKey, sectionId, (existing) => {
1141+ const currentIds = getValidReviewExpandedFileIds(parsedDiff.files, existing);
1142+ return currentIds.includes(fileId)
1143+ ? currentIds.filter((id) => id !== fileId)
1144+ : [...currentIds, fileId];
1145+ });
1146+ }
1147 },
1148 [parsedDiff, reviewCache.threadKey, selectedSection?.id],
1149 );
1150
1151+ const handleToggleViewedFile = useCallback(
1152+ (fileId: string) => {
1153+ if (!selectedSection?.id) {
1154+ return;
1155+ }
1156+
1157+ const sectionId = selectedSection.id;
1158+
1159+ setLocalViewedFileIdsBySection((current) => {
1160+ const currentIds = current[sectionId] ?? [];
1161+ const nextIds = currentIds.includes(fileId)
1162+ ? currentIds.filter((id) => id !== fileId)
1163+ : [...currentIds, fileId];
1164+
1165+ return {
1166+ ...current,
1167+ [sectionId]: nextIds,
1168+ };
1169+ });
1170+
1171+ if (reviewCache.threadKey) {
1172+ updateReviewViewedFileIds(reviewCache.threadKey, sectionId, (existing) => {
1173+ const currentIds = existing ?? [];
1174+ return currentIds.includes(fileId)
1175+ ? currentIds.filter((id) => id !== fileId)
1176+ : [...currentIds, fileId];
1177+ });
1178+ }
1179+ },
1180+ [reviewCache.threadKey, selectedSection?.id],
1181+ );
1182+
1183 const handleRevealLargeDiff = useCallback(
1184 (fileId: string) => {
1185 if (!reviewCache.threadKey || !selectedSection?.id) {
1186@@ -1080,35 +1324,6 @@ export function ReviewSheet() {
1187
1188 return <>{children}</>;
1189 }, [error, parsedDiffNotice]);
1190- const stickyHeaderIndices = useMemo(() => {
1191- const itemOffset = listHeader ? 1 : 0;
1192-
1193- return reviewListItems.flatMap((item, index) =>
1194- item.kind === "file-header" ? [index + itemOffset] : [],
1195- );
1196- }, [listHeader, reviewListItems]);
1197-
1198- const viewabilityConfigRef = useRef({
1199- itemVisiblePercentThreshold: 10,
1200- });
1201- const onViewableItemsChangedRef = useRef(
1202- ({
1203- viewableItems,
1204- }: {
1205- readonly viewableItems: Array<ViewToken<ReviewListItem>>;
1206- readonly changed: Array<ViewToken<ReviewListItem>>;
1207- }) => {
1208- const nextVisibleFileIds = Array.from(
1209- new Set(
1210- viewableItems
1211- .filter((token) => token.isViewable && token.item !== undefined)
1212- .map((token) => token.item.fileId),
1213- ),
1214- );
1215-
1216- setVisibleFileIds(nextVisibleFileIds);
1217- },
1218- );
1219
1220 const renderReviewListItem = useCallback(
1221 ({ item }: ListRenderItemInfo<ReviewListItem>) => {
1222@@ -1116,112 +1331,142 @@ export function ReviewSheet() {
1223 return null;
1224 }
1225
1226+ let renderedItem: ReactElement | null = null;
1227 switch (item.kind) {
1228 case "file-header":
1229- return (
1230+ renderedItem = (
1231 <ReviewFileCard
1232 file={item.file}
1233 fileId={item.fileId}
1234 expanded={item.expanded}
1235- viewportWidth={reviewListContentWidth}
1236+ viewed={viewedFileIdSet.has(item.fileId)}
1237+ viewportWidth={viewportWidth}
1238 onToggleFile={handleToggleExpandedFile}
1239+ onToggleViewed={handleToggleViewedFile}
1240 />
1241 );
1242+ break;
1243 case "file-suppressed":
1244- return (
1245+ renderedItem = (
1246 <ReviewFileSuppressedBody
1247 message={item.message}
1248 actionLabel={item.actionLabel}
1249 fileId={item.fileId}
1250- viewportWidth={reviewListContentWidth}
1251+ viewportWidth={viewportWidth}
1252 onLoadDiffFile={handleRevealLargeDiff}
1253 />
1254 );
1255- case "hunk":
1256- return (
1257- <ReviewHunkRow
1258- header={item.row.header}
1259- context={item.row.context}
1260- viewportWidth={reviewListContentWidth}
1261- />
1262+ break;
1263+ case "hunk": {
1264+ const contentWidth = reviewContentWidthByFileId.get(item.fileId) ?? viewportWidth;
1265+ const gutterWidth = reviewGutterWidthByFileId.get(item.fileId) ?? 0;
1266+
1267+ renderedItem = (
1268+ <ReviewCodePanRow
1269+ key={item.id}
1270+ contentWidth={contentWidth}
1271+ gutterWidth={gutterWidth}
1272+ horizontalOffset={getReviewFileHorizontalOffset(item.fileId)}
1273+ leftGutter={<ReviewHunkGutter gutterWidth={gutterWidth} />}
1274+ viewportWidth={viewportWidth}
1275+ >
1276+ <ReviewHunkRow
1277+ header={item.row.header}
1278+ context={item.row.context}
1279+ viewportWidth={contentWidth}
1280+ />
1281+ </ReviewCodePanRow>
1282 );
1283+ break;
1284+ }
1285 case "line": {
1286- const file = reviewFileById.get(item.fileId);
1287- if (!file) {
1288- return null;
1289- }
1290-
1291- const fileLineRows = reviewLineRowsByFileId.get(file.id) ?? [];
1292- const lineIndex = reviewLineIndexByRowId.get(item.row.id);
1293- if (lineIndex === undefined) {
1294- return null;
1295- }
1296-
1297+ const fileLineRows = reviewLineRowsByFileId.get(item.file.id) ?? [];
1298 const pendingSelectionForFile =
1299 pendingCommentSelection &&
1300 pendingCommentSelection.sectionTitle === selectedSection.title &&
1301- pendingCommentSelection.filePath === file.path
1302+ pendingCommentSelection.filePath === item.file.path
1303 ? pendingCommentSelection
1304 : null;
1305 const selectedTargetForFile =
1306 activeCommentTarget &&
1307 activeCommentTarget.sectionTitle === selectedSection.title &&
1308- activeCommentTarget.filePath === file.path
1309+ activeCommentTarget.filePath === item.file.path
1310 ? activeCommentTarget
1311 : null;
1312 const highlightedFile =
1313- highlightedFilesById[file.id] ??
1314- getCachedHighlightedReviewFile(file, selectedTheme) ??
1315+ deferredHighlightedFilesById[item.file.id] ??
1316+ getCachedHighlightedReviewFile(item.file, selectedTheme) ??
1317 null;
1318+ const contentWidth = reviewContentWidthByFileId.get(item.fileId) ?? viewportWidth;
1319+ const gutterWidth = reviewGutterWidthByFileId.get(item.fileId) ?? 0;
1320
1321 if (highlightedFile === null) {
1322- const missingTokenKey = `${selectedSection.id}:${file.id}`;
1323+ const missingTokenKey = `${selectedSection.id}:${item.file.id}`;
1324 if (!loggedMissingReviewTokenKeys.has(missingTokenKey)) {
1325 loggedMissingReviewTokenKeys.add(missingTokenKey);
1326 logReviewDiffDiagnostic("rendering file without tokens", {
1327 sectionId: selectedSection.id,
1328- fileId: file.id,
1329- filePath: file.path,
1330- highlightedFileKnownInState: highlightedFilesById[file.id] !== undefined,
1331+ fileId: item.file.id,
1332+ filePath: item.file.path,
1333+ highlightedFileKnownInState:
1334+ deferredHighlightedFilesById[item.file.id] !== undefined,
1335 });
1336 }
1337 }
1338
1339 const selectionState =
1340- pendingSelectionForFile?.anchorIndex === lineIndex
1341+ pendingSelectionForFile?.anchorIndex === item.lineIndex
1342 ? ("anchor" as const)
1343 : selectedTargetForFile &&
1344- lineIndex >= selectedTargetForFile.startIndex &&
1345- lineIndex <= selectedTargetForFile.endIndex
1346+ item.lineIndex >= selectedTargetForFile.startIndex &&
1347+ item.lineIndex <= selectedTargetForFile.endIndex
1348 ? ("selected" as const)
1349 : null;
1350
1351- return (
1352- <ReviewLineRow
1353- line={item.row}
1354- tokens={getHighlightedTokensForLine(item.row, highlightedFile)}
1355- viewportWidth={reviewListContentWidth}
1356- selectionState={selectionState}
1357- onComment={() =>
1358- handlePressLine({
1359- sectionTitle: selectedSection.title,
1360- filePath: file.path,
1361- lines: fileLineRows,
1362- lineIndex,
1363- })
1364- }
1365- onStartRangeSelection={() =>
1366- handleStartRangeSelection({
1367- sectionTitle: selectedSection.title,
1368- filePath: file.path,
1369- lines: fileLineRows,
1370- lineIndex,
1371- })
1372+ renderedItem = (
1373+ <ReviewCodePanRow
1374+ key={item.id}
1375+ contentWidth={contentWidth}
1376+ gutterWidth={gutterWidth}
1377+ horizontalOffset={getReviewFileHorizontalOffset(item.fileId)}
1378+ leftGutter={
1379+ <ReviewLineGutter
1380+ change={item.row.change}
1381+ gutterWidth={gutterWidth}
1382+ lineNumber={getReviewUnifiedLineNumber(item.row)}
1383+ />
1384 }
1385- />
1386+ viewportWidth={viewportWidth}
1387+ >
1388+ <ReviewLineRow
1389+ line={item.row}
1390+ tokens={getHighlightedTokensForLine(item.row, highlightedFile)}
1391+ viewportWidth={contentWidth}
1392+ selectionState={selectionState}
1393+ onComment={() =>
1394+ handlePressLine({
1395+ sectionTitle: selectedSection.title,
1396+ filePath: item.file.path,
1397+ lines: fileLineRows,
1398+ lineIndex: item.lineIndex,
1399+ })
1400+ }
1401+ onStartRangeSelection={() =>
1402+ handleStartRangeSelection({
1403+ sectionTitle: selectedSection.title,
1404+ filePath: item.file.path,
1405+ lines: fileLineRows,
1406+ lineIndex: item.lineIndex,
1407+ })
1408+ }
1409+ />
1410+ </ReviewCodePanRow>
1411 );
1412+ break;
1413 }
1414 }
1415+
1416+ return renderedItem;
1417 },
1418 [
1419 activeCommentTarget,
1420@@ -1229,14 +1474,17 @@ export function ReviewSheet() {
1421 handleRevealLargeDiff,
1422 handleStartRangeSelection,
1423 handleToggleExpandedFile,
1424- highlightedFilesById,
1425+ handleToggleViewedFile,
1426+ getReviewFileHorizontalOffset,
1427+ deferredHighlightedFilesById,
1428 pendingCommentSelection,
1429- reviewFileById,
1430- reviewLineIndexByRowId,
1431+ reviewContentWidthByFileId,
1432+ reviewGutterWidthByFileId,
1433 reviewLineRowsByFileId,
1434- reviewListContentWidth,
1435 selectedSection,
1436 selectedTheme,
1437+ viewedFileIdSet,
1438+ viewportWidth,
1439 ],
1440 );
1441
1442@@ -1374,27 +1622,20 @@ export function ReviewSheet() {
1443 <View className="flex-1 bg-sheet">
1444 {selectedSection && parsedDiff.kind === "files" ? (
1445 <FlatList
1446- style={{ flex: 1 }}
1447+ style={{ flex: 1, width: viewportWidth }}
1448 contentInsetAdjustmentBehavior="never"
1449- contentInset={{ top: topContentInset }}
1450- contentOffset={{ x: 0, y: -topContentInset }}
1451- scrollIndicatorInsets={{ top: topContentInset }}
1452 data={reviewListItems}
1453 renderItem={renderReviewListItem}
1454 keyExtractor={(item) => item.id}
1455+ initialNumToRender={20}
1456+ maxToRenderPerBatch={20}
1457+ updateCellsBatchingPeriod={16}
1458+ windowSize={5}
1459+ removeClippedSubviews={false}
1460 keyboardShouldPersistTaps="handled"
1461 ListHeaderComponent={listHeader}
1462- stickyHeaderIndices={stickyHeaderIndices}
1463- removeClippedSubviews={false}
1464- initialNumToRender={24}
1465- maxToRenderPerBatch={16}
1466- updateCellsBatchingPeriod={16}
1467- windowSize={10}
1468- scrollEventThrottle={16}
1469- onViewableItemsChanged={onViewableItemsChangedRef.current}
1470- viewabilityConfig={viewabilityConfigRef.current}
1471 contentContainerStyle={{
1472- paddingTop: REVIEW_HEADER_SPACING,
1473+ paddingTop: topContentInset + REVIEW_HEADER_SPACING,
1474 paddingBottom: Math.max(insets.bottom, 18) + 18,
1475 }}
1476 />
1477diff --git a/apps/mobile/src/features/review/shikiReviewHighlighter.ts b/apps/mobile/src/features/review/shikiReviewHighlighter.ts
1478index f7a5c4125..eb6bf6973 100644
1479--- a/apps/mobile/src/features/review/shikiReviewHighlighter.ts
1480+++ b/apps/mobile/src/features/review/shikiReviewHighlighter.ts
1481@@ -1,5 +1,14 @@
1482 import { createHighlighterCore, type HighlighterCore } from "@shikijs/core";
1483 import { createJavaScriptRegexEngine } from "@shikijs/engine-javascript";
1484+import bashLanguage from "@shikijs/langs/bash";
1485+import javascriptLanguage from "@shikijs/langs/javascript";
1486+import jsonLanguage from "@shikijs/langs/json";
1487+import jsxLanguage from "@shikijs/langs/jsx";
1488+import tsxLanguage from "@shikijs/langs/tsx";
1489+import typescriptLanguage from "@shikijs/langs/typescript";
1490+import yamlLanguage from "@shikijs/langs/yaml";
1491+import githubDarkDefault from "@shikijs/themes/github-dark-default";
1492+import githubLightDefault from "@shikijs/themes/github-light-default";
1493 import { getFiletypeFromFileName } from "@pierre/diffs/utils";
1494
1495 import {
1496@@ -11,6 +20,7 @@ import type { ReviewRenderableFile, ReviewRenderableLineRow } from "./reviewMode
1497 import { applyDiffRangesToTokens, computeWordAltDiffRanges } from "./reviewWordDiffs";
1498
1499 export type ReviewDiffTheme = "light" | "dark";
1500+export type { ReviewHighlighterEngine };
1501
1502 export interface ReviewHighlightedToken {
1503 content: string;
1504@@ -24,12 +34,19 @@ export interface ReviewHighlightedFile {
1505 readonly deletionLines: ReadonlyArray<ReadonlyArray<ReviewHighlightedToken>>;
1506 }
1507
1508+export interface ReviewHighlightFileProgress {
1509+ readonly highlightedFile: ReviewHighlightedFile;
1510+ readonly complete: boolean;
1511+ readonly highlightedLineCount: number;
1512+}
1513+
1514 const SHIKI_THEME_NAME_BY_SCHEME = {
1515 light: "github-light-default",
1516 dark: "github-dark-default",
1517 } as const;
1518 const REVIEW_HIGHLIGHTER_ENGINE_ENV_VALUE =
1519- process.env.EXPO_PUBLIC_REVIEW_HIGHLIGHTER_ENGINE ?? "javascript";
1520+ process.env.EXPO_PUBLIC_REVIEW_HIGHLIGHTER_ENGINE ??
1521+ (process.env.NODE_ENV === "test" ? "javascript" : "native");
1522 const REVIEW_HIGHLIGHTER_ENGINE_PREFERENCE = resolveReviewHighlighterEnginePreference(
1523 REVIEW_HIGHLIGHTER_ENGINE_ENV_VALUE,
1524 );
1525@@ -38,12 +55,30 @@ const REVIEW_HIGHLIGHTER_DISABLE_RESULT_CACHE = resolveReviewHighlighterBooleanF
1526 false,
1527 );
1528 const REVIEW_HIGHLIGHT_RESULT_CACHE_LIMIT = 8;
1529-const REVIEW_HIGHLIGHT_CHUNK_LINE_THRESHOLD = 40;
1530-const REVIEW_HIGHLIGHT_CHUNK_SIZE = 20;
1531+const REVIEW_HIGHLIGHT_CHUNK_LINE_THRESHOLD = 8;
1532+const REVIEW_HIGHLIGHT_CHUNK_SIZE = 200;
1533 const REVIEW_TOKENIZE_MAX_LINE_LENGTH = 1_000;
1534 const highlightCache = new Map<string, Promise<ReviewHighlightedFile>>();
1535 const resolvedHighlightCache = new Map<string, ReviewHighlightedFile>();
1536-const loadedLanguages = new Set<string>(["text"]);
1537+const REVIEW_INITIAL_LANGUAGE_MODULES = [
1538+ bashLanguage,
1539+ javascriptLanguage,
1540+ jsonLanguage,
1541+ jsxLanguage,
1542+ tsxLanguage,
1543+ typescriptLanguage,
1544+ yamlLanguage,
1545+] satisfies Parameters<typeof createHighlighterCore>[0]["langs"];
1546+const loadedLanguages = new Set<string>([
1547+ "text",
1548+ "bash",
1549+ "javascript",
1550+ "json",
1551+ "jsx",
1552+ "tsx",
1553+ "typescript",
1554+ "yaml",
1555+]);
1556 const languageLoadingPromises = new Map<string, Promise<boolean>>();
1557 const languageImports: Partial<Record<string, () => Promise<unknown>>> = {
1558 javascript: () => import("@shikijs/langs/javascript"),
1559@@ -215,21 +250,13 @@ function joinPatchLines(lines: ReadonlyArray<string>): string {
1560
1561 function waitForNextFrame(): Promise<void> {
1562 return new Promise((resolve) => {
1563- if (typeof requestAnimationFrame === "function") {
1564- requestAnimationFrame(() => resolve());
1565- return;
1566- }
1567-
1568 setTimeout(resolve, 0);
1569 });
1570 }
1571
1572 async function getHighlighter(): Promise<HighlighterCore> {
1573 if (!highlighterPromise) {
1574- const configuredHighlighterPromise = Promise.all([
1575- import("@shikijs/themes/github-light-default"),
1576- import("@shikijs/themes/github-dark-default"),
1577- ]).then(async ([lightThemeModule, darkThemeModule]) => {
1578+ const configuredHighlighterPromise = (async () => {
1579 let nativeEngineAvailable = false;
1580
1581 logReviewHighlighterDiagnostic("initializing", {
1582@@ -238,12 +265,11 @@ async function getHighlighter(): Promise<HighlighterCore> {
1583 resultCacheDisabled: REVIEW_HIGHLIGHTER_DISABLE_RESULT_CACHE,
1584 });
1585
1586- const themes = [lightThemeModule.default, darkThemeModule.default];
1587+ const themes = [githubLightDefault, githubDarkDefault];
1588
1589 if (REVIEW_HIGHLIGHTER_ENGINE_PREFERENCE !== "javascript") {
1590 try {
1591 const nativeEngineModule = await import("react-native-shiki-engine");
1592- logReviewHighlighterDiagnostic("imported react-native-shiki-engine");
1593 nativeEngineAvailable = nativeEngineModule.isNativeEngineAvailable();
1594 logReviewHighlighterDiagnostic("checked native engine availability", {
1595 nativeEngineAvailable,
1596@@ -253,7 +279,7 @@ async function getHighlighter(): Promise<HighlighterCore> {
1597 logReviewHighlighterDiagnostic("creating native regex engine");
1598 const highlighter = await createHighlighterCore({
1599 themes,
1600- langs: [],
1601+ langs: REVIEW_INITIAL_LANGUAGE_MODULES,
1602 engine: nativeEngineModule.createNativeEngine(),
1603 });
1604 logReviewHighlighterDiagnostic("using native engine");
1605@@ -281,7 +307,7 @@ async function getHighlighter(): Promise<HighlighterCore> {
1606 );
1607 const highlighter = await createHighlighterCore({
1608 themes,
1609- langs: [],
1610+ langs: REVIEW_INITIAL_LANGUAGE_MODULES,
1611 engine: createJavaScriptRegexEngine(),
1612 });
1613 logReviewHighlighterDiagnostic("using javascript engine", {
1614@@ -291,7 +317,7 @@ async function getHighlighter(): Promise<HighlighterCore> {
1615 highlighter,
1616 engine,
1617 };
1618- });
1619+ })();
1620
1621 highlighterPromise = configuredHighlighterPromise
1622 .then((result) => result.highlighter)
1623@@ -316,11 +342,52 @@ export async function getActiveReviewHighlighterEngine(): Promise<ReviewHighligh
1624 return activeHighlighterEnginePromise ?? Promise.resolve("javascript");
1625 }
1626
1627+export async function prepareReviewHighlighter(): Promise<void> {
1628+ await getHighlighter();
1629+}
1630+
1631+export async function prepareReviewHighlighterLanguages(
1632+ languages: ReadonlyArray<string>,
1633+): Promise<void> {
1634+ const highlighter = await getHighlighter();
1635+ await Promise.all(
1636+ languages.map(async (language) => {
1637+ const candidate = resolveLanguageAlias(language);
1638+ if (candidate === "text" || !(candidate in languageImports)) {
1639+ return;
1640+ }
1641+
1642+ await loadSingleLanguage(highlighter, candidate);
1643+ }),
1644+ );
1645+}
1646+
1647 function resolveLanguageAlias(language: string): string {
1648 const normalized = language.toLowerCase();
1649 return languageAliases[normalized] ?? normalized;
1650 }
1651
1652+function resolveLoadedLanguageFromPath(
1653+ path: string,
1654+ languageHint: string | null = null,
1655+): string | null {
1656+ const detectedLanguage = languageHint ?? getFiletypeFromFileName(path);
1657+ if (!detectedLanguage) {
1658+ return "text";
1659+ }
1660+
1661+ const candidate = resolveLanguageAlias(detectedLanguage);
1662+ if (candidate === "text" || candidate === "ansi") {
1663+ return "text";
1664+ }
1665+
1666+ if (!(candidate in languageImports)) {
1667+ return "text";
1668+ }
1669+
1670+ return loadedLanguages.has(candidate) ? candidate : null;
1671+}
1672+
1673 async function loadSingleLanguage(
1674 highlighter: HighlighterCore,
1675 language: string,
1676@@ -360,6 +427,11 @@ async function resolveLanguageFromPath(
1677 path: string,
1678 languageHint: string | null = null,
1679 ): Promise<string> {
1680+ const loadedLanguage = resolveLoadedLanguageFromPath(path, languageHint);
1681+ if (loadedLanguage) {
1682+ return loadedLanguage;
1683+ }
1684+
1685 const detectedLanguage = languageHint ?? getFiletypeFromFileName(path);
1686 if (!detectedLanguage) {
1687 return "text";
1688@@ -374,8 +446,12 @@ async function resolveLanguageFromPath(
1689 return "text";
1690 }
1691
1692+ if (loadedLanguages.has(candidate)) {
1693+ return candidate;
1694+ }
1695+
1696 const highlighter = await getHighlighter();
1697- const loaded = await loadSingleLanguage(highlighter, resolveLanguageAlias(candidate));
1698+ const loaded = await loadSingleLanguage(highlighter, candidate);
1699 if (!loaded) {
1700 return "text";
1701 }
1702@@ -384,7 +460,10 @@ async function resolveLanguageFromPath(
1703 }
1704
1705 async function resolveLanguage(file: ReviewRenderableFile): Promise<string> {
1706- return resolveLanguageFromPath(file.path, file.languageHint);
1707+ return (
1708+ resolveLoadedLanguageFromPath(file.path, file.languageHint) ??
1709+ (await resolveLanguageFromPath(file.path, file.languageHint))
1710+ );
1711 }
1712
1713 function normalizeHighlightedLines(
1714@@ -399,6 +478,18 @@ function normalizeHighlightedLines(
1715 );
1716 }
1717
1718+function makePlainHighlightedLines(
1719+ lines: ReadonlyArray<string>,
1720+): ReadonlyArray<ReadonlyArray<ReviewHighlightedToken>> {
1721+ return lines.map((line) => [
1722+ {
1723+ content: stripTrailingNewline(line),
1724+ color: null,
1725+ fontStyle: null,
1726+ },
1727+ ]);
1728+}
1729+
1730 function applyWordAltDiffHighlightsToFile(
1731 file: ReviewRenderableFile,
1732 highlighted: ReviewHighlightedFile,
1733@@ -594,6 +685,67 @@ async function highlightLines(
1734 return highlightedLines;
1735 }
1736
1737+async function highlightPatchLinesInChunks(input: {
1738+ readonly lines: ReadonlyArray<string>;
1739+ readonly language: string;
1740+ readonly theme: string;
1741+ readonly onChunk: (
1742+ startIndex: number,
1743+ tokens: ReadonlyArray<ReadonlyArray<ReviewHighlightedToken>>,
1744+ ) => void;
1745+}): Promise<ReadonlyArray<ReadonlyArray<ReviewHighlightedToken>>> {
1746+ if (input.lines.length === 0) {
1747+ return [];
1748+ }
1749+
1750+ const highlighter = await getHighlighter();
1751+ const highlightedLines: Array<ReadonlyArray<ReviewHighlightedToken>> = [];
1752+
1753+ for (
1754+ let startIndex = 0;
1755+ startIndex < input.lines.length;
1756+ startIndex += REVIEW_HIGHLIGHT_CHUNK_SIZE
1757+ ) {
1758+ const lineChunk = input.lines.slice(startIndex, startIndex + REVIEW_HIGHLIGHT_CHUNK_SIZE);
1759+ const chunkTokens: Array<ReadonlyArray<ReviewHighlightedToken>> = [];
1760+ const tokenizableLines: string[] = [];
1761+ const tokenizableIndexes: number[] = [];
1762+
1763+ lineChunk.forEach((line, index) => {
1764+ const strippedLine = stripTrailingNewline(line);
1765+ if (strippedLine.length > REVIEW_TOKENIZE_MAX_LINE_LENGTH) {
1766+ chunkTokens[index] = [{ content: strippedLine, color: null, fontStyle: null }];
1767+ return;
1768+ }
1769+
1770+ tokenizableIndexes.push(index);
1771+ tokenizableLines.push(strippedLine);
1772+ });
1773+
1774+ if (tokenizableLines.length > 0) {
1775+ const tokenLines = highlighter.codeToTokensBase(tokenizableLines.join("\n"), {
1776+ lang: input.language,
1777+ theme: input.theme,
1778+ });
1779+ const normalizedTokenLines = normalizeHighlightedLines(tokenLines);
1780+
1781+ tokenizableIndexes.forEach((chunkIndex, tokenIndex) => {
1782+ chunkTokens[chunkIndex] = normalizedTokenLines[tokenIndex] ?? [];
1783+ });
1784+ }
1785+
1786+ const completedChunk = lineChunk.map((_, index) => chunkTokens[index] ?? []);
1787+ highlightedLines.push(...completedChunk);
1788+ input.onChunk(startIndex, completedChunk);
1789+
1790+ if (startIndex + REVIEW_HIGHLIGHT_CHUNK_SIZE < input.lines.length) {
1791+ await waitForNextFrame();
1792+ }
1793+ }
1794+
1795+ return highlightedLines;
1796+}
1797+
1798 function getHighlightCacheKey(file: ReviewRenderableFile, theme: ReviewDiffTheme): string {
1799 return `${SHIKI_THEME_NAME_BY_SCHEME[theme]}:${file.cacheKey}`;
1800 }
1801@@ -667,7 +819,28 @@ export async function highlightReviewFile(
1802 deletionLineCount: file.deletionLines.length,
1803 rowCount: file.rows.length,
1804 });
1805- const language = await resolveLanguage(file);
1806+ const loadedLanguage = resolveLoadedLanguageFromPath(file.path, file.languageHint);
1807+ const language = loadedLanguage ?? (await resolveLanguage(file));
1808+ if (language === "text") {
1809+ const highlighted = applyWordAltDiffHighlightsToFile(file, {
1810+ additionLines: makePlainHighlightedLines(file.additionLines),
1811+ deletionLines: makePlainHighlightedLines(file.deletionLines),
1812+ });
1813+ if (!REVIEW_HIGHLIGHTER_DISABLE_RESULT_CACHE) {
1814+ storeResolvedHighlightedFile(cacheKey, highlighted);
1815+ }
1816+ logReviewHighlighterDiagnostic("file highlight complete", {
1817+ fileId: file.id,
1818+ filePath: file.path,
1819+ theme,
1820+ language,
1821+ highlightedAdditionLineCount: highlighted.additionLines.length,
1822+ highlightedDeletionLineCount: highlighted.deletionLines.length,
1823+ durationMs: Date.now() - startedAt,
1824+ });
1825+ return highlighted;
1826+ }
1827+
1828 const additionLines = await highlightLines(
1829 joinPatchLines(file.additionLines),
1830 language,
1831@@ -707,6 +880,113 @@ export async function highlightReviewFile(
1832 });
1833 }
1834
1835+export async function streamHighlightReviewFile(
1836+ file: ReviewRenderableFile,
1837+ theme: ReviewDiffTheme,
1838+ onProgress: (progress: ReviewHighlightFileProgress) => void,
1839+): Promise<ReviewHighlightedFile> {
1840+ const shikiTheme = SHIKI_THEME_NAME_BY_SCHEME[theme];
1841+ const cacheKey = getHighlightCacheKey(file, theme);
1842+ if (!REVIEW_HIGHLIGHTER_DISABLE_RESULT_CACHE) {
1843+ const resolved = resolvedHighlightCache.get(cacheKey);
1844+ if (resolved) {
1845+ onProgress({
1846+ highlightedFile: resolved,
1847+ complete: true,
1848+ highlightedLineCount: resolved.additionLines.length + resolved.deletionLines.length,
1849+ });
1850+ return resolved;
1851+ }
1852+ }
1853+
1854+ const startedAt = Date.now();
1855+ logReviewHighlighterDiagnostic("file stream highlight start", {
1856+ fileId: file.id,
1857+ filePath: file.path,
1858+ theme,
1859+ additionLineCount: file.additionLines.length,
1860+ deletionLineCount: file.deletionLines.length,
1861+ rowCount: file.rows.length,
1862+ });
1863+
1864+ const loadedLanguage = resolveLoadedLanguageFromPath(file.path, file.languageHint);
1865+ const language = loadedLanguage ?? (await resolveLanguage(file));
1866+ if (language === "text") {
1867+ const highlighted = applyWordAltDiffHighlightsToFile(file, {
1868+ additionLines: makePlainHighlightedLines(file.additionLines),
1869+ deletionLines: makePlainHighlightedLines(file.deletionLines),
1870+ });
1871+ if (!REVIEW_HIGHLIGHTER_DISABLE_RESULT_CACHE) {
1872+ storeResolvedHighlightedFile(cacheKey, highlighted);
1873+ }
1874+ onProgress({
1875+ highlightedFile: highlighted,
1876+ complete: true,
1877+ highlightedLineCount: highlighted.additionLines.length + highlighted.deletionLines.length,
1878+ });
1879+ logReviewHighlighterDiagnostic("file stream highlight complete", {
1880+ fileId: file.id,
1881+ filePath: file.path,
1882+ theme,
1883+ language,
1884+ highlightedAdditionLineCount: highlighted.additionLines.length,
1885+ highlightedDeletionLineCount: highlighted.deletionLines.length,
1886+ highlightedLineCount: highlighted.additionLines.length + highlighted.deletionLines.length,
1887+ durationMs: Date.now() - startedAt,
1888+ });
1889+ return highlighted;
1890+ }
1891+
1892+ const additionLines: Array<ReadonlyArray<ReviewHighlightedToken>> = [];
1893+ const deletionLines: Array<ReadonlyArray<ReviewHighlightedToken>> = [];
1894+ let highlightedLineCount = 0;
1895+
1896+ await highlightPatchLinesInChunks({
1897+ lines: file.additionLines,
1898+ language,
1899+ theme: shikiTheme,
1900+ onChunk: (startIndex, tokens) => {
1901+ tokens.forEach((lineTokens, index) => {
1902+ additionLines[startIndex + index] = lineTokens;
1903+ });
1904+ highlightedLineCount += tokens.length;
1905+ },
1906+ });
1907+ await waitForNextFrame();
1908+ await highlightPatchLinesInChunks({
1909+ lines: file.deletionLines,
1910+ language,
1911+ theme: shikiTheme,
1912+ onChunk: (startIndex, tokens) => {
1913+ tokens.forEach((lineTokens, index) => {
1914+ deletionLines[startIndex + index] = lineTokens;
1915+ });
1916+ highlightedLineCount += tokens.length;
1917+ },
1918+ });
1919+
1920+ const highlighted = applyWordAltDiffHighlightsToFile(file, { additionLines, deletionLines });
1921+ if (!REVIEW_HIGHLIGHTER_DISABLE_RESULT_CACHE) {
1922+ storeResolvedHighlightedFile(cacheKey, highlighted);
1923+ }
1924+ onProgress({
1925+ highlightedFile: highlighted,
1926+ complete: true,
1927+ highlightedLineCount,
1928+ });
1929+ logReviewHighlighterDiagnostic("file stream highlight complete", {
1930+ fileId: file.id,
1931+ filePath: file.path,
1932+ theme,
1933+ language,
1934+ highlightedAdditionLineCount: highlighted.additionLines.length,
1935+ highlightedDeletionLineCount: highlighted.deletionLines.length,
1936+ highlightedLineCount,
1937+ durationMs: Date.now() - startedAt,
1938+ });
1939+ return highlighted;
1940+}
1941+
1942 export async function highlightReviewSelectedLines(input: {
1943 readonly filePath: string;
1944 readonly lines: ReadonlyArray<ReviewRenderableLineRow>;
1945@@ -717,7 +997,9 @@ export async function highlightReviewSelectedLines(input: {
1946 return {};
1947 }
1948
1949- const language = await resolveLanguageFromPath(input.filePath, input.languageHint ?? null);
1950+ const loadedLanguage = resolveLoadedLanguageFromPath(input.filePath, input.languageHint ?? null);
1951+ const language =
1952+ loadedLanguage ?? (await resolveLanguageFromPath(input.filePath, input.languageHint ?? null));
1953 const shikiTheme = SHIKI_THEME_NAME_BY_SCHEME[input.theme];
1954 const additionLikeLines = input.lines
1955 .filter((line) => line.change !== "delete")
apps/mobile/src/features/debug/fixtures/review-small.diff+0−155
@@ -1,155 +0,0 @@
1diff --git a/apps/mobile/src/features/review/reviewDiffRendering.tsx b/apps/mobile/src/features/review/reviewDiffRendering.tsx
2index d61924a62..3f2ae0160 100644
3--- a/apps/mobile/src/features/review/reviewDiffRendering.tsx
4+++ b/apps/mobile/src/features/review/reviewDiffRendering.tsx
5@@ -11,6 +11,9 @@ export const REVIEW_MONO_FONT_FAMILY = Platform.select({
6 default: "monospace",
7 });
8
9+export const REVIEW_DIFF_LINE_HEIGHT = 26;
10+const REVIEW_DELETE_STRIPE_COUNT = REVIEW_DIFF_LINE_HEIGHT / 2;
11+
12 export function renderVisibleWhitespace(value: string): string {
13 const expandedTabs = value.replace(/\t/g, " ");
14 return expandedTabs.replace(/^( +)/, (leading) => leading.replaceAll(" ", "\u00A0"));
15@@ -37,10 +40,13 @@ function diffHighlightColor(change: ReviewRenderableLineRow["change"]): string |
16 export function ReviewChangeBar(props: { readonly change: ReviewRenderableLineRow["change"] }) {
17 if (props.change === "delete") {
18 return (
19- <View className="w-[5px] self-stretch overflow-hidden">
20- <View className="flex-1 justify-between">
21- {Array.from({ length: 6 }, (_, index) => (
22- <View key={index} className="h-[2px] w-[5px] bg-rose-400" />
23+ <View className="w-[5px] overflow-hidden" style={{ height: REVIEW_DIFF_LINE_HEIGHT }}>
24+ <View>
25+ {Array.from({ length: REVIEW_DELETE_STRIPE_COUNT }, (_, index) => (
26+ <View key={index}>
27+ <View className="w-[5px] bg-rose-400" style={{ height: 1 }} />
28+ <View style={{ height: 1 }} />
29+ </View>
30 ))}
31 </View>
32 </View>
33@@ -48,7 +54,7 @@ export function ReviewChangeBar(props: { readonly change: ReviewRenderableLineRo
34 }
35
36 return (
37- <View className="w-[5px] self-stretch overflow-hidden">
38+ <View className="w-[5px] overflow-hidden" style={{ height: REVIEW_DIFF_LINE_HEIGHT }}>
39 <View className={cn("h-full w-[5px] flex-1", changeBarTone(props.change))} />
40 </View>
41 );
42@@ -63,6 +69,7 @@ export function DiffTokenText(props: {
43 if (!props.tokens || props.tokens.length === 0) {
44 return (
45 <NativeText
46+ numberOfLines={1}
47 selectable
48 className={cn("text-[13px] leading-[17px] font-medium text-foreground", props.className)}
49 style={{ fontFamily: REVIEW_MONO_FONT_FAMILY }}
50@@ -74,6 +81,7 @@ export function DiffTokenText(props: {
51
52 return (
53 <NativeText
54+ numberOfLines={1}
55 selectable
56 className={cn("text-[13px] leading-[17px] font-medium text-foreground", props.className)}
57 style={{ fontFamily: REVIEW_MONO_FONT_FAMILY }}
58diff --git a/apps/mobile/src/features/review/reviewModel.test.ts b/apps/mobile/src/features/review/reviewModel.test.ts
59index a24a99ceb..69a6e7261 100644
60--- a/apps/mobile/src/features/review/reviewModel.test.ts
61+++ b/apps/mobile/src/features/review/reviewModel.test.ts
62@@ -238,7 +238,7 @@ describe("buildReviewParsedDiff", () => {
63 });
64 });
65
66- it("flattens expanded files into virtualizable review items", () => {
67+ it("flattens expanded file rows into virtualized review items", () => {
68 const file = makeRenderableFile({
69 path: "apps/mobile/src/a.ts",
70 rows: [
71@@ -270,8 +270,19 @@ describe("buildReviewParsedDiff", () => {
72
73 expect(items).toEqual([
74 expect.objectContaining({ kind: "file-header", fileId: file.id, expanded: true }),
75- expect.objectContaining({ kind: "hunk", fileId: file.id, row: file.rows[0] }),
76- expect.objectContaining({ kind: "line", fileId: file.id, row: file.rows[1] }),
77+ expect.objectContaining({
78+ kind: "hunk",
79+ fileId: file.id,
80+ file,
81+ row: file.rows[0],
82+ }),
83+ expect.objectContaining({
84+ kind: "line",
85+ fileId: file.id,
86+ file,
87+ row: file.rows[1],
88+ lineIndex: 0,
89+ }),
90 ]);
91 });
92
93diff --git a/apps/mobile/src/features/review/reviewModel.ts b/apps/mobile/src/features/review/reviewModel.ts
94index 27e6d7ae4..1cfbf358c 100644
95--- a/apps/mobile/src/features/review/reviewModel.ts
96+++ b/apps/mobile/src/features/review/reviewModel.ts
97@@ -72,6 +72,7 @@ export interface ReviewHunkListItem {
98 readonly kind: "hunk";
99 readonly id: string;
100 readonly fileId: string;
101+ readonly file: ReviewRenderableFile;
102 readonly row: ReviewRenderableHunkRow;
103 }
104
105@@ -79,7 +80,9 @@ export interface ReviewLineListItem {
106 readonly kind: "line";
107 readonly id: string;
108 readonly fileId: string;
109+ readonly file: ReviewRenderableFile;
110 readonly row: ReviewRenderableLineRow;
111+ readonly lineIndex: number;
112 }
113
114 export type ReviewListItem =
115@@ -308,7 +311,7 @@ export function getReviewFilePreviewState(file: ReviewRenderableFile): ReviewFil
116 }
117
118 // The flattened review list item model is inspired by pierre/diffs' iterator-first
119-// virtualization architecture, adapted here for React Native and LegendList.
120+// virtualization architecture, adapted here for React Native virtualization.
121 // Original project: https://github.com/pingdotgg/pierre/tree/main/packages/diffs
122 // Reference files:
123 // - src/utils/iterateOverDiff.ts
124@@ -350,12 +353,14 @@ export function buildReviewListItems(input: {
125 }
126 }
127
128- file.rows.forEach((row) => {
129+ let lineIndex = 0;
130+ file.rows.forEach((row, rowIndex) => {
131 if (row.kind === "hunk") {
132 items.push({
133 kind: "hunk",
134- id: row.id,
135+ id: `${file.id}:row:${rowIndex}:${row.id}`,
136 fileId: file.id,
137+ file,
138 row,
139 });
140 return;
141@@ -363,10 +368,13 @@ export function buildReviewListItems(input: {
142
143 items.push({
144 kind: "line",
145- id: row.id,
146+ id: `${file.id}:row:${rowIndex}:${row.id}`,
147 fileId: file.id,
148+ file,
149 row,
150+ lineIndex,
151 });
152+ lineIndex += 1;
153 });
154 });
155
apps/mobile/src/features/debug/fixtures/reviewDiffFixtures.ts+0−238
@@ -1,238 +0,0 @@
1import { DEBUG_REVIEW_XL_DIFF } from "./reviewDiffXlFixture";
2
3export type DebugReviewDiffFixtureId = "small" | "medium" | "large" | "xl" | "current" | "states";
4
5export interface DebugReviewDiffFixture {
6 readonly id: DebugReviewDiffFixtureId;
7 readonly label: string;
8 readonly filename: string;
9 readonly lineCount: number;
10 readonly diff: string;
11}
12
13const DEBUG_REVIEW_STATES_DIFF = `diff --git a/apps/demo/src/main.ts b/apps/demo/src/main.ts
14index 78f5eaa12..c2874ad31 100644
15--- a/apps/demo/src/main.ts
16+++ b/apps/demo/src/main.ts
17@@ -1,18 +1,24 @@
18 import { createServer } from "./server";
19 import { createLogger } from "./logger";
20
21-const retryLimit = 2;
22-const greeting = "Hi You, {name}! Welcome to our application.";
23+const retryLimit = 4;
24+const greeting = "Hello There, {name}! Welcome to the updated application.";
25 const logger = createLogger("demo");
26
27 export async function boot() {
28 const server = createServer({
29- port: 3000,
30- timeoutMs: 1200,
31+ port: 3030,
32+ timeoutMs: 2500,
33 retryLimit,
34 });
35
36- logger.info("starting server");
37+ logger.info("starting review fixture server");
38+ logger.debug({ retryLimit }, "configured retry policy");
39 await server.start();
40- logger.info(greeting.replace("{name}", "reviewer"));
41+ logger.info(greeting.replace("{name}", "native reviewer"));
42+
43+ if (process.env.DEMO_FIXTURE_VERBOSE === "1") {
44+ logger.debug("verbose review fixture mode enabled");
45+ }
46 }
47
48 void boot();
49diff --git a/apps/demo/src/utils/format.ts b/apps/demo/src/utils/stringFormat.ts
50similarity index 100%
51rename from apps/demo/src/utils/format.ts
52rename to apps/demo/src/utils/stringFormat.ts
53diff --git a/apps/demo/src/oldClient.ts b/apps/demo/src/apiClient.ts
54similarity index 62%
55rename from apps/demo/src/oldClient.ts
56rename to apps/demo/src/apiClient.ts
57index 18518fca1..87e0e2bea 100644
58--- a/apps/demo/src/oldClient.ts
59+++ b/apps/demo/src/apiClient.ts
60@@ -1,15 +1,22 @@
61-export interface ClientOptions {
62- readonly baseUrl: string;
63- readonly timeoutMs: number;
64-}
65-
66-export function request(path: string, options: ClientOptions) {
67- return fetch(options.baseUrl + path, {
68- signal: AbortSignal.timeout(options.timeoutMs),
69- });
70+export interface ApiClientOptions {
71+ readonly baseUrl: string;
72+ readonly token: string;
73+ readonly timeoutMs: number;
74+}
75+
76+export async function request(path: string, options: ApiClientOptions) {
77+ const response = await fetch(options.baseUrl + "/v2" + path, {
78+ headers: {
79+ Authorization: "Bearer " + options.token,
80+ "X-Client": "native-review-debug",
81+ },
82+ signal: AbortSignal.timeout(options.timeoutMs),
83+ });
84+
85+ if (!response.ok) {
86+ throw new Error("Request failed: " + response.status);
87+ }
88+
89+ return response.json();
90 }
91-
92-export function requestJson(path: string, options: ClientOptions) {
93- return request(path, options).then((response) => response.json());
94-}
95diff --git a/apps/demo/src/features/flags.ts b/apps/demo/src/features/flags.ts
96new file mode 100644
97index 000000000..755df9762
98--- /dev/null
99+++ b/apps/demo/src/features/flags.ts
100@@ -0,0 +1,29 @@
101+export type FeatureState = "enabled" | "disabled" | "preview";
102+
103+export interface FeatureFlag {
104+ readonly key: string;
105+ readonly label: string;
106+ readonly state: FeatureState;
107+}
108+
109+export const reviewFixtureFlags: ReadonlyArray<FeatureFlag> = [
110+ {
111+ key: "native-file-headers",
112+ label: "Native file headers",
113+ state: "preview",
114+ },
115+ {
116+ key: "word-diff-highlights",
117+ label: "Word diff highlights",
118+ state: "enabled",
119+ },
120+ {
121+ key: "deleted-file-markers",
122+ label: "Deleted file markers",
123+ state: "enabled",
124+ },
125+];
126+
127+export function isEnabled(flag: FeatureFlag): boolean {
128+ return flag.state !== "disabled";
129+}
130diff --git a/apps/demo/src/legacyReview.ts b/apps/demo/src/legacyReview.ts
131deleted file mode 100644
132index 9cf2f63dc..000000000
133--- a/apps/demo/src/legacyReview.ts
134+++ /dev/null
135@@ -1,22 +0,0 @@
136-export const legacyReviewMode = true;
137-
138-export function createLegacyRows(lines: ReadonlyArray<string>) {
139- return lines.map((line, index) => ({
140- id: "legacy-" + index,
141- lineNumber: index + 1,
142- text: line,
143- }));
144-}
145-
146-export function renderLegacyHeader(path: string) {
147- return {
148- title: path,
149- subtitle: "legacy renderer",
150- icon: "blue-dot",
151- };
152-}
153-
154-export function shouldUseLegacyReview() {
155- return legacyReviewMode;
156-}
157diff --git a/apps/demo/src/wordChanges.zig b/apps/demo/src/wordChanges.zig
158index 6bfcc7e37..af359829c 100644
159--- a/apps/demo/src/wordChanges.zig
160+++ b/apps/demo/src/wordChanges.zig
161@@ -1,18 +1,23 @@
162 const std = @import("std");
163-const Allocator = std.heap.page_allocator;
164+const GeneralPurposeAllocator = std.heap.GeneralPurposeAllocator;
165 const ArrayList = std.ArrayList;
166
167 pub fn main() !void {
168+ var gpa = GeneralPurposeAllocator(.{}){};
169+ defer _ = gpa.deinit();
170+ const allocator = gpa.allocator();
171+
172 const stdout_writer_instance = std.io.getStdOut().writer();
173- try stdout_writer_instance.print("Hi You, {s}! Welcome to our application.", .{"Reviewer"});
174+ try stdout_writer_instance.print("Hello There, {s}! Welcome to the updated application.", .{"Reviewer"});
175
176- var list = ArrayList(i32).init(Allocator);
177+ var list = ArrayList(i32).init(allocator);
178 defer list.deinit();
179+ try list.append(42);
180
181- const configuration_options = .{ .enable_logging = true, .max_buffer_size = 1024 };
182+ const configuration_options = .{ .enable_logging = true, .max_buffer_size = 2048 };
183 _ = configuration_options;
184 }
185diff --git a/apps/demo/assets/review-logo.png b/apps/demo/assets/review-logo.png
186new file mode 100644
187index 000000000..4628f44da
188--- /dev/null
189+++ b/apps/demo/assets/review-logo.png
190Binary files /dev/null and b/apps/demo/assets/review-logo.png differ
191diff --git a/apps/demo/scripts/review-fixture.sh b/apps/demo/scripts/review-fixture.sh
192old mode 100644
193new mode 100755`;
194
195export const debugReviewDiffFixtures: ReadonlyArray<DebugReviewDiffFixture> = [
196 {
197 id: "states",
198 label: "States",
199 filename: "review-states.diff",
200 lineCount: DEBUG_REVIEW_STATES_DIFF.split("\n").length,
201 diff: DEBUG_REVIEW_STATES_DIFF,
202 },
203 {
204 id: "xl",
205 label: "XL",
206 filename: "08e6d4cfbfe55af83fe5fb6b9e75364f42f1f22f.patch",
207 lineCount: DEBUG_REVIEW_XL_DIFF.split("\n").length,
208 diff: DEBUG_REVIEW_XL_DIFF,
209 },
210 {
211 id: "small",
212 label: "Small",
213 filename: "review-small.diff",
214 lineCount: 155,
215 diff: 'diff --git a/apps/mobile/src/features/review/reviewDiffRendering.tsx b/apps/mobile/src/features/review/reviewDiffRendering.tsx\nindex d61924a62..3f2ae0160 100644\n--- a/apps/mobile/src/features/review/reviewDiffRendering.tsx\n+++ b/apps/mobile/src/features/review/reviewDiffRendering.tsx\n@@ -11,6 +11,9 @@ export const REVIEW_MONO_FONT_FAMILY = Platform.select({\n default: "monospace",\n });\n \n+export const REVIEW_DIFF_LINE_HEIGHT = 26;\n+const REVIEW_DELETE_STRIPE_COUNT = REVIEW_DIFF_LINE_HEIGHT / 2;\n+\n export function renderVisibleWhitespace(value: string): string {\n const expandedTabs = value.replace(/\\t/g, " ");\n return expandedTabs.replace(/^( +)/, (leading) => leading.replaceAll(" ", "\\u00A0"));\n@@ -37,10 +40,13 @@ function diffHighlightColor(change: ReviewRenderableLineRow["change"]): string |\n export function ReviewChangeBar(props: { readonly change: ReviewRenderableLineRow["change"] }) {\n if (props.change === "delete") {\n return (\n- <View className="w-[5px] self-stretch overflow-hidden">\n- <View className="flex-1 justify-between">\n- {Array.from({ length: 6 }, (_, index) => (\n- <View key={index} className="h-[2px] w-[5px] bg-rose-400" />\n+ <View className="w-[5px] overflow-hidden" style={{ height: REVIEW_DIFF_LINE_HEIGHT }}>\n+ <View>\n+ {Array.from({ length: REVIEW_DELETE_STRIPE_COUNT }, (_, index) => (\n+ <View key={index}>\n+ <View className="w-[5px] bg-rose-400" style={{ height: 1 }} />\n+ <View style={{ height: 1 }} />\n+ </View>\n ))}\n </View>\n </View>\n@@ -48,7 +54,7 @@ export function ReviewChangeBar(props: { readonly change: ReviewRenderableLineRo\n }\n \n return (\n- <View className="w-[5px] self-stretch overflow-hidden">\n+ <View className="w-[5px] overflow-hidden" style={{ height: REVIEW_DIFF_LINE_HEIGHT }}>\n <View className={cn("h-full w-[5px] flex-1", changeBarTone(props.change))} />\n </View>\n );\n@@ -63,6 +69,7 @@ export function DiffTokenText(props: {\n if (!props.tokens || props.tokens.length === 0) {\n return (\n <NativeText\n+ numberOfLines={1}\n selectable\n className={cn("text-[13px] leading-[17px] font-medium text-foreground", props.className)}\n style={{ fontFamily: REVIEW_MONO_FONT_FAMILY }}\n@@ -74,6 +81,7 @@ export function DiffTokenText(props: {\n \n return (\n <NativeText\n+ numberOfLines={1}\n selectable\n className={cn("text-[13px] leading-[17px] font-medium text-foreground", props.className)}\n style={{ fontFamily: REVIEW_MONO_FONT_FAMILY }}\ndiff --git a/apps/mobile/src/features/review/reviewModel.test.ts b/apps/mobile/src/features/review/reviewModel.test.ts\nindex a24a99ceb..69a6e7261 100644\n--- a/apps/mobile/src/features/review/reviewModel.test.ts\n+++ b/apps/mobile/src/features/review/reviewModel.test.ts\n@@ -238,7 +238,7 @@ describe("buildReviewParsedDiff", () => {\n });\n });\n \n- it("flattens expanded files into virtualizable review items", () => {\n+ it("flattens expanded file rows into virtualized review items", () => {\n const file = makeRenderableFile({\n path: "apps/mobile/src/a.ts",\n rows: [\n@@ -270,8 +270,19 @@ describe("buildReviewParsedDiff", () => {\n \n expect(items).toEqual([\n expect.objectContaining({ kind: "file-header", fileId: file.id, expanded: true }),\n- expect.objectContaining({ kind: "hunk", fileId: file.id, row: file.rows[0] }),\n- expect.objectContaining({ kind: "line", fileId: file.id, row: file.rows[1] }),\n+ expect.objectContaining({\n+ kind: "hunk",\n+ fileId: file.id,\n+ file,\n+ row: file.rows[0],\n+ }),\n+ expect.objectContaining({\n+ kind: "line",\n+ fileId: file.id,\n+ file,\n+ row: file.rows[1],\n+ lineIndex: 0,\n+ }),\n ]);\n });\n \ndiff --git a/apps/mobile/src/features/review/reviewModel.ts b/apps/mobile/src/features/review/reviewModel.ts\nindex 27e6d7ae4..1cfbf358c 100644\n--- a/apps/mobile/src/features/review/reviewModel.ts\n+++ b/apps/mobile/src/features/review/reviewModel.ts\n@@ -72,6 +72,7 @@ export interface ReviewHunkListItem {\n readonly kind: "hunk";\n readonly id: string;\n readonly fileId: string;\n+ readonly file: ReviewRenderableFile;\n readonly row: ReviewRenderableHunkRow;\n }\n \n@@ -79,7 +80,9 @@ export interface ReviewLineListItem {\n readonly kind: "line";\n readonly id: string;\n readonly fileId: string;\n+ readonly file: ReviewRenderableFile;\n readonly row: ReviewRenderableLineRow;\n+ readonly lineIndex: number;\n }\n \n export type ReviewListItem =\n@@ -308,7 +311,7 @@ export function getReviewFilePreviewState(file: ReviewRenderableFile): ReviewFil\n }\n \n // The flattened review list item model is inspired by pierre/diffs\' iterator-first\n-// virtualization architecture, adapted here for React Native and LegendList.\n+// virtualization architecture, adapted here for React Native virtualization.\n // Original project: https://github.com/pingdotgg/pierre/tree/main/packages/diffs\n // Reference files:\n // - src/utils/iterateOverDiff.ts\n@@ -350,12 +353,14 @@ export function buildReviewListItems(input: {\n }\n }\n \n- file.rows.forEach((row) => {\n+ let lineIndex = 0;\n+ file.rows.forEach((row, rowIndex) => {\n if (row.kind === "hunk") {\n items.push({\n kind: "hunk",\n- id: row.id,\n+ id: `${file.id}:row:${rowIndex}:${row.id}`,\n fileId: file.id,\n+ file,\n row,\n });\n return;\n@@ -363,10 +368,13 @@ export function buildReviewListItems(input: {\n \n items.push({\n kind: "line",\n- id: row.id,\n+ id: `${file.id}:row:${rowIndex}:${row.id}`,\n fileId: file.id,\n+ file,\n row,\n+ lineIndex,\n });\n+ lineIndex += 1;\n });\n });\n \n',
216 },
217 {
218 id: "medium",
219 label: "Medium",
220 filename: "review-medium.diff",
221 lineCount: 1955,
222 diff: 'diff --git a/apps/mobile/src/app/threads/[environmentId]/[threadId]/review.tsx b/apps/mobile/src/app/threads/[environmentId]/[threadId]/review.tsx\nindex 84c48c6ed..ee993ee7c 100644\n--- a/apps/mobile/src/app/threads/[environmentId]/[threadId]/review.tsx\n+++ b/apps/mobile/src/app/threads/[environmentId]/[threadId]/review.tsx\n@@ -1,5 +1,10 @@\n+import { ReviewHighlighterProvider } from "../../../../features/review/ReviewHighlighterProvider";\n import { ReviewSheet } from "../../../../features/review/ReviewSheet";\n \n export default function ReviewRoute() {\n- return <ReviewSheet />;\n+ return (\n+ <ReviewHighlighterProvider>\n+ <ReviewSheet />\n+ </ReviewHighlighterProvider>\n+ );\n }\ndiff --git a/apps/mobile/src/features/review/ReviewSheet.tsx b/apps/mobile/src/features/review/ReviewSheet.tsx\nindex 82c28e81e..e148a8da2 100644\n--- a/apps/mobile/src/features/review/ReviewSheet.tsx\n+++ b/apps/mobile/src/features/review/ReviewSheet.tsx\n@@ -1,17 +1,31 @@\n import { EnvironmentId, ThreadId, type OrchestrationCheckpointSummary } from "@t3tools/contracts";\n+import { Gesture, GestureDetector } from "react-native-gesture-handler";\n+import Animated, {\n+ makeMutable,\n+ type SharedValue,\n+ useAnimatedStyle,\n+ useSharedValue,\n+} from "react-native-reanimated";\n import { useLocalSearchParams, useRouter } from "expo-router";\n import Stack from "expo-router/stack";\n import { SymbolView } from "expo-symbols";\n-import { memo, type ReactElement, useCallback, useEffect, useMemo, useRef, useState } from "react";\n+import {\n+ memo,\n+ type ReactElement,\n+ useCallback,\n+ useDeferredValue,\n+ useEffect,\n+ useMemo,\n+ useRef,\n+ useState,\n+} from "react";\n import {\n ActivityIndicator,\n FlatList,\n- InteractionManager,\n type ListRenderItemInfo,\n Pressable,\n ScrollView,\n Text as NativeText,\n- type ViewToken,\n useColorScheme,\n useWindowDimensions,\n View,\n@@ -32,6 +46,7 @@ import {\n setReviewTurnDiff,\n updateReviewExpandedFileIds,\n updateReviewRevealedLargeFileIds,\n+ updateReviewViewedFileIds,\n useReviewCacheForThread,\n } from "./reviewState";\n import {\n@@ -45,11 +60,12 @@ import {\n type ReviewParsedDiff,\n type ReviewRenderableFile,\n type ReviewRenderableLineRow,\n+ type ReviewRenderableRow,\n } from "./reviewModel";\n import {\n clearReviewHighlightFileCache,\n getCachedHighlightedReviewFile,\n- highlightReviewFile,\n+ streamHighlightReviewFile,\n type ReviewDiffTheme,\n type ReviewHighlightedFile,\n type ReviewHighlightedToken,\n@@ -67,9 +83,12 @@ import {\n import {\n changeTone,\n DiffTokenText,\n+ REVIEW_DIFF_LINE_HEIGHT,\n REVIEW_MONO_FONT_FAMILY,\n ReviewChangeBar,\n } from "./reviewDiffRendering";\n+import { markReviewEvent, measureReviewWork } from "./reviewPerf";\n+import { useReviewHighlighterStatus } from "./ReviewHighlighterProvider";\n \n interface PendingCommentSelection {\n readonly sectionTitle: string;\n@@ -87,14 +106,21 @@ interface ReviewLineActionInput {\n \n const IOS_NAV_BAR_HEIGHT = 44;\n const REVIEW_HEADER_SPACING = 0;\n-const REVIEW_LINE_GUTTER_WIDTH = 62;\n+const REVIEW_CHANGE_BAR_WIDTH = 5;\n+const REVIEW_MIN_LINE_NUMBER_WIDTH = 27;\n+const REVIEW_LINE_NUMBER_DIGIT_WIDTH_ESTIMATE = 8;\n+const REVIEW_LINE_NUMBER_HORIZONTAL_PADDING = 6;\n const REVIEW_CHARACTER_WIDTH_ESTIMATE = 8.4;\n const REVIEW_MAX_CONTENT_WIDTH = 4_800;\n-const REVIEW_INITIAL_HIGHLIGHT_FILE_COUNT = 2;\n-const REVIEW_HIGHLIGHT_BACKTRACK_COUNT = 0;\n-const REVIEW_HIGHLIGHT_LOOKAHEAD_COUNT = 1;\n+const REVIEW_HUNK_ROW_HEIGHT = 35;\n+const REVIEW_FILE_HEADER_HEIGHT = 43;\n+const REVIEW_SUPPRESSED_ROW_HEIGHT = 92;\n const loggedMissingReviewTokenKeys = new Set<string>();\n \n+function waitForReviewDelay(durationMs: number): Promise<void> {\n+ return new Promise((resolve) => setTimeout(resolve, durationMs));\n+}\n+\n function isReviewDiffDebugLoggingEnabled(): boolean {\n return typeof __DEV__ !== "undefined" ? __DEV__ : false;\n }\n@@ -113,33 +139,27 @@ function logReviewDiffDiagnostic(message: string, details?: Record<string, unkno\n }\n \n function getFileHeaderChrome(changeType: ReviewRenderableFile["changeType"]): {\n- readonly rail: string;\n readonly dot: string;\n } {\n switch (changeType) {\n case "new":\n return {\n- rail: "bg-emerald-400",\n dot: "bg-emerald-400",\n };\n case "deleted":\n return {\n- rail: "bg-rose-400",\n dot: "bg-rose-400",\n };\n case "rename-pure":\n return {\n- rail: "bg-amber-400",\n dot: "bg-amber-400",\n };\n case "rename-changed":\n return {\n- rail: "bg-sky-400",\n dot: "bg-sky-400",\n };\n default:\n return {\n- rail: "bg-sky-400",\n dot: "bg-sky-400",\n };\n }\n@@ -159,51 +179,72 @@ function formatHeaderDiffSummary(parsedDiff: ReviewParsedDiff): {\n };\n }\n \n-function computeReviewListContentWidth(\n- items: ReadonlyArray<ReviewListItem>,\n+function computeReviewFileContentWidth(\n+ rows: ReadonlyArray<ReviewRenderableRow>,\n viewportWidth: number,\n+ gutterWidth: number,\n ): number {\n let maxTextLength = 0;\n \n- items.forEach((item) => {\n- switch (item.kind) {\n- case "file-header":\n- maxTextLength = Math.max(\n- maxTextLength,\n- item.file.path.length,\n- item.file.previousPath?.length ?? 0,\n- );\n- break;\n- case "file-suppressed":\n- maxTextLength = Math.max(maxTextLength, item.message.length, item.actionLabel?.length ?? 0);\n- break;\n- case "hunk":\n- maxTextLength = Math.max(\n- maxTextLength,\n- item.row.header.length + (item.row.context ? item.row.context.length + 1 : 0),\n- );\n- break;\n- case "line":\n- maxTextLength = Math.max(maxTextLength, item.row.content.length);\n- break;\n+ rows.forEach((row) => {\n+ if (row.kind === "hunk") {\n+ maxTextLength = Math.max(\n+ maxTextLength,\n+ row.header.length + (row.context ? row.context.length + 1 : 0),\n+ );\n+ return;\n }\n+\n+ maxTextLength = Math.max(maxTextLength, row.content.length);\n });\n \n return Math.max(\n- viewportWidth,\n+ Math.max(0, viewportWidth - gutterWidth),\n Math.min(\n REVIEW_MAX_CONTENT_WIDTH,\n- Math.ceil(REVIEW_LINE_GUTTER_WIDTH + 48 + maxTextLength * REVIEW_CHARACTER_WIDTH_ESTIMATE),\n+ Math.ceil(48 + maxTextLength * REVIEW_CHARACTER_WIDTH_ESTIMATE),\n ),\n );\n }\n \n+function computeReviewFileGutterWidth(rows: ReadonlyArray<ReviewRenderableRow>): number {\n+ let maxLineNumber = 0;\n+\n+ rows.forEach((row) => {\n+ if (row.kind !== "line") {\n+ return;\n+ }\n+\n+ maxLineNumber = Math.max(maxLineNumber, row.oldLineNumber ?? 0, row.newLineNumber ?? 0);\n+ });\n+\n+ const digitCount = Math.max(1, String(maxLineNumber).length);\n+ const lineNumberWidth = Math.max(\n+ REVIEW_MIN_LINE_NUMBER_WIDTH,\n+ digitCount * REVIEW_LINE_NUMBER_DIGIT_WIDTH_ESTIMATE + REVIEW_LINE_NUMBER_HORIZONTAL_PADDING,\n+ );\n+\n+ return REVIEW_CHANGE_BAR_WIDTH + lineNumberWidth;\n+}\n+\n function getDefaultExpandedFileIds(\n files: ReadonlyArray<ReviewRenderableFile>,\n ): ReadonlyArray<string> {\n return files.map((file) => file.id);\n }\n \n+function getValidReviewExpandedFileIds(\n+ files: ReadonlyArray<ReviewRenderableFile>,\n+ cachedExpandedFileIds: ReadonlyArray<string> | undefined,\n+): ReadonlyArray<string> {\n+ if (cachedExpandedFileIds === undefined) {\n+ return getDefaultExpandedFileIds(files);\n+ }\n+\n+ const fileIdSet = new Set(files.map((file) => file.id));\n+ return cachedExpandedFileIds.filter((id) => fileIdSet.has(id));\n+}\n+\n function getHighlightedTokensForLine(\n line: ReviewRenderableLineRow,\n highlightedFile: ReviewHighlightedFile | null,\n@@ -252,16 +293,13 @@ const ReviewLineRow = memo(function ReviewLineRow(props: {\n delayLongPress={220}\n onLongPress={props.onStartRangeSelection}\n onPress={props.onComment}\n- style={{ minWidth: props.viewportWidth }}\n+ style={{\n+ height: REVIEW_DIFF_LINE_HEIGHT,\n+ width: props.viewportWidth,\n+ overflow: "hidden",\n+ }}\n >\n- <ReviewChangeBar change={props.line.change} />\n- <Text\n- className="w-9 py-1 pr-1 text-right text-[11px] font-t3-medium text-foreground-muted"\n- style={{ fontFamily: REVIEW_MONO_FONT_FAMILY }}\n- >\n- {lineNumber ?? ""}\n- </Text>\n- <View className="min-w-0 flex-1 shrink-0 px-1 py-1">\n+ <View className="min-w-0 flex-1 shrink-0 px-1 py-1" style={{ width: props.viewportWidth }}>\n <DiffTokenText\n tokens={props.tokens}\n fallback={props.line.content}\n@@ -272,62 +310,135 @@ const ReviewLineRow = memo(function ReviewLineRow(props: {\n );\n });\n \n+const ReviewLineGutter = memo(function ReviewLineGutter(props: {\n+ readonly change: ReviewRenderableLineRow["change"];\n+ readonly gutterWidth: number;\n+ readonly lineNumber: number | null;\n+}) {\n+ const lineNumberWidth = Math.max(0, props.gutterWidth - REVIEW_CHANGE_BAR_WIDTH);\n+\n+ return (\n+ <View className={cn("flex-row", changeTone(props.change))} style={{ width: props.gutterWidth }}>\n+ <ReviewChangeBar change={props.change} />\n+ <Text\n+ className="py-1 pr-1 text-right text-[11px] font-t3-medium text-foreground-muted"\n+ style={[{ fontFamily: REVIEW_MONO_FONT_FAMILY }, { width: lineNumberWidth }]}\n+ >\n+ {props.lineNumber ?? ""}\n+ </Text>\n+ </View>\n+ );\n+});\n+\n+const ReviewHunkGutter = memo(function ReviewHunkGutter(props: { readonly gutterWidth: number }) {\n+ return (\n+ <View\n+ className="border-b border-border/60 bg-sky-500/10"\n+ style={{ width: props.gutterWidth }}\n+ />\n+ );\n+});\n+\n const ReviewFileCard = memo(function ReviewFileCard(props: {\n readonly file: ReviewRenderableFile;\n readonly fileId: string;\n readonly expanded: boolean;\n+ readonly viewed: boolean;\n readonly viewportWidth: number;\n readonly onToggleFile: (fileId: string) => void;\n+ readonly onToggleViewed: (fileId: string) => void;\n }) {\n- const chrome = getFileHeaderChrome(props.file.changeType);\n+ const { expanded, file, fileId, onToggleFile, onToggleViewed, viewed, viewportWidth } = props;\n+ const chrome = getFileHeaderChrome(file.changeType);\n+ const iconColor = String(useThemeColor("--color-icon-muted"));\n+ const handleToggleFile = useCallback(() => {\n+ onToggleFile(fileId);\n+ }, [fileId, onToggleFile]);\n+ const handleToggleViewed = useCallback(() => {\n+ onToggleViewed(fileId);\n+ }, [fileId, onToggleViewed]);\n \n return (\n <View\n- className="border-b border-border/70 bg-card"\n- style={{\n- zIndex: 1,\n- width: props.viewportWidth,\n- shadowColor: "#000000",\n- shadowOpacity: 0.08,\n- shadowRadius: 10,\n- shadowOffset: { width: 0, height: 6 },\n- elevation: 4,\n- }}\n+ className="border-b border-border bg-card"\n+ style={{ height: REVIEW_FILE_HEADER_HEIGHT, overflow: "hidden", width: viewportWidth }}\n >\n- <Pressable className="flex-row items-center" onPress={() => props.onToggleFile(props.fileId)}>\n- <View className={cn("w-1 self-stretch", chrome.rail)} />\n- <View className="flex-1 flex-row items-center px-3 py-1.5">\n- <View className="size-7 items-center justify-center rounded-full bg-subtle">\n- <SymbolView\n- name={props.expanded ? "chevron.down" : "chevron.right"}\n- size={12}\n- tintColor="#8a8a8a"\n- type="monochrome"\n- />\n- </View>\n- <View className="ml-2 min-w-0 flex-1 flex-row items-center gap-2">\n- <View className={cn("size-2 rounded-full", chrome.dot)} />\n- <View className="min-w-0 flex-1">\n- <Text className="font-mono text-[13px] leading-[18px] text-foreground">\n- {props.file.path}\n+ <View className="min-h-[42px] flex-row items-center gap-1.5 px-2">\n+ <Pressable\n+ className="size-9 items-center justify-center"\n+ accessibilityRole="button"\n+ accessibilityLabel={expanded ? "Collapse file" : "Expand file"}\n+ hitSlop={{ bottom: 8, left: 8, right: 8, top: 8 }}\n+ onTouchEnd={handleToggleFile}\n+ >\n+ <SymbolView\n+ name={expanded ? "chevron.down" : "chevron.right"}\n+ size={13}\n+ tintColor={iconColor}\n+ type="monochrome"\n+ />\n+ </Pressable>\n+ <Pressable\n+ className="min-w-0 flex-1 flex-row items-center gap-2 py-2"\n+ accessibilityRole="button"\n+ accessibilityLabel={expanded ? "Collapse file" : "Expand file"}\n+ onTouchEnd={handleToggleFile}\n+ >\n+ <View className={cn("size-2.5 rounded-full", chrome.dot)} />\n+ <View className="min-w-0 flex-1">\n+ <Text\n+ className="font-mono text-[13px] leading-[18px] text-foreground"\n+ numberOfLines={1}\n+ >\n+ {file.path}\n+ </Text>\n+ {file.previousPath && file.previousPath !== file.path ? (\n+ <Text\n+ className="font-mono text-[10px] leading-[14px] text-foreground-muted"\n+ numberOfLines={1}\n+ >\n+ {file.previousPath}\n </Text>\n- {props.file.previousPath && props.file.previousPath !== props.file.path ? (\n- <Text className="font-mono text-[10px] leading-[14px] text-foreground-muted">\n- {props.file.previousPath}\n- </Text>\n+ ) : null}\n+ </View>\n+ </Pressable>\n+ <View className="flex-row items-center justify-end gap-1.5">\n+ <Text className="font-mono text-[12px] font-t3-bold text-rose-400">\n+ -{file.deletions}\n+ </Text>\n+ <Text className="font-mono text-[12px] font-t3-bold text-emerald-400">\n+ +{file.additions}\n+ </Text>\n+ <Pressable\n+ className="ml-0.5 min-h-[40px] min-w-[82px] flex-row items-center justify-center gap-1.5 px-1.5"\n+ accessibilityRole="checkbox"\n+ accessibilityState={{ checked: viewed }}\n+ accessibilityLabel={viewed ? "Mark file as unviewed" : "Mark file as viewed"}\n+ hitSlop={{ bottom: 8, left: 4, right: 8, top: 8 }}\n+ onTouchEnd={handleToggleViewed}\n+ >\n+ <View\n+ className={cn(\n+ "size-[18px] items-center justify-center rounded border",\n+ viewed ? "border-sky-500 bg-sky-500" : "border-icon-muted",\n+ )}\n+ >\n+ {viewed ? (\n+ <SymbolView name="checkmark" size={11} tintColor="#ffffff" type="monochrome" />\n ) : null}\n </View>\n- </View>\n- <View className="ml-3 flex-row items-center justify-end gap-2">\n- <Text className="font-mono text-[12px] font-t3-bold text-emerald-600 dark:text-emerald-300">\n- +{props.file.additions}\n- </Text>\n- <Text className="font-mono text-[12px] font-t3-bold text-rose-600 dark:text-rose-300">\n- -{props.file.deletions}\n+ <Text\n+ className={cn(\n+ "text-[12px] font-t3-medium",\n+ viewed ? "text-foreground" : "text-foreground-muted",\n+ )}\n+ numberOfLines={1}\n+ >\n+ Viewed\n </Text>\n- </View>\n+ </Pressable>\n </View>\n- </Pressable>\n+ </View>\n </View>\n );\n });\n@@ -342,7 +453,11 @@ const ReviewFileSuppressedBody = memo(function ReviewFileSuppressedBody(props: {\n return (\n <View\n className="gap-2 border-b border-border bg-card px-4 py-3"\n- style={{ minWidth: props.viewportWidth }}\n+ style={{\n+ height: REVIEW_SUPPRESSED_ROW_HEIGHT,\n+ overflow: "hidden",\n+ width: props.viewportWidth,\n+ }}\n >\n <Text className="text-[12px] leading-[18px] text-foreground-muted">{props.message}</Text>\n {props.actionLabel && props.onLoadDiffFile ? (\n@@ -364,10 +479,13 @@ const ReviewHunkRow = memo(function ReviewHunkRow(props: {\n }) {\n return (\n <View\n- className="border-b border-border/60 bg-sky-500/10 px-2 py-2"\n- style={{ minWidth: props.viewportWidth }}\n+ className="border-b border-border/60 bg-sky-500/10 py-2"\n+ style={{ height: REVIEW_HUNK_ROW_HEIGHT, width: props.viewportWidth, overflow: "hidden" }}\n >\n- <Text className="font-mono text-[12px] leading-[18px] text-sky-700 dark:text-sky-300">\n+ <Text\n+ className="px-2 font-mono text-[12px] leading-[18px] text-sky-700 dark:text-sky-300"\n+ numberOfLines={1}\n+ >\n {props.header}\n {props.context ? ` ${props.context}` : ""}\n </Text>\n@@ -375,6 +493,61 @@ const ReviewHunkRow = memo(function ReviewHunkRow(props: {\n );\n });\n \n+const ReviewCodePanRow = memo(function ReviewCodePanRow(props: {\n+ readonly contentWidth: number;\n+ readonly horizontalOffset: SharedValue<number>;\n+ readonly gutterWidth?: number;\n+ readonly viewportWidth: number;\n+ readonly leftGutter?: ReactElement;\n+ readonly children: ReactElement;\n+}) {\n+ const {\n+ children,\n+ contentWidth,\n+ gutterWidth = 0,\n+ horizontalOffset,\n+ leftGutter,\n+ viewportWidth,\n+ } = props;\n+ const dragStartOffset = useSharedValue(0);\n+ const visibleContentWidth = leftGutter ? viewportWidth - gutterWidth : viewportWidth;\n+ const maxOffset = Math.max(0, contentWidth - visibleContentWidth);\n+\n+ const panGesture = useMemo(\n+ () =>\n+ Gesture.Pan()\n+ .activeOffsetX([-8, 8])\n+ .failOffsetY([-10, 10])\n+ .onBegin(() => {\n+ dragStartOffset.value = horizontalOffset.value;\n+ })\n+ .onUpdate((event) => {\n+ "worklet";\n+ const nextOffset = dragStartOffset.value - event.translationX;\n+ horizontalOffset.value = Math.min(maxOffset, Math.max(0, nextOffset));\n+ }),\n+ [dragStartOffset, horizontalOffset, maxOffset],\n+ );\n+\n+ const contentStyle = useAnimatedStyle(\n+ () => ({\n+ transform: [{ translateX: -horizontalOffset.value }],\n+ }),\n+ [horizontalOffset],\n+ );\n+\n+ return (\n+ <GestureDetector gesture={panGesture}>\n+ <View style={{ flexDirection: "row", overflow: "hidden", width: viewportWidth }}>\n+ {leftGutter ?? null}\n+ <View style={{ flex: 1, overflow: "hidden" }}>\n+ <Animated.View style={[{ width: contentWidth }, contentStyle]}>{children}</Animated.View>\n+ </View>\n+ </View>\n+ </GestureDetector>\n+ );\n+});\n+\n const ReviewNotice = memo(function ReviewNotice(props: { readonly notice: string }) {\n return (\n <View className="border-b border-amber-200 bg-amber-50 px-4 py-3 dark:border-amber-900/60 dark:bg-amber-950/40">\n@@ -454,15 +627,19 @@ export function ReviewSheet() {\n const [highlightedFilesById, setHighlightedFilesById] = useState<\n Record<string, ReviewHighlightedFile | null>\n >({});\n- const [visibleFileIds, setVisibleFileIds] = useState<ReadonlyArray<string>>([]);\n+ const deferredHighlightedFilesById = useDeferredValue(highlightedFilesById);\n+ const [localExpandedFileIdsBySection, setLocalExpandedFileIdsBySection] = useState<\n+ Record<string, ReadonlyArray<string>>\n+ >({});\n+ const [localViewedFileIdsBySection, setLocalViewedFileIdsBySection] = useState<\n+ Record<string, ReadonlyArray<string>>\n+ >({});\n const activeCommentTarget = useReviewCommentTarget();\n const selectedTheme = (colorScheme === "dark" ? "dark" : "light") satisfies ReviewDiffTheme;\n- const highlightQueueRef = useRef<string[]>([]);\n- const highlightRequestedFileIdsRef = useRef<Set<string>>(new Set());\n- const highlightQueueGenerationRef = useRef(0);\n- const highlightQueueActiveRef = useRef(false);\n- const highlightableFilesByIdRef = useRef<ReadonlyMap<string, ReviewRenderableFile>>(new Map());\n- const selectedThemeRef = useRef<ReviewDiffTheme>(selectedTheme);\n+ const reviewHighlighter = useReviewHighlighterStatus();\n+ const highlightRunIdRef = useRef(0);\n+ const highlightableFilesRef = useRef<ReadonlyArray<ReviewRenderableFile>>([]);\n+ const horizontalOffsetByFileIdRef = useRef<Map<string, SharedValue<number>>>(new Map());\n const { selectedThreadCwd } = useSelectedThreadWorktree();\n \n const cwd = selectedThreadCwd;\n@@ -498,11 +675,13 @@ export function ReviewSheet() {\n const topContentInset = insets.top + IOS_NAV_BAR_HEIGHT;\n const parsedDiff = useMemo(\n () =>\n- getCachedReviewParsedDiff({\n- threadKey: reviewCache.threadKey,\n- sectionId: selectedSection?.id ?? null,\n- diff: selectedSection?.diff,\n- }),\n+ measureReviewWork("parse-diff", () =>\n+ getCachedReviewParsedDiff({\n+ threadKey: reviewCache.threadKey,\n+ sectionId: selectedSection?.id ?? null,\n+ diff: selectedSection?.diff,\n+ }),\n+ ),\n [reviewCache.threadKey, selectedSection?.diff, selectedSection?.id],\n );\n const headerDiffSummary = useMemo(() => formatHeaderDiffSummary(parsedDiff), [parsedDiff]);\n@@ -510,14 +689,53 @@ export function ReviewSheet() {\n () => countReviewCommentContexts(draftMessage),\n [draftMessage],\n );\n+ const viewportWidth = Math.max(width, 280);\n+\n+ useEffect(() => {\n+ if (!selectedSection?.id || parsedDiff.kind !== "files") {\n+ return;\n+ }\n+\n+ setLocalExpandedFileIdsBySection((current) => {\n+ if (current[selectedSection.id] !== undefined) {\n+ return current;\n+ }\n+\n+ return {\n+ ...current,\n+ [selectedSection.id]: getValidReviewExpandedFileIds(\n+ parsedDiff.files,\n+ reviewCache.expandedFileIdsBySection[selectedSection.id],\n+ ),\n+ };\n+ });\n+\n+ setLocalViewedFileIdsBySection((current) => {\n+ if (current[selectedSection.id] !== undefined) {\n+ return current;\n+ }\n+\n+ return {\n+ ...current,\n+ [selectedSection.id]: reviewCache.viewedFileIdsBySection[selectedSection.id] ?? [],\n+ };\n+ });\n+ }, [\n+ parsedDiff,\n+ reviewCache.expandedFileIdsBySection,\n+ reviewCache.viewedFileIdsBySection,\n+ selectedSection?.id,\n+ ]);\n \n const expandedFileIds = useMemo(\n () =>\n selectedSection?.id && parsedDiff.kind === "files"\n- ? (reviewCache.expandedFileIdsBySection[selectedSection.id] ??\n- getDefaultExpandedFileIds(parsedDiff.files))\n+ ? getValidReviewExpandedFileIds(\n+ parsedDiff.files,\n+ localExpandedFileIdsBySection[selectedSection.id],\n+ )\n : [],\n- [parsedDiff, reviewCache.expandedFileIdsBySection, selectedSection?.id],\n+ [localExpandedFileIdsBySection, parsedDiff, selectedSection?.id],\n );\n const revealedLargeFileIds = useMemo(\n () =>\n@@ -526,47 +744,96 @@ export function ReviewSheet() {\n : [],\n [reviewCache.revealedLargeFileIdsBySection, selectedSection?.id],\n );\n+ const viewedFileIds = useMemo(\n+ () => (selectedSection?.id ? (localViewedFileIdsBySection[selectedSection.id] ?? []) : []),\n+ [localViewedFileIdsBySection, selectedSection?.id],\n+ );\n+ const viewedFileIdSet = useMemo(() => new Set(viewedFileIds), [viewedFileIds]);\n const reviewListItems = useMemo(\n () =>\n selectedSection && parsedDiff.kind === "files"\n- ? buildReviewListItems({\n- files: parsedDiff.files,\n- expandedFileIds,\n- revealedLargeFileIds,\n- })\n+ ? measureReviewWork("build-list-items", () =>\n+ buildReviewListItems({\n+ files: parsedDiff.files,\n+ expandedFileIds,\n+ revealedLargeFileIds,\n+ }),\n+ )\n : [],\n [expandedFileIds, parsedDiff, revealedLargeFileIds, selectedSection],\n );\n- const reviewFileById = useMemo(() => {\n+ const reviewLineRowsByFileId = useMemo(() => {\n if (parsedDiff.kind !== "files") {\n- return new Map<string, ReviewRenderableFile>();\n+ return new Map<string, ReadonlyArray<ReviewRenderableLineRow>>();\n }\n \n- return new Map(parsedDiff.files.map((file) => [file.id, file] as const));\n+ return measureReviewWork(\n+ "index-line-rows",\n+ () =>\n+ new Map(\n+ parsedDiff.files.map((file) => [\n+ file.id,\n+ file.rows.filter((row): row is ReviewRenderableLineRow => row.kind === "line"),\n+ ]),\n+ ),\n+ );\n }, [parsedDiff]);\n- const reviewLineRowsByFileId = useMemo(() => {\n+ const reviewContentWidthByFileId = useMemo(() => {\n if (parsedDiff.kind !== "files") {\n- return new Map<string, ReadonlyArray<ReviewRenderableLineRow>>();\n+ return new Map<string, number>();\n+ }\n+\n+ return measureReviewWork(\n+ "measure-file-widths",\n+ () =>\n+ new Map(\n+ parsedDiff.files.map((file) => [\n+ file.id,\n+ computeReviewFileContentWidth(\n+ file.rows,\n+ viewportWidth,\n+ computeReviewFileGutterWidth(file.rows),\n+ ),\n+ ]),\n+ ),\n+ );\n+ }, [parsedDiff, viewportWidth]);\n+ const reviewGutterWidthByFileId = useMemo(() => {\n+ if (parsedDiff.kind !== "files") {\n+ return new Map<string, number>();\n }\n \n return new Map(\n- parsedDiff.files.map((file) => [\n- file.id,\n- file.rows.filter((row): row is ReviewRenderableLineRow => row.kind === "line"),\n- ]),\n+ parsedDiff.files.map((file) => [file.id, computeReviewFileGutterWidth(file.rows)]),\n );\n }, [parsedDiff]);\n- const reviewLineIndexByRowId = useMemo(() => {\n- const map = new Map<string, number>();\n+ const getReviewFileHorizontalOffset = useCallback((fileId: string) => {\n+ let offset = horizontalOffsetByFileIdRef.current.get(fileId);\n+ if (!offset) {\n+ offset = makeMutable(0);\n+ horizontalOffsetByFileIdRef.current.set(fileId, offset);\n+ }\n \n- reviewLineRowsByFileId.forEach((rows) => {\n- rows.forEach((row, index) => {\n- map.set(row.id, index);\n- });\n- });\n+ return offset;\n+ }, []);\n+ useEffect(() => {\n+ const knownFileIds =\n+ parsedDiff.kind === "files" ? new Set(parsedDiff.files.map((file) => file.id)) : new Set();\n \n- return map;\n- }, [reviewLineRowsByFileId]);\n+ horizontalOffsetByFileIdRef.current.forEach((offset, fileId) => {\n+ if (!knownFileIds.has(fileId)) {\n+ horizontalOffsetByFileIdRef.current.delete(fileId);\n+ return;\n+ }\n+\n+ const contentWidth = reviewContentWidthByFileId.get(fileId) ?? viewportWidth;\n+ const gutterWidth = reviewGutterWidthByFileId.get(fileId) ?? 0;\n+ offset.value = Math.min(\n+ offset.value,\n+ Math.max(0, contentWidth - (viewportWidth - gutterWidth)),\n+ );\n+ });\n+ }, [parsedDiff, reviewContentWidthByFileId, reviewGutterWidthByFileId, viewportWidth]);\n const highlightableFiles = useMemo(() => {\n if (parsedDiff.kind !== "files") {\n return [] as ReadonlyArray<ReviewRenderableFile>;\n@@ -587,59 +854,13 @@ export function ReviewSheet() {\n );\n });\n }, [expandedFileIds, parsedDiff, revealedLargeFileIds]);\n- const highlightableFileIds = useMemo(\n- () => new Set(highlightableFiles.map((file) => file.id)),\n+ const highlightableFilesKey = useMemo(\n+ () => highlightableFiles.map((file) => `${file.id}:${file.cacheKey}`).join("\\n"),\n [highlightableFiles],\n );\n- const priorityHighlightFileIds = useMemo(() => {\n- if (parsedDiff.kind !== "files" || highlightableFiles.length === 0) {\n- return [] as ReadonlyArray<string>;\n- }\n-\n- const fileIdsInPriorityOrder =\n- visibleFileIds.length > 0\n- ? visibleFileIds.filter((fileId) => highlightableFileIds.has(fileId))\n- : parsedDiff.files\n- .slice(0, REVIEW_INITIAL_HIGHLIGHT_FILE_COUNT)\n- .map((file) => file.id)\n- .filter((fileId) => highlightableFileIds.has(fileId));\n-\n- if (fileIdsInPriorityOrder.length === 0) {\n- return [] as ReadonlyArray<string>;\n- }\n-\n- const firstVisibleIndex = parsedDiff.files.findIndex(\n- (file) => file.id === fileIdsInPriorityOrder[0],\n- );\n- const lastVisibleIndex = parsedDiff.files.findIndex(\n- (file) => file.id === fileIdsInPriorityOrder[fileIdsInPriorityOrder.length - 1],\n- );\n-\n- if (firstVisibleIndex < 0 || lastVisibleIndex < 0) {\n- return fileIdsInPriorityOrder;\n- }\n-\n- const startIndex = Math.max(0, firstVisibleIndex - REVIEW_HIGHLIGHT_BACKTRACK_COUNT);\n- const endIndex = Math.min(\n- parsedDiff.files.length - 1,\n- lastVisibleIndex + REVIEW_HIGHLIGHT_LOOKAHEAD_COUNT,\n- );\n-\n- const queuedIds: string[] = [];\n- for (let index = startIndex; index <= endIndex; index += 1) {\n- const fileId = parsedDiff.files[index]?.id;\n- if (fileId && highlightableFileIds.has(fileId)) {\n- queuedIds.push(fileId);\n- }\n- }\n-\n- return queuedIds;\n- }, [highlightableFileIds, highlightableFiles.length, parsedDiff, visibleFileIds]);\n- const viewportWidth = Math.max(width, 280);\n- const reviewListContentWidth = useMemo(\n- () => computeReviewListContentWidth(reviewListItems, viewportWidth),\n- [reviewListItems, viewportWidth],\n- );\n+ useEffect(() => {\n+ highlightableFilesRef.current = highlightableFiles;\n+ }, [highlightableFiles]);\n const loadGitDiffs = useCallback(async () => {\n if (!cwd) {\n return;\n@@ -714,100 +935,6 @@ export function ReviewSheet() {\n void loadGitDiffs();\n }, [loadGitDiffs]);\n \n- useEffect(() => {\n- selectedThemeRef.current = selectedTheme;\n- }, [selectedTheme]);\n-\n- useEffect(() => {\n- highlightableFilesByIdRef.current = new Map(highlightableFiles.map((file) => [file.id, file]));\n- }, [highlightableFiles]);\n-\n- const startHighlightQueueRunner = useCallback(function startHighlightQueueRunner() {\n- if (highlightQueueActiveRef.current) {\n- return;\n- }\n-\n- const generation = highlightQueueGenerationRef.current;\n- highlightQueueActiveRef.current = true;\n-\n- void (async () => {\n- try {\n- while (generation === highlightQueueGenerationRef.current) {\n- const nextFileId = highlightQueueRef.current.shift();\n- if (!nextFileId) {\n- break;\n- }\n-\n- const file = highlightableFilesByIdRef.current.get(nextFileId);\n- if (!file) {\n- continue;\n- }\n-\n- const theme = selectedThemeRef.current;\n- const cached = getCachedHighlightedReviewFile(file, theme);\n- if (cached) {\n- logReviewDiffDiagnostic("using cached highlighted file", {\n- fileId: file.id,\n- filePath: file.path,\n- theme,\n- });\n- setHighlightedFilesById((current) =>\n- current[file.id] === cached ? current : { ...current, [file.id]: cached },\n- );\n- continue;\n- }\n-\n- logReviewDiffDiagnostic("requesting highlighted file", {\n- fileId: file.id,\n- filePath: file.path,\n- theme,\n- });\n-\n- try {\n- await new Promise<void>((resolve) => {\n- InteractionManager.runAfterInteractions(() => resolve());\n- });\n- const result = await highlightReviewFile(file, theme);\n- if (generation !== highlightQueueGenerationRef.current) {\n- logReviewDiffDiagnostic("discarding highlighted file after cancellation", {\n- fileId: file.id,\n- filePath: file.path,\n- });\n- return;\n- }\n-\n- logReviewDiffDiagnostic("received highlighted file", {\n- fileId: file.id,\n- filePath: file.path,\n- additionLines: result.additionLines.length,\n- deletionLines: result.deletionLines.length,\n- });\n- setHighlightedFilesById((current) => {\n- if (current[file.id] === result) {\n- return current;\n- }\n- return { ...current, [file.id]: result };\n- });\n- } catch (error) {\n- logReviewDiffDiagnostic("highlight request failed", {\n- fileId: file.id,\n- filePath: file.path,\n- error: error instanceof Error ? error.message : String(error),\n- });\n- }\n- }\n- } finally {\n- highlightQueueActiveRef.current = false;\n- if (\n- generation === highlightQueueGenerationRef.current &&\n- highlightQueueRef.current.length > 0\n- ) {\n- startHighlightQueueRunner();\n- }\n- }\n- })();\n- }, []);\n-\n useEffect(() => {\n if (reviewSections.length === 0) {\n return;\n@@ -854,15 +981,15 @@ export function ReviewSheet() {\n }\n \n updateReviewExpandedFileIds(reviewCache.threadKey, selectedSection.id, (existing) => {\n- if (existing !== undefined) {\n- const validIds = existing.filter((id) => parsedDiff.files.some((file) => file.id === id));\n- if (validIds.length === existing.length) {\n- return existing;\n- }\n- return validIds;\n+ const validIds = getValidReviewExpandedFileIds(parsedDiff.files, existing);\n+ if (\n+ existing !== undefined &&\n+ validIds.length === existing.length &&\n+ validIds.every((id, index) => id === existing[index])\n+ ) {\n+ return existing;\n }\n-\n- return getDefaultExpandedFileIds(parsedDiff.files);\n+ return validIds;\n });\n }, [parsedDiff, reviewCache.threadKey, selectedSection?.id]);\n \n@@ -887,11 +1014,7 @@ export function ReviewSheet() {\n \n useEffect(() => {\n setHighlightedFilesById({});\n- setVisibleFileIds([]);\n- highlightQueueGenerationRef.current += 1;\n- highlightQueueRef.current = [];\n- highlightRequestedFileIdsRef.current = new Set();\n- highlightQueueActiveRef.current = false;\n+ highlightRunIdRef.current += 1;\n clearReviewHighlightFileCache();\n loggedMissingReviewTokenKeys.clear();\n logReviewDiffDiagnostic("reset highlighted files", {\n@@ -905,15 +1028,23 @@ export function ReviewSheet() {\n return;\n }\n \n+ markReviewEvent("parsed-diff-ready", {\n+ sectionId: selectedSection?.id ?? null,\n+ fileCount: parsedDiff.fileCount,\n+ additions: parsedDiff.additions,\n+ deletions: parsedDiff.deletions,\n+ renderedItems: reviewListItems.length,\n+ });\n logReviewDiffDiagnostic("parsed diff files", {\n selectedSectionId: selectedSection?.id ?? null,\n fileCount: parsedDiff.fileCount,\n renderableFileCount: parsedDiff.files.length,\n });\n- }, [parsedDiff, selectedSection?.id]);\n+ }, [parsedDiff, reviewListItems.length, selectedSection?.id]);\n \n useEffect(() => {\n- if (priorityHighlightFileIds.length === 0) {\n+ const files = highlightableFilesRef.current;\n+ if (files.length === 0) {\n logReviewDiffDiagnostic("no highlightable files", {\n selectedSectionId: selectedSection?.id ?? null,\n parsedDiffKind: parsedDiff.kind,\n@@ -922,33 +1053,98 @@ export function ReviewSheet() {\n return;\n }\n \n- const queuedFileIds: string[] = [];\n- priorityHighlightFileIds.forEach((fileId) => {\n- if (highlightRequestedFileIdsRef.current.has(fileId)) {\n- return;\n- }\n-\n- const file = highlightableFilesByIdRef.current.get(fileId);\n- if (!file) {\n- return;\n- }\n-\n- highlightRequestedFileIdsRef.current.add(fileId);\n- highlightQueueRef.current.push(fileId);\n- queuedFileIds.push(fileId);\n- });\n-\n- if (queuedFileIds.length === 0) {\n+ if (reviewHighlighter.status !== "ready") {\n+ logReviewDiffDiagnostic("waiting for highlighter provider", {\n+ selectedSectionId: selectedSection?.id ?? null,\n+ status: reviewHighlighter.status,\n+ error: reviewHighlighter.error,\n+ });\n return;\n }\n \n- logReviewDiffDiagnostic("scheduling file highlights", {\n+ const runId = highlightRunIdRef.current;\n+ let cancelled = false;\n+\n+ logReviewDiffDiagnostic("streaming file highlights", {\n selectedSectionId: selectedSection?.id ?? null,\n- fileCount: queuedFileIds.length,\n- fileIds: queuedFileIds,\n+ fileCount: files.length,\n });\n- startHighlightQueueRunner();\n- }, [parsedDiff.kind, priorityHighlightFileIds, selectedSection?.id, startHighlightQueueRunner]);\n+\n+ void (async () => {\n+ for (const file of files) {\n+ if (cancelled || runId !== highlightRunIdRef.current) {\n+ return;\n+ }\n+\n+ const cached = getCachedHighlightedReviewFile(file, selectedTheme);\n+ if (cached) {\n+ setHighlightedFilesById((current) =>\n+ current[file.id] === cached ? current : { ...current, [file.id]: cached },\n+ );\n+ continue;\n+ }\n+\n+ logReviewDiffDiagnostic("requesting highlighted file", {\n+ fileId: file.id,\n+ filePath: file.path,\n+ theme: selectedTheme,\n+ });\n+\n+ try {\n+ const highlightStartedAt = performance.now();\n+ const result = await streamHighlightReviewFile(file, selectedTheme, (progress) => {\n+ if (cancelled || runId !== highlightRunIdRef.current) {\n+ return;\n+ }\n+\n+ if (!progress.complete) {\n+ return;\n+ }\n+\n+ logReviewDiffDiagnostic("received streamed highlighted file", {\n+ fileId: file.id,\n+ filePath: file.path,\n+ highlightedLineCount: progress.highlightedLineCount,\n+ durationMs: Math.round(performance.now() - highlightStartedAt),\n+ });\n+ });\n+\n+ if (cancelled || runId !== highlightRunIdRef.current) {\n+ return;\n+ }\n+\n+ logReviewDiffDiagnostic("received highlighted file", {\n+ fileId: file.id,\n+ filePath: file.path,\n+ additionLines: result.additionLines.length,\n+ deletionLines: result.deletionLines.length,\n+ });\n+ setHighlightedFilesById((current) =>\n+ current[file.id] === result ? current : { ...current, [file.id]: result },\n+ );\n+ } catch (error) {\n+ logReviewDiffDiagnostic("highlight request failed", {\n+ fileId: file.id,\n+ filePath: file.path,\n+ error: error instanceof Error ? error.message : String(error),\n+ });\n+ }\n+\n+ await waitForReviewDelay(0);\n+ }\n+ })();\n+\n+ return () => {\n+ cancelled = true;\n+ };\n+ }, [\n+ highlightableFilesKey,\n+ parsedDiff.kind,\n+ reviewHighlighter.error,\n+ reviewHighlighter.status,\n+ selectedSection?.id,\n+ selectedTheme,\n+ ]);\n \n const refreshSelectedSection = useCallback(async () => {\n if (!selectedSection) {\n@@ -968,20 +1164,68 @@ export function ReviewSheet() {\n \n const handleToggleExpandedFile = useCallback(\n (fileId: string) => {\n- if (!reviewCache.threadKey || !selectedSection?.id || parsedDiff.kind !== "files") {\n+ if (!selectedSection?.id || parsedDiff.kind !== "files") {\n return;\n }\n \n- updateReviewExpandedFileIds(reviewCache.threadKey, selectedSection.id, (existing) => {\n- const currentIds = existing ?? getDefaultExpandedFileIds(parsedDiff.files);\n- return currentIds.includes(fileId)\n+ const sectionId = selectedSection.id;\n+\n+ setLocalExpandedFileIdsBySection((current) => {\n+ const currentIds = getValidReviewExpandedFileIds(parsedDiff.files, current[sectionId]);\n+ const nextIds = currentIds.includes(fileId)\n ? currentIds.filter((id) => id !== fileId)\n : [...currentIds, fileId];\n+\n+ return {\n+ ...current,\n+ [sectionId]: nextIds,\n+ };\n });\n+\n+ if (reviewCache.threadKey) {\n+ updateReviewExpandedFileIds(reviewCache.threadKey, sectionId, (existing) => {\n+ const currentIds = getValidReviewExpandedFileIds(parsedDiff.files, existing);\n+ return currentIds.includes(fileId)\n+ ? currentIds.filter((id) => id !== fileId)\n+ : [...currentIds, fileId];\n+ });\n+ }\n },\n [parsedDiff, reviewCache.threadKey, selectedSection?.id],\n );\n \n+ const handleToggleViewedFile = useCallback(\n+ (fileId: string) => {\n+ if (!selectedSection?.id) {\n+ return;\n+ }\n+\n+ const sectionId = selectedSection.id;\n+\n+ setLocalViewedFileIdsBySection((current) => {\n+ const currentIds = current[sectionId] ?? [];\n+ const nextIds = currentIds.includes(fileId)\n+ ? currentIds.filter((id) => id !== fileId)\n+ : [...currentIds, fileId];\n+\n+ return {\n+ ...current,\n+ [sectionId]: nextIds,\n+ };\n+ });\n+\n+ if (reviewCache.threadKey) {\n+ updateReviewViewedFileIds(reviewCache.threadKey, sectionId, (existing) => {\n+ const currentIds = existing ?? [];\n+ return currentIds.includes(fileId)\n+ ? currentIds.filter((id) => id !== fileId)\n+ : [...currentIds, fileId];\n+ });\n+ }\n+ },\n+ [reviewCache.threadKey, selectedSection?.id],\n+ );\n+\n const handleRevealLargeDiff = useCallback(\n (fileId: string) => {\n if (!reviewCache.threadKey || !selectedSection?.id) {\n@@ -1080,35 +1324,6 @@ export function ReviewSheet() {\n \n return <>{children}</>;\n }, [error, parsedDiffNotice]);\n- const stickyHeaderIndices = useMemo(() => {\n- const itemOffset = listHeader ? 1 : 0;\n-\n- return reviewListItems.flatMap((item, index) =>\n- item.kind === "file-header" ? [index + itemOffset] : [],\n- );\n- }, [listHeader, reviewListItems]);\n-\n- const viewabilityConfigRef = useRef({\n- itemVisiblePercentThreshold: 10,\n- });\n- const onViewableItemsChangedRef = useRef(\n- ({\n- viewableItems,\n- }: {\n- readonly viewableItems: Array<ViewToken<ReviewListItem>>;\n- readonly changed: Array<ViewToken<ReviewListItem>>;\n- }) => {\n- const nextVisibleFileIds = Array.from(\n- new Set(\n- viewableItems\n- .filter((token) => token.isViewable && token.item !== undefined)\n- .map((token) => token.item.fileId),\n- ),\n- );\n-\n- setVisibleFileIds(nextVisibleFileIds);\n- },\n- );\n \n const renderReviewListItem = useCallback(\n ({ item }: ListRenderItemInfo<ReviewListItem>) => {\n@@ -1116,112 +1331,142 @@ export function ReviewSheet() {\n return null;\n }\n \n+ let renderedItem: ReactElement | null = null;\n switch (item.kind) {\n case "file-header":\n- return (\n+ renderedItem = (\n <ReviewFileCard\n file={item.file}\n fileId={item.fileId}\n expanded={item.expanded}\n- viewportWidth={reviewListContentWidth}\n+ viewed={viewedFileIdSet.has(item.fileId)}\n+ viewportWidth={viewportWidth}\n onToggleFile={handleToggleExpandedFile}\n+ onToggleViewed={handleToggleViewedFile}\n />\n );\n+ break;\n case "file-suppressed":\n- return (\n+ renderedItem = (\n <ReviewFileSuppressedBody\n message={item.message}\n actionLabel={item.actionLabel}\n fileId={item.fileId}\n- viewportWidth={reviewListContentWidth}\n+ viewportWidth={viewportWidth}\n onLoadDiffFile={handleRevealLargeDiff}\n />\n );\n- case "hunk":\n- return (\n- <ReviewHunkRow\n- header={item.row.header}\n- context={item.row.context}\n- viewportWidth={reviewListContentWidth}\n- />\n+ break;\n+ case "hunk": {\n+ const contentWidth = reviewContentWidthByFileId.get(item.fileId) ?? viewportWidth;\n+ const gutterWidth = reviewGutterWidthByFileId.get(item.fileId) ?? 0;\n+\n+ renderedItem = (\n+ <ReviewCodePanRow\n+ key={item.id}\n+ contentWidth={contentWidth}\n+ gutterWidth={gutterWidth}\n+ horizontalOffset={getReviewFileHorizontalOffset(item.fileId)}\n+ leftGutter={<ReviewHunkGutter gutterWidth={gutterWidth} />}\n+ viewportWidth={viewportWidth}\n+ >\n+ <ReviewHunkRow\n+ header={item.row.header}\n+ context={item.row.context}\n+ viewportWidth={contentWidth}\n+ />\n+ </ReviewCodePanRow>\n );\n+ break;\n+ }\n case "line": {\n- const file = reviewFileById.get(item.fileId);\n- if (!file) {\n- return null;\n- }\n-\n- const fileLineRows = reviewLineRowsByFileId.get(file.id) ?? [];\n- const lineIndex = reviewLineIndexByRowId.get(item.row.id);\n- if (lineIndex === undefined) {\n- return null;\n- }\n-\n+ const fileLineRows = reviewLineRowsByFileId.get(item.file.id) ?? [];\n const pendingSelectionForFile =\n pendingCommentSelection &&\n pendingCommentSelection.sectionTitle === selectedSection.title &&\n- pendingCommentSelection.filePath === file.path\n+ pendingCommentSelection.filePath === item.file.path\n ? pendingCommentSelection\n : null;\n const selectedTargetForFile =\n activeCommentTarget &&\n activeCommentTarget.sectionTitle === selectedSection.title &&\n- activeCommentTarget.filePath === file.path\n+ activeCommentTarget.filePath === item.file.path\n ? activeCommentTarget\n : null;\n const highlightedFile =\n- highlightedFilesById[file.id] ??\n- getCachedHighlightedReviewFile(file, selectedTheme) ??\n+ deferredHighlightedFilesById[item.file.id] ??\n+ getCachedHighlightedReviewFile(item.file, selectedTheme) ??\n null;\n+ const contentWidth = reviewContentWidthByFileId.get(item.fileId) ?? viewportWidth;\n+ const gutterWidth = reviewGutterWidthByFileId.get(item.fileId) ?? 0;\n \n if (highlightedFile === null) {\n- const missingTokenKey = `${selectedSection.id}:${file.id}`;\n+ const missingTokenKey = `${selectedSection.id}:${item.file.id}`;\n if (!loggedMissingReviewTokenKeys.has(missingTokenKey)) {\n loggedMissingReviewTokenKeys.add(missingTokenKey);\n logReviewDiffDiagnostic("rendering file without tokens", {\n sectionId: selectedSection.id,\n- fileId: file.id,\n- filePath: file.path,\n- highlightedFileKnownInState: highlightedFilesById[file.id] !== undefined,\n+ fileId: item.file.id,\n+ filePath: item.file.path,\n+ highlightedFileKnownInState:\n+ deferredHighlightedFilesById[item.file.id] !== undefined,\n });\n }\n }\n \n const selectionState =\n- pendingSelectionForFile?.anchorIndex === lineIndex\n+ pendingSelectionForFile?.anchorIndex === item.lineIndex\n ? ("anchor" as const)\n : selectedTargetForFile &&\n- lineIndex >= selectedTargetForFile.startIndex &&\n- lineIndex <= selectedTargetForFile.endIndex\n+ item.lineIndex >= selectedTargetForFile.startIndex &&\n+ item.lineIndex <= selectedTargetForFile.endIndex\n ? ("selected" as const)\n : null;\n \n- return (\n- <ReviewLineRow\n- line={item.row}\n- tokens={getHighlightedTokensForLine(item.row, highlightedFile)}\n- viewportWidth={reviewListContentWidth}\n- selectionState={selectionState}\n- onComment={() =>\n- handlePressLine({\n- sectionTitle: selectedSection.title,\n- filePath: file.path,\n- lines: fileLineRows,\n- lineIndex,\n- })\n- }\n- onStartRangeSelection={() =>\n- handleStartRangeSelection({\n- sectionTitle: selectedSection.title,\n- filePath: file.path,\n- lines: fileLineRows,\n- lineIndex,\n- })\n+ renderedItem = (\n+ <ReviewCodePanRow\n+ key={item.id}\n+ contentWidth={contentWidth}\n+ gutterWidth={gutterWidth}\n+ horizontalOffset={getReviewFileHorizontalOffset(item.fileId)}\n+ leftGutter={\n+ <ReviewLineGutter\n+ change={item.row.change}\n+ gutterWidth={gutterWidth}\n+ lineNumber={getReviewUnifiedLineNumber(item.row)}\n+ />\n }\n- />\n+ viewportWidth={viewportWidth}\n+ >\n+ <ReviewLineRow\n+ line={item.row}\n+ tokens={getHighlightedTokensForLine(item.row, highlightedFile)}\n+ viewportWidth={contentWidth}\n+ selectionState={selectionState}\n+ onComment={() =>\n+ handlePressLine({\n+ sectionTitle: selectedSection.title,\n+ filePath: item.file.path,\n+ lines: fileLineRows,\n+ lineIndex: item.lineIndex,\n+ })\n+ }\n+ onStartRangeSelection={() =>\n+ handleStartRangeSelection({\n+ sectionTitle: selectedSection.title,\n+ filePath: item.file.path,\n+ lines: fileLineRows,\n+ lineIndex: item.lineIndex,\n+ })\n+ }\n+ />\n+ </ReviewCodePanRow>\n );\n+ break;\n }\n }\n+\n+ return renderedItem;\n },\n [\n activeCommentTarget,\n@@ -1229,14 +1474,17 @@ export function ReviewSheet() {\n handleRevealLargeDiff,\n handleStartRangeSelection,\n handleToggleExpandedFile,\n- highlightedFilesById,\n+ handleToggleViewedFile,\n+ getReviewFileHorizontalOffset,\n+ deferredHighlightedFilesById,\n pendingCommentSelection,\n- reviewFileById,\n- reviewLineIndexByRowId,\n+ reviewContentWidthByFileId,\n+ reviewGutterWidthByFileId,\n reviewLineRowsByFileId,\n- reviewListContentWidth,\n selectedSection,\n selectedTheme,\n+ viewedFileIdSet,\n+ viewportWidth,\n ],\n );\n \n@@ -1374,27 +1622,20 @@ export function ReviewSheet() {\n <View className="flex-1 bg-sheet">\n {selectedSection && parsedDiff.kind === "files" ? (\n <FlatList\n- style={{ flex: 1 }}\n+ style={{ flex: 1, width: viewportWidth }}\n contentInsetAdjustmentBehavior="never"\n- contentInset={{ top: topContentInset }}\n- contentOffset={{ x: 0, y: -topContentInset }}\n- scrollIndicatorInsets={{ top: topContentInset }}\n data={reviewListItems}\n renderItem={renderReviewListItem}\n keyExtractor={(item) => item.id}\n+ initialNumToRender={20}\n+ maxToRenderPerBatch={20}\n+ updateCellsBatchingPeriod={16}\n+ windowSize={5}\n+ removeClippedSubviews={false}\n keyboardShouldPersistTaps="handled"\n ListHeaderComponent={listHeader}\n- stickyHeaderIndices={stickyHeaderIndices}\n- removeClippedSubviews={false}\n- initialNumToRender={24}\n- maxToRenderPerBatch={16}\n- updateCellsBatchingPeriod={16}\n- windowSize={10}\n- scrollEventThrottle={16}\n- onViewableItemsChanged={onViewableItemsChangedRef.current}\n- viewabilityConfig={viewabilityConfigRef.current}\n contentContainerStyle={{\n- paddingTop: REVIEW_HEADER_SPACING,\n+ paddingTop: topContentInset + REVIEW_HEADER_SPACING,\n paddingBottom: Math.max(insets.bottom, 18) + 18,\n }}\n />\ndiff --git a/apps/mobile/src/features/review/shikiReviewHighlighter.ts b/apps/mobile/src/features/review/shikiReviewHighlighter.ts\nindex f7a5c4125..eb6bf6973 100644\n--- a/apps/mobile/src/features/review/shikiReviewHighlighter.ts\n+++ b/apps/mobile/src/features/review/shikiReviewHighlighter.ts\n@@ -1,5 +1,14 @@\n import { createHighlighterCore, type HighlighterCore } from "@shikijs/core";\n import { createJavaScriptRegexEngine } from "@shikijs/engine-javascript";\n+import bashLanguage from "@shikijs/langs/bash";\n+import javascriptLanguage from "@shikijs/langs/javascript";\n+import jsonLanguage from "@shikijs/langs/json";\n+import jsxLanguage from "@shikijs/langs/jsx";\n+import tsxLanguage from "@shikijs/langs/tsx";\n+import typescriptLanguage from "@shikijs/langs/typescript";\n+import yamlLanguage from "@shikijs/langs/yaml";\n+import githubDarkDefault from "@shikijs/themes/github-dark-default";\n+import githubLightDefault from "@shikijs/themes/github-light-default";\n import { getFiletypeFromFileName } from "@pierre/diffs/utils";\n \n import {\n@@ -11,6 +20,7 @@ import type { ReviewRenderableFile, ReviewRenderableLineRow } from "./reviewMode\n import { applyDiffRangesToTokens, computeWordAltDiffRanges } from "./reviewWordDiffs";\n \n export type ReviewDiffTheme = "light" | "dark";\n+export type { ReviewHighlighterEngine };\n \n export interface ReviewHighlightedToken {\n content: string;\n@@ -24,12 +34,19 @@ export interface ReviewHighlightedFile {\n readonly deletionLines: ReadonlyArray<ReadonlyArray<ReviewHighlightedToken>>;\n }\n \n+export interface ReviewHighlightFileProgress {\n+ readonly highlightedFile: ReviewHighlightedFile;\n+ readonly complete: boolean;\n+ readonly highlightedLineCount: number;\n+}\n+\n const SHIKI_THEME_NAME_BY_SCHEME = {\n light: "github-light-default",\n dark: "github-dark-default",\n } as const;\n const REVIEW_HIGHLIGHTER_ENGINE_ENV_VALUE =\n- process.env.EXPO_PUBLIC_REVIEW_HIGHLIGHTER_ENGINE ?? "javascript";\n+ process.env.EXPO_PUBLIC_REVIEW_HIGHLIGHTER_ENGINE ??\n+ (process.env.NODE_ENV === "test" ? "javascript" : "native");\n const REVIEW_HIGHLIGHTER_ENGINE_PREFERENCE = resolveReviewHighlighterEnginePreference(\n REVIEW_HIGHLIGHTER_ENGINE_ENV_VALUE,\n );\n@@ -38,12 +55,30 @@ const REVIEW_HIGHLIGHTER_DISABLE_RESULT_CACHE = resolveReviewHighlighterBooleanF\n false,\n );\n const REVIEW_HIGHLIGHT_RESULT_CACHE_LIMIT = 8;\n-const REVIEW_HIGHLIGHT_CHUNK_LINE_THRESHOLD = 40;\n-const REVIEW_HIGHLIGHT_CHUNK_SIZE = 20;\n+const REVIEW_HIGHLIGHT_CHUNK_LINE_THRESHOLD = 8;\n+const REVIEW_HIGHLIGHT_CHUNK_SIZE = 200;\n const REVIEW_TOKENIZE_MAX_LINE_LENGTH = 1_000;\n const highlightCache = new Map<string, Promise<ReviewHighlightedFile>>();\n const resolvedHighlightCache = new Map<string, ReviewHighlightedFile>();\n-const loadedLanguages = new Set<string>(["text"]);\n+const REVIEW_INITIAL_LANGUAGE_MODULES = [\n+ bashLanguage,\n+ javascriptLanguage,\n+ jsonLanguage,\n+ jsxLanguage,\n+ tsxLanguage,\n+ typescriptLanguage,\n+ yamlLanguage,\n+] satisfies Parameters<typeof createHighlighterCore>[0]["langs"];\n+const loadedLanguages = new Set<string>([\n+ "text",\n+ "bash",\n+ "javascript",\n+ "json",\n+ "jsx",\n+ "tsx",\n+ "typescript",\n+ "yaml",\n+]);\n const languageLoadingPromises = new Map<string, Promise<boolean>>();\n const languageImports: Partial<Record<string, () => Promise<unknown>>> = {\n javascript: () => import("@shikijs/langs/javascript"),\n@@ -215,21 +250,13 @@ function joinPatchLines(lines: ReadonlyArray<string>): string {\n \n function waitForNextFrame(): Promise<void> {\n return new Promise((resolve) => {\n- if (typeof requestAnimationFrame === "function") {\n- requestAnimationFrame(() => resolve());\n- return;\n- }\n-\n setTimeout(resolve, 0);\n });\n }\n \n async function getHighlighter(): Promise<HighlighterCore> {\n if (!highlighterPromise) {\n- const configuredHighlighterPromise = Promise.all([\n- import("@shikijs/themes/github-light-default"),\n- import("@shikijs/themes/github-dark-default"),\n- ]).then(async ([lightThemeModule, darkThemeModule]) => {\n+ const configuredHighlighterPromise = (async () => {\n let nativeEngineAvailable = false;\n \n logReviewHighlighterDiagnostic("initializing", {\n@@ -238,12 +265,11 @@ async function getHighlighter(): Promise<HighlighterCore> {\n resultCacheDisabled: REVIEW_HIGHLIGHTER_DISABLE_RESULT_CACHE,\n });\n \n- const themes = [lightThemeModule.default, darkThemeModule.default];\n+ const themes = [githubLightDefault, githubDarkDefault];\n \n if (REVIEW_HIGHLIGHTER_ENGINE_PREFERENCE !== "javascript") {\n try {\n const nativeEngineModule = await import("react-native-shiki-engine");\n- logReviewHighlighterDiagnostic("imported react-native-shiki-engine");\n nativeEngineAvailable = nativeEngineModule.isNativeEngineAvailable();\n logReviewHighlighterDiagnostic("checked native engine availability", {\n nativeEngineAvailable,\n@@ -253,7 +279,7 @@ async function getHighlighter(): Promise<HighlighterCore> {\n logReviewHighlighterDiagnostic("creating native regex engine");\n const highlighter = await createHighlighterCore({\n themes,\n- langs: [],\n+ langs: REVIEW_INITIAL_LANGUAGE_MODULES,\n engine: nativeEngineModule.createNativeEngine(),\n });\n logReviewHighlighterDiagnostic("using native engine");\n@@ -281,7 +307,7 @@ async function getHighlighter(): Promise<HighlighterCore> {\n );\n const highlighter = await createHighlighterCore({\n themes,\n- langs: [],\n+ langs: REVIEW_INITIAL_LANGUAGE_MODULES,\n engine: createJavaScriptRegexEngine(),\n });\n logReviewHighlighterDiagnostic("using javascript engine", {\n@@ -291,7 +317,7 @@ async function getHighlighter(): Promise<HighlighterCore> {\n highlighter,\n engine,\n };\n- });\n+ })();\n \n highlighterPromise = configuredHighlighterPromise\n .then((result) => result.highlighter)\n@@ -316,11 +342,52 @@ export async function getActiveReviewHighlighterEngine(): Promise<ReviewHighligh\n return activeHighlighterEnginePromise ?? Promise.resolve("javascript");\n }\n \n+export async function prepareReviewHighlighter(): Promise<void> {\n+ await getHighlighter();\n+}\n+\n+export async function prepareReviewHighlighterLanguages(\n+ languages: ReadonlyArray<string>,\n+): Promise<void> {\n+ const highlighter = await getHighlighter();\n+ await Promise.all(\n+ languages.map(async (language) => {\n+ const candidate = resolveLanguageAlias(language);\n+ if (candidate === "text" || !(candidate in languageImports)) {\n+ return;\n+ }\n+\n+ await loadSingleLanguage(highlighter, candidate);\n+ }),\n+ );\n+}\n+\n function resolveLanguageAlias(language: string): string {\n const normalized = language.toLowerCase();\n return languageAliases[normalized] ?? normalized;\n }\n \n+function resolveLoadedLanguageFromPath(\n+ path: string,\n+ languageHint: string | null = null,\n+): string | null {\n+ const detectedLanguage = languageHint ?? getFiletypeFromFileName(path);\n+ if (!detectedLanguage) {\n+ return "text";\n+ }\n+\n+ const candidate = resolveLanguageAlias(detectedLanguage);\n+ if (candidate === "text" || candidate === "ansi") {\n+ return "text";\n+ }\n+\n+ if (!(candidate in languageImports)) {\n+ return "text";\n+ }\n+\n+ return loadedLanguages.has(candidate) ? candidate : null;\n+}\n+\n async function loadSingleLanguage(\n highlighter: HighlighterCore,\n language: string,\n@@ -360,6 +427,11 @@ async function resolveLanguageFromPath(\n path: string,\n languageHint: string | null = null,\n ): Promise<string> {\n+ const loadedLanguage = resolveLoadedLanguageFromPath(path, languageHint);\n+ if (loadedLanguage) {\n+ return loadedLanguage;\n+ }\n+\n const detectedLanguage = languageHint ?? getFiletypeFromFileName(path);\n if (!detectedLanguage) {\n return "text";\n@@ -374,8 +446,12 @@ async function resolveLanguageFromPath(\n return "text";\n }\n \n+ if (loadedLanguages.has(candidate)) {\n+ return candidate;\n+ }\n+\n const highlighter = await getHighlighter();\n- const loaded = await loadSingleLanguage(highlighter, resolveLanguageAlias(candidate));\n+ const loaded = await loadSingleLanguage(highlighter, candidate);\n if (!loaded) {\n return "text";\n }\n@@ -384,7 +460,10 @@ async function resolveLanguageFromPath(\n }\n \n async function resolveLanguage(file: ReviewRenderableFile): Promise<string> {\n- return resolveLanguageFromPath(file.path, file.languageHint);\n+ return (\n+ resolveLoadedLanguageFromPath(file.path, file.languageHint) ??\n+ (await resolveLanguageFromPath(file.path, file.languageHint))\n+ );\n }\n \n function normalizeHighlightedLines(\n@@ -399,6 +478,18 @@ function normalizeHighlightedLines(\n );\n }\n \n+function makePlainHighlightedLines(\n+ lines: ReadonlyArray<string>,\n+): ReadonlyArray<ReadonlyArray<ReviewHighlightedToken>> {\n+ return lines.map((line) => [\n+ {\n+ content: stripTrailingNewline(line),\n+ color: null,\n+ fontStyle: null,\n+ },\n+ ]);\n+}\n+\n function applyWordAltDiffHighlightsToFile(\n file: ReviewRenderableFile,\n highlighted: ReviewHighlightedFile,\n@@ -594,6 +685,67 @@ async function highlightLines(\n return highlightedLines;\n }\n \n+async function highlightPatchLinesInChunks(input: {\n+ readonly lines: ReadonlyArray<string>;\n+ readonly language: string;\n+ readonly theme: string;\n+ readonly onChunk: (\n+ startIndex: number,\n+ tokens: ReadonlyArray<ReadonlyArray<ReviewHighlightedToken>>,\n+ ) => void;\n+}): Promise<ReadonlyArray<ReadonlyArray<ReviewHighlightedToken>>> {\n+ if (input.lines.length === 0) {\n+ return [];\n+ }\n+\n+ const highlighter = await getHighlighter();\n+ const highlightedLines: Array<ReadonlyArray<ReviewHighlightedToken>> = [];\n+\n+ for (\n+ let startIndex = 0;\n+ startIndex < input.lines.length;\n+ startIndex += REVIEW_HIGHLIGHT_CHUNK_SIZE\n+ ) {\n+ const lineChunk = input.lines.slice(startIndex, startIndex + REVIEW_HIGHLIGHT_CHUNK_SIZE);\n+ const chunkTokens: Array<ReadonlyArray<ReviewHighlightedToken>> = [];\n+ const tokenizableLines: string[] = [];\n+ const tokenizableIndexes: number[] = [];\n+\n+ lineChunk.forEach((line, index) => {\n+ const strippedLine = stripTrailingNewline(line);\n+ if (strippedLine.length > REVIEW_TOKENIZE_MAX_LINE_LENGTH) {\n+ chunkTokens[index] = [{ content: strippedLine, color: null, fontStyle: null }];\n+ return;\n+ }\n+\n+ tokenizableIndexes.push(index);\n+ tokenizableLines.push(strippedLine);\n+ });\n+\n+ if (tokenizableLines.length > 0) {\n+ const tokenLines = highlighter.codeToTokensBase(tokenizableLines.join("\\n"), {\n+ lang: input.language,\n+ theme: input.theme,\n+ });\n+ const normalizedTokenLines = normalizeHighlightedLines(tokenLines);\n+\n+ tokenizableIndexes.forEach((chunkIndex, tokenIndex) => {\n+ chunkTokens[chunkIndex] = normalizedTokenLines[tokenIndex] ?? [];\n+ });\n+ }\n+\n+ const completedChunk = lineChunk.map((_, index) => chunkTokens[index] ?? []);\n+ highlightedLines.push(...completedChunk);\n+ input.onChunk(startIndex, completedChunk);\n+\n+ if (startIndex + REVIEW_HIGHLIGHT_CHUNK_SIZE < input.lines.length) {\n+ await waitForNextFrame();\n+ }\n+ }\n+\n+ return highlightedLines;\n+}\n+\n function getHighlightCacheKey(file: ReviewRenderableFile, theme: ReviewDiffTheme): string {\n return `${SHIKI_THEME_NAME_BY_SCHEME[theme]}:${file.cacheKey}`;\n }\n@@ -667,7 +819,28 @@ export async function highlightReviewFile(\n deletionLineCount: file.deletionLines.length,\n rowCount: file.rows.length,\n });\n- const language = await resolveLanguage(file);\n+ const loadedLanguage = resolveLoadedLanguageFromPath(file.path, file.languageHint);\n+ const language = loadedLanguage ?? (await resolveLanguage(file));\n+ if (language === "text") {\n+ const highlighted = applyWordAltDiffHighlightsToFile(file, {\n+ additionLines: makePlainHighlightedLines(file.additionLines),\n+ deletionLines: makePlainHighlightedLines(file.deletionLines),\n+ });\n+ if (!REVIEW_HIGHLIGHTER_DISABLE_RESULT_CACHE) {\n+ storeResolvedHighlightedFile(cacheKey, highlighted);\n+ }\n+ logReviewHighlighterDiagnostic("file highlight complete", {\n+ fileId: file.id,\n+ filePath: file.path,\n+ theme,\n+ language,\n+ highlightedAdditionLineCount: highlighted.additionLines.length,\n+ highlightedDeletionLineCount: highlighted.deletionLines.length,\n+ durationMs: Date.now() - startedAt,\n+ });\n+ return highlighted;\n+ }\n+\n const additionLines = await highlightLines(\n joinPatchLines(file.additionLines),\n language,\n@@ -707,6 +880,113 @@ export async function highlightReviewFile(\n });\n }\n \n+export async function streamHighlightReviewFile(\n+ file: ReviewRenderableFile,\n+ theme: ReviewDiffTheme,\n+ onProgress: (progress: ReviewHighlightFileProgress) => void,\n+): Promise<ReviewHighlightedFile> {\n+ const shikiTheme = SHIKI_THEME_NAME_BY_SCHEME[theme];\n+ const cacheKey = getHighlightCacheKey(file, theme);\n+ if (!REVIEW_HIGHLIGHTER_DISABLE_RESULT_CACHE) {\n+ const resolved = resolvedHighlightCache.get(cacheKey);\n+ if (resolved) {\n+ onProgress({\n+ highlightedFile: resolved,\n+ complete: true,\n+ highlightedLineCount: resolved.additionLines.length + resolved.deletionLines.length,\n+ });\n+ return resolved;\n+ }\n+ }\n+\n+ const startedAt = Date.now();\n+ logReviewHighlighterDiagnostic("file stream highlight start", {\n+ fileId: file.id,\n+ filePath: file.path,\n+ theme,\n+ additionLineCount: file.additionLines.length,\n+ deletionLineCount: file.deletionLines.length,\n+ rowCount: file.rows.length,\n+ });\n+\n+ const loadedLanguage = resolveLoadedLanguageFromPath(file.path, file.languageHint);\n+ const language = loadedLanguage ?? (await resolveLanguage(file));\n+ if (language === "text") {\n+ const highlighted = applyWordAltDiffHighlightsToFile(file, {\n+ additionLines: makePlainHighlightedLines(file.additionLines),\n+ deletionLines: makePlainHighlightedLines(file.deletionLines),\n+ });\n+ if (!REVIEW_HIGHLIGHTER_DISABLE_RESULT_CACHE) {\n+ storeResolvedHighlightedFile(cacheKey, highlighted);\n+ }\n+ onProgress({\n+ highlightedFile: highlighted,\n+ complete: true,\n+ highlightedLineCount: highlighted.additionLines.length + highlighted.deletionLines.length,\n+ });\n+ logReviewHighlighterDiagnostic("file stream highlight complete", {\n+ fileId: file.id,\n+ filePath: file.path,\n+ theme,\n+ language,\n+ highlightedAdditionLineCount: highlighted.additionLines.length,\n+ highlightedDeletionLineCount: highlighted.deletionLines.length,\n+ highlightedLineCount: highlighted.additionLines.length + highlighted.deletionLines.length,\n+ durationMs: Date.now() - startedAt,\n+ });\n+ return highlighted;\n+ }\n+\n+ const additionLines: Array<ReadonlyArray<ReviewHighlightedToken>> = [];\n+ const deletionLines: Array<ReadonlyArray<ReviewHighlightedToken>> = [];\n+ let highlightedLineCount = 0;\n+\n+ await highlightPatchLinesInChunks({\n+ lines: file.additionLines,\n+ language,\n+ theme: shikiTheme,\n+ onChunk: (startIndex, tokens) => {\n+ tokens.forEach((lineTokens, index) => {\n+ additionLines[startIndex + index] = lineTokens;\n+ });\n+ highlightedLineCount += tokens.length;\n+ },\n+ });\n+ await waitForNextFrame();\n+ await highlightPatchLinesInChunks({\n+ lines: file.deletionLines,\n+ language,\n+ theme: shikiTheme,\n+ onChunk: (startIndex, tokens) => {\n+ tokens.forEach((lineTokens, index) => {\n+ deletionLines[startIndex + index] = lineTokens;\n+ });\n+ highlightedLineCount += tokens.length;\n+ },\n+ });\n+\n+ const highlighted = applyWordAltDiffHighlightsToFile(file, { additionLines, deletionLines });\n+ if (!REVIEW_HIGHLIGHTER_DISABLE_RESULT_CACHE) {\n+ storeResolvedHighlightedFile(cacheKey, highlighted);\n+ }\n+ onProgress({\n+ highlightedFile: highlighted,\n+ complete: true,\n+ highlightedLineCount,\n+ });\n+ logReviewHighlighterDiagnostic("file stream highlight complete", {\n+ fileId: file.id,\n+ filePath: file.path,\n+ theme,\n+ language,\n+ highlightedAdditionLineCount: highlighted.additionLines.length,\n+ highlightedDeletionLineCount: highlighted.deletionLines.length,\n+ highlightedLineCount,\n+ durationMs: Date.now() - startedAt,\n+ });\n+ return highlighted;\n+}\n+\n export async function highlightReviewSelectedLines(input: {\n readonly filePath: string;\n readonly lines: ReadonlyArray<ReviewRenderableLineRow>;\n@@ -717,7 +997,9 @@ export async function highlightReviewSelectedLines(input: {\n return {};\n }\n \n- const language = await resolveLanguageFromPath(input.filePath, input.languageHint ?? null);\n+ const loadedLanguage = resolveLoadedLanguageFromPath(input.filePath, input.languageHint ?? null);\n+ const language =\n+ loadedLanguage ?? (await resolveLanguageFromPath(input.filePath, input.languageHint ?? null));\n const shikiTheme = SHIKI_THEME_NAME_BY_SCHEME[input.theme];\n const additionLikeLines = input.lines\n .filter((line) => line.change !== "delete")\n',
223 },
224 {
225 id: "large",
226 label: "Large",
227 filename: "review-large.diff",
228 lineCount: 3208,
229 diff: 'diff --git a/apps/mobile/package.json b/apps/mobile/package.json\nindex 08329e1d4..36ac93a0f 100644\n--- a/apps/mobile/package.json\n+++ b/apps/mobile/package.json\n@@ -30,6 +30,7 @@\n "config:dev": "APP_VARIANT=development expo config",\n "config:preview": "APP_VARIANT=preview expo config",\n "config:prod": "APP_VARIANT=production expo config",\n+ "profile:android:hermes": "mkdir -p profiles/review && react-native profile-hermes profiles/review",\n "test": "vitest run",\n "typecheck": "tsc --noEmit"\n },\ndiff --git a/apps/mobile/src/app/index.tsx b/apps/mobile/src/app/index.tsx\nindex f153db701..f6095c051 100644\n--- a/apps/mobile/src/app/index.tsx\n+++ b/apps/mobile/src/app/index.tsx\n@@ -43,28 +43,50 @@ export default function HomeRouteScreen() {\n headerTintColor: iconColor,\n headerTitle: "",\n headerRight: () => (\n- <Pressable\n- onPress={() => router.push("/connections")}\n- hitSlop={8}\n- style={{\n- flexDirection: "row",\n- alignItems: "center",\n- gap: 8,\n- paddingHorizontal: 4,\n- paddingVertical: 4,\n- }}\n- >\n- <ConnectionStatusDot state={connectionState} pulse={hasRemoteActivity} size={7} />\n- <RNText\n+ <View style={{ flexDirection: "row", alignItems: "center", gap: 12 }}>\n+ <Pressable\n+ onPress={() => router.push("/debug/syntax-highlight")}\n+ hitSlop={8}\n style={{\n- fontFamily: "DMSans_700Bold",\n- fontSize: 12,\n- color: secondaryFg,\n+ borderRadius: 999,\n+ backgroundColor: isDark ? "rgba(255,255,255,0.06)" : "rgba(0,0,0,0.06)",\n+ paddingHorizontal: 10,\n+ paddingVertical: 5,\n }}\n >\n- {CONNECTION_LABEL[connectionState]}\n- </RNText>\n- </Pressable>\n+ <RNText\n+ style={{\n+ fontFamily: "DMSans_700Bold",\n+ fontSize: 12,\n+ color: secondaryFg,\n+ }}\n+ >\n+ Debug\n+ </RNText>\n+ </Pressable>\n+ <Pressable\n+ onPress={() => router.push("/connections")}\n+ hitSlop={8}\n+ style={{\n+ flexDirection: "row",\n+ alignItems: "center",\n+ gap: 8,\n+ paddingHorizontal: 4,\n+ paddingVertical: 4,\n+ }}\n+ >\n+ <ConnectionStatusDot state={connectionState} pulse={hasRemoteActivity} size={7} />\n+ <RNText\n+ style={{\n+ fontFamily: "DMSans_700Bold",\n+ fontSize: 12,\n+ color: secondaryFg,\n+ }}\n+ >\n+ {CONNECTION_LABEL[connectionState]}\n+ </RNText>\n+ </Pressable>\n+ </View>\n ),\n headerSearchBarOptions: {\n placeholder: "Search threads",\ndiff --git a/apps/mobile/src/app/threads/[environmentId]/[threadId]/review.tsx b/apps/mobile/src/app/threads/[environmentId]/[threadId]/review.tsx\nindex 84c48c6ed..ee993ee7c 100644\n--- a/apps/mobile/src/app/threads/[environmentId]/[threadId]/review.tsx\n+++ b/apps/mobile/src/app/threads/[environmentId]/[threadId]/review.tsx\n@@ -1,5 +1,10 @@\n+import { ReviewHighlighterProvider } from "../../../../features/review/ReviewHighlighterProvider";\n import { ReviewSheet } from "../../../../features/review/ReviewSheet";\n \n export default function ReviewRoute() {\n- return <ReviewSheet />;\n+ return (\n+ <ReviewHighlighterProvider>\n+ <ReviewSheet />\n+ </ReviewHighlighterProvider>\n+ );\n }\ndiff --git a/apps/mobile/src/features/review/ReviewCommentComposerSheet.tsx b/apps/mobile/src/features/review/ReviewCommentComposerSheet.tsx\nindex 076a2286d..9a173224a 100644\n--- a/apps/mobile/src/features/review/ReviewCommentComposerSheet.tsx\n+++ b/apps/mobile/src/features/review/ReviewCommentComposerSheet.tsx\n@@ -2,15 +2,8 @@ import { useLocalSearchParams, useRouter } from "expo-router";\n import { SymbolView } from "expo-symbols";\n import { TextInputWrapper } from "expo-paste-input";\n import { useEffect, useMemo, useState } from "react";\n-import {\n- KeyboardAvoidingView,\n- Platform,\n- Pressable,\n- ScrollView,\n- View,\n- useColorScheme,\n- useWindowDimensions,\n-} from "react-native";\n+import { Pressable, ScrollView, View, useColorScheme, useWindowDimensions } from "react-native";\n+import { KeyboardStickyView } from "react-native-keyboard-controller";\n import { useSafeAreaInsets } from "react-native-safe-area-context";\n import ImageViewing from "react-native-image-viewing";\n \n@@ -34,6 +27,7 @@ import {\n import {\n changeTone,\n DiffTokenText,\n+ REVIEW_DIFF_LINE_HEIGHT,\n REVIEW_MONO_FONT_FAMILY,\n ReviewChangeBar,\n } from "./reviewDiffRendering";\n@@ -44,7 +38,6 @@ import {\n } from "./shikiReviewHighlighter";\n \n const REVIEW_COMMENT_PREVIEW_MAX_LINES = 5;\n-const REVIEW_COMMENT_LINE_HEIGHT = 26;\n \n export function ReviewCommentComposerSheet() {\n const router = useRouter();\n@@ -84,8 +77,8 @@ export function ReviewCommentComposerSheet() {\n ? `Lines ${firstNumber}-${lastNumber}`\n : `${selectedLines.length} lines selected`;\n const previewHeight = Math.max(\n- Math.min(selectedLines.length, REVIEW_COMMENT_PREVIEW_MAX_LINES) * REVIEW_COMMENT_LINE_HEIGHT,\n- REVIEW_COMMENT_LINE_HEIGHT,\n+ Math.min(selectedLines.length, REVIEW_COMMENT_PREVIEW_MAX_LINES) * REVIEW_DIFF_LINE_HEIGHT,\n+ REVIEW_DIFF_LINE_HEIGHT,\n );\n const previewViewportWidth = Math.max(width - 40, 280);\n const handleNativePaste = useNativePaste((uris) => {\n@@ -143,17 +136,13 @@ export function ReviewCommentComposerSheet() {\n }\n \n return (\n- <KeyboardAvoidingView\n- behavior={Platform.OS === "ios" ? "padding" : "height"}\n- keyboardVerticalOffset={Platform.OS === "ios" ? 12 : 0}\n- style={{ flex: 1 }}\n- >\n+ <View style={{ flex: 1 }}>\n <View\n style={{\n flex: 1,\n paddingHorizontal: 20,\n paddingTop: 8,\n- paddingBottom: Math.max(insets.bottom, 18) + 18,\n+ paddingBottom: Math.max(insets.bottom, 18) + 82,\n }}\n >\n <View className="flex-row items-center justify-between py-2">\n@@ -219,7 +208,7 @@ export function ReviewCommentComposerSheet() {\n <View\n key={line.id}\n className={cn("flex-row items-start", changeTone(line.change))}\n- style={{ height: REVIEW_COMMENT_LINE_HEIGHT }}\n+ style={{ height: REVIEW_DIFF_LINE_HEIGHT }}\n >\n <ReviewChangeBar change={line.change} />\n <Text\n@@ -280,35 +269,41 @@ export function ReviewCommentComposerSheet() {\n ) : null}\n </View>\n </View>\n-\n- <View className="flex-row items-center gap-3 pt-1">\n- <ControlPill icon="plus" onPress={() => void handlePickImages()} />\n- <View className="flex-1" />\n- <ControlPill\n- icon="arrow.up"\n- label="Comment"\n- variant="primary"\n- disabled={!canSubmit}\n- onPress={() => {\n- if (!target || !environmentId || !threadId || commentText.trim().length === 0) {\n- return;\n- }\n-\n- appendReviewCommentToDraft({\n- environmentId,\n- threadId,\n- text: formatReviewCommentContext(target, commentText),\n- attachments,\n- });\n- setAttachments([]);\n- clearReviewCommentTarget();\n- router.dismiss();\n- }}\n- />\n- </View>\n </View>\n )}\n </View>\n+ {target ? (\n+ <KeyboardStickyView style={{ position: "absolute", bottom: 0, left: 0, right: 0 }}>\n+ <View\n+ className="flex-row items-center gap-3 bg-sheet px-5 pt-3"\n+ style={{ paddingBottom: Math.max(insets.bottom, 18) }}\n+ >\n+ <ControlPill icon="plus" onPress={() => void handlePickImages()} />\n+ <View className="flex-1" />\n+ <ControlPill\n+ icon="arrow.up"\n+ label="Comment"\n+ variant="primary"\n+ disabled={!canSubmit}\n+ onPress={() => {\n+ if (!target || !environmentId || !threadId || commentText.trim().length === 0) {\n+ return;\n+ }\n+\n+ appendReviewCommentToDraft({\n+ environmentId,\n+ threadId,\n+ text: formatReviewCommentContext(target, commentText),\n+ attachments,\n+ });\n+ setAttachments([]);\n+ clearReviewCommentTarget();\n+ router.dismiss();\n+ }}\n+ />\n+ </View>\n+ </KeyboardStickyView>\n+ ) : null}\n <ImageViewing\n images={previewImageUri ? [{ uri: previewImageUri }] : []}\n imageIndex={0}\n@@ -317,6 +312,6 @@ export function ReviewCommentComposerSheet() {\n swipeToCloseEnabled\n doubleTapToZoomEnabled\n />\n- </KeyboardAvoidingView>\n+ </View>\n );\n }\ndiff --git a/apps/mobile/src/features/review/ReviewSheet.tsx b/apps/mobile/src/features/review/ReviewSheet.tsx\nindex 82c28e81e..e148a8da2 100644\n--- a/apps/mobile/src/features/review/ReviewSheet.tsx\n+++ b/apps/mobile/src/features/review/ReviewSheet.tsx\n@@ -1,17 +1,31 @@\n import { EnvironmentId, ThreadId, type OrchestrationCheckpointSummary } from "@t3tools/contracts";\n+import { Gesture, GestureDetector } from "react-native-gesture-handler";\n+import Animated, {\n+ makeMutable,\n+ type SharedValue,\n+ useAnimatedStyle,\n+ useSharedValue,\n+} from "react-native-reanimated";\n import { useLocalSearchParams, useRouter } from "expo-router";\n import Stack from "expo-router/stack";\n import { SymbolView } from "expo-symbols";\n-import { memo, type ReactElement, useCallback, useEffect, useMemo, useRef, useState } from "react";\n+import {\n+ memo,\n+ type ReactElement,\n+ useCallback,\n+ useDeferredValue,\n+ useEffect,\n+ useMemo,\n+ useRef,\n+ useState,\n+} from "react";\n import {\n ActivityIndicator,\n FlatList,\n- InteractionManager,\n type ListRenderItemInfo,\n Pressable,\n ScrollView,\n Text as NativeText,\n- type ViewToken,\n useColorScheme,\n useWindowDimensions,\n View,\n@@ -32,6 +46,7 @@ import {\n setReviewTurnDiff,\n updateReviewExpandedFileIds,\n updateReviewRevealedLargeFileIds,\n+ updateReviewViewedFileIds,\n useReviewCacheForThread,\n } from "./reviewState";\n import {\n@@ -45,11 +60,12 @@ import {\n type ReviewParsedDiff,\n type ReviewRenderableFile,\n type ReviewRenderableLineRow,\n+ type ReviewRenderableRow,\n } from "./reviewModel";\n import {\n clearReviewHighlightFileCache,\n getCachedHighlightedReviewFile,\n- highlightReviewFile,\n+ streamHighlightReviewFile,\n type ReviewDiffTheme,\n type ReviewHighlightedFile,\n type ReviewHighlightedToken,\n@@ -67,9 +83,12 @@ import {\n import {\n changeTone,\n DiffTokenText,\n+ REVIEW_DIFF_LINE_HEIGHT,\n REVIEW_MONO_FONT_FAMILY,\n ReviewChangeBar,\n } from "./reviewDiffRendering";\n+import { markReviewEvent, measureReviewWork } from "./reviewPerf";\n+import { useReviewHighlighterStatus } from "./ReviewHighlighterProvider";\n \n interface PendingCommentSelection {\n readonly sectionTitle: string;\n@@ -87,14 +106,21 @@ interface ReviewLineActionInput {\n \n const IOS_NAV_BAR_HEIGHT = 44;\n const REVIEW_HEADER_SPACING = 0;\n-const REVIEW_LINE_GUTTER_WIDTH = 62;\n+const REVIEW_CHANGE_BAR_WIDTH = 5;\n+const REVIEW_MIN_LINE_NUMBER_WIDTH = 27;\n+const REVIEW_LINE_NUMBER_DIGIT_WIDTH_ESTIMATE = 8;\n+const REVIEW_LINE_NUMBER_HORIZONTAL_PADDING = 6;\n const REVIEW_CHARACTER_WIDTH_ESTIMATE = 8.4;\n const REVIEW_MAX_CONTENT_WIDTH = 4_800;\n-const REVIEW_INITIAL_HIGHLIGHT_FILE_COUNT = 2;\n-const REVIEW_HIGHLIGHT_BACKTRACK_COUNT = 0;\n-const REVIEW_HIGHLIGHT_LOOKAHEAD_COUNT = 1;\n+const REVIEW_HUNK_ROW_HEIGHT = 35;\n+const REVIEW_FILE_HEADER_HEIGHT = 43;\n+const REVIEW_SUPPRESSED_ROW_HEIGHT = 92;\n const loggedMissingReviewTokenKeys = new Set<string>();\n \n+function waitForReviewDelay(durationMs: number): Promise<void> {\n+ return new Promise((resolve) => setTimeout(resolve, durationMs));\n+}\n+\n function isReviewDiffDebugLoggingEnabled(): boolean {\n return typeof __DEV__ !== "undefined" ? __DEV__ : false;\n }\n@@ -113,33 +139,27 @@ function logReviewDiffDiagnostic(message: string, details?: Record<string, unkno\n }\n \n function getFileHeaderChrome(changeType: ReviewRenderableFile["changeType"]): {\n- readonly rail: string;\n readonly dot: string;\n } {\n switch (changeType) {\n case "new":\n return {\n- rail: "bg-emerald-400",\n dot: "bg-emerald-400",\n };\n case "deleted":\n return {\n- rail: "bg-rose-400",\n dot: "bg-rose-400",\n };\n case "rename-pure":\n return {\n- rail: "bg-amber-400",\n dot: "bg-amber-400",\n };\n case "rename-changed":\n return {\n- rail: "bg-sky-400",\n dot: "bg-sky-400",\n };\n default:\n return {\n- rail: "bg-sky-400",\n dot: "bg-sky-400",\n };\n }\n@@ -159,51 +179,72 @@ function formatHeaderDiffSummary(parsedDiff: ReviewParsedDiff): {\n };\n }\n \n-function computeReviewListContentWidth(\n- items: ReadonlyArray<ReviewListItem>,\n+function computeReviewFileContentWidth(\n+ rows: ReadonlyArray<ReviewRenderableRow>,\n viewportWidth: number,\n+ gutterWidth: number,\n ): number {\n let maxTextLength = 0;\n \n- items.forEach((item) => {\n- switch (item.kind) {\n- case "file-header":\n- maxTextLength = Math.max(\n- maxTextLength,\n- item.file.path.length,\n- item.file.previousPath?.length ?? 0,\n- );\n- break;\n- case "file-suppressed":\n- maxTextLength = Math.max(maxTextLength, item.message.length, item.actionLabel?.length ?? 0);\n- break;\n- case "hunk":\n- maxTextLength = Math.max(\n- maxTextLength,\n- item.row.header.length + (item.row.context ? item.row.context.length + 1 : 0),\n- );\n- break;\n- case "line":\n- maxTextLength = Math.max(maxTextLength, item.row.content.length);\n- break;\n+ rows.forEach((row) => {\n+ if (row.kind === "hunk") {\n+ maxTextLength = Math.max(\n+ maxTextLength,\n+ row.header.length + (row.context ? row.context.length + 1 : 0),\n+ );\n+ return;\n }\n+\n+ maxTextLength = Math.max(maxTextLength, row.content.length);\n });\n \n return Math.max(\n- viewportWidth,\n+ Math.max(0, viewportWidth - gutterWidth),\n Math.min(\n REVIEW_MAX_CONTENT_WIDTH,\n- Math.ceil(REVIEW_LINE_GUTTER_WIDTH + 48 + maxTextLength * REVIEW_CHARACTER_WIDTH_ESTIMATE),\n+ Math.ceil(48 + maxTextLength * REVIEW_CHARACTER_WIDTH_ESTIMATE),\n ),\n );\n }\n \n+function computeReviewFileGutterWidth(rows: ReadonlyArray<ReviewRenderableRow>): number {\n+ let maxLineNumber = 0;\n+\n+ rows.forEach((row) => {\n+ if (row.kind !== "line") {\n+ return;\n+ }\n+\n+ maxLineNumber = Math.max(maxLineNumber, row.oldLineNumber ?? 0, row.newLineNumber ?? 0);\n+ });\n+\n+ const digitCount = Math.max(1, String(maxLineNumber).length);\n+ const lineNumberWidth = Math.max(\n+ REVIEW_MIN_LINE_NUMBER_WIDTH,\n+ digitCount * REVIEW_LINE_NUMBER_DIGIT_WIDTH_ESTIMATE + REVIEW_LINE_NUMBER_HORIZONTAL_PADDING,\n+ );\n+\n+ return REVIEW_CHANGE_BAR_WIDTH + lineNumberWidth;\n+}\n+\n function getDefaultExpandedFileIds(\n files: ReadonlyArray<ReviewRenderableFile>,\n ): ReadonlyArray<string> {\n return files.map((file) => file.id);\n }\n \n+function getValidReviewExpandedFileIds(\n+ files: ReadonlyArray<ReviewRenderableFile>,\n+ cachedExpandedFileIds: ReadonlyArray<string> | undefined,\n+): ReadonlyArray<string> {\n+ if (cachedExpandedFileIds === undefined) {\n+ return getDefaultExpandedFileIds(files);\n+ }\n+\n+ const fileIdSet = new Set(files.map((file) => file.id));\n+ return cachedExpandedFileIds.filter((id) => fileIdSet.has(id));\n+}\n+\n function getHighlightedTokensForLine(\n line: ReviewRenderableLineRow,\n highlightedFile: ReviewHighlightedFile | null,\n@@ -252,16 +293,13 @@ const ReviewLineRow = memo(function ReviewLineRow(props: {\n delayLongPress={220}\n onLongPress={props.onStartRangeSelection}\n onPress={props.onComment}\n- style={{ minWidth: props.viewportWidth }}\n+ style={{\n+ height: REVIEW_DIFF_LINE_HEIGHT,\n+ width: props.viewportWidth,\n+ overflow: "hidden",\n+ }}\n >\n- <ReviewChangeBar change={props.line.change} />\n- <Text\n- className="w-9 py-1 pr-1 text-right text-[11px] font-t3-medium text-foreground-muted"\n- style={{ fontFamily: REVIEW_MONO_FONT_FAMILY }}\n- >\n- {lineNumber ?? ""}\n- </Text>\n- <View className="min-w-0 flex-1 shrink-0 px-1 py-1">\n+ <View className="min-w-0 flex-1 shrink-0 px-1 py-1" style={{ width: props.viewportWidth }}>\n <DiffTokenText\n tokens={props.tokens}\n fallback={props.line.content}\n@@ -272,62 +310,135 @@ const ReviewLineRow = memo(function ReviewLineRow(props: {\n );\n });\n \n+const ReviewLineGutter = memo(function ReviewLineGutter(props: {\n+ readonly change: ReviewRenderableLineRow["change"];\n+ readonly gutterWidth: number;\n+ readonly lineNumber: number | null;\n+}) {\n+ const lineNumberWidth = Math.max(0, props.gutterWidth - REVIEW_CHANGE_BAR_WIDTH);\n+\n+ return (\n+ <View className={cn("flex-row", changeTone(props.change))} style={{ width: props.gutterWidth }}>\n+ <ReviewChangeBar change={props.change} />\n+ <Text\n+ className="py-1 pr-1 text-right text-[11px] font-t3-medium text-foreground-muted"\n+ style={[{ fontFamily: REVIEW_MONO_FONT_FAMILY }, { width: lineNumberWidth }]}\n+ >\n+ {props.lineNumber ?? ""}\n+ </Text>\n+ </View>\n+ );\n+});\n+\n+const ReviewHunkGutter = memo(function ReviewHunkGutter(props: { readonly gutterWidth: number }) {\n+ return (\n+ <View\n+ className="border-b border-border/60 bg-sky-500/10"\n+ style={{ width: props.gutterWidth }}\n+ />\n+ );\n+});\n+\n const ReviewFileCard = memo(function ReviewFileCard(props: {\n readonly file: ReviewRenderableFile;\n readonly fileId: string;\n readonly expanded: boolean;\n+ readonly viewed: boolean;\n readonly viewportWidth: number;\n readonly onToggleFile: (fileId: string) => void;\n+ readonly onToggleViewed: (fileId: string) => void;\n }) {\n- const chrome = getFileHeaderChrome(props.file.changeType);\n+ const { expanded, file, fileId, onToggleFile, onToggleViewed, viewed, viewportWidth } = props;\n+ const chrome = getFileHeaderChrome(file.changeType);\n+ const iconColor = String(useThemeColor("--color-icon-muted"));\n+ const handleToggleFile = useCallback(() => {\n+ onToggleFile(fileId);\n+ }, [fileId, onToggleFile]);\n+ const handleToggleViewed = useCallback(() => {\n+ onToggleViewed(fileId);\n+ }, [fileId, onToggleViewed]);\n \n return (\n <View\n- className="border-b border-border/70 bg-card"\n- style={{\n- zIndex: 1,\n- width: props.viewportWidth,\n- shadowColor: "#000000",\n- shadowOpacity: 0.08,\n- shadowRadius: 10,\n- shadowOffset: { width: 0, height: 6 },\n- elevation: 4,\n- }}\n+ className="border-b border-border bg-card"\n+ style={{ height: REVIEW_FILE_HEADER_HEIGHT, overflow: "hidden", width: viewportWidth }}\n >\n- <Pressable className="flex-row items-center" onPress={() => props.onToggleFile(props.fileId)}>\n- <View className={cn("w-1 self-stretch", chrome.rail)} />\n- <View className="flex-1 flex-row items-center px-3 py-1.5">\n- <View className="size-7 items-center justify-center rounded-full bg-subtle">\n- <SymbolView\n- name={props.expanded ? "chevron.down" : "chevron.right"}\n- size={12}\n- tintColor="#8a8a8a"\n- type="monochrome"\n- />\n- </View>\n- <View className="ml-2 min-w-0 flex-1 flex-row items-center gap-2">\n- <View className={cn("size-2 rounded-full", chrome.dot)} />\n- <View className="min-w-0 flex-1">\n- <Text className="font-mono text-[13px] leading-[18px] text-foreground">\n- {props.file.path}\n+ <View className="min-h-[42px] flex-row items-center gap-1.5 px-2">\n+ <Pressable\n+ className="size-9 items-center justify-center"\n+ accessibilityRole="button"\n+ accessibilityLabel={expanded ? "Collapse file" : "Expand file"}\n+ hitSlop={{ bottom: 8, left: 8, right: 8, top: 8 }}\n+ onTouchEnd={handleToggleFile}\n+ >\n+ <SymbolView\n+ name={expanded ? "chevron.down" : "chevron.right"}\n+ size={13}\n+ tintColor={iconColor}\n+ type="monochrome"\n+ />\n+ </Pressable>\n+ <Pressable\n+ className="min-w-0 flex-1 flex-row items-center gap-2 py-2"\n+ accessibilityRole="button"\n+ accessibilityLabel={expanded ? "Collapse file" : "Expand file"}\n+ onTouchEnd={handleToggleFile}\n+ >\n+ <View className={cn("size-2.5 rounded-full", chrome.dot)} />\n+ <View className="min-w-0 flex-1">\n+ <Text\n+ className="font-mono text-[13px] leading-[18px] text-foreground"\n+ numberOfLines={1}\n+ >\n+ {file.path}\n+ </Text>\n+ {file.previousPath && file.previousPath !== file.path ? (\n+ <Text\n+ className="font-mono text-[10px] leading-[14px] text-foreground-muted"\n+ numberOfLines={1}\n+ >\n+ {file.previousPath}\n </Text>\n- {props.file.previousPath && props.file.previousPath !== props.file.path ? (\n- <Text className="font-mono text-[10px] leading-[14px] text-foreground-muted">\n- {props.file.previousPath}\n- </Text>\n+ ) : null}\n+ </View>\n+ </Pressable>\n+ <View className="flex-row items-center justify-end gap-1.5">\n+ <Text className="font-mono text-[12px] font-t3-bold text-rose-400">\n+ -{file.deletions}\n+ </Text>\n+ <Text className="font-mono text-[12px] font-t3-bold text-emerald-400">\n+ +{file.additions}\n+ </Text>\n+ <Pressable\n+ className="ml-0.5 min-h-[40px] min-w-[82px] flex-row items-center justify-center gap-1.5 px-1.5"\n+ accessibilityRole="checkbox"\n+ accessibilityState={{ checked: viewed }}\n+ accessibilityLabel={viewed ? "Mark file as unviewed" : "Mark file as viewed"}\n+ hitSlop={{ bottom: 8, left: 4, right: 8, top: 8 }}\n+ onTouchEnd={handleToggleViewed}\n+ >\n+ <View\n+ className={cn(\n+ "size-[18px] items-center justify-center rounded border",\n+ viewed ? "border-sky-500 bg-sky-500" : "border-icon-muted",\n+ )}\n+ >\n+ {viewed ? (\n+ <SymbolView name="checkmark" size={11} tintColor="#ffffff" type="monochrome" />\n ) : null}\n </View>\n- </View>\n- <View className="ml-3 flex-row items-center justify-end gap-2">\n- <Text className="font-mono text-[12px] font-t3-bold text-emerald-600 dark:text-emerald-300">\n- +{props.file.additions}\n- </Text>\n- <Text className="font-mono text-[12px] font-t3-bold text-rose-600 dark:text-rose-300">\n- -{props.file.deletions}\n+ <Text\n+ className={cn(\n+ "text-[12px] font-t3-medium",\n+ viewed ? "text-foreground" : "text-foreground-muted",\n+ )}\n+ numberOfLines={1}\n+ >\n+ Viewed\n </Text>\n- </View>\n+ </Pressable>\n </View>\n- </Pressable>\n+ </View>\n </View>\n );\n });\n@@ -342,7 +453,11 @@ const ReviewFileSuppressedBody = memo(function ReviewFileSuppressedBody(props: {\n return (\n <View\n className="gap-2 border-b border-border bg-card px-4 py-3"\n- style={{ minWidth: props.viewportWidth }}\n+ style={{\n+ height: REVIEW_SUPPRESSED_ROW_HEIGHT,\n+ overflow: "hidden",\n+ width: props.viewportWidth,\n+ }}\n >\n <Text className="text-[12px] leading-[18px] text-foreground-muted">{props.message}</Text>\n {props.actionLabel && props.onLoadDiffFile ? (\n@@ -364,10 +479,13 @@ const ReviewHunkRow = memo(function ReviewHunkRow(props: {\n }) {\n return (\n <View\n- className="border-b border-border/60 bg-sky-500/10 px-2 py-2"\n- style={{ minWidth: props.viewportWidth }}\n+ className="border-b border-border/60 bg-sky-500/10 py-2"\n+ style={{ height: REVIEW_HUNK_ROW_HEIGHT, width: props.viewportWidth, overflow: "hidden" }}\n >\n- <Text className="font-mono text-[12px] leading-[18px] text-sky-700 dark:text-sky-300">\n+ <Text\n+ className="px-2 font-mono text-[12px] leading-[18px] text-sky-700 dark:text-sky-300"\n+ numberOfLines={1}\n+ >\n {props.header}\n {props.context ? ` ${props.context}` : ""}\n </Text>\n@@ -375,6 +493,61 @@ const ReviewHunkRow = memo(function ReviewHunkRow(props: {\n );\n });\n \n+const ReviewCodePanRow = memo(function ReviewCodePanRow(props: {\n+ readonly contentWidth: number;\n+ readonly horizontalOffset: SharedValue<number>;\n+ readonly gutterWidth?: number;\n+ readonly viewportWidth: number;\n+ readonly leftGutter?: ReactElement;\n+ readonly children: ReactElement;\n+}) {\n+ const {\n+ children,\n+ contentWidth,\n+ gutterWidth = 0,\n+ horizontalOffset,\n+ leftGutter,\n+ viewportWidth,\n+ } = props;\n+ const dragStartOffset = useSharedValue(0);\n+ const visibleContentWidth = leftGutter ? viewportWidth - gutterWidth : viewportWidth;\n+ const maxOffset = Math.max(0, contentWidth - visibleContentWidth);\n+\n+ const panGesture = useMemo(\n+ () =>\n+ Gesture.Pan()\n+ .activeOffsetX([-8, 8])\n+ .failOffsetY([-10, 10])\n+ .onBegin(() => {\n+ dragStartOffset.value = horizontalOffset.value;\n+ })\n+ .onUpdate((event) => {\n+ "worklet";\n+ const nextOffset = dragStartOffset.value - event.translationX;\n+ horizontalOffset.value = Math.min(maxOffset, Math.max(0, nextOffset));\n+ }),\n+ [dragStartOffset, horizontalOffset, maxOffset],\n+ );\n+\n+ const contentStyle = useAnimatedStyle(\n+ () => ({\n+ transform: [{ translateX: -horizontalOffset.value }],\n+ }),\n+ [horizontalOffset],\n+ );\n+\n+ return (\n+ <GestureDetector gesture={panGesture}>\n+ <View style={{ flexDirection: "row", overflow: "hidden", width: viewportWidth }}>\n+ {leftGutter ?? null}\n+ <View style={{ flex: 1, overflow: "hidden" }}>\n+ <Animated.View style={[{ width: contentWidth }, contentStyle]}>{children}</Animated.View>\n+ </View>\n+ </View>\n+ </GestureDetector>\n+ );\n+});\n+\n const ReviewNotice = memo(function ReviewNotice(props: { readonly notice: string }) {\n return (\n <View className="border-b border-amber-200 bg-amber-50 px-4 py-3 dark:border-amber-900/60 dark:bg-amber-950/40">\n@@ -454,15 +627,19 @@ export function ReviewSheet() {\n const [highlightedFilesById, setHighlightedFilesById] = useState<\n Record<string, ReviewHighlightedFile | null>\n >({});\n- const [visibleFileIds, setVisibleFileIds] = useState<ReadonlyArray<string>>([]);\n+ const deferredHighlightedFilesById = useDeferredValue(highlightedFilesById);\n+ const [localExpandedFileIdsBySection, setLocalExpandedFileIdsBySection] = useState<\n+ Record<string, ReadonlyArray<string>>\n+ >({});\n+ const [localViewedFileIdsBySection, setLocalViewedFileIdsBySection] = useState<\n+ Record<string, ReadonlyArray<string>>\n+ >({});\n const activeCommentTarget = useReviewCommentTarget();\n const selectedTheme = (colorScheme === "dark" ? "dark" : "light") satisfies ReviewDiffTheme;\n- const highlightQueueRef = useRef<string[]>([]);\n- const highlightRequestedFileIdsRef = useRef<Set<string>>(new Set());\n- const highlightQueueGenerationRef = useRef(0);\n- const highlightQueueActiveRef = useRef(false);\n- const highlightableFilesByIdRef = useRef<ReadonlyMap<string, ReviewRenderableFile>>(new Map());\n- const selectedThemeRef = useRef<ReviewDiffTheme>(selectedTheme);\n+ const reviewHighlighter = useReviewHighlighterStatus();\n+ const highlightRunIdRef = useRef(0);\n+ const highlightableFilesRef = useRef<ReadonlyArray<ReviewRenderableFile>>([]);\n+ const horizontalOffsetByFileIdRef = useRef<Map<string, SharedValue<number>>>(new Map());\n const { selectedThreadCwd } = useSelectedThreadWorktree();\n \n const cwd = selectedThreadCwd;\n@@ -498,11 +675,13 @@ export function ReviewSheet() {\n const topContentInset = insets.top + IOS_NAV_BAR_HEIGHT;\n const parsedDiff = useMemo(\n () =>\n- getCachedReviewParsedDiff({\n- threadKey: reviewCache.threadKey,\n- sectionId: selectedSection?.id ?? null,\n- diff: selectedSection?.diff,\n- }),\n+ measureReviewWork("parse-diff", () =>\n+ getCachedReviewParsedDiff({\n+ threadKey: reviewCache.threadKey,\n+ sectionId: selectedSection?.id ?? null,\n+ diff: selectedSection?.diff,\n+ }),\n+ ),\n [reviewCache.threadKey, selectedSection?.diff, selectedSection?.id],\n );\n const headerDiffSummary = useMemo(() => formatHeaderDiffSummary(parsedDiff), [parsedDiff]);\n@@ -510,14 +689,53 @@ export function ReviewSheet() {\n () => countReviewCommentContexts(draftMessage),\n [draftMessage],\n );\n+ const viewportWidth = Math.max(width, 280);\n+\n+ useEffect(() => {\n+ if (!selectedSection?.id || parsedDiff.kind !== "files") {\n+ return;\n+ }\n+\n+ setLocalExpandedFileIdsBySection((current) => {\n+ if (current[selectedSection.id] !== undefined) {\n+ return current;\n+ }\n+\n+ return {\n+ ...current,\n+ [selectedSection.id]: getValidReviewExpandedFileIds(\n+ parsedDiff.files,\n+ reviewCache.expandedFileIdsBySection[selectedSection.id],\n+ ),\n+ };\n+ });\n+\n+ setLocalViewedFileIdsBySection((current) => {\n+ if (current[selectedSection.id] !== undefined) {\n+ return current;\n+ }\n+\n+ return {\n+ ...current,\n+ [selectedSection.id]: reviewCache.viewedFileIdsBySection[selectedSection.id] ?? [],\n+ };\n+ });\n+ }, [\n+ parsedDiff,\n+ reviewCache.expandedFileIdsBySection,\n+ reviewCache.viewedFileIdsBySection,\n+ selectedSection?.id,\n+ ]);\n \n const expandedFileIds = useMemo(\n () =>\n selectedSection?.id && parsedDiff.kind === "files"\n- ? (reviewCache.expandedFileIdsBySection[selectedSection.id] ??\n- getDefaultExpandedFileIds(parsedDiff.files))\n+ ? getValidReviewExpandedFileIds(\n+ parsedDiff.files,\n+ localExpandedFileIdsBySection[selectedSection.id],\n+ )\n : [],\n- [parsedDiff, reviewCache.expandedFileIdsBySection, selectedSection?.id],\n+ [localExpandedFileIdsBySection, parsedDiff, selectedSection?.id],\n );\n const revealedLargeFileIds = useMemo(\n () =>\n@@ -526,47 +744,96 @@ export function ReviewSheet() {\n : [],\n [reviewCache.revealedLargeFileIdsBySection, selectedSection?.id],\n );\n+ const viewedFileIds = useMemo(\n+ () => (selectedSection?.id ? (localViewedFileIdsBySection[selectedSection.id] ?? []) : []),\n+ [localViewedFileIdsBySection, selectedSection?.id],\n+ );\n+ const viewedFileIdSet = useMemo(() => new Set(viewedFileIds), [viewedFileIds]);\n const reviewListItems = useMemo(\n () =>\n selectedSection && parsedDiff.kind === "files"\n- ? buildReviewListItems({\n- files: parsedDiff.files,\n- expandedFileIds,\n- revealedLargeFileIds,\n- })\n+ ? measureReviewWork("build-list-items", () =>\n+ buildReviewListItems({\n+ files: parsedDiff.files,\n+ expandedFileIds,\n+ revealedLargeFileIds,\n+ }),\n+ )\n : [],\n [expandedFileIds, parsedDiff, revealedLargeFileIds, selectedSection],\n );\n- const reviewFileById = useMemo(() => {\n+ const reviewLineRowsByFileId = useMemo(() => {\n if (parsedDiff.kind !== "files") {\n- return new Map<string, ReviewRenderableFile>();\n+ return new Map<string, ReadonlyArray<ReviewRenderableLineRow>>();\n }\n \n- return new Map(parsedDiff.files.map((file) => [file.id, file] as const));\n+ return measureReviewWork(\n+ "index-line-rows",\n+ () =>\n+ new Map(\n+ parsedDiff.files.map((file) => [\n+ file.id,\n+ file.rows.filter((row): row is ReviewRenderableLineRow => row.kind === "line"),\n+ ]),\n+ ),\n+ );\n }, [parsedDiff]);\n- const reviewLineRowsByFileId = useMemo(() => {\n+ const reviewContentWidthByFileId = useMemo(() => {\n if (parsedDiff.kind !== "files") {\n- return new Map<string, ReadonlyArray<ReviewRenderableLineRow>>();\n+ return new Map<string, number>();\n+ }\n+\n+ return measureReviewWork(\n+ "measure-file-widths",\n+ () =>\n+ new Map(\n+ parsedDiff.files.map((file) => [\n+ file.id,\n+ computeReviewFileContentWidth(\n+ file.rows,\n+ viewportWidth,\n+ computeReviewFileGutterWidth(file.rows),\n+ ),\n+ ]),\n+ ),\n+ );\n+ }, [parsedDiff, viewportWidth]);\n+ const reviewGutterWidthByFileId = useMemo(() => {\n+ if (parsedDiff.kind !== "files") {\n+ return new Map<string, number>();\n }\n \n return new Map(\n- parsedDiff.files.map((file) => [\n- file.id,\n- file.rows.filter((row): row is ReviewRenderableLineRow => row.kind === "line"),\n- ]),\n+ parsedDiff.files.map((file) => [file.id, computeReviewFileGutterWidth(file.rows)]),\n );\n }, [parsedDiff]);\n- const reviewLineIndexByRowId = useMemo(() => {\n- const map = new Map<string, number>();\n+ const getReviewFileHorizontalOffset = useCallback((fileId: string) => {\n+ let offset = horizontalOffsetByFileIdRef.current.get(fileId);\n+ if (!offset) {\n+ offset = makeMutable(0);\n+ horizontalOffsetByFileIdRef.current.set(fileId, offset);\n+ }\n \n- reviewLineRowsByFileId.forEach((rows) => {\n- rows.forEach((row, index) => {\n- map.set(row.id, index);\n- });\n- });\n+ return offset;\n+ }, []);\n+ useEffect(() => {\n+ const knownFileIds =\n+ parsedDiff.kind === "files" ? new Set(parsedDiff.files.map((file) => file.id)) : new Set();\n \n- return map;\n- }, [reviewLineRowsByFileId]);\n+ horizontalOffsetByFileIdRef.current.forEach((offset, fileId) => {\n+ if (!knownFileIds.has(fileId)) {\n+ horizontalOffsetByFileIdRef.current.delete(fileId);\n+ return;\n+ }\n+\n+ const contentWidth = reviewContentWidthByFileId.get(fileId) ?? viewportWidth;\n+ const gutterWidth = reviewGutterWidthByFileId.get(fileId) ?? 0;\n+ offset.value = Math.min(\n+ offset.value,\n+ Math.max(0, contentWidth - (viewportWidth - gutterWidth)),\n+ );\n+ });\n+ }, [parsedDiff, reviewContentWidthByFileId, reviewGutterWidthByFileId, viewportWidth]);\n const highlightableFiles = useMemo(() => {\n if (parsedDiff.kind !== "files") {\n return [] as ReadonlyArray<ReviewRenderableFile>;\n@@ -587,59 +854,13 @@ export function ReviewSheet() {\n );\n });\n }, [expandedFileIds, parsedDiff, revealedLargeFileIds]);\n- const highlightableFileIds = useMemo(\n- () => new Set(highlightableFiles.map((file) => file.id)),\n+ const highlightableFilesKey = useMemo(\n+ () => highlightableFiles.map((file) => `${file.id}:${file.cacheKey}`).join("\\n"),\n [highlightableFiles],\n );\n- const priorityHighlightFileIds = useMemo(() => {\n- if (parsedDiff.kind !== "files" || highlightableFiles.length === 0) {\n- return [] as ReadonlyArray<string>;\n- }\n-\n- const fileIdsInPriorityOrder =\n- visibleFileIds.length > 0\n- ? visibleFileIds.filter((fileId) => highlightableFileIds.has(fileId))\n- : parsedDiff.files\n- .slice(0, REVIEW_INITIAL_HIGHLIGHT_FILE_COUNT)\n- .map((file) => file.id)\n- .filter((fileId) => highlightableFileIds.has(fileId));\n-\n- if (fileIdsInPriorityOrder.length === 0) {\n- return [] as ReadonlyArray<string>;\n- }\n-\n- const firstVisibleIndex = parsedDiff.files.findIndex(\n- (file) => file.id === fileIdsInPriorityOrder[0],\n- );\n- const lastVisibleIndex = parsedDiff.files.findIndex(\n- (file) => file.id === fileIdsInPriorityOrder[fileIdsInPriorityOrder.length - 1],\n- );\n-\n- if (firstVisibleIndex < 0 || lastVisibleIndex < 0) {\n- return fileIdsInPriorityOrder;\n- }\n-\n- const startIndex = Math.max(0, firstVisibleIndex - REVIEW_HIGHLIGHT_BACKTRACK_COUNT);\n- const endIndex = Math.min(\n- parsedDiff.files.length - 1,\n- lastVisibleIndex + REVIEW_HIGHLIGHT_LOOKAHEAD_COUNT,\n- );\n-\n- const queuedIds: string[] = [];\n- for (let index = startIndex; index <= endIndex; index += 1) {\n- const fileId = parsedDiff.files[index]?.id;\n- if (fileId && highlightableFileIds.has(fileId)) {\n- queuedIds.push(fileId);\n- }\n- }\n-\n- return queuedIds;\n- }, [highlightableFileIds, highlightableFiles.length, parsedDiff, visibleFileIds]);\n- const viewportWidth = Math.max(width, 280);\n- const reviewListContentWidth = useMemo(\n- () => computeReviewListContentWidth(reviewListItems, viewportWidth),\n- [reviewListItems, viewportWidth],\n- );\n+ useEffect(() => {\n+ highlightableFilesRef.current = highlightableFiles;\n+ }, [highlightableFiles]);\n const loadGitDiffs = useCallback(async () => {\n if (!cwd) {\n return;\n@@ -714,100 +935,6 @@ export function ReviewSheet() {\n void loadGitDiffs();\n }, [loadGitDiffs]);\n \n- useEffect(() => {\n- selectedThemeRef.current = selectedTheme;\n- }, [selectedTheme]);\n-\n- useEffect(() => {\n- highlightableFilesByIdRef.current = new Map(highlightableFiles.map((file) => [file.id, file]));\n- }, [highlightableFiles]);\n-\n- const startHighlightQueueRunner = useCallback(function startHighlightQueueRunner() {\n- if (highlightQueueActiveRef.current) {\n- return;\n- }\n-\n- const generation = highlightQueueGenerationRef.current;\n- highlightQueueActiveRef.current = true;\n-\n- void (async () => {\n- try {\n- while (generation === highlightQueueGenerationRef.current) {\n- const nextFileId = highlightQueueRef.current.shift();\n- if (!nextFileId) {\n- break;\n- }\n-\n- const file = highlightableFilesByIdRef.current.get(nextFileId);\n- if (!file) {\n- continue;\n- }\n-\n- const theme = selectedThemeRef.current;\n- const cached = getCachedHighlightedReviewFile(file, theme);\n- if (cached) {\n- logReviewDiffDiagnostic("using cached highlighted file", {\n- fileId: file.id,\n- filePath: file.path,\n- theme,\n- });\n- setHighlightedFilesById((current) =>\n- current[file.id] === cached ? current : { ...current, [file.id]: cached },\n- );\n- continue;\n- }\n-\n- logReviewDiffDiagnostic("requesting highlighted file", {\n- fileId: file.id,\n- filePath: file.path,\n- theme,\n- });\n-\n- try {\n- await new Promise<void>((resolve) => {\n- InteractionManager.runAfterInteractions(() => resolve());\n- });\n- const result = await highlightReviewFile(file, theme);\n- if (generation !== highlightQueueGenerationRef.current) {\n- logReviewDiffDiagnostic("discarding highlighted file after cancellation", {\n- fileId: file.id,\n- filePath: file.path,\n- });\n- return;\n- }\n-\n- logReviewDiffDiagnostic("received highlighted file", {\n- fileId: file.id,\n- filePath: file.path,\n- additionLines: result.additionLines.length,\n- deletionLines: result.deletionLines.length,\n- });\n- setHighlightedFilesById((current) => {\n- if (current[file.id] === result) {\n- return current;\n- }\n- return { ...current, [file.id]: result };\n- });\n- } catch (error) {\n- logReviewDiffDiagnostic("highlight request failed", {\n- fileId: file.id,\n- filePath: file.path,\n- error: error instanceof Error ? error.message : String(error),\n- });\n- }\n- }\n- } finally {\n- highlightQueueActiveRef.current = false;\n- if (\n- generation === highlightQueueGenerationRef.current &&\n- highlightQueueRef.current.length > 0\n- ) {\n- startHighlightQueueRunner();\n- }\n- }\n- })();\n- }, []);\n-\n useEffect(() => {\n if (reviewSections.length === 0) {\n return;\n@@ -854,15 +981,15 @@ export function ReviewSheet() {\n }\n \n updateReviewExpandedFileIds(reviewCache.threadKey, selectedSection.id, (existing) => {\n- if (existing !== undefined) {\n- const validIds = existing.filter((id) => parsedDiff.files.some((file) => file.id === id));\n- if (validIds.length === existing.length) {\n- return existing;\n- }\n- return validIds;\n+ const validIds = getValidReviewExpandedFileIds(parsedDiff.files, existing);\n+ if (\n+ existing !== undefined &&\n+ validIds.length === existing.length &&\n+ validIds.every((id, index) => id === existing[index])\n+ ) {\n+ return existing;\n }\n-\n- return getDefaultExpandedFileIds(parsedDiff.files);\n+ return validIds;\n });\n }, [parsedDiff, reviewCache.threadKey, selectedSection?.id]);\n \n@@ -887,11 +1014,7 @@ export function ReviewSheet() {\n \n useEffect(() => {\n setHighlightedFilesById({});\n- setVisibleFileIds([]);\n- highlightQueueGenerationRef.current += 1;\n- highlightQueueRef.current = [];\n- highlightRequestedFileIdsRef.current = new Set();\n- highlightQueueActiveRef.current = false;\n+ highlightRunIdRef.current += 1;\n clearReviewHighlightFileCache();\n loggedMissingReviewTokenKeys.clear();\n logReviewDiffDiagnostic("reset highlighted files", {\n@@ -905,15 +1028,23 @@ export function ReviewSheet() {\n return;\n }\n \n+ markReviewEvent("parsed-diff-ready", {\n+ sectionId: selectedSection?.id ?? null,\n+ fileCount: parsedDiff.fileCount,\n+ additions: parsedDiff.additions,\n+ deletions: parsedDiff.deletions,\n+ renderedItems: reviewListItems.length,\n+ });\n logReviewDiffDiagnostic("parsed diff files", {\n selectedSectionId: selectedSection?.id ?? null,\n fileCount: parsedDiff.fileCount,\n renderableFileCount: parsedDiff.files.length,\n });\n- }, [parsedDiff, selectedSection?.id]);\n+ }, [parsedDiff, reviewListItems.length, selectedSection?.id]);\n \n useEffect(() => {\n- if (priorityHighlightFileIds.length === 0) {\n+ const files = highlightableFilesRef.current;\n+ if (files.length === 0) {\n logReviewDiffDiagnostic("no highlightable files", {\n selectedSectionId: selectedSection?.id ?? null,\n parsedDiffKind: parsedDiff.kind,\n@@ -922,33 +1053,98 @@ export function ReviewSheet() {\n return;\n }\n \n- const queuedFileIds: string[] = [];\n- priorityHighlightFileIds.forEach((fileId) => {\n- if (highlightRequestedFileIdsRef.current.has(fileId)) {\n- return;\n- }\n-\n- const file = highlightableFilesByIdRef.current.get(fileId);\n- if (!file) {\n- return;\n- }\n-\n- highlightRequestedFileIdsRef.current.add(fileId);\n- highlightQueueRef.current.push(fileId);\n- queuedFileIds.push(fileId);\n- });\n-\n- if (queuedFileIds.length === 0) {\n+ if (reviewHighlighter.status !== "ready") {\n+ logReviewDiffDiagnostic("waiting for highlighter provider", {\n+ selectedSectionId: selectedSection?.id ?? null,\n+ status: reviewHighlighter.status,\n+ error: reviewHighlighter.error,\n+ });\n return;\n }\n \n- logReviewDiffDiagnostic("scheduling file highlights", {\n+ const runId = highlightRunIdRef.current;\n+ let cancelled = false;\n+\n+ logReviewDiffDiagnostic("streaming file highlights", {\n selectedSectionId: selectedSection?.id ?? null,\n- fileCount: queuedFileIds.length,\n- fileIds: queuedFileIds,\n+ fileCount: files.length,\n });\n- startHighlightQueueRunner();\n- }, [parsedDiff.kind, priorityHighlightFileIds, selectedSection?.id, startHighlightQueueRunner]);\n+\n+ void (async () => {\n+ for (const file of files) {\n+ if (cancelled || runId !== highlightRunIdRef.current) {\n+ return;\n+ }\n+\n+ const cached = getCachedHighlightedReviewFile(file, selectedTheme);\n+ if (cached) {\n+ setHighlightedFilesById((current) =>\n+ current[file.id] === cached ? current : { ...current, [file.id]: cached },\n+ );\n+ continue;\n+ }\n+\n+ logReviewDiffDiagnostic("requesting highlighted file", {\n+ fileId: file.id,\n+ filePath: file.path,\n+ theme: selectedTheme,\n+ });\n+\n+ try {\n+ const highlightStartedAt = performance.now();\n+ const result = await streamHighlightReviewFile(file, selectedTheme, (progress) => {\n+ if (cancelled || runId !== highlightRunIdRef.current) {\n+ return;\n+ }\n+\n+ if (!progress.complete) {\n+ return;\n+ }\n+\n+ logReviewDiffDiagnostic("received streamed highlighted file", {\n+ fileId: file.id,\n+ filePath: file.path,\n+ highlightedLineCount: progress.highlightedLineCount,\n+ durationMs: Math.round(performance.now() - highlightStartedAt),\n+ });\n+ });\n+\n+ if (cancelled || runId !== highlightRunIdRef.current) {\n+ return;\n+ }\n+\n+ logReviewDiffDiagnostic("received highlighted file", {\n+ fileId: file.id,\n+ filePath: file.path,\n+ additionLines: result.additionLines.length,\n+ deletionLines: result.deletionLines.length,\n+ });\n+ setHighlightedFilesById((current) =>\n+ current[file.id] === result ? current : { ...current, [file.id]: result },\n+ );\n+ } catch (error) {\n+ logReviewDiffDiagnostic("highlight request failed", {\n+ fileId: file.id,\n+ filePath: file.path,\n+ error: error instanceof Error ? error.message : String(error),\n+ });\n+ }\n+\n+ await waitForReviewDelay(0);\n+ }\n+ })();\n+\n+ return () => {\n+ cancelled = true;\n+ };\n+ }, [\n+ highlightableFilesKey,\n+ parsedDiff.kind,\n+ reviewHighlighter.error,\n+ reviewHighlighter.status,\n+ selectedSection?.id,\n+ selectedTheme,\n+ ]);\n \n const refreshSelectedSection = useCallback(async () => {\n if (!selectedSection) {\n@@ -968,20 +1164,68 @@ export function ReviewSheet() {\n \n const handleToggleExpandedFile = useCallback(\n (fileId: string) => {\n- if (!reviewCache.threadKey || !selectedSection?.id || parsedDiff.kind !== "files") {\n+ if (!selectedSection?.id || parsedDiff.kind !== "files") {\n return;\n }\n \n- updateReviewExpandedFileIds(reviewCache.threadKey, selectedSection.id, (existing) => {\n- const currentIds = existing ?? getDefaultExpandedFileIds(parsedDiff.files);\n- return currentIds.includes(fileId)\n+ const sectionId = selectedSection.id;\n+\n+ setLocalExpandedFileIdsBySection((current) => {\n+ const currentIds = getValidReviewExpandedFileIds(parsedDiff.files, current[sectionId]);\n+ const nextIds = currentIds.includes(fileId)\n ? currentIds.filter((id) => id !== fileId)\n : [...currentIds, fileId];\n+\n+ return {\n+ ...current,\n+ [sectionId]: nextIds,\n+ };\n });\n+\n+ if (reviewCache.threadKey) {\n+ updateReviewExpandedFileIds(reviewCache.threadKey, sectionId, (existing) => {\n+ const currentIds = getValidReviewExpandedFileIds(parsedDiff.files, existing);\n+ return currentIds.includes(fileId)\n+ ? currentIds.filter((id) => id !== fileId)\n+ : [...currentIds, fileId];\n+ });\n+ }\n },\n [parsedDiff, reviewCache.threadKey, selectedSection?.id],\n );\n \n+ const handleToggleViewedFile = useCallback(\n+ (fileId: string) => {\n+ if (!selectedSection?.id) {\n+ return;\n+ }\n+\n+ const sectionId = selectedSection.id;\n+\n+ setLocalViewedFileIdsBySection((current) => {\n+ const currentIds = current[sectionId] ?? [];\n+ const nextIds = currentIds.includes(fileId)\n+ ? currentIds.filter((id) => id !== fileId)\n+ : [...currentIds, fileId];\n+\n+ return {\n+ ...current,\n+ [sectionId]: nextIds,\n+ };\n+ });\n+\n+ if (reviewCache.threadKey) {\n+ updateReviewViewedFileIds(reviewCache.threadKey, sectionId, (existing) => {\n+ const currentIds = existing ?? [];\n+ return currentIds.includes(fileId)\n+ ? currentIds.filter((id) => id !== fileId)\n+ : [...currentIds, fileId];\n+ });\n+ }\n+ },\n+ [reviewCache.threadKey, selectedSection?.id],\n+ );\n+\n const handleRevealLargeDiff = useCallback(\n (fileId: string) => {\n if (!reviewCache.threadKey || !selectedSection?.id) {\n@@ -1080,35 +1324,6 @@ export function ReviewSheet() {\n \n return <>{children}</>;\n }, [error, parsedDiffNotice]);\n- const stickyHeaderIndices = useMemo(() => {\n- const itemOffset = listHeader ? 1 : 0;\n-\n- return reviewListItems.flatMap((item, index) =>\n- item.kind === "file-header" ? [index + itemOffset] : [],\n- );\n- }, [listHeader, reviewListItems]);\n-\n- const viewabilityConfigRef = useRef({\n- itemVisiblePercentThreshold: 10,\n- });\n- const onViewableItemsChangedRef = useRef(\n- ({\n- viewableItems,\n- }: {\n- readonly viewableItems: Array<ViewToken<ReviewListItem>>;\n- readonly changed: Array<ViewToken<ReviewListItem>>;\n- }) => {\n- const nextVisibleFileIds = Array.from(\n- new Set(\n- viewableItems\n- .filter((token) => token.isViewable && token.item !== undefined)\n- .map((token) => token.item.fileId),\n- ),\n- );\n-\n- setVisibleFileIds(nextVisibleFileIds);\n- },\n- );\n \n const renderReviewListItem = useCallback(\n ({ item }: ListRenderItemInfo<ReviewListItem>) => {\n@@ -1116,112 +1331,142 @@ export function ReviewSheet() {\n return null;\n }\n \n+ let renderedItem: ReactElement | null = null;\n switch (item.kind) {\n case "file-header":\n- return (\n+ renderedItem = (\n <ReviewFileCard\n file={item.file}\n fileId={item.fileId}\n expanded={item.expanded}\n- viewportWidth={reviewListContentWidth}\n+ viewed={viewedFileIdSet.has(item.fileId)}\n+ viewportWidth={viewportWidth}\n onToggleFile={handleToggleExpandedFile}\n+ onToggleViewed={handleToggleViewedFile}\n />\n );\n+ break;\n case "file-suppressed":\n- return (\n+ renderedItem = (\n <ReviewFileSuppressedBody\n message={item.message}\n actionLabel={item.actionLabel}\n fileId={item.fileId}\n- viewportWidth={reviewListContentWidth}\n+ viewportWidth={viewportWidth}\n onLoadDiffFile={handleRevealLargeDiff}\n />\n );\n- case "hunk":\n- return (\n- <ReviewHunkRow\n- header={item.row.header}\n- context={item.row.context}\n- viewportWidth={reviewListContentWidth}\n- />\n+ break;\n+ case "hunk": {\n+ const contentWidth = reviewContentWidthByFileId.get(item.fileId) ?? viewportWidth;\n+ const gutterWidth = reviewGutterWidthByFileId.get(item.fileId) ?? 0;\n+\n+ renderedItem = (\n+ <ReviewCodePanRow\n+ key={item.id}\n+ contentWidth={contentWidth}\n+ gutterWidth={gutterWidth}\n+ horizontalOffset={getReviewFileHorizontalOffset(item.fileId)}\n+ leftGutter={<ReviewHunkGutter gutterWidth={gutterWidth} />}\n+ viewportWidth={viewportWidth}\n+ >\n+ <ReviewHunkRow\n+ header={item.row.header}\n+ context={item.row.context}\n+ viewportWidth={contentWidth}\n+ />\n+ </ReviewCodePanRow>\n );\n+ break;\n+ }\n case "line": {\n- const file = reviewFileById.get(item.fileId);\n- if (!file) {\n- return null;\n- }\n-\n- const fileLineRows = reviewLineRowsByFileId.get(file.id) ?? [];\n- const lineIndex = reviewLineIndexByRowId.get(item.row.id);\n- if (lineIndex === undefined) {\n- return null;\n- }\n-\n+ const fileLineRows = reviewLineRowsByFileId.get(item.file.id) ?? [];\n const pendingSelectionForFile =\n pendingCommentSelection &&\n pendingCommentSelection.sectionTitle === selectedSection.title &&\n- pendingCommentSelection.filePath === file.path\n+ pendingCommentSelection.filePath === item.file.path\n ? pendingCommentSelection\n : null;\n const selectedTargetForFile =\n activeCommentTarget &&\n activeCommentTarget.sectionTitle === selectedSection.title &&\n- activeCommentTarget.filePath === file.path\n+ activeCommentTarget.filePath === item.file.path\n ? activeCommentTarget\n : null;\n const highlightedFile =\n- highlightedFilesById[file.id] ??\n- getCachedHighlightedReviewFile(file, selectedTheme) ??\n+ deferredHighlightedFilesById[item.file.id] ??\n+ getCachedHighlightedReviewFile(item.file, selectedTheme) ??\n null;\n+ const contentWidth = reviewContentWidthByFileId.get(item.fileId) ?? viewportWidth;\n+ const gutterWidth = reviewGutterWidthByFileId.get(item.fileId) ?? 0;\n \n if (highlightedFile === null) {\n- const missingTokenKey = `${selectedSection.id}:${file.id}`;\n+ const missingTokenKey = `${selectedSection.id}:${item.file.id}`;\n if (!loggedMissingReviewTokenKeys.has(missingTokenKey)) {\n loggedMissingReviewTokenKeys.add(missingTokenKey);\n logReviewDiffDiagnostic("rendering file without tokens", {\n sectionId: selectedSection.id,\n- fileId: file.id,\n- filePath: file.path,\n- highlightedFileKnownInState: highlightedFilesById[file.id] !== undefined,\n+ fileId: item.file.id,\n+ filePath: item.file.path,\n+ highlightedFileKnownInState:\n+ deferredHighlightedFilesById[item.file.id] !== undefined,\n });\n }\n }\n \n const selectionState =\n- pendingSelectionForFile?.anchorIndex === lineIndex\n+ pendingSelectionForFile?.anchorIndex === item.lineIndex\n ? ("anchor" as const)\n : selectedTargetForFile &&\n- lineIndex >= selectedTargetForFile.startIndex &&\n- lineIndex <= selectedTargetForFile.endIndex\n+ item.lineIndex >= selectedTargetForFile.startIndex &&\n+ item.lineIndex <= selectedTargetForFile.endIndex\n ? ("selected" as const)\n : null;\n \n- return (\n- <ReviewLineRow\n- line={item.row}\n- tokens={getHighlightedTokensForLine(item.row, highlightedFile)}\n- viewportWidth={reviewListContentWidth}\n- selectionState={selectionState}\n- onComment={() =>\n- handlePressLine({\n- sectionTitle: selectedSection.title,\n- filePath: file.path,\n- lines: fileLineRows,\n- lineIndex,\n- })\n- }\n- onStartRangeSelection={() =>\n- handleStartRangeSelection({\n- sectionTitle: selectedSection.title,\n- filePath: file.path,\n- lines: fileLineRows,\n- lineIndex,\n- })\n+ renderedItem = (\n+ <ReviewCodePanRow\n+ key={item.id}\n+ contentWidth={contentWidth}\n+ gutterWidth={gutterWidth}\n+ horizontalOffset={getReviewFileHorizontalOffset(item.fileId)}\n+ leftGutter={\n+ <ReviewLineGutter\n+ change={item.row.change}\n+ gutterWidth={gutterWidth}\n+ lineNumber={getReviewUnifiedLineNumber(item.row)}\n+ />\n }\n- />\n+ viewportWidth={viewportWidth}\n+ >\n+ <ReviewLineRow\n+ line={item.row}\n+ tokens={getHighlightedTokensForLine(item.row, highlightedFile)}\n+ viewportWidth={contentWidth}\n+ selectionState={selectionState}\n+ onComment={() =>\n+ handlePressLine({\n+ sectionTitle: selectedSection.title,\n+ filePath: item.file.path,\n+ lines: fileLineRows,\n+ lineIndex: item.lineIndex,\n+ })\n+ }\n+ onStartRangeSelection={() =>\n+ handleStartRangeSelection({\n+ sectionTitle: selectedSection.title,\n+ filePath: item.file.path,\n+ lines: fileLineRows,\n+ lineIndex: item.lineIndex,\n+ })\n+ }\n+ />\n+ </ReviewCodePanRow>\n );\n+ break;\n }\n }\n+\n+ return renderedItem;\n },\n [\n activeCommentTarget,\n@@ -1229,14 +1474,17 @@ export function ReviewSheet() {\n handleRevealLargeDiff,\n handleStartRangeSelection,\n handleToggleExpandedFile,\n- highlightedFilesById,\n+ handleToggleViewedFile,\n+ getReviewFileHorizontalOffset,\n+ deferredHighlightedFilesById,\n pendingCommentSelection,\n- reviewFileById,\n- reviewLineIndexByRowId,\n+ reviewContentWidthByFileId,\n+ reviewGutterWidthByFileId,\n reviewLineRowsByFileId,\n- reviewListContentWidth,\n selectedSection,\n selectedTheme,\n+ viewedFileIdSet,\n+ viewportWidth,\n ],\n );\n \n@@ -1374,27 +1622,20 @@ export function ReviewSheet() {\n <View className="flex-1 bg-sheet">\n {selectedSection && parsedDiff.kind === "files" ? (\n <FlatList\n- style={{ flex: 1 }}\n+ style={{ flex: 1, width: viewportWidth }}\n contentInsetAdjustmentBehavior="never"\n- contentInset={{ top: topContentInset }}\n- contentOffset={{ x: 0, y: -topContentInset }}\n- scrollIndicatorInsets={{ top: topContentInset }}\n data={reviewListItems}\n renderItem={renderReviewListItem}\n keyExtractor={(item) => item.id}\n+ initialNumToRender={20}\n+ maxToRenderPerBatch={20}\n+ updateCellsBatchingPeriod={16}\n+ windowSize={5}\n+ removeClippedSubviews={false}\n keyboardShouldPersistTaps="handled"\n ListHeaderComponent={listHeader}\n- stickyHeaderIndices={stickyHeaderIndices}\n- removeClippedSubviews={false}\n- initialNumToRender={24}\n- maxToRenderPerBatch={16}\n- updateCellsBatchingPeriod={16}\n- windowSize={10}\n- scrollEventThrottle={16}\n- onViewableItemsChanged={onViewableItemsChangedRef.current}\n- viewabilityConfig={viewabilityConfigRef.current}\n contentContainerStyle={{\n- paddingTop: REVIEW_HEADER_SPACING,\n+ paddingTop: topContentInset + REVIEW_HEADER_SPACING,\n paddingBottom: Math.max(insets.bottom, 18) + 18,\n }}\n />\ndiff --git a/apps/mobile/src/features/review/reviewDiffRendering.tsx b/apps/mobile/src/features/review/reviewDiffRendering.tsx\nindex d61924a62..3f2ae0160 100644\n--- a/apps/mobile/src/features/review/reviewDiffRendering.tsx\n+++ b/apps/mobile/src/features/review/reviewDiffRendering.tsx\n@@ -11,6 +11,9 @@ export const REVIEW_MONO_FONT_FAMILY = Platform.select({\n default: "monospace",\n });\n \n+export const REVIEW_DIFF_LINE_HEIGHT = 26;\n+const REVIEW_DELETE_STRIPE_COUNT = REVIEW_DIFF_LINE_HEIGHT / 2;\n+\n export function renderVisibleWhitespace(value: string): string {\n const expandedTabs = value.replace(/\\t/g, " ");\n return expandedTabs.replace(/^( +)/, (leading) => leading.replaceAll(" ", "\\u00A0"));\n@@ -37,10 +40,13 @@ function diffHighlightColor(change: ReviewRenderableLineRow["change"]): string |\n export function ReviewChangeBar(props: { readonly change: ReviewRenderableLineRow["change"] }) {\n if (props.change === "delete") {\n return (\n- <View className="w-[5px] self-stretch overflow-hidden">\n- <View className="flex-1 justify-between">\n- {Array.from({ length: 6 }, (_, index) => (\n- <View key={index} className="h-[2px] w-[5px] bg-rose-400" />\n+ <View className="w-[5px] overflow-hidden" style={{ height: REVIEW_DIFF_LINE_HEIGHT }}>\n+ <View>\n+ {Array.from({ length: REVIEW_DELETE_STRIPE_COUNT }, (_, index) => (\n+ <View key={index}>\n+ <View className="w-[5px] bg-rose-400" style={{ height: 1 }} />\n+ <View style={{ height: 1 }} />\n+ </View>\n ))}\n </View>\n </View>\n@@ -48,7 +54,7 @@ export function ReviewChangeBar(props: { readonly change: ReviewRenderableLineRo\n }\n \n return (\n- <View className="w-[5px] self-stretch overflow-hidden">\n+ <View className="w-[5px] overflow-hidden" style={{ height: REVIEW_DIFF_LINE_HEIGHT }}>\n <View className={cn("h-full w-[5px] flex-1", changeBarTone(props.change))} />\n </View>\n );\n@@ -63,6 +69,7 @@ export function DiffTokenText(props: {\n if (!props.tokens || props.tokens.length === 0) {\n return (\n <NativeText\n+ numberOfLines={1}\n selectable\n className={cn("text-[13px] leading-[17px] font-medium text-foreground", props.className)}\n style={{ fontFamily: REVIEW_MONO_FONT_FAMILY }}\n@@ -74,6 +81,7 @@ export function DiffTokenText(props: {\n \n return (\n <NativeText\n+ numberOfLines={1}\n selectable\n className={cn("text-[13px] leading-[17px] font-medium text-foreground", props.className)}\n style={{ fontFamily: REVIEW_MONO_FONT_FAMILY }}\ndiff --git a/apps/mobile/src/features/review/reviewHighlighterEngine.test.ts b/apps/mobile/src/features/review/reviewHighlighterEngine.test.ts\nindex d63a7a67c..5449fc6bf 100644\n--- a/apps/mobile/src/features/review/reviewHighlighterEngine.test.ts\n+++ b/apps/mobile/src/features/review/reviewHighlighterEngine.test.ts\n@@ -6,9 +6,9 @@ import {\n } from "./reviewHighlighterEngine";\n \n describe("resolveReviewHighlighterEnginePreference", () => {\n- it("defaults invalid values to javascript", () => {\n- expect(resolveReviewHighlighterEnginePreference(undefined)).toBe("javascript");\n- expect(resolveReviewHighlighterEnginePreference("bogus")).toBe("javascript");\n+ it("defaults invalid values to native", () => {\n+ expect(resolveReviewHighlighterEnginePreference(undefined)).toBe("native");\n+ expect(resolveReviewHighlighterEnginePreference("bogus")).toBe("native");\n });\n \n it("accepts supported values", () => {\ndiff --git a/apps/mobile/src/features/review/reviewHighlighterEngine.ts b/apps/mobile/src/features/review/reviewHighlighterEngine.ts\nindex 5ef9f055a..428768537 100644\n--- a/apps/mobile/src/features/review/reviewHighlighterEngine.ts\n+++ b/apps/mobile/src/features/review/reviewHighlighterEngine.ts\n@@ -11,7 +11,7 @@ export function resolveReviewHighlighterEnginePreference(\n case "native":\n return "native";\n default:\n- return "javascript";\n+ return "native";\n }\n }\n \ndiff --git a/apps/mobile/src/features/review/reviewModel.test.ts b/apps/mobile/src/features/review/reviewModel.test.ts\nindex a24a99ceb..69a6e7261 100644\n--- a/apps/mobile/src/features/review/reviewModel.test.ts\n+++ b/apps/mobile/src/features/review/reviewModel.test.ts\n@@ -238,7 +238,7 @@ describe("buildReviewParsedDiff", () => {\n });\n });\n \n- it("flattens expanded files into virtualizable review items", () => {\n+ it("flattens expanded file rows into virtualized review items", () => {\n const file = makeRenderableFile({\n path: "apps/mobile/src/a.ts",\n rows: [\n@@ -270,8 +270,19 @@ describe("buildReviewParsedDiff", () => {\n \n expect(items).toEqual([\n expect.objectContaining({ kind: "file-header", fileId: file.id, expanded: true }),\n- expect.objectContaining({ kind: "hunk", fileId: file.id, row: file.rows[0] }),\n- expect.objectContaining({ kind: "line", fileId: file.id, row: file.rows[1] }),\n+ expect.objectContaining({\n+ kind: "hunk",\n+ fileId: file.id,\n+ file,\n+ row: file.rows[0],\n+ }),\n+ expect.objectContaining({\n+ kind: "line",\n+ fileId: file.id,\n+ file,\n+ row: file.rows[1],\n+ lineIndex: 0,\n+ }),\n ]);\n });\n \ndiff --git a/apps/mobile/src/features/review/reviewModel.ts b/apps/mobile/src/features/review/reviewModel.ts\nindex 27e6d7ae4..1cfbf358c 100644\n--- a/apps/mobile/src/features/review/reviewModel.ts\n+++ b/apps/mobile/src/features/review/reviewModel.ts\n@@ -72,6 +72,7 @@ export interface ReviewHunkListItem {\n readonly kind: "hunk";\n readonly id: string;\n readonly fileId: string;\n+ readonly file: ReviewRenderableFile;\n readonly row: ReviewRenderableHunkRow;\n }\n \n@@ -79,7 +80,9 @@ export interface ReviewLineListItem {\n readonly kind: "line";\n readonly id: string;\n readonly fileId: string;\n+ readonly file: ReviewRenderableFile;\n readonly row: ReviewRenderableLineRow;\n+ readonly lineIndex: number;\n }\n \n export type ReviewListItem =\n@@ -308,7 +311,7 @@ export function getReviewFilePreviewState(file: ReviewRenderableFile): ReviewFil\n }\n \n // The flattened review list item model is inspired by pierre/diffs\' iterator-first\n-// virtualization architecture, adapted here for React Native and LegendList.\n+// virtualization architecture, adapted here for React Native virtualization.\n // Original project: https://github.com/pingdotgg/pierre/tree/main/packages/diffs\n // Reference files:\n // - src/utils/iterateOverDiff.ts\n@@ -350,12 +353,14 @@ export function buildReviewListItems(input: {\n }\n }\n \n- file.rows.forEach((row) => {\n+ let lineIndex = 0;\n+ file.rows.forEach((row, rowIndex) => {\n if (row.kind === "hunk") {\n items.push({\n kind: "hunk",\n- id: row.id,\n+ id: `${file.id}:row:${rowIndex}:${row.id}`,\n fileId: file.id,\n+ file,\n row,\n });\n return;\n@@ -363,10 +368,13 @@ export function buildReviewListItems(input: {\n \n items.push({\n kind: "line",\n- id: row.id,\n+ id: `${file.id}:row:${rowIndex}:${row.id}`,\n fileId: file.id,\n+ file,\n row,\n+ lineIndex,\n });\n+ lineIndex += 1;\n });\n });\n \ndiff --git a/apps/mobile/src/features/review/reviewState.ts b/apps/mobile/src/features/review/reviewState.ts\nindex 06134db7d..c116f93fe 100644\n--- a/apps/mobile/src/features/review/reviewState.ts\n+++ b/apps/mobile/src/features/review/reviewState.ts\n@@ -64,6 +64,13 @@ const reviewRevealedLargeFileIdsByThreadKeyAtom = Atom.family((threadKey: string\n ),\n );\n \n+const reviewViewedFileIdsByThreadKeyAtom = Atom.family((threadKey: string) =>\n+ Atom.make(EMPTY_REVIEW_SECTION_FILE_IDS).pipe(\n+ Atom.keepAlive,\n+ Atom.withLabel(`mobile:review:viewed-file-ids:${threadKey}`),\n+ ),\n+);\n+\n const reviewParsedDiffBySectionCacheKeyAtom = Atom.family((cacheKey: string) =>\n Atom.make<{ readonly diff: string | null; readonly parsed: ReviewParsedDiff } | null>(null).pipe(\n Atom.keepAlive,\n@@ -110,6 +117,9 @@ export function useReviewCacheForThread(input: {\n ? reviewRevealedLargeFileIdsByThreadKeyAtom(threadKey)\n : EMPTY_REVIEW_SECTION_FILE_IDS_ATOM,\n );\n+ const viewedFileIdsBySection = useAtomValue(\n+ threadKey ? reviewViewedFileIdsByThreadKeyAtom(threadKey) : EMPTY_REVIEW_SECTION_FILE_IDS_ATOM,\n+ );\n \n return {\n threadKey,\n@@ -118,6 +128,7 @@ export function useReviewCacheForThread(input: {\n selectedSectionId,\n expandedFileIdsBySection,\n revealedLargeFileIdsBySection,\n+ viewedFileIdsBySection,\n };\n }\n \n@@ -169,6 +180,20 @@ export function updateReviewRevealedLargeFileIds(\n });\n }\n \n+export function updateReviewViewedFileIds(\n+ threadKey: string,\n+ sectionId: string,\n+ update: (current: ReadonlyArray<string> | undefined) => ReadonlyArray<string> | undefined,\n+): void {\n+ const atom = reviewViewedFileIdsByThreadKeyAtom(threadKey);\n+ const current = appAtomRegistry.get(atom);\n+ const nextValue = update(current[sectionId]);\n+ appAtomRegistry.set(atom, {\n+ ...current,\n+ [sectionId]: nextValue,\n+ });\n+}\n+\n export function getCachedReviewParsedDiff(input: {\n readonly threadKey: string | null;\n readonly sectionId: string | null;\ndiff --git a/apps/mobile/src/features/review/shikiReviewHighlighter.test.ts b/apps/mobile/src/features/review/shikiReviewHighlighter.test.ts\nindex 05b5c9213..402d00668 100644\n--- a/apps/mobile/src/features/review/shikiReviewHighlighter.test.ts\n+++ b/apps/mobile/src/features/review/shikiReviewHighlighter.test.ts\n@@ -24,7 +24,7 @@ function makeRenderableFile(\n describe("highlightReviewFile", () => {\n it("preserves one highlighted token row per diff line even without trailing newlines", async () => {\n const file = makeRenderableFile({\n- path: "apps/mobile/src/example.test.ts",\n+ path: "apps/mobile/src/example.txt",\n additionLines: [\n \'const items = ["a"];\',\n \'expect(items).toEqual(["a"]);\',\n@@ -36,15 +36,23 @@ describe("highlightReviewFile", () => {\n const highlighted = await highlightReviewFile(file, "light");\n \n expect(highlighted.additionLines).toHaveLength(file.additionLines.length);\n- expect(highlighted.additionLines[0]?.some((token) => token.content === "const")).toBe(true);\n- expect(highlighted.additionLines[1]?.some((token) => token.content === "expect")).toBe(true);\n- expect(highlighted.additionLines[2]?.some((token) => token.content === "const")).toBe(true);\n- expect(highlighted.additionLines[3]?.some((token) => token.content === "expect")).toBe(true);\n+ expect(highlighted.additionLines[0]?.map((token) => token.content).join("")).toBe(\n+ file.additionLines[0],\n+ );\n+ expect(highlighted.additionLines[1]?.map((token) => token.content).join("")).toBe(\n+ file.additionLines[1],\n+ );\n+ expect(highlighted.additionLines[2]?.map((token) => token.content).join("")).toBe(\n+ file.additionLines[2],\n+ );\n+ expect(highlighted.additionLines[3]?.map((token) => token.content).join("")).toBe(\n+ file.additionLines[3],\n+ );\n });\n \n it("adds word-alt diff emphasis for paired deletion and addition lines", async () => {\n const file = makeRenderableFile({\n- path: "apps/mobile/src/example-inline-diff.test.ts",\n+ path: "apps/mobile/src/example-inline-diff.txt",\n additionLines: ["const after = 2;"],\n deletionLines: ["const before = 1;"],\n rows: [\n@@ -82,7 +90,7 @@ describe("highlightReviewFile", () => {\n it("falls back to plain tokens for very long lines", async () => {\n const longLine = `const value = "${"a".repeat(1_100)}";`;\n const file = makeRenderableFile({\n- path: "apps/mobile/src/example-long-line.ts",\n+ path: "apps/mobile/src/example-long-line.txt",\n additionLines: [longLine],\n rows: [\n {\ndiff --git a/apps/mobile/src/features/review/shikiReviewHighlighter.ts b/apps/mobile/src/features/review/shikiReviewHighlighter.ts\nindex f7a5c4125..eb6bf6973 100644\n--- a/apps/mobile/src/features/review/shikiReviewHighlighter.ts\n+++ b/apps/mobile/src/features/review/shikiReviewHighlighter.ts\n@@ -1,5 +1,14 @@\n import { createHighlighterCore, type HighlighterCore } from "@shikijs/core";\n import { createJavaScriptRegexEngine } from "@shikijs/engine-javascript";\n+import bashLanguage from "@shikijs/langs/bash";\n+import javascriptLanguage from "@shikijs/langs/javascript";\n+import jsonLanguage from "@shikijs/langs/json";\n+import jsxLanguage from "@shikijs/langs/jsx";\n+import tsxLanguage from "@shikijs/langs/tsx";\n+import typescriptLanguage from "@shikijs/langs/typescript";\n+import yamlLanguage from "@shikijs/langs/yaml";\n+import githubDarkDefault from "@shikijs/themes/github-dark-default";\n+import githubLightDefault from "@shikijs/themes/github-light-default";\n import { getFiletypeFromFileName } from "@pierre/diffs/utils";\n \n import {\n@@ -11,6 +20,7 @@ import type { ReviewRenderableFile, ReviewRenderableLineRow } from "./reviewMode\n import { applyDiffRangesToTokens, computeWordAltDiffRanges } from "./reviewWordDiffs";\n \n export type ReviewDiffTheme = "light" | "dark";\n+export type { ReviewHighlighterEngine };\n \n export interface ReviewHighlightedToken {\n content: string;\n@@ -24,12 +34,19 @@ export interface ReviewHighlightedFile {\n readonly deletionLines: ReadonlyArray<ReadonlyArray<ReviewHighlightedToken>>;\n }\n \n+export interface ReviewHighlightFileProgress {\n+ readonly highlightedFile: ReviewHighlightedFile;\n+ readonly complete: boolean;\n+ readonly highlightedLineCount: number;\n+}\n+\n const SHIKI_THEME_NAME_BY_SCHEME = {\n light: "github-light-default",\n dark: "github-dark-default",\n } as const;\n const REVIEW_HIGHLIGHTER_ENGINE_ENV_VALUE =\n- process.env.EXPO_PUBLIC_REVIEW_HIGHLIGHTER_ENGINE ?? "javascript";\n+ process.env.EXPO_PUBLIC_REVIEW_HIGHLIGHTER_ENGINE ??\n+ (process.env.NODE_ENV === "test" ? "javascript" : "native");\n const REVIEW_HIGHLIGHTER_ENGINE_PREFERENCE = resolveReviewHighlighterEnginePreference(\n REVIEW_HIGHLIGHTER_ENGINE_ENV_VALUE,\n );\n@@ -38,12 +55,30 @@ const REVIEW_HIGHLIGHTER_DISABLE_RESULT_CACHE = resolveReviewHighlighterBooleanF\n false,\n );\n const REVIEW_HIGHLIGHT_RESULT_CACHE_LIMIT = 8;\n-const REVIEW_HIGHLIGHT_CHUNK_LINE_THRESHOLD = 40;\n-const REVIEW_HIGHLIGHT_CHUNK_SIZE = 20;\n+const REVIEW_HIGHLIGHT_CHUNK_LINE_THRESHOLD = 8;\n+const REVIEW_HIGHLIGHT_CHUNK_SIZE = 200;\n const REVIEW_TOKENIZE_MAX_LINE_LENGTH = 1_000;\n const highlightCache = new Map<string, Promise<ReviewHighlightedFile>>();\n const resolvedHighlightCache = new Map<string, ReviewHighlightedFile>();\n-const loadedLanguages = new Set<string>(["text"]);\n+const REVIEW_INITIAL_LANGUAGE_MODULES = [\n+ bashLanguage,\n+ javascriptLanguage,\n+ jsonLanguage,\n+ jsxLanguage,\n+ tsxLanguage,\n+ typescriptLanguage,\n+ yamlLanguage,\n+] satisfies Parameters<typeof createHighlighterCore>[0]["langs"];\n+const loadedLanguages = new Set<string>([\n+ "text",\n+ "bash",\n+ "javascript",\n+ "json",\n+ "jsx",\n+ "tsx",\n+ "typescript",\n+ "yaml",\n+]);\n const languageLoadingPromises = new Map<string, Promise<boolean>>();\n const languageImports: Partial<Record<string, () => Promise<unknown>>> = {\n javascript: () => import("@shikijs/langs/javascript"),\n@@ -215,21 +250,13 @@ function joinPatchLines(lines: ReadonlyArray<string>): string {\n \n function waitForNextFrame(): Promise<void> {\n return new Promise((resolve) => {\n- if (typeof requestAnimationFrame === "function") {\n- requestAnimationFrame(() => resolve());\n- return;\n- }\n-\n setTimeout(resolve, 0);\n });\n }\n \n async function getHighlighter(): Promise<HighlighterCore> {\n if (!highlighterPromise) {\n- const configuredHighlighterPromise = Promise.all([\n- import("@shikijs/themes/github-light-default"),\n- import("@shikijs/themes/github-dark-default"),\n- ]).then(async ([lightThemeModule, darkThemeModule]) => {\n+ const configuredHighlighterPromise = (async () => {\n let nativeEngineAvailable = false;\n \n logReviewHighlighterDiagnostic("initializing", {\n@@ -238,12 +265,11 @@ async function getHighlighter(): Promise<HighlighterCore> {\n resultCacheDisabled: REVIEW_HIGHLIGHTER_DISABLE_RESULT_CACHE,\n });\n \n- const themes = [lightThemeModule.default, darkThemeModule.default];\n+ const themes = [githubLightDefault, githubDarkDefault];\n \n if (REVIEW_HIGHLIGHTER_ENGINE_PREFERENCE !== "javascript") {\n try {\n const nativeEngineModule = await import("react-native-shiki-engine");\n- logReviewHighlighterDiagnostic("imported react-native-shiki-engine");\n nativeEngineAvailable = nativeEngineModule.isNativeEngineAvailable();\n logReviewHighlighterDiagnostic("checked native engine availability", {\n nativeEngineAvailable,\n@@ -253,7 +279,7 @@ async function getHighlighter(): Promise<HighlighterCore> {\n logReviewHighlighterDiagnostic("creating native regex engine");\n const highlighter = await createHighlighterCore({\n themes,\n- langs: [],\n+ langs: REVIEW_INITIAL_LANGUAGE_MODULES,\n engine: nativeEngineModule.createNativeEngine(),\n });\n logReviewHighlighterDiagnostic("using native engine");\n@@ -281,7 +307,7 @@ async function getHighlighter(): Promise<HighlighterCore> {\n );\n const highlighter = await createHighlighterCore({\n themes,\n- langs: [],\n+ langs: REVIEW_INITIAL_LANGUAGE_MODULES,\n engine: createJavaScriptRegexEngine(),\n });\n logReviewHighlighterDiagnostic("using javascript engine", {\n@@ -291,7 +317,7 @@ async function getHighlighter(): Promise<HighlighterCore> {\n highlighter,\n engine,\n };\n- });\n+ })();\n \n highlighterPromise = configuredHighlighterPromise\n .then((result) => result.highlighter)\n@@ -316,11 +342,52 @@ export async function getActiveReviewHighlighterEngine(): Promise<ReviewHighligh\n return activeHighlighterEnginePromise ?? Promise.resolve("javascript");\n }\n \n+export async function prepareReviewHighlighter(): Promise<void> {\n+ await getHighlighter();\n+}\n+\n+export async function prepareReviewHighlighterLanguages(\n+ languages: ReadonlyArray<string>,\n+): Promise<void> {\n+ const highlighter = await getHighlighter();\n+ await Promise.all(\n+ languages.map(async (language) => {\n+ const candidate = resolveLanguageAlias(language);\n+ if (candidate === "text" || !(candidate in languageImports)) {\n+ return;\n+ }\n+\n+ await loadSingleLanguage(highlighter, candidate);\n+ }),\n+ );\n+}\n+\n function resolveLanguageAlias(language: string): string {\n const normalized = language.toLowerCase();\n return languageAliases[normalized] ?? normalized;\n }\n \n+function resolveLoadedLanguageFromPath(\n+ path: string,\n+ languageHint: string | null = null,\n+): string | null {\n+ const detectedLanguage = languageHint ?? getFiletypeFromFileName(path);\n+ if (!detectedLanguage) {\n+ return "text";\n+ }\n+\n+ const candidate = resolveLanguageAlias(detectedLanguage);\n+ if (candidate === "text" || candidate === "ansi") {\n+ return "text";\n+ }\n+\n+ if (!(candidate in languageImports)) {\n+ return "text";\n+ }\n+\n+ return loadedLanguages.has(candidate) ? candidate : null;\n+}\n+\n async function loadSingleLanguage(\n highlighter: HighlighterCore,\n language: string,\n@@ -360,6 +427,11 @@ async function resolveLanguageFromPath(\n path: string,\n languageHint: string | null = null,\n ): Promise<string> {\n+ const loadedLanguage = resolveLoadedLanguageFromPath(path, languageHint);\n+ if (loadedLanguage) {\n+ return loadedLanguage;\n+ }\n+\n const detectedLanguage = languageHint ?? getFiletypeFromFileName(path);\n if (!detectedLanguage) {\n return "text";\n@@ -374,8 +446,12 @@ async function resolveLanguageFromPath(\n return "text";\n }\n \n+ if (loadedLanguages.has(candidate)) {\n+ return candidate;\n+ }\n+\n const highlighter = await getHighlighter();\n- const loaded = await loadSingleLanguage(highlighter, resolveLanguageAlias(candidate));\n+ const loaded = await loadSingleLanguage(highlighter, candidate);\n if (!loaded) {\n return "text";\n }\n@@ -384,7 +460,10 @@ async function resolveLanguageFromPath(\n }\n \n async function resolveLanguage(file: ReviewRenderableFile): Promise<string> {\n- return resolveLanguageFromPath(file.path, file.languageHint);\n+ return (\n+ resolveLoadedLanguageFromPath(file.path, file.languageHint) ??\n+ (await resolveLanguageFromPath(file.path, file.languageHint))\n+ );\n }\n \n function normalizeHighlightedLines(\n@@ -399,6 +478,18 @@ function normalizeHighlightedLines(\n );\n }\n \n+function makePlainHighlightedLines(\n+ lines: ReadonlyArray<string>,\n+): ReadonlyArray<ReadonlyArray<ReviewHighlightedToken>> {\n+ return lines.map((line) => [\n+ {\n+ content: stripTrailingNewline(line),\n+ color: null,\n+ fontStyle: null,\n+ },\n+ ]);\n+}\n+\n function applyWordAltDiffHighlightsToFile(\n file: ReviewRenderableFile,\n highlighted: ReviewHighlightedFile,\n@@ -594,6 +685,67 @@ async function highlightLines(\n return highlightedLines;\n }\n \n+async function highlightPatchLinesInChunks(input: {\n+ readonly lines: ReadonlyArray<string>;\n+ readonly language: string;\n+ readonly theme: string;\n+ readonly onChunk: (\n+ startIndex: number,\n+ tokens: ReadonlyArray<ReadonlyArray<ReviewHighlightedToken>>,\n+ ) => void;\n+}): Promise<ReadonlyArray<ReadonlyArray<ReviewHighlightedToken>>> {\n+ if (input.lines.length === 0) {\n+ return [];\n+ }\n+\n+ const highlighter = await getHighlighter();\n+ const highlightedLines: Array<ReadonlyArray<ReviewHighlightedToken>> = [];\n+\n+ for (\n+ let startIndex = 0;\n+ startIndex < input.lines.length;\n+ startIndex += REVIEW_HIGHLIGHT_CHUNK_SIZE\n+ ) {\n+ const lineChunk = input.lines.slice(startIndex, startIndex + REVIEW_HIGHLIGHT_CHUNK_SIZE);\n+ const chunkTokens: Array<ReadonlyArray<ReviewHighlightedToken>> = [];\n+ const tokenizableLines: string[] = [];\n+ const tokenizableIndexes: number[] = [];\n+\n+ lineChunk.forEach((line, index) => {\n+ const strippedLine = stripTrailingNewline(line);\n+ if (strippedLine.length > REVIEW_TOKENIZE_MAX_LINE_LENGTH) {\n+ chunkTokens[index] = [{ content: strippedLine, color: null, fontStyle: null }];\n+ return;\n+ }\n+\n+ tokenizableIndexes.push(index);\n+ tokenizableLines.push(strippedLine);\n+ });\n+\n+ if (tokenizableLines.length > 0) {\n+ const tokenLines = highlighter.codeToTokensBase(tokenizableLines.join("\\n"), {\n+ lang: input.language,\n+ theme: input.theme,\n+ });\n+ const normalizedTokenLines = normalizeHighlightedLines(tokenLines);\n+\n+ tokenizableIndexes.forEach((chunkIndex, tokenIndex) => {\n+ chunkTokens[chunkIndex] = normalizedTokenLines[tokenIndex] ?? [];\n+ });\n+ }\n+\n+ const completedChunk = lineChunk.map((_, index) => chunkTokens[index] ?? []);\n+ highlightedLines.push(...completedChunk);\n+ input.onChunk(startIndex, completedChunk);\n+\n+ if (startIndex + REVIEW_HIGHLIGHT_CHUNK_SIZE < input.lines.length) {\n+ await waitForNextFrame();\n+ }\n+ }\n+\n+ return highlightedLines;\n+}\n+\n function getHighlightCacheKey(file: ReviewRenderableFile, theme: ReviewDiffTheme): string {\n return `${SHIKI_THEME_NAME_BY_SCHEME[theme]}:${file.cacheKey}`;\n }\n@@ -667,7 +819,28 @@ export async function highlightReviewFile(\n deletionLineCount: file.deletionLines.length,\n rowCount: file.rows.length,\n });\n- const language = await resolveLanguage(file);\n+ const loadedLanguage = resolveLoadedLanguageFromPath(file.path, file.languageHint);\n+ const language = loadedLanguage ?? (await resolveLanguage(file));\n+ if (language === "text") {\n+ const highlighted = applyWordAltDiffHighlightsToFile(file, {\n+ additionLines: makePlainHighlightedLines(file.additionLines),\n+ deletionLines: makePlainHighlightedLines(file.deletionLines),\n+ });\n+ if (!REVIEW_HIGHLIGHTER_DISABLE_RESULT_CACHE) {\n+ storeResolvedHighlightedFile(cacheKey, highlighted);\n+ }\n+ logReviewHighlighterDiagnostic("file highlight complete", {\n+ fileId: file.id,\n+ filePath: file.path,\n+ theme,\n+ language,\n+ highlightedAdditionLineCount: highlighted.additionLines.length,\n+ highlightedDeletionLineCount: highlighted.deletionLines.length,\n+ durationMs: Date.now() - startedAt,\n+ });\n+ return highlighted;\n+ }\n+\n const additionLines = await highlightLines(\n joinPatchLines(file.additionLines),\n language,\n@@ -707,6 +880,113 @@ export async function highlightReviewFile(\n });\n }\n \n+export async function streamHighlightReviewFile(\n+ file: ReviewRenderableFile,\n+ theme: ReviewDiffTheme,\n+ onProgress: (progress: ReviewHighlightFileProgress) => void,\n+): Promise<ReviewHighlightedFile> {\n+ const shikiTheme = SHIKI_THEME_NAME_BY_SCHEME[theme];\n+ const cacheKey = getHighlightCacheKey(file, theme);\n+ if (!REVIEW_HIGHLIGHTER_DISABLE_RESULT_CACHE) {\n+ const resolved = resolvedHighlightCache.get(cacheKey);\n+ if (resolved) {\n+ onProgress({\n+ highlightedFile: resolved,\n+ complete: true,\n+ highlightedLineCount: resolved.additionLines.length + resolved.deletionLines.length,\n+ });\n+ return resolved;\n+ }\n+ }\n+\n+ const startedAt = Date.now();\n+ logReviewHighlighterDiagnostic("file stream highlight start", {\n+ fileId: file.id,\n+ filePath: file.path,\n+ theme,\n+ additionLineCount: file.additionLines.length,\n+ deletionLineCount: file.deletionLines.length,\n+ rowCount: file.rows.length,\n+ });\n+\n+ const loadedLanguage = resolveLoadedLanguageFromPath(file.path, file.languageHint);\n+ const language = loadedLanguage ?? (await resolveLanguage(file));\n+ if (language === "text") {\n+ const highlighted = applyWordAltDiffHighlightsToFile(file, {\n+ additionLines: makePlainHighlightedLines(file.additionLines),\n+ deletionLines: makePlainHighlightedLines(file.deletionLines),\n+ });\n+ if (!REVIEW_HIGHLIGHTER_DISABLE_RESULT_CACHE) {\n+ storeResolvedHighlightedFile(cacheKey, highlighted);\n+ }\n+ onProgress({\n+ highlightedFile: highlighted,\n+ complete: true,\n+ highlightedLineCount: highlighted.additionLines.length + highlighted.deletionLines.length,\n+ });\n+ logReviewHighlighterDiagnostic("file stream highlight complete", {\n+ fileId: file.id,\n+ filePath: file.path,\n+ theme,\n+ language,\n+ highlightedAdditionLineCount: highlighted.additionLines.length,\n+ highlightedDeletionLineCount: highlighted.deletionLines.length,\n+ highlightedLineCount: highlighted.additionLines.length + highlighted.deletionLines.length,\n+ durationMs: Date.now() - startedAt,\n+ });\n+ return highlighted;\n+ }\n+\n+ const additionLines: Array<ReadonlyArray<ReviewHighlightedToken>> = [];\n+ const deletionLines: Array<ReadonlyArray<ReviewHighlightedToken>> = [];\n+ let highlightedLineCount = 0;\n+\n+ await highlightPatchLinesInChunks({\n+ lines: file.additionLines,\n+ language,\n+ theme: shikiTheme,\n+ onChunk: (startIndex, tokens) => {\n+ tokens.forEach((lineTokens, index) => {\n+ additionLines[startIndex + index] = lineTokens;\n+ });\n+ highlightedLineCount += tokens.length;\n+ },\n+ });\n+ await waitForNextFrame();\n+ await highlightPatchLinesInChunks({\n+ lines: file.deletionLines,\n+ language,\n+ theme: shikiTheme,\n+ onChunk: (startIndex, tokens) => {\n+ tokens.forEach((lineTokens, index) => {\n+ deletionLines[startIndex + index] = lineTokens;\n+ });\n+ highlightedLineCount += tokens.length;\n+ },\n+ });\n+\n+ const highlighted = applyWordAltDiffHighlightsToFile(file, { additionLines, deletionLines });\n+ if (!REVIEW_HIGHLIGHTER_DISABLE_RESULT_CACHE) {\n+ storeResolvedHighlightedFile(cacheKey, highlighted);\n+ }\n+ onProgress({\n+ highlightedFile: highlighted,\n+ complete: true,\n+ highlightedLineCount,\n+ });\n+ logReviewHighlighterDiagnostic("file stream highlight complete", {\n+ fileId: file.id,\n+ filePath: file.path,\n+ theme,\n+ language,\n+ highlightedAdditionLineCount: highlighted.additionLines.length,\n+ highlightedDeletionLineCount: highlighted.deletionLines.length,\n+ highlightedLineCount,\n+ durationMs: Date.now() - startedAt,\n+ });\n+ return highlighted;\n+}\n+\n export async function highlightReviewSelectedLines(input: {\n readonly filePath: string;\n readonly lines: ReadonlyArray<ReviewRenderableLineRow>;\n@@ -717,7 +997,9 @@ export async function highlightReviewSelectedLines(input: {\n return {};\n }\n \n- const language = await resolveLanguageFromPath(input.filePath, input.languageHint ?? null);\n+ const loadedLanguage = resolveLoadedLanguageFromPath(input.filePath, input.languageHint ?? null);\n+ const language =\n+ loadedLanguage ?? (await resolveLanguageFromPath(input.filePath, input.languageHint ?? null));\n const shikiTheme = SHIKI_THEME_NAME_BY_SCHEME[input.theme];\n const additionLikeLines = input.lines\n .filter((line) => line.change !== "delete")\ndiff --git a/apps/mobile/docs/review-profiling.md b/apps/mobile/docs/review-profiling.md\nnew file mode 100644\nindex 000000000..6977eaf6e\n--- /dev/null\n+++ b/apps/mobile/docs/review-profiling.md\n@@ -0,0 +1,80 @@\n+# Review Screen Profiling\n+\n+Use this when the mobile review screen is slow or crashes while opening large diffs.\n+\n+## Preferred Capture: React Native DevTools Performance\n+\n+This app is on Expo SDK 55 / React Native 0.83 with Hermes, so the best first trace is the React Native DevTools Performance recording. The review screen also emits `t3.review.*` user timing marks in development builds so the trace can show parse, list-building, row indexing, and syntax-highlighting work.\n+\n+1. Start the development client:\n+\n+ ```sh\n+ cd apps/mobile\n+ bun dev:client\n+ ```\n+\n+2. Open the app in the iOS Simulator or on the device using the development client.\n+\n+3. In the terminal running Expo, press `j` to open React Native DevTools.\n+\n+4. In DevTools, open the `Performance` panel.\n+\n+5. Start recording.\n+\n+6. In the app, reproduce the slow path:\n+ - Navigate to the thread.\n+ - Open `Files Changed`.\n+ - Select the largest review source.\n+ - Expand a few large files or tap `Load diff`.\n+ - Scroll until the app is clearly slow or until just before it crashes.\n+\n+7. Stop recording.\n+\n+8. Export or save the Performance recording as a JSON trace.\n+\n+Send that exported trace file here. Also include the device/simulator model and whether it was iOS or Android.\n+\n+## Android Fallback: Hermes Sampling Profile\n+\n+Use this if the app crashes before DevTools can export a trace, or if we need deeper JavaScript stack samples.\n+\n+1. Run Android dev client:\n+\n+ ```sh\n+ cd apps/mobile\n+ bun android:dev\n+ bun dev:client\n+ ```\n+\n+2. Open the developer menu from the Expo terminal with `d`.\n+\n+3. Select `Enable Sampling Profiler`.\n+\n+4. Reproduce the review-screen slowdown.\n+\n+5. Open the developer menu again with `d`.\n+\n+6. Select `Disable Sampling Profiler`.\n+\n+7. Pull and convert the Hermes profile:\n+\n+ ```sh\n+ cd apps/mobile\n+ mkdir -p profiles/review\n+ bunx react-native profile-hermes profiles/review\n+ ```\n+\n+8. Send the generated Chrome trace/profile file from `apps/mobile/profiles/review`.\n+\n+For the development app variant, the Android package is `com.t3tools.t3code.dev`.\n+\n+## What To Capture\n+\n+For the first trace, do not optimize the repro. We want the slowest realistic case:\n+\n+- A diff with many files and large line counts.\n+- At least one `Load diff` action for a suppressed large diff.\n+- One vertical scroll pass after the content appears.\n+- One horizontal scroll of a long file, if that is part of the slowdown.\n+\n+If the app crashes, note the last visible action before the crash and attach device logs if available.\ndiff --git a/apps/mobile/src/app/debug/syntax-highlight.tsx b/apps/mobile/src/app/debug/syntax-highlight.tsx\nnew file mode 100644\nindex 000000000..c2a36d126\n--- /dev/null\n+++ b/apps/mobile/src/app/debug/syntax-highlight.tsx\n@@ -0,0 +1,423 @@\n+import { createHighlighterCore, type HighlighterCore } from "@shikijs/core";\n+import { createJavaScriptRegexEngine } from "@shikijs/engine-javascript";\n+import typescriptLanguage from "@shikijs/langs/typescript";\n+import githubDarkDefault from "@shikijs/themes/github-dark-default";\n+import githubLightDefault from "@shikijs/themes/github-light-default";\n+import Stack from "expo-router/stack";\n+import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";\n+import {\n+ FlatList,\n+ Pressable,\n+ Text as NativeText,\n+ type ListRenderItemInfo,\n+ useColorScheme,\n+ useWindowDimensions,\n+ View,\n+} from "react-native";\n+import { useSafeAreaInsets } from "react-native-safe-area-context";\n+\n+import { AppText as Text } from "../../components/AppText";\n+import { cn } from "../../lib/cn";\n+import { useThemeColor } from "../../lib/useThemeColor";\n+\n+type DebugHighlightEngine = "native" | "javascript";\n+\n+type DebugToken = {\n+ readonly content: string;\n+ readonly color: string | null;\n+ readonly fontStyle: number | null;\n+};\n+\n+type DebugLine = {\n+ readonly id: string;\n+ readonly chunkIndex: number;\n+ readonly indexInChunk: number;\n+ readonly lineNumber: number;\n+ readonly content: string;\n+};\n+\n+type DebugHighlighterHandle = {\n+ readonly engine: DebugHighlightEngine;\n+ readonly tokenize: (\n+ code: string,\n+ options: { readonly lang: string; readonly theme: string },\n+ ) => ReadonlyArray<ReadonlyArray<DebugToken>>;\n+};\n+\n+const DEBUG_LINE_COUNT = 10_000;\n+const DEBUG_CHUNK_SIZE = 500;\n+const DEBUG_LINE_HEIGHT = 24;\n+const DEBUG_GUTTER_WIDTH = 58;\n+const DEBUG_CONTENT_WIDTH = 3_200;\n+const DEBUG_MONO_FONT_FAMILY = "BerkeleyMono-Regular";\n+const DEBUG_THEME_NAME_BY_SCHEME = {\n+ dark: "github-dark-default",\n+ light: "github-light-default",\n+} as const;\n+\n+let nativeHighlighterPromise: Promise<DebugHighlighterHandle> | null = null;\n+let javascriptHighlighterPromise: Promise<DebugHighlighterHandle> | null = null;\n+\n+function waitForNextFrame(): Promise<void> {\n+ return new Promise((resolve) => setTimeout(resolve, 0));\n+}\n+\n+function normalizeTokens(\n+ tokenLines: ReadonlyArray<ReadonlyArray<{ content: string; color?: string; fontStyle?: number }>>,\n+): ReadonlyArray<ReadonlyArray<DebugToken>> {\n+ return tokenLines.map((line) =>\n+ line.map((token) => ({\n+ content: token.content,\n+ color: token.color ?? null,\n+ fontStyle: token.fontStyle ?? null,\n+ })),\n+ );\n+}\n+\n+function makeDebugCodeLine(index: number): string {\n+ const label = `generatedLine${String(index).padStart(5, "0")}`;\n+ switch (index % 8) {\n+ case 0:\n+ return `export async function ${label}(input: { value: number; name: string }) {`;\n+ case 1:\n+ return ` const normalized = input.name.trim().toLowerCase();`;\n+ case 2:\n+ return ` const result = await Promise.resolve({ id: "${label}", score: input.value * ${index + 1} });`;\n+ case 3:\n+ return ` if (result.score > ${index * 17}) return normalized + ":" + result.id;`;\n+ case 4:\n+ return ` return [normalized, String(result.score), "${"x".repeat((index % 24) + 8)}"].join("/");`;\n+ case 5:\n+ return `}`;\n+ case 6:\n+ return `type ${label}Record = Readonly<{ id: string; createdAt: Date; tags: string[] }>;`;\n+ default:\n+ return `const ${label}: ${label}Record = { id: "${label}", createdAt: new Date(), tags: ["debug", "highlight"] };`;\n+ }\n+}\n+\n+function makeDebugLines(): ReadonlyArray<DebugLine> {\n+ return Array.from({ length: DEBUG_LINE_COUNT }, (_, index) => ({\n+ id: `line:${index + 1}`,\n+ chunkIndex: Math.floor(index / DEBUG_CHUNK_SIZE),\n+ indexInChunk: index % DEBUG_CHUNK_SIZE,\n+ lineNumber: index + 1,\n+ content: makeDebugCodeLine(index + 1),\n+ }));\n+}\n+\n+async function createNativeDebugHighlighter(): Promise<DebugHighlighterHandle> {\n+ const nativeEngineModule = await import("react-native-shiki-engine");\n+ if (!nativeEngineModule.isNativeEngineAvailable()) {\n+ throw new Error("Native Shiki engine is not available in this build.");\n+ }\n+\n+ const highlighter = await createHighlighterCore({\n+ langs: [typescriptLanguage],\n+ themes: [githubLightDefault, githubDarkDefault],\n+ engine: nativeEngineModule.createNativeEngine(),\n+ });\n+\n+ return {\n+ engine: "native",\n+ tokenize: (code, options) => normalizeTokens(highlighter.codeToTokensBase(code, options)),\n+ };\n+}\n+\n+async function createJavascriptDebugHighlighter(): Promise<DebugHighlighterHandle> {\n+ const highlighter: HighlighterCore = await createHighlighterCore({\n+ langs: [typescriptLanguage],\n+ themes: [githubLightDefault, githubDarkDefault],\n+ engine: createJavaScriptRegexEngine(),\n+ });\n+\n+ return {\n+ engine: "javascript",\n+ tokenize: (code, options) => normalizeTokens(highlighter.codeToTokensBase(code, options)),\n+ };\n+}\n+\n+async function getDebugHighlighter(engine: DebugHighlightEngine): Promise<DebugHighlighterHandle> {\n+ if (engine === "native") {\n+ nativeHighlighterPromise ??= createNativeDebugHighlighter();\n+ return nativeHighlighterPromise;\n+ }\n+\n+ javascriptHighlighterPromise ??= createJavascriptDebugHighlighter();\n+ return javascriptHighlighterPromise;\n+}\n+\n+const TokenText = memo(function TokenText(props: {\n+ readonly content: string;\n+ readonly tokens: ReadonlyArray<DebugToken> | null;\n+}) {\n+ if (!props.tokens) {\n+ return (\n+ <NativeText\n+ numberOfLines={1}\n+ className="text-[13px] font-medium leading-[18px] text-foreground"\n+ style={{ fontFamily: DEBUG_MONO_FONT_FAMILY }}\n+ >\n+ {props.content}\n+ </NativeText>\n+ );\n+ }\n+\n+ let tokenOffset = 0;\n+\n+ return (\n+ <NativeText\n+ numberOfLines={1}\n+ className="text-[13px] font-medium leading-[18px] text-foreground"\n+ style={{ fontFamily: DEBUG_MONO_FONT_FAMILY }}\n+ >\n+ {props.tokens.map((token) => {\n+ const tokenKey = `${tokenOffset}:${token.content.length}:${token.color ?? ""}:${token.fontStyle ?? ""}`;\n+ tokenOffset += token.content.length;\n+ const fontWeight =\n+ token.fontStyle !== null && (token.fontStyle & 2) === 2\n+ ? ("700" as const)\n+ : ("500" as const);\n+ const fontStyle =\n+ token.fontStyle !== null && (token.fontStyle & 1) === 1\n+ ? ("italic" as const)\n+ : ("normal" as const);\n+\n+ return (\n+ <NativeText\n+ key={tokenKey}\n+ style={{\n+ color: token.color ?? undefined,\n+ fontFamily: DEBUG_MONO_FONT_FAMILY,\n+ fontStyle,\n+ fontWeight,\n+ }}\n+ >\n+ {token.content}\n+ </NativeText>\n+ );\n+ })}\n+ </NativeText>\n+ );\n+});\n+\n+const DebugCodeLineRow = memo(function DebugCodeLineRow(props: {\n+ readonly item: DebugLine;\n+ readonly tokens: ReadonlyArray<DebugToken> | null;\n+ readonly width: number;\n+}) {\n+ return (\n+ <View className="flex-row bg-card" style={{ height: DEBUG_LINE_HEIGHT, width: props.width }}>\n+ <View className="items-end justify-center pr-2" style={{ width: DEBUG_GUTTER_WIDTH }}>\n+ <Text className="font-mono text-[11px] text-foreground-muted">{props.item.lineNumber}</Text>\n+ </View>\n+ <View className="justify-center px-2" style={{ width: DEBUG_CONTENT_WIDTH }}>\n+ <TokenText content={props.item.content} tokens={props.tokens} />\n+ </View>\n+ </View>\n+ );\n+});\n+\n+function EngineToggle(props: {\n+ readonly engine: DebugHighlightEngine;\n+ readonly onChangeEngine: (engine: DebugHighlightEngine) => void;\n+}) {\n+ return (\n+ <View className="flex-row rounded-full bg-subtle p-1">\n+ {(["native", "javascript"] as const).map((engine) => {\n+ const selected = props.engine === engine;\n+ return (\n+ <Pressable\n+ key={engine}\n+ className={cn("rounded-full px-3 py-1.5", selected && "bg-card")}\n+ onPress={() => props.onChangeEngine(engine)}\n+ >\n+ <Text\n+ className={cn(\n+ "text-[12px] font-t3-bold",\n+ selected ? "text-foreground" : "text-foreground-muted",\n+ )}\n+ >\n+ {engine === "javascript" ? "JS" : "Native"}\n+ </Text>\n+ </Pressable>\n+ );\n+ })}\n+ </View>\n+ );\n+}\n+\n+export default function SyntaxHighlightDebugRoute() {\n+ const insets = useSafeAreaInsets();\n+ const { width } = useWindowDimensions();\n+ const colorScheme = useColorScheme();\n+ const headerIcon = String(useThemeColor("--color-icon"));\n+ const themeName = DEBUG_THEME_NAME_BY_SCHEME[colorScheme === "dark" ? "dark" : "light"];\n+ const [engine, setEngine] = useState<DebugHighlightEngine>("native");\n+ const [tokensByChunkIndex, setTokensByChunkIndex] = useState<\n+ Record<number, ReadonlyArray<ReadonlyArray<DebugToken>>>\n+ >({});\n+ const [status, setStatus] = useState("Idle");\n+ const renderStartRef = useRef<number | null>(null);\n+ const generationRef = useRef(0);\n+ const lines = useMemo(() => makeDebugLines(), []);\n+\n+ useEffect(() => {\n+ const generation = generationRef.current + 1;\n+ generationRef.current = generation;\n+ renderStartRef.current = performance.now();\n+ setTokensByChunkIndex({});\n+ setStatus("Initializing highlighter");\n+\n+ void (async () => {\n+ try {\n+ const highlighterStartedAt = performance.now();\n+ const highlighter = await getDebugHighlighter(engine);\n+ if (generation !== generationRef.current) {\n+ return;\n+ }\n+\n+ console.log("[debug-syntax-scratch] initialize", {\n+ durationMs: Math.round(performance.now() - highlighterStartedAt),\n+ engine: highlighter.engine,\n+ });\n+\n+ let firstChunkMs: number | null = null;\n+ const totalStartedAt = performance.now();\n+ setStatus(`Streaming ${DEBUG_LINE_COUNT.toLocaleString()} lines`);\n+\n+ for (let startIndex = 0; startIndex < lines.length; startIndex += DEBUG_CHUNK_SIZE) {\n+ if (generation !== generationRef.current) {\n+ return;\n+ }\n+\n+ const chunkLines = lines.slice(startIndex, startIndex + DEBUG_CHUNK_SIZE);\n+ const chunkCode = chunkLines.map((line) => line.content).join("\\n");\n+ const chunkStartedAt = performance.now();\n+ const chunkTokens = highlighter.tokenize(chunkCode, {\n+ lang: "typescript",\n+ theme: themeName,\n+ });\n+ const chunkMs = performance.now() - chunkStartedAt;\n+\n+ if (firstChunkMs === null) {\n+ firstChunkMs = performance.now() - totalStartedAt;\n+ console.log("[debug-syntax-scratch] first chunk", {\n+ chunkSize: DEBUG_CHUNK_SIZE,\n+ durationMs: Math.round(firstChunkMs),\n+ engine,\n+ lineCount: chunkTokens.length,\n+ });\n+ }\n+\n+ setTokensByChunkIndex((current) => ({\n+ ...current,\n+ [startIndex / DEBUG_CHUNK_SIZE]: chunkTokens,\n+ }));\n+ setStatus(\n+ `Streamed ${Math.min(startIndex + DEBUG_CHUNK_SIZE, lines.length).toLocaleString()} / ${lines.length.toLocaleString()} lines`,\n+ );\n+\n+ console.log("[debug-syntax-scratch] chunk", {\n+ chunkIndex: startIndex / DEBUG_CHUNK_SIZE,\n+ chunkMs: Math.round(chunkMs),\n+ engine,\n+ lineCount: chunkTokens.length,\n+ });\n+\n+ await waitForNextFrame();\n+ }\n+\n+ console.log("[debug-syntax-scratch] complete", {\n+ durationMs: Math.round(performance.now() - totalStartedAt),\n+ engine,\n+ lineCount: lines.length,\n+ });\n+ setStatus(`Complete with ${engine}`);\n+ } catch (error) {\n+ console.error("[debug-syntax-scratch] failed", {\n+ engine,\n+ message: error instanceof Error ? error.message : String(error),\n+ });\n+ setStatus(error instanceof Error ? error.message : "Highlight failed");\n+ }\n+ })();\n+ }, [engine, lines, themeName]);\n+\n+ useEffect(() => {\n+ if (renderStartRef.current === null) {\n+ return;\n+ }\n+\n+ const startedAt = renderStartRef.current;\n+ renderStartRef.current = null;\n+ const commitMs = performance.now() - startedAt;\n+ requestAnimationFrame(() => {\n+ console.log("[debug-syntax-scratch] render", {\n+ commitMs: Math.round(commitMs),\n+ paintMs: Math.round(performance.now() - startedAt),\n+ });\n+ });\n+ });\n+\n+ const renderItem = useCallback(\n+ ({ item }: ListRenderItemInfo<DebugLine>) => (\n+ <DebugCodeLineRow\n+ item={item}\n+ tokens={tokensByChunkIndex[item.chunkIndex]?.[item.indexInChunk] ?? null}\n+ width={width}\n+ />\n+ ),\n+ [tokensByChunkIndex, width],\n+ );\n+\n+ return (\n+ <View className="flex-1 bg-sheet">\n+ <Stack.Screen\n+ options={{\n+ headerShown: true,\n+ headerTitle: "Syntax Scratch",\n+ headerTintColor: headerIcon,\n+ headerTransparent: true,\n+ headerShadowVisible: false,\n+ }}\n+ />\n+\n+ <View\n+ className="border-b border-border bg-sheet px-3 pb-3"\n+ style={{ paddingTop: insets.top + 56 }}\n+ >\n+ <View className="flex-row items-center justify-between gap-3">\n+ <View className="min-w-0 flex-1">\n+ <Text className="text-[13px] font-t3-bold text-foreground">\n+ Shiki streaming baseline\n+ </Text>\n+ <Text className="text-[11px] text-foreground-muted" numberOfLines={1}>\n+ {status}\n+ </Text>\n+ </View>\n+ <EngineToggle engine={engine} onChangeEngine={setEngine} />\n+ </View>\n+ </View>\n+\n+ <FlatList\n+ style={{ flex: 1, width }}\n+ data={lines}\n+ renderItem={renderItem}\n+ keyExtractor={(item) => item.id}\n+ getItemLayout={(_, index) => ({\n+ length: DEBUG_LINE_HEIGHT,\n+ offset: DEBUG_LINE_HEIGHT * index,\n+ index,\n+ })}\n+ initialNumToRender={40}\n+ maxToRenderPerBatch={80}\n+ updateCellsBatchingPeriod={16}\n+ windowSize={9}\n+ removeClippedSubviews\n+ keyboardShouldPersistTaps="handled"\n+ contentContainerStyle={{ paddingBottom: Math.max(insets.bottom, 18) + 18 }}\n+ />\n+ </View>\n+ );\n+}\ndiff --git a/apps/mobile/src/features/review/ReviewHighlighterProvider.tsx b/apps/mobile/src/features/review/ReviewHighlighterProvider.tsx\nnew file mode 100644\nindex 000000000..095201929\n--- /dev/null\n+++ b/apps/mobile/src/features/review/ReviewHighlighterProvider.tsx\n@@ -0,0 +1,110 @@\n+import { createContext, type ReactNode, useContext, useEffect, useMemo, useState } from "react";\n+\n+import {\n+ getActiveReviewHighlighterEngine,\n+ prepareReviewHighlighter,\n+ prepareReviewHighlighterLanguages,\n+ type ReviewHighlighterEngine,\n+} from "./shikiReviewHighlighter";\n+\n+type ReviewHighlighterStatus = "idle" | "initializing" | "ready" | "error";\n+\n+interface ReviewHighlighterContextValue {\n+ readonly engine: ReviewHighlighterEngine | null;\n+ readonly error: string | null;\n+ readonly status: ReviewHighlighterStatus;\n+}\n+\n+const ReviewHighlighterContext = createContext<ReviewHighlighterContextValue>({\n+ engine: null,\n+ error: null,\n+ status: "idle",\n+});\n+\n+const REVIEW_INITIAL_LANGUAGES = [\n+ "typescript",\n+ "tsx",\n+ "javascript",\n+ "jsx",\n+ "json",\n+ "yaml",\n+ "bash",\n+] as const;\n+\n+function isReviewHighlighterProviderDebugLoggingEnabled(): boolean {\n+ return typeof __DEV__ !== "undefined" ? __DEV__ : false;\n+}\n+\n+function logReviewHighlighterProviderDiagnostic(\n+ message: string,\n+ details?: Record<string, unknown>,\n+): void {\n+ if (!isReviewHighlighterProviderDebugLoggingEnabled()) {\n+ return;\n+ }\n+\n+ if (details) {\n+ console.log(`[review-highlighter-provider] ${message}`, details);\n+ return;\n+ }\n+\n+ console.log(`[review-highlighter-provider] ${message}`);\n+}\n+\n+export function ReviewHighlighterProvider(props: { readonly children: ReactNode }) {\n+ const [value, setValue] = useState<ReviewHighlighterContextValue>({\n+ engine: null,\n+ error: null,\n+ status: "idle",\n+ });\n+\n+ useEffect(() => {\n+ let cancelled = false;\n+\n+ setValue({ engine: null, error: null, status: "initializing" });\n+\n+ void (async () => {\n+ const startedAt = performance.now();\n+ try {\n+ await prepareReviewHighlighter();\n+ await prepareReviewHighlighterLanguages(REVIEW_INITIAL_LANGUAGES);\n+ const engine = await getActiveReviewHighlighterEngine();\n+\n+ if (cancelled) {\n+ return;\n+ }\n+\n+ const durationMs = Math.round(performance.now() - startedAt);\n+ logReviewHighlighterProviderDiagnostic("initialized", {\n+ durationMs,\n+ engine,\n+ });\n+ setValue({ engine, error: null, status: "ready" });\n+ } catch (error) {\n+ if (cancelled) {\n+ return;\n+ }\n+\n+ const message = error instanceof Error ? error.message : String(error);\n+ logReviewHighlighterProviderDiagnostic("initialization failed", { error: message });\n+ setValue({ engine: null, error: message, status: "error" });\n+ }\n+ })();\n+\n+ return () => {\n+ cancelled = true;\n+ };\n+ }, []);\n+\n+ const contextValue = useMemo(() => value, [value]);\n+\n+ return (\n+ <ReviewHighlighterContext.Provider value={contextValue}>\n+ {props.children}\n+ </ReviewHighlighterContext.Provider>\n+ );\n+}\n+\n+export function useReviewHighlighterStatus(): ReviewHighlighterContextValue {\n+ return useContext(ReviewHighlighterContext);\n+}\ndiff --git a/apps/mobile/src/features/review/reviewPerf.ts b/apps/mobile/src/features/review/reviewPerf.ts\nnew file mode 100644\nindex 000000000..2ae1095b1\n--- /dev/null\n+++ b/apps/mobile/src/features/review/reviewPerf.ts\n@@ -0,0 +1,83 @@\n+interface ReviewPerformanceLike {\n+ readonly now?: () => number;\n+ readonly mark?: (name: string) => void;\n+ readonly measure?: (name: string, startMark: string, endMark: string) => void;\n+ readonly clearMarks?: (name?: string) => void;\n+ readonly clearMeasures?: (name?: string) => void;\n+}\n+\n+const REVIEW_PERF_PREFIX = "t3.review";\n+let reviewPerfSequence = 0;\n+\n+function getPerformance(): ReviewPerformanceLike | null {\n+ const candidate = (globalThis as { readonly performance?: ReviewPerformanceLike }).performance;\n+ return candidate ?? null;\n+}\n+\n+export function isReviewPerfEnabled(): boolean {\n+ return typeof __DEV__ !== "undefined" ? __DEV__ : false;\n+}\n+\n+export function measureReviewWork<T>(name: string, callback: () => T): T {\n+ if (!isReviewPerfEnabled()) {\n+ return callback();\n+ }\n+\n+ const perf = getPerformance();\n+ const marker = `${REVIEW_PERF_PREFIX}.${name}.${reviewPerfSequence++}`;\n+ const startMark = `${marker}.start`;\n+ const endMark = `${marker}.end`;\n+ const startedAt = perf?.now?.() ?? Date.now();\n+\n+ perf?.mark?.(startMark);\n+ try {\n+ return callback();\n+ } finally {\n+ const durationMs = (perf?.now?.() ?? Date.now()) - startedAt;\n+ perf?.mark?.(endMark);\n+ perf?.measure?.(`${REVIEW_PERF_PREFIX}.${name}`, startMark, endMark);\n+ perf?.clearMarks?.(startMark);\n+ perf?.clearMarks?.(endMark);\n+ console.log(`[review-perf] ${name}`, { durationMs: Number(durationMs.toFixed(2)) });\n+ }\n+}\n+\n+export async function measureReviewAsyncWork<T>(\n+ name: string,\n+ callback: () => Promise<T>,\n+): Promise<T> {\n+ if (!isReviewPerfEnabled()) {\n+ return callback();\n+ }\n+\n+ const perf = getPerformance();\n+ const marker = `${REVIEW_PERF_PREFIX}.${name}.${reviewPerfSequence++}`;\n+ const startMark = `${marker}.start`;\n+ const endMark = `${marker}.end`;\n+ const startedAt = perf?.now?.() ?? Date.now();\n+\n+ perf?.mark?.(startMark);\n+ try {\n+ return await callback();\n+ } finally {\n+ const durationMs = (perf?.now?.() ?? Date.now()) - startedAt;\n+ perf?.mark?.(endMark);\n+ perf?.measure?.(`${REVIEW_PERF_PREFIX}.${name}`, startMark, endMark);\n+ perf?.clearMarks?.(startMark);\n+ perf?.clearMarks?.(endMark);\n+ console.log(`[review-perf] ${name}`, { durationMs: Number(durationMs.toFixed(2)) });\n+ }\n+}\n+\n+export function markReviewEvent(name: string, details?: Record<string, unknown>): void {\n+ if (!isReviewPerfEnabled()) {\n+ return;\n+ }\n+\n+ getPerformance()?.mark?.(`${REVIEW_PERF_PREFIX}.${name}`);\n+ if (details) {\n+ console.log(`[review-perf] ${name}`, details);\n+ return;\n+ }\n+ console.log(`[review-perf] ${name}`);\n+}\n',
230 },
231 {
232 id: "current",
233 label: "Current Working",
234 filename: "current-working-review.diff",
235 lineCount: 3208,
236 diff: 'diff --git a/apps/mobile/package.json b/apps/mobile/package.json\nindex 08329e1d4..36ac93a0f 100644\n--- a/apps/mobile/package.json\n+++ b/apps/mobile/package.json\n@@ -30,6 +30,7 @@\n "config:dev": "APP_VARIANT=development expo config",\n "config:preview": "APP_VARIANT=preview expo config",\n "config:prod": "APP_VARIANT=production expo config",\n+ "profile:android:hermes": "mkdir -p profiles/review && react-native profile-hermes profiles/review",\n "test": "vitest run",\n "typecheck": "tsc --noEmit"\n },\ndiff --git a/apps/mobile/src/app/index.tsx b/apps/mobile/src/app/index.tsx\nindex f153db701..f6095c051 100644\n--- a/apps/mobile/src/app/index.tsx\n+++ b/apps/mobile/src/app/index.tsx\n@@ -43,28 +43,50 @@ export default function HomeRouteScreen() {\n headerTintColor: iconColor,\n headerTitle: "",\n headerRight: () => (\n- <Pressable\n- onPress={() => router.push("/connections")}\n- hitSlop={8}\n- style={{\n- flexDirection: "row",\n- alignItems: "center",\n- gap: 8,\n- paddingHorizontal: 4,\n- paddingVertical: 4,\n- }}\n- >\n- <ConnectionStatusDot state={connectionState} pulse={hasRemoteActivity} size={7} />\n- <RNText\n+ <View style={{ flexDirection: "row", alignItems: "center", gap: 12 }}>\n+ <Pressable\n+ onPress={() => router.push("/debug/syntax-highlight")}\n+ hitSlop={8}\n style={{\n- fontFamily: "DMSans_700Bold",\n- fontSize: 12,\n- color: secondaryFg,\n+ borderRadius: 999,\n+ backgroundColor: isDark ? "rgba(255,255,255,0.06)" : "rgba(0,0,0,0.06)",\n+ paddingHorizontal: 10,\n+ paddingVertical: 5,\n }}\n >\n- {CONNECTION_LABEL[connectionState]}\n- </RNText>\n- </Pressable>\n+ <RNText\n+ style={{\n+ fontFamily: "DMSans_700Bold",\n+ fontSize: 12,\n+ color: secondaryFg,\n+ }}\n+ >\n+ Debug\n+ </RNText>\n+ </Pressable>\n+ <Pressable\n+ onPress={() => router.push("/connections")}\n+ hitSlop={8}\n+ style={{\n+ flexDirection: "row",\n+ alignItems: "center",\n+ gap: 8,\n+ paddingHorizontal: 4,\n+ paddingVertical: 4,\n+ }}\n+ >\n+ <ConnectionStatusDot state={connectionState} pulse={hasRemoteActivity} size={7} />\n+ <RNText\n+ style={{\n+ fontFamily: "DMSans_700Bold",\n+ fontSize: 12,\n+ color: secondaryFg,\n+ }}\n+ >\n+ {CONNECTION_LABEL[connectionState]}\n+ </RNText>\n+ </Pressable>\n+ </View>\n ),\n headerSearchBarOptions: {\n placeholder: "Search threads",\ndiff --git a/apps/mobile/src/app/threads/[environmentId]/[threadId]/review.tsx b/apps/mobile/src/app/threads/[environmentId]/[threadId]/review.tsx\nindex 84c48c6ed..ee993ee7c 100644\n--- a/apps/mobile/src/app/threads/[environmentId]/[threadId]/review.tsx\n+++ b/apps/mobile/src/app/threads/[environmentId]/[threadId]/review.tsx\n@@ -1,5 +1,10 @@\n+import { ReviewHighlighterProvider } from "../../../../features/review/ReviewHighlighterProvider";\n import { ReviewSheet } from "../../../../features/review/ReviewSheet";\n \n export default function ReviewRoute() {\n- return <ReviewSheet />;\n+ return (\n+ <ReviewHighlighterProvider>\n+ <ReviewSheet />\n+ </ReviewHighlighterProvider>\n+ );\n }\ndiff --git a/apps/mobile/src/features/review/ReviewCommentComposerSheet.tsx b/apps/mobile/src/features/review/ReviewCommentComposerSheet.tsx\nindex 076a2286d..9a173224a 100644\n--- a/apps/mobile/src/features/review/ReviewCommentComposerSheet.tsx\n+++ b/apps/mobile/src/features/review/ReviewCommentComposerSheet.tsx\n@@ -2,15 +2,8 @@ import { useLocalSearchParams, useRouter } from "expo-router";\n import { SymbolView } from "expo-symbols";\n import { TextInputWrapper } from "expo-paste-input";\n import { useEffect, useMemo, useState } from "react";\n-import {\n- KeyboardAvoidingView,\n- Platform,\n- Pressable,\n- ScrollView,\n- View,\n- useColorScheme,\n- useWindowDimensions,\n-} from "react-native";\n+import { Pressable, ScrollView, View, useColorScheme, useWindowDimensions } from "react-native";\n+import { KeyboardStickyView } from "react-native-keyboard-controller";\n import { useSafeAreaInsets } from "react-native-safe-area-context";\n import ImageViewing from "react-native-image-viewing";\n \n@@ -34,6 +27,7 @@ import {\n import {\n changeTone,\n DiffTokenText,\n+ REVIEW_DIFF_LINE_HEIGHT,\n REVIEW_MONO_FONT_FAMILY,\n ReviewChangeBar,\n } from "./reviewDiffRendering";\n@@ -44,7 +38,6 @@ import {\n } from "./shikiReviewHighlighter";\n \n const REVIEW_COMMENT_PREVIEW_MAX_LINES = 5;\n-const REVIEW_COMMENT_LINE_HEIGHT = 26;\n \n export function ReviewCommentComposerSheet() {\n const router = useRouter();\n@@ -84,8 +77,8 @@ export function ReviewCommentComposerSheet() {\n ? `Lines ${firstNumber}-${lastNumber}`\n : `${selectedLines.length} lines selected`;\n const previewHeight = Math.max(\n- Math.min(selectedLines.length, REVIEW_COMMENT_PREVIEW_MAX_LINES) * REVIEW_COMMENT_LINE_HEIGHT,\n- REVIEW_COMMENT_LINE_HEIGHT,\n+ Math.min(selectedLines.length, REVIEW_COMMENT_PREVIEW_MAX_LINES) * REVIEW_DIFF_LINE_HEIGHT,\n+ REVIEW_DIFF_LINE_HEIGHT,\n );\n const previewViewportWidth = Math.max(width - 40, 280);\n const handleNativePaste = useNativePaste((uris) => {\n@@ -143,17 +136,13 @@ export function ReviewCommentComposerSheet() {\n }\n \n return (\n- <KeyboardAvoidingView\n- behavior={Platform.OS === "ios" ? "padding" : "height"}\n- keyboardVerticalOffset={Platform.OS === "ios" ? 12 : 0}\n- style={{ flex: 1 }}\n- >\n+ <View style={{ flex: 1 }}>\n <View\n style={{\n flex: 1,\n paddingHorizontal: 20,\n paddingTop: 8,\n- paddingBottom: Math.max(insets.bottom, 18) + 18,\n+ paddingBottom: Math.max(insets.bottom, 18) + 82,\n }}\n >\n <View className="flex-row items-center justify-between py-2">\n@@ -219,7 +208,7 @@ export function ReviewCommentComposerSheet() {\n <View\n key={line.id}\n className={cn("flex-row items-start", changeTone(line.change))}\n- style={{ height: REVIEW_COMMENT_LINE_HEIGHT }}\n+ style={{ height: REVIEW_DIFF_LINE_HEIGHT }}\n >\n <ReviewChangeBar change={line.change} />\n <Text\n@@ -280,35 +269,41 @@ export function ReviewCommentComposerSheet() {\n ) : null}\n </View>\n </View>\n-\n- <View className="flex-row items-center gap-3 pt-1">\n- <ControlPill icon="plus" onPress={() => void handlePickImages()} />\n- <View className="flex-1" />\n- <ControlPill\n- icon="arrow.up"\n- label="Comment"\n- variant="primary"\n- disabled={!canSubmit}\n- onPress={() => {\n- if (!target || !environmentId || !threadId || commentText.trim().length === 0) {\n- return;\n- }\n-\n- appendReviewCommentToDraft({\n- environmentId,\n- threadId,\n- text: formatReviewCommentContext(target, commentText),\n- attachments,\n- });\n- setAttachments([]);\n- clearReviewCommentTarget();\n- router.dismiss();\n- }}\n- />\n- </View>\n </View>\n )}\n </View>\n+ {target ? (\n+ <KeyboardStickyView style={{ position: "absolute", bottom: 0, left: 0, right: 0 }}>\n+ <View\n+ className="flex-row items-center gap-3 bg-sheet px-5 pt-3"\n+ style={{ paddingBottom: Math.max(insets.bottom, 18) }}\n+ >\n+ <ControlPill icon="plus" onPress={() => void handlePickImages()} />\n+ <View className="flex-1" />\n+ <ControlPill\n+ icon="arrow.up"\n+ label="Comment"\n+ variant="primary"\n+ disabled={!canSubmit}\n+ onPress={() => {\n+ if (!target || !environmentId || !threadId || commentText.trim().length === 0) {\n+ return;\n+ }\n+\n+ appendReviewCommentToDraft({\n+ environmentId,\n+ threadId,\n+ text: formatReviewCommentContext(target, commentText),\n+ attachments,\n+ });\n+ setAttachments([]);\n+ clearReviewCommentTarget();\n+ router.dismiss();\n+ }}\n+ />\n+ </View>\n+ </KeyboardStickyView>\n+ ) : null}\n <ImageViewing\n images={previewImageUri ? [{ uri: previewImageUri }] : []}\n imageIndex={0}\n@@ -317,6 +312,6 @@ export function ReviewCommentComposerSheet() {\n swipeToCloseEnabled\n doubleTapToZoomEnabled\n />\n- </KeyboardAvoidingView>\n+ </View>\n );\n }\ndiff --git a/apps/mobile/src/features/review/ReviewSheet.tsx b/apps/mobile/src/features/review/ReviewSheet.tsx\nindex 82c28e81e..e148a8da2 100644\n--- a/apps/mobile/src/features/review/ReviewSheet.tsx\n+++ b/apps/mobile/src/features/review/ReviewSheet.tsx\n@@ -1,17 +1,31 @@\n import { EnvironmentId, ThreadId, type OrchestrationCheckpointSummary } from "@t3tools/contracts";\n+import { Gesture, GestureDetector } from "react-native-gesture-handler";\n+import Animated, {\n+ makeMutable,\n+ type SharedValue,\n+ useAnimatedStyle,\n+ useSharedValue,\n+} from "react-native-reanimated";\n import { useLocalSearchParams, useRouter } from "expo-router";\n import Stack from "expo-router/stack";\n import { SymbolView } from "expo-symbols";\n-import { memo, type ReactElement, useCallback, useEffect, useMemo, useRef, useState } from "react";\n+import {\n+ memo,\n+ type ReactElement,\n+ useCallback,\n+ useDeferredValue,\n+ useEffect,\n+ useMemo,\n+ useRef,\n+ useState,\n+} from "react";\n import {\n ActivityIndicator,\n FlatList,\n- InteractionManager,\n type ListRenderItemInfo,\n Pressable,\n ScrollView,\n Text as NativeText,\n- type ViewToken,\n useColorScheme,\n useWindowDimensions,\n View,\n@@ -32,6 +46,7 @@ import {\n setReviewTurnDiff,\n updateReviewExpandedFileIds,\n updateReviewRevealedLargeFileIds,\n+ updateReviewViewedFileIds,\n useReviewCacheForThread,\n } from "./reviewState";\n import {\n@@ -45,11 +60,12 @@ import {\n type ReviewParsedDiff,\n type ReviewRenderableFile,\n type ReviewRenderableLineRow,\n+ type ReviewRenderableRow,\n } from "./reviewModel";\n import {\n clearReviewHighlightFileCache,\n getCachedHighlightedReviewFile,\n- highlightReviewFile,\n+ streamHighlightReviewFile,\n type ReviewDiffTheme,\n type ReviewHighlightedFile,\n type ReviewHighlightedToken,\n@@ -67,9 +83,12 @@ import {\n import {\n changeTone,\n DiffTokenText,\n+ REVIEW_DIFF_LINE_HEIGHT,\n REVIEW_MONO_FONT_FAMILY,\n ReviewChangeBar,\n } from "./reviewDiffRendering";\n+import { markReviewEvent, measureReviewWork } from "./reviewPerf";\n+import { useReviewHighlighterStatus } from "./ReviewHighlighterProvider";\n \n interface PendingCommentSelection {\n readonly sectionTitle: string;\n@@ -87,14 +106,21 @@ interface ReviewLineActionInput {\n \n const IOS_NAV_BAR_HEIGHT = 44;\n const REVIEW_HEADER_SPACING = 0;\n-const REVIEW_LINE_GUTTER_WIDTH = 62;\n+const REVIEW_CHANGE_BAR_WIDTH = 5;\n+const REVIEW_MIN_LINE_NUMBER_WIDTH = 27;\n+const REVIEW_LINE_NUMBER_DIGIT_WIDTH_ESTIMATE = 8;\n+const REVIEW_LINE_NUMBER_HORIZONTAL_PADDING = 6;\n const REVIEW_CHARACTER_WIDTH_ESTIMATE = 8.4;\n const REVIEW_MAX_CONTENT_WIDTH = 4_800;\n-const REVIEW_INITIAL_HIGHLIGHT_FILE_COUNT = 2;\n-const REVIEW_HIGHLIGHT_BACKTRACK_COUNT = 0;\n-const REVIEW_HIGHLIGHT_LOOKAHEAD_COUNT = 1;\n+const REVIEW_HUNK_ROW_HEIGHT = 35;\n+const REVIEW_FILE_HEADER_HEIGHT = 43;\n+const REVIEW_SUPPRESSED_ROW_HEIGHT = 92;\n const loggedMissingReviewTokenKeys = new Set<string>();\n \n+function waitForReviewDelay(durationMs: number): Promise<void> {\n+ return new Promise((resolve) => setTimeout(resolve, durationMs));\n+}\n+\n function isReviewDiffDebugLoggingEnabled(): boolean {\n return typeof __DEV__ !== "undefined" ? __DEV__ : false;\n }\n@@ -113,33 +139,27 @@ function logReviewDiffDiagnostic(message: string, details?: Record<string, unkno\n }\n \n function getFileHeaderChrome(changeType: ReviewRenderableFile["changeType"]): {\n- readonly rail: string;\n readonly dot: string;\n } {\n switch (changeType) {\n case "new":\n return {\n- rail: "bg-emerald-400",\n dot: "bg-emerald-400",\n };\n case "deleted":\n return {\n- rail: "bg-rose-400",\n dot: "bg-rose-400",\n };\n case "rename-pure":\n return {\n- rail: "bg-amber-400",\n dot: "bg-amber-400",\n };\n case "rename-changed":\n return {\n- rail: "bg-sky-400",\n dot: "bg-sky-400",\n };\n default:\n return {\n- rail: "bg-sky-400",\n dot: "bg-sky-400",\n };\n }\n@@ -159,51 +179,72 @@ function formatHeaderDiffSummary(parsedDiff: ReviewParsedDiff): {\n };\n }\n \n-function computeReviewListContentWidth(\n- items: ReadonlyArray<ReviewListItem>,\n+function computeReviewFileContentWidth(\n+ rows: ReadonlyArray<ReviewRenderableRow>,\n viewportWidth: number,\n+ gutterWidth: number,\n ): number {\n let maxTextLength = 0;\n \n- items.forEach((item) => {\n- switch (item.kind) {\n- case "file-header":\n- maxTextLength = Math.max(\n- maxTextLength,\n- item.file.path.length,\n- item.file.previousPath?.length ?? 0,\n- );\n- break;\n- case "file-suppressed":\n- maxTextLength = Math.max(maxTextLength, item.message.length, item.actionLabel?.length ?? 0);\n- break;\n- case "hunk":\n- maxTextLength = Math.max(\n- maxTextLength,\n- item.row.header.length + (item.row.context ? item.row.context.length + 1 : 0),\n- );\n- break;\n- case "line":\n- maxTextLength = Math.max(maxTextLength, item.row.content.length);\n- break;\n+ rows.forEach((row) => {\n+ if (row.kind === "hunk") {\n+ maxTextLength = Math.max(\n+ maxTextLength,\n+ row.header.length + (row.context ? row.context.length + 1 : 0),\n+ );\n+ return;\n }\n+\n+ maxTextLength = Math.max(maxTextLength, row.content.length);\n });\n \n return Math.max(\n- viewportWidth,\n+ Math.max(0, viewportWidth - gutterWidth),\n Math.min(\n REVIEW_MAX_CONTENT_WIDTH,\n- Math.ceil(REVIEW_LINE_GUTTER_WIDTH + 48 + maxTextLength * REVIEW_CHARACTER_WIDTH_ESTIMATE),\n+ Math.ceil(48 + maxTextLength * REVIEW_CHARACTER_WIDTH_ESTIMATE),\n ),\n );\n }\n \n+function computeReviewFileGutterWidth(rows: ReadonlyArray<ReviewRenderableRow>): number {\n+ let maxLineNumber = 0;\n+\n+ rows.forEach((row) => {\n+ if (row.kind !== "line") {\n+ return;\n+ }\n+\n+ maxLineNumber = Math.max(maxLineNumber, row.oldLineNumber ?? 0, row.newLineNumber ?? 0);\n+ });\n+\n+ const digitCount = Math.max(1, String(maxLineNumber).length);\n+ const lineNumberWidth = Math.max(\n+ REVIEW_MIN_LINE_NUMBER_WIDTH,\n+ digitCount * REVIEW_LINE_NUMBER_DIGIT_WIDTH_ESTIMATE + REVIEW_LINE_NUMBER_HORIZONTAL_PADDING,\n+ );\n+\n+ return REVIEW_CHANGE_BAR_WIDTH + lineNumberWidth;\n+}\n+\n function getDefaultExpandedFileIds(\n files: ReadonlyArray<ReviewRenderableFile>,\n ): ReadonlyArray<string> {\n return files.map((file) => file.id);\n }\n \n+function getValidReviewExpandedFileIds(\n+ files: ReadonlyArray<ReviewRenderableFile>,\n+ cachedExpandedFileIds: ReadonlyArray<string> | undefined,\n+): ReadonlyArray<string> {\n+ if (cachedExpandedFileIds === undefined) {\n+ return getDefaultExpandedFileIds(files);\n+ }\n+\n+ const fileIdSet = new Set(files.map((file) => file.id));\n+ return cachedExpandedFileIds.filter((id) => fileIdSet.has(id));\n+}\n+\n function getHighlightedTokensForLine(\n line: ReviewRenderableLineRow,\n highlightedFile: ReviewHighlightedFile | null,\n@@ -252,16 +293,13 @@ const ReviewLineRow = memo(function ReviewLineRow(props: {\n delayLongPress={220}\n onLongPress={props.onStartRangeSelection}\n onPress={props.onComment}\n- style={{ minWidth: props.viewportWidth }}\n+ style={{\n+ height: REVIEW_DIFF_LINE_HEIGHT,\n+ width: props.viewportWidth,\n+ overflow: "hidden",\n+ }}\n >\n- <ReviewChangeBar change={props.line.change} />\n- <Text\n- className="w-9 py-1 pr-1 text-right text-[11px] font-t3-medium text-foreground-muted"\n- style={{ fontFamily: REVIEW_MONO_FONT_FAMILY }}\n- >\n- {lineNumber ?? ""}\n- </Text>\n- <View className="min-w-0 flex-1 shrink-0 px-1 py-1">\n+ <View className="min-w-0 flex-1 shrink-0 px-1 py-1" style={{ width: props.viewportWidth }}>\n <DiffTokenText\n tokens={props.tokens}\n fallback={props.line.content}\n@@ -272,62 +310,135 @@ const ReviewLineRow = memo(function ReviewLineRow(props: {\n );\n });\n \n+const ReviewLineGutter = memo(function ReviewLineGutter(props: {\n+ readonly change: ReviewRenderableLineRow["change"];\n+ readonly gutterWidth: number;\n+ readonly lineNumber: number | null;\n+}) {\n+ const lineNumberWidth = Math.max(0, props.gutterWidth - REVIEW_CHANGE_BAR_WIDTH);\n+\n+ return (\n+ <View className={cn("flex-row", changeTone(props.change))} style={{ width: props.gutterWidth }}>\n+ <ReviewChangeBar change={props.change} />\n+ <Text\n+ className="py-1 pr-1 text-right text-[11px] font-t3-medium text-foreground-muted"\n+ style={[{ fontFamily: REVIEW_MONO_FONT_FAMILY }, { width: lineNumberWidth }]}\n+ >\n+ {props.lineNumber ?? ""}\n+ </Text>\n+ </View>\n+ );\n+});\n+\n+const ReviewHunkGutter = memo(function ReviewHunkGutter(props: { readonly gutterWidth: number }) {\n+ return (\n+ <View\n+ className="border-b border-border/60 bg-sky-500/10"\n+ style={{ width: props.gutterWidth }}\n+ />\n+ );\n+});\n+\n const ReviewFileCard = memo(function ReviewFileCard(props: {\n readonly file: ReviewRenderableFile;\n readonly fileId: string;\n readonly expanded: boolean;\n+ readonly viewed: boolean;\n readonly viewportWidth: number;\n readonly onToggleFile: (fileId: string) => void;\n+ readonly onToggleViewed: (fileId: string) => void;\n }) {\n- const chrome = getFileHeaderChrome(props.file.changeType);\n+ const { expanded, file, fileId, onToggleFile, onToggleViewed, viewed, viewportWidth } = props;\n+ const chrome = getFileHeaderChrome(file.changeType);\n+ const iconColor = String(useThemeColor("--color-icon-muted"));\n+ const handleToggleFile = useCallback(() => {\n+ onToggleFile(fileId);\n+ }, [fileId, onToggleFile]);\n+ const handleToggleViewed = useCallback(() => {\n+ onToggleViewed(fileId);\n+ }, [fileId, onToggleViewed]);\n \n return (\n <View\n- className="border-b border-border/70 bg-card"\n- style={{\n- zIndex: 1,\n- width: props.viewportWidth,\n- shadowColor: "#000000",\n- shadowOpacity: 0.08,\n- shadowRadius: 10,\n- shadowOffset: { width: 0, height: 6 },\n- elevation: 4,\n- }}\n+ className="border-b border-border bg-card"\n+ style={{ height: REVIEW_FILE_HEADER_HEIGHT, overflow: "hidden", width: viewportWidth }}\n >\n- <Pressable className="flex-row items-center" onPress={() => props.onToggleFile(props.fileId)}>\n- <View className={cn("w-1 self-stretch", chrome.rail)} />\n- <View className="flex-1 flex-row items-center px-3 py-1.5">\n- <View className="size-7 items-center justify-center rounded-full bg-subtle">\n- <SymbolView\n- name={props.expanded ? "chevron.down" : "chevron.right"}\n- size={12}\n- tintColor="#8a8a8a"\n- type="monochrome"\n- />\n- </View>\n- <View className="ml-2 min-w-0 flex-1 flex-row items-center gap-2">\n- <View className={cn("size-2 rounded-full", chrome.dot)} />\n- <View className="min-w-0 flex-1">\n- <Text className="font-mono text-[13px] leading-[18px] text-foreground">\n- {props.file.path}\n+ <View className="min-h-[42px] flex-row items-center gap-1.5 px-2">\n+ <Pressable\n+ className="size-9 items-center justify-center"\n+ accessibilityRole="button"\n+ accessibilityLabel={expanded ? "Collapse file" : "Expand file"}\n+ hitSlop={{ bottom: 8, left: 8, right: 8, top: 8 }}\n+ onTouchEnd={handleToggleFile}\n+ >\n+ <SymbolView\n+ name={expanded ? "chevron.down" : "chevron.right"}\n+ size={13}\n+ tintColor={iconColor}\n+ type="monochrome"\n+ />\n+ </Pressable>\n+ <Pressable\n+ className="min-w-0 flex-1 flex-row items-center gap-2 py-2"\n+ accessibilityRole="button"\n+ accessibilityLabel={expanded ? "Collapse file" : "Expand file"}\n+ onTouchEnd={handleToggleFile}\n+ >\n+ <View className={cn("size-2.5 rounded-full", chrome.dot)} />\n+ <View className="min-w-0 flex-1">\n+ <Text\n+ className="font-mono text-[13px] leading-[18px] text-foreground"\n+ numberOfLines={1}\n+ >\n+ {file.path}\n+ </Text>\n+ {file.previousPath && file.previousPath !== file.path ? (\n+ <Text\n+ className="font-mono text-[10px] leading-[14px] text-foreground-muted"\n+ numberOfLines={1}\n+ >\n+ {file.previousPath}\n </Text>\n- {props.file.previousPath && props.file.previousPath !== props.file.path ? (\n- <Text className="font-mono text-[10px] leading-[14px] text-foreground-muted">\n- {props.file.previousPath}\n- </Text>\n+ ) : null}\n+ </View>\n+ </Pressable>\n+ <View className="flex-row items-center justify-end gap-1.5">\n+ <Text className="font-mono text-[12px] font-t3-bold text-rose-400">\n+ -{file.deletions}\n+ </Text>\n+ <Text className="font-mono text-[12px] font-t3-bold text-emerald-400">\n+ +{file.additions}\n+ </Text>\n+ <Pressable\n+ className="ml-0.5 min-h-[40px] min-w-[82px] flex-row items-center justify-center gap-1.5 px-1.5"\n+ accessibilityRole="checkbox"\n+ accessibilityState={{ checked: viewed }}\n+ accessibilityLabel={viewed ? "Mark file as unviewed" : "Mark file as viewed"}\n+ hitSlop={{ bottom: 8, left: 4, right: 8, top: 8 }}\n+ onTouchEnd={handleToggleViewed}\n+ >\n+ <View\n+ className={cn(\n+ "size-[18px] items-center justify-center rounded border",\n+ viewed ? "border-sky-500 bg-sky-500" : "border-icon-muted",\n+ )}\n+ >\n+ {viewed ? (\n+ <SymbolView name="checkmark" size={11} tintColor="#ffffff" type="monochrome" />\n ) : null}\n </View>\n- </View>\n- <View className="ml-3 flex-row items-center justify-end gap-2">\n- <Text className="font-mono text-[12px] font-t3-bold text-emerald-600 dark:text-emerald-300">\n- +{props.file.additions}\n- </Text>\n- <Text className="font-mono text-[12px] font-t3-bold text-rose-600 dark:text-rose-300">\n- -{props.file.deletions}\n+ <Text\n+ className={cn(\n+ "text-[12px] font-t3-medium",\n+ viewed ? "text-foreground" : "text-foreground-muted",\n+ )}\n+ numberOfLines={1}\n+ >\n+ Viewed\n </Text>\n- </View>\n+ </Pressable>\n </View>\n- </Pressable>\n+ </View>\n </View>\n );\n });\n@@ -342,7 +453,11 @@ const ReviewFileSuppressedBody = memo(function ReviewFileSuppressedBody(props: {\n return (\n <View\n className="gap-2 border-b border-border bg-card px-4 py-3"\n- style={{ minWidth: props.viewportWidth }}\n+ style={{\n+ height: REVIEW_SUPPRESSED_ROW_HEIGHT,\n+ overflow: "hidden",\n+ width: props.viewportWidth,\n+ }}\n >\n <Text className="text-[12px] leading-[18px] text-foreground-muted">{props.message}</Text>\n {props.actionLabel && props.onLoadDiffFile ? (\n@@ -364,10 +479,13 @@ const ReviewHunkRow = memo(function ReviewHunkRow(props: {\n }) {\n return (\n <View\n- className="border-b border-border/60 bg-sky-500/10 px-2 py-2"\n- style={{ minWidth: props.viewportWidth }}\n+ className="border-b border-border/60 bg-sky-500/10 py-2"\n+ style={{ height: REVIEW_HUNK_ROW_HEIGHT, width: props.viewportWidth, overflow: "hidden" }}\n >\n- <Text className="font-mono text-[12px] leading-[18px] text-sky-700 dark:text-sky-300">\n+ <Text\n+ className="px-2 font-mono text-[12px] leading-[18px] text-sky-700 dark:text-sky-300"\n+ numberOfLines={1}\n+ >\n {props.header}\n {props.context ? ` ${props.context}` : ""}\n </Text>\n@@ -375,6 +493,61 @@ const ReviewHunkRow = memo(function ReviewHunkRow(props: {\n );\n });\n \n+const ReviewCodePanRow = memo(function ReviewCodePanRow(props: {\n+ readonly contentWidth: number;\n+ readonly horizontalOffset: SharedValue<number>;\n+ readonly gutterWidth?: number;\n+ readonly viewportWidth: number;\n+ readonly leftGutter?: ReactElement;\n+ readonly children: ReactElement;\n+}) {\n+ const {\n+ children,\n+ contentWidth,\n+ gutterWidth = 0,\n+ horizontalOffset,\n+ leftGutter,\n+ viewportWidth,\n+ } = props;\n+ const dragStartOffset = useSharedValue(0);\n+ const visibleContentWidth = leftGutter ? viewportWidth - gutterWidth : viewportWidth;\n+ const maxOffset = Math.max(0, contentWidth - visibleContentWidth);\n+\n+ const panGesture = useMemo(\n+ () =>\n+ Gesture.Pan()\n+ .activeOffsetX([-8, 8])\n+ .failOffsetY([-10, 10])\n+ .onBegin(() => {\n+ dragStartOffset.value = horizontalOffset.value;\n+ })\n+ .onUpdate((event) => {\n+ "worklet";\n+ const nextOffset = dragStartOffset.value - event.translationX;\n+ horizontalOffset.value = Math.min(maxOffset, Math.max(0, nextOffset));\n+ }),\n+ [dragStartOffset, horizontalOffset, maxOffset],\n+ );\n+\n+ const contentStyle = useAnimatedStyle(\n+ () => ({\n+ transform: [{ translateX: -horizontalOffset.value }],\n+ }),\n+ [horizontalOffset],\n+ );\n+\n+ return (\n+ <GestureDetector gesture={panGesture}>\n+ <View style={{ flexDirection: "row", overflow: "hidden", width: viewportWidth }}>\n+ {leftGutter ?? null}\n+ <View style={{ flex: 1, overflow: "hidden" }}>\n+ <Animated.View style={[{ width: contentWidth }, contentStyle]}>{children}</Animated.View>\n+ </View>\n+ </View>\n+ </GestureDetector>\n+ );\n+});\n+\n const ReviewNotice = memo(function ReviewNotice(props: { readonly notice: string }) {\n return (\n <View className="border-b border-amber-200 bg-amber-50 px-4 py-3 dark:border-amber-900/60 dark:bg-amber-950/40">\n@@ -454,15 +627,19 @@ export function ReviewSheet() {\n const [highlightedFilesById, setHighlightedFilesById] = useState<\n Record<string, ReviewHighlightedFile | null>\n >({});\n- const [visibleFileIds, setVisibleFileIds] = useState<ReadonlyArray<string>>([]);\n+ const deferredHighlightedFilesById = useDeferredValue(highlightedFilesById);\n+ const [localExpandedFileIdsBySection, setLocalExpandedFileIdsBySection] = useState<\n+ Record<string, ReadonlyArray<string>>\n+ >({});\n+ const [localViewedFileIdsBySection, setLocalViewedFileIdsBySection] = useState<\n+ Record<string, ReadonlyArray<string>>\n+ >({});\n const activeCommentTarget = useReviewCommentTarget();\n const selectedTheme = (colorScheme === "dark" ? "dark" : "light") satisfies ReviewDiffTheme;\n- const highlightQueueRef = useRef<string[]>([]);\n- const highlightRequestedFileIdsRef = useRef<Set<string>>(new Set());\n- const highlightQueueGenerationRef = useRef(0);\n- const highlightQueueActiveRef = useRef(false);\n- const highlightableFilesByIdRef = useRef<ReadonlyMap<string, ReviewRenderableFile>>(new Map());\n- const selectedThemeRef = useRef<ReviewDiffTheme>(selectedTheme);\n+ const reviewHighlighter = useReviewHighlighterStatus();\n+ const highlightRunIdRef = useRef(0);\n+ const highlightableFilesRef = useRef<ReadonlyArray<ReviewRenderableFile>>([]);\n+ const horizontalOffsetByFileIdRef = useRef<Map<string, SharedValue<number>>>(new Map());\n const { selectedThreadCwd } = useSelectedThreadWorktree();\n \n const cwd = selectedThreadCwd;\n@@ -498,11 +675,13 @@ export function ReviewSheet() {\n const topContentInset = insets.top + IOS_NAV_BAR_HEIGHT;\n const parsedDiff = useMemo(\n () =>\n- getCachedReviewParsedDiff({\n- threadKey: reviewCache.threadKey,\n- sectionId: selectedSection?.id ?? null,\n- diff: selectedSection?.diff,\n- }),\n+ measureReviewWork("parse-diff", () =>\n+ getCachedReviewParsedDiff({\n+ threadKey: reviewCache.threadKey,\n+ sectionId: selectedSection?.id ?? null,\n+ diff: selectedSection?.diff,\n+ }),\n+ ),\n [reviewCache.threadKey, selectedSection?.diff, selectedSection?.id],\n );\n const headerDiffSummary = useMemo(() => formatHeaderDiffSummary(parsedDiff), [parsedDiff]);\n@@ -510,14 +689,53 @@ export function ReviewSheet() {\n () => countReviewCommentContexts(draftMessage),\n [draftMessage],\n );\n+ const viewportWidth = Math.max(width, 280);\n+\n+ useEffect(() => {\n+ if (!selectedSection?.id || parsedDiff.kind !== "files") {\n+ return;\n+ }\n+\n+ setLocalExpandedFileIdsBySection((current) => {\n+ if (current[selectedSection.id] !== undefined) {\n+ return current;\n+ }\n+\n+ return {\n+ ...current,\n+ [selectedSection.id]: getValidReviewExpandedFileIds(\n+ parsedDiff.files,\n+ reviewCache.expandedFileIdsBySection[selectedSection.id],\n+ ),\n+ };\n+ });\n+\n+ setLocalViewedFileIdsBySection((current) => {\n+ if (current[selectedSection.id] !== undefined) {\n+ return current;\n+ }\n+\n+ return {\n+ ...current,\n+ [selectedSection.id]: reviewCache.viewedFileIdsBySection[selectedSection.id] ?? [],\n+ };\n+ });\n+ }, [\n+ parsedDiff,\n+ reviewCache.expandedFileIdsBySection,\n+ reviewCache.viewedFileIdsBySection,\n+ selectedSection?.id,\n+ ]);\n \n const expandedFileIds = useMemo(\n () =>\n selectedSection?.id && parsedDiff.kind === "files"\n- ? (reviewCache.expandedFileIdsBySection[selectedSection.id] ??\n- getDefaultExpandedFileIds(parsedDiff.files))\n+ ? getValidReviewExpandedFileIds(\n+ parsedDiff.files,\n+ localExpandedFileIdsBySection[selectedSection.id],\n+ )\n : [],\n- [parsedDiff, reviewCache.expandedFileIdsBySection, selectedSection?.id],\n+ [localExpandedFileIdsBySection, parsedDiff, selectedSection?.id],\n );\n const revealedLargeFileIds = useMemo(\n () =>\n@@ -526,47 +744,96 @@ export function ReviewSheet() {\n : [],\n [reviewCache.revealedLargeFileIdsBySection, selectedSection?.id],\n );\n+ const viewedFileIds = useMemo(\n+ () => (selectedSection?.id ? (localViewedFileIdsBySection[selectedSection.id] ?? []) : []),\n+ [localViewedFileIdsBySection, selectedSection?.id],\n+ );\n+ const viewedFileIdSet = useMemo(() => new Set(viewedFileIds), [viewedFileIds]);\n const reviewListItems = useMemo(\n () =>\n selectedSection && parsedDiff.kind === "files"\n- ? buildReviewListItems({\n- files: parsedDiff.files,\n- expandedFileIds,\n- revealedLargeFileIds,\n- })\n+ ? measureReviewWork("build-list-items", () =>\n+ buildReviewListItems({\n+ files: parsedDiff.files,\n+ expandedFileIds,\n+ revealedLargeFileIds,\n+ }),\n+ )\n : [],\n [expandedFileIds, parsedDiff, revealedLargeFileIds, selectedSection],\n );\n- const reviewFileById = useMemo(() => {\n+ const reviewLineRowsByFileId = useMemo(() => {\n if (parsedDiff.kind !== "files") {\n- return new Map<string, ReviewRenderableFile>();\n+ return new Map<string, ReadonlyArray<ReviewRenderableLineRow>>();\n }\n \n- return new Map(parsedDiff.files.map((file) => [file.id, file] as const));\n+ return measureReviewWork(\n+ "index-line-rows",\n+ () =>\n+ new Map(\n+ parsedDiff.files.map((file) => [\n+ file.id,\n+ file.rows.filter((row): row is ReviewRenderableLineRow => row.kind === "line"),\n+ ]),\n+ ),\n+ );\n }, [parsedDiff]);\n- const reviewLineRowsByFileId = useMemo(() => {\n+ const reviewContentWidthByFileId = useMemo(() => {\n if (parsedDiff.kind !== "files") {\n- return new Map<string, ReadonlyArray<ReviewRenderableLineRow>>();\n+ return new Map<string, number>();\n+ }\n+\n+ return measureReviewWork(\n+ "measure-file-widths",\n+ () =>\n+ new Map(\n+ parsedDiff.files.map((file) => [\n+ file.id,\n+ computeReviewFileContentWidth(\n+ file.rows,\n+ viewportWidth,\n+ computeReviewFileGutterWidth(file.rows),\n+ ),\n+ ]),\n+ ),\n+ );\n+ }, [parsedDiff, viewportWidth]);\n+ const reviewGutterWidthByFileId = useMemo(() => {\n+ if (parsedDiff.kind !== "files") {\n+ return new Map<string, number>();\n }\n \n return new Map(\n- parsedDiff.files.map((file) => [\n- file.id,\n- file.rows.filter((row): row is ReviewRenderableLineRow => row.kind === "line"),\n- ]),\n+ parsedDiff.files.map((file) => [file.id, computeReviewFileGutterWidth(file.rows)]),\n );\n }, [parsedDiff]);\n- const reviewLineIndexByRowId = useMemo(() => {\n- const map = new Map<string, number>();\n+ const getReviewFileHorizontalOffset = useCallback((fileId: string) => {\n+ let offset = horizontalOffsetByFileIdRef.current.get(fileId);\n+ if (!offset) {\n+ offset = makeMutable(0);\n+ horizontalOffsetByFileIdRef.current.set(fileId, offset);\n+ }\n \n- reviewLineRowsByFileId.forEach((rows) => {\n- rows.forEach((row, index) => {\n- map.set(row.id, index);\n- });\n- });\n+ return offset;\n+ }, []);\n+ useEffect(() => {\n+ const knownFileIds =\n+ parsedDiff.kind === "files" ? new Set(parsedDiff.files.map((file) => file.id)) : new Set();\n \n- return map;\n- }, [reviewLineRowsByFileId]);\n+ horizontalOffsetByFileIdRef.current.forEach((offset, fileId) => {\n+ if (!knownFileIds.has(fileId)) {\n+ horizontalOffsetByFileIdRef.current.delete(fileId);\n+ return;\n+ }\n+\n+ const contentWidth = reviewContentWidthByFileId.get(fileId) ?? viewportWidth;\n+ const gutterWidth = reviewGutterWidthByFileId.get(fileId) ?? 0;\n+ offset.value = Math.min(\n+ offset.value,\n+ Math.max(0, contentWidth - (viewportWidth - gutterWidth)),\n+ );\n+ });\n+ }, [parsedDiff, reviewContentWidthByFileId, reviewGutterWidthByFileId, viewportWidth]);\n const highlightableFiles = useMemo(() => {\n if (parsedDiff.kind !== "files") {\n return [] as ReadonlyArray<ReviewRenderableFile>;\n@@ -587,59 +854,13 @@ export function ReviewSheet() {\n );\n });\n }, [expandedFileIds, parsedDiff, revealedLargeFileIds]);\n- const highlightableFileIds = useMemo(\n- () => new Set(highlightableFiles.map((file) => file.id)),\n+ const highlightableFilesKey = useMemo(\n+ () => highlightableFiles.map((file) => `${file.id}:${file.cacheKey}`).join("\\n"),\n [highlightableFiles],\n );\n- const priorityHighlightFileIds = useMemo(() => {\n- if (parsedDiff.kind !== "files" || highlightableFiles.length === 0) {\n- return [] as ReadonlyArray<string>;\n- }\n-\n- const fileIdsInPriorityOrder =\n- visibleFileIds.length > 0\n- ? visibleFileIds.filter((fileId) => highlightableFileIds.has(fileId))\n- : parsedDiff.files\n- .slice(0, REVIEW_INITIAL_HIGHLIGHT_FILE_COUNT)\n- .map((file) => file.id)\n- .filter((fileId) => highlightableFileIds.has(fileId));\n-\n- if (fileIdsInPriorityOrder.length === 0) {\n- return [] as ReadonlyArray<string>;\n- }\n-\n- const firstVisibleIndex = parsedDiff.files.findIndex(\n- (file) => file.id === fileIdsInPriorityOrder[0],\n- );\n- const lastVisibleIndex = parsedDiff.files.findIndex(\n- (file) => file.id === fileIdsInPriorityOrder[fileIdsInPriorityOrder.length - 1],\n- );\n-\n- if (firstVisibleIndex < 0 || lastVisibleIndex < 0) {\n- return fileIdsInPriorityOrder;\n- }\n-\n- const startIndex = Math.max(0, firstVisibleIndex - REVIEW_HIGHLIGHT_BACKTRACK_COUNT);\n- const endIndex = Math.min(\n- parsedDiff.files.length - 1,\n- lastVisibleIndex + REVIEW_HIGHLIGHT_LOOKAHEAD_COUNT,\n- );\n-\n- const queuedIds: string[] = [];\n- for (let index = startIndex; index <= endIndex; index += 1) {\n- const fileId = parsedDiff.files[index]?.id;\n- if (fileId && highlightableFileIds.has(fileId)) {\n- queuedIds.push(fileId);\n- }\n- }\n-\n- return queuedIds;\n- }, [highlightableFileIds, highlightableFiles.length, parsedDiff, visibleFileIds]);\n- const viewportWidth = Math.max(width, 280);\n- const reviewListContentWidth = useMemo(\n- () => computeReviewListContentWidth(reviewListItems, viewportWidth),\n- [reviewListItems, viewportWidth],\n- );\n+ useEffect(() => {\n+ highlightableFilesRef.current = highlightableFiles;\n+ }, [highlightableFiles]);\n const loadGitDiffs = useCallback(async () => {\n if (!cwd) {\n return;\n@@ -714,100 +935,6 @@ export function ReviewSheet() {\n void loadGitDiffs();\n }, [loadGitDiffs]);\n \n- useEffect(() => {\n- selectedThemeRef.current = selectedTheme;\n- }, [selectedTheme]);\n-\n- useEffect(() => {\n- highlightableFilesByIdRef.current = new Map(highlightableFiles.map((file) => [file.id, file]));\n- }, [highlightableFiles]);\n-\n- const startHighlightQueueRunner = useCallback(function startHighlightQueueRunner() {\n- if (highlightQueueActiveRef.current) {\n- return;\n- }\n-\n- const generation = highlightQueueGenerationRef.current;\n- highlightQueueActiveRef.current = true;\n-\n- void (async () => {\n- try {\n- while (generation === highlightQueueGenerationRef.current) {\n- const nextFileId = highlightQueueRef.current.shift();\n- if (!nextFileId) {\n- break;\n- }\n-\n- const file = highlightableFilesByIdRef.current.get(nextFileId);\n- if (!file) {\n- continue;\n- }\n-\n- const theme = selectedThemeRef.current;\n- const cached = getCachedHighlightedReviewFile(file, theme);\n- if (cached) {\n- logReviewDiffDiagnostic("using cached highlighted file", {\n- fileId: file.id,\n- filePath: file.path,\n- theme,\n- });\n- setHighlightedFilesById((current) =>\n- current[file.id] === cached ? current : { ...current, [file.id]: cached },\n- );\n- continue;\n- }\n-\n- logReviewDiffDiagnostic("requesting highlighted file", {\n- fileId: file.id,\n- filePath: file.path,\n- theme,\n- });\n-\n- try {\n- await new Promise<void>((resolve) => {\n- InteractionManager.runAfterInteractions(() => resolve());\n- });\n- const result = await highlightReviewFile(file, theme);\n- if (generation !== highlightQueueGenerationRef.current) {\n- logReviewDiffDiagnostic("discarding highlighted file after cancellation", {\n- fileId: file.id,\n- filePath: file.path,\n- });\n- return;\n- }\n-\n- logReviewDiffDiagnostic("received highlighted file", {\n- fileId: file.id,\n- filePath: file.path,\n- additionLines: result.additionLines.length,\n- deletionLines: result.deletionLines.length,\n- });\n- setHighlightedFilesById((current) => {\n- if (current[file.id] === result) {\n- return current;\n- }\n- return { ...current, [file.id]: result };\n- });\n- } catch (error) {\n- logReviewDiffDiagnostic("highlight request failed", {\n- fileId: file.id,\n- filePath: file.path,\n- error: error instanceof Error ? error.message : String(error),\n- });\n- }\n- }\n- } finally {\n- highlightQueueActiveRef.current = false;\n- if (\n- generation === highlightQueueGenerationRef.current &&\n- highlightQueueRef.current.length > 0\n- ) {\n- startHighlightQueueRunner();\n- }\n- }\n- })();\n- }, []);\n-\n useEffect(() => {\n if (reviewSections.length === 0) {\n return;\n@@ -854,15 +981,15 @@ export function ReviewSheet() {\n }\n \n updateReviewExpandedFileIds(reviewCache.threadKey, selectedSection.id, (existing) => {\n- if (existing !== undefined) {\n- const validIds = existing.filter((id) => parsedDiff.files.some((file) => file.id === id));\n- if (validIds.length === existing.length) {\n- return existing;\n- }\n- return validIds;\n+ const validIds = getValidReviewExpandedFileIds(parsedDiff.files, existing);\n+ if (\n+ existing !== undefined &&\n+ validIds.length === existing.length &&\n+ validIds.every((id, index) => id === existing[index])\n+ ) {\n+ return existing;\n }\n-\n- return getDefaultExpandedFileIds(parsedDiff.files);\n+ return validIds;\n });\n }, [parsedDiff, reviewCache.threadKey, selectedSection?.id]);\n \n@@ -887,11 +1014,7 @@ export function ReviewSheet() {\n \n useEffect(() => {\n setHighlightedFilesById({});\n- setVisibleFileIds([]);\n- highlightQueueGenerationRef.current += 1;\n- highlightQueueRef.current = [];\n- highlightRequestedFileIdsRef.current = new Set();\n- highlightQueueActiveRef.current = false;\n+ highlightRunIdRef.current += 1;\n clearReviewHighlightFileCache();\n loggedMissingReviewTokenKeys.clear();\n logReviewDiffDiagnostic("reset highlighted files", {\n@@ -905,15 +1028,23 @@ export function ReviewSheet() {\n return;\n }\n \n+ markReviewEvent("parsed-diff-ready", {\n+ sectionId: selectedSection?.id ?? null,\n+ fileCount: parsedDiff.fileCount,\n+ additions: parsedDiff.additions,\n+ deletions: parsedDiff.deletions,\n+ renderedItems: reviewListItems.length,\n+ });\n logReviewDiffDiagnostic("parsed diff files", {\n selectedSectionId: selectedSection?.id ?? null,\n fileCount: parsedDiff.fileCount,\n renderableFileCount: parsedDiff.files.length,\n });\n- }, [parsedDiff, selectedSection?.id]);\n+ }, [parsedDiff, reviewListItems.length, selectedSection?.id]);\n \n useEffect(() => {\n- if (priorityHighlightFileIds.length === 0) {\n+ const files = highlightableFilesRef.current;\n+ if (files.length === 0) {\n logReviewDiffDiagnostic("no highlightable files", {\n selectedSectionId: selectedSection?.id ?? null,\n parsedDiffKind: parsedDiff.kind,\n@@ -922,33 +1053,98 @@ export function ReviewSheet() {\n return;\n }\n \n- const queuedFileIds: string[] = [];\n- priorityHighlightFileIds.forEach((fileId) => {\n- if (highlightRequestedFileIdsRef.current.has(fileId)) {\n- return;\n- }\n-\n- const file = highlightableFilesByIdRef.current.get(fileId);\n- if (!file) {\n- return;\n- }\n-\n- highlightRequestedFileIdsRef.current.add(fileId);\n- highlightQueueRef.current.push(fileId);\n- queuedFileIds.push(fileId);\n- });\n-\n- if (queuedFileIds.length === 0) {\n+ if (reviewHighlighter.status !== "ready") {\n+ logReviewDiffDiagnostic("waiting for highlighter provider", {\n+ selectedSectionId: selectedSection?.id ?? null,\n+ status: reviewHighlighter.status,\n+ error: reviewHighlighter.error,\n+ });\n return;\n }\n \n- logReviewDiffDiagnostic("scheduling file highlights", {\n+ const runId = highlightRunIdRef.current;\n+ let cancelled = false;\n+\n+ logReviewDiffDiagnostic("streaming file highlights", {\n selectedSectionId: selectedSection?.id ?? null,\n- fileCount: queuedFileIds.length,\n- fileIds: queuedFileIds,\n+ fileCount: files.length,\n });\n- startHighlightQueueRunner();\n- }, [parsedDiff.kind, priorityHighlightFileIds, selectedSection?.id, startHighlightQueueRunner]);\n+\n+ void (async () => {\n+ for (const file of files) {\n+ if (cancelled || runId !== highlightRunIdRef.current) {\n+ return;\n+ }\n+\n+ const cached = getCachedHighlightedReviewFile(file, selectedTheme);\n+ if (cached) {\n+ setHighlightedFilesById((current) =>\n+ current[file.id] === cached ? current : { ...current, [file.id]: cached },\n+ );\n+ continue;\n+ }\n+\n+ logReviewDiffDiagnostic("requesting highlighted file", {\n+ fileId: file.id,\n+ filePath: file.path,\n+ theme: selectedTheme,\n+ });\n+\n+ try {\n+ const highlightStartedAt = performance.now();\n+ const result = await streamHighlightReviewFile(file, selectedTheme, (progress) => {\n+ if (cancelled || runId !== highlightRunIdRef.current) {\n+ return;\n+ }\n+\n+ if (!progress.complete) {\n+ return;\n+ }\n+\n+ logReviewDiffDiagnostic("received streamed highlighted file", {\n+ fileId: file.id,\n+ filePath: file.path,\n+ highlightedLineCount: progress.highlightedLineCount,\n+ durationMs: Math.round(performance.now() - highlightStartedAt),\n+ });\n+ });\n+\n+ if (cancelled || runId !== highlightRunIdRef.current) {\n+ return;\n+ }\n+\n+ logReviewDiffDiagnostic("received highlighted file", {\n+ fileId: file.id,\n+ filePath: file.path,\n+ additionLines: result.additionLines.length,\n+ deletionLines: result.deletionLines.length,\n+ });\n+ setHighlightedFilesById((current) =>\n+ current[file.id] === result ? current : { ...current, [file.id]: result },\n+ );\n+ } catch (error) {\n+ logReviewDiffDiagnostic("highlight request failed", {\n+ fileId: file.id,\n+ filePath: file.path,\n+ error: error instanceof Error ? error.message : String(error),\n+ });\n+ }\n+\n+ await waitForReviewDelay(0);\n+ }\n+ })();\n+\n+ return () => {\n+ cancelled = true;\n+ };\n+ }, [\n+ highlightableFilesKey,\n+ parsedDiff.kind,\n+ reviewHighlighter.error,\n+ reviewHighlighter.status,\n+ selectedSection?.id,\n+ selectedTheme,\n+ ]);\n \n const refreshSelectedSection = useCallback(async () => {\n if (!selectedSection) {\n@@ -968,20 +1164,68 @@ export function ReviewSheet() {\n \n const handleToggleExpandedFile = useCallback(\n (fileId: string) => {\n- if (!reviewCache.threadKey || !selectedSection?.id || parsedDiff.kind !== "files") {\n+ if (!selectedSection?.id || parsedDiff.kind !== "files") {\n return;\n }\n \n- updateReviewExpandedFileIds(reviewCache.threadKey, selectedSection.id, (existing) => {\n- const currentIds = existing ?? getDefaultExpandedFileIds(parsedDiff.files);\n- return currentIds.includes(fileId)\n+ const sectionId = selectedSection.id;\n+\n+ setLocalExpandedFileIdsBySection((current) => {\n+ const currentIds = getValidReviewExpandedFileIds(parsedDiff.files, current[sectionId]);\n+ const nextIds = currentIds.includes(fileId)\n ? currentIds.filter((id) => id !== fileId)\n : [...currentIds, fileId];\n+\n+ return {\n+ ...current,\n+ [sectionId]: nextIds,\n+ };\n });\n+\n+ if (reviewCache.threadKey) {\n+ updateReviewExpandedFileIds(reviewCache.threadKey, sectionId, (existing) => {\n+ const currentIds = getValidReviewExpandedFileIds(parsedDiff.files, existing);\n+ return currentIds.includes(fileId)\n+ ? currentIds.filter((id) => id !== fileId)\n+ : [...currentIds, fileId];\n+ });\n+ }\n },\n [parsedDiff, reviewCache.threadKey, selectedSection?.id],\n );\n \n+ const handleToggleViewedFile = useCallback(\n+ (fileId: string) => {\n+ if (!selectedSection?.id) {\n+ return;\n+ }\n+\n+ const sectionId = selectedSection.id;\n+\n+ setLocalViewedFileIdsBySection((current) => {\n+ const currentIds = current[sectionId] ?? [];\n+ const nextIds = currentIds.includes(fileId)\n+ ? currentIds.filter((id) => id !== fileId)\n+ : [...currentIds, fileId];\n+\n+ return {\n+ ...current,\n+ [sectionId]: nextIds,\n+ };\n+ });\n+\n+ if (reviewCache.threadKey) {\n+ updateReviewViewedFileIds(reviewCache.threadKey, sectionId, (existing) => {\n+ const currentIds = existing ?? [];\n+ return currentIds.includes(fileId)\n+ ? currentIds.filter((id) => id !== fileId)\n+ : [...currentIds, fileId];\n+ });\n+ }\n+ },\n+ [reviewCache.threadKey, selectedSection?.id],\n+ );\n+\n const handleRevealLargeDiff = useCallback(\n (fileId: string) => {\n if (!reviewCache.threadKey || !selectedSection?.id) {\n@@ -1080,35 +1324,6 @@ export function ReviewSheet() {\n \n return <>{children}</>;\n }, [error, parsedDiffNotice]);\n- const stickyHeaderIndices = useMemo(() => {\n- const itemOffset = listHeader ? 1 : 0;\n-\n- return reviewListItems.flatMap((item, index) =>\n- item.kind === "file-header" ? [index + itemOffset] : [],\n- );\n- }, [listHeader, reviewListItems]);\n-\n- const viewabilityConfigRef = useRef({\n- itemVisiblePercentThreshold: 10,\n- });\n- const onViewableItemsChangedRef = useRef(\n- ({\n- viewableItems,\n- }: {\n- readonly viewableItems: Array<ViewToken<ReviewListItem>>;\n- readonly changed: Array<ViewToken<ReviewListItem>>;\n- }) => {\n- const nextVisibleFileIds = Array.from(\n- new Set(\n- viewableItems\n- .filter((token) => token.isViewable && token.item !== undefined)\n- .map((token) => token.item.fileId),\n- ),\n- );\n-\n- setVisibleFileIds(nextVisibleFileIds);\n- },\n- );\n \n const renderReviewListItem = useCallback(\n ({ item }: ListRenderItemInfo<ReviewListItem>) => {\n@@ -1116,112 +1331,142 @@ export function ReviewSheet() {\n return null;\n }\n \n+ let renderedItem: ReactElement | null = null;\n switch (item.kind) {\n case "file-header":\n- return (\n+ renderedItem = (\n <ReviewFileCard\n file={item.file}\n fileId={item.fileId}\n expanded={item.expanded}\n- viewportWidth={reviewListContentWidth}\n+ viewed={viewedFileIdSet.has(item.fileId)}\n+ viewportWidth={viewportWidth}\n onToggleFile={handleToggleExpandedFile}\n+ onToggleViewed={handleToggleViewedFile}\n />\n );\n+ break;\n case "file-suppressed":\n- return (\n+ renderedItem = (\n <ReviewFileSuppressedBody\n message={item.message}\n actionLabel={item.actionLabel}\n fileId={item.fileId}\n- viewportWidth={reviewListContentWidth}\n+ viewportWidth={viewportWidth}\n onLoadDiffFile={handleRevealLargeDiff}\n />\n );\n- case "hunk":\n- return (\n- <ReviewHunkRow\n- header={item.row.header}\n- context={item.row.context}\n- viewportWidth={reviewListContentWidth}\n- />\n+ break;\n+ case "hunk": {\n+ const contentWidth = reviewContentWidthByFileId.get(item.fileId) ?? viewportWidth;\n+ const gutterWidth = reviewGutterWidthByFileId.get(item.fileId) ?? 0;\n+\n+ renderedItem = (\n+ <ReviewCodePanRow\n+ key={item.id}\n+ contentWidth={contentWidth}\n+ gutterWidth={gutterWidth}\n+ horizontalOffset={getReviewFileHorizontalOffset(item.fileId)}\n+ leftGutter={<ReviewHunkGutter gutterWidth={gutterWidth} />}\n+ viewportWidth={viewportWidth}\n+ >\n+ <ReviewHunkRow\n+ header={item.row.header}\n+ context={item.row.context}\n+ viewportWidth={contentWidth}\n+ />\n+ </ReviewCodePanRow>\n );\n+ break;\n+ }\n case "line": {\n- const file = reviewFileById.get(item.fileId);\n- if (!file) {\n- return null;\n- }\n-\n- const fileLineRows = reviewLineRowsByFileId.get(file.id) ?? [];\n- const lineIndex = reviewLineIndexByRowId.get(item.row.id);\n- if (lineIndex === undefined) {\n- return null;\n- }\n-\n+ const fileLineRows = reviewLineRowsByFileId.get(item.file.id) ?? [];\n const pendingSelectionForFile =\n pendingCommentSelection &&\n pendingCommentSelection.sectionTitle === selectedSection.title &&\n- pendingCommentSelection.filePath === file.path\n+ pendingCommentSelection.filePath === item.file.path\n ? pendingCommentSelection\n : null;\n const selectedTargetForFile =\n activeCommentTarget &&\n activeCommentTarget.sectionTitle === selectedSection.title &&\n- activeCommentTarget.filePath === file.path\n+ activeCommentTarget.filePath === item.file.path\n ? activeCommentTarget\n : null;\n const highlightedFile =\n- highlightedFilesById[file.id] ??\n- getCachedHighlightedReviewFile(file, selectedTheme) ??\n+ deferredHighlightedFilesById[item.file.id] ??\n+ getCachedHighlightedReviewFile(item.file, selectedTheme) ??\n null;\n+ const contentWidth = reviewContentWidthByFileId.get(item.fileId) ?? viewportWidth;\n+ const gutterWidth = reviewGutterWidthByFileId.get(item.fileId) ?? 0;\n \n if (highlightedFile === null) {\n- const missingTokenKey = `${selectedSection.id}:${file.id}`;\n+ const missingTokenKey = `${selectedSection.id}:${item.file.id}`;\n if (!loggedMissingReviewTokenKeys.has(missingTokenKey)) {\n loggedMissingReviewTokenKeys.add(missingTokenKey);\n logReviewDiffDiagnostic("rendering file without tokens", {\n sectionId: selectedSection.id,\n- fileId: file.id,\n- filePath: file.path,\n- highlightedFileKnownInState: highlightedFilesById[file.id] !== undefined,\n+ fileId: item.file.id,\n+ filePath: item.file.path,\n+ highlightedFileKnownInState:\n+ deferredHighlightedFilesById[item.file.id] !== undefined,\n });\n }\n }\n \n const selectionState =\n- pendingSelectionForFile?.anchorIndex === lineIndex\n+ pendingSelectionForFile?.anchorIndex === item.lineIndex\n ? ("anchor" as const)\n : selectedTargetForFile &&\n- lineIndex >= selectedTargetForFile.startIndex &&\n- lineIndex <= selectedTargetForFile.endIndex\n+ item.lineIndex >= selectedTargetForFile.startIndex &&\n+ item.lineIndex <= selectedTargetForFile.endIndex\n ? ("selected" as const)\n : null;\n \n- return (\n- <ReviewLineRow\n- line={item.row}\n- tokens={getHighlightedTokensForLine(item.row, highlightedFile)}\n- viewportWidth={reviewListContentWidth}\n- selectionState={selectionState}\n- onComment={() =>\n- handlePressLine({\n- sectionTitle: selectedSection.title,\n- filePath: file.path,\n- lines: fileLineRows,\n- lineIndex,\n- })\n- }\n- onStartRangeSelection={() =>\n- handleStartRangeSelection({\n- sectionTitle: selectedSection.title,\n- filePath: file.path,\n- lines: fileLineRows,\n- lineIndex,\n- })\n+ renderedItem = (\n+ <ReviewCodePanRow\n+ key={item.id}\n+ contentWidth={contentWidth}\n+ gutterWidth={gutterWidth}\n+ horizontalOffset={getReviewFileHorizontalOffset(item.fileId)}\n+ leftGutter={\n+ <ReviewLineGutter\n+ change={item.row.change}\n+ gutterWidth={gutterWidth}\n+ lineNumber={getReviewUnifiedLineNumber(item.row)}\n+ />\n }\n- />\n+ viewportWidth={viewportWidth}\n+ >\n+ <ReviewLineRow\n+ line={item.row}\n+ tokens={getHighlightedTokensForLine(item.row, highlightedFile)}\n+ viewportWidth={contentWidth}\n+ selectionState={selectionState}\n+ onComment={() =>\n+ handlePressLine({\n+ sectionTitle: selectedSection.title,\n+ filePath: item.file.path,\n+ lines: fileLineRows,\n+ lineIndex: item.lineIndex,\n+ })\n+ }\n+ onStartRangeSelection={() =>\n+ handleStartRangeSelection({\n+ sectionTitle: selectedSection.title,\n+ filePath: item.file.path,\n+ lines: fileLineRows,\n+ lineIndex: item.lineIndex,\n+ })\n+ }\n+ />\n+ </ReviewCodePanRow>\n );\n+ break;\n }\n }\n+\n+ return renderedItem;\n },\n [\n activeCommentTarget,\n@@ -1229,14 +1474,17 @@ export function ReviewSheet() {\n handleRevealLargeDiff,\n handleStartRangeSelection,\n handleToggleExpandedFile,\n- highlightedFilesById,\n+ handleToggleViewedFile,\n+ getReviewFileHorizontalOffset,\n+ deferredHighlightedFilesById,\n pendingCommentSelection,\n- reviewFileById,\n- reviewLineIndexByRowId,\n+ reviewContentWidthByFileId,\n+ reviewGutterWidthByFileId,\n reviewLineRowsByFileId,\n- reviewListContentWidth,\n selectedSection,\n selectedTheme,\n+ viewedFileIdSet,\n+ viewportWidth,\n ],\n );\n \n@@ -1374,27 +1622,20 @@ export function ReviewSheet() {\n <View className="flex-1 bg-sheet">\n {selectedSection && parsedDiff.kind === "files" ? (\n <FlatList\n- style={{ flex: 1 }}\n+ style={{ flex: 1, width: viewportWidth }}\n contentInsetAdjustmentBehavior="never"\n- contentInset={{ top: topContentInset }}\n- contentOffset={{ x: 0, y: -topContentInset }}\n- scrollIndicatorInsets={{ top: topContentInset }}\n data={reviewListItems}\n renderItem={renderReviewListItem}\n keyExtractor={(item) => item.id}\n+ initialNumToRender={20}\n+ maxToRenderPerBatch={20}\n+ updateCellsBatchingPeriod={16}\n+ windowSize={5}\n+ removeClippedSubviews={false}\n keyboardShouldPersistTaps="handled"\n ListHeaderComponent={listHeader}\n- stickyHeaderIndices={stickyHeaderIndices}\n- removeClippedSubviews={false}\n- initialNumToRender={24}\n- maxToRenderPerBatch={16}\n- updateCellsBatchingPeriod={16}\n- windowSize={10}\n- scrollEventThrottle={16}\n- onViewableItemsChanged={onViewableItemsChangedRef.current}\n- viewabilityConfig={viewabilityConfigRef.current}\n contentContainerStyle={{\n- paddingTop: REVIEW_HEADER_SPACING,\n+ paddingTop: topContentInset + REVIEW_HEADER_SPACING,\n paddingBottom: Math.max(insets.bottom, 18) + 18,\n }}\n />\ndiff --git a/apps/mobile/src/features/review/reviewDiffRendering.tsx b/apps/mobile/src/features/review/reviewDiffRendering.tsx\nindex d61924a62..3f2ae0160 100644\n--- a/apps/mobile/src/features/review/reviewDiffRendering.tsx\n+++ b/apps/mobile/src/features/review/reviewDiffRendering.tsx\n@@ -11,6 +11,9 @@ export const REVIEW_MONO_FONT_FAMILY = Platform.select({\n default: "monospace",\n });\n \n+export const REVIEW_DIFF_LINE_HEIGHT = 26;\n+const REVIEW_DELETE_STRIPE_COUNT = REVIEW_DIFF_LINE_HEIGHT / 2;\n+\n export function renderVisibleWhitespace(value: string): string {\n const expandedTabs = value.replace(/\\t/g, " ");\n return expandedTabs.replace(/^( +)/, (leading) => leading.replaceAll(" ", "\\u00A0"));\n@@ -37,10 +40,13 @@ function diffHighlightColor(change: ReviewRenderableLineRow["change"]): string |\n export function ReviewChangeBar(props: { readonly change: ReviewRenderableLineRow["change"] }) {\n if (props.change === "delete") {\n return (\n- <View className="w-[5px] self-stretch overflow-hidden">\n- <View className="flex-1 justify-between">\n- {Array.from({ length: 6 }, (_, index) => (\n- <View key={index} className="h-[2px] w-[5px] bg-rose-400" />\n+ <View className="w-[5px] overflow-hidden" style={{ height: REVIEW_DIFF_LINE_HEIGHT }}>\n+ <View>\n+ {Array.from({ length: REVIEW_DELETE_STRIPE_COUNT }, (_, index) => (\n+ <View key={index}>\n+ <View className="w-[5px] bg-rose-400" style={{ height: 1 }} />\n+ <View style={{ height: 1 }} />\n+ </View>\n ))}\n </View>\n </View>\n@@ -48,7 +54,7 @@ export function ReviewChangeBar(props: { readonly change: ReviewRenderableLineRo\n }\n \n return (\n- <View className="w-[5px] self-stretch overflow-hidden">\n+ <View className="w-[5px] overflow-hidden" style={{ height: REVIEW_DIFF_LINE_HEIGHT }}>\n <View className={cn("h-full w-[5px] flex-1", changeBarTone(props.change))} />\n </View>\n );\n@@ -63,6 +69,7 @@ export function DiffTokenText(props: {\n if (!props.tokens || props.tokens.length === 0) {\n return (\n <NativeText\n+ numberOfLines={1}\n selectable\n className={cn("text-[13px] leading-[17px] font-medium text-foreground", props.className)}\n style={{ fontFamily: REVIEW_MONO_FONT_FAMILY }}\n@@ -74,6 +81,7 @@ export function DiffTokenText(props: {\n \n return (\n <NativeText\n+ numberOfLines={1}\n selectable\n className={cn("text-[13px] leading-[17px] font-medium text-foreground", props.className)}\n style={{ fontFamily: REVIEW_MONO_FONT_FAMILY }}\ndiff --git a/apps/mobile/src/features/review/reviewHighlighterEngine.test.ts b/apps/mobile/src/features/review/reviewHighlighterEngine.test.ts\nindex d63a7a67c..5449fc6bf 100644\n--- a/apps/mobile/src/features/review/reviewHighlighterEngine.test.ts\n+++ b/apps/mobile/src/features/review/reviewHighlighterEngine.test.ts\n@@ -6,9 +6,9 @@ import {\n } from "./reviewHighlighterEngine";\n \n describe("resolveReviewHighlighterEnginePreference", () => {\n- it("defaults invalid values to javascript", () => {\n- expect(resolveReviewHighlighterEnginePreference(undefined)).toBe("javascript");\n- expect(resolveReviewHighlighterEnginePreference("bogus")).toBe("javascript");\n+ it("defaults invalid values to native", () => {\n+ expect(resolveReviewHighlighterEnginePreference(undefined)).toBe("native");\n+ expect(resolveReviewHighlighterEnginePreference("bogus")).toBe("native");\n });\n \n it("accepts supported values", () => {\ndiff --git a/apps/mobile/src/features/review/reviewHighlighterEngine.ts b/apps/mobile/src/features/review/reviewHighlighterEngine.ts\nindex 5ef9f055a..428768537 100644\n--- a/apps/mobile/src/features/review/reviewHighlighterEngine.ts\n+++ b/apps/mobile/src/features/review/reviewHighlighterEngine.ts\n@@ -11,7 +11,7 @@ export function resolveReviewHighlighterEnginePreference(\n case "native":\n return "native";\n default:\n- return "javascript";\n+ return "native";\n }\n }\n \ndiff --git a/apps/mobile/src/features/review/reviewModel.test.ts b/apps/mobile/src/features/review/reviewModel.test.ts\nindex a24a99ceb..69a6e7261 100644\n--- a/apps/mobile/src/features/review/reviewModel.test.ts\n+++ b/apps/mobile/src/features/review/reviewModel.test.ts\n@@ -238,7 +238,7 @@ describe("buildReviewParsedDiff", () => {\n });\n });\n \n- it("flattens expanded files into virtualizable review items", () => {\n+ it("flattens expanded file rows into virtualized review items", () => {\n const file = makeRenderableFile({\n path: "apps/mobile/src/a.ts",\n rows: [\n@@ -270,8 +270,19 @@ describe("buildReviewParsedDiff", () => {\n \n expect(items).toEqual([\n expect.objectContaining({ kind: "file-header", fileId: file.id, expanded: true }),\n- expect.objectContaining({ kind: "hunk", fileId: file.id, row: file.rows[0] }),\n- expect.objectContaining({ kind: "line", fileId: file.id, row: file.rows[1] }),\n+ expect.objectContaining({\n+ kind: "hunk",\n+ fileId: file.id,\n+ file,\n+ row: file.rows[0],\n+ }),\n+ expect.objectContaining({\n+ kind: "line",\n+ fileId: file.id,\n+ file,\n+ row: file.rows[1],\n+ lineIndex: 0,\n+ }),\n ]);\n });\n \ndiff --git a/apps/mobile/src/features/review/reviewModel.ts b/apps/mobile/src/features/review/reviewModel.ts\nindex 27e6d7ae4..1cfbf358c 100644\n--- a/apps/mobile/src/features/review/reviewModel.ts\n+++ b/apps/mobile/src/features/review/reviewModel.ts\n@@ -72,6 +72,7 @@ export interface ReviewHunkListItem {\n readonly kind: "hunk";\n readonly id: string;\n readonly fileId: string;\n+ readonly file: ReviewRenderableFile;\n readonly row: ReviewRenderableHunkRow;\n }\n \n@@ -79,7 +80,9 @@ export interface ReviewLineListItem {\n readonly kind: "line";\n readonly id: string;\n readonly fileId: string;\n+ readonly file: ReviewRenderableFile;\n readonly row: ReviewRenderableLineRow;\n+ readonly lineIndex: number;\n }\n \n export type ReviewListItem =\n@@ -308,7 +311,7 @@ export function getReviewFilePreviewState(file: ReviewRenderableFile): ReviewFil\n }\n \n // The flattened review list item model is inspired by pierre/diffs\' iterator-first\n-// virtualization architecture, adapted here for React Native and LegendList.\n+// virtualization architecture, adapted here for React Native virtualization.\n // Original project: https://github.com/pingdotgg/pierre/tree/main/packages/diffs\n // Reference files:\n // - src/utils/iterateOverDiff.ts\n@@ -350,12 +353,14 @@ export function buildReviewListItems(input: {\n }\n }\n \n- file.rows.forEach((row) => {\n+ let lineIndex = 0;\n+ file.rows.forEach((row, rowIndex) => {\n if (row.kind === "hunk") {\n items.push({\n kind: "hunk",\n- id: row.id,\n+ id: `${file.id}:row:${rowIndex}:${row.id}`,\n fileId: file.id,\n+ file,\n row,\n });\n return;\n@@ -363,10 +368,13 @@ export function buildReviewListItems(input: {\n \n items.push({\n kind: "line",\n- id: row.id,\n+ id: `${file.id}:row:${rowIndex}:${row.id}`,\n fileId: file.id,\n+ file,\n row,\n+ lineIndex,\n });\n+ lineIndex += 1;\n });\n });\n \ndiff --git a/apps/mobile/src/features/review/reviewState.ts b/apps/mobile/src/features/review/reviewState.ts\nindex 06134db7d..c116f93fe 100644\n--- a/apps/mobile/src/features/review/reviewState.ts\n+++ b/apps/mobile/src/features/review/reviewState.ts\n@@ -64,6 +64,13 @@ const reviewRevealedLargeFileIdsByThreadKeyAtom = Atom.family((threadKey: string\n ),\n );\n \n+const reviewViewedFileIdsByThreadKeyAtom = Atom.family((threadKey: string) =>\n+ Atom.make(EMPTY_REVIEW_SECTION_FILE_IDS).pipe(\n+ Atom.keepAlive,\n+ Atom.withLabel(`mobile:review:viewed-file-ids:${threadKey}`),\n+ ),\n+);\n+\n const reviewParsedDiffBySectionCacheKeyAtom = Atom.family((cacheKey: string) =>\n Atom.make<{ readonly diff: string | null; readonly parsed: ReviewParsedDiff } | null>(null).pipe(\n Atom.keepAlive,\n@@ -110,6 +117,9 @@ export function useReviewCacheForThread(input: {\n ? reviewRevealedLargeFileIdsByThreadKeyAtom(threadKey)\n : EMPTY_REVIEW_SECTION_FILE_IDS_ATOM,\n );\n+ const viewedFileIdsBySection = useAtomValue(\n+ threadKey ? reviewViewedFileIdsByThreadKeyAtom(threadKey) : EMPTY_REVIEW_SECTION_FILE_IDS_ATOM,\n+ );\n \n return {\n threadKey,\n@@ -118,6 +128,7 @@ export function useReviewCacheForThread(input: {\n selectedSectionId,\n expandedFileIdsBySection,\n revealedLargeFileIdsBySection,\n+ viewedFileIdsBySection,\n };\n }\n \n@@ -169,6 +180,20 @@ export function updateReviewRevealedLargeFileIds(\n });\n }\n \n+export function updateReviewViewedFileIds(\n+ threadKey: string,\n+ sectionId: string,\n+ update: (current: ReadonlyArray<string> | undefined) => ReadonlyArray<string> | undefined,\n+): void {\n+ const atom = reviewViewedFileIdsByThreadKeyAtom(threadKey);\n+ const current = appAtomRegistry.get(atom);\n+ const nextValue = update(current[sectionId]);\n+ appAtomRegistry.set(atom, {\n+ ...current,\n+ [sectionId]: nextValue,\n+ });\n+}\n+\n export function getCachedReviewParsedDiff(input: {\n readonly threadKey: string | null;\n readonly sectionId: string | null;\ndiff --git a/apps/mobile/src/features/review/shikiReviewHighlighter.test.ts b/apps/mobile/src/features/review/shikiReviewHighlighter.test.ts\nindex 05b5c9213..402d00668 100644\n--- a/apps/mobile/src/features/review/shikiReviewHighlighter.test.ts\n+++ b/apps/mobile/src/features/review/shikiReviewHighlighter.test.ts\n@@ -24,7 +24,7 @@ function makeRenderableFile(\n describe("highlightReviewFile", () => {\n it("preserves one highlighted token row per diff line even without trailing newlines", async () => {\n const file = makeRenderableFile({\n- path: "apps/mobile/src/example.test.ts",\n+ path: "apps/mobile/src/example.txt",\n additionLines: [\n \'const items = ["a"];\',\n \'expect(items).toEqual(["a"]);\',\n@@ -36,15 +36,23 @@ describe("highlightReviewFile", () => {\n const highlighted = await highlightReviewFile(file, "light");\n \n expect(highlighted.additionLines).toHaveLength(file.additionLines.length);\n- expect(highlighted.additionLines[0]?.some((token) => token.content === "const")).toBe(true);\n- expect(highlighted.additionLines[1]?.some((token) => token.content === "expect")).toBe(true);\n- expect(highlighted.additionLines[2]?.some((token) => token.content === "const")).toBe(true);\n- expect(highlighted.additionLines[3]?.some((token) => token.content === "expect")).toBe(true);\n+ expect(highlighted.additionLines[0]?.map((token) => token.content).join("")).toBe(\n+ file.additionLines[0],\n+ );\n+ expect(highlighted.additionLines[1]?.map((token) => token.content).join("")).toBe(\n+ file.additionLines[1],\n+ );\n+ expect(highlighted.additionLines[2]?.map((token) => token.content).join("")).toBe(\n+ file.additionLines[2],\n+ );\n+ expect(highlighted.additionLines[3]?.map((token) => token.content).join("")).toBe(\n+ file.additionLines[3],\n+ );\n });\n \n it("adds word-alt diff emphasis for paired deletion and addition lines", async () => {\n const file = makeRenderableFile({\n- path: "apps/mobile/src/example-inline-diff.test.ts",\n+ path: "apps/mobile/src/example-inline-diff.txt",\n additionLines: ["const after = 2;"],\n deletionLines: ["const before = 1;"],\n rows: [\n@@ -82,7 +90,7 @@ describe("highlightReviewFile", () => {\n it("falls back to plain tokens for very long lines", async () => {\n const longLine = `const value = "${"a".repeat(1_100)}";`;\n const file = makeRenderableFile({\n- path: "apps/mobile/src/example-long-line.ts",\n+ path: "apps/mobile/src/example-long-line.txt",\n additionLines: [longLine],\n rows: [\n {\ndiff --git a/apps/mobile/src/features/review/shikiReviewHighlighter.ts b/apps/mobile/src/features/review/shikiReviewHighlighter.ts\nindex f7a5c4125..eb6bf6973 100644\n--- a/apps/mobile/src/features/review/shikiReviewHighlighter.ts\n+++ b/apps/mobile/src/features/review/shikiReviewHighlighter.ts\n@@ -1,5 +1,14 @@\n import { createHighlighterCore, type HighlighterCore } from "@shikijs/core";\n import { createJavaScriptRegexEngine } from "@shikijs/engine-javascript";\n+import bashLanguage from "@shikijs/langs/bash";\n+import javascriptLanguage from "@shikijs/langs/javascript";\n+import jsonLanguage from "@shikijs/langs/json";\n+import jsxLanguage from "@shikijs/langs/jsx";\n+import tsxLanguage from "@shikijs/langs/tsx";\n+import typescriptLanguage from "@shikijs/langs/typescript";\n+import yamlLanguage from "@shikijs/langs/yaml";\n+import githubDarkDefault from "@shikijs/themes/github-dark-default";\n+import githubLightDefault from "@shikijs/themes/github-light-default";\n import { getFiletypeFromFileName } from "@pierre/diffs/utils";\n \n import {\n@@ -11,6 +20,7 @@ import type { ReviewRenderableFile, ReviewRenderableLineRow } from "./reviewMode\n import { applyDiffRangesToTokens, computeWordAltDiffRanges } from "./reviewWordDiffs";\n \n export type ReviewDiffTheme = "light" | "dark";\n+export type { ReviewHighlighterEngine };\n \n export interface ReviewHighlightedToken {\n content: string;\n@@ -24,12 +34,19 @@ export interface ReviewHighlightedFile {\n readonly deletionLines: ReadonlyArray<ReadonlyArray<ReviewHighlightedToken>>;\n }\n \n+export interface ReviewHighlightFileProgress {\n+ readonly highlightedFile: ReviewHighlightedFile;\n+ readonly complete: boolean;\n+ readonly highlightedLineCount: number;\n+}\n+\n const SHIKI_THEME_NAME_BY_SCHEME = {\n light: "github-light-default",\n dark: "github-dark-default",\n } as const;\n const REVIEW_HIGHLIGHTER_ENGINE_ENV_VALUE =\n- process.env.EXPO_PUBLIC_REVIEW_HIGHLIGHTER_ENGINE ?? "javascript";\n+ process.env.EXPO_PUBLIC_REVIEW_HIGHLIGHTER_ENGINE ??\n+ (process.env.NODE_ENV === "test" ? "javascript" : "native");\n const REVIEW_HIGHLIGHTER_ENGINE_PREFERENCE = resolveReviewHighlighterEnginePreference(\n REVIEW_HIGHLIGHTER_ENGINE_ENV_VALUE,\n );\n@@ -38,12 +55,30 @@ const REVIEW_HIGHLIGHTER_DISABLE_RESULT_CACHE = resolveReviewHighlighterBooleanF\n false,\n );\n const REVIEW_HIGHLIGHT_RESULT_CACHE_LIMIT = 8;\n-const REVIEW_HIGHLIGHT_CHUNK_LINE_THRESHOLD = 40;\n-const REVIEW_HIGHLIGHT_CHUNK_SIZE = 20;\n+const REVIEW_HIGHLIGHT_CHUNK_LINE_THRESHOLD = 8;\n+const REVIEW_HIGHLIGHT_CHUNK_SIZE = 200;\n const REVIEW_TOKENIZE_MAX_LINE_LENGTH = 1_000;\n const highlightCache = new Map<string, Promise<ReviewHighlightedFile>>();\n const resolvedHighlightCache = new Map<string, ReviewHighlightedFile>();\n-const loadedLanguages = new Set<string>(["text"]);\n+const REVIEW_INITIAL_LANGUAGE_MODULES = [\n+ bashLanguage,\n+ javascriptLanguage,\n+ jsonLanguage,\n+ jsxLanguage,\n+ tsxLanguage,\n+ typescriptLanguage,\n+ yamlLanguage,\n+] satisfies Parameters<typeof createHighlighterCore>[0]["langs"];\n+const loadedLanguages = new Set<string>([\n+ "text",\n+ "bash",\n+ "javascript",\n+ "json",\n+ "jsx",\n+ "tsx",\n+ "typescript",\n+ "yaml",\n+]);\n const languageLoadingPromises = new Map<string, Promise<boolean>>();\n const languageImports: Partial<Record<string, () => Promise<unknown>>> = {\n javascript: () => import("@shikijs/langs/javascript"),\n@@ -215,21 +250,13 @@ function joinPatchLines(lines: ReadonlyArray<string>): string {\n \n function waitForNextFrame(): Promise<void> {\n return new Promise((resolve) => {\n- if (typeof requestAnimationFrame === "function") {\n- requestAnimationFrame(() => resolve());\n- return;\n- }\n-\n setTimeout(resolve, 0);\n });\n }\n \n async function getHighlighter(): Promise<HighlighterCore> {\n if (!highlighterPromise) {\n- const configuredHighlighterPromise = Promise.all([\n- import("@shikijs/themes/github-light-default"),\n- import("@shikijs/themes/github-dark-default"),\n- ]).then(async ([lightThemeModule, darkThemeModule]) => {\n+ const configuredHighlighterPromise = (async () => {\n let nativeEngineAvailable = false;\n \n logReviewHighlighterDiagnostic("initializing", {\n@@ -238,12 +265,11 @@ async function getHighlighter(): Promise<HighlighterCore> {\n resultCacheDisabled: REVIEW_HIGHLIGHTER_DISABLE_RESULT_CACHE,\n });\n \n- const themes = [lightThemeModule.default, darkThemeModule.default];\n+ const themes = [githubLightDefault, githubDarkDefault];\n \n if (REVIEW_HIGHLIGHTER_ENGINE_PREFERENCE !== "javascript") {\n try {\n const nativeEngineModule = await import("react-native-shiki-engine");\n- logReviewHighlighterDiagnostic("imported react-native-shiki-engine");\n nativeEngineAvailable = nativeEngineModule.isNativeEngineAvailable();\n logReviewHighlighterDiagnostic("checked native engine availability", {\n nativeEngineAvailable,\n@@ -253,7 +279,7 @@ async function getHighlighter(): Promise<HighlighterCore> {\n logReviewHighlighterDiagnostic("creating native regex engine");\n const highlighter = await createHighlighterCore({\n themes,\n- langs: [],\n+ langs: REVIEW_INITIAL_LANGUAGE_MODULES,\n engine: nativeEngineModule.createNativeEngine(),\n });\n logReviewHighlighterDiagnostic("using native engine");\n@@ -281,7 +307,7 @@ async function getHighlighter(): Promise<HighlighterCore> {\n );\n const highlighter = await createHighlighterCore({\n themes,\n- langs: [],\n+ langs: REVIEW_INITIAL_LANGUAGE_MODULES,\n engine: createJavaScriptRegexEngine(),\n });\n logReviewHighlighterDiagnostic("using javascript engine", {\n@@ -291,7 +317,7 @@ async function getHighlighter(): Promise<HighlighterCore> {\n highlighter,\n engine,\n };\n- });\n+ })();\n \n highlighterPromise = configuredHighlighterPromise\n .then((result) => result.highlighter)\n@@ -316,11 +342,52 @@ export async function getActiveReviewHighlighterEngine(): Promise<ReviewHighligh\n return activeHighlighterEnginePromise ?? Promise.resolve("javascript");\n }\n \n+export async function prepareReviewHighlighter(): Promise<void> {\n+ await getHighlighter();\n+}\n+\n+export async function prepareReviewHighlighterLanguages(\n+ languages: ReadonlyArray<string>,\n+): Promise<void> {\n+ const highlighter = await getHighlighter();\n+ await Promise.all(\n+ languages.map(async (language) => {\n+ const candidate = resolveLanguageAlias(language);\n+ if (candidate === "text" || !(candidate in languageImports)) {\n+ return;\n+ }\n+\n+ await loadSingleLanguage(highlighter, candidate);\n+ }),\n+ );\n+}\n+\n function resolveLanguageAlias(language: string): string {\n const normalized = language.toLowerCase();\n return languageAliases[normalized] ?? normalized;\n }\n \n+function resolveLoadedLanguageFromPath(\n+ path: string,\n+ languageHint: string | null = null,\n+): string | null {\n+ const detectedLanguage = languageHint ?? getFiletypeFromFileName(path);\n+ if (!detectedLanguage) {\n+ return "text";\n+ }\n+\n+ const candidate = resolveLanguageAlias(detectedLanguage);\n+ if (candidate === "text" || candidate === "ansi") {\n+ return "text";\n+ }\n+\n+ if (!(candidate in languageImports)) {\n+ return "text";\n+ }\n+\n+ return loadedLanguages.has(candidate) ? candidate : null;\n+}\n+\n async function loadSingleLanguage(\n highlighter: HighlighterCore,\n language: string,\n@@ -360,6 +427,11 @@ async function resolveLanguageFromPath(\n path: string,\n languageHint: string | null = null,\n ): Promise<string> {\n+ const loadedLanguage = resolveLoadedLanguageFromPath(path, languageHint);\n+ if (loadedLanguage) {\n+ return loadedLanguage;\n+ }\n+\n const detectedLanguage = languageHint ?? getFiletypeFromFileName(path);\n if (!detectedLanguage) {\n return "text";\n@@ -374,8 +446,12 @@ async function resolveLanguageFromPath(\n return "text";\n }\n \n+ if (loadedLanguages.has(candidate)) {\n+ return candidate;\n+ }\n+\n const highlighter = await getHighlighter();\n- const loaded = await loadSingleLanguage(highlighter, resolveLanguageAlias(candidate));\n+ const loaded = await loadSingleLanguage(highlighter, candidate);\n if (!loaded) {\n return "text";\n }\n@@ -384,7 +460,10 @@ async function resolveLanguageFromPath(\n }\n \n async function resolveLanguage(file: ReviewRenderableFile): Promise<string> {\n- return resolveLanguageFromPath(file.path, file.languageHint);\n+ return (\n+ resolveLoadedLanguageFromPath(file.path, file.languageHint) ??\n+ (await resolveLanguageFromPath(file.path, file.languageHint))\n+ );\n }\n \n function normalizeHighlightedLines(\n@@ -399,6 +478,18 @@ function normalizeHighlightedLines(\n );\n }\n \n+function makePlainHighlightedLines(\n+ lines: ReadonlyArray<string>,\n+): ReadonlyArray<ReadonlyArray<ReviewHighlightedToken>> {\n+ return lines.map((line) => [\n+ {\n+ content: stripTrailingNewline(line),\n+ color: null,\n+ fontStyle: null,\n+ },\n+ ]);\n+}\n+\n function applyWordAltDiffHighlightsToFile(\n file: ReviewRenderableFile,\n highlighted: ReviewHighlightedFile,\n@@ -594,6 +685,67 @@ async function highlightLines(\n return highlightedLines;\n }\n \n+async function highlightPatchLinesInChunks(input: {\n+ readonly lines: ReadonlyArray<string>;\n+ readonly language: string;\n+ readonly theme: string;\n+ readonly onChunk: (\n+ startIndex: number,\n+ tokens: ReadonlyArray<ReadonlyArray<ReviewHighlightedToken>>,\n+ ) => void;\n+}): Promise<ReadonlyArray<ReadonlyArray<ReviewHighlightedToken>>> {\n+ if (input.lines.length === 0) {\n+ return [];\n+ }\n+\n+ const highlighter = await getHighlighter();\n+ const highlightedLines: Array<ReadonlyArray<ReviewHighlightedToken>> = [];\n+\n+ for (\n+ let startIndex = 0;\n+ startIndex < input.lines.length;\n+ startIndex += REVIEW_HIGHLIGHT_CHUNK_SIZE\n+ ) {\n+ const lineChunk = input.lines.slice(startIndex, startIndex + REVIEW_HIGHLIGHT_CHUNK_SIZE);\n+ const chunkTokens: Array<ReadonlyArray<ReviewHighlightedToken>> = [];\n+ const tokenizableLines: string[] = [];\n+ const tokenizableIndexes: number[] = [];\n+\n+ lineChunk.forEach((line, index) => {\n+ const strippedLine = stripTrailingNewline(line);\n+ if (strippedLine.length > REVIEW_TOKENIZE_MAX_LINE_LENGTH) {\n+ chunkTokens[index] = [{ content: strippedLine, color: null, fontStyle: null }];\n+ return;\n+ }\n+\n+ tokenizableIndexes.push(index);\n+ tokenizableLines.push(strippedLine);\n+ });\n+\n+ if (tokenizableLines.length > 0) {\n+ const tokenLines = highlighter.codeToTokensBase(tokenizableLines.join("\\n"), {\n+ lang: input.language,\n+ theme: input.theme,\n+ });\n+ const normalizedTokenLines = normalizeHighlightedLines(tokenLines);\n+\n+ tokenizableIndexes.forEach((chunkIndex, tokenIndex) => {\n+ chunkTokens[chunkIndex] = normalizedTokenLines[tokenIndex] ?? [];\n+ });\n+ }\n+\n+ const completedChunk = lineChunk.map((_, index) => chunkTokens[index] ?? []);\n+ highlightedLines.push(...completedChunk);\n+ input.onChunk(startIndex, completedChunk);\n+\n+ if (startIndex + REVIEW_HIGHLIGHT_CHUNK_SIZE < input.lines.length) {\n+ await waitForNextFrame();\n+ }\n+ }\n+\n+ return highlightedLines;\n+}\n+\n function getHighlightCacheKey(file: ReviewRenderableFile, theme: ReviewDiffTheme): string {\n return `${SHIKI_THEME_NAME_BY_SCHEME[theme]}:${file.cacheKey}`;\n }\n@@ -667,7 +819,28 @@ export async function highlightReviewFile(\n deletionLineCount: file.deletionLines.length,\n rowCount: file.rows.length,\n });\n- const language = await resolveLanguage(file);\n+ const loadedLanguage = resolveLoadedLanguageFromPath(file.path, file.languageHint);\n+ const language = loadedLanguage ?? (await resolveLanguage(file));\n+ if (language === "text") {\n+ const highlighted = applyWordAltDiffHighlightsToFile(file, {\n+ additionLines: makePlainHighlightedLines(file.additionLines),\n+ deletionLines: makePlainHighlightedLines(file.deletionLines),\n+ });\n+ if (!REVIEW_HIGHLIGHTER_DISABLE_RESULT_CACHE) {\n+ storeResolvedHighlightedFile(cacheKey, highlighted);\n+ }\n+ logReviewHighlighterDiagnostic("file highlight complete", {\n+ fileId: file.id,\n+ filePath: file.path,\n+ theme,\n+ language,\n+ highlightedAdditionLineCount: highlighted.additionLines.length,\n+ highlightedDeletionLineCount: highlighted.deletionLines.length,\n+ durationMs: Date.now() - startedAt,\n+ });\n+ return highlighted;\n+ }\n+\n const additionLines = await highlightLines(\n joinPatchLines(file.additionLines),\n language,\n@@ -707,6 +880,113 @@ export async function highlightReviewFile(\n });\n }\n \n+export async function streamHighlightReviewFile(\n+ file: ReviewRenderableFile,\n+ theme: ReviewDiffTheme,\n+ onProgress: (progress: ReviewHighlightFileProgress) => void,\n+): Promise<ReviewHighlightedFile> {\n+ const shikiTheme = SHIKI_THEME_NAME_BY_SCHEME[theme];\n+ const cacheKey = getHighlightCacheKey(file, theme);\n+ if (!REVIEW_HIGHLIGHTER_DISABLE_RESULT_CACHE) {\n+ const resolved = resolvedHighlightCache.get(cacheKey);\n+ if (resolved) {\n+ onProgress({\n+ highlightedFile: resolved,\n+ complete: true,\n+ highlightedLineCount: resolved.additionLines.length + resolved.deletionLines.length,\n+ });\n+ return resolved;\n+ }\n+ }\n+\n+ const startedAt = Date.now();\n+ logReviewHighlighterDiagnostic("file stream highlight start", {\n+ fileId: file.id,\n+ filePath: file.path,\n+ theme,\n+ additionLineCount: file.additionLines.length,\n+ deletionLineCount: file.deletionLines.length,\n+ rowCount: file.rows.length,\n+ });\n+\n+ const loadedLanguage = resolveLoadedLanguageFromPath(file.path, file.languageHint);\n+ const language = loadedLanguage ?? (await resolveLanguage(file));\n+ if (language === "text") {\n+ const highlighted = applyWordAltDiffHighlightsToFile(file, {\n+ additionLines: makePlainHighlightedLines(file.additionLines),\n+ deletionLines: makePlainHighlightedLines(file.deletionLines),\n+ });\n+ if (!REVIEW_HIGHLIGHTER_DISABLE_RESULT_CACHE) {\n+ storeResolvedHighlightedFile(cacheKey, highlighted);\n+ }\n+ onProgress({\n+ highlightedFile: highlighted,\n+ complete: true,\n+ highlightedLineCount: highlighted.additionLines.length + highlighted.deletionLines.length,\n+ });\n+ logReviewHighlighterDiagnostic("file stream highlight complete", {\n+ fileId: file.id,\n+ filePath: file.path,\n+ theme,\n+ language,\n+ highlightedAdditionLineCount: highlighted.additionLines.length,\n+ highlightedDeletionLineCount: highlighted.deletionLines.length,\n+ highlightedLineCount: highlighted.additionLines.length + highlighted.deletionLines.length,\n+ durationMs: Date.now() - startedAt,\n+ });\n+ return highlighted;\n+ }\n+\n+ const additionLines: Array<ReadonlyArray<ReviewHighlightedToken>> = [];\n+ const deletionLines: Array<ReadonlyArray<ReviewHighlightedToken>> = [];\n+ let highlightedLineCount = 0;\n+\n+ await highlightPatchLinesInChunks({\n+ lines: file.additionLines,\n+ language,\n+ theme: shikiTheme,\n+ onChunk: (startIndex, tokens) => {\n+ tokens.forEach((lineTokens, index) => {\n+ additionLines[startIndex + index] = lineTokens;\n+ });\n+ highlightedLineCount += tokens.length;\n+ },\n+ });\n+ await waitForNextFrame();\n+ await highlightPatchLinesInChunks({\n+ lines: file.deletionLines,\n+ language,\n+ theme: shikiTheme,\n+ onChunk: (startIndex, tokens) => {\n+ tokens.forEach((lineTokens, index) => {\n+ deletionLines[startIndex + index] = lineTokens;\n+ });\n+ highlightedLineCount += tokens.length;\n+ },\n+ });\n+\n+ const highlighted = applyWordAltDiffHighlightsToFile(file, { additionLines, deletionLines });\n+ if (!REVIEW_HIGHLIGHTER_DISABLE_RESULT_CACHE) {\n+ storeResolvedHighlightedFile(cacheKey, highlighted);\n+ }\n+ onProgress({\n+ highlightedFile: highlighted,\n+ complete: true,\n+ highlightedLineCount,\n+ });\n+ logReviewHighlighterDiagnostic("file stream highlight complete", {\n+ fileId: file.id,\n+ filePath: file.path,\n+ theme,\n+ language,\n+ highlightedAdditionLineCount: highlighted.additionLines.length,\n+ highlightedDeletionLineCount: highlighted.deletionLines.length,\n+ highlightedLineCount,\n+ durationMs: Date.now() - startedAt,\n+ });\n+ return highlighted;\n+}\n+\n export async function highlightReviewSelectedLines(input: {\n readonly filePath: string;\n readonly lines: ReadonlyArray<ReviewRenderableLineRow>;\n@@ -717,7 +997,9 @@ export async function highlightReviewSelectedLines(input: {\n return {};\n }\n \n- const language = await resolveLanguageFromPath(input.filePath, input.languageHint ?? null);\n+ const loadedLanguage = resolveLoadedLanguageFromPath(input.filePath, input.languageHint ?? null);\n+ const language =\n+ loadedLanguage ?? (await resolveLanguageFromPath(input.filePath, input.languageHint ?? null));\n const shikiTheme = SHIKI_THEME_NAME_BY_SCHEME[input.theme];\n const additionLikeLines = input.lines\n .filter((line) => line.change !== "delete")\ndiff --git a/apps/mobile/docs/review-profiling.md b/apps/mobile/docs/review-profiling.md\nnew file mode 100644\nindex 000000000..6977eaf6e\n--- /dev/null\n+++ b/apps/mobile/docs/review-profiling.md\n@@ -0,0 +1,80 @@\n+# Review Screen Profiling\n+\n+Use this when the mobile review screen is slow or crashes while opening large diffs.\n+\n+## Preferred Capture: React Native DevTools Performance\n+\n+This app is on Expo SDK 55 / React Native 0.83 with Hermes, so the best first trace is the React Native DevTools Performance recording. The review screen also emits `t3.review.*` user timing marks in development builds so the trace can show parse, list-building, row indexing, and syntax-highlighting work.\n+\n+1. Start the development client:\n+\n+ ```sh\n+ cd apps/mobile\n+ bun dev:client\n+ ```\n+\n+2. Open the app in the iOS Simulator or on the device using the development client.\n+\n+3. In the terminal running Expo, press `j` to open React Native DevTools.\n+\n+4. In DevTools, open the `Performance` panel.\n+\n+5. Start recording.\n+\n+6. In the app, reproduce the slow path:\n+ - Navigate to the thread.\n+ - Open `Files Changed`.\n+ - Select the largest review source.\n+ - Expand a few large files or tap `Load diff`.\n+ - Scroll until the app is clearly slow or until just before it crashes.\n+\n+7. Stop recording.\n+\n+8. Export or save the Performance recording as a JSON trace.\n+\n+Send that exported trace file here. Also include the device/simulator model and whether it was iOS or Android.\n+\n+## Android Fallback: Hermes Sampling Profile\n+\n+Use this if the app crashes before DevTools can export a trace, or if we need deeper JavaScript stack samples.\n+\n+1. Run Android dev client:\n+\n+ ```sh\n+ cd apps/mobile\n+ bun android:dev\n+ bun dev:client\n+ ```\n+\n+2. Open the developer menu from the Expo terminal with `d`.\n+\n+3. Select `Enable Sampling Profiler`.\n+\n+4. Reproduce the review-screen slowdown.\n+\n+5. Open the developer menu again with `d`.\n+\n+6. Select `Disable Sampling Profiler`.\n+\n+7. Pull and convert the Hermes profile:\n+\n+ ```sh\n+ cd apps/mobile\n+ mkdir -p profiles/review\n+ bunx react-native profile-hermes profiles/review\n+ ```\n+\n+8. Send the generated Chrome trace/profile file from `apps/mobile/profiles/review`.\n+\n+For the development app variant, the Android package is `com.t3tools.t3code.dev`.\n+\n+## What To Capture\n+\n+For the first trace, do not optimize the repro. We want the slowest realistic case:\n+\n+- A diff with many files and large line counts.\n+- At least one `Load diff` action for a suppressed large diff.\n+- One vertical scroll pass after the content appears.\n+- One horizontal scroll of a long file, if that is part of the slowdown.\n+\n+If the app crashes, note the last visible action before the crash and attach device logs if available.\ndiff --git a/apps/mobile/src/app/debug/syntax-highlight.tsx b/apps/mobile/src/app/debug/syntax-highlight.tsx\nnew file mode 100644\nindex 000000000..c2a36d126\n--- /dev/null\n+++ b/apps/mobile/src/app/debug/syntax-highlight.tsx\n@@ -0,0 +1,423 @@\n+import { createHighlighterCore, type HighlighterCore } from "@shikijs/core";\n+import { createJavaScriptRegexEngine } from "@shikijs/engine-javascript";\n+import typescriptLanguage from "@shikijs/langs/typescript";\n+import githubDarkDefault from "@shikijs/themes/github-dark-default";\n+import githubLightDefault from "@shikijs/themes/github-light-default";\n+import Stack from "expo-router/stack";\n+import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";\n+import {\n+ FlatList,\n+ Pressable,\n+ Text as NativeText,\n+ type ListRenderItemInfo,\n+ useColorScheme,\n+ useWindowDimensions,\n+ View,\n+} from "react-native";\n+import { useSafeAreaInsets } from "react-native-safe-area-context";\n+\n+import { AppText as Text } from "../../components/AppText";\n+import { cn } from "../../lib/cn";\n+import { useThemeColor } from "../../lib/useThemeColor";\n+\n+type DebugHighlightEngine = "native" | "javascript";\n+\n+type DebugToken = {\n+ readonly content: string;\n+ readonly color: string | null;\n+ readonly fontStyle: number | null;\n+};\n+\n+type DebugLine = {\n+ readonly id: string;\n+ readonly chunkIndex: number;\n+ readonly indexInChunk: number;\n+ readonly lineNumber: number;\n+ readonly content: string;\n+};\n+\n+type DebugHighlighterHandle = {\n+ readonly engine: DebugHighlightEngine;\n+ readonly tokenize: (\n+ code: string,\n+ options: { readonly lang: string; readonly theme: string },\n+ ) => ReadonlyArray<ReadonlyArray<DebugToken>>;\n+};\n+\n+const DEBUG_LINE_COUNT = 10_000;\n+const DEBUG_CHUNK_SIZE = 500;\n+const DEBUG_LINE_HEIGHT = 24;\n+const DEBUG_GUTTER_WIDTH = 58;\n+const DEBUG_CONTENT_WIDTH = 3_200;\n+const DEBUG_MONO_FONT_FAMILY = "BerkeleyMono-Regular";\n+const DEBUG_THEME_NAME_BY_SCHEME = {\n+ dark: "github-dark-default",\n+ light: "github-light-default",\n+} as const;\n+\n+let nativeHighlighterPromise: Promise<DebugHighlighterHandle> | null = null;\n+let javascriptHighlighterPromise: Promise<DebugHighlighterHandle> | null = null;\n+\n+function waitForNextFrame(): Promise<void> {\n+ return new Promise((resolve) => setTimeout(resolve, 0));\n+}\n+\n+function normalizeTokens(\n+ tokenLines: ReadonlyArray<ReadonlyArray<{ content: string; color?: string; fontStyle?: number }>>,\n+): ReadonlyArray<ReadonlyArray<DebugToken>> {\n+ return tokenLines.map((line) =>\n+ line.map((token) => ({\n+ content: token.content,\n+ color: token.color ?? null,\n+ fontStyle: token.fontStyle ?? null,\n+ })),\n+ );\n+}\n+\n+function makeDebugCodeLine(index: number): string {\n+ const label = `generatedLine${String(index).padStart(5, "0")}`;\n+ switch (index % 8) {\n+ case 0:\n+ return `export async function ${label}(input: { value: number; name: string }) {`;\n+ case 1:\n+ return ` const normalized = input.name.trim().toLowerCase();`;\n+ case 2:\n+ return ` const result = await Promise.resolve({ id: "${label}", score: input.value * ${index + 1} });`;\n+ case 3:\n+ return ` if (result.score > ${index * 17}) return normalized + ":" + result.id;`;\n+ case 4:\n+ return ` return [normalized, String(result.score), "${"x".repeat((index % 24) + 8)}"].join("/");`;\n+ case 5:\n+ return `}`;\n+ case 6:\n+ return `type ${label}Record = Readonly<{ id: string; createdAt: Date; tags: string[] }>;`;\n+ default:\n+ return `const ${label}: ${label}Record = { id: "${label}", createdAt: new Date(), tags: ["debug", "highlight"] };`;\n+ }\n+}\n+\n+function makeDebugLines(): ReadonlyArray<DebugLine> {\n+ return Array.from({ length: DEBUG_LINE_COUNT }, (_, index) => ({\n+ id: `line:${index + 1}`,\n+ chunkIndex: Math.floor(index / DEBUG_CHUNK_SIZE),\n+ indexInChunk: index % DEBUG_CHUNK_SIZE,\n+ lineNumber: index + 1,\n+ content: makeDebugCodeLine(index + 1),\n+ }));\n+}\n+\n+async function createNativeDebugHighlighter(): Promise<DebugHighlighterHandle> {\n+ const nativeEngineModule = await import("react-native-shiki-engine");\n+ if (!nativeEngineModule.isNativeEngineAvailable()) {\n+ throw new Error("Native Shiki engine is not available in this build.");\n+ }\n+\n+ const highlighter = await createHighlighterCore({\n+ langs: [typescriptLanguage],\n+ themes: [githubLightDefault, githubDarkDefault],\n+ engine: nativeEngineModule.createNativeEngine(),\n+ });\n+\n+ return {\n+ engine: "native",\n+ tokenize: (code, options) => normalizeTokens(highlighter.codeToTokensBase(code, options)),\n+ };\n+}\n+\n+async function createJavascriptDebugHighlighter(): Promise<DebugHighlighterHandle> {\n+ const highlighter: HighlighterCore = await createHighlighterCore({\n+ langs: [typescriptLanguage],\n+ themes: [githubLightDefault, githubDarkDefault],\n+ engine: createJavaScriptRegexEngine(),\n+ });\n+\n+ return {\n+ engine: "javascript",\n+ tokenize: (code, options) => normalizeTokens(highlighter.codeToTokensBase(code, options)),\n+ };\n+}\n+\n+async function getDebugHighlighter(engine: DebugHighlightEngine): Promise<DebugHighlighterHandle> {\n+ if (engine === "native") {\n+ nativeHighlighterPromise ??= createNativeDebugHighlighter();\n+ return nativeHighlighterPromise;\n+ }\n+\n+ javascriptHighlighterPromise ??= createJavascriptDebugHighlighter();\n+ return javascriptHighlighterPromise;\n+}\n+\n+const TokenText = memo(function TokenText(props: {\n+ readonly content: string;\n+ readonly tokens: ReadonlyArray<DebugToken> | null;\n+}) {\n+ if (!props.tokens) {\n+ return (\n+ <NativeText\n+ numberOfLines={1}\n+ className="text-[13px] font-medium leading-[18px] text-foreground"\n+ style={{ fontFamily: DEBUG_MONO_FONT_FAMILY }}\n+ >\n+ {props.content}\n+ </NativeText>\n+ );\n+ }\n+\n+ let tokenOffset = 0;\n+\n+ return (\n+ <NativeText\n+ numberOfLines={1}\n+ className="text-[13px] font-medium leading-[18px] text-foreground"\n+ style={{ fontFamily: DEBUG_MONO_FONT_FAMILY }}\n+ >\n+ {props.tokens.map((token) => {\n+ const tokenKey = `${tokenOffset}:${token.content.length}:${token.color ?? ""}:${token.fontStyle ?? ""}`;\n+ tokenOffset += token.content.length;\n+ const fontWeight =\n+ token.fontStyle !== null && (token.fontStyle & 2) === 2\n+ ? ("700" as const)\n+ : ("500" as const);\n+ const fontStyle =\n+ token.fontStyle !== null && (token.fontStyle & 1) === 1\n+ ? ("italic" as const)\n+ : ("normal" as const);\n+\n+ return (\n+ <NativeText\n+ key={tokenKey}\n+ style={{\n+ color: token.color ?? undefined,\n+ fontFamily: DEBUG_MONO_FONT_FAMILY,\n+ fontStyle,\n+ fontWeight,\n+ }}\n+ >\n+ {token.content}\n+ </NativeText>\n+ );\n+ })}\n+ </NativeText>\n+ );\n+});\n+\n+const DebugCodeLineRow = memo(function DebugCodeLineRow(props: {\n+ readonly item: DebugLine;\n+ readonly tokens: ReadonlyArray<DebugToken> | null;\n+ readonly width: number;\n+}) {\n+ return (\n+ <View className="flex-row bg-card" style={{ height: DEBUG_LINE_HEIGHT, width: props.width }}>\n+ <View className="items-end justify-center pr-2" style={{ width: DEBUG_GUTTER_WIDTH }}>\n+ <Text className="font-mono text-[11px] text-foreground-muted">{props.item.lineNumber}</Text>\n+ </View>\n+ <View className="justify-center px-2" style={{ width: DEBUG_CONTENT_WIDTH }}>\n+ <TokenText content={props.item.content} tokens={props.tokens} />\n+ </View>\n+ </View>\n+ );\n+});\n+\n+function EngineToggle(props: {\n+ readonly engine: DebugHighlightEngine;\n+ readonly onChangeEngine: (engine: DebugHighlightEngine) => void;\n+}) {\n+ return (\n+ <View className="flex-row rounded-full bg-subtle p-1">\n+ {(["native", "javascript"] as const).map((engine) => {\n+ const selected = props.engine === engine;\n+ return (\n+ <Pressable\n+ key={engine}\n+ className={cn("rounded-full px-3 py-1.5", selected && "bg-card")}\n+ onPress={() => props.onChangeEngine(engine)}\n+ >\n+ <Text\n+ className={cn(\n+ "text-[12px] font-t3-bold",\n+ selected ? "text-foreground" : "text-foreground-muted",\n+ )}\n+ >\n+ {engine === "javascript" ? "JS" : "Native"}\n+ </Text>\n+ </Pressable>\n+ );\n+ })}\n+ </View>\n+ );\n+}\n+\n+export default function SyntaxHighlightDebugRoute() {\n+ const insets = useSafeAreaInsets();\n+ const { width } = useWindowDimensions();\n+ const colorScheme = useColorScheme();\n+ const headerIcon = String(useThemeColor("--color-icon"));\n+ const themeName = DEBUG_THEME_NAME_BY_SCHEME[colorScheme === "dark" ? "dark" : "light"];\n+ const [engine, setEngine] = useState<DebugHighlightEngine>("native");\n+ const [tokensByChunkIndex, setTokensByChunkIndex] = useState<\n+ Record<number, ReadonlyArray<ReadonlyArray<DebugToken>>>\n+ >({});\n+ const [status, setStatus] = useState("Idle");\n+ const renderStartRef = useRef<number | null>(null);\n+ const generationRef = useRef(0);\n+ const lines = useMemo(() => makeDebugLines(), []);\n+\n+ useEffect(() => {\n+ const generation = generationRef.current + 1;\n+ generationRef.current = generation;\n+ renderStartRef.current = performance.now();\n+ setTokensByChunkIndex({});\n+ setStatus("Initializing highlighter");\n+\n+ void (async () => {\n+ try {\n+ const highlighterStartedAt = performance.now();\n+ const highlighter = await getDebugHighlighter(engine);\n+ if (generation !== generationRef.current) {\n+ return;\n+ }\n+\n+ console.log("[debug-syntax-scratch] initialize", {\n+ durationMs: Math.round(performance.now() - highlighterStartedAt),\n+ engine: highlighter.engine,\n+ });\n+\n+ let firstChunkMs: number | null = null;\n+ const totalStartedAt = performance.now();\n+ setStatus(`Streaming ${DEBUG_LINE_COUNT.toLocaleString()} lines`);\n+\n+ for (let startIndex = 0; startIndex < lines.length; startIndex += DEBUG_CHUNK_SIZE) {\n+ if (generation !== generationRef.current) {\n+ return;\n+ }\n+\n+ const chunkLines = lines.slice(startIndex, startIndex + DEBUG_CHUNK_SIZE);\n+ const chunkCode = chunkLines.map((line) => line.content).join("\\n");\n+ const chunkStartedAt = performance.now();\n+ const chunkTokens = highlighter.tokenize(chunkCode, {\n+ lang: "typescript",\n+ theme: themeName,\n+ });\n+ const chunkMs = performance.now() - chunkStartedAt;\n+\n+ if (firstChunkMs === null) {\n+ firstChunkMs = performance.now() - totalStartedAt;\n+ console.log("[debug-syntax-scratch] first chunk", {\n+ chunkSize: DEBUG_CHUNK_SIZE,\n+ durationMs: Math.round(firstChunkMs),\n+ engine,\n+ lineCount: chunkTokens.length,\n+ });\n+ }\n+\n+ setTokensByChunkIndex((current) => ({\n+ ...current,\n+ [startIndex / DEBUG_CHUNK_SIZE]: chunkTokens,\n+ }));\n+ setStatus(\n+ `Streamed ${Math.min(startIndex + DEBUG_CHUNK_SIZE, lines.length).toLocaleString()} / ${lines.length.toLocaleString()} lines`,\n+ );\n+\n+ console.log("[debug-syntax-scratch] chunk", {\n+ chunkIndex: startIndex / DEBUG_CHUNK_SIZE,\n+ chunkMs: Math.round(chunkMs),\n+ engine,\n+ lineCount: chunkTokens.length,\n+ });\n+\n+ await waitForNextFrame();\n+ }\n+\n+ console.log("[debug-syntax-scratch] complete", {\n+ durationMs: Math.round(performance.now() - totalStartedAt),\n+ engine,\n+ lineCount: lines.length,\n+ });\n+ setStatus(`Complete with ${engine}`);\n+ } catch (error) {\n+ console.error("[debug-syntax-scratch] failed", {\n+ engine,\n+ message: error instanceof Error ? error.message : String(error),\n+ });\n+ setStatus(error instanceof Error ? error.message : "Highlight failed");\n+ }\n+ })();\n+ }, [engine, lines, themeName]);\n+\n+ useEffect(() => {\n+ if (renderStartRef.current === null) {\n+ return;\n+ }\n+\n+ const startedAt = renderStartRef.current;\n+ renderStartRef.current = null;\n+ const commitMs = performance.now() - startedAt;\n+ requestAnimationFrame(() => {\n+ console.log("[debug-syntax-scratch] render", {\n+ commitMs: Math.round(commitMs),\n+ paintMs: Math.round(performance.now() - startedAt),\n+ });\n+ });\n+ });\n+\n+ const renderItem = useCallback(\n+ ({ item }: ListRenderItemInfo<DebugLine>) => (\n+ <DebugCodeLineRow\n+ item={item}\n+ tokens={tokensByChunkIndex[item.chunkIndex]?.[item.indexInChunk] ?? null}\n+ width={width}\n+ />\n+ ),\n+ [tokensByChunkIndex, width],\n+ );\n+\n+ return (\n+ <View className="flex-1 bg-sheet">\n+ <Stack.Screen\n+ options={{\n+ headerShown: true,\n+ headerTitle: "Syntax Scratch",\n+ headerTintColor: headerIcon,\n+ headerTransparent: true,\n+ headerShadowVisible: false,\n+ }}\n+ />\n+\n+ <View\n+ className="border-b border-border bg-sheet px-3 pb-3"\n+ style={{ paddingTop: insets.top + 56 }}\n+ >\n+ <View className="flex-row items-center justify-between gap-3">\n+ <View className="min-w-0 flex-1">\n+ <Text className="text-[13px] font-t3-bold text-foreground">\n+ Shiki streaming baseline\n+ </Text>\n+ <Text className="text-[11px] text-foreground-muted" numberOfLines={1}>\n+ {status}\n+ </Text>\n+ </View>\n+ <EngineToggle engine={engine} onChangeEngine={setEngine} />\n+ </View>\n+ </View>\n+\n+ <FlatList\n+ style={{ flex: 1, width }}\n+ data={lines}\n+ renderItem={renderItem}\n+ keyExtractor={(item) => item.id}\n+ getItemLayout={(_, index) => ({\n+ length: DEBUG_LINE_HEIGHT,\n+ offset: DEBUG_LINE_HEIGHT * index,\n+ index,\n+ })}\n+ initialNumToRender={40}\n+ maxToRenderPerBatch={80}\n+ updateCellsBatchingPeriod={16}\n+ windowSize={9}\n+ removeClippedSubviews\n+ keyboardShouldPersistTaps="handled"\n+ contentContainerStyle={{ paddingBottom: Math.max(insets.bottom, 18) + 18 }}\n+ />\n+ </View>\n+ );\n+}\ndiff --git a/apps/mobile/src/features/review/ReviewHighlighterProvider.tsx b/apps/mobile/src/features/review/ReviewHighlighterProvider.tsx\nnew file mode 100644\nindex 000000000..095201929\n--- /dev/null\n+++ b/apps/mobile/src/features/review/ReviewHighlighterProvider.tsx\n@@ -0,0 +1,110 @@\n+import { createContext, type ReactNode, useContext, useEffect, useMemo, useState } from "react";\n+\n+import {\n+ getActiveReviewHighlighterEngine,\n+ prepareReviewHighlighter,\n+ prepareReviewHighlighterLanguages,\n+ type ReviewHighlighterEngine,\n+} from "./shikiReviewHighlighter";\n+\n+type ReviewHighlighterStatus = "idle" | "initializing" | "ready" | "error";\n+\n+interface ReviewHighlighterContextValue {\n+ readonly engine: ReviewHighlighterEngine | null;\n+ readonly error: string | null;\n+ readonly status: ReviewHighlighterStatus;\n+}\n+\n+const ReviewHighlighterContext = createContext<ReviewHighlighterContextValue>({\n+ engine: null,\n+ error: null,\n+ status: "idle",\n+});\n+\n+const REVIEW_INITIAL_LANGUAGES = [\n+ "typescript",\n+ "tsx",\n+ "javascript",\n+ "jsx",\n+ "json",\n+ "yaml",\n+ "bash",\n+] as const;\n+\n+function isReviewHighlighterProviderDebugLoggingEnabled(): boolean {\n+ return typeof __DEV__ !== "undefined" ? __DEV__ : false;\n+}\n+\n+function logReviewHighlighterProviderDiagnostic(\n+ message: string,\n+ details?: Record<string, unknown>,\n+): void {\n+ if (!isReviewHighlighterProviderDebugLoggingEnabled()) {\n+ return;\n+ }\n+\n+ if (details) {\n+ console.log(`[review-highlighter-provider] ${message}`, details);\n+ return;\n+ }\n+\n+ console.log(`[review-highlighter-provider] ${message}`);\n+}\n+\n+export function ReviewHighlighterProvider(props: { readonly children: ReactNode }) {\n+ const [value, setValue] = useState<ReviewHighlighterContextValue>({\n+ engine: null,\n+ error: null,\n+ status: "idle",\n+ });\n+\n+ useEffect(() => {\n+ let cancelled = false;\n+\n+ setValue({ engine: null, error: null, status: "initializing" });\n+\n+ void (async () => {\n+ const startedAt = performance.now();\n+ try {\n+ await prepareReviewHighlighter();\n+ await prepareReviewHighlighterLanguages(REVIEW_INITIAL_LANGUAGES);\n+ const engine = await getActiveReviewHighlighterEngine();\n+\n+ if (cancelled) {\n+ return;\n+ }\n+\n+ const durationMs = Math.round(performance.now() - startedAt);\n+ logReviewHighlighterProviderDiagnostic("initialized", {\n+ durationMs,\n+ engine,\n+ });\n+ setValue({ engine, error: null, status: "ready" });\n+ } catch (error) {\n+ if (cancelled) {\n+ return;\n+ }\n+\n+ const message = error instanceof Error ? error.message : String(error);\n+ logReviewHighlighterProviderDiagnostic("initialization failed", { error: message });\n+ setValue({ engine: null, error: message, status: "error" });\n+ }\n+ })();\n+\n+ return () => {\n+ cancelled = true;\n+ };\n+ }, []);\n+\n+ const contextValue = useMemo(() => value, [value]);\n+\n+ return (\n+ <ReviewHighlighterContext.Provider value={contextValue}>\n+ {props.children}\n+ </ReviewHighlighterContext.Provider>\n+ );\n+}\n+\n+export function useReviewHighlighterStatus(): ReviewHighlighterContextValue {\n+ return useContext(ReviewHighlighterContext);\n+}\ndiff --git a/apps/mobile/src/features/review/reviewPerf.ts b/apps/mobile/src/features/review/reviewPerf.ts\nnew file mode 100644\nindex 000000000..2ae1095b1\n--- /dev/null\n+++ b/apps/mobile/src/features/review/reviewPerf.ts\n@@ -0,0 +1,83 @@\n+interface ReviewPerformanceLike {\n+ readonly now?: () => number;\n+ readonly mark?: (name: string) => void;\n+ readonly measure?: (name: string, startMark: string, endMark: string) => void;\n+ readonly clearMarks?: (name?: string) => void;\n+ readonly clearMeasures?: (name?: string) => void;\n+}\n+\n+const REVIEW_PERF_PREFIX = "t3.review";\n+let reviewPerfSequence = 0;\n+\n+function getPerformance(): ReviewPerformanceLike | null {\n+ const candidate = (globalThis as { readonly performance?: ReviewPerformanceLike }).performance;\n+ return candidate ?? null;\n+}\n+\n+export function isReviewPerfEnabled(): boolean {\n+ return typeof __DEV__ !== "undefined" ? __DEV__ : false;\n+}\n+\n+export function measureReviewWork<T>(name: string, callback: () => T): T {\n+ if (!isReviewPerfEnabled()) {\n+ return callback();\n+ }\n+\n+ const perf = getPerformance();\n+ const marker = `${REVIEW_PERF_PREFIX}.${name}.${reviewPerfSequence++}`;\n+ const startMark = `${marker}.start`;\n+ const endMark = `${marker}.end`;\n+ const startedAt = perf?.now?.() ?? Date.now();\n+\n+ perf?.mark?.(startMark);\n+ try {\n+ return callback();\n+ } finally {\n+ const durationMs = (perf?.now?.() ?? Date.now()) - startedAt;\n+ perf?.mark?.(endMark);\n+ perf?.measure?.(`${REVIEW_PERF_PREFIX}.${name}`, startMark, endMark);\n+ perf?.clearMarks?.(startMark);\n+ perf?.clearMarks?.(endMark);\n+ console.log(`[review-perf] ${name}`, { durationMs: Number(durationMs.toFixed(2)) });\n+ }\n+}\n+\n+export async function measureReviewAsyncWork<T>(\n+ name: string,\n+ callback: () => Promise<T>,\n+): Promise<T> {\n+ if (!isReviewPerfEnabled()) {\n+ return callback();\n+ }\n+\n+ const perf = getPerformance();\n+ const marker = `${REVIEW_PERF_PREFIX}.${name}.${reviewPerfSequence++}`;\n+ const startMark = `${marker}.start`;\n+ const endMark = `${marker}.end`;\n+ const startedAt = perf?.now?.() ?? Date.now();\n+\n+ perf?.mark?.(startMark);\n+ try {\n+ return await callback();\n+ } finally {\n+ const durationMs = (perf?.now?.() ?? Date.now()) - startedAt;\n+ perf?.mark?.(endMark);\n+ perf?.measure?.(`${REVIEW_PERF_PREFIX}.${name}`, startMark, endMark);\n+ perf?.clearMarks?.(startMark);\n+ perf?.clearMarks?.(endMark);\n+ console.log(`[review-perf] ${name}`, { durationMs: Number(durationMs.toFixed(2)) });\n+ }\n+}\n+\n+export function markReviewEvent(name: string, details?: Record<string, unknown>): void {\n+ if (!isReviewPerfEnabled()) {\n+ return;\n+ }\n+\n+ getPerformance()?.mark?.(`${REVIEW_PERF_PREFIX}.${name}`);\n+ if (details) {\n+ console.log(`[review-perf] ${name}`, details);\n+ return;\n+ }\n+ console.log(`[review-perf] ${name}`);\n+}\n',
237 },
238];
apps/mobile/src/features/debug/fixtures/reviewDiffXlFixture.ts+0−4
@@ -1,4 +0,0 @@
1// Generated from https://github.com/pingdotgg/t3code/commit/08e6d4cfbfe55af83fe5fb6b9e75364f42f1f22f.patch
2// Keep this split from reviewDiffFixtures.ts so the fixture registry stays readable.
3export const DEBUG_REVIEW_XL_DIFF =
4 'From 08e6d4cfbfe55af83fe5fb6b9e75364f42f1f22f Mon Sep 17 00:00:00 2001\nFrom: Julius Marminge <julius0216@outlook.com>\nDate: Wed, 29 Apr 2026 16:13:55 -0700\nSubject: [PATCH] feat: Multi-Provider support (#2277)\n\nCo-authored-by: Claude Opus 4.7 <noreply@anthropic.com>\nCo-authored-by: codex <codex@users.noreply.github.com>\n---\n apps/desktop/src/clientPersistence.test.ts | 1 +\n .../OrchestrationEngineHarness.integration.ts | 44 +-\n .../TestProviderAdapter.integration.ts | 17 +-\n .../integration/fixtures/providerRuntime.ts | 4 +-\n .../orchestrationEngine.integration.test.ts | 178 +-\n .../providerService.integration.test.ts | 37 +-\n .../git/Layers/ClaudeTextGeneration.test.ts | 311 +--\n .../src/git/Layers/ClaudeTextGeneration.ts | 55 +-\n .../git/Layers/CodexTextGeneration.test.ts | 528 +++--\n .../src/git/Layers/CodexTextGeneration.ts | 97 +-\n .../git/Layers/CursorTextGeneration.test.ts | 311 ++-\n .../src/git/Layers/CursorTextGeneration.ts | 56 +-\n .../git/Layers/OpenCodeTextGeneration.test.ts | 354 ++--\n .../src/git/Layers/OpenCodeTextGeneration.ts | 77 +-\n .../src/git/Layers/RoutingTextGeneration.ts | 104 -\n .../src/git/Layers/TextGenerationLive.test.ts | 117 ++\n .../src/git/Layers/TextGenerationLive.ts | 101 +\n apps/server/src/observability/Metrics.test.ts | 10 +-\n .../Layers/CheckpointReactor.test.ts | 60 +-\n .../Layers/OrchestrationEngine.test.ts | 51 +-\n .../Layers/ProjectionPipeline.test.ts | 33 +-\n .../Layers/ProjectionPipeline.ts | 1 +\n .../Layers/ProjectionSnapshotQuery.test.ts | 18 +-\n .../Layers/ProjectionSnapshotQuery.ts | 6 +\n .../Layers/ProviderCommandReactor.test.ts | 438 +++-\n .../Layers/ProviderCommandReactor.ts | 183 +-\n .../Layers/ProviderRuntimeIngestion.test.ts | 229 ++-\n .../Layers/ProviderRuntimeIngestion.ts | 6 +\n .../orchestration/commandInvariants.test.ts | 13 +-\n .../src/orchestration/decider.delete.test.ts | 5 +-\n .../decider.projectScripts.test.ts | 11 +-\n .../src/orchestration/projector.test.ts | 21 +-\n .../Layers/ProjectionRepositories.test.ts | 14 +-\n .../Layers/ProjectionThreadSessions.ts | 4 +\n .../Layers/ProviderSessionRuntime.ts | 5 +\n apps/server/src/persistence/Migrations.ts | 4 +\n .../027_028_ProviderInstanceIdColumns.test.ts | 74 +\n .../027_ProviderSessionRuntimeInstanceId.ts | 38 +\n .../028_ProjectionThreadSessionInstanceId.ts | 21 +\n .../Services/ProjectionThreadSessions.ts | 2 +\n .../Services/ProviderSessionRuntime.ts | 9 +\n .../src/provider/Drivers/ClaudeDriver.ts | 157 ++\n .../src/provider/Drivers/ClaudeHome.test.ts | 52 +\n .../server/src/provider/Drivers/ClaudeHome.ts | 43 +\n .../src/provider/Drivers/CodexDriver.ts | 171 ++\n .../provider/Drivers/CodexHomeLayout.test.ts | 209 ++\n .../src/provider/Drivers/CodexHomeLayout.ts | 263 +++\n .../src/provider/Drivers/CursorDriver.ts | 148 ++\n .../src/provider/Drivers/OpenCodeDriver.ts | 135 ++\n apps/server/src/provider/Errors.ts | 41 +\n .../src/provider/Layers/ClaudeAdapter.test.ts | 339 ++--\n .../src/provider/Layers/ClaudeAdapter.ts | 63 +-\n .../src/provider/Layers/ClaudeProvider.ts | 484 ++---\n .../src/provider/Layers/CodexAdapter.test.ts | 186 +-\n .../src/provider/Layers/CodexAdapter.ts | 65 +-\n .../src/provider/Layers/CodexProvider.ts | 99 +-\n .../provider/Layers/CodexSessionRuntime.ts | 61 +-\n .../src/provider/Layers/CursorAdapter.test.ts | 213 +-\n .../src/provider/Layers/CursorAdapter.ts | 73 +-\n .../provider/Layers/CursorProvider.test.ts | 159 +-\n .../src/provider/Layers/CursorProvider.ts | 665 ++++---\n .../provider/Layers/OpenCodeAdapter.test.ts | 286 ++-\n .../src/provider/Layers/OpenCodeAdapter.ts | 1770 +++++++++--------\n .../provider/Layers/OpenCodeProvider.test.ts | 119 +-\n .../src/provider/Layers/OpenCodeProvider.ts | 378 ++--\n .../Layers/ProviderAdapterRegistry.test.ts | 148 +-\n .../Layers/ProviderAdapterRegistry.ts | 133 +-\n .../provider/Layers/ProviderEventLoggers.ts | 83 +\n .../ProviderInstanceRegistryHydration.ts | 176 ++\n .../ProviderInstanceRegistryLive.test.ts | 357 ++++\n .../Layers/ProviderInstanceRegistryLive.ts | 434 ++++\n .../provider/Layers/ProviderRegistry.test.ts | 850 ++++++--\n .../src/provider/Layers/ProviderRegistry.ts | 546 +++--\n .../provider/Layers/ProviderService.test.ts | 583 ++++--\n .../src/provider/Layers/ProviderService.ts | 418 +++-\n .../Layers/ProviderSessionDirectory.test.ts | 25 +-\n .../Layers/ProviderSessionDirectory.ts | 24 +-\n .../Layers/ProviderSessionReaper.test.ts | 31 +-\n .../Layers/scopedSafeTeardown.test.ts | 94 +\n .../src/provider/Layers/scopedSafeTeardown.ts | 61 +\n apps/server/src/provider/ProviderDriver.ts | 167 ++\n .../ProviderInstanceEnvironment.test.ts | 21 +\n .../provider/ProviderInstanceEnvironment.ts | 16 +\n .../src/provider/Services/ClaudeAdapter.ts | 29 +-\n .../src/provider/Services/ClaudeProvider.ts | 9 -\n .../src/provider/Services/CodexAdapter.ts | 29 +-\n .../src/provider/Services/CodexProvider.ts | 9 -\n .../src/provider/Services/CursorAdapter.ts | 25 +-\n .../src/provider/Services/CursorProvider.ts | 9 -\n .../src/provider/Services/OpenCodeAdapter.ts | 25 +-\n .../src/provider/Services/OpenCodeProvider.ts | 9 -\n .../src/provider/Services/ProviderAdapter.ts | 4 +-\n .../Services/ProviderAdapterRegistry.ts | 81 +-\n .../Services/ProviderInstanceRegistry.ts | 84 +\n .../ProviderInstanceRegistryMutator.ts | 52 +\n .../src/provider/Services/ProviderRegistry.ts | 29 +-\n .../src/provider/Services/ProviderService.ts | 11 +-\n .../Services/ProviderSessionDirectory.ts | 13 +-\n .../provider/acp/AcpAdapterSupport.test.ts | 3 +-\n .../src/provider/acp/AcpAdapterSupport.ts | 4 +-\n .../provider/acp/AcpCoreRuntimeEvents.test.ts | 14 +-\n .../src/provider/acp/AcpCoreRuntimeEvents.ts | 14 +-\n .../src/provider/acp/AcpNativeLogging.ts | 6 +-\n .../src/provider/acp/AcpSessionRuntime.ts | 2 +-\n .../src/provider/acp/CursorAcpSupport.ts | 5 +-\n apps/server/src/provider/builtInDrivers.ts | 50 +\n .../src/provider/builtInProviderCatalog.ts | 50 +-\n .../makeManagedServerProvider.test.ts | 8 +-\n apps/server/src/provider/opencodeRuntime.ts | 8 +-\n .../src/provider/providerSnapshot.test.ts | 4 +-\n apps/server/src/provider/providerSnapshot.ts | 9 +-\n .../src/provider/providerStatusCache.test.ts | 106 +-\n .../src/provider/providerStatusCache.ts | 80 +-\n .../testUtils/providerAdapterRegistryMock.ts | 95 +\n .../provider/unavailableProviderSnapshot.ts | 72 +\n apps/server/src/server.test.ts | 12 +-\n apps/server/src/server.ts | 76 +-\n apps/server/src/serverRuntimeStartup.test.ts | 6 +-\n apps/server/src/serverRuntimeStartup.ts | 7 +-\n apps/server/src/serverSettings.test.ts | 242 ++-\n apps/server/src/serverSettings.ts | 246 ++-\n apps/server/src/ws.ts | 42 +-\n apps/web/src/components/ChatView.browser.tsx | 221 +-\n .../web/src/components/ChatView.logic.test.ts | 27 +-\n apps/web/src/components/ChatView.logic.ts | 35 +-\n apps/web/src/components/ChatView.tsx | 89 +-\n .../components/CommandPalette.logic.test.ts | 4 +-\n apps/web/src/components/CommandPalette.tsx | 7 +-\n apps/web/src/components/Icons.tsx | 23 +\n .../components/KeybindingsToast.browser.tsx | 30 +-\n apps/web/src/components/Sidebar.logic.test.ts | 15 +-\n apps/web/src/components/chat/ChatComposer.tsx | 187 +-\n .../CompactComposerControlsMenu.browser.tsx | 52 +-\n .../components/chat/ComposerCommandMenu.tsx | 6 +-\n apps/web/src/components/chat/ModelListRow.tsx | 33 +-\n .../components/chat/ModelPickerContent.tsx | 368 ++--\n .../components/chat/ModelPickerSidebar.tsx | 373 ++--\n .../components/chat/ProviderInstanceIcon.tsx | 73 +\n .../chat/ProviderModelPicker.browser.tsx | 252 ++-\n .../components/chat/ProviderModelPicker.tsx | 83 +-\n .../components/chat/ProviderStatusBanner.tsx | 4 +-\n apps/web/src/components/chat/TraitsPicker.tsx | 10 +-\n .../chat/composerProviderState.test.tsx | 12 +-\n .../components/chat/composerProviderState.tsx | 8 +-\n .../chat/composerSlashCommandSearch.test.ts | 11 +-\n .../chat/modelPickerModelHighlights.ts | 4 +-\n .../components/chat/modelPickerSearch.test.ts | 40 +-\n .../src/components/chat/modelPickerSearch.ts | 22 +-\n .../src/components/chat/providerIconUtils.ts | 19 +-\n .../settings/AddProviderInstanceDialog.tsx | 493 +++++\n .../settings/ProviderInstanceCard.test.ts | 36 +\n .../settings/ProviderInstanceCard.tsx | 814 ++++++++\n .../settings/ProviderModelsSection.tsx | 411 ++++\n .../settings/SettingsPanels.browser.tsx | 10 +-\n .../settings/SettingsPanels.logic.test.ts | 63 +\n .../settings/SettingsPanels.logic.ts | 43 +\n .../components/settings/SettingsPanels.tsx | 1128 ++++-------\n .../components/settings/providerDriverMeta.ts | 151 ++\n .../src/components/settings/providerStatus.ts | 91 +\n apps/web/src/components/ui/draft-input.tsx | 21 +\n apps/web/src/composerDraftStore.test.ts | 243 ++-\n apps/web/src/composerDraftStore.ts | 382 ++--\n apps/web/src/environmentGrouping.test.ts | 4 +-\n .../service.threadSubscriptions.test.ts | 3 +-\n apps/web/src/hooks/useCommitOnBlur.ts | 49 +\n apps/web/src/lib/threadSort.test.ts | 10 +-\n apps/web/src/localApi.test.ts | 11 +-\n apps/web/src/modelOrdering.test.ts | 52 +\n apps/web/src/modelOrdering.ts | 86 +\n apps/web/src/modelSelection.test.ts | 251 +++\n apps/web/src/modelSelection.ts | 271 ++-\n .../web/src/orchestrationEventEffects.test.ts | 5 +-\n apps/web/src/providerInstances.test.ts | 132 ++\n apps/web/src/providerInstances.ts | 248 +++\n apps/web/src/providerModels.ts | 47 +-\n apps/web/src/rpc/serverState.test.ts | 5 +-\n apps/web/src/rpc/wsRpcClient.ts | 12 +-\n apps/web/src/session-logic.ts | 22 +-\n apps/web/src/store.test.ts | 27 +-\n apps/web/src/store.ts | 21 +-\n apps/web/src/types.ts | 6 +-\n apps/web/src/worktreeCleanup.test.ts | 4 +-\n apps/web/vite.config.ts | 8 +-\n docs/providers/claude.md | 224 +++\n docs/providers/codex.md | 140 ++\n packages/contracts/src/index.ts | 1 +\n packages/contracts/src/ipc.ts | 10 +-\n packages/contracts/src/model.ts | 56 +-\n packages/contracts/src/orchestration.test.ts | 111 +-\n packages/contracts/src/orchestration.ts | 99 +-\n packages/contracts/src/provider.test.ts | 145 +-\n packages/contracts/src/provider.ts | 16 +-\n .../contracts/src/providerInstance.test.ts | 192 ++\n packages/contracts/src/providerInstance.ts | 148 ++\n .../contracts/src/providerRuntime.test.ts | 17 +\n packages/contracts/src/providerRuntime.ts | 8 +-\n packages/contracts/src/rpc.ts | 11 +-\n packages/contracts/src/server.test.ts | 24 +-\n packages/contracts/src/server.ts | 55 +-\n packages/contracts/src/settings.test.ts | 94 +\n packages/contracts/src/settings.ts | 99 +-\n packages/shared/src/model.test.ts | 42 +-\n packages/shared/src/model.ts | 28 +-\n packages/shared/src/serverSettings.test.ts | 90 +-\n packages/shared/src/serverSettings.ts | 17 +-\n 205 files changed, 17851 insertions(+), 6517 deletions(-)\n delete mode 100644 apps/server/src/git/Layers/RoutingTextGeneration.ts\n create mode 100644 apps/server/src/git/Layers/TextGenerationLive.test.ts\n create mode 100644 apps/server/src/git/Layers/TextGenerationLive.ts\n create mode 100644 apps/server/src/persistence/Migrations/027_028_ProviderInstanceIdColumns.test.ts\n create mode 100644 apps/server/src/persistence/Migrations/027_ProviderSessionRuntimeInstanceId.ts\n create mode 100644 apps/server/src/persistence/Migrations/028_ProjectionThreadSessionInstanceId.ts\n create mode 100644 apps/server/src/provider/Drivers/ClaudeDriver.ts\n create mode 100644 apps/server/src/provider/Drivers/ClaudeHome.test.ts\n create mode 100644 apps/server/src/provider/Drivers/ClaudeHome.ts\n create mode 100644 apps/server/src/provider/Drivers/CodexDriver.ts\n create mode 100644 apps/server/src/provider/Drivers/CodexHomeLayout.test.ts\n create mode 100644 apps/server/src/provider/Drivers/CodexHomeLayout.ts\n create mode 100644 apps/server/src/provider/Drivers/CursorDriver.ts\n create mode 100644 apps/server/src/provider/Drivers/OpenCodeDriver.ts\n create mode 100644 apps/server/src/provider/Layers/ProviderEventLoggers.ts\n create mode 100644 apps/server/src/provider/Layers/ProviderInstanceRegistryHydration.ts\n create mode 100644 apps/server/src/provider/Layers/ProviderInstanceRegistryLive.test.ts\n create mode 100644 apps/server/src/provider/Layers/ProviderInstanceRegistryLive.ts\n create mode 100644 apps/server/src/provider/Layers/scopedSafeTeardown.test.ts\n create mode 100644 apps/server/src/provider/Layers/scopedSafeTeardown.ts\n create mode 100644 apps/server/src/provider/ProviderDriver.ts\n create mode 100644 apps/server/src/provider/ProviderInstanceEnvironment.test.ts\n create mode 100644 apps/server/src/provider/ProviderInstanceEnvironment.ts\n delete mode 100644 apps/server/src/provider/Services/ClaudeProvider.ts\n delete mode 100644 apps/server/src/provider/Services/CodexProvider.ts\n delete mode 100644 apps/server/src/provider/Services/CursorProvider.ts\n delete mode 100644 apps/server/src/provider/Services/OpenCodeProvider.ts\n create mode 100644 apps/server/src/provider/Services/ProviderInstanceRegistry.ts\n create mode 100644 apps/server/src/provider/Services/ProviderInstanceRegistryMutator.ts\n create mode 100644 apps/server/src/provider/builtInDrivers.ts\n create mode 100644 apps/server/src/provider/testUtils/providerAdapterRegistryMock.ts\n create mode 100644 apps/server/src/provider/unavailableProviderSnapshot.ts\n create mode 100644 apps/web/src/components/chat/ProviderInstanceIcon.tsx\n create mode 100644 apps/web/src/components/settings/AddProviderInstanceDialog.tsx\n create mode 100644 apps/web/src/components/settings/ProviderInstanceCard.test.ts\n create mode 100644 apps/web/src/components/settings/ProviderInstanceCard.tsx\n create mode 100644 apps/web/src/components/settings/ProviderModelsSection.tsx\n create mode 100644 apps/web/src/components/settings/SettingsPanels.logic.test.ts\n create mode 100644 apps/web/src/components/settings/SettingsPanels.logic.ts\n create mode 100644 apps/web/src/components/settings/providerDriverMeta.ts\n create mode 100644 apps/web/src/components/settings/providerStatus.ts\n create mode 100644 apps/web/src/components/ui/draft-input.tsx\n create mode 100644 apps/web/src/hooks/useCommitOnBlur.ts\n create mode 100644 apps/web/src/modelOrdering.test.ts\n create mode 100644 apps/web/src/modelOrdering.ts\n create mode 100644 apps/web/src/modelSelection.test.ts\n create mode 100644 apps/web/src/providerInstances.test.ts\n create mode 100644 apps/web/src/providerInstances.ts\n create mode 100644 docs/providers/claude.md\n create mode 100644 docs/providers/codex.md\n create mode 100644 packages/contracts/src/providerInstance.test.ts\n create mode 100644 packages/contracts/src/providerInstance.ts\n create mode 100644 packages/contracts/src/settings.test.ts\n\ndiff --git a/apps/desktop/src/clientPersistence.test.ts b/apps/desktop/src/clientPersistence.test.ts\nindex 192d7ac106..71b6b7df4e 100644\n--- a/apps/desktop/src/clientPersistence.test.ts\n+++ b/apps/desktop/src/clientPersistence.test.ts\n@@ -54,6 +54,7 @@ const clientSettings: ClientSettings = {\n confirmThreadDelete: false,\n diffWordWrap: true,\n favorites: [],\n+ providerModelPreferences: {},\n sidebarProjectGroupingMode: "repository_path",\n sidebarProjectGroupingOverrides: {\n "environment-1:/tmp/project-a": "separate",\ndiff --git a/apps/server/integration/OrchestrationEngineHarness.integration.ts b/apps/server/integration/OrchestrationEngineHarness.integration.ts\nindex 6f9f4c6f44..d650f62308 100644\n--- a/apps/server/integration/OrchestrationEngineHarness.integration.ts\n+++ b/apps/server/integration/OrchestrationEngineHarness.integration.ts\n@@ -3,7 +3,8 @@ import { execFileSync } from "node:child_process";\n import * as NodeServices from "@effect/platform-node/NodeServices";\n import {\n ApprovalRequestId,\n- ProviderKind,\n+ CodexSettings,\n+ ProviderDriverKind,\n type OrchestrationEvent,\n type OrchestrationThread,\n } from "@t3tools/contracts";\n@@ -36,13 +37,16 @@ import { ProviderSessionRuntimeRepositoryLive } from "../src/persistence/Layers/\n import { makeSqlitePersistenceLive } from "../src/persistence/Layers/Sqlite.ts";\n import { ProjectionCheckpointRepository } from "../src/persistence/Services/ProjectionCheckpoints.ts";\n import { ProjectionPendingApprovalRepository } from "../src/persistence/Services/ProjectionPendingApprovals.ts";\n-import { ProviderUnsupportedError } from "../src/provider/Errors.ts";\n+import { makeAdapterRegistryMock } from "../src/provider/testUtils/providerAdapterRegistryMock.ts";\n import { ProviderAdapterRegistry } from "../src/provider/Services/ProviderAdapterRegistry.ts";\n import { ProviderSessionDirectoryLive } from "../src/provider/Layers/ProviderSessionDirectory.ts";\n import { ServerSettingsService } from "../src/serverSettings.ts";\n import { makeProviderServiceLive } from "../src/provider/Layers/ProviderService.ts";\n-import { makeCodexAdapterLive } from "../src/provider/Layers/CodexAdapter.ts";\n-import { CodexAdapter } from "../src/provider/Services/CodexAdapter.ts";\n+import { makeCodexAdapter } from "../src/provider/Layers/CodexAdapter.ts";\n+import {\n+ NoOpProviderEventLoggers,\n+ ProviderEventLoggers,\n+} from "../src/provider/Layers/ProviderEventLoggers.ts";\n import { ProviderService } from "../src/provider/Services/ProviderService.ts";\n import { AnalyticsService } from "../src/telemetry/Services/AnalyticsService.ts";\n import { CheckpointReactorLive } from "../src/orchestration/Layers/CheckpointReactor.ts";\n@@ -214,7 +218,7 @@ export interface OrchestrationIntegrationHarness {\n }\n \n interface MakeOrchestrationIntegrationHarnessOptions {\n- readonly provider?: ProviderKind;\n+ readonly provider?: ProviderDriverKind;\n readonly realCodex?: boolean;\n }\n \n@@ -225,7 +229,7 @@ export const makeOrchestrationIntegrationHarness = (\n const path = yield* Path.Path;\n const fileSystem = yield* FileSystem.FileSystem;\n \n- const provider = options?.provider ?? "codex";\n+ const provider = options?.provider ?? ProviderDriverKind.make("codex");\n const useRealCodex = options?.realCodex === true;\n const adapterHarness = useRealCodex\n ? null\n@@ -233,13 +237,10 @@ export const makeOrchestrationIntegrationHarness = (\n provider,\n });\n const fakeRegistry = adapterHarness\n- ? Layer.succeed(ProviderAdapterRegistry, {\n- getByProvider: (resolvedProvider) =>\n- resolvedProvider === adapterHarness.provider\n- ? Effect.succeed(adapterHarness.adapter)\n- : Effect.fail(new ProviderUnsupportedError({ provider: resolvedProvider })),\n- listProviders: () => Effect.succeed([adapterHarness.provider]),\n- } as typeof ProviderAdapterRegistry.Service)\n+ ? Layer.succeed(\n+ ProviderAdapterRegistry,\n+ makeAdapterRegistryMock({ [adapterHarness.provider]: adapterHarness.adapter }),\n+ )\n : null;\n const rootDir = yield* fileSystem.makeTempDirectoryScoped({\n prefix: "t3-orchestration-integration-",\n@@ -264,31 +265,30 @@ export const makeOrchestrationIntegrationHarness = (\n const realCodexRegistry = Layer.effect(\n ProviderAdapterRegistry,\n Effect.gen(function* () {\n- const codexAdapter = yield* CodexAdapter;\n- return {\n- getByProvider: (resolvedProvider) =>\n- resolvedProvider === "codex"\n- ? Effect.succeed(codexAdapter)\n- : Effect.fail(new ProviderUnsupportedError({ provider: resolvedProvider })),\n- listProviders: () => Effect.succeed(["codex"] as const),\n- } as typeof ProviderAdapterRegistry.Service;\n+ const codexSettings = Schema.decodeSync(CodexSettings)({});\n+ const codexAdapter = yield* makeCodexAdapter(codexSettings);\n+ return makeAdapterRegistryMock({\n+ [ProviderDriverKind.make("codex")]: codexAdapter,\n+ });\n }),\n ).pipe(\n- Layer.provide(makeCodexAdapterLive()),\n Layer.provideMerge(ServerConfig.layerTest(workspaceDir, rootDir)),\n Layer.provideMerge(NodeServices.layer),\n Layer.provideMerge(providerSessionDirectoryLayer),\n );\n+ const providerEventLoggersLayer = Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers);\n const providerLayer = useRealCodex\n ? makeProviderServiceLive().pipe(\n Layer.provide(providerSessionDirectoryLayer),\n Layer.provide(realCodexRegistry),\n Layer.provide(AnalyticsService.layerTest),\n+ Layer.provide(providerEventLoggersLayer),\n )\n : makeProviderServiceLive().pipe(\n Layer.provide(providerSessionDirectoryLayer),\n Layer.provide(fakeRegistry!),\n Layer.provide(AnalyticsService.layerTest),\n+ Layer.provide(providerEventLoggersLayer),\n );\n \n const checkpointStoreLayer = CheckpointStoreLive.pipe(Layer.provide(GitCoreLive));\ndiff --git a/apps/server/integration/TestProviderAdapter.integration.ts b/apps/server/integration/TestProviderAdapter.integration.ts\nindex f497395307..9ed58c0a5b 100644\n--- a/apps/server/integration/TestProviderAdapter.integration.ts\n+++ b/apps/server/integration/TestProviderAdapter.integration.ts\n@@ -10,7 +10,7 @@ import {\n ProviderTurnStartResult,\n ThreadId,\n TurnId,\n- ProviderKind,\n+ ProviderDriverKind,\n } from "@t3tools/contracts";\n import { Effect, Queue, Stream } from "effect";\n \n@@ -36,7 +36,7 @@ export interface TestTurnResponse {\n export type FixtureProviderRuntimeEvent = {\n readonly type: string;\n readonly eventId: EventId;\n- readonly provider: ProviderKind;\n+ readonly provider: ProviderDriverKind;\n readonly createdAt: string;\n readonly threadId: string;\n readonly turnId?: string | undefined;\n@@ -178,7 +178,7 @@ function normalizeFixtureEvent(rawEvent: Record<string, unknown>): ProviderRunti\n \n export interface TestProviderAdapterHarness {\n readonly adapter: ProviderAdapterShape<ProviderAdapterError>;\n- readonly provider: ProviderKind;\n+ readonly provider: ProviderDriverKind;\n readonly queueTurnResponse: (\n threadId: ThreadId,\n response: TestTurnResponse,\n@@ -198,7 +198,7 @@ export interface TestProviderAdapterHarness {\n }\n \n interface MakeTestProviderAdapterHarnessOptions {\n- readonly provider?: ProviderKind;\n+ readonly provider?: ProviderDriverKind;\n }\n \n function nowIso(): string {\n@@ -206,7 +206,7 @@ function nowIso(): string {\n }\n \n function sessionNotFound(\n- provider: ProviderKind,\n+ provider: ProviderDriverKind,\n threadId: ThreadId,\n ): ProviderAdapterSessionNotFoundError {\n return new ProviderAdapterSessionNotFoundError({\n@@ -216,7 +216,7 @@ function sessionNotFound(\n }\n \n function missingSessionEffect(\n- provider: ProviderKind,\n+ provider: ProviderDriverKind,\n threadId: ThreadId,\n ): Effect.Effect<never, ProviderAdapterError> {\n return Effect.fail(sessionNotFound(provider, threadId));\n@@ -224,7 +224,7 @@ function missingSessionEffect(\n \n export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapterHarnessOptions) =>\n Effect.gen(function* () {\n- const provider = options?.provider ?? "codex";\n+ const provider = options?.provider ?? ProviderDriverKind.make("codex");\n const runtimeEvents = yield* Queue.unbounded<ProviderRuntimeEvent>();\n let sessionCount = 0;\n const sessions = new Map<ThreadId, SessionState>();\n@@ -257,6 +257,9 @@ export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapter\n \n const session: ProviderSession = {\n provider,\n+ ...(input.providerInstanceId !== undefined\n+ ? { providerInstanceId: input.providerInstanceId }\n+ : {}),\n status: "ready",\n runtimeMode: input.runtimeMode,\n threadId,\ndiff --git a/apps/server/integration/fixtures/providerRuntime.ts b/apps/server/integration/fixtures/providerRuntime.ts\nindex 14a45518c3..e1258c4cc6 100644\n--- a/apps/server/integration/fixtures/providerRuntime.ts\n+++ b/apps/server/integration/fixtures/providerRuntime.ts\n@@ -1,7 +1,7 @@\n-import { EventId, RuntimeRequestId } from "@t3tools/contracts";\n+import { EventId, ProviderDriverKind, RuntimeRequestId } from "@t3tools/contracts";\n import type { LegacyProviderRuntimeEvent } from "../TestProviderAdapter.integration.ts";\n \n-const PROVIDER = "codex" as const;\n+const PROVIDER = ProviderDriverKind.make("codex");\n const SESSION_ID = "fixture-session";\n const THREAD_ID = "fixture-thread";\n const TURN_ID = "fixture-turn";\ndiff --git a/apps/server/integration/orchestrationEngine.integration.test.ts b/apps/server/integration/orchestrationEngine.integration.test.ts\nindex a7f845672c..6ea4d84908 100644\n--- a/apps/server/integration/orchestrationEngine.integration.test.ts\n+++ b/apps/server/integration/orchestrationEngine.integration.test.ts\n@@ -4,14 +4,17 @@ import path from "node:path";\n import {\n ApprovalRequestId,\n CommandId,\n+ defaultInstanceIdForDriver,\n DEFAULT_PROVIDER_INTERACTION_MODE,\n+ DEFAULT_MODEL,\n DEFAULT_MODEL_BY_PROVIDER,\n EventId,\n MessageId,\n ProjectId,\n- ProviderKind,\n+ ProviderDriverKind,\n ThreadId,\n ModelSelection,\n+ ProviderInstanceId,\n } from "@t3tools/contracts";\n import { assert, it } from "@effect/vitest";\n import { Effect, Option, Schema } from "effect";\n@@ -39,7 +42,9 @@ const PROJECT_ID = asProjectId("project-1");\n const THREAD_ID = ThreadId.make("thread-1");\n const FIXTURE_TURN_ID = "fixture-turn";\n const APPROVAL_REQUEST_ID = asApprovalRequestId("req-approval-1");\n-type IntegrationProvider = ProviderKind;\n+type IntegrationProvider = ProviderDriverKind;\n+const CODEX_PROVIDER = ProviderDriverKind.make("codex");\n+const CLAUDE_AGENT_PROVIDER = ProviderDriverKind.make("claudeAgent");\n \n function nowIso() {\n return new Date().toISOString();\n@@ -74,7 +79,11 @@ function waitForSync<A>(\n });\n }\n \n-function runtimeBase(eventId: string, createdAt: string, provider: IntegrationProvider = "codex") {\n+function runtimeBase(\n+ eventId: string,\n+ createdAt: string,\n+ provider: IntegrationProvider = CODEX_PROVIDER,\n+) {\n return {\n eventId: asEventId(eventId),\n provider,\n@@ -84,7 +93,7 @@ function runtimeBase(eventId: string, createdAt: string, provider: IntegrationPr\n \n function withHarness<A, E>(\n use: (harness: OrchestrationIntegrationHarness) => Effect.Effect<A, E>,\n- provider: IntegrationProvider = "codex",\n+ provider: IntegrationProvider = CODEX_PROVIDER,\n ) {\n return Effect.acquireUseRelease(\n makeOrchestrationIntegrationHarness({ provider }),\n@@ -97,7 +106,7 @@ function withRealCodexHarness<A, E>(\n use: (harness: OrchestrationIntegrationHarness) => Effect.Effect<A, E>,\n ) {\n return Effect.acquireUseRelease(\n- makeOrchestrationIntegrationHarness({ provider: "codex", realCodex: true }),\n+ makeOrchestrationIntegrationHarness({ provider: CODEX_PROVIDER, realCodex: true }),\n use,\n (harness) => harness.dispose,\n ).pipe(Effect.provide(NodeServices.layer));\n@@ -106,8 +115,9 @@ function withRealCodexHarness<A, E>(\n const seedProjectAndThread = (harness: OrchestrationIntegrationHarness) =>\n Effect.gen(function* () {\n const createdAt = nowIso();\n- const provider = harness.adapterHarness?.provider ?? "codex";\n- const defaultModel = DEFAULT_MODEL_BY_PROVIDER[provider];\n+ const provider = harness.adapterHarness?.provider ?? CODEX_PROVIDER;\n+ const defaultModel = DEFAULT_MODEL_BY_PROVIDER[provider] ?? DEFAULT_MODEL;\n+ const instanceId = defaultInstanceIdForDriver(provider);\n \n yield* harness.engine.dispatch({\n type: "project.create",\n@@ -116,7 +126,7 @@ const seedProjectAndThread = (harness: OrchestrationIntegrationHarness) =>\n title: "Integration Project",\n workspaceRoot: harness.workspaceDir,\n defaultModelSelection: {\n- provider,\n+ instanceId,\n model: defaultModel,\n },\n createdAt,\n@@ -129,7 +139,7 @@ const seedProjectAndThread = (harness: OrchestrationIntegrationHarness) =>\n projectId: PROJECT_ID,\n title: "Integration Thread",\n modelSelection: {\n- provider,\n+ instanceId,\n model: defaultModel,\n },\n interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,\n@@ -265,7 +275,7 @@ it.live.skipIf(!process.env.CODEX_BINARY_PATH)(\n title: "Integration Project",\n workspaceRoot: harness.workspaceDir,\n defaultModelSelection: {\n- provider: "codex",\n+ instanceId: ProviderInstanceId.make("codex"),\n model: "gpt-5.3-codex",\n },\n createdAt,\n@@ -278,7 +288,7 @@ it.live.skipIf(!process.env.CODEX_BINARY_PATH)(\n projectId: PROJECT_ID,\n title: "Integration Thread",\n modelSelection: {\n- provider: "codex",\n+ instanceId: ProviderInstanceId.make("codex"),\n model: "gpt-5.3-codex",\n },\n interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,\n@@ -912,20 +922,32 @@ it.live("starts a claudeAgent session on first turn when provider is requested",\n events: [\n {\n type: "turn.started",\n- ...runtimeBase("evt-claude-start-1", "2026-02-24T10:10:00.000Z", "claudeAgent"),\n+ ...runtimeBase(\n+ "evt-claude-start-1",\n+ "2026-02-24T10:10:00.000Z",\n+ CLAUDE_AGENT_PROVIDER,\n+ ),\n threadId: THREAD_ID,\n turnId: FIXTURE_TURN_ID,\n },\n {\n type: "message.delta",\n- ...runtimeBase("evt-claude-start-2", "2026-02-24T10:10:00.050Z", "claudeAgent"),\n+ ...runtimeBase(\n+ "evt-claude-start-2",\n+ "2026-02-24T10:10:00.050Z",\n+ CLAUDE_AGENT_PROVIDER,\n+ ),\n threadId: THREAD_ID,\n turnId: FIXTURE_TURN_ID,\n delta: "Claude first turn.\\n",\n },\n {\n type: "turn.completed",\n- ...runtimeBase("evt-claude-start-3", "2026-02-24T10:10:00.100Z", "claudeAgent"),\n+ ...runtimeBase(\n+ "evt-claude-start-3",\n+ "2026-02-24T10:10:00.100Z",\n+ CLAUDE_AGENT_PROVIDER,\n+ ),\n threadId: THREAD_ID,\n turnId: FIXTURE_TURN_ID,\n status: "completed",\n@@ -939,7 +961,7 @@ it.live("starts a claudeAgent session on first turn when provider is requested",\n messageId: "msg-user-claude-initial",\n text: "Use Claude",\n modelSelection: {\n- provider: "claudeAgent",\n+ instanceId: ProviderInstanceId.make("claudeAgent"),\n model: "claude-sonnet-4-6",\n },\n });\n@@ -955,7 +977,7 @@ it.live("starts a claudeAgent session on first turn when provider is requested",\n );\n assert.equal(thread.session?.providerName, "claudeAgent");\n }),\n- "claudeAgent",\n+ CLAUDE_AGENT_PROVIDER,\n ),\n );\n \n@@ -969,20 +991,32 @@ it.live("recovers claudeAgent sessions after provider stopAll using persisted re\n events: [\n {\n type: "turn.started",\n- ...runtimeBase("evt-claude-recover-1", "2026-02-24T10:11:00.000Z", "claudeAgent"),\n+ ...runtimeBase(\n+ "evt-claude-recover-1",\n+ "2026-02-24T10:11:00.000Z",\n+ CLAUDE_AGENT_PROVIDER,\n+ ),\n threadId: THREAD_ID,\n turnId: FIXTURE_TURN_ID,\n },\n {\n type: "message.delta",\n- ...runtimeBase("evt-claude-recover-2", "2026-02-24T10:11:00.050Z", "claudeAgent"),\n+ ...runtimeBase(\n+ "evt-claude-recover-2",\n+ "2026-02-24T10:11:00.050Z",\n+ CLAUDE_AGENT_PROVIDER,\n+ ),\n threadId: THREAD_ID,\n turnId: FIXTURE_TURN_ID,\n delta: "Turn before restart.\\n",\n },\n {\n type: "turn.completed",\n- ...runtimeBase("evt-claude-recover-3", "2026-02-24T10:11:00.100Z", "claudeAgent"),\n+ ...runtimeBase(\n+ "evt-claude-recover-3",\n+ "2026-02-24T10:11:00.100Z",\n+ CLAUDE_AGENT_PROVIDER,\n+ ),\n threadId: THREAD_ID,\n turnId: FIXTURE_TURN_ID,\n status: "completed",\n@@ -996,7 +1030,7 @@ it.live("recovers claudeAgent sessions after provider stopAll using persisted re\n messageId: "msg-user-claude-recover-1",\n text: "Before restart",\n modelSelection: {\n- provider: "claudeAgent",\n+ instanceId: ProviderInstanceId.make("claudeAgent"),\n model: "claude-sonnet-4-6",\n },\n });\n@@ -1018,20 +1052,32 @@ it.live("recovers claudeAgent sessions after provider stopAll using persisted re\n events: [\n {\n type: "turn.started",\n- ...runtimeBase("evt-claude-recover-4", "2026-02-24T10:11:01.000Z", "claudeAgent"),\n+ ...runtimeBase(\n+ "evt-claude-recover-4",\n+ "2026-02-24T10:11:01.000Z",\n+ CLAUDE_AGENT_PROVIDER,\n+ ),\n threadId: THREAD_ID,\n turnId: FIXTURE_TURN_ID,\n },\n {\n type: "message.delta",\n- ...runtimeBase("evt-claude-recover-5", "2026-02-24T10:11:01.050Z", "claudeAgent"),\n+ ...runtimeBase(\n+ "evt-claude-recover-5",\n+ "2026-02-24T10:11:01.050Z",\n+ CLAUDE_AGENT_PROVIDER,\n+ ),\n threadId: THREAD_ID,\n turnId: FIXTURE_TURN_ID,\n delta: "Turn after restart.\\n",\n },\n {\n type: "turn.completed",\n- ...runtimeBase("evt-claude-recover-6", "2026-02-24T10:11:01.100Z", "claudeAgent"),\n+ ...runtimeBase(\n+ "evt-claude-recover-6",\n+ "2026-02-24T10:11:01.100Z",\n+ CLAUDE_AGENT_PROVIDER,\n+ ),\n threadId: THREAD_ID,\n turnId: FIXTURE_TURN_ID,\n status: "completed",\n@@ -1063,7 +1109,7 @@ it.live("recovers claudeAgent sessions after provider stopAll using persisted re\n assert.equal(recoveredThread.session?.providerName, "claudeAgent");\n assert.equal(recoveredThread.session?.threadId, "thread-1");\n }),\n- "claudeAgent",\n+ CLAUDE_AGENT_PROVIDER,\n ),\n );\n \n@@ -1077,13 +1123,21 @@ it.live("forwards claudeAgent approval responses to the provider session", () =>\n events: [\n {\n type: "turn.started",\n- ...runtimeBase("evt-claude-approval-1", "2026-02-24T10:12:00.000Z", "claudeAgent"),\n+ ...runtimeBase(\n+ "evt-claude-approval-1",\n+ "2026-02-24T10:12:00.000Z",\n+ CLAUDE_AGENT_PROVIDER,\n+ ),\n threadId: THREAD_ID,\n turnId: FIXTURE_TURN_ID,\n },\n {\n type: "approval.requested",\n- ...runtimeBase("evt-claude-approval-2", "2026-02-24T10:12:00.050Z", "claudeAgent"),\n+ ...runtimeBase(\n+ "evt-claude-approval-2",\n+ "2026-02-24T10:12:00.050Z",\n+ CLAUDE_AGENT_PROVIDER,\n+ ),\n threadId: THREAD_ID,\n turnId: FIXTURE_TURN_ID,\n requestId: APPROVAL_REQUEST_ID,\n@@ -1092,7 +1146,11 @@ it.live("forwards claudeAgent approval responses to the provider session", () =>\n },\n {\n type: "turn.completed",\n- ...runtimeBase("evt-claude-approval-3", "2026-02-24T10:12:00.100Z", "claudeAgent"),\n+ ...runtimeBase(\n+ "evt-claude-approval-3",\n+ "2026-02-24T10:12:00.100Z",\n+ CLAUDE_AGENT_PROVIDER,\n+ ),\n threadId: THREAD_ID,\n turnId: FIXTURE_TURN_ID,\n status: "completed",\n@@ -1106,7 +1164,7 @@ it.live("forwards claudeAgent approval responses to the provider session", () =>\n messageId: "msg-user-claude-approval",\n text: "Need approval",\n modelSelection: {\n- provider: "claudeAgent",\n+ instanceId: ProviderInstanceId.make("claudeAgent"),\n model: "claude-sonnet-4-6",\n },\n });\n@@ -1137,7 +1195,7 @@ it.live("forwards claudeAgent approval responses to the provider session", () =>\n );\n assert.equal(approvalResponses[0]?.decision, "accept");\n }),\n- "claudeAgent",\n+ CLAUDE_AGENT_PROVIDER,\n ),\n );\n \n@@ -1151,20 +1209,32 @@ it.live("forwards thread.turn.interrupt to claudeAgent provider sessions", () =>\n events: [\n {\n type: "turn.started",\n- ...runtimeBase("evt-claude-interrupt-1", "2026-02-24T10:13:00.000Z", "claudeAgent"),\n+ ...runtimeBase(\n+ "evt-claude-interrupt-1",\n+ "2026-02-24T10:13:00.000Z",\n+ CLAUDE_AGENT_PROVIDER,\n+ ),\n threadId: THREAD_ID,\n turnId: FIXTURE_TURN_ID,\n },\n {\n type: "message.delta",\n- ...runtimeBase("evt-claude-interrupt-2", "2026-02-24T10:13:00.050Z", "claudeAgent"),\n+ ...runtimeBase(\n+ "evt-claude-interrupt-2",\n+ "2026-02-24T10:13:00.050Z",\n+ CLAUDE_AGENT_PROVIDER,\n+ ),\n threadId: THREAD_ID,\n turnId: FIXTURE_TURN_ID,\n delta: "Long running output.\\n",\n },\n {\n type: "turn.completed",\n- ...runtimeBase("evt-claude-interrupt-3", "2026-02-24T10:13:00.100Z", "claudeAgent"),\n+ ...runtimeBase(\n+ "evt-claude-interrupt-3",\n+ "2026-02-24T10:13:00.100Z",\n+ CLAUDE_AGENT_PROVIDER,\n+ ),\n threadId: THREAD_ID,\n turnId: FIXTURE_TURN_ID,\n status: "completed",\n@@ -1178,7 +1248,7 @@ it.live("forwards thread.turn.interrupt to claudeAgent provider sessions", () =>\n messageId: "msg-user-claude-interrupt",\n text: "Start long turn",\n modelSelection: {\n- provider: "claudeAgent",\n+ instanceId: ProviderInstanceId.make("claudeAgent"),\n model: "claude-sonnet-4-6",\n },\n });\n@@ -1206,7 +1276,7 @@ it.live("forwards thread.turn.interrupt to claudeAgent provider sessions", () =>\n );\n assert.equal(interruptCalls.length, 1);\n }),\n- "claudeAgent",\n+ CLAUDE_AGENT_PROVIDER,\n ),\n );\n \n@@ -1220,20 +1290,32 @@ it.live("reverts claudeAgent turns and rolls back provider conversation state",\n events: [\n {\n type: "turn.started",\n- ...runtimeBase("evt-claude-revert-1", "2026-02-24T10:14:00.000Z", "claudeAgent"),\n+ ...runtimeBase(\n+ "evt-claude-revert-1",\n+ "2026-02-24T10:14:00.000Z",\n+ CLAUDE_AGENT_PROVIDER,\n+ ),\n threadId: THREAD_ID,\n turnId: FIXTURE_TURN_ID,\n },\n {\n type: "message.delta",\n- ...runtimeBase("evt-claude-revert-2", "2026-02-24T10:14:00.050Z", "claudeAgent"),\n+ ...runtimeBase(\n+ "evt-claude-revert-2",\n+ "2026-02-24T10:14:00.050Z",\n+ CLAUDE_AGENT_PROVIDER,\n+ ),\n threadId: THREAD_ID,\n turnId: FIXTURE_TURN_ID,\n delta: "README -> v2\\n",\n },\n {\n type: "turn.completed",\n- ...runtimeBase("evt-claude-revert-3", "2026-02-24T10:14:00.100Z", "claudeAgent"),\n+ ...runtimeBase(\n+ "evt-claude-revert-3",\n+ "2026-02-24T10:14:00.100Z",\n+ CLAUDE_AGENT_PROVIDER,\n+ ),\n threadId: THREAD_ID,\n turnId: FIXTURE_TURN_ID,\n status: "completed",\n@@ -1251,7 +1333,7 @@ it.live("reverts claudeAgent turns and rolls back provider conversation state",\n messageId: "msg-user-claude-revert-1",\n text: "First Claude edit",\n modelSelection: {\n- provider: "claudeAgent",\n+ instanceId: ProviderInstanceId.make("claudeAgent"),\n model: "claude-sonnet-4-6",\n },\n });\n@@ -1266,20 +1348,32 @@ it.live("reverts claudeAgent turns and rolls back provider conversation state",\n events: [\n {\n type: "turn.started",\n- ...runtimeBase("evt-claude-revert-4", "2026-02-24T10:14:01.000Z", "claudeAgent"),\n+ ...runtimeBase(\n+ "evt-claude-revert-4",\n+ "2026-02-24T10:14:01.000Z",\n+ CLAUDE_AGENT_PROVIDER,\n+ ),\n threadId: THREAD_ID,\n turnId: FIXTURE_TURN_ID,\n },\n {\n type: "message.delta",\n- ...runtimeBase("evt-claude-revert-5", "2026-02-24T10:14:01.050Z", "claudeAgent"),\n+ ...runtimeBase(\n+ "evt-claude-revert-5",\n+ "2026-02-24T10:14:01.050Z",\n+ CLAUDE_AGENT_PROVIDER,\n+ ),\n threadId: THREAD_ID,\n turnId: FIXTURE_TURN_ID,\n delta: "README -> v3\\n",\n },\n {\n type: "turn.completed",\n- ...runtimeBase("evt-claude-revert-6", "2026-02-24T10:14:01.100Z", "claudeAgent"),\n+ ...runtimeBase(\n+ "evt-claude-revert-6",\n+ "2026-02-24T10:14:01.100Z",\n+ CLAUDE_AGENT_PROVIDER,\n+ ),\n threadId: THREAD_ID,\n turnId: FIXTURE_TURN_ID,\n status: "completed",\n@@ -1330,6 +1424,6 @@ it.live("reverts claudeAgent turns and rolls back provider conversation state",\n );\n assert.deepEqual(harness.adapterHarness!.getRollbackCalls(THREAD_ID), [1]);\n }),\n- "claudeAgent",\n+ CLAUDE_AGENT_PROVIDER,\n ),\n );\ndiff --git a/apps/server/integration/providerService.integration.test.ts b/apps/server/integration/providerService.integration.test.ts\nindex 89cf6ac153..60fe01d4c2 100644\n--- a/apps/server/integration/providerService.integration.test.ts\n+++ b/apps/server/integration/providerService.integration.test.ts\n@@ -1,13 +1,17 @@\n import type { ProviderRuntimeEvent } from "@t3tools/contracts";\n-import { ThreadId } from "@t3tools/contracts";\n+import { ProviderDriverKind, ProviderInstanceId, ThreadId } from "@t3tools/contracts";\n import { DEFAULT_SERVER_SETTINGS } from "@t3tools/contracts/settings";\n import * as NodeServices from "@effect/platform-node/NodeServices";\n import { it, assert } from "@effect/vitest";\n import { Effect, FileSystem, Layer, Path, Queue, Stream } from "effect";\n \n-import { ProviderUnsupportedError } from "../src/provider/Errors.ts";\n import { ProviderAdapterRegistry } from "../src/provider/Services/ProviderAdapterRegistry.ts";\n+import { makeAdapterRegistryMock } from "../src/provider/testUtils/providerAdapterRegistryMock.ts";\n import { ProviderSessionDirectoryLive } from "../src/provider/Layers/ProviderSessionDirectory.ts";\n+import {\n+ NoOpProviderEventLoggers,\n+ ProviderEventLoggers,\n+} from "../src/provider/Layers/ProviderEventLoggers.ts";\n import { makeProviderServiceLive } from "../src/provider/Layers/ProviderService.ts";\n import {\n ProviderService,\n@@ -29,6 +33,8 @@ import {\n codexTurnTextFixture,\n } from "./fixtures/providerRuntime.ts";\n \n+const codexInstanceId = ProviderInstanceId.make("codex");\n+\n const makeWorkspaceDirectory = Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const pathService = yield* Path.Path;\n@@ -47,13 +53,9 @@ const makeIntegrationFixture = Effect.gen(function* () {\n const cwd = yield* makeWorkspaceDirectory;\n const harness = yield* makeTestProviderAdapterHarness();\n \n- const registry: typeof ProviderAdapterRegistry.Service = {\n- getByProvider: (provider) =>\n- provider === "codex"\n- ? Effect.succeed(harness.adapter)\n- : Effect.fail(new ProviderUnsupportedError({ provider })),\n- listProviders: () => Effect.succeed(["codex"]),\n- };\n+ const registry = makeAdapterRegistryMock({\n+ [ProviderDriverKind.make("codex")]: harness.adapter,\n+ });\n \n const directoryLayer = ProviderSessionDirectoryLive.pipe(\n Layer.provide(ProviderSessionRuntimeRepositoryLive),\n@@ -64,6 +66,7 @@ const makeIntegrationFixture = Effect.gen(function* () {\n Layer.succeed(ProviderAdapterRegistry, registry),\n ServerSettingsService.layerTest(DEFAULT_SERVER_SETTINGS),\n AnalyticsService.layerTest,\n+ Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers),\n ).pipe(Layer.provide(SqlitePersistenceMemory));\n \n const layer = makeProviderServiceLive().pipe(Layer.provide(shared));\n@@ -124,7 +127,8 @@ it.live("replays typed runtime fixture events", () =>\n const provider = yield* ProviderService;\n const session = yield* provider.startSession(ThreadId.make("thread-integration-typed"), {\n threadId: ThreadId.make("thread-integration-typed"),\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n+ providerInstanceId: codexInstanceId,\n cwd: fixture.cwd,\n runtimeMode: "full-access",\n });\n@@ -142,6 +146,10 @@ it.live("replays typed runtime fixture events", () =>\n observedEvents.map((event) => event.type),\n codexTurnTextFixture.map((event) => event.type),\n );\n+ assert.deepEqual(\n+ observedEvents.map((event) => event.providerInstanceId),\n+ codexTurnTextFixture.map(() => codexInstanceId),\n+ );\n }).pipe(Effect.provide(fixture.layer));\n }).pipe(Effect.provide(NodeServices.layer)),\n );\n@@ -156,7 +164,8 @@ it.live("replays file-changing fixture turn events", () =>\n const provider = yield* ProviderService;\n const session = yield* provider.startSession(ThreadId.make("thread-integration-tools"), {\n threadId: ThreadId.make("thread-integration-tools"),\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n+ providerInstanceId: codexInstanceId,\n cwd: fixture.cwd,\n runtimeMode: "full-access",\n });\n@@ -192,7 +201,8 @@ it.live("runs multi-turn tool/approval flow", () =>\n const provider = yield* ProviderService;\n const session = yield* provider.startSession(ThreadId.make("thread-integration-multi"), {\n threadId: ThreadId.make("thread-integration-multi"),\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n+ providerInstanceId: codexInstanceId,\n cwd: fixture.cwd,\n runtimeMode: "full-access",\n });\n@@ -243,7 +253,8 @@ it.live("rolls back provider conversation state only", () =>\n const provider = yield* ProviderService;\n const session = yield* provider.startSession(ThreadId.make("thread-integration-rollback"), {\n threadId: ThreadId.make("thread-integration-rollback"),\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n+ providerInstanceId: codexInstanceId,\n cwd: fixture.cwd,\n runtimeMode: "full-access",\n });\ndiff --git a/apps/server/src/git/Layers/ClaudeTextGeneration.test.ts b/apps/server/src/git/Layers/ClaudeTextGeneration.test.ts\nindex 773f781eed..eb7bf62ad4 100644\n--- a/apps/server/src/git/Layers/ClaudeTextGeneration.test.ts\n+++ b/apps/server/src/git/Layers/ClaudeTextGeneration.test.ts\n@@ -1,24 +1,18 @@\n+import { ClaudeSettings, ProviderInstanceId } from "@t3tools/contracts";\n import * as NodeServices from "@effect/platform-node/NodeServices";\n import { it } from "@effect/vitest";\n-import { Effect, FileSystem, Layer, Path } from "effect";\n+import { Effect, FileSystem, Layer, Path, Schema } from "effect";\n import { createModelSelection } from "@t3tools/shared/model";\n import { expect } from "vitest";\n \n import { ServerConfig } from "../../config.ts";\n-import { TextGeneration } from "../Services/TextGeneration.ts";\n+import { type TextGenerationShape } from "../Services/TextGeneration.ts";\n import { sanitizeThreadTitle } from "../Utils.ts";\n-import { ClaudeTextGenerationLive } from "./ClaudeTextGeneration.ts";\n-import { ServerSettingsService } from "../../serverSettings.ts";\n+import { makeClaudeTextGeneration } from "./ClaudeTextGeneration.ts";\n \n-const ClaudeTextGenerationTestLayer = ClaudeTextGenerationLive.pipe(\n- Layer.provideMerge(ServerSettingsService.layerTest()),\n- Layer.provideMerge(\n- ServerConfig.layerTest(process.cwd(), {\n- prefix: "t3code-claude-text-generation-test-",\n- }),\n- ),\n- Layer.provideMerge(NodeServices.layer),\n-);\n+const ClaudeTextGenerationTestLayer = ServerConfig.layerTest(process.cwd(), {\n+ prefix: "t3code-claude-text-generation-test-",\n+}).pipe(Layer.provideMerge(NodeServices.layer));\n \n function makeFakeClaudeBinary(dir: string) {\n return Effect.gen(function* () {\n@@ -52,6 +46,10 @@ function makeFakeClaudeBinary(dir: string) {\n " exit 4",\n " }",\n "fi",\n+ \'if [ -n "$T3_FAKE_CLAUDE_HOME_MUST_BE" ] && [ "$HOME" != "$T3_FAKE_CLAUDE_HOME_MUST_BE" ]; then\',\n+ \' printf "%s\\\\n" "HOME was $HOME" >&2\',\n+ " exit 5",\n+ "fi",\n \'if [ -n "$T3_FAKE_CLAUDE_STDERR" ]; then\',\n \' printf "%s\\\\n" "$T3_FAKE_CLAUDE_STDERR" >&2\',\n "fi",\n@@ -73,23 +71,26 @@ function withFakeClaudeEnv<A, E, R>(\n argsMustContain?: string;\n argsMustNotContain?: string;\n stdinMustContain?: string;\n+ homeMustBe?: string;\n+ claudeConfig?: Partial<ClaudeSettings>;\n },\n- effect: Effect.Effect<A, E, R>,\n+ effectFn: (textGeneration: TextGenerationShape) => Effect.Effect<A, E, R>,\n ) {\n- return Effect.acquireUseRelease(\n- Effect.gen(function* () {\n- const fs = yield* FileSystem.FileSystem;\n- const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-claude-text-" });\n- const binDir = yield* makeFakeClaudeBinary(tempDir);\n- const previousPath = process.env.PATH;\n- const previousOutput = process.env.T3_FAKE_CLAUDE_OUTPUT;\n- const previousExitCode = process.env.T3_FAKE_CLAUDE_EXIT_CODE;\n- const previousStderr = process.env.T3_FAKE_CLAUDE_STDERR;\n- const previousArgsMustContain = process.env.T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN;\n- const previousArgsMustNotContain = process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN;\n- const previousStdinMustContain = process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN;\n+ return Effect.gen(function* () {\n+ const fs = yield* FileSystem.FileSystem;\n+ const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-claude-text-" });\n+ const binDir = yield* makeFakeClaudeBinary(tempDir);\n+ const previousPath = process.env.PATH;\n+ const previousOutput = process.env.T3_FAKE_CLAUDE_OUTPUT;\n+ const previousExitCode = process.env.T3_FAKE_CLAUDE_EXIT_CODE;\n+ const previousStderr = process.env.T3_FAKE_CLAUDE_STDERR;\n+ const previousArgsMustContain = process.env.T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN;\n+ const previousArgsMustNotContain = process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN;\n+ const previousStdinMustContain = process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN;\n+ const previousHomeMustBe = process.env.T3_FAKE_CLAUDE_HOME_MUST_BE;\n \n- yield* Effect.sync(() => {\n+ yield* Effect.acquireRelease(\n+ Effect.sync(() => {\n process.env.PATH = `${binDir}:${previousPath ?? ""}`;\n process.env.T3_FAKE_CLAUDE_OUTPUT = input.output;\n \n@@ -122,60 +123,65 @@ function withFakeClaudeEnv<A, E, R>(\n } else {\n delete process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN;\n }\n- });\n-\n- return {\n- previousPath,\n- previousOutput,\n- previousExitCode,\n- previousStderr,\n- previousArgsMustContain,\n- previousArgsMustNotContain,\n- previousStdinMustContain,\n- };\n- }),\n- () => effect,\n- (previous) =>\n- Effect.sync(() => {\n- process.env.PATH = previous.previousPath;\n \n- if (previous.previousOutput === undefined) {\n- delete process.env.T3_FAKE_CLAUDE_OUTPUT;\n+ if (input.homeMustBe !== undefined) {\n+ process.env.T3_FAKE_CLAUDE_HOME_MUST_BE = input.homeMustBe;\n } else {\n- process.env.T3_FAKE_CLAUDE_OUTPUT = previous.previousOutput;\n+ delete process.env.T3_FAKE_CLAUDE_HOME_MUST_BE;\n }\n+ }),\n+ () =>\n+ Effect.sync(() => {\n+ process.env.PATH = previousPath;\n \n- if (previous.previousExitCode === undefined) {\n- delete process.env.T3_FAKE_CLAUDE_EXIT_CODE;\n- } else {\n- process.env.T3_FAKE_CLAUDE_EXIT_CODE = previous.previousExitCode;\n- }\n+ if (previousOutput === undefined) {\n+ delete process.env.T3_FAKE_CLAUDE_OUTPUT;\n+ } else {\n+ process.env.T3_FAKE_CLAUDE_OUTPUT = previousOutput;\n+ }\n \n- if (previous.previousStderr === undefined) {\n- delete process.env.T3_FAKE_CLAUDE_STDERR;\n- } else {\n- process.env.T3_FAKE_CLAUDE_STDERR = previous.previousStderr;\n- }\n+ if (previousExitCode === undefined) {\n+ delete process.env.T3_FAKE_CLAUDE_EXIT_CODE;\n+ } else {\n+ process.env.T3_FAKE_CLAUDE_EXIT_CODE = previousExitCode;\n+ }\n \n- if (previous.previousArgsMustContain === undefined) {\n- delete process.env.T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN;\n- } else {\n- process.env.T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN = previous.previousArgsMustContain;\n- }\n+ if (previousStderr === undefined) {\n+ delete process.env.T3_FAKE_CLAUDE_STDERR;\n+ } else {\n+ process.env.T3_FAKE_CLAUDE_STDERR = previousStderr;\n+ }\n \n- if (previous.previousArgsMustNotContain === undefined) {\n- delete process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN;\n- } else {\n- process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN = previous.previousArgsMustNotContain;\n- }\n+ if (previousArgsMustContain === undefined) {\n+ delete process.env.T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN;\n+ } else {\n+ process.env.T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN = previousArgsMustContain;\n+ }\n \n- if (previous.previousStdinMustContain === undefined) {\n- delete process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN;\n- } else {\n- process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN = previous.previousStdinMustContain;\n- }\n- }),\n- );\n+ if (previousArgsMustNotContain === undefined) {\n+ delete process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN;\n+ } else {\n+ process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN = previousArgsMustNotContain;\n+ }\n+\n+ if (previousStdinMustContain === undefined) {\n+ delete process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN;\n+ } else {\n+ process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN = previousStdinMustContain;\n+ }\n+\n+ if (previousHomeMustBe === undefined) {\n+ delete process.env.T3_FAKE_CLAUDE_HOME_MUST_BE;\n+ } else {\n+ process.env.T3_FAKE_CLAUDE_HOME_MUST_BE = previousHomeMustBe;\n+ }\n+ }),\n+ );\n+\n+ const config = Schema.decodeSync(ClaudeSettings)(input.claudeConfig ?? {});\n+ const textGeneration = yield* makeClaudeTextGeneration(config);\n+ return yield* effectFn(textGeneration);\n+ }).pipe(Effect.scoped);\n }\n \n it.layer(ClaudeTextGenerationTestLayer)("ClaudeTextGenerationLive", (it) => {\n@@ -191,24 +197,23 @@ it.layer(ClaudeTextGenerationTestLayer)("ClaudeTextGenerationLive", (it) => {\n argsMustContain: \'--settings {"alwaysThinkingEnabled":false}\',\n argsMustNotContain: "--effort",\n },\n- Effect.gen(function* () {\n- const textGeneration = yield* TextGeneration;\n-\n- const generated = yield* textGeneration.generateCommitMessage({\n- cwd: process.cwd(),\n- branch: "feature/claude-effect",\n- stagedSummary: "M README.md",\n- stagedPatch: "diff --git a/README.md b/README.md",\n- modelSelection: {\n- ...createModelSelection("claudeAgent", "claude-haiku-4-5", [\n- { id: "thinking", value: false },\n- { id: "effort", value: "high" },\n- ]),\n- },\n- });\n+ (textGeneration) =>\n+ Effect.gen(function* () {\n+ const generated = yield* textGeneration.generateCommitMessage({\n+ cwd: process.cwd(),\n+ branch: "feature/claude-effect",\n+ stagedSummary: "M README.md",\n+ stagedPatch: "diff --git a/README.md b/README.md",\n+ modelSelection: {\n+ ...createModelSelection(ProviderInstanceId.make("claudeAgent"), "claude-haiku-4-5", [\n+ { id: "thinking", value: false },\n+ { id: "effort", value: "high" },\n+ ]),\n+ },\n+ });\n \n- expect(generated.subject).toBe("Add important change");\n- }),\n+ expect(generated.subject).toBe("Add important change");\n+ }),\n ),\n );\n \n@@ -223,26 +228,25 @@ it.layer(ClaudeTextGenerationTestLayer)("ClaudeTextGenerationLive", (it) => {\n }),\n argsMustContain: \'--effort max --settings {"fastMode":true}\',\n },\n- Effect.gen(function* () {\n- const textGeneration = yield* TextGeneration;\n-\n- const generated = yield* textGeneration.generatePrContent({\n- cwd: process.cwd(),\n- baseBranch: "main",\n- headBranch: "feature/claude-effect",\n- commitSummary: "Improve orchestration",\n- diffSummary: "1 file changed",\n- diffPatch: "diff --git a/README.md b/README.md",\n- modelSelection: {\n- ...createModelSelection("claudeAgent", "claude-opus-4-6", [\n- { id: "effort", value: "max" },\n- { id: "fastMode", value: true },\n- ]),\n- },\n- });\n+ (textGeneration) =>\n+ Effect.gen(function* () {\n+ const generated = yield* textGeneration.generatePrContent({\n+ cwd: process.cwd(),\n+ baseBranch: "main",\n+ headBranch: "feature/claude-effect",\n+ commitSummary: "Improve orchestration",\n+ diffSummary: "1 file changed",\n+ diffPatch: "diff --git a/README.md b/README.md",\n+ modelSelection: {\n+ ...createModelSelection(ProviderInstanceId.make("claudeAgent"), "claude-opus-4-6", [\n+ { id: "effort", value: "max" },\n+ { id: "fastMode", value: true },\n+ ]),\n+ },\n+ });\n \n- expect(generated.title).toBe("Improve orchestration flow");\n- }),\n+ expect(generated.title).toBe("Improve orchestration flow");\n+ }),\n ),\n );\n \n@@ -257,27 +261,57 @@ it.layer(ClaudeTextGenerationTestLayer)("ClaudeTextGenerationLive", (it) => {\n }),\n stdinMustContain: "You write concise thread titles for coding conversations.",\n },\n- Effect.gen(function* () {\n- const textGeneration = yield* TextGeneration;\n+ (textGeneration) =>\n+ Effect.gen(function* () {\n+ const generated = yield* textGeneration.generateThreadTitle({\n+ cwd: process.cwd(),\n+ message: "Please investigate reconnect failures after restarting the session.",\n+ modelSelection: {\n+ instanceId: ProviderInstanceId.make("claudeAgent"),\n+ model: "claude-sonnet-4-6",\n+ },\n+ });\n \n- const generated = yield* textGeneration.generateThreadTitle({\n- cwd: process.cwd(),\n- message: "Please investigate reconnect failures after restarting the session.",\n- modelSelection: {\n- provider: "claudeAgent",\n- model: "claude-sonnet-4-6",\n- },\n- });\n-\n- expect(generated.title).toBe(\n- sanitizeThreadTitle(\n- \'"Reconnect failures after restart because the session state does not recover"\',\n- ),\n- );\n- }),\n+ expect(generated.title).toBe(\n+ sanitizeThreadTitle(\n+ \'"Reconnect failures after restart because the session state does not recover"\',\n+ ),\n+ );\n+ }),\n ),\n );\n \n+ it.effect("runs Claude text generation with the configured Claude HOME", () =>\n+ Effect.gen(function* () {\n+ const path = yield* Path.Path;\n+ const claudeHome = path.join(process.cwd(), ".claude-work-test");\n+ return yield* withFakeClaudeEnv(\n+ {\n+ output: JSON.stringify({\n+ structured_output: {\n+ title: "Use Claude home",\n+ },\n+ }),\n+ homeMustBe: claudeHome,\n+ claudeConfig: { homePath: claudeHome },\n+ },\n+ (textGeneration) =>\n+ Effect.gen(function* () {\n+ const generated = yield* textGeneration.generateThreadTitle({\n+ cwd: process.cwd(),\n+ message: "thread title",\n+ modelSelection: {\n+ instanceId: ProviderInstanceId.make("claudeAgent"),\n+ model: "claude-sonnet-4-6",\n+ },\n+ });\n+\n+ expect(generated.title).toBe(sanitizeThreadTitle("Use Claude home"));\n+ }),\n+ );\n+ }),\n+ );\n+\n it.effect("falls back when Claude thread title normalization becomes whitespace-only", () =>\n withFakeClaudeEnv(\n {\n@@ -287,20 +321,19 @@ it.layer(ClaudeTextGenerationTestLayer)("ClaudeTextGenerationLive", (it) => {\n },\n }),\n },\n- Effect.gen(function* () {\n- const textGeneration = yield* TextGeneration;\n-\n- const generated = yield* textGeneration.generateThreadTitle({\n- cwd: process.cwd(),\n- message: "Name this thread.",\n- modelSelection: {\n- provider: "claudeAgent",\n- model: "claude-sonnet-4-6",\n- },\n- });\n+ (textGeneration) =>\n+ Effect.gen(function* () {\n+ const generated = yield* textGeneration.generateThreadTitle({\n+ cwd: process.cwd(),\n+ message: "Name this thread.",\n+ modelSelection: {\n+ instanceId: ProviderInstanceId.make("claudeAgent"),\n+ model: "claude-sonnet-4-6",\n+ },\n+ });\n \n- expect(generated.title).toBe("New thread");\n- }),\n+ expect(generated.title).toBe("New thread");\n+ }),\n ),\n );\n });\ndiff --git a/apps/server/src/git/Layers/ClaudeTextGeneration.ts b/apps/server/src/git/Layers/ClaudeTextGeneration.ts\nindex 8175dc54b2..33bf7bc014 100644\n--- a/apps/server/src/git/Layers/ClaudeTextGeneration.ts\n+++ b/apps/server/src/git/Layers/ClaudeTextGeneration.ts\n@@ -7,14 +7,14 @@\n *\n * @module ClaudeTextGeneration\n */\n-import { Effect, Layer, Option, Schema, Stream } from "effect";\n+import { Effect, Option, Schema, Stream } from "effect";\n import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";\n \n-import { ClaudeModelSelection } from "@t3tools/contracts";\n+import { type ClaudeSettings, type ModelSelection } from "@t3tools/contracts";\n import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";\n \n import { TextGenerationError } from "@t3tools/contracts";\n-import { type TextGenerationShape, TextGeneration } from "../Services/TextGeneration.ts";\n+import { type TextGenerationShape } from "../Services/TextGeneration.ts";\n import {\n buildBranchNamePrompt,\n buildCommitMessagePrompt,\n@@ -38,7 +38,7 @@ import {\n resolveClaudeApiModelId,\n resolveClaudeEffort,\n } from "../../provider/Layers/ClaudeProvider.ts";\n-import { ServerSettingsService } from "../../serverSettings.ts";\n+import { makeClaudeEnvironment } from "../../provider/Drivers/ClaudeHome.ts";\n \n const CLAUDE_TIMEOUT_MS = 180_000;\n \n@@ -50,9 +50,12 @@ const ClaudeOutputEnvelope = Schema.Struct({\n structured_output: Schema.Unknown,\n });\n \n-const makeClaudeTextGeneration = Effect.gen(function* () {\n+export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(function* (\n+ claudeSettings: ClaudeSettings,\n+ environment: NodeJS.ProcessEnv = process.env,\n+) {\n const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;\n- const serverSettingsService = yield* Effect.service(ServerSettingsService);\n+ const claudeEnvironment = yield* makeClaudeEnvironment(claudeSettings, environment);\n \n const readStreamAsString = <E>(\n operation: string,\n@@ -88,7 +91,7 @@ const makeClaudeTextGeneration = Effect.gen(function* () {\n cwd: string;\n prompt: string;\n outputSchemaJson: S;\n- modelSelection: ClaudeModelSelection;\n+ modelSelection: ModelSelection;\n }): Effect.fn.Return<S["Type"], TextGenerationError, S["DecodingServices"]> {\n const jsonSchemaStr = JSON.stringify(toJsonSchemaObject(outputSchemaJson));\n const caps = getClaudeModelCapabilities(modelSelection.model);\n@@ -111,14 +114,9 @@ const makeClaudeTextGeneration = Effect.gen(function* () {\n ...(fastMode ? { fastMode: true } : {}),\n };\n \n- const claudeSettings = yield* Effect.map(\n- serverSettingsService.getSettings,\n- (settings) => settings.providers.claudeAgent,\n- ).pipe(Effect.catch(() => Effect.undefined));\n-\n const runClaudeCommand = Effect.fn("runClaudeJson.runClaudeCommand")(function* () {\n const command = ChildProcess.make(\n- claudeSettings?.binaryPath || "claude",\n+ claudeSettings.binaryPath || "claude",\n [\n "-p",\n "--output-format",\n@@ -132,6 +130,7 @@ const makeClaudeTextGeneration = Effect.gen(function* () {\n "--dangerously-skip-permissions",\n ],\n {\n+ env: claudeEnvironment,\n cwd,\n shell: process.platform === "win32",\n stdin: {\n@@ -232,13 +231,6 @@ const makeClaudeTextGeneration = Effect.gen(function* () {\n includeBranch: input.includeBranch === true,\n });\n \n- if (input.modelSelection.provider !== "claudeAgent") {\n- return yield* new TextGenerationError({\n- operation: "generateCommitMessage",\n- detail: "Invalid model selection.",\n- });\n- }\n-\n const generated = yield* runClaudeJson({\n operation: "generateCommitMessage",\n cwd: input.cwd,\n@@ -267,13 +259,6 @@ const makeClaudeTextGeneration = Effect.gen(function* () {\n diffPatch: input.diffPatch,\n });\n \n- if (input.modelSelection.provider !== "claudeAgent") {\n- return yield* new TextGenerationError({\n- operation: "generatePrContent",\n- detail: "Invalid model selection.",\n- });\n- }\n-\n const generated = yield* runClaudeJson({\n operation: "generatePrContent",\n cwd: input.cwd,\n@@ -296,13 +281,6 @@ const makeClaudeTextGeneration = Effect.gen(function* () {\n attachments: input.attachments,\n });\n \n- if (input.modelSelection.provider !== "claudeAgent") {\n- return yield* new TextGenerationError({\n- operation: "generateBranchName",\n- detail: "Invalid model selection.",\n- });\n- }\n-\n const generated = yield* runClaudeJson({\n operation: "generateBranchName",\n cwd: input.cwd,\n@@ -324,13 +302,6 @@ const makeClaudeTextGeneration = Effect.gen(function* () {\n attachments: input.attachments,\n });\n \n- if (input.modelSelection.provider !== "claudeAgent") {\n- return yield* new TextGenerationError({\n- operation: "generateThreadTitle",\n- detail: "Invalid model selection.",\n- });\n- }\n-\n const generated = yield* runClaudeJson({\n operation: "generateThreadTitle",\n cwd: input.cwd,\n@@ -351,5 +322,3 @@ const makeClaudeTextGeneration = Effect.gen(function* () {\n generateThreadTitle,\n } satisfies TextGenerationShape;\n });\n-\n-export const ClaudeTextGenerationLive = Layer.effect(TextGeneration, makeClaudeTextGeneration);\ndiff --git a/apps/server/src/git/Layers/CodexTextGeneration.test.ts b/apps/server/src/git/Layers/CodexTextGeneration.test.ts\nindex 2adfcca848..f38d6a68a8 100644\n--- a/apps/server/src/git/Layers/CodexTextGeneration.test.ts\n+++ b/apps/server/src/git/Layers/CodexTextGeneration.test.ts\n@@ -1,30 +1,24 @@\n import * as NodeServices from "@effect/platform-node/NodeServices";\n import { it } from "@effect/vitest";\n-import { Effect, FileSystem, Layer, Path, Result } from "effect";\n+import { Effect, FileSystem, Layer, Path, Result, Schema } from "effect";\n import { createModelSelection } from "@t3tools/shared/model";\n import { expect } from "vitest";\n \n+import { CodexSettings, ProviderInstanceId, TextGenerationError } from "@t3tools/contracts";\n+\n import { ServerConfig } from "../../config.ts";\n-import { CodexTextGenerationLive } from "./CodexTextGeneration.ts";\n-import { TextGenerationError } from "@t3tools/contracts";\n-import { TextGeneration } from "../Services/TextGeneration.ts";\n-import { ServerSettingsService } from "../../serverSettings.ts";\n-\n-const DEFAULT_TEST_MODEL_SELECTION = {\n- provider: "codex" as const,\n- model: "gpt-5.4-mini",\n-};\n-\n-const CodexTextGenerationTestLayer = CodexTextGenerationLive.pipe(\n- Layer.provideMerge(ServerSettingsService.layerTest()),\n- Layer.provideMerge(\n- ServerConfig.layerTest(process.cwd(), {\n- prefix: "t3code-codex-text-generation-test-",\n- }),\n- ),\n- Layer.provideMerge(NodeServices.layer),\n+import { type TextGenerationShape } from "../Services/TextGeneration.ts";\n+import { makeCodexTextGeneration } from "./CodexTextGeneration.ts";\n+\n+const DEFAULT_TEST_MODEL_SELECTION = createModelSelection(\n+ ProviderInstanceId.make("codex"),\n+ "gpt-5.4-mini",\n );\n \n+const CodexTextGenerationTestLayer = ServerConfig.layerTest(process.cwd(), {\n+ prefix: "t3code-codex-text-generation-test-",\n+}).pipe(Layer.provideMerge(NodeServices.layer));\n+\n function makeFakeCodexBinary(\n dir: string,\n input: {\n@@ -162,36 +156,16 @@ function withFakeCodexEnv<A, E, R>(\n stdinMustContain?: string;\n stdinMustNotContain?: string;\n },\n- effect: Effect.Effect<A, E, R>,\n+ effectFn: (textGeneration: TextGenerationShape) => Effect.Effect<A, E, R>,\n ) {\n- return Effect.acquireUseRelease(\n- Effect.gen(function* () {\n- const fs = yield* FileSystem.FileSystem;\n- const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-codex-text-" });\n- const codexPath = yield* makeFakeCodexBinary(tempDir, input);\n- const serverSettings = yield* ServerSettingsService;\n- const previousSettings = yield* serverSettings.getSettings;\n- yield* serverSettings.updateSettings({\n- providers: {\n- codex: {\n- binaryPath: codexPath,\n- },\n- },\n- });\n- return { serverSettings, previousBinaryPath: previousSettings.providers.codex.binaryPath };\n- }),\n- () => effect,\n- ({ serverSettings, previousBinaryPath }) =>\n- serverSettings\n- .updateSettings({\n- providers: {\n- codex: {\n- binaryPath: previousBinaryPath,\n- },\n- },\n- })\n- .pipe(Effect.asVoid),\n- );\n+ return Effect.gen(function* () {\n+ const fs = yield* FileSystem.FileSystem;\n+ const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-codex-text-" });\n+ const codexPath = yield* makeFakeCodexBinary(tempDir, input);\n+ const config = Schema.decodeSync(CodexSettings)({ binaryPath: codexPath });\n+ const textGeneration = yield* makeCodexTextGeneration(config);\n+ return yield* effectFn(textGeneration);\n+ }).pipe(Effect.scoped);\n }\n \n it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {\n@@ -205,22 +179,21 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {\n }),\n stdinMustNotContain: "branch must be a short semantic git branch fragment",\n },\n- Effect.gen(function* () {\n- const textGeneration = yield* TextGeneration;\n-\n- const generated = yield* textGeneration.generateCommitMessage({\n- cwd: process.cwd(),\n- branch: "feature/codex-effect",\n- stagedSummary: "M README.md",\n- stagedPatch: "diff --git a/README.md b/README.md",\n- modelSelection: DEFAULT_TEST_MODEL_SELECTION,\n- });\n+ (textGeneration) =>\n+ Effect.gen(function* () {\n+ const generated = yield* textGeneration.generateCommitMessage({\n+ cwd: process.cwd(),\n+ branch: "feature/codex-effect",\n+ stagedSummary: "M README.md",\n+ stagedPatch: "diff --git a/README.md b/README.md",\n+ modelSelection: DEFAULT_TEST_MODEL_SELECTION,\n+ });\n \n- expect(generated.subject.length).toBeLessThanOrEqual(72);\n- expect(generated.subject.endsWith(".")).toBe(false);\n- expect(generated.body).toBe("- added migration\\n- updated tests");\n- expect(generated.branch).toBeUndefined();\n- }),\n+ expect(generated.subject.length).toBeLessThanOrEqual(72);\n+ expect(generated.subject.endsWith(".")).toBe(false);\n+ expect(generated.body).toBe("- added migration\\n- updated tests");\n+ expect(generated.branch).toBeUndefined();\n+ }),\n ),\n );\n \n@@ -237,20 +210,17 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {\n requireReasoningEffort: "xhigh",\n stdinMustNotContain: "branch must be a short semantic git branch fragment",\n },\n- Effect.gen(function* () {\n- const textGeneration = yield* TextGeneration;\n-\n- yield* textGeneration.generateCommitMessage({\n+ (textGeneration) =>\n+ textGeneration.generateCommitMessage({\n cwd: process.cwd(),\n branch: "feature/codex-effect",\n stagedSummary: "M README.md",\n stagedPatch: "diff --git a/README.md b/README.md",\n- modelSelection: createModelSelection("codex", "gpt-5.4", [\n+ modelSelection: createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.4", [\n { id: "reasoningEffort", value: "xhigh" },\n { id: "fastMode", value: true },\n ]),\n- });\n- }),\n+ }),\n ),\n );\n \n@@ -263,17 +233,14 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {\n }),\n requireReasoningEffort: "low",\n },\n- Effect.gen(function* () {\n- const textGeneration = yield* TextGeneration;\n-\n- yield* textGeneration.generateCommitMessage({\n+ (textGeneration) =>\n+ textGeneration.generateCommitMessage({\n cwd: process.cwd(),\n branch: "feature/codex-effect",\n stagedSummary: "M README.md",\n stagedPatch: "diff --git a/README.md b/README.md",\n modelSelection: DEFAULT_TEST_MODEL_SELECTION,\n- });\n- }),\n+ }),\n ),\n );\n \n@@ -287,21 +254,20 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {\n }),\n stdinMustContain: "branch must be a short semantic git branch fragment",\n },\n- Effect.gen(function* () {\n- const textGeneration = yield* TextGeneration;\n-\n- const generated = yield* textGeneration.generateCommitMessage({\n- cwd: process.cwd(),\n- branch: "feature/codex-effect",\n- stagedSummary: "M README.md",\n- stagedPatch: "diff --git a/README.md b/README.md",\n- includeBranch: true,\n- modelSelection: DEFAULT_TEST_MODEL_SELECTION,\n- });\n+ (textGeneration) =>\n+ Effect.gen(function* () {\n+ const generated = yield* textGeneration.generateCommitMessage({\n+ cwd: process.cwd(),\n+ branch: "feature/codex-effect",\n+ stagedSummary: "M README.md",\n+ stagedPatch: "diff --git a/README.md b/README.md",\n+ includeBranch: true,\n+ modelSelection: DEFAULT_TEST_MODEL_SELECTION,\n+ });\n \n- expect(generated.subject).toBe("Add important change");\n- expect(generated.branch).toBe("feature/fix/important-system-change");\n- }),\n+ expect(generated.subject).toBe("Add important change");\n+ expect(generated.branch).toBe("feature/fix/important-system-change");\n+ }),\n ),\n );\n \n@@ -313,23 +279,22 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {\n body: "\\n## Summary\\n- improve flow\\n\\n## Testing\\n- bun test\\n\\n",\n }),\n },\n- Effect.gen(function* () {\n- const textGeneration = yield* TextGeneration;\n-\n- const generated = yield* textGeneration.generatePrContent({\n- cwd: process.cwd(),\n- baseBranch: "main",\n- headBranch: "feature/codex-effect",\n- commitSummary: "feat: improve orchestration flow",\n- diffSummary: "2 files changed",\n- diffPatch: "diff --git a/a.ts b/a.ts",\n- modelSelection: DEFAULT_TEST_MODEL_SELECTION,\n- });\n+ (textGeneration) =>\n+ Effect.gen(function* () {\n+ const generated = yield* textGeneration.generatePrContent({\n+ cwd: process.cwd(),\n+ baseBranch: "main",\n+ headBranch: "feature/codex-effect",\n+ commitSummary: "feat: improve orchestration flow",\n+ diffSummary: "2 files changed",\n+ diffPatch: "diff --git a/a.ts b/a.ts",\n+ modelSelection: DEFAULT_TEST_MODEL_SELECTION,\n+ });\n \n- expect(generated.title).toBe("Improve orchestration flow");\n- expect(generated.body.startsWith("## Summary")).toBe(true);\n- expect(generated.body.endsWith("\\n\\n")).toBe(false);\n- }),\n+ expect(generated.title).toBe("Improve orchestration flow");\n+ expect(generated.body.startsWith("## Summary")).toBe(true);\n+ expect(generated.body.endsWith("\\n\\n")).toBe(false);\n+ }),\n ),\n );\n \n@@ -341,17 +306,16 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {\n }),\n stdinMustNotContain: "Image attachments supplied to the model",\n },\n- Effect.gen(function* () {\n- const textGeneration = yield* TextGeneration;\n-\n- const generated = yield* textGeneration.generateBranchName({\n- cwd: process.cwd(),\n- message: "Please update session handling.",\n- modelSelection: DEFAULT_TEST_MODEL_SELECTION,\n- });\n+ (textGeneration) =>\n+ Effect.gen(function* () {\n+ const generated = yield* textGeneration.generateBranchName({\n+ cwd: process.cwd(),\n+ message: "Please update session handling.",\n+ modelSelection: DEFAULT_TEST_MODEL_SELECTION,\n+ });\n \n- expect(generated.branch).toBe("feat/session");\n- }),\n+ expect(generated.branch).toBe("feat/session");\n+ }),\n ),\n );\n \n@@ -363,17 +327,16 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {\n \' "Investigate websocket reconnect regressions after worktree restore" \\nignored line\',\n }),\n },\n- Effect.gen(function* () {\n- const textGeneration = yield* TextGeneration;\n-\n- const generated = yield* textGeneration.generateThreadTitle({\n- cwd: process.cwd(),\n- message: "Please investigate websocket reconnect regressions after a worktree restore.",\n- modelSelection: DEFAULT_TEST_MODEL_SELECTION,\n- });\n+ (textGeneration) =>\n+ Effect.gen(function* () {\n+ const generated = yield* textGeneration.generateThreadTitle({\n+ cwd: process.cwd(),\n+ message: "Please investigate websocket reconnect regressions after a worktree restore.",\n+ modelSelection: DEFAULT_TEST_MODEL_SELECTION,\n+ });\n \n- expect(generated.title).toBe("Investigate websocket reconnect regressions aft...");\n- }),\n+ expect(generated.title).toBe("Investigate websocket reconnect regressions aft...");\n+ }),\n ),\n );\n \n@@ -384,17 +347,16 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {\n title: \' """ """ \',\n }),\n },\n- Effect.gen(function* () {\n- const textGeneration = yield* TextGeneration;\n-\n- const generated = yield* textGeneration.generateThreadTitle({\n- cwd: process.cwd(),\n- message: "Name this thread.",\n- modelSelection: DEFAULT_TEST_MODEL_SELECTION,\n- });\n+ (textGeneration) =>\n+ Effect.gen(function* () {\n+ const generated = yield* textGeneration.generateThreadTitle({\n+ cwd: process.cwd(),\n+ message: "Name this thread.",\n+ modelSelection: DEFAULT_TEST_MODEL_SELECTION,\n+ });\n \n- expect(generated.title).toBe("New thread");\n- }),\n+ expect(generated.title).toBe("New thread");\n+ }),\n ),\n );\n \n@@ -405,17 +367,16 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {\n title: ` "\' hello world \'" `,\n }),\n },\n- Effect.gen(function* () {\n- const textGeneration = yield* TextGeneration;\n-\n- const generated = yield* textGeneration.generateThreadTitle({\n- cwd: process.cwd(),\n- message: "Name this thread.",\n- modelSelection: DEFAULT_TEST_MODEL_SELECTION,\n- });\n+ (textGeneration) =>\n+ Effect.gen(function* () {\n+ const generated = yield* textGeneration.generateThreadTitle({\n+ cwd: process.cwd(),\n+ message: "Name this thread.",\n+ modelSelection: DEFAULT_TEST_MODEL_SELECTION,\n+ });\n \n- expect(generated.title).toBe("hello world");\n- }),\n+ expect(generated.title).toBe("hello world");\n+ }),\n ),\n );\n \n@@ -427,17 +388,16 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {\n }),\n stdinMustNotContain: "Attachment metadata:",\n },\n- Effect.gen(function* () {\n- const textGeneration = yield* TextGeneration;\n-\n- const generated = yield* textGeneration.generateBranchName({\n- cwd: process.cwd(),\n- message: "Fix timeout behavior.",\n- modelSelection: DEFAULT_TEST_MODEL_SELECTION,\n- });\n+ (textGeneration) =>\n+ Effect.gen(function* () {\n+ const generated = yield* textGeneration.generateBranchName({\n+ cwd: process.cwd(),\n+ message: "Fix timeout behavior.",\n+ modelSelection: DEFAULT_TEST_MODEL_SELECTION,\n+ });\n \n- expect(generated.branch).toBe("fix/session-timeout");\n- }),\n+ expect(generated.branch).toBe("fix/session-timeout");\n+ }),\n ),\n );\n \n@@ -450,56 +410,17 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {\n requireImage: true,\n stdinMustContain: "Attachment metadata:",\n },\n- Effect.gen(function* () {\n- const fs = yield* FileSystem.FileSystem;\n- const path = yield* Path.Path;\n- const { attachmentsDir } = yield* ServerConfig;\n- const attachmentId = `thread-branch-image-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;\n- const attachmentPath = path.join(attachmentsDir, `${attachmentId}.png`);\n- yield* fs.makeDirectory(attachmentsDir, { recursive: true });\n- yield* fs.writeFile(attachmentPath, Buffer.from("hello"));\n-\n- const textGeneration = yield* TextGeneration;\n- const generated = yield* textGeneration.generateBranchName({\n- modelSelection: DEFAULT_TEST_MODEL_SELECTION,\n- cwd: process.cwd(),\n- message: "Fix layout bug from screenshot.",\n- attachments: [\n- {\n- type: "image",\n- id: attachmentId,\n- name: "bug.png",\n- mimeType: "image/png",\n- sizeBytes: 5,\n- },\n- ],\n- });\n-\n- expect(generated.branch).toBe("fix/ui-regression");\n- }),\n- ),\n- );\n-\n- it.effect("resolves persisted attachment ids to files for codex image inputs", () =>\n- withFakeCodexEnv(\n- {\n- output: JSON.stringify({\n- branch: "fix/ui-regression",\n- }),\n- requireImage: true,\n- },\n- Effect.gen(function* () {\n- const fs = yield* FileSystem.FileSystem;\n- const path = yield* Path.Path;\n- const { attachmentsDir } = yield* ServerConfig;\n- const attachmentId = `thread-1-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;\n- const imagePath = path.join(attachmentsDir, `${attachmentId}.png`);\n- yield* fs.makeDirectory(attachmentsDir, { recursive: true });\n- yield* fs.writeFile(imagePath, Buffer.from("hello"));\n-\n- const textGeneration = yield* TextGeneration;\n- const generated = yield* textGeneration\n- .generateBranchName({\n+ (textGeneration) =>\n+ Effect.gen(function* () {\n+ const fs = yield* FileSystem.FileSystem;\n+ const path = yield* Path.Path;\n+ const { attachmentsDir } = yield* ServerConfig;\n+ const attachmentId = `thread-branch-image-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;\n+ const attachmentPath = path.join(attachmentsDir, `${attachmentId}.png`);\n+ yield* fs.makeDirectory(attachmentsDir, { recursive: true });\n+ yield* fs.writeFile(attachmentPath, Buffer.from("hello"));\n+\n+ const generated = yield* textGeneration.generateBranchName({\n modelSelection: DEFAULT_TEST_MODEL_SELECTION,\n cwd: process.cwd(),\n message: "Fix layout bug from screenshot.",\n@@ -512,24 +433,14 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {\n sizeBytes: 5,\n },\n ],\n- })\n- .pipe(\n- Effect.tap(() =>\n- fs.stat(imagePath).pipe(\n- Effect.map((fileInfo) => {\n- expect(fileInfo.type).toBe("File");\n- }),\n- ),\n- ),\n- Effect.ensuring(fs.remove(imagePath).pipe(Effect.catch(() => Effect.void))),\n- );\n+ });\n \n- expect(generated.branch).toBe("fix/ui-regression");\n- }),\n+ expect(generated.branch).toBe("fix/ui-regression");\n+ }),\n ),\n );\n \n- it.effect("ignores missing attachment ids for codex image inputs", () =>\n+ it.effect("resolves persisted attachment ids to files for codex image inputs", () =>\n withFakeCodexEnv(\n {\n output: JSON.stringify({\n@@ -537,67 +448,115 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {\n }),\n requireImage: true,\n },\n- Effect.gen(function* () {\n- const fs = yield* FileSystem.FileSystem;\n- const path = yield* Path.Path;\n- const { attachmentsDir } = yield* ServerConfig;\n- const missingAttachmentId = `thread-missing-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;\n- const missingPath = path.join(attachmentsDir, `${missingAttachmentId}.png`);\n- yield* fs.remove(missingPath).pipe(Effect.catch(() => Effect.void));\n-\n- const textGeneration = yield* TextGeneration;\n- const result = yield* textGeneration\n- .generateBranchName({\n- modelSelection: DEFAULT_TEST_MODEL_SELECTION,\n- cwd: process.cwd(),\n- message: "Fix layout bug from screenshot.",\n- attachments: [\n- {\n- type: "image",\n- id: missingAttachmentId,\n- name: "outside.png",\n- mimeType: "image/png",\n- sizeBytes: 5,\n- },\n- ],\n- })\n- .pipe(Effect.result);\n-\n- expect(Result.isFailure(result)).toBe(true);\n- if (Result.isFailure(result)) {\n- expect(result.failure).toBeInstanceOf(TextGenerationError);\n- expect(result.failure.message).toContain("missing --image input");\n- }\n- }),\n+ (textGeneration) =>\n+ Effect.gen(function* () {\n+ const fs = yield* FileSystem.FileSystem;\n+ const path = yield* Path.Path;\n+ const { attachmentsDir } = yield* ServerConfig;\n+ const attachmentId = `thread-1-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;\n+ const imagePath = path.join(attachmentsDir, `${attachmentId}.png`);\n+ yield* fs.makeDirectory(attachmentsDir, { recursive: true });\n+ yield* fs.writeFile(imagePath, Buffer.from("hello"));\n+\n+ const generated = yield* textGeneration\n+ .generateBranchName({\n+ modelSelection: DEFAULT_TEST_MODEL_SELECTION,\n+ cwd: process.cwd(),\n+ message: "Fix layout bug from screenshot.",\n+ attachments: [\n+ {\n+ type: "image",\n+ id: attachmentId,\n+ name: "bug.png",\n+ mimeType: "image/png",\n+ sizeBytes: 5,\n+ },\n+ ],\n+ })\n+ .pipe(\n+ Effect.tap(() =>\n+ fs.stat(imagePath).pipe(\n+ Effect.map((fileInfo) => {\n+ expect(fileInfo.type).toBe("File");\n+ }),\n+ ),\n+ ),\n+ Effect.ensuring(fs.remove(imagePath).pipe(Effect.catch(() => Effect.void))),\n+ );\n+\n+ expect(generated.branch).toBe("fix/ui-regression");\n+ }),\n ),\n );\n \n- it.effect(\n- "fails with typed TextGenerationError when codex returns wrong branch payload shape",\n- () =>\n- withFakeCodexEnv(\n- {\n- output: JSON.stringify({\n- title: "This is not a branch payload",\n- }),\n- },\n+ it.effect("ignores missing attachment ids for codex image inputs", () =>\n+ withFakeCodexEnv(\n+ {\n+ output: JSON.stringify({\n+ branch: "fix/ui-regression",\n+ }),\n+ requireImage: true,\n+ },\n+ (textGeneration) =>\n Effect.gen(function* () {\n- const textGeneration = yield* TextGeneration;\n+ const fs = yield* FileSystem.FileSystem;\n+ const path = yield* Path.Path;\n+ const { attachmentsDir } = yield* ServerConfig;\n+ const missingAttachmentId = `thread-missing-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;\n+ const missingPath = path.join(attachmentsDir, `${missingAttachmentId}.png`);\n+ yield* fs.remove(missingPath).pipe(Effect.catch(() => Effect.void));\n \n const result = yield* textGeneration\n .generateBranchName({\n- cwd: process.cwd(),\n- message: "Fix websocket reconnect flake",\n modelSelection: DEFAULT_TEST_MODEL_SELECTION,\n+ cwd: process.cwd(),\n+ message: "Fix layout bug from screenshot.",\n+ attachments: [\n+ {\n+ type: "image",\n+ id: missingAttachmentId,\n+ name: "outside.png",\n+ mimeType: "image/png",\n+ sizeBytes: 5,\n+ },\n+ ],\n })\n .pipe(Effect.result);\n \n expect(Result.isFailure(result)).toBe(true);\n if (Result.isFailure(result)) {\n expect(result.failure).toBeInstanceOf(TextGenerationError);\n- expect(result.failure.message).toContain("Codex returned invalid structured output");\n+ expect(result.failure.message).toContain("missing --image input");\n }\n }),\n+ ),\n+ );\n+\n+ it.effect(\n+ "fails with typed TextGenerationError when codex returns wrong branch payload shape",\n+ () =>\n+ withFakeCodexEnv(\n+ {\n+ output: JSON.stringify({\n+ title: "This is not a branch payload",\n+ }),\n+ },\n+ (textGeneration) =>\n+ Effect.gen(function* () {\n+ const result = yield* textGeneration\n+ .generateBranchName({\n+ cwd: process.cwd(),\n+ message: "Fix websocket reconnect flake",\n+ modelSelection: DEFAULT_TEST_MODEL_SELECTION,\n+ })\n+ .pipe(Effect.result);\n+\n+ expect(Result.isFailure(result)).toBe(true);\n+ if (Result.isFailure(result)) {\n+ expect(result.failure).toBeInstanceOf(TextGenerationError);\n+ expect(result.failure.message).toContain("Codex returned invalid structured output");\n+ }\n+ }),\n ),\n );\n \n@@ -608,27 +567,26 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {\n exitCode: 1,\n stderr: "codex execution failed",\n },\n- Effect.gen(function* () {\n- const textGeneration = yield* TextGeneration;\n+ (textGeneration) =>\n+ Effect.gen(function* () {\n+ const result = yield* textGeneration\n+ .generateCommitMessage({\n+ cwd: process.cwd(),\n+ branch: "feature/codex-error",\n+ stagedSummary: "M README.md",\n+ stagedPatch: "diff --git a/README.md b/README.md",\n+ modelSelection: DEFAULT_TEST_MODEL_SELECTION,\n+ })\n+ .pipe(Effect.result);\n \n- const result = yield* textGeneration\n- .generateCommitMessage({\n- cwd: process.cwd(),\n- branch: "feature/codex-error",\n- stagedSummary: "M README.md",\n- stagedPatch: "diff --git a/README.md b/README.md",\n- modelSelection: DEFAULT_TEST_MODEL_SELECTION,\n- })\n- .pipe(Effect.result);\n-\n- expect(Result.isFailure(result)).toBe(true);\n- if (Result.isFailure(result)) {\n- expect(result.failure).toBeInstanceOf(TextGenerationError);\n- expect(result.failure.message).toContain(\n- "Codex CLI command failed: codex execution failed",\n- );\n- }\n- }),\n+ expect(Result.isFailure(result)).toBe(true);\n+ if (Result.isFailure(result)) {\n+ expect(result.failure).toBeInstanceOf(TextGenerationError);\n+ expect(result.failure.message).toContain(\n+ "Codex CLI command failed: codex execution failed",\n+ );\n+ }\n+ }),\n ),\n );\n });\ndiff --git a/apps/server/src/git/Layers/CodexTextGeneration.ts b/apps/server/src/git/Layers/CodexTextGeneration.ts\nindex ee1e39d0fa..d4bc8f1632 100644\n--- a/apps/server/src/git/Layers/CodexTextGeneration.ts\n+++ b/apps/server/src/git/Layers/CodexTextGeneration.ts\n@@ -1,9 +1,7 @@\n-import { randomUUID } from "node:crypto";\n-\n-import { Effect, FileSystem, Layer, Option, Path, Schema, Scope, Stream } from "effect";\n+import { Effect, FileSystem, Option, Path, Random, Schema, Scope, Stream } from "effect";\n import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";\n \n-import { CodexModelSelection } from "@t3tools/contracts";\n+import { type CodexSettings, type ModelSelection } from "@t3tools/contracts";\n import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";\n \n import { resolveAttachmentPath } from "../../attachmentStore.ts";\n@@ -14,7 +12,6 @@ import {\n type BranchNameGenerationInput,\n type ThreadTitleGenerationResult,\n type TextGenerationShape,\n- TextGeneration,\n } from "../Services/TextGeneration.ts";\n import {\n buildBranchNamePrompt,\n@@ -29,7 +26,6 @@ import {\n sanitizeThreadTitle,\n toJsonSchemaObject,\n } from "../Utils.ts";\n-import { ServerSettingsService } from "../../serverSettings.ts";\n import {\n getModelSelectionBooleanOptionValue,\n getModelSelectionStringOptionValue,\n@@ -37,12 +33,18 @@ import {\n \n const CODEX_GIT_TEXT_GENERATION_REASONING_EFFORT = "low";\n const CODEX_TIMEOUT_MS = 180_000;\n-const makeCodexTextGeneration = Effect.gen(function* () {\n+/**\n+ * Build a Codex text-generation closure bound to a specific `CodexSettings`\n+ * payload. See `makeCodexAdapter` for the overall per-instance rationale.\n+ */\n+export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(function* (\n+ codexConfig: CodexSettings,\n+ environment: NodeJS.ProcessEnv = process.env,\n+) {\n const fileSystem = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;\n const serverConfig = yield* Effect.service(ServerConfig);\n- const serverSettingsService = yield* Effect.service(ServerSettingsService);\n \n type MaterializedImageAttachments = {\n readonly imagePaths: ReadonlyArray<string>;\n@@ -68,21 +70,23 @@ const makeCodexTextGeneration = Effect.gen(function* () {\n prefix: string,\n content: string,\n ): Effect.Effect<string, TextGenerationError, Scope.Scope> => {\n- return fileSystem\n- .makeTempFileScoped({\n- prefix: `t3code-${prefix}-${process.pid}-${randomUUID()}.tmp`,\n- })\n- .pipe(\n- Effect.tap((filePath) => fileSystem.writeFileString(filePath, content)),\n- Effect.mapError(\n- (cause) =>\n- new TextGenerationError({\n- operation,\n- detail: `Failed to write temp file`,\n- cause,\n- }),\n- ),\n- );\n+ return Effect.gen(function* () {\n+ const tempFileId = yield* Random.nextUUIDv4;\n+ return yield* fileSystem\n+ .makeTempFileScoped({\n+ prefix: `t3code-${prefix}-${process.pid}-${tempFileId}.tmp`,\n+ })\n+ .pipe(Effect.tap((filePath) => fileSystem.writeFileString(filePath, content)));\n+ }).pipe(\n+ Effect.mapError(\n+ (cause) =>\n+ new TextGenerationError({\n+ operation,\n+ detail: `Failed to write temp file`,\n+ cause,\n+ }),\n+ ),\n+ );\n };\n \n const safeUnlink = (filePath: string): Effect.Effect<void, never> =>\n@@ -143,7 +147,7 @@ const makeCodexTextGeneration = Effect.gen(function* () {\n outputSchemaJson: S;\n imagePaths?: ReadonlyArray<string>;\n cleanupPaths?: ReadonlyArray<string>;\n- modelSelection: CodexModelSelection;\n+ modelSelection: ModelSelection;\n }): Effect.fn.Return<S["Type"], TextGenerationError, S["DecodingServices"]> {\n const schemaPath = yield* writeTempFile(\n operation,\n@@ -152,17 +156,12 @@ const makeCodexTextGeneration = Effect.gen(function* () {\n );\n const outputPath = yield* writeTempFile(operation, "codex-output", "");\n \n- const codexSettings = yield* Effect.map(\n- serverSettingsService.getSettings,\n- (settings) => settings.providers.codex,\n- ).pipe(Effect.catch(() => Effect.undefined));\n-\n const runCodexCommand = Effect.fn("runCodexJson.runCodexCommand")(function* () {\n const reasoningEffort =\n getModelSelectionStringOptionValue(modelSelection, "reasoningEffort") ??\n CODEX_GIT_TEXT_GENERATION_REASONING_EFFORT;\n const command = ChildProcess.make(\n- codexSettings?.binaryPath || "codex",\n+ codexConfig.binaryPath || "codex",\n [\n "exec",\n "--ephemeral",\n@@ -185,10 +184,8 @@ const makeCodexTextGeneration = Effect.gen(function* () {\n ],\n {\n env: {\n- ...process.env,\n- ...(codexSettings?.homePath\n- ? { CODEX_HOME: expandHomePath(codexSettings.homePath) }\n- : {}),\n+ ...environment,\n+ ...(codexConfig.homePath ? { CODEX_HOME: expandHomePath(codexConfig.homePath) } : {}),\n },\n cwd,\n shell: process.platform === "win32",\n@@ -288,13 +285,6 @@ const makeCodexTextGeneration = Effect.gen(function* () {\n includeBranch: input.includeBranch === true,\n });\n \n- if (input.modelSelection.provider !== "codex") {\n- return yield* new TextGenerationError({\n- operation: "generateCommitMessage",\n- detail: "Invalid model selection.",\n- });\n- }\n-\n const generated = yield* runCodexJson({\n operation: "generateCommitMessage",\n cwd: input.cwd,\n@@ -323,13 +313,6 @@ const makeCodexTextGeneration = Effect.gen(function* () {\n diffPatch: input.diffPatch,\n });\n \n- if (input.modelSelection.provider !== "codex") {\n- return yield* new TextGenerationError({\n- operation: "generatePrContent",\n- detail: "Invalid model selection.",\n- });\n- }\n-\n const generated = yield* runCodexJson({\n operation: "generatePrContent",\n cwd: input.cwd,\n@@ -356,13 +339,6 @@ const makeCodexTextGeneration = Effect.gen(function* () {\n attachments: input.attachments,\n });\n \n- if (input.modelSelection.provider !== "codex") {\n- return yield* new TextGenerationError({\n- operation: "generateBranchName",\n- detail: "Invalid model selection.",\n- });\n- }\n-\n const generated = yield* runCodexJson({\n operation: "generateBranchName",\n cwd: input.cwd,\n@@ -389,13 +365,6 @@ const makeCodexTextGeneration = Effect.gen(function* () {\n attachments: input.attachments,\n });\n \n- if (input.modelSelection.provider !== "codex") {\n- return yield* new TextGenerationError({\n- operation: "generateThreadTitle",\n- detail: "Invalid model selection.",\n- });\n- }\n-\n const generated = yield* runCodexJson({\n operation: "generateThreadTitle",\n cwd: input.cwd,\n@@ -418,4 +387,6 @@ const makeCodexTextGeneration = Effect.gen(function* () {\n } satisfies TextGenerationShape;\n });\n \n-export const CodexTextGenerationLive = Layer.effect(TextGeneration, makeCodexTextGeneration);\n+// NOTE: `CodexTextGenerationLive` (the singleton Layer) has been removed.\n+// `makeCodexTextGeneration(codexConfig)` is now invoked directly by\n+// `CodexDriver.create()` for each configured instance.\ndiff --git a/apps/server/src/git/Layers/CursorTextGeneration.test.ts b/apps/server/src/git/Layers/CursorTextGeneration.test.ts\nindex b8d974fd94..3718557664 100644\n--- a/apps/server/src/git/Layers/CursorTextGeneration.test.ts\n+++ b/apps/server/src/git/Layers/CursorTextGeneration.test.ts\n@@ -5,16 +5,15 @@ import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync\n \n import * as NodeServices from "@effect/platform-node/NodeServices";\n import { it } from "@effect/vitest";\n-import { Effect, Layer } from "effect";\n+import { Effect, Layer, Schema } from "effect";\n import { createModelSelection } from "@t3tools/shared/model";\n import { expect } from "vitest";\n \n-import { ServerSettingsError } from "@t3tools/contracts";\n+import { CursorSettings, ProviderInstanceId } from "@t3tools/contracts";\n \n import { ServerConfig } from "../../config.ts";\n-import { TextGeneration } from "../Services/TextGeneration.ts";\n-import { CursorTextGenerationLive } from "./CursorTextGeneration.ts";\n-import { ServerSettingsService } from "../../serverSettings.ts";\n+import { type TextGenerationShape } from "../Services/TextGeneration.ts";\n+import { makeCursorTextGeneration } from "./CursorTextGeneration.ts";\n \n const __dirname = path.dirname(fileURLToPath(import.meta.url));\n const mockAgentPath = path.join(__dirname, "../../../scripts/acp-mock-agent.ts");\n@@ -23,15 +22,9 @@ function shellSingleQuote(value: string): string {\n return `\'${value.replaceAll("\'", `\'"\'"\'`)}\'`;\n }\n \n-const CursorTextGenerationTestLayer = CursorTextGenerationLive.pipe(\n- Layer.provideMerge(ServerSettingsService.layerTest()),\n- Layer.provideMerge(\n- ServerConfig.layerTest(process.cwd(), {\n- prefix: "t3code-cursor-text-generation-test-",\n- }),\n- ),\n- Layer.provideMerge(NodeServices.layer),\n-);\n+const CursorTextGenerationTestLayer = ServerConfig.layerTest(process.cwd(), {\n+ prefix: "t3code-cursor-text-generation-test-",\n+}).pipe(Layer.provideMerge(NodeServices.layer));\n \n function makeAcpAgentWrapper(dir: string, env: Record<string, string>): string {\n const binDir = path.join(dir, "bin");\n@@ -57,44 +50,20 @@ function makeAcpAgentWrapper(dir: string, env: Record<string, string>): string {\n \n function withFakeAcpAgent<A, E, R>(\n env: Record<string, string>,\n- effect: Effect.Effect<A, E, R>,\n-): Effect.Effect<A, E | ServerSettingsError, R | ServerSettingsService> {\n+ effectFn: (textGeneration: TextGenerationShape) => Effect.Effect<A, E, R>,\n+) {\n return Effect.gen(function* () {\n const tempDir = mkdtempSync(path.join(os.tmpdir(), "t3code-cursor-text-acp-"));\n- const agentPath = makeAcpAgentWrapper(tempDir, env);\n- const serverSettings = yield* ServerSettingsService;\n- const previousSettings = yield* serverSettings.getSettings;\n-\n- yield* serverSettings.updateSettings({\n- providers: {\n- cursor: {\n- binaryPath: agentPath,\n- },\n- },\n- });\n-\n- return yield* effect.pipe(\n- Effect.ensuring(\n- serverSettings\n- .updateSettings({\n- providers: {\n- cursor: {\n- binaryPath: previousSettings.providers.cursor.binaryPath,\n- },\n- },\n- })\n- .pipe(\n- Effect.catch(() => Effect.void),\n- Effect.ensuring(\n- Effect.sync(() => {\n- rmSync(tempDir, { recursive: true, force: true });\n- }),\n- ),\n- Effect.asVoid,\n- ),\n- ),\n+ yield* Effect.addFinalizer(() =>\n+ Effect.sync(() => {\n+ rmSync(tempDir, { recursive: true, force: true });\n+ }),\n );\n- });\n+ const agentPath = makeAcpAgentWrapper(tempDir, env);\n+ const config = Schema.decodeSync(CursorSettings)({ binaryPath: agentPath });\n+ const textGeneration = yield* makeCursorTextGeneration(config);\n+ return yield* effectFn(textGeneration);\n+ }).pipe(Effect.scoped);\n }\n \n function waitForFileContent(path: string): Effect.Effect<string> {\n@@ -126,85 +95,86 @@ it.layer(CursorTextGenerationTestLayer)("CursorTextGenerationLive", (it) => {\n body: "- verify cursor acp model config path",\n }),\n },\n- Effect.gen(function* () {\n- const textGeneration = yield* TextGeneration;\n-\n- const generated = yield* textGeneration.generateCommitMessage({\n- cwd: process.cwd(),\n- branch: "feature/cursor-text-generation",\n- stagedSummary: "M apps/server/src/git/Layers/CursorTextGeneration.ts",\n- stagedPatch:\n- "diff --git a/apps/server/src/git/Layers/CursorTextGeneration.ts b/apps/server/src/git/Layers/CursorTextGeneration.ts",\n- modelSelection: {\n- ...createModelSelection("cursor", "gpt-5.4", [\n- { id: "reasoning", value: "xhigh" },\n- { id: "fastMode", value: true },\n- { id: "contextWindow", value: "1m" },\n- ]),\n- },\n- });\n+ (textGeneration) =>\n+ Effect.gen(function* () {\n+ const generated = yield* textGeneration.generateCommitMessage({\n+ cwd: process.cwd(),\n+ branch: "feature/cursor-text-generation",\n+ stagedSummary: "M apps/server/src/git/Layers/CursorTextGeneration.ts",\n+ stagedPatch:\n+ "diff --git a/apps/server/src/git/Layers/CursorTextGeneration.ts b/apps/server/src/git/Layers/CursorTextGeneration.ts",\n+ modelSelection: {\n+ ...createModelSelection(ProviderInstanceId.make("cursor"), "gpt-5.4", [\n+ { id: "reasoning", value: "xhigh" },\n+ { id: "fastMode", value: true },\n+ { id: "contextWindow", value: "1m" },\n+ ]),\n+ },\n+ });\n \n- expect(generated.subject).toBe("Add generated commit message");\n- expect(generated.body).toBe("- verify cursor acp model config path");\n+ expect(generated.subject).toBe("Add generated commit message");\n+ expect(generated.body).toBe("- verify cursor acp model config path");\n \n- const requests = readFileSync(requestLogPath, "utf8")\n- .trim()\n- .split("\\n")\n- .filter((line) => line.length > 0)\n- .map((line) => JSON.parse(line) as { method?: string; params?: Record<string, unknown> });\n+ const requests = readFileSync(requestLogPath, "utf8")\n+ .trim()\n+ .split("\\n")\n+ .filter((line) => line.length > 0)\n+ .map(\n+ (line) => JSON.parse(line) as { method?: string; params?: Record<string, unknown> },\n+ );\n \n- expect(\n- requests.find((request) => request.method === "initialize")?.params?.clientCapabilities,\n- ).toMatchObject({\n- _meta: {\n- parameterizedModelPicker: true,\n- },\n- });\n- expect(\n- requests.some(\n- (request) =>\n- request.method === "session/set_config_option" &&\n- request.params?.configId === "model" &&\n- request.params?.value === "gpt-5.4",\n- ),\n- ).toBe(true);\n- expect(\n- requests.some(\n- (request) =>\n- request.method === "session/set_config_option" &&\n- request.params?.configId === "reasoning" &&\n- request.params?.value === "extra-high",\n- ),\n- ).toBe(true);\n- expect(\n- requests.some(\n- (request) =>\n- request.method === "session/set_config_option" &&\n- request.params?.configId === "context" &&\n- request.params?.value === "1m",\n- ),\n- ).toBe(true);\n- expect(\n- requests.some(\n- (request) =>\n- request.method === "session/set_config_option" &&\n- request.params?.configId === "fast" &&\n- request.params?.value === "true",\n- ),\n- ).toBe(true);\n- expect(\n- requests.find((request) => request.method === "session/prompt")?.params?.prompt,\n- ).toEqual(\n- expect.arrayContaining([\n- expect.objectContaining({\n- type: "text",\n- text: expect.stringContaining("Staged patch:"),\n- }),\n- ]),\n- );\n+ expect(\n+ requests.find((request) => request.method === "initialize")?.params?.clientCapabilities,\n+ ).toMatchObject({\n+ _meta: {\n+ parameterizedModelPicker: true,\n+ },\n+ });\n+ expect(\n+ requests.some(\n+ (request) =>\n+ request.method === "session/set_config_option" &&\n+ request.params?.configId === "model" &&\n+ request.params?.value === "gpt-5.4",\n+ ),\n+ ).toBe(true);\n+ expect(\n+ requests.some(\n+ (request) =>\n+ request.method === "session/set_config_option" &&\n+ request.params?.configId === "reasoning" &&\n+ request.params?.value === "extra-high",\n+ ),\n+ ).toBe(true);\n+ expect(\n+ requests.some(\n+ (request) =>\n+ request.method === "session/set_config_option" &&\n+ request.params?.configId === "context" &&\n+ request.params?.value === "1m",\n+ ),\n+ ).toBe(true);\n+ expect(\n+ requests.some(\n+ (request) =>\n+ request.method === "session/set_config_option" &&\n+ request.params?.configId === "fast" &&\n+ request.params?.value === "true",\n+ ),\n+ ).toBe(true);\n+ expect(\n+ requests.find((request) => request.method === "session/prompt")?.params?.prompt,\n+ ).toEqual(\n+ expect.arrayContaining([\n+ expect.objectContaining({\n+ type: "text",\n+ text: expect.stringContaining("Staged patch:"),\n+ }),\n+ ]),\n+ );\n \n- rmSync(requestLogDir, { recursive: true, force: true });\n- }),\n+ rmSync(requestLogDir, { recursive: true, force: true });\n+ }),\n );\n });\n \n@@ -214,23 +184,22 @@ it.layer(CursorTextGenerationTestLayer)("CursorTextGenerationLive", (it) => {\n T3_ACP_PROMPT_RESPONSE_TEXT:\n \'Sure, here is the JSON:\\n```json\\n{\\n "subject": "Update README dummy comment with attribution and date",\\n "body": ""\\n}\\n```\\nDone.\',\n },\n- Effect.gen(function* () {\n- const textGeneration = yield* TextGeneration;\n-\n- const generated = yield* textGeneration.generateCommitMessage({\n- cwd: process.cwd(),\n- branch: "feature/cursor-noisy-json",\n- stagedSummary: "M README.md",\n- stagedPatch: "diff --git a/README.md b/README.md",\n- modelSelection: {\n- provider: "cursor",\n- model: "composer-2",\n- },\n- });\n+ (textGeneration) =>\n+ Effect.gen(function* () {\n+ const generated = yield* textGeneration.generateCommitMessage({\n+ cwd: process.cwd(),\n+ branch: "feature/cursor-noisy-json",\n+ stagedSummary: "M README.md",\n+ stagedPatch: "diff --git a/README.md b/README.md",\n+ modelSelection: {\n+ instanceId: ProviderInstanceId.make("cursor"),\n+ model: "composer-2",\n+ },\n+ });\n \n- expect(generated.subject).toBe("Update README dummy comment with attribution and date");\n- expect(generated.body).toBe("");\n- }),\n+ expect(generated.subject).toBe("Update README dummy comment with attribution and date");\n+ expect(generated.body).toBe("");\n+ }),\n ),\n );\n \n@@ -241,20 +210,19 @@ it.layer(CursorTextGenerationTestLayer)("CursorTextGenerationLive", (it) => {\n title: \'"Trim reconnect spinner status after resume."\',\n }),\n },\n- Effect.gen(function* () {\n- const textGeneration = yield* TextGeneration;\n-\n- const generated = yield* textGeneration.generateThreadTitle({\n- cwd: process.cwd(),\n- message: "Fix the reconnect spinner after a resumed session.",\n- modelSelection: {\n- provider: "cursor",\n- model: "composer-2",\n- },\n- });\n+ (textGeneration) =>\n+ Effect.gen(function* () {\n+ const generated = yield* textGeneration.generateThreadTitle({\n+ cwd: process.cwd(),\n+ message: "Fix the reconnect spinner after a resumed session.",\n+ modelSelection: {\n+ instanceId: ProviderInstanceId.make("cursor"),\n+ model: "composer-2",\n+ },\n+ });\n \n- expect(generated.title).toBe("Trim reconnect spinner status after resume.");\n- }),\n+ expect(generated.title).toBe("Trim reconnect spinner status after resume.");\n+ }),\n ),\n );\n \n@@ -270,28 +238,27 @@ it.layer(CursorTextGenerationTestLayer)("CursorTextGenerationLive", (it) => {\n body: "",\n }),\n },\n- Effect.gen(function* () {\n- const textGeneration = yield* TextGeneration;\n-\n- const generated = yield* textGeneration.generateCommitMessage({\n- cwd: process.cwd(),\n- branch: "feature/cursor-runtime-close",\n- stagedSummary: "M apps/server/src/git/Layers/CursorTextGeneration.ts",\n- stagedPatch:\n- "diff --git a/apps/server/src/git/Layers/CursorTextGeneration.ts b/apps/server/src/git/Layers/CursorTextGeneration.ts",\n- modelSelection: {\n- provider: "cursor",\n- model: "composer-2",\n- },\n- });\n+ (textGeneration) =>\n+ Effect.gen(function* () {\n+ const generated = yield* textGeneration.generateCommitMessage({\n+ cwd: process.cwd(),\n+ branch: "feature/cursor-runtime-close",\n+ stagedSummary: "M apps/server/src/git/Layers/CursorTextGeneration.ts",\n+ stagedPatch:\n+ "diff --git a/apps/server/src/git/Layers/CursorTextGeneration.ts b/apps/server/src/git/Layers/CursorTextGeneration.ts",\n+ modelSelection: {\n+ instanceId: ProviderInstanceId.make("cursor"),\n+ model: "composer-2",\n+ },\n+ });\n \n- expect(generated.subject).toBe("Close runtime after generation");\n+ expect(generated.subject).toBe("Close runtime after generation");\n \n- const exitLog = yield* waitForFileContent(exitLogPath);\n- expect(exitLog).toContain("exit:0");\n+ const exitLog = yield* waitForFileContent(exitLogPath);\n+ expect(exitLog).toContain("exit:0");\n \n- rmSync(exitLogDir, { recursive: true, force: true });\n- }),\n+ rmSync(exitLogDir, { recursive: true, force: true });\n+ }),\n );\n });\n });\ndiff --git a/apps/server/src/git/Layers/CursorTextGeneration.ts b/apps/server/src/git/Layers/CursorTextGeneration.ts\nindex 6b78728b95..c94c6dd180 100644\n--- a/apps/server/src/git/Layers/CursorTextGeneration.ts\n+++ b/apps/server/src/git/Layers/CursorTextGeneration.ts\n@@ -1,14 +1,13 @@\n-import { Effect, Layer, Option, Ref, Schema } from "effect";\n+import { Effect, Option, Ref, Schema } from "effect";\n import { ChildProcessSpawner } from "effect/unstable/process";\n \n-import { CursorModelSelection } from "@t3tools/contracts";\n+import { type CursorSettings, type ModelSelection } from "@t3tools/contracts";\n import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";\n \n import { TextGenerationError } from "@t3tools/contracts";\n import {\n type ThreadTitleGenerationResult,\n type TextGenerationShape,\n- TextGeneration,\n } from "../Services/TextGeneration.ts";\n import {\n buildBranchNamePrompt,\n@@ -26,7 +25,6 @@ import {\n applyCursorAcpModelSelection,\n makeCursorAcpRuntime,\n } from "../../provider/acp/CursorAcpSupport.ts";\n-import { ServerSettingsService } from "../../serverSettings.ts";\n \n const CURSOR_TIMEOUT_MS = 180_000;\n \n@@ -55,9 +53,15 @@ function isTextGenerationError(error: unknown): error is TextGenerationError {\n );\n }\n \n-const makeCursorTextGeneration = Effect.gen(function* () {\n+/**\n+ * Build a Cursor text-generation closure bound to a specific `CursorSettings`\n+ * payload. See `makeCodexAdapter` for the overall per-instance rationale.\n+ */\n+export const makeCursorTextGeneration = Effect.fn("makeCursorTextGeneration")(function* (\n+ cursorSettings: CursorSettings,\n+ environment: NodeJS.ProcessEnv = process.env,\n+) {\n const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;\n- const serverSettingsService = yield* Effect.service(ServerSettingsService);\n \n const runCursorJson = <S extends Schema.Top>({\n operation,\n@@ -74,17 +78,13 @@ const makeCursorTextGeneration = Effect.gen(function* () {\n cwd: string;\n prompt: string;\n outputSchemaJson: S;\n- modelSelection: CursorModelSelection;\n+ modelSelection: ModelSelection;\n }): Effect.Effect<S["Type"], TextGenerationError, S["DecodingServices"]> =>\n Effect.gen(function* () {\n- const cursorSettings = yield* Effect.map(\n- serverSettingsService.getSettings,\n- (settings) => settings.providers.cursor,\n- ).pipe(Effect.catch(() => Effect.undefined));\n-\n const outputRef = yield* Ref.make("");\n const runtime = yield* makeCursorAcpRuntime({\n cursorSettings,\n+ environment,\n childProcessSpawner: commandSpawner,\n cwd,\n clientInfo: { name: "t3-code-git-text", version: "0.0.0" },\n@@ -186,13 +186,6 @@ const makeCursorTextGeneration = Effect.gen(function* () {\n includeBranch: input.includeBranch === true,\n });\n \n- if (input.modelSelection.provider !== "cursor") {\n- return yield* new TextGenerationError({\n- operation: "generateCommitMessage",\n- detail: "Invalid model selection.",\n- });\n- }\n-\n const generated = yield* runCursorJson({\n operation: "generateCommitMessage",\n cwd: input.cwd,\n@@ -221,13 +214,6 @@ const makeCursorTextGeneration = Effect.gen(function* () {\n diffPatch: input.diffPatch,\n });\n \n- if (input.modelSelection.provider !== "cursor") {\n- return yield* new TextGenerationError({\n- operation: "generatePrContent",\n- detail: "Invalid model selection.",\n- });\n- }\n-\n const generated = yield* runCursorJson({\n operation: "generatePrContent",\n cwd: input.cwd,\n@@ -250,13 +236,6 @@ const makeCursorTextGeneration = Effect.gen(function* () {\n attachments: input.attachments,\n });\n \n- if (input.modelSelection.provider !== "cursor") {\n- return yield* new TextGenerationError({\n- operation: "generateBranchName",\n- detail: "Invalid model selection.",\n- });\n- }\n-\n const generated = yield* runCursorJson({\n operation: "generateBranchName",\n cwd: input.cwd,\n@@ -278,13 +257,6 @@ const makeCursorTextGeneration = Effect.gen(function* () {\n attachments: input.attachments,\n });\n \n- if (input.modelSelection.provider !== "cursor") {\n- return yield* new TextGenerationError({\n- operation: "generateThreadTitle",\n- detail: "Invalid model selection.",\n- });\n- }\n-\n const generated = yield* runCursorJson({\n operation: "generateThreadTitle",\n cwd: input.cwd,\n@@ -306,4 +278,6 @@ const makeCursorTextGeneration = Effect.gen(function* () {\n } satisfies TextGenerationShape;\n });\n \n-export const CursorTextGenerationLive = Layer.effect(TextGeneration, makeCursorTextGeneration);\n+// NOTE: `CursorTextGenerationLive` (the singleton Layer) has been removed.\n+// `makeCursorTextGeneration(cursorConfig)` is now invoked directly by\n+// `CursorDriver.create()` so each provider instance owns its own closure.\ndiff --git a/apps/server/src/git/Layers/OpenCodeTextGeneration.test.ts b/apps/server/src/git/Layers/OpenCodeTextGeneration.test.ts\nindex 28ee0a3e6f..c3bdd6035e 100644\n--- a/apps/server/src/git/Layers/OpenCodeTextGeneration.test.ts\n+++ b/apps/server/src/git/Layers/OpenCodeTextGeneration.test.ts\n@@ -1,19 +1,19 @@\n+import { OpenCodeSettings, ProviderInstanceId } from "@t3tools/contracts";\n import * as NodeServices from "@effect/platform-node/NodeServices";\n import { it } from "@effect/vitest";\n-import { Duration, Effect, Layer } from "effect";\n+import { Duration, Effect, Layer, Schema } from "effect";\n import { TestClock } from "effect/testing";\n import { NetService } from "@t3tools/shared/Net";\n import { beforeEach, expect } from "vitest";\n \n import { ServerConfig } from "../../config.ts";\n-import { ServerSettingsService } from "../../serverSettings.ts";\n import {\n OpenCodeRuntime,\n OpenCodeRuntimeError,\n type OpenCodeRuntimeShape,\n } from "../../provider/opencodeRuntime.ts";\n-import { TextGeneration } from "../Services/TextGeneration.ts";\n-import { OpenCodeTextGenerationLive } from "./OpenCodeTextGeneration.ts";\n+import { type TextGenerationShape } from "../Services/TextGeneration.ts";\n+import { makeOpenCodeTextGeneration } from "./OpenCodeTextGeneration.ts";\n \n const runtimeMock = {\n state: {\n@@ -97,23 +97,16 @@ const OpenCodeRuntimeTestDouble: OpenCodeRuntimeShape = {\n };\n \n const DEFAULT_TEST_MODEL_SELECTION = {\n- provider: "opencode" as const,\n+ instanceId: ProviderInstanceId.make("opencode"),\n model: "openai/gpt-5",\n };\n \n const OPENCODE_TEXT_GENERATION_IDLE_TTL_MS = 30_000;\n \n-const OpenCodeTextGenerationTestLayer = OpenCodeTextGenerationLive.pipe(\n- Layer.provideMerge(Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble)),\n- Layer.provideMerge(\n- ServerSettingsService.layerTest({\n- providers: {\n- opencode: {\n- binaryPath: "fake-opencode",\n- },\n- },\n- }),\n- ),\n+const OpenCodeTextGenerationTestLayer = Layer.succeed(\n+ OpenCodeRuntime,\n+ OpenCodeRuntimeTestDouble,\n+).pipe(\n Layer.provideMerge(\n ServerConfig.layerTest(process.cwd(), {\n prefix: "t3code-opencode-text-generation-test-",\n@@ -123,19 +116,10 @@ const OpenCodeTextGenerationTestLayer = OpenCodeTextGenerationLive.pipe(\n Layer.provideMerge(NodeServices.layer),\n );\n \n-const OpenCodeTextGenerationExistingServerTestLayer = OpenCodeTextGenerationLive.pipe(\n- Layer.provideMerge(Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble)),\n- Layer.provideMerge(\n- ServerSettingsService.layerTest({\n- providers: {\n- opencode: {\n- binaryPath: "fake-opencode",\n- serverUrl: "http://127.0.0.1:9999",\n- serverPassword: "secret-password",\n- },\n- },\n- }),\n- ),\n+const OpenCodeTextGenerationExistingServerTestLayer = Layer.succeed(\n+ OpenCodeRuntime,\n+ OpenCodeRuntimeTestDouble,\n+).pipe(\n Layer.provideMerge(\n ServerConfig.layerTest(process.cwd(), {\n prefix: "t3code-opencode-text-generation-existing-server-test-",\n@@ -145,6 +129,25 @@ const OpenCodeTextGenerationExistingServerTestLayer = OpenCodeTextGenerationLive\n Layer.provideMerge(NodeServices.layer),\n );\n \n+const DEFAULT_OPENCODE_SETTINGS = Schema.decodeSync(OpenCodeSettings)({\n+ binaryPath: "fake-opencode",\n+});\n+const EXISTING_SERVER_OPENCODE_SETTINGS = Schema.decodeSync(OpenCodeSettings)({\n+ binaryPath: "fake-opencode",\n+ serverUrl: "http://127.0.0.1:9999",\n+ serverPassword: "secret-password",\n+});\n+\n+function withOpenCodeTextGeneration<A, E, R>(\n+ settings: OpenCodeSettings,\n+ effectFn: (textGeneration: TextGenerationShape) => Effect.Effect<A, E, R>,\n+) {\n+ return Effect.gen(function* () {\n+ const textGeneration = yield* makeOpenCodeTextGeneration(settings);\n+ return yield* effectFn(textGeneration);\n+ }).pipe(Effect.scoped);\n+}\n+\n beforeEach(() => {\n runtimeMock.reset();\n });\n@@ -157,155 +160,40 @@ const advanceIdleClock = Effect.gen(function* () {\n \n it.layer(OpenCodeTextGenerationTestLayer)("OpenCodeTextGenerationLive", (it) => {\n it.effect("reuses a warm server across back-to-back requests and closes it after idling", () =>\n- Effect.gen(function* () {\n- const textGeneration = yield* TextGeneration;\n-\n- yield* textGeneration.generateCommitMessage({\n- cwd: process.cwd(),\n- branch: "feature/opencode-reuse",\n- stagedSummary: "M README.md",\n- stagedPatch: "diff --git a/README.md b/README.md",\n- modelSelection: DEFAULT_TEST_MODEL_SELECTION,\n- });\n- yield* textGeneration.generateCommitMessage({\n- cwd: process.cwd(),\n- branch: "feature/opencode-reuse",\n- stagedSummary: "M README.md",\n- stagedPatch: "diff --git a/README.md b/README.md",\n- modelSelection: DEFAULT_TEST_MODEL_SELECTION,\n- });\n-\n- expect(runtimeMock.state.startCalls).toEqual(["fake-opencode"]);\n- expect(runtimeMock.state.promptUrls).toEqual([\n- "http://127.0.0.1:4301",\n- "http://127.0.0.1:4301",\n- ]);\n- expect(runtimeMock.state.closeCalls).toEqual([]);\n-\n- yield* advanceIdleClock;\n-\n- expect(runtimeMock.state.closeCalls).toEqual(["http://127.0.0.1:4301"]);\n- }).pipe(Effect.provide(TestClock.layer())),\n- );\n-\n- it.effect("starts a new server after the warm server idles out", () =>\n- Effect.gen(function* () {\n- const textGeneration = yield* TextGeneration;\n-\n- yield* textGeneration.generateCommitMessage({\n- cwd: process.cwd(),\n- branch: "feature/opencode-reuse",\n- stagedSummary: "M README.md",\n- stagedPatch: "diff --git a/README.md b/README.md",\n- modelSelection: DEFAULT_TEST_MODEL_SELECTION,\n- });\n-\n- yield* advanceIdleClock;\n-\n- yield* textGeneration.generateCommitMessage({\n- cwd: process.cwd(),\n- branch: "feature/opencode-reuse",\n- stagedSummary: "M README.md",\n- stagedPatch: "diff --git a/README.md b/README.md",\n- modelSelection: DEFAULT_TEST_MODEL_SELECTION,\n- });\n-\n- expect(runtimeMock.state.startCalls).toEqual(["fake-opencode", "fake-opencode"]);\n- expect(runtimeMock.state.promptUrls).toEqual([\n- "http://127.0.0.1:4301",\n- "http://127.0.0.1:4302",\n- ]);\n- expect(runtimeMock.state.closeCalls).toEqual(["http://127.0.0.1:4301"]);\n- }).pipe(Effect.provide(TestClock.layer())),\n- );\n-\n- it.effect("returns a typed empty-output error when OpenCode returns no text parts", () =>\n- Effect.gen(function* () {\n- runtimeMock.state.promptResult = { data: {} };\n- const textGeneration = yield* TextGeneration;\n-\n- const error = yield* textGeneration\n- .generateCommitMessage({\n+ withOpenCodeTextGeneration(DEFAULT_OPENCODE_SETTINGS, (textGeneration) =>\n+ Effect.gen(function* () {\n+ yield* textGeneration.generateCommitMessage({\n cwd: process.cwd(),\n branch: "feature/opencode-reuse",\n stagedSummary: "M README.md",\n stagedPatch: "diff --git a/README.md b/README.md",\n modelSelection: DEFAULT_TEST_MODEL_SELECTION,\n- })\n- .pipe(Effect.flip);\n-\n- expect(error.message).toContain("OpenCode returned empty output.");\n- }),\n- );\n-\n- it.effect("parses JSON returned as plain text output", () =>\n- Effect.gen(function* () {\n- runtimeMock.state.promptResult = {\n- data: {\n- parts: [\n- {\n- type: "text",\n- text: \'Here is the result:\\n{"subject":"Tighten OpenCode parsing","body":"Handle JSON text output locally."}\',\n- },\n- ],\n- },\n- };\n- const textGeneration = yield* TextGeneration;\n-\n- const result = yield* textGeneration.generateCommitMessage({\n- cwd: process.cwd(),\n- branch: "feature/opencode-reuse",\n- stagedSummary: "M README.md",\n- stagedPatch: "diff --git a/README.md b/README.md",\n- modelSelection: DEFAULT_TEST_MODEL_SELECTION,\n- });\n-\n- expect(result).toEqual({\n- subject: "Tighten OpenCode parsing",\n- body: "Handle JSON text output locally.",\n- });\n- }),\n- );\n-\n- it.effect("surfaces the upstream OpenCode structured-output error message", () =>\n- Effect.gen(function* () {\n- runtimeMock.state.promptResult = {\n- data: {\n- info: {\n- error: {\n- name: "StructuredOutputError",\n- data: {\n- message: "Model did not produce structured output",\n- retries: 2,\n- },\n- },\n- },\n- },\n- };\n- const textGeneration = yield* TextGeneration;\n-\n- const error = yield* textGeneration\n- .generateCommitMessage({\n+ });\n+ yield* textGeneration.generateCommitMessage({\n cwd: process.cwd(),\n branch: "feature/opencode-reuse",\n stagedSummary: "M README.md",\n stagedPatch: "diff --git a/README.md b/README.md",\n modelSelection: DEFAULT_TEST_MODEL_SELECTION,\n- })\n- .pipe(Effect.flip);\n+ });\n \n- expect(error.message).toContain("Model did not produce structured output");\n- }),\n+ expect(runtimeMock.state.startCalls).toEqual(["fake-opencode"]);\n+ expect(runtimeMock.state.promptUrls).toEqual([\n+ "http://127.0.0.1:4301",\n+ "http://127.0.0.1:4301",\n+ ]);\n+ expect(runtimeMock.state.closeCalls).toEqual([]);\n+\n+ yield* advanceIdleClock;\n+\n+ expect(runtimeMock.state.closeCalls).toEqual(["http://127.0.0.1:4301"]);\n+ }),\n+ ).pipe(Effect.provide(TestClock.layer())),\n );\n-});\n \n-it.layer(OpenCodeTextGenerationExistingServerTestLayer)(\n- "OpenCodeTextGenerationLive with configured server URL",\n- (it) => {\n- it.effect("reuses a configured OpenCode server URL without spawning or applying idle TTL", () =>\n+ it.effect("starts a new server after the warm server idles out", () =>\n+ withOpenCodeTextGeneration(DEFAULT_OPENCODE_SETTINGS, (textGeneration) =>\n Effect.gen(function* () {\n- const textGeneration = yield* TextGeneration;\n-\n yield* textGeneration.generateCommitMessage({\n cwd: process.cwd(),\n branch: "feature/opencode-reuse",\n@@ -313,6 +201,9 @@ it.layer(OpenCodeTextGenerationExistingServerTestLayer)(\n stagedPatch: "diff --git a/README.md b/README.md",\n modelSelection: DEFAULT_TEST_MODEL_SELECTION,\n });\n+\n+ yield* advanceIdleClock;\n+\n yield* textGeneration.generateCommitMessage({\n cwd: process.cwd(),\n branch: "feature/opencode-reuse",\n@@ -321,20 +212,135 @@ it.layer(OpenCodeTextGenerationExistingServerTestLayer)(\n modelSelection: DEFAULT_TEST_MODEL_SELECTION,\n });\n \n- expect(runtimeMock.state.startCalls).toEqual([]);\n+ expect(runtimeMock.state.startCalls).toEqual(["fake-opencode", "fake-opencode"]);\n expect(runtimeMock.state.promptUrls).toEqual([\n- "http://127.0.0.1:9999",\n- "http://127.0.0.1:9999",\n- ]);\n- expect(runtimeMock.state.authHeaders).toEqual([\n- `Basic ${btoa("opencode:secret-password")}`,\n- `Basic ${btoa("opencode:secret-password")}`,\n+ "http://127.0.0.1:4301",\n+ "http://127.0.0.1:4302",\n ]);\n+ expect(runtimeMock.state.closeCalls).toEqual(["http://127.0.0.1:4301"]);\n+ }),\n+ ).pipe(Effect.provide(TestClock.layer())),\n+ );\n \n- yield* advanceIdleClock;\n+ it.effect("returns a typed empty-output error when OpenCode returns no text parts", () =>\n+ withOpenCodeTextGeneration(DEFAULT_OPENCODE_SETTINGS, (textGeneration) =>\n+ Effect.gen(function* () {\n+ runtimeMock.state.promptResult = { data: {} };\n+\n+ const error = yield* textGeneration\n+ .generateCommitMessage({\n+ cwd: process.cwd(),\n+ branch: "feature/opencode-reuse",\n+ stagedSummary: "M README.md",\n+ stagedPatch: "diff --git a/README.md b/README.md",\n+ modelSelection: DEFAULT_TEST_MODEL_SELECTION,\n+ })\n+ .pipe(Effect.flip);\n+\n+ expect(error.message).toContain("OpenCode returned empty output.");\n+ }),\n+ ),\n+ );\n \n- expect(runtimeMock.state.closeCalls).toEqual([]);\n- }).pipe(Effect.provide(TestClock.layer())),\n+ it.effect("parses JSON returned as plain text output", () =>\n+ withOpenCodeTextGeneration(DEFAULT_OPENCODE_SETTINGS, (textGeneration) =>\n+ Effect.gen(function* () {\n+ runtimeMock.state.promptResult = {\n+ data: {\n+ parts: [\n+ {\n+ type: "text",\n+ text: \'Here is the result:\\n{"subject":"Tighten OpenCode parsing","body":"Handle JSON text output locally."}\',\n+ },\n+ ],\n+ },\n+ };\n+\n+ const result = yield* textGeneration.generateCommitMessage({\n+ cwd: process.cwd(),\n+ branch: "feature/opencode-reuse",\n+ stagedSummary: "M README.md",\n+ stagedPatch: "diff --git a/README.md b/README.md",\n+ modelSelection: DEFAULT_TEST_MODEL_SELECTION,\n+ });\n+\n+ expect(result).toEqual({\n+ subject: "Tighten OpenCode parsing",\n+ body: "Handle JSON text output locally.",\n+ });\n+ }),\n+ ),\n+ );\n+\n+ it.effect("surfaces the upstream OpenCode structured-output error message", () =>\n+ withOpenCodeTextGeneration(DEFAULT_OPENCODE_SETTINGS, (textGeneration) =>\n+ Effect.gen(function* () {\n+ runtimeMock.state.promptResult = {\n+ data: {\n+ info: {\n+ error: {\n+ name: "StructuredOutputError",\n+ data: {\n+ message: "Model did not produce structured output",\n+ retries: 2,\n+ },\n+ },\n+ },\n+ },\n+ };\n+\n+ const error = yield* textGeneration\n+ .generateCommitMessage({\n+ cwd: process.cwd(),\n+ branch: "feature/opencode-reuse",\n+ stagedSummary: "M README.md",\n+ stagedPatch: "diff --git a/README.md b/README.md",\n+ modelSelection: DEFAULT_TEST_MODEL_SELECTION,\n+ })\n+ .pipe(Effect.flip);\n+\n+ expect(error.message).toContain("Model did not produce structured output");\n+ }),\n+ ),\n+ );\n+});\n+\n+it.layer(OpenCodeTextGenerationExistingServerTestLayer)(\n+ "OpenCodeTextGenerationLive with configured server URL",\n+ (it) => {\n+ it.effect("reuses a configured OpenCode server URL without spawning or applying idle TTL", () =>\n+ withOpenCodeTextGeneration(EXISTING_SERVER_OPENCODE_SETTINGS, (textGeneration) =>\n+ Effect.gen(function* () {\n+ yield* textGeneration.generateCommitMessage({\n+ cwd: process.cwd(),\n+ branch: "feature/opencode-reuse",\n+ stagedSummary: "M README.md",\n+ stagedPatch: "diff --git a/README.md b/README.md",\n+ modelSelection: DEFAULT_TEST_MODEL_SELECTION,\n+ });\n+ yield* textGeneration.generateCommitMessage({\n+ cwd: process.cwd(),\n+ branch: "feature/opencode-reuse",\n+ stagedSummary: "M README.md",\n+ stagedPatch: "diff --git a/README.md b/README.md",\n+ modelSelection: DEFAULT_TEST_MODEL_SELECTION,\n+ });\n+\n+ expect(runtimeMock.state.startCalls).toEqual([]);\n+ expect(runtimeMock.state.promptUrls).toEqual([\n+ "http://127.0.0.1:9999",\n+ "http://127.0.0.1:9999",\n+ ]);\n+ expect(runtimeMock.state.authHeaders).toEqual([\n+ `Basic ${btoa("opencode:secret-password")}`,\n+ `Basic ${btoa("opencode:secret-password")}`,\n+ ]);\n+\n+ yield* advanceIdleClock;\n+\n+ expect(runtimeMock.state.closeCalls).toEqual([]);\n+ }),\n+ ).pipe(Effect.provide(TestClock.layer())),\n );\n },\n );\ndiff --git a/apps/server/src/git/Layers/OpenCodeTextGeneration.ts b/apps/server/src/git/Layers/OpenCodeTextGeneration.ts\nindex d9ebb094e7..f2d0b4b272 100644\n--- a/apps/server/src/git/Layers/OpenCodeTextGeneration.ts\n+++ b/apps/server/src/git/Layers/OpenCodeTextGeneration.ts\n@@ -1,24 +1,24 @@\n-import { Effect, Exit, Fiber, Layer, Schema, Scope } from "effect";\n+import { Effect, Exit, Fiber, Schema, Scope } from "effect";\n import * as Semaphore from "effect/Semaphore";\n \n import {\n TextGenerationError,\n type ChatAttachment,\n- type OpenCodeModelSelection,\n+ type ModelSelection,\n+ type OpenCodeSettings,\n } from "@t3tools/contracts";\n import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";\n import { getModelSelectionStringOptionValue } from "@t3tools/shared/model";\n \n import { ServerConfig } from "../../config.ts";\n import { resolveAttachmentPath } from "../../attachmentStore.ts";\n-import { ServerSettingsService } from "../../serverSettings.ts";\n import {\n buildBranchNamePrompt,\n buildCommitMessagePrompt,\n buildPrContentPrompt,\n buildThreadTitlePrompt,\n } from "../Prompts.ts";\n-import { type TextGenerationShape, TextGeneration } from "../Services/TextGeneration.ts";\n+import { type TextGenerationShape } from "../Services/TextGeneration.ts";\n import {\n extractJsonObject,\n sanitizeCommitSubject,\n@@ -93,9 +93,11 @@ interface SharedOpenCodeTextGenerationServerState {\n idleCloseFiber: Fiber.Fiber<void, never> | null;\n }\n \n-const makeOpenCodeTextGeneration = Effect.gen(function* () {\n+export const makeOpenCodeTextGeneration = Effect.fn("makeOpenCodeTextGeneration")(function* (\n+ openCodeSettings: OpenCodeSettings,\n+ environment: NodeJS.ProcessEnv = process.env,\n+) {\n const serverConfig = yield* ServerConfig;\n- const serverSettingsService = yield* ServerSettingsService;\n const openCodeRuntime = yield* OpenCodeRuntime;\n const idleFiberScope = yield* Effect.acquireRelease(Scope.make(), (scope) =>\n Scope.close(scope, Exit.void),\n@@ -202,6 +204,7 @@ const makeOpenCodeTextGeneration = Effect.gen(function* () {\n openCodeRuntime\n .startOpenCodeServerProcess({\n binaryPath: input.binaryPath,\n+ environment,\n })\n .pipe(\n Effect.provideService(Scope.Scope, serverScope),\n@@ -267,7 +270,7 @@ const makeOpenCodeTextGeneration = Effect.gen(function* () {\n readonly cwd: string;\n readonly prompt: string;\n readonly outputSchemaJson: S;\n- readonly modelSelection: OpenCodeModelSelection;\n+ readonly modelSelection: ModelSelection;\n readonly attachments?: ReadonlyArray<ChatAttachment> | undefined;\n }) {\n const parsedModel = parseOpenCodeModelSlug(input.modelSelection.model);\n@@ -278,26 +281,6 @@ const makeOpenCodeTextGeneration = Effect.gen(function* () {\n });\n }\n \n- const settings = yield* serverSettingsService.getSettings.pipe(\n- Effect.map(\n- (value) =>\n- value.providers?.opencode ?? {\n- enabled: true,\n- binaryPath: "opencode",\n- serverUrl: "",\n- serverPassword: "",\n- customModels: [],\n- },\n- ),\n- Effect.orElseSucceed(() => ({\n- enabled: true,\n- binaryPath: "opencode",\n- serverUrl: "",\n- serverPassword: "",\n- customModels: [],\n- })),\n- );\n-\n const fileParts = toOpenCodeFileParts({\n attachments: input.attachments,\n resolveAttachmentPath: (attachment) =>\n@@ -310,8 +293,8 @@ const makeOpenCodeTextGeneration = Effect.gen(function* () {\n const client = openCodeRuntime.createOpenCodeSdkClient({\n baseUrl: server.url,\n directory: input.cwd,\n- ...(settings.serverUrl.length > 0 && settings.serverPassword\n- ? { serverPassword: settings.serverPassword }\n+ ...(openCodeSettings.serverUrl.length > 0 && openCodeSettings.serverPassword\n+ ? { serverPassword: openCodeSettings.serverPassword }\n : {}),\n });\n const session = await client.session.create({\n@@ -354,11 +337,11 @@ const makeOpenCodeTextGeneration = Effect.gen(function* () {\n });\n \n const rawOutput =\n- settings.serverUrl.length > 0\n- ? yield* runAgainstServer({ url: settings.serverUrl })\n+ openCodeSettings.serverUrl.length > 0\n+ ? yield* runAgainstServer({ url: openCodeSettings.serverUrl })\n : yield* Effect.acquireUseRelease(\n acquireSharedServer({\n- binaryPath: settings.binaryPath,\n+ binaryPath: openCodeSettings.binaryPath,\n operation: input.operation,\n }),\n runAgainstServer,\n@@ -383,13 +366,6 @@ const makeOpenCodeTextGeneration = Effect.gen(function* () {\n const generateCommitMessage: TextGenerationShape["generateCommitMessage"] = Effect.fn(\n "OpenCodeTextGeneration.generateCommitMessage",\n )(function* (input) {\n- if (input.modelSelection.provider !== "opencode") {\n- return yield* new TextGenerationError({\n- operation: "generateCommitMessage",\n- detail: "Invalid model selection.",\n- });\n- }\n-\n const { prompt, outputSchema } = buildCommitMessagePrompt({\n branch: input.branch,\n stagedSummary: input.stagedSummary,\n@@ -416,13 +392,6 @@ const makeOpenCodeTextGeneration = Effect.gen(function* () {\n const generatePrContent: TextGenerationShape["generatePrContent"] = Effect.fn(\n "OpenCodeTextGeneration.generatePrContent",\n )(function* (input) {\n- if (input.modelSelection.provider !== "opencode") {\n- return yield* new TextGenerationError({\n- operation: "generatePrContent",\n- detail: "Invalid model selection.",\n- });\n- }\n-\n const { prompt, outputSchema } = buildPrContentPrompt({\n baseBranch: input.baseBranch,\n headBranch: input.headBranch,\n@@ -447,13 +416,6 @@ const makeOpenCodeTextGeneration = Effect.gen(function* () {\n const generateBranchName: TextGenerationShape["generateBranchName"] = Effect.fn(\n "OpenCodeTextGeneration.generateBranchName",\n )(function* (input) {\n- if (input.modelSelection.provider !== "opencode") {\n- return yield* new TextGenerationError({\n- operation: "generateBranchName",\n- detail: "Invalid model selection.",\n- });\n- }\n-\n const { prompt, outputSchema } = buildBranchNamePrompt({\n message: input.message,\n attachments: input.attachments,\n@@ -475,13 +437,6 @@ const makeOpenCodeTextGeneration = Effect.gen(function* () {\n const generateThreadTitle: TextGenerationShape["generateThreadTitle"] = Effect.fn(\n "OpenCodeTextGeneration.generateThreadTitle",\n )(function* (input) {\n- if (input.modelSelection.provider !== "opencode") {\n- return yield* new TextGenerationError({\n- operation: "generateThreadTitle",\n- detail: "Invalid model selection.",\n- });\n- }\n-\n const { prompt, outputSchema } = buildThreadTitlePrompt({\n message: input.message,\n attachments: input.attachments,\n@@ -507,5 +462,3 @@ const makeOpenCodeTextGeneration = Effect.gen(function* () {\n generateThreadTitle,\n } satisfies TextGenerationShape;\n });\n-\n-export const OpenCodeTextGenerationLive = Layer.effect(TextGeneration, makeOpenCodeTextGeneration);\ndiff --git a/apps/server/src/git/Layers/RoutingTextGeneration.ts b/apps/server/src/git/Layers/RoutingTextGeneration.ts\ndeleted file mode 100644\nindex 873d616f39..0000000000\n--- a/apps/server/src/git/Layers/RoutingTextGeneration.ts\n+++ /dev/null\n@@ -1,104 +0,0 @@\n-/**\n- * RoutingTextGeneration – Dispatches text generation requests to either the\n- * Codex CLI or Claude CLI implementation based on the provider in each\n- * request input.\n- *\n- * When `modelSelection.provider` is `"claudeAgent"` the request is forwarded to\n- * the Claude layer; for any other value (including the default `undefined`) it\n- * falls through to the Codex layer.\n- *\n- * @module RoutingTextGeneration\n- */\n-import { Effect, Layer, Context } from "effect";\n-\n-import { TextGeneration, type TextGenerationShape } from "../Services/TextGeneration.ts";\n-import { CodexTextGenerationLive } from "./CodexTextGeneration.ts";\n-import { ClaudeTextGenerationLive } from "./ClaudeTextGeneration.ts";\n-import { CursorTextGenerationLive } from "./CursorTextGeneration.ts";\n-import { OpenCodeTextGenerationLive } from "./OpenCodeTextGeneration.ts";\n-\n-// ---------------------------------------------------------------------------\n-// Internal service tags so both concrete layers can coexist.\n-// ---------------------------------------------------------------------------\n-\n-class CodexTextGen extends Context.Service<CodexTextGen, TextGenerationShape>()(\n- "t3/git/Layers/RoutingTextGeneration/CodexTextGen",\n-) {}\n-\n-class ClaudeTextGen extends Context.Service<ClaudeTextGen, TextGenerationShape>()(\n- "t3/git/Layers/RoutingTextGeneration/ClaudeTextGen",\n-) {}\n-\n-class CursorTextGen extends Context.Service<CursorTextGen, TextGenerationShape>()(\n- "t3/git/Layers/RoutingTextGeneration/CursorTextGen",\n-) {}\n-\n-class OpenCodeTextGen extends Context.Service<OpenCodeTextGen, TextGenerationShape>()(\n- "t3/git/Layers/RoutingTextGeneration/OpenCodeTextGen",\n-) {}\n-\n-// ---------------------------------------------------------------------------\n-// Routing implementation\n-// ---------------------------------------------------------------------------\n-\n-const makeRoutingTextGeneration = Effect.gen(function* () {\n- const byProvider = {\n- codex: yield* CodexTextGen,\n- claudeAgent: yield* ClaudeTextGen,\n- cursor: yield* CursorTextGen,\n- opencode: yield* OpenCodeTextGen,\n- };\n-\n- return {\n- generateCommitMessage: (input) =>\n- byProvider[input.modelSelection.provider].generateCommitMessage(input),\n- generatePrContent: (input) =>\n- byProvider[input.modelSelection.provider].generatePrContent(input),\n- generateBranchName: (input) =>\n- byProvider[input.modelSelection.provider].generateBranchName(input),\n- generateThreadTitle: (input) =>\n- byProvider[input.modelSelection.provider].generateThreadTitle(input),\n- } satisfies TextGenerationShape;\n-});\n-\n-const InternalCodexLayer = Layer.effect(\n- CodexTextGen,\n- Effect.gen(function* () {\n- const svc = yield* TextGeneration;\n- return svc;\n- }),\n-).pipe(Layer.provide(CodexTextGenerationLive));\n-\n-const InternalClaudeLayer = Layer.effect(\n- ClaudeTextGen,\n- Effect.gen(function* () {\n- const svc = yield* TextGeneration;\n- return svc;\n- }),\n-).pipe(Layer.provide(ClaudeTextGenerationLive));\n-\n-const InternalCursorLayer = Layer.effect(\n- CursorTextGen,\n- Effect.gen(function* () {\n- const svc = yield* TextGeneration;\n- return svc;\n- }),\n-).pipe(Layer.provide(CursorTextGenerationLive));\n-\n-const InternalOpenCodeLayer = Layer.effect(\n- OpenCodeTextGen,\n- Effect.gen(function* () {\n- const svc = yield* TextGeneration;\n- return svc;\n- }),\n-).pipe(Layer.provide(OpenCodeTextGenerationLive));\n-\n-export const RoutingTextGenerationLive = Layer.effect(\n- TextGeneration,\n- makeRoutingTextGeneration,\n-).pipe(\n- Layer.provide(InternalCodexLayer),\n- Layer.provide(InternalClaudeLayer),\n- Layer.provide(InternalCursorLayer),\n- Layer.provide(InternalOpenCodeLayer),\n-);\ndiff --git a/apps/server/src/git/Layers/TextGenerationLive.test.ts b/apps/server/src/git/Layers/TextGenerationLive.test.ts\nnew file mode 100644\nindex 0000000000..3b03696eb4\n--- /dev/null\n+++ b/apps/server/src/git/Layers/TextGenerationLive.test.ts\n@@ -0,0 +1,117 @@\n+import { it } from "@effect/vitest";\n+import { Effect, PubSub, Result, Stream } from "effect";\n+import { describe, expect } from "vitest";\n+\n+import { ProviderInstanceId } from "@t3tools/contracts";\n+import { createModelSelection } from "@t3tools/shared/model";\n+\n+import type { ProviderInstance } from "../../provider/ProviderDriver.ts";\n+import type { ProviderInstanceRegistryShape } from "../../provider/Services/ProviderInstanceRegistry.ts";\n+import type { TextGenerationShape } from "../Services/TextGeneration.ts";\n+\n+import { makeTextGenerationFromRegistry } from "./TextGenerationLive.ts";\n+\n+const makeStubTextGeneration = (overrides: Partial<TextGenerationShape>): TextGenerationShape => ({\n+ generateCommitMessage: () =>\n+ Effect.die("generateCommitMessage stub not configured for this test"),\n+ generatePrContent: () => Effect.die("generatePrContent stub not configured for this test"),\n+ generateBranchName: () => Effect.die("generateBranchName stub not configured for this test"),\n+ generateThreadTitle: () => Effect.die("generateThreadTitle stub not configured for this test"),\n+ ...overrides,\n+});\n+\n+const makeStubInstance = (\n+ instanceId: ProviderInstanceId,\n+ textGeneration: TextGenerationShape,\n+): ProviderInstance =>\n+ ({\n+ instanceId,\n+ driverKind: instanceId as unknown as ProviderInstance["driverKind"],\n+ continuationIdentity: {\n+ driverKind: instanceId as unknown as ProviderInstance["driverKind"],\n+ continuationKey: `${instanceId}:test`,\n+ },\n+ displayName: undefined,\n+ enabled: true,\n+ snapshot: {} as ProviderInstance["snapshot"],\n+ adapter: {} as ProviderInstance["adapter"],\n+ textGeneration,\n+ }) satisfies ProviderInstance;\n+\n+const makeStubRegistry = (\n+ instances: ReadonlyArray<ProviderInstance>,\n+): ProviderInstanceRegistryShape => {\n+ const byId = new Map(instances.map((instance) => [instance.instanceId, instance] as const));\n+ return {\n+ getInstance: (id) => Effect.succeed(byId.get(id)),\n+ listInstances: Effect.succeed(instances),\n+ listUnavailable: Effect.succeed([]),\n+ streamChanges: Stream.empty,\n+ // Tests never drive changes through this stub; acquire a throwaway\n+ // subscription on an unused PubSub so the shape is satisfied.\n+ subscribeChanges: Effect.flatMap(PubSub.unbounded<void>(), (pubsub) =>\n+ PubSub.subscribe(pubsub),\n+ ),\n+ };\n+};\n+\n+describe("makeTextGenerationFromRegistry", () => {\n+ it.effect("delegates to the matching instance\'s textGeneration closure", () =>\n+ Effect.gen(function* () {\n+ const personalId = ProviderInstanceId.make("codex_personal");\n+ const personalCalls: string[] = [];\n+ const personal = makeStubInstance(\n+ personalId,\n+ makeStubTextGeneration({\n+ generateBranchName: (input) => {\n+ personalCalls.push(input.message);\n+ return Effect.succeed({ branch: "personal-branch" });\n+ },\n+ }),\n+ );\n+\n+ const workId = ProviderInstanceId.make("codex_work");\n+ const work = makeStubInstance(\n+ workId,\n+ makeStubTextGeneration({\n+ generateBranchName: () => Effect.succeed({ branch: "work-branch" }),\n+ }),\n+ );\n+\n+ const tg = makeTextGenerationFromRegistry(makeStubRegistry([personal, work]));\n+\n+ const result = yield* tg.generateBranchName({\n+ cwd: process.cwd(),\n+ message: "Refactor the routing layer",\n+ modelSelection: createModelSelection(ProviderInstanceId.make("codex_personal"), "gpt-5"),\n+ });\n+\n+ expect(result.branch).toBe("personal-branch");\n+ expect(personalCalls).toEqual(["Refactor the routing layer"]);\n+ }),\n+ );\n+\n+ it.effect("fails with TextGenerationError when the instance is unknown", () =>\n+ Effect.gen(function* () {\n+ const tg = makeTextGenerationFromRegistry(makeStubRegistry([]));\n+\n+ const result = yield* tg\n+ .generateBranchName({\n+ cwd: process.cwd(),\n+ message: "anything",\n+ modelSelection: createModelSelection(\n+ ProviderInstanceId.make("missing_instance"),\n+ "gpt-5",\n+ ),\n+ })\n+ .pipe(Effect.result);\n+\n+ expect(Result.isFailure(result)).toBe(true);\n+ if (Result.isFailure(result)) {\n+ expect(result.failure._tag).toBe("TextGenerationError");\n+ expect(result.failure.operation).toBe("generateBranchName");\n+ expect(result.failure.detail).toContain("missing_instance");\n+ }\n+ }),\n+ );\n+});\ndiff --git a/apps/server/src/git/Layers/TextGenerationLive.ts b/apps/server/src/git/Layers/TextGenerationLive.ts\nnew file mode 100644\nindex 0000000000..58e1541d55\n--- /dev/null\n+++ b/apps/server/src/git/Layers/TextGenerationLive.ts\n@@ -0,0 +1,101 @@\n+/**\n+ * TextGenerationLive — registry-backed implementation of the `TextGeneration`\n+ * service tag.\n+ *\n+ * The `TextGeneration` tag is kept as a thin facade over\n+ * `ProviderInstanceRegistry`. Every op pulls `modelSelection.instanceId`,\n+ * looks up the matching `ProviderInstance`, and delegates to that instance\'s\n+ * own `textGeneration` closure (built by its driver\'s `create()`).\n+ *\n+ * There is deliberately no per-driver dispatch here — the registry already\n+ * knows which driver backs each instance, and each `ProviderInstance`\n+ * carries the fully-bound `TextGenerationShape` produced by its driver.\n+ * That means:\n+ *\n+ * - Multiple instances of the same driver (e.g. `codex_personal`,\n+ * `codex_work`) each get their own text-generation closure bound to\n+ * their own settings — the routing is by instance, not by driver.\n+ * - Unknown or disabled instances surface a `TextGenerationError` with\n+ * the missing `instanceId`, instead of silently falling back to a\n+ * default.\n+ *\n+ * This replaces the old `RoutingTextGenerationLive`, which tried to route\n+ * by driver-kind and misused `modelSelection.instanceId` as a driver-id\n+ * literal.\n+ *\n+ * @module git/Layers/TextGenerationLive\n+ */\n+import { Effect, Layer } from "effect";\n+\n+import { TextGenerationError } from "@t3tools/contracts";\n+import type { ProviderInstanceId } from "@t3tools/contracts";\n+\n+import {\n+ ProviderInstanceRegistry,\n+ type ProviderInstanceRegistryShape,\n+} from "../../provider/Services/ProviderInstanceRegistry.ts";\n+import type { ProviderInstance } from "../../provider/ProviderDriver.ts";\n+import { TextGeneration, type TextGenerationShape } from "../Services/TextGeneration.ts";\n+\n+type TextGenerationOp =\n+ | "generateCommitMessage"\n+ | "generatePrContent"\n+ | "generateBranchName"\n+ | "generateThreadTitle";\n+\n+const resolveInstance = (\n+ registry: ProviderInstanceRegistryShape,\n+ operation: TextGenerationOp,\n+ instanceId: ProviderInstanceId,\n+): Effect.Effect<ProviderInstance["textGeneration"], TextGenerationError> =>\n+ registry.getInstance(instanceId).pipe(\n+ Effect.flatMap((instance) =>\n+ instance\n+ ? Effect.succeed(instance.textGeneration)\n+ : Effect.fail(\n+ new TextGenerationError({\n+ operation,\n+ detail: `No provider instance registered for id \'${instanceId}\'.`,\n+ }),\n+ ),\n+ ),\n+ );\n+\n+/**\n+ * Build a `TextGenerationShape` that routes every call through the\n+ * registry. Exposed separately from the Layer so tests can construct it\n+ * against a stub registry without layering gymnastics.\n+ */\n+export const makeTextGenerationFromRegistry = (\n+ registry: ProviderInstanceRegistryShape,\n+): TextGenerationShape => ({\n+ generateCommitMessage: (input) =>\n+ resolveInstance(registry, "generateCommitMessage", input.modelSelection.instanceId).pipe(\n+ Effect.flatMap((tg) => tg.generateCommitMessage(input)),\n+ ),\n+ generatePrContent: (input) =>\n+ resolveInstance(registry, "generatePrContent", input.modelSelection.instanceId).pipe(\n+ Effect.flatMap((tg) => tg.generatePrContent(input)),\n+ ),\n+ generateBranchName: (input) =>\n+ resolveInstance(registry, "generateBranchName", input.modelSelection.instanceId).pipe(\n+ Effect.flatMap((tg) => tg.generateBranchName(input)),\n+ ),\n+ generateThreadTitle: (input) =>\n+ resolveInstance(registry, "generateThreadTitle", input.modelSelection.instanceId).pipe(\n+ Effect.flatMap((tg) => tg.generateThreadTitle(input)),\n+ ),\n+});\n+\n+/**\n+ * `TextGeneration` Layer wired to the `ProviderInstanceRegistry`. The rest\n+ * of the server keeps using `yield* TextGeneration` — only the underlying\n+ * wiring changed from kind-based routing to instance-based routing.\n+ */\n+export const TextGenerationLive = Layer.effect(\n+ TextGeneration,\n+ Effect.gen(function* () {\n+ const registry = yield* ProviderInstanceRegistry;\n+ return makeTextGenerationFromRegistry(registry);\n+ }),\n+);\ndiff --git a/apps/server/src/observability/Metrics.test.ts b/apps/server/src/observability/Metrics.test.ts\nindex 4604f43b63..b5eeedaaa4 100644\n--- a/apps/server/src/observability/Metrics.test.ts\n+++ b/apps/server/src/observability/Metrics.test.ts\n@@ -1,4 +1,5 @@\n import { assert, describe, it } from "@effect/vitest";\n+import { ProviderDriverKind } from "@t3tools/contracts";\n import { Effect, Metric } from "effect";\n \n import { withMetrics } from "./Metrics.ts";\n@@ -75,10 +76,11 @@ describe("withMetrics", () => {\n Effect.gen(function* () {\n const counter = Metric.counter("with_metrics_lazy_total");\n const timer = Metric.timer("with_metrics_lazy_duration");\n- let provider = "unknown";\n+ let provider = ProviderDriverKind.make("unknown");\n+ const lazyInittedProvider = ProviderDriverKind.make("codex");\n \n yield* Effect.sync(() => {\n- provider = "codex";\n+ provider = lazyInittedProvider;\n }).pipe(\n withMetrics({\n counter,\n@@ -93,7 +95,7 @@ describe("withMetrics", () => {\n const snapshots = yield* Metric.snapshot;\n assert.equal(\n hasMetricSnapshot(snapshots, "with_metrics_lazy_total", {\n- provider: "codex",\n+ provider: lazyInittedProvider,\n operation: "lazy",\n outcome: "success",\n }),\n@@ -101,7 +103,7 @@ describe("withMetrics", () => {\n );\n assert.equal(\n hasMetricSnapshot(snapshots, "with_metrics_lazy_duration", {\n- provider: "codex",\n+ provider: lazyInittedProvider,\n operation: "lazy",\n }),\n true,\ndiff --git a/apps/server/src/orchestration/Layers/CheckpointReactor.test.ts b/apps/server/src/orchestration/Layers/CheckpointReactor.test.ts\nindex 12e11450dd..5603ce6325 100644\n--- a/apps/server/src/orchestration/Layers/CheckpointReactor.test.ts\n+++ b/apps/server/src/orchestration/Layers/CheckpointReactor.test.ts\n@@ -3,7 +3,12 @@ import os from "node:os";\n import path from "node:path";\n import { execFileSync } from "node:child_process";\n \n-import type { ProviderKind, ProviderRuntimeEvent, ProviderSession } from "@t3tools/contracts";\n+import {\n+ ProviderDriverKind,\n+ ProviderRuntimeEvent,\n+ ProviderSession,\n+ ProviderInstanceId,\n+} from "@t3tools/contracts";\n import {\n CommandId,\n DEFAULT_PROVIDER_INTERACTION_MODE,\n@@ -50,7 +55,7 @@ const asTurnId = (value: string): TurnId => TurnId.make(value);\n type LegacyProviderRuntimeEvent = {\n readonly type: string;\n readonly eventId: EventId;\n- readonly provider: ProviderKind;\n+ readonly provider: ProviderDriverKind;\n readonly createdAt: string;\n readonly threadId: ThreadId;\n readonly turnId?: string | undefined;\n@@ -64,7 +69,7 @@ function createProviderServiceHarness(\n cwd: string,\n hasSession = true,\n sessionCwd = cwd,\n- providerName: ProviderSession["provider"] = "codex",\n+ providerName: ProviderSession["provider"] = ProviderDriverKind.make("codex"),\n ) {\n const now = new Date().toISOString();\n const runtimeEventPubSub = Effect.runSync(PubSub.unbounded<ProviderRuntimeEvent>());\n@@ -97,6 +102,17 @@ function createProviderServiceHarness(\n stopSession: () => unsupported(),\n listSessions,\n getCapabilities: () => Effect.succeed({ sessionModelSwitch: "in-session" }),\n+ getInstanceInfo: (instanceId) =>\n+ Effect.succeed({\n+ instanceId,\n+ driverKind: ProviderDriverKind.make(providerName),\n+ displayName: undefined,\n+ enabled: true,\n+ continuationIdentity: {\n+ driverKind: ProviderDriverKind.make(providerName),\n+ continuationKey: `${providerName}:instance:${instanceId}`,\n+ },\n+ }),\n rollbackConversation,\n get streamEvents() {\n return Stream.fromPubSub(runtimeEventPubSub);\n@@ -243,7 +259,7 @@ describe("CheckpointReactor", () => {\n readonly projectWorkspaceRoot?: string;\n readonly threadWorktreePath?: string | null;\n readonly providerSessionCwd?: string;\n- readonly providerName?: ProviderKind;\n+ readonly providerName?: ProviderDriverKind;\n readonly gitStatusRefreshCalls?: Array<string>;\n }) {\n const cwd = createGitRepository();\n@@ -252,7 +268,7 @@ describe("CheckpointReactor", () => {\n cwd,\n options?.hasSession ?? true,\n options?.providerSessionCwd ?? cwd,\n- options?.providerName ?? "codex",\n+ options?.providerName ?? ProviderDriverKind.make("codex"),\n );\n const orchestrationLayer = OrchestrationEngineLive.pipe(\n Layer.provide(OrchestrationProjectionSnapshotQueryLive),\n@@ -315,7 +331,7 @@ describe("CheckpointReactor", () => {\n title: "Test Project",\n workspaceRoot: options?.projectWorkspaceRoot ?? cwd,\n defaultModelSelection: {\n- provider: "codex",\n+ instanceId: ProviderInstanceId.make("codex"),\n model: "gpt-5-codex",\n },\n createdAt,\n@@ -329,7 +345,7 @@ describe("CheckpointReactor", () => {\n projectId: asProjectId("project-1"),\n title: "Thread",\n modelSelection: {\n- provider: "codex",\n+ instanceId: ProviderInstanceId.make("codex"),\n model: "gpt-5-codex",\n },\n interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,\n@@ -396,7 +412,7 @@ describe("CheckpointReactor", () => {\n harness.provider.emit({\n type: "turn.started",\n eventId: EventId.make("evt-turn-started-1"),\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n \n createdAt: new Date().toISOString(),\n threadId: ThreadId.make("thread-1"),\n@@ -411,7 +427,7 @@ describe("CheckpointReactor", () => {\n harness.provider.emit({\n type: "turn.completed",\n eventId: EventId.make("evt-turn-completed-1"),\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n \n createdAt: new Date().toISOString(),\n threadId: ThreadId.make("thread-1"),\n@@ -457,7 +473,7 @@ describe("CheckpointReactor", () => {\n harness.provider.emit({\n type: "turn.completed",\n eventId: EventId.make("evt-turn-completed-refresh-local-status"),\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n createdAt: new Date().toISOString(),\n threadId: ThreadId.make("thread-1"),\n turnId: asTurnId("turn-refresh-local-status"),\n@@ -494,7 +510,7 @@ describe("CheckpointReactor", () => {\n harness.provider.emit({\n type: "turn.started",\n eventId: EventId.make("evt-turn-started-main"),\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n \n createdAt: new Date().toISOString(),\n threadId: ThreadId.make("thread-1"),\n@@ -510,7 +526,7 @@ describe("CheckpointReactor", () => {\n harness.provider.emit({\n type: "turn.completed",\n eventId: EventId.make("evt-turn-completed-aux"),\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n \n createdAt: new Date().toISOString(),\n threadId: ThreadId.make("thread-1"),\n@@ -526,7 +542,7 @@ describe("CheckpointReactor", () => {\n harness.provider.emit({\n type: "turn.completed",\n eventId: EventId.make("evt-turn-completed-main"),\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n \n createdAt: new Date().toISOString(),\n threadId: ThreadId.make("thread-1"),\n@@ -544,7 +560,7 @@ describe("CheckpointReactor", () => {\n it("captures pre-turn and completion checkpoints for claude runtime events", async () => {\n const harness = await createHarness({\n seedFilesystemCheckpoints: false,\n- providerName: "claudeAgent",\n+ providerName: ProviderDriverKind.make("claudeAgent"),\n });\n const createdAt = new Date().toISOString();\n \n@@ -569,7 +585,7 @@ describe("CheckpointReactor", () => {\n harness.provider.emit({\n type: "turn.started",\n eventId: EventId.make("evt-turn-started-claude-1"),\n- provider: "claudeAgent",\n+ provider: ProviderDriverKind.make("claudeAgent"),\n createdAt: new Date().toISOString(),\n threadId: ThreadId.make("thread-1"),\n turnId: asTurnId("turn-claude-1"),\n@@ -583,7 +599,7 @@ describe("CheckpointReactor", () => {\n harness.provider.emit({\n type: "turn.completed",\n eventId: EventId.make("evt-turn-completed-claude-1"),\n- provider: "claudeAgent",\n+ provider: ProviderDriverKind.make("claudeAgent"),\n createdAt: new Date().toISOString(),\n threadId: ThreadId.make("thread-1"),\n turnId: asTurnId("turn-claude-1"),\n@@ -627,7 +643,7 @@ describe("CheckpointReactor", () => {\n harness.provider.emit({\n type: "turn.completed",\n eventId: EventId.make("evt-turn-completed-missing-baseline"),\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n \n createdAt: new Date().toISOString(),\n threadId: ThreadId.make("thread-1"),\n@@ -716,7 +732,7 @@ describe("CheckpointReactor", () => {\n harness.provider.emit({\n type: "turn.completed",\n eventId: EventId.make("evt-turn-completed-missing-provider-cwd"),\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n \n createdAt: new Date().toISOString(),\n threadId: ThreadId.make("thread-1"),\n@@ -762,7 +778,7 @@ describe("CheckpointReactor", () => {\n harness.provider.emit({\n type: "checkpoint.captured",\n eventId: EventId.make("evt-checkpoint-captured-3"),\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n \n createdAt: new Date().toISOString(),\n threadId: ThreadId.make("thread-1"),\n@@ -812,7 +828,7 @@ describe("CheckpointReactor", () => {\n harness.provider.emit({\n type: "turn.completed",\n eventId: EventId.make("evt-runtime-capture-failure"),\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n \n createdAt: new Date().toISOString(),\n threadId: ThreadId.make("thread-1"),\n@@ -823,7 +839,7 @@ describe("CheckpointReactor", () => {\n harness.provider.emit({\n type: "turn.started",\n eventId: EventId.make("evt-turn-started-after-runtime-failure"),\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n \n createdAt: new Date().toISOString(),\n threadId: ThreadId.make("thread-1"),\n@@ -918,7 +934,7 @@ describe("CheckpointReactor", () => {\n });\n \n it("executes provider revert and emits thread.reverted for claude sessions", async () => {\n- const harness = await createHarness({ providerName: "claudeAgent" });\n+ const harness = await createHarness({ providerName: ProviderDriverKind.make("claudeAgent") });\n const createdAt = new Date().toISOString();\n \n await Effect.runPromise(\ndiff --git a/apps/server/src/orchestration/Layers/OrchestrationEngine.test.ts b/apps/server/src/orchestration/Layers/OrchestrationEngine.test.ts\nindex b61664f161..0af5b099a6 100644\n--- a/apps/server/src/orchestration/Layers/OrchestrationEngine.test.ts\n+++ b/apps/server/src/orchestration/Layers/OrchestrationEngine.test.ts\n@@ -7,6 +7,7 @@ import {\n ThreadId,\n TurnId,\n type OrchestrationEvent,\n+ ProviderInstanceId,\n } from "@t3tools/contracts";\n import { Effect, Layer, ManagedRuntime, Metric, Option, Queue, Stream } from "effect";\n import { describe, expect, it } from "vitest";\n@@ -104,7 +105,7 @@ describe("OrchestrationEngine", () => {\n title: "Bootstrap Project",\n workspaceRoot: "/tmp/project-bootstrap",\n defaultModelSelection: {\n- provider: "codex" as const,\n+ instanceId: ProviderInstanceId.make("codex"),\n model: "gpt-5-codex",\n },\n scripts: [],\n@@ -119,7 +120,7 @@ describe("OrchestrationEngine", () => {\n projectId: asProjectId("project-bootstrap"),\n title: "Bootstrap Thread",\n modelSelection: {\n- provider: "codex" as const,\n+ instanceId: ProviderInstanceId.make("codex"),\n model: "gpt-5-codex",\n },\n interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,\n@@ -198,7 +199,7 @@ describe("OrchestrationEngine", () => {\n title: "Project 1",\n workspaceRoot: "/tmp/project-1",\n defaultModelSelection: {\n- provider: "codex",\n+ instanceId: ProviderInstanceId.make("codex"),\n model: "gpt-5-codex",\n },\n createdAt,\n@@ -212,7 +213,7 @@ describe("OrchestrationEngine", () => {\n projectId: asProjectId("project-1"),\n title: "Thread",\n modelSelection: {\n- provider: "codex",\n+ instanceId: ProviderInstanceId.make("codex"),\n model: "gpt-5-codex",\n },\n interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,\n@@ -258,7 +259,7 @@ describe("OrchestrationEngine", () => {\n title: "Project Archive",\n workspaceRoot: "/tmp/project-archive",\n defaultModelSelection: {\n- provider: "codex",\n+ instanceId: ProviderInstanceId.make("codex"),\n model: "gpt-5-codex",\n },\n createdAt,\n@@ -272,7 +273,7 @@ describe("OrchestrationEngine", () => {\n projectId: asProjectId("project-archive"),\n title: "Archive me",\n modelSelection: {\n- provider: "codex",\n+ instanceId: ProviderInstanceId.make("codex"),\n model: "gpt-5-codex",\n },\n interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,\n@@ -325,7 +326,7 @@ describe("OrchestrationEngine", () => {\n title: "Replay Project",\n workspaceRoot: "/tmp/project-replay",\n defaultModelSelection: {\n- provider: "codex",\n+ instanceId: ProviderInstanceId.make("codex"),\n model: "gpt-5-codex",\n },\n createdAt,\n@@ -339,7 +340,7 @@ describe("OrchestrationEngine", () => {\n projectId: asProjectId("project-replay"),\n title: "replay",\n modelSelection: {\n- provider: "codex",\n+ instanceId: ProviderInstanceId.make("codex"),\n model: "gpt-5-codex",\n },\n interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,\n@@ -383,7 +384,7 @@ describe("OrchestrationEngine", () => {\n title: "Stream Project",\n workspaceRoot: "/tmp/project-stream",\n defaultModelSelection: {\n- provider: "codex",\n+ instanceId: ProviderInstanceId.make("codex"),\n model: "gpt-5-codex",\n },\n createdAt,\n@@ -407,7 +408,7 @@ describe("OrchestrationEngine", () => {\n projectId: asProjectId("project-stream"),\n title: "domain-stream",\n modelSelection: {\n- provider: "codex",\n+ instanceId: ProviderInstanceId.make("codex"),\n model: "gpt-5-codex",\n },\n interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,\n@@ -444,7 +445,7 @@ describe("OrchestrationEngine", () => {\n title: "Ack Project",\n workspaceRoot: "/tmp/project-ack",\n defaultModelSelection: {\n- provider: "codex",\n+ instanceId: ProviderInstanceId.make("codex"),\n model: "gpt-5-codex",\n },\n createdAt,\n@@ -459,7 +460,7 @@ describe("OrchestrationEngine", () => {\n projectId: asProjectId("project-ack"),\n title: "Ack Thread",\n modelSelection: {\n- provider: "codex",\n+ instanceId: ProviderInstanceId.make("codex"),\n model: "gpt-5-codex",\n },\n interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,\n@@ -496,7 +497,7 @@ describe("OrchestrationEngine", () => {\n projectId: asProjectId("project-missing"),\n title: "Missing Project Thread",\n modelSelection: {\n- provider: "codex",\n+ instanceId: ProviderInstanceId.make("codex"),\n model: "gpt-5-codex",\n },\n interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,\n@@ -533,7 +534,7 @@ describe("OrchestrationEngine", () => {\n title: "Turn Diff Project",\n workspaceRoot: "/tmp/project-turn-diff",\n defaultModelSelection: {\n- provider: "codex",\n+ instanceId: ProviderInstanceId.make("codex"),\n model: "gpt-5-codex",\n },\n createdAt,\n@@ -547,7 +548,7 @@ describe("OrchestrationEngine", () => {\n projectId: asProjectId("project-turn-diff"),\n title: "Turn diff thread",\n modelSelection: {\n- provider: "codex",\n+ instanceId: ProviderInstanceId.make("codex"),\n model: "gpt-5-codex",\n },\n interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,\n@@ -652,7 +653,7 @@ describe("OrchestrationEngine", () => {\n title: "Flaky Project",\n workspaceRoot: "/tmp/project-flaky",\n defaultModelSelection: {\n- provider: "codex",\n+ instanceId: ProviderInstanceId.make("codex"),\n model: "gpt-5-codex",\n },\n createdAt,\n@@ -668,7 +669,7 @@ describe("OrchestrationEngine", () => {\n projectId: asProjectId("project-flaky"),\n title: "flaky-fail",\n modelSelection: {\n- provider: "codex",\n+ instanceId: ProviderInstanceId.make("codex"),\n model: "gpt-5-codex",\n },\n interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,\n@@ -688,7 +689,7 @@ describe("OrchestrationEngine", () => {\n projectId: asProjectId("project-flaky"),\n title: "flaky-ok",\n modelSelection: {\n- provider: "codex",\n+ instanceId: ProviderInstanceId.make("codex"),\n model: "gpt-5-codex",\n },\n interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,\n@@ -747,7 +748,7 @@ describe("OrchestrationEngine", () => {\n title: "Atomic Project",\n workspaceRoot: "/tmp/project-atomic",\n defaultModelSelection: {\n- provider: "codex",\n+ instanceId: ProviderInstanceId.make("codex"),\n model: "gpt-5-codex",\n },\n createdAt,\n@@ -761,7 +762,7 @@ describe("OrchestrationEngine", () => {\n projectId: asProjectId("project-atomic"),\n title: "atomic",\n modelSelection: {\n- provider: "codex",\n+ instanceId: ProviderInstanceId.make("codex"),\n model: "gpt-5-codex",\n },\n interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,\n@@ -890,7 +891,7 @@ describe("OrchestrationEngine", () => {\n title: "Sync Project",\n workspaceRoot: "/tmp/project-sync",\n defaultModelSelection: {\n- provider: "codex",\n+ instanceId: ProviderInstanceId.make("codex"),\n model: "gpt-5-codex",\n },\n createdAt,\n@@ -904,7 +905,7 @@ describe("OrchestrationEngine", () => {\n projectId: asProjectId("project-sync"),\n title: "sync-before",\n modelSelection: {\n- provider: "codex",\n+ instanceId: ProviderInstanceId.make("codex"),\n model: "gpt-5-codex",\n },\n interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,\n@@ -975,7 +976,7 @@ describe("OrchestrationEngine", () => {\n title: "Duplicate Project",\n workspaceRoot: "/tmp/project-duplicate",\n defaultModelSelection: {\n- provider: "codex",\n+ instanceId: ProviderInstanceId.make("codex"),\n model: "gpt-5-codex",\n },\n createdAt,\n@@ -990,7 +991,7 @@ describe("OrchestrationEngine", () => {\n projectId: asProjectId("project-duplicate"),\n title: "duplicate",\n modelSelection: {\n- provider: "codex",\n+ instanceId: ProviderInstanceId.make("codex"),\n model: "gpt-5-codex",\n },\n interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,\n@@ -1010,7 +1011,7 @@ describe("OrchestrationEngine", () => {\n projectId: asProjectId("project-duplicate"),\n title: "duplicate",\n modelSelection: {\n- provider: "codex",\n+ instanceId: ProviderInstanceId.make("codex"),\n model: "gpt-5-codex",\n },\n interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,\ndiff --git a/apps/server/src/orchestration/Layers/ProjectionPipeline.test.ts b/apps/server/src/orchestration/Layers/ProjectionPipeline.test.ts\nindex 7a08765647..7f364c717a 100644\n--- a/apps/server/src/orchestration/Layers/ProjectionPipeline.test.ts\n+++ b/apps/server/src/orchestration/Layers/ProjectionPipeline.test.ts\n@@ -7,6 +7,7 @@ import {\n ProjectId,\n ThreadId,\n TurnId,\n+ ProviderInstanceId,\n } from "@t3tools/contracts";\n import * as NodeServices from "@effect/platform-node/NodeServices";\n import { assert, it } from "@effect/vitest";\n@@ -92,7 +93,7 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {\n projectId: ProjectId.make("project-1"),\n title: "Thread 1",\n modelSelection: {\n- provider: "codex",\n+ instanceId: ProviderInstanceId.make("codex"),\n model: "gpt-5-codex",\n },\n runtimeMode: "full-access",\n@@ -364,7 +365,7 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {\n projectId: ProjectId.make("project-clear-attachments"),\n title: "Thread Clear Attachments",\n modelSelection: {\n- provider: "codex",\n+ instanceId: ProviderInstanceId.make("codex"),\n model: "gpt-5-codex",\n },\n runtimeMode: "full-access",\n@@ -492,7 +493,7 @@ it.layer(\n projectId: ProjectId.make("project-overwrite"),\n title: "Thread Overwrite",\n modelSelection: {\n- provider: "codex",\n+ instanceId: ProviderInstanceId.make("codex"),\n model: "gpt-5-codex",\n },\n runtimeMode: "full-access",\n@@ -640,7 +641,7 @@ it.layer(\n projectId: ProjectId.make("project-rollback"),\n title: "Thread Rollback",\n modelSelection: {\n- provider: "codex",\n+ instanceId: ProviderInstanceId.make("codex"),\n model: "gpt-5-codex",\n },\n runtimeMode: "full-access",\n@@ -769,7 +770,7 @@ it.layer(\n projectId: ProjectId.make("project-revert-files"),\n title: "Thread Revert Files",\n modelSelection: {\n- provider: "codex",\n+ instanceId: ProviderInstanceId.make("codex"),\n model: "gpt-5-codex",\n },\n runtimeMode: "full-access",\n@@ -977,7 +978,7 @@ it.layer(Layer.fresh(makeProjectionPipelinePrefixedTestLayer("t3-projection-atta\n projectId: ProjectId.make("project-delete-files"),\n title: "Thread Delete Files",\n modelSelection: {\n- provider: "codex",\n+ instanceId: ProviderInstanceId.make("codex"),\n model: "gpt-5-codex",\n },\n runtimeMode: "full-access",\n@@ -1140,7 +1141,7 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {\n projectId: ProjectId.make("project-a"),\n title: "Thread A",\n modelSelection: {\n- provider: "codex",\n+ instanceId: ProviderInstanceId.make("codex"),\n model: "gpt-5-codex",\n },\n runtimeMode: "full-access",\n@@ -1267,7 +1268,7 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {\n projectId: ProjectId.make("project-empty"),\n title: "Thread Empty",\n modelSelection: {\n- provider: "codex",\n+ instanceId: ProviderInstanceId.make("codex"),\n model: "gpt-5-codex",\n },\n runtimeMode: "full-access",\n@@ -1407,7 +1408,7 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {\n projectId: ProjectId.make("project-conflict"),\n title: "Thread Conflict",\n modelSelection: {\n- provider: "codex",\n+ instanceId: ProviderInstanceId.make("codex"),\n model: "gpt-5-codex",\n },\n runtimeMode: "full-access",\n@@ -1551,7 +1552,7 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {\n projectId: ProjectId.make("project-stale-approval"),\n title: "Thread Stale Approval",\n modelSelection: {\n- provider: "codex",\n+ instanceId: ProviderInstanceId.make("codex"),\n model: "gpt-5-codex",\n },\n runtimeMode: "approval-required",\n@@ -1694,7 +1695,7 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {\n projectId: ProjectId.make("project-nonstale-approval"),\n title: "Thread Non-Stale Approval",\n modelSelection: {\n- provider: "codex",\n+ instanceId: ProviderInstanceId.make("codex"),\n model: "gpt-5-codex",\n },\n runtimeMode: "approval-required",\n@@ -1874,7 +1875,7 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {\n projectId: ProjectId.make("project-revert"),\n title: "Thread Revert",\n modelSelection: {\n- provider: "codex",\n+ instanceId: ProviderInstanceId.make("codex"),\n model: "gpt-5-codex",\n },\n runtimeMode: "full-access",\n@@ -2195,7 +2196,7 @@ engineLayer("OrchestrationProjectionPipeline via engine dispatch", (it) => {\n title: "Live Project",\n workspaceRoot: "/tmp/project-live",\n defaultModelSelection: {\n- provider: "codex",\n+ instanceId: ProviderInstanceId.make("codex"),\n model: "gpt-5-codex",\n },\n createdAt,\n@@ -2233,7 +2234,7 @@ engineLayer("OrchestrationProjectionPipeline via engine dispatch", (it) => {\n title: "Scripts Project",\n workspaceRoot: "/tmp/project-scripts",\n defaultModelSelection: {\n- provider: "codex",\n+ instanceId: ProviderInstanceId.make("codex"),\n model: "gpt-5-codex",\n },\n createdAt,\n@@ -2253,7 +2254,7 @@ engineLayer("OrchestrationProjectionPipeline via engine dispatch", (it) => {\n },\n ],\n defaultModelSelection: {\n- provider: "codex",\n+ instanceId: ProviderInstanceId.make("codex"),\n model: "gpt-5",\n },\n });\n@@ -2272,7 +2273,7 @@ engineLayer("OrchestrationProjectionPipeline via engine dispatch", (it) => {\n {\n scriptsJson:\n \'[{"id":"script-1","name":"Build","command":"bun run build","icon":"build","runOnWorktreeCreate":false}]\',\n- defaultModelSelection: \'{"provider":"codex","model":"gpt-5"}\',\n+ defaultModelSelection: \'{"instanceId":"codex","model":"gpt-5"}\',\n },\n ]);\n }),\ndiff --git a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts b/apps/server/src/orchestration/Layers/ProjectionPipeline.ts\nindex d981ae0da6..28a0208e75 100644\n--- a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts\n+++ b/apps/server/src/orchestration/Layers/ProjectionPipeline.ts\n@@ -945,6 +945,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti\n threadId: event.payload.threadId,\n status: event.payload.session.status,\n providerName: event.payload.session.providerName,\n+ providerInstanceId: event.payload.session.providerInstanceId ?? null,\n runtimeMode: event.payload.session.runtimeMode,\n activeTurnId: event.payload.session.activeTurnId,\n lastError: event.payload.session.lastError,\ndiff --git a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts\nindex 9f0d63545f..cba5ce7e83 100644\n--- a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts\n+++ b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts\n@@ -1,4 +1,12 @@\n-import { CheckpointRef, EventId, MessageId, ProjectId, ThreadId, TurnId } from "@t3tools/contracts";\n+import {\n+ CheckpointRef,\n+ EventId,\n+ MessageId,\n+ ProjectId,\n+ ThreadId,\n+ TurnId,\n+ ProviderInstanceId,\n+} from "@t3tools/contracts";\n import { assert, it } from "@effect/vitest";\n import { Effect, Layer } from "effect";\n import * as SqlClient from "effect/unstable/sql/SqlClient";\n@@ -252,7 +260,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {\n workspaceRoot: "/tmp/project-1",\n repositoryIdentity: null,\n defaultModelSelection: {\n- provider: "codex",\n+ instanceId: ProviderInstanceId.make("codex"),\n model: "gpt-5-codex",\n },\n scripts: [\n@@ -275,7 +283,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {\n projectId: asProjectId("project-1"),\n title: "Thread 1",\n modelSelection: {\n- provider: "codex",\n+ instanceId: ProviderInstanceId.make("codex"),\n model: "gpt-5-codex",\n },\n interactionMode: "default",\n@@ -363,7 +371,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {\n workspaceRoot: "/tmp/project-1",\n repositoryIdentity: null,\n defaultModelSelection: {\n- provider: "codex",\n+ instanceId: ProviderInstanceId.make("codex"),\n model: "gpt-5-codex",\n },\n scripts: [\n@@ -385,7 +393,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {\n projectId: asProjectId("project-1"),\n title: "Thread 1",\n modelSelection: {\n- provider: "codex",\n+ instanceId: ProviderInstanceId.make("codex"),\n model: "gpt-5-codex",\n },\n interactionMode: "default",\ndiff --git a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts\nindex 07645571ba..59a396c926 100644\n--- a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts\n+++ b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts\n@@ -195,6 +195,7 @@ function mapSessionRow(\n threadId: row.threadId,\n status: row.status,\n providerName: row.providerName,\n+ ...(row.providerInstanceId !== null ? { providerInstanceId: row.providerInstanceId } : {}),\n runtimeMode: row.runtimeMode,\n activeTurnId: row.activeTurnId,\n lastError: row.lastError,\n@@ -350,6 +351,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {\n thread_id AS "threadId",\n status,\n provider_name AS "providerName",\n+ provider_instance_id AS "providerInstanceId",\n provider_session_id AS "providerSessionId",\n provider_thread_id AS "providerThreadId",\n runtime_mode AS "runtimeMode",\n@@ -608,6 +610,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {\n thread_id AS "threadId",\n status,\n provider_name AS "providerName",\n+ provider_instance_id AS "providerInstanceId",\n runtime_mode AS "runtimeMode",\n active_turn_id AS "activeTurnId",\n last_error AS "lastError",\n@@ -879,6 +882,9 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {\n threadId: row.threadId,\n status: row.status,\n providerName: row.providerName,\n+ ...(row.providerInstanceId !== null\n+ ? { providerInstanceId: row.providerInstanceId }\n+ : {}),\n runtimeMode: row.runtimeMode,\n activeTurnId: row.activeTurnId,\n lastError: row.lastError,\ndiff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts\nindex 80f571285d..c44f291504 100644\n--- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts\n+++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts\n@@ -2,7 +2,13 @@ import fs from "node:fs";\n import os from "node:os";\n import path from "node:path";\n \n-import type { ModelSelection, ProviderRuntimeEvent, ProviderSession } from "@t3tools/contracts";\n+import {\n+ ModelSelection,\n+ ProviderRuntimeEvent,\n+ ProviderSession,\n+ ProviderDriverKind,\n+ ProviderInstanceId,\n+} from "@t3tools/contracts";\n import { createModelSelection } from "@t3tools/shared/model";\n import {\n ApprovalRequestId,\n@@ -37,7 +43,11 @@ import { RepositoryIdentityResolverLive } from "../../project/Layers/RepositoryI\n import { OrchestrationEngineLive } from "./OrchestrationEngine.ts";\n import { OrchestrationProjectionPipelineLive } from "./ProjectionPipeline.ts";\n import { OrchestrationProjectionSnapshotQueryLive } from "./ProjectionSnapshotQuery.ts";\n-import { ProviderCommandReactorLive } from "./ProviderCommandReactor.ts";\n+import {\n+ providerErrorLabel,\n+ providerErrorLabelFromInstanceHint,\n+ ProviderCommandReactorLive,\n+} from "./ProviderCommandReactor.ts";\n import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";\n import { ProviderCommandReactor } from "../Services/ProviderCommandReactor.ts";\n import * as NodeServices from "@effect/platform-node/NodeServices";\n@@ -98,6 +108,30 @@ describe("ProviderCommandReactor", () => {\n createdBaseDirs.clear();\n });\n \n+ describe("provider error attribution", () => {\n+ it("uses the current provider instance slug when current instance lookup fails", () => {\n+ expect(\n+ providerErrorLabelFromInstanceHint({\n+ instanceId: "codex_personal",\n+ modelSelectionInstanceId: "codex",\n+ sessionProvider: "codex",\n+ }),\n+ ).toBe("codex_personal");\n+ });\n+\n+ it("uses the desired provider instance slug when desired instance lookup fails", () => {\n+ expect(\n+ providerErrorLabelFromInstanceHint({\n+ instanceId: "claude_openrouter",\n+ }),\n+ ).toBe("claude_openrouter");\n+ });\n+\n+ it("uses the unknown driver kind when the resolved driver is not registered locally", () => {\n+ expect(providerErrorLabel("third_party_driver")).toBe("third_party_driver");\n+ });\n+ });\n+\n async function createHarness(input?: {\n readonly baseDir?: string;\n readonly threadModelSelection?: ModelSelection;\n@@ -112,7 +146,7 @@ describe("ProviderCommandReactor", () => {\n let nextSessionIndex = 1;\n const runtimeSessions: Array<ProviderSession> = [];\n const modelSelection = input?.threadModelSelection ?? {\n- provider: "codex",\n+ instanceId: ProviderInstanceId.make("codex"),\n model: "gpt-5-codex",\n };\n const startSession = vi.fn((_: unknown, input: unknown) => {\n@@ -128,8 +162,24 @@ describe("ProviderCommandReactor", () => {\n typeof input.threadId === "string"\n ? ThreadId.make(input.threadId)\n : ThreadId.make(`thread-${sessionIndex}`);\n+ const inputModelSelection =\n+ typeof input === "object" && input !== null && "modelSelection" in input\n+ ? (input.modelSelection as ModelSelection | undefined)\n+ : undefined;\n+ const providerInstanceId =\n+ typeof input === "object" && input !== null && "providerInstanceId" in input\n+ ? (input.providerInstanceId as ProviderInstanceId | undefined)\n+ : inputModelSelection?.instanceId;\n+ const provider =\n+ typeof input === "object" &&\n+ input !== null &&\n+ "provider" in input &&\n+ typeof input.provider === "string"\n+ ? (input.provider as ProviderSession["provider"])\n+ : ProviderDriverKind.make(inputModelSelection?.instanceId ?? modelSelection.instanceId);\n const session: ProviderSession = {\n- provider: modelSelection.provider,\n+ provider,\n+ ...(providerInstanceId ? { providerInstanceId } : {}),\n status: "ready" as const,\n runtimeMode:\n typeof input === "object" &&\n@@ -144,7 +194,9 @@ describe("ProviderCommandReactor", () => {\n typeof input.cwd === "string"\n ? { cwd: input.cwd }\n : {}),\n- ...(modelSelection.model !== undefined ? { model: modelSelection.model } : {}),\n+ ...((inputModelSelection?.model ?? modelSelection.model)\n+ ? { model: inputModelSelection?.model ?? modelSelection.model }\n+ : {}),\n threadId,\n resumeCursor: resumeCursor ?? { opaque: `resume-${sessionIndex}` },\n createdAt: now,\n@@ -236,6 +288,25 @@ describe("ProviderCommandReactor", () => {\n Effect.succeed({\n sessionModelSwitch: input?.sessionModelSwitch ?? "in-session",\n }),\n+ getInstanceInfo: (instanceId) => {\n+ const raw = String(instanceId);\n+ const driverKind = ProviderDriverKind.make(\n+ raw.startsWith("claude") ? "claudeAgent" : raw.startsWith("codex") ? "codex" : raw,\n+ );\n+ return Effect.succeed({\n+ instanceId,\n+ driverKind,\n+ displayName: undefined,\n+ enabled: true,\n+ continuationIdentity: {\n+ driverKind,\n+ continuationKey:\n+ driverKind === ProviderDriverKind.make("codex")\n+ ? "codex:home:/shared-codex"\n+ : `${driverKind}:instance:${instanceId}`,\n+ },\n+ });\n+ },\n rollbackConversation: () => unsupported(),\n get streamEvents() {\n return Stream.fromPubSub(runtimeEventPubSub);\n@@ -320,6 +391,7 @@ describe("ProviderCommandReactor", () => {\n refreshStatus,\n generateBranchName,\n generateThreadTitle,\n+ runtimeSessions,\n stateDir,\n drain,\n };\n@@ -352,7 +424,7 @@ describe("ProviderCommandReactor", () => {\n expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({\n cwd: "/tmp/provider-project",\n modelSelection: {\n- provider: "codex",\n+ instanceId: ProviderInstanceId.make("codex"),\n model: "gpt-5-codex",\n },\n runtimeMode: "approval-required",\n@@ -574,7 +646,7 @@ describe("ProviderCommandReactor", () => {\n text: "hello fast mode",\n attachments: [],\n },\n- modelSelection: createModelSelection("codex", "gpt-5.3-codex", [\n+ modelSelection: createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.3-codex", [\n { id: "reasoningEffort", value: "high" },\n { id: "fastMode", value: true },\n ]),\n@@ -587,14 +659,14 @@ describe("ProviderCommandReactor", () => {\n await waitFor(() => harness.startSession.mock.calls.length === 1);\n await waitFor(() => harness.sendTurn.mock.calls.length === 1);\n expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({\n- modelSelection: createModelSelection("codex", "gpt-5.3-codex", [\n+ modelSelection: createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.3-codex", [\n { id: "reasoningEffort", value: "high" },\n { id: "fastMode", value: true },\n ]),\n });\n expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({\n threadId: ThreadId.make("thread-1"),\n- modelSelection: createModelSelection("codex", "gpt-5.3-codex", [\n+ modelSelection: createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.3-codex", [\n { id: "reasoningEffort", value: "high" },\n { id: "fastMode", value: true },\n ]),\n@@ -603,7 +675,10 @@ describe("ProviderCommandReactor", () => {\n \n it("forwards claude effort options through session start and turn send", async () => {\n const harness = await createHarness({\n- threadModelSelection: { provider: "claudeAgent", model: "claude-sonnet-4-6" },\n+ threadModelSelection: {\n+ instanceId: ProviderInstanceId.make("claudeAgent"),\n+ model: "claude-sonnet-4-6",\n+ },\n });\n const now = new Date().toISOString();\n \n@@ -618,9 +693,11 @@ describe("ProviderCommandReactor", () => {\n text: "hello with effort",\n attachments: [],\n },\n- modelSelection: createModelSelection("claudeAgent", "claude-sonnet-4-6", [\n- { id: "effort", value: "max" },\n- ]),\n+ modelSelection: createModelSelection(\n+ ProviderInstanceId.make("claudeAgent"),\n+ "claude-sonnet-4-6",\n+ [{ id: "effort", value: "max" }],\n+ ),\n interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,\n runtimeMode: "approval-required",\n createdAt: now,\n@@ -630,21 +707,28 @@ describe("ProviderCommandReactor", () => {\n await waitFor(() => harness.startSession.mock.calls.length === 1);\n await waitFor(() => harness.sendTurn.mock.calls.length === 1);\n expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({\n- modelSelection: createModelSelection("claudeAgent", "claude-sonnet-4-6", [\n- { id: "effort", value: "max" },\n- ]),\n+ modelSelection: createModelSelection(\n+ ProviderInstanceId.make("claudeAgent"),\n+ "claude-sonnet-4-6",\n+ [{ id: "effort", value: "max" }],\n+ ),\n });\n expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({\n threadId: ThreadId.make("thread-1"),\n- modelSelection: createModelSelection("claudeAgent", "claude-sonnet-4-6", [\n- { id: "effort", value: "max" },\n- ]),\n+ modelSelection: createModelSelection(\n+ ProviderInstanceId.make("claudeAgent"),\n+ "claude-sonnet-4-6",\n+ [{ id: "effort", value: "max" }],\n+ ),\n });\n });\n \n it("forwards claude fast mode options through session start and turn send", async () => {\n const harness = await createHarness({\n- threadModelSelection: { provider: "claudeAgent", model: "claude-opus-4-6" },\n+ threadModelSelection: {\n+ instanceId: ProviderInstanceId.make("claudeAgent"),\n+ model: "claude-opus-4-6",\n+ },\n });\n const now = new Date().toISOString();\n \n@@ -659,9 +743,11 @@ describe("ProviderCommandReactor", () => {\n text: "hello with fast mode",\n attachments: [],\n },\n- modelSelection: createModelSelection("claudeAgent", "claude-opus-4-6", [\n- { id: "fastMode", value: true },\n- ]),\n+ modelSelection: createModelSelection(\n+ ProviderInstanceId.make("claudeAgent"),\n+ "claude-opus-4-6",\n+ [{ id: "fastMode", value: true }],\n+ ),\n interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,\n runtimeMode: "approval-required",\n createdAt: now,\n@@ -671,15 +757,19 @@ describe("ProviderCommandReactor", () => {\n await waitFor(() => harness.startSession.mock.calls.length === 1);\n await waitFor(() => harness.sendTurn.mock.calls.length === 1);\n expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({\n- modelSelection: createModelSelection("claudeAgent", "claude-opus-4-6", [\n- { id: "fastMode", value: true },\n- ]),\n+ modelSelection: createModelSelection(\n+ ProviderInstanceId.make("claudeAgent"),\n+ "claude-opus-4-6",\n+ [{ id: "fastMode", value: true }],\n+ ),\n });\n expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({\n threadId: ThreadId.make("thread-1"),\n- modelSelection: createModelSelection("claudeAgent", "claude-opus-4-6", [\n- { id: "fastMode", value: true },\n- ]),\n+ modelSelection: createModelSelection(\n+ ProviderInstanceId.make("claudeAgent"),\n+ "claude-opus-4-6",\n+ [{ id: "fastMode", value: true }],\n+ ),\n });\n });\n \n@@ -766,15 +856,15 @@ describe("ProviderCommandReactor", () => {\n expect(harness.sendTurn.mock.calls[1]?.[0]).toMatchObject({\n threadId: ThreadId.make("thread-1"),\n modelSelection: {\n- provider: "codex",\n+ instanceId: ProviderInstanceId.make("codex"),\n model: "gpt-5-codex",\n },\n });\n });\n \n- it("rejects a first turn when requested provider conflicts with the thread model", async () => {\n+ it("starts a first turn on the requested provider instance even when it differs from the thread model", async () => {\n const harness = await createHarness({\n- threadModelSelection: { provider: "codex", model: "gpt-5-codex" },\n+ threadModelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5-codex" },\n });\n const now = new Date().toISOString();\n \n@@ -790,7 +880,7 @@ describe("ProviderCommandReactor", () => {\n attachments: [],\n },\n modelSelection: {\n- provider: "claudeAgent",\n+ instanceId: ProviderInstanceId.make("claudeAgent"),\n model: "claude-opus-4-6",\n },\n interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,\n@@ -799,29 +889,25 @@ describe("ProviderCommandReactor", () => {\n }),\n );\n \n- await waitFor(async () => {\n- const readModel = await Effect.runPromise(harness.engine.getReadModel());\n- const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));\n- return (\n- thread?.activities.some((activity) => activity.kind === "provider.turn.start.failed") ??\n- false\n- );\n- });\n+ await waitFor(() => harness.sendTurn.mock.calls.length === 1);\n \n- expect(harness.startSession).not.toHaveBeenCalled();\n- expect(harness.sendTurn).not.toHaveBeenCalled();\n+ expect(harness.startSession).toHaveBeenCalledTimes(1);\n+ expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({\n+ provider: ProviderDriverKind.make("claudeAgent"),\n+ providerInstanceId: ProviderInstanceId.make("claudeAgent"),\n+ modelSelection: {\n+ instanceId: ProviderInstanceId.make("claudeAgent"),\n+ model: "claude-opus-4-6",\n+ },\n+ });\n \n const readModel = await Effect.runPromise(harness.engine.getReadModel());\n const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));\n- expect(thread?.session).toBeNull();\n+ expect(thread?.session?.providerName).toBe("claudeAgent");\n+ expect(thread?.session?.providerInstanceId).toBe(ProviderInstanceId.make("claudeAgent"));\n expect(\n thread?.activities.find((activity) => activity.kind === "provider.turn.start.failed"),\n- ).toMatchObject({\n- summary: "Provider turn start failed",\n- payload: {\n- detail: expect.stringContaining("cannot switch to \'claudeAgent\'"),\n- },\n- });\n+ ).toBeUndefined();\n });\n \n it("reuses the same provider session when runtime mode is unchanged", async () => {\n@@ -870,9 +956,74 @@ describe("ProviderCommandReactor", () => {\n expect(harness.stopSession.mock.calls.length).toBe(0);\n });\n \n+ it("restarts an existing Codex thread on a compatible requested instance", async () => {\n+ const harness = await createHarness();\n+ const now = new Date().toISOString();\n+\n+ await Effect.runPromise(\n+ harness.engine.dispatch({\n+ type: "thread.turn.start",\n+ commandId: CommandId.make("cmd-turn-start-compatible-codex-1"),\n+ threadId: ThreadId.make("thread-1"),\n+ message: {\n+ messageId: asMessageId("user-message-compatible-codex-1"),\n+ role: "user",\n+ text: "first",\n+ attachments: [],\n+ },\n+ modelSelection: {\n+ instanceId: ProviderInstanceId.make("codex"),\n+ model: "gpt-5-codex",\n+ },\n+ interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,\n+ runtimeMode: "approval-required",\n+ createdAt: now,\n+ }),\n+ );\n+\n+ await waitFor(() => harness.sendTurn.mock.calls.length === 1);\n+\n+ await Effect.runPromise(\n+ harness.engine.dispatch({\n+ type: "thread.turn.start",\n+ commandId: CommandId.make("cmd-turn-start-compatible-codex-2"),\n+ threadId: ThreadId.make("thread-1"),\n+ message: {\n+ messageId: asMessageId("user-message-compatible-codex-2"),\n+ role: "user",\n+ text: "second",\n+ attachments: [],\n+ },\n+ modelSelection: {\n+ instanceId: ProviderInstanceId.make("codex_work"),\n+ model: "gpt-5-codex",\n+ },\n+ interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,\n+ runtimeMode: "approval-required",\n+ createdAt: new Date().toISOString(),\n+ }),\n+ );\n+\n+ await waitFor(() => harness.sendTurn.mock.calls.length === 2);\n+\n+ expect(harness.startSession).toHaveBeenCalledTimes(2);\n+ expect(harness.startSession.mock.calls[1]?.[1]).toMatchObject({\n+ provider: ProviderDriverKind.make("codex"),\n+ providerInstanceId: ProviderInstanceId.make("codex_work"),\n+ resumeCursor: { opaque: "resume-1" },\n+ });\n+\n+ const readModel = await Effect.runPromise(harness.engine.getReadModel());\n+ const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));\n+ expect(thread?.session?.providerInstanceId).toBe(ProviderInstanceId.make("codex_work"));\n+ });\n+\n it("restarts the provider session when the thread workspace changes", async () => {\n const harness = await createHarness({\n- threadModelSelection: { provider: "claudeAgent", model: "claude-sonnet-4-6" },\n+ threadModelSelection: {\n+ instanceId: ProviderInstanceId.make("claudeAgent"),\n+ model: "claude-sonnet-4-6",\n+ },\n });\n const now = new Date().toISOString();\n \n@@ -933,7 +1084,7 @@ describe("ProviderCommandReactor", () => {\n cwd: "/tmp/provider-project-worktree",\n resumeCursor: { opaque: "resume-1" },\n modelSelection: {\n- provider: "claudeAgent",\n+ instanceId: ProviderInstanceId.make("claudeAgent"),\n model: "claude-sonnet-4-6",\n },\n runtimeMode: "approval-required",\n@@ -942,7 +1093,10 @@ describe("ProviderCommandReactor", () => {\n \n it("restarts claude sessions when claude effort changes", async () => {\n const harness = await createHarness({\n- threadModelSelection: { provider: "claudeAgent", model: "claude-sonnet-4-6" },\n+ threadModelSelection: {\n+ instanceId: ProviderInstanceId.make("claudeAgent"),\n+ model: "claude-sonnet-4-6",\n+ },\n });\n const now = new Date().toISOString();\n \n@@ -957,9 +1111,11 @@ describe("ProviderCommandReactor", () => {\n text: "first claude turn",\n attachments: [],\n },\n- modelSelection: createModelSelection("claudeAgent", "claude-sonnet-4-6", [\n- { id: "effort", value: "medium" },\n- ]),\n+ modelSelection: createModelSelection(\n+ ProviderInstanceId.make("claudeAgent"),\n+ "claude-sonnet-4-6",\n+ [{ id: "effort", value: "medium" }],\n+ ),\n interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,\n runtimeMode: "approval-required",\n createdAt: now,\n@@ -980,9 +1136,11 @@ describe("ProviderCommandReactor", () => {\n text: "second claude turn",\n attachments: [],\n },\n- modelSelection: createModelSelection("claudeAgent", "claude-sonnet-4-6", [\n- { id: "effort", value: "max" },\n- ]),\n+ modelSelection: createModelSelection(\n+ ProviderInstanceId.make("claudeAgent"),\n+ "claude-sonnet-4-6",\n+ [{ id: "effort", value: "max" }],\n+ ),\n interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,\n runtimeMode: "approval-required",\n createdAt: now,\n@@ -993,9 +1151,11 @@ describe("ProviderCommandReactor", () => {\n await waitFor(() => harness.sendTurn.mock.calls.length === 2);\n expect(harness.startSession.mock.calls[1]?.[1]).toMatchObject({\n resumeCursor: { opaque: "resume-1" },\n- modelSelection: createModelSelection("claudeAgent", "claude-sonnet-4-6", [\n- { id: "effort", value: "max" },\n- ]),\n+ modelSelection: createModelSelection(\n+ ProviderInstanceId.make("claudeAgent"),\n+ "claude-sonnet-4-6",\n+ [{ id: "effort", value: "max" }],\n+ ),\n });\n });\n \n@@ -1086,7 +1246,10 @@ describe("ProviderCommandReactor", () => {\n \n it("does not inject derived model options when restarting claude on runtime mode changes", async () => {\n const harness = await createHarness({\n- threadModelSelection: { provider: "claudeAgent", model: "claude-opus-4-6" },\n+ threadModelSelection: {\n+ instanceId: ProviderInstanceId.make("claudeAgent"),\n+ model: "claude-opus-4-6",\n+ },\n });\n const now = new Date().toISOString();\n \n@@ -1122,7 +1285,7 @@ describe("ProviderCommandReactor", () => {\n \n expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({\n modelSelection: {\n- provider: "claudeAgent",\n+ instanceId: ProviderInstanceId.make("claudeAgent"),\n model: "claude-opus-4-6",\n },\n runtimeMode: "approval-required",\n@@ -1230,7 +1393,7 @@ describe("ProviderCommandReactor", () => {\n attachments: [],\n },\n modelSelection: {\n- provider: "claudeAgent",\n+ instanceId: ProviderInstanceId.make("claudeAgent"),\n model: "claude-opus-4-6",\n },\n interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,\n@@ -1266,6 +1429,72 @@ describe("ProviderCommandReactor", () => {\n });\n });\n \n+ it("rejects cross-driver provider changes after the existing thread session has stopped", async () => {\n+ const harness = await createHarness();\n+ const now = new Date().toISOString();\n+\n+ await Effect.runPromise(\n+ harness.engine.dispatch({\n+ type: "thread.session.set",\n+ commandId: CommandId.make("cmd-session-set-stopped-provider-switch"),\n+ threadId: ThreadId.make("thread-1"),\n+ session: {\n+ threadId: ThreadId.make("thread-1"),\n+ status: "stopped",\n+ providerName: "codex",\n+ providerInstanceId: ProviderInstanceId.make("codex"),\n+ runtimeMode: "approval-required",\n+ activeTurnId: null,\n+ lastError: null,\n+ updatedAt: now,\n+ },\n+ createdAt: now,\n+ }),\n+ );\n+\n+ await Effect.runPromise(\n+ harness.engine.dispatch({\n+ type: "thread.turn.start",\n+ commandId: CommandId.make("cmd-turn-start-stopped-provider-switch"),\n+ threadId: ThreadId.make("thread-1"),\n+ message: {\n+ messageId: asMessageId("user-message-stopped-provider-switch"),\n+ role: "user",\n+ text: "continue with claude",\n+ attachments: [],\n+ },\n+ modelSelection: {\n+ instanceId: ProviderInstanceId.make("claudeAgent"),\n+ model: "claude-opus-4-6",\n+ },\n+ interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,\n+ runtimeMode: "approval-required",\n+ createdAt: now,\n+ }),\n+ );\n+\n+ await waitFor(async () => {\n+ const readModel = await Effect.runPromise(harness.engine.getReadModel());\n+ const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));\n+ return (\n+ thread?.activities.some((activity) => activity.kind === "provider.turn.start.failed") ??\n+ false\n+ );\n+ });\n+\n+ expect(harness.startSession.mock.calls.length).toBe(0);\n+ expect(harness.sendTurn.mock.calls.length).toBe(0);\n+ const readModel = await Effect.runPromise(harness.engine.getReadModel());\n+ const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));\n+ expect(\n+ thread?.activities.find((activity) => activity.kind === "provider.turn.start.failed"),\n+ ).toMatchObject({\n+ payload: {\n+ detail: expect.stringContaining("cannot switch to \'claudeAgent\'"),\n+ },\n+ });\n+ });\n+\n it("reacts to thread.turn.interrupt-requested by calling provider interrupt", async () => {\n const harness = await createHarness();\n const now = new Date().toISOString();\n@@ -1349,7 +1578,7 @@ describe("ProviderCommandReactor", () => {\n expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({\n threadId: ThreadId.make("thread-1"),\n modelSelection: {\n- provider: "codex",\n+ instanceId: ProviderInstanceId.make("codex"),\n model: "gpt-5-codex",\n },\n runtimeMode: "approval-required",\n@@ -1359,6 +1588,77 @@ describe("ProviderCommandReactor", () => {\n });\n });\n \n+ it("rejects active runtime sessions that are missing provider instance ids", async () => {\n+ const harness = await createHarness();\n+ const now = new Date().toISOString();\n+\n+ await Effect.runPromise(\n+ harness.engine.dispatch({\n+ type: "thread.session.set",\n+ commandId: CommandId.make("cmd-session-set-missing-instance"),\n+ threadId: ThreadId.make("thread-1"),\n+ session: {\n+ threadId: ThreadId.make("thread-1"),\n+ status: "ready",\n+ providerName: "codex",\n+ runtimeMode: "approval-required",\n+ activeTurnId: null,\n+ lastError: null,\n+ updatedAt: now,\n+ },\n+ createdAt: now,\n+ }),\n+ );\n+ harness.runtimeSessions.push({\n+ provider: ProviderDriverKind.make("codex"),\n+ status: "ready",\n+ runtimeMode: "approval-required",\n+ threadId: ThreadId.make("thread-1"),\n+ cwd: "/tmp/provider-project",\n+ resumeCursor: { opaque: "resume-without-instance" },\n+ createdAt: now,\n+ updatedAt: now,\n+ });\n+\n+ await Effect.runPromise(\n+ harness.engine.dispatch({\n+ type: "thread.turn.start",\n+ commandId: CommandId.make("cmd-turn-start-missing-instance"),\n+ threadId: ThreadId.make("thread-1"),\n+ message: {\n+ messageId: asMessageId("user-message-missing-instance"),\n+ role: "user",\n+ text: "resume codex",\n+ attachments: [],\n+ },\n+ interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,\n+ runtimeMode: "approval-required",\n+ createdAt: now,\n+ }),\n+ );\n+\n+ await waitFor(async () => {\n+ const readModel = await Effect.runPromise(harness.engine.getReadModel());\n+ const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));\n+ return (\n+ thread?.activities.some((activity) => activity.kind === "provider.turn.start.failed") ??\n+ false\n+ );\n+ });\n+\n+ expect(harness.startSession.mock.calls.length).toBe(0);\n+ expect(harness.sendTurn.mock.calls.length).toBe(0);\n+ const readModel = await Effect.runPromise(harness.engine.getReadModel());\n+ const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));\n+ expect(\n+ thread?.activities.find((activity) => activity.kind === "provider.turn.start.failed"),\n+ ).toMatchObject({\n+ payload: {\n+ detail: expect.stringContaining("without a provider instance id"),\n+ },\n+ });\n+ });\n+\n it("reacts to thread.approval.respond by forwarding provider approval response", async () => {\n const harness = await createHarness();\n const now = new Date().toISOString();\n@@ -1451,7 +1751,7 @@ describe("ProviderCommandReactor", () => {\n harness.respondToRequest.mockImplementation(() =>\n Effect.fail(\n new ProviderAdapterRequestError({\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n method: "session/request_permission",\n detail: "Unknown pending permission request: approval-request-1",\n }),\n@@ -1546,7 +1846,7 @@ describe("ProviderCommandReactor", () => {\n harness.respondToUserInput.mockImplementation(() =>\n Effect.fail(\n new ProviderAdapterRequestError({\n- provider: "claudeAgent",\n+ provider: ProviderDriverKind.make("claudeAgent"),\n method: "item/tool/respondToUserInput",\n detail: "Unknown pending user-input request: user-input-request-1",\n }),\n@@ -1662,6 +1962,7 @@ describe("ProviderCommandReactor", () => {\n threadId: ThreadId.make("thread-1"),\n status: "ready",\n providerName: "codex",\n+ providerInstanceId: ProviderInstanceId.make("codex_work"),\n runtimeMode: "approval-required",\n activeTurnId: null,\n lastError: null,\n@@ -1686,6 +1987,7 @@ describe("ProviderCommandReactor", () => {\n expect(thread?.session).not.toBeNull();\n expect(thread?.session?.status).toBe("stopped");\n expect(thread?.session?.threadId).toBe("thread-1");\n+ expect(thread?.session?.providerInstanceId).toBe(ProviderInstanceId.make("codex_work"));\n expect(thread?.session?.activeTurnId).toBeNull();\n });\n });\ndiff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts\nindex f7ae38b2d2..9a9f3d71b0 100644\n--- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts\n+++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts\n@@ -4,7 +4,7 @@ import {\n EventId,\n type ModelSelection,\n type OrchestrationEvent,\n- ProviderKind,\n+ ProviderDriverKind,\n type OrchestrationSession,\n ThreadId,\n type ProviderSession,\n@@ -77,6 +77,21 @@ const HANDLED_TURN_START_KEY_TTL = Duration.minutes(30);\n const DEFAULT_RUNTIME_MODE: RuntimeMode = "full-access";\n const DEFAULT_THREAD_TITLE = "New thread";\n \n+export function providerErrorLabel(value: string | undefined): string {\n+ const normalized = value?.trim();\n+ return normalized && normalized.length > 0 ? normalized : "unknown";\n+}\n+\n+export function providerErrorLabelFromInstanceHint(input: {\n+ readonly instanceId?: string | undefined;\n+ readonly modelSelectionInstanceId?: string | undefined;\n+ readonly sessionProvider?: string | undefined;\n+}): string {\n+ return providerErrorLabel(\n+ input.instanceId ?? input.modelSelectionInstanceId ?? input.sessionProvider,\n+ );\n+}\n+\n function canReplaceThreadTitle(currentTitle: string, titleSeed?: string): boolean {\n const trimmedCurrentTitle = currentTitle.trim();\n if (trimmedCurrentTitle === DEFAULT_THREAD_TITLE) {\n@@ -271,42 +286,108 @@ const make = Effect.gen(function* () {\n }\n \n const desiredRuntimeMode = thread.runtimeMode;\n- const currentProvider: ProviderKind | undefined = Schema.is(ProviderKind)(\n- thread.session?.providerName,\n- )\n- ? thread.session.providerName\n- : undefined;\n const requestedModelSelection = options?.modelSelection;\n- const threadProvider: ProviderKind = currentProvider ?? thread.modelSelection.provider;\n+ const resolveActiveSession = (threadId: ThreadId) =>\n+ providerService\n+ .listSessions()\n+ .pipe(Effect.map((sessions) => sessions.find((session) => session.threadId === threadId)));\n+\n+ const activeSession = yield* resolveActiveSession(threadId);\n+ const activeThreadSession =\n+ thread.session !== null && thread.session.status !== "stopped" && activeSession\n+ ? thread.session\n+ : null;\n if (\n- requestedModelSelection !== undefined &&\n- requestedModelSelection.provider !== threadProvider\n+ activeThreadSession !== null &&\n+ activeSession !== undefined &&\n+ (activeThreadSession.providerInstanceId === undefined ||\n+ activeSession.providerInstanceId === undefined)\n ) {\n return yield* new ProviderAdapterRequestError({\n- provider: threadProvider,\n+ provider: providerErrorLabel(activeThreadSession.providerName ?? undefined),\n method: "thread.turn.start",\n- detail: `Thread \'${threadId}\' is bound to provider \'${threadProvider}\' and cannot switch to \'${requestedModelSelection.provider}\'.`,\n+ detail: `Thread \'${threadId}\' has an active provider session without a provider instance id.`,\n });\n }\n- const preferredProvider: ProviderKind = threadProvider;\n+ const currentInstanceId =\n+ activeThreadSession !== null &&\n+ activeSession !== undefined &&\n+ activeSession.providerInstanceId !== undefined\n+ ? activeSession.providerInstanceId\n+ : thread.modelSelection.instanceId;\n const desiredModelSelection = requestedModelSelection ?? thread.modelSelection;\n+ const desiredInstanceId = desiredModelSelection.instanceId;\n+ const currentInfo = yield* providerService.getInstanceInfo(currentInstanceId).pipe(\n+ Effect.mapError(\n+ () =>\n+ new ProviderAdapterRequestError({\n+ provider: providerErrorLabelFromInstanceHint({\n+ instanceId: String(currentInstanceId),\n+ modelSelectionInstanceId: String(thread.modelSelection.instanceId),\n+ sessionProvider: thread.session?.providerName ?? undefined,\n+ }),\n+ method: "thread.turn.start",\n+ detail: `Thread \'${threadId}\' references unknown provider instance \'${currentInstanceId}\'. The instance is not configured in this build.`,\n+ }),\n+ ),\n+ );\n+ const desiredInfo = yield* providerService.getInstanceInfo(desiredInstanceId).pipe(\n+ Effect.mapError(\n+ () =>\n+ new ProviderAdapterRequestError({\n+ provider: providerErrorLabelFromInstanceHint({\n+ instanceId: String(desiredModelSelection.instanceId),\n+ }),\n+ method: "thread.turn.start",\n+ detail: `Requested provider instance \'${desiredInstanceId}\' is not configured in this build.`,\n+ }),\n+ ),\n+ );\n+ const desiredDriverKind = desiredInfo.driverKind;\n+ if (!Schema.is(ProviderDriverKind)(desiredDriverKind)) {\n+ return yield* new ProviderAdapterRequestError({\n+ provider: providerErrorLabel(String(desiredDriverKind)),\n+ method: "thread.turn.start",\n+ detail: `Requested provider instance \'${desiredInstanceId}\' uses unknown provider driver \'${desiredDriverKind}\'. The driver is not installed in this build.`,\n+ });\n+ }\n+ const preferredProvider: ProviderDriverKind = desiredDriverKind;\n+ if (\n+ thread.session !== null &&\n+ requestedModelSelection !== undefined &&\n+ requestedModelSelection.instanceId !== currentInstanceId\n+ ) {\n+ if (currentInfo.driverKind !== desiredInfo.driverKind) {\n+ return yield* new ProviderAdapterRequestError({\n+ provider: preferredProvider,\n+ method: "thread.turn.start",\n+ detail: `Thread \'${threadId}\' is bound to driver \'${currentInfo.driverKind}\' and cannot switch to \'${desiredInfo.driverKind}\'.`,\n+ });\n+ }\n+ if (\n+ currentInfo.continuationIdentity.continuationKey !==\n+ desiredInfo.continuationIdentity.continuationKey\n+ ) {\n+ return yield* new ProviderAdapterRequestError({\n+ provider: preferredProvider,\n+ method: "thread.turn.start",\n+ detail: `Thread \'${threadId}\' cannot switch from instance \'${currentInstanceId}\' to \'${desiredInstanceId}\' because their provider resume state is incompatible.`,\n+ });\n+ }\n+ }\n const effectiveCwd = resolveThreadWorkspaceCwd({\n thread,\n projects: readModel.projects,\n });\n \n- const resolveActiveSession = (threadId: ThreadId) =>\n- providerService\n- .listSessions()\n- .pipe(Effect.map((sessions) => sessions.find((session) => session.threadId === threadId)));\n-\n const startProviderSession = (input?: {\n readonly resumeCursor?: unknown;\n- readonly provider?: ProviderKind;\n+ readonly provider?: ProviderDriverKind;\n }) =>\n providerService.startSession(threadId, {\n threadId,\n ...(preferredProvider ? { provider: preferredProvider } : {}),\n+ providerInstanceId: desiredInstanceId,\n ...(effectiveCwd ? { cwd: effectiveCwd } : {}),\n modelSelection: desiredModelSelection,\n ...(input?.resumeCursor !== undefined ? { resumeCursor: input.resumeCursor } : {}),\n@@ -314,44 +395,55 @@ const make = Effect.gen(function* () {\n });\n \n const bindSessionToThread = (session: ProviderSession) =>\n- setThreadSession({\n- threadId,\n- session: {\n+ Effect.gen(function* () {\n+ if (session.providerInstanceId === undefined) {\n+ return yield* new ProviderAdapterRequestError({\n+ provider: providerErrorLabel(session.provider),\n+ method: "thread.turn.start",\n+ detail: `Provider session \'${session.threadId}\' started without a provider instance id.`,\n+ });\n+ }\n+ yield* setThreadSession({\n threadId,\n- status: mapProviderSessionStatusToOrchestrationStatus(session.status),\n- providerName: session.provider,\n- runtimeMode: desiredRuntimeMode,\n- // Provider turn ids are not orchestration turn ids.\n- activeTurnId: null,\n- lastError: session.lastError ?? null,\n- updatedAt: session.updatedAt,\n- },\n- createdAt,\n+ session: {\n+ threadId,\n+ status: mapProviderSessionStatusToOrchestrationStatus(session.status),\n+ providerName: session.provider,\n+ providerInstanceId: session.providerInstanceId,\n+ runtimeMode: desiredRuntimeMode,\n+ // Provider turn ids are not orchestration turn ids.\n+ activeTurnId: null,\n+ lastError: session.lastError ?? null,\n+ updatedAt: session.updatedAt,\n+ },\n+ createdAt,\n+ });\n });\n \n- const activeSession = yield* resolveActiveSession(threadId);\n const existingSessionThreadId =\n thread.session && thread.session.status !== "stopped" && activeSession ? thread.id : null;\n if (existingSessionThreadId) {\n const runtimeModeChanged = thread.runtimeMode !== thread.session?.runtimeMode;\n const cwdChanged = effectiveCwd !== activeSession?.cwd;\n- const sessionModelSwitch =\n- currentProvider === undefined\n- ? "in-session"\n- : (yield* providerService.getCapabilities(currentProvider)).sessionModelSwitch;\n+ const sessionModelSwitch = (yield* providerService.getCapabilities(desiredInstanceId))\n+ .sessionModelSwitch;\n const modelChanged =\n requestedModelSelection !== undefined &&\n requestedModelSelection.model !== activeSession?.model;\n+ const instanceChanged =\n+ requestedModelSelection !== undefined &&\n+ activeSession?.providerInstanceId !== requestedModelSelection.instanceId;\n const shouldRestartForModelChange = modelChanged && sessionModelSwitch === "unsupported";\n const previousModelSelection = threadModelSelections.get(threadId);\n const shouldRestartForModelSelectionChange =\n- currentProvider === "claudeAgent" &&\n+ preferredProvider === "claudeAgent" &&\n requestedModelSelection !== undefined &&\n !Equal.equals(previousModelSelection, requestedModelSelection);\n \n if (\n !runtimeModeChanged &&\n !cwdChanged &&\n+ !instanceChanged &&\n !shouldRestartForModelChange &&\n !shouldRestartForModelSelectionChange\n ) {\n@@ -364,8 +456,10 @@ const make = Effect.gen(function* () {\n yield* Effect.logInfo("provider command reactor restarting provider session", {\n threadId,\n existingSessionThreadId,\n- currentProvider,\n- desiredProvider: desiredModelSelection.provider,\n+ currentProvider: activeSession?.provider,\n+ currentInstanceId,\n+ desiredInstanceId,\n+ desiredProvider: desiredModelSelection.instanceId,\n currentRuntimeMode: thread.session?.runtimeMode,\n desiredRuntimeMode: thread.runtimeMode,\n runtimeModeChanged,\n@@ -373,6 +467,7 @@ const make = Effect.gen(function* () {\n desiredCwd: effectiveCwd,\n cwdChanged,\n modelChanged,\n+ instanceChanged,\n shouldRestartForModelChange,\n shouldRestartForModelSelectionChange,\n hasResumeCursor: resumeCursor !== undefined,\n@@ -429,7 +524,14 @@ const make = Effect.gen(function* () {\n const sessionModelSwitch =\n activeSession === undefined\n ? "in-session"\n- : (yield* providerService.getCapabilities(activeSession.provider)).sessionModelSwitch;\n+ : activeSession.providerInstanceId === undefined\n+ ? yield* new ProviderAdapterRequestError({\n+ provider: providerErrorLabel(activeSession.provider),\n+ method: "thread.turn.start",\n+ detail: `Active provider session \'${activeSession.threadId}\' is missing a provider instance id.`,\n+ })\n+ : (yield* providerService.getCapabilities(activeSession.providerInstanceId))\n+ .sessionModelSwitch;\n const requestedModelSelection =\n input.modelSelection ?? threadModelSelections.get(input.threadId) ?? thread.modelSelection;\n const modelForTurn =\n@@ -800,6 +902,9 @@ const make = Effect.gen(function* () {\n threadId: thread.id,\n status: "stopped",\n providerName: thread.session?.providerName ?? null,\n+ ...(thread.session?.providerInstanceId !== undefined\n+ ? { providerInstanceId: thread.session.providerInstanceId }\n+ : {}),\n runtimeMode: thread.session?.runtimeMode ?? DEFAULT_RUNTIME_MODE,\n activeTurnId: null,\n lastError: thread.session?.lastError ?? null,\ndiff --git a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts\nindex 577c5050ea..487d1a3aac 100644\n--- a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts\n+++ b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts\n@@ -2,10 +2,12 @@ import fs from "node:fs";\n import os from "node:os";\n import path from "node:path";\n \n-import type {\n+import {\n OrchestrationReadModel,\n+ ProviderDriverKind,\n ProviderRuntimeEvent,\n ProviderSession,\n+ ProviderInstanceId,\n } from "@t3tools/contracts";\n import {\n ApprovalRequestId,\n@@ -98,6 +100,19 @@ function createProviderServiceHarness() {\n stopSession: () => unsupported(),\n listSessions: () => Effect.succeed([...runtimeSessions]),\n getCapabilities: () => Effect.succeed({ sessionModelSwitch: "in-session" }),\n+ getInstanceInfo: (instanceId) => {\n+ const driverKind = ProviderDriverKind.make(String(instanceId));\n+ return Effect.succeed({\n+ instanceId,\n+ driverKind,\n+ displayName: undefined,\n+ enabled: true,\n+ continuationIdentity: {\n+ driverKind,\n+ continuationKey: `${driverKind}:instance:${instanceId}`,\n+ },\n+ });\n+ },\n rollbackConversation: () => unsupported(),\n get streamEvents() {\n return Stream.fromPubSub(runtimeEventPubSub);\n@@ -232,7 +247,7 @@ describe("ProviderRuntimeIngestion", () => {\n title: "Provider Project",\n workspaceRoot,\n defaultModelSelection: {\n- provider: "codex",\n+ instanceId: ProviderInstanceId.make("codex"),\n model: "gpt-5-codex",\n },\n createdAt,\n@@ -246,7 +261,7 @@ describe("ProviderRuntimeIngestion", () => {\n projectId: asProjectId("project-1"),\n title: "Thread",\n modelSelection: {\n- provider: "codex",\n+ instanceId: ProviderInstanceId.make("codex"),\n model: "gpt-5-codex",\n },\n interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,\n@@ -274,7 +289,7 @@ describe("ProviderRuntimeIngestion", () => {\n }),\n );\n provider.setSession({\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n status: "ready",\n runtimeMode: "approval-required",\n threadId: ThreadId.make("thread-1"),\n@@ -297,7 +312,7 @@ describe("ProviderRuntimeIngestion", () => {\n harness.emit({\n type: "turn.started",\n eventId: asEventId("evt-turn-started"),\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n threadId: asThreadId("thread-1"),\n createdAt: now,\n turnId: asTurnId("turn-1"),\n@@ -311,7 +326,7 @@ describe("ProviderRuntimeIngestion", () => {\n harness.emit({\n type: "turn.completed",\n eventId: asEventId("evt-turn-completed"),\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n threadId: asThreadId("thread-1"),\n createdAt: new Date().toISOString(),\n turnId: asTurnId("turn-1"),\n@@ -339,7 +354,7 @@ describe("ProviderRuntimeIngestion", () => {\n harness.emit({\n type: "session.state.changed",\n eventId: asEventId("evt-session-state-waiting"),\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n threadId: asThreadId("thread-1"),\n createdAt: waitingAt,\n payload: {\n@@ -358,7 +373,7 @@ describe("ProviderRuntimeIngestion", () => {\n harness.emit({\n type: "session.state.changed",\n eventId: asEventId("evt-session-state-error"),\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n threadId: asThreadId("thread-1"),\n createdAt: new Date().toISOString(),\n payload: {\n@@ -380,7 +395,7 @@ describe("ProviderRuntimeIngestion", () => {\n harness.emit({\n type: "session.state.changed",\n eventId: asEventId("evt-session-state-stopped"),\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n threadId: asThreadId("thread-1"),\n createdAt: new Date().toISOString(),\n payload: {\n@@ -401,7 +416,7 @@ describe("ProviderRuntimeIngestion", () => {\n harness.emit({\n type: "session.state.changed",\n eventId: asEventId("evt-session-state-ready"),\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n threadId: asThreadId("thread-1"),\n createdAt: new Date().toISOString(),\n payload: {\n@@ -427,7 +442,7 @@ describe("ProviderRuntimeIngestion", () => {\n harness.emit({\n type: "turn.started",\n eventId: asEventId("evt-turn-started-midturn-lifecycle"),\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n createdAt: now,\n threadId: asThreadId("thread-1"),\n turnId: asTurnId("turn-midturn-lifecycle"),\n@@ -443,14 +458,14 @@ describe("ProviderRuntimeIngestion", () => {\n harness.emit({\n type: "thread.started",\n eventId: asEventId("evt-thread-started-midturn-lifecycle"),\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n createdAt: new Date().toISOString(),\n threadId: asThreadId("thread-1"),\n });\n harness.emit({\n type: "session.started",\n eventId: asEventId("evt-session-started-midturn-lifecycle"),\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n createdAt: new Date().toISOString(),\n threadId: asThreadId("thread-1"),\n });\n@@ -464,7 +479,7 @@ describe("ProviderRuntimeIngestion", () => {\n harness.emit({\n type: "turn.completed",\n eventId: asEventId("evt-turn-completed-midturn-lifecycle"),\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n createdAt: new Date().toISOString(),\n threadId: asThreadId("thread-1"),\n turnId: asTurnId("turn-midturn-lifecycle"),\n@@ -502,7 +517,7 @@ describe("ProviderRuntimeIngestion", () => {\n harness.emit({\n type: "turn.started",\n eventId: asEventId("evt-turn-started-claude-placeholder"),\n- provider: "claudeAgent",\n+ provider: ProviderDriverKind.make("claudeAgent"),\n createdAt: new Date().toISOString(),\n threadId: asThreadId("thread-1"),\n turnId: asTurnId("turn-claude-placeholder"),\n@@ -518,7 +533,7 @@ describe("ProviderRuntimeIngestion", () => {\n harness.emit({\n type: "turn.completed",\n eventId: asEventId("evt-turn-completed-claude-placeholder"),\n- provider: "claudeAgent",\n+ provider: ProviderDriverKind.make("claudeAgent"),\n createdAt: new Date().toISOString(),\n threadId: asThreadId("thread-1"),\n turnId: asTurnId("turn-claude-placeholder"),\n@@ -538,7 +553,7 @@ describe("ProviderRuntimeIngestion", () => {\n harness.emit({\n type: "turn.started",\n eventId: asEventId("evt-turn-started-primary"),\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n createdAt: now,\n threadId: asThreadId("thread-1"),\n turnId: asTurnId("turn-primary"),\n@@ -553,7 +568,7 @@ describe("ProviderRuntimeIngestion", () => {\n harness.emit({\n type: "turn.completed",\n eventId: asEventId("evt-turn-completed-aux"),\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n createdAt: new Date().toISOString(),\n threadId: asThreadId("thread-1"),\n turnId: asTurnId("turn-aux"),\n@@ -569,7 +584,7 @@ describe("ProviderRuntimeIngestion", () => {\n harness.emit({\n type: "turn.completed",\n eventId: asEventId("evt-turn-completed-primary"),\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n createdAt: new Date().toISOString(),\n threadId: asThreadId("thread-1"),\n turnId: asTurnId("turn-primary"),\n@@ -589,7 +604,7 @@ describe("ProviderRuntimeIngestion", () => {\n harness.emit({\n type: "turn.started",\n eventId: asEventId("evt-turn-started-guarded"),\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n createdAt: now,\n threadId: asThreadId("thread-1"),\n turnId: asTurnId("turn-guarded-main"),\n@@ -605,7 +620,7 @@ describe("ProviderRuntimeIngestion", () => {\n harness.emit({\n type: "turn.completed",\n eventId: asEventId("evt-turn-completed-guarded-other"),\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n createdAt: new Date().toISOString(),\n threadId: asThreadId("thread-1"),\n turnId: asTurnId("turn-guarded-other"),\n@@ -621,7 +636,7 @@ describe("ProviderRuntimeIngestion", () => {\n harness.emit({\n type: "turn.completed",\n eventId: asEventId("evt-turn-completed-guarded-main"),\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n createdAt: new Date().toISOString(),\n threadId: asThreadId("thread-1"),\n turnId: asTurnId("turn-guarded-main"),\n@@ -641,7 +656,7 @@ describe("ProviderRuntimeIngestion", () => {\n harness.emit({\n type: "content.delta",\n eventId: asEventId("evt-message-delta-1"),\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n createdAt: now,\n threadId: asThreadId("thread-1"),\n turnId: asTurnId("turn-2"),\n@@ -654,7 +669,7 @@ describe("ProviderRuntimeIngestion", () => {\n harness.emit({\n type: "content.delta",\n eventId: asEventId("evt-message-delta-2"),\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n createdAt: now,\n threadId: asThreadId("thread-1"),\n turnId: asTurnId("turn-2"),\n@@ -667,7 +682,7 @@ describe("ProviderRuntimeIngestion", () => {\n harness.emit({\n type: "item.completed",\n eventId: asEventId("evt-message-completed"),\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n createdAt: now,\n threadId: asThreadId("thread-1"),\n turnId: asTurnId("turn-2"),\n@@ -698,7 +713,7 @@ describe("ProviderRuntimeIngestion", () => {\n harness.emit({\n type: "item.completed",\n eventId: asEventId("evt-assistant-item-completed-no-delta"),\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n createdAt: now,\n threadId: asThreadId("thread-1"),\n turnId: asTurnId("turn-no-delta"),\n@@ -730,7 +745,7 @@ describe("ProviderRuntimeIngestion", () => {\n harness.emit({\n type: "item.completed",\n eventId: asEventId("evt-tool-completed-with-data"),\n- provider: "cursor",\n+ provider: ProviderDriverKind.make("cursor"),\n createdAt: now,\n threadId: asThreadId("thread-1"),\n turnId: asTurnId("turn-tool-completed"),\n@@ -786,7 +801,7 @@ describe("ProviderRuntimeIngestion", () => {\n harness.emit({\n type: "item.completed",\n eventId: asEventId("evt-command-completed"),\n- provider: "cursor",\n+ provider: ProviderDriverKind.make("cursor"),\n createdAt: now,\n threadId: asThreadId("thread-1"),\n turnId: asTurnId("turn-command-completed"),\n@@ -828,7 +843,7 @@ describe("ProviderRuntimeIngestion", () => {\n harness.emit({\n type: "item.completed",\n eventId: asEventId("evt-read-path-completed"),\n- provider: "cursor",\n+ provider: ProviderDriverKind.make("cursor"),\n createdAt: now,\n threadId: asThreadId("thread-1"),\n turnId: asTurnId("turn-read-path"),\n@@ -870,7 +885,7 @@ describe("ProviderRuntimeIngestion", () => {\n harness.emit({\n type: "turn.proposed.completed",\n eventId: asEventId("evt-plan-item-completed"),\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n createdAt: now,\n threadId: asThreadId("thread-1"),\n turnId: asTurnId("turn-plan-final"),\n@@ -909,7 +924,7 @@ describe("ProviderRuntimeIngestion", () => {\n projectId: asProjectId("project-1"),\n title: "Plan Source",\n modelSelection: {\n- provider: "codex",\n+ instanceId: ProviderInstanceId.make("codex"),\n model: "gpt-5-codex",\n },\n interactionMode: "plan",\n@@ -944,7 +959,7 @@ describe("ProviderRuntimeIngestion", () => {\n projectId: asProjectId("project-1"),\n title: "Plan Target",\n modelSelection: {\n- provider: "codex",\n+ instanceId: ProviderInstanceId.make("codex"),\n model: "gpt-5-codex",\n },\n interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,\n@@ -972,7 +987,7 @@ describe("ProviderRuntimeIngestion", () => {\n }),\n );\n harness.setProviderSession({\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n status: "ready",\n runtimeMode: "approval-required",\n threadId: targetThreadId,\n@@ -984,7 +999,7 @@ describe("ProviderRuntimeIngestion", () => {\n harness.emit({\n type: "turn.proposed.completed",\n eventId: asEventId("evt-plan-source-completed"),\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n createdAt,\n threadId: sourceThreadId,\n turnId: sourceTurnId,\n@@ -1054,7 +1069,7 @@ describe("ProviderRuntimeIngestion", () => {\n harness.emit({\n type: "turn.started",\n eventId: asEventId("evt-plan-target-started"),\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n createdAt: new Date().toISOString(),\n threadId: targetThreadId,\n turnId: targetTurnId,\n@@ -1096,7 +1111,7 @@ describe("ProviderRuntimeIngestion", () => {\n projectId: asProjectId("project-1"),\n title: "Plan Source",\n modelSelection: {\n- provider: "codex",\n+ instanceId: ProviderInstanceId.make("codex"),\n model: "gpt-5-codex",\n },\n interactionMode: "plan",\n@@ -1124,7 +1139,7 @@ describe("ProviderRuntimeIngestion", () => {\n }),\n );\n harness.setProviderSession({\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n status: "running",\n runtimeMode: "approval-required",\n threadId: targetThreadId,\n@@ -1136,7 +1151,7 @@ describe("ProviderRuntimeIngestion", () => {\n harness.emit({\n type: "turn.started",\n eventId: asEventId("evt-turn-started-already-running"),\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n createdAt,\n threadId: targetThreadId,\n turnId: activeTurnId,\n@@ -1153,7 +1168,7 @@ describe("ProviderRuntimeIngestion", () => {\n harness.emit({\n type: "turn.proposed.completed",\n eventId: asEventId("evt-plan-source-completed-guarded"),\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n createdAt,\n threadId: sourceThreadId,\n turnId: sourceTurnId,\n@@ -1206,7 +1221,7 @@ describe("ProviderRuntimeIngestion", () => {\n harness.emit({\n type: "turn.started",\n eventId: asEventId("evt-turn-started-stale-plan-implementation"),\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n createdAt: new Date().toISOString(),\n threadId: targetThreadId,\n turnId: staleTurnId,\n@@ -1249,7 +1264,7 @@ describe("ProviderRuntimeIngestion", () => {\n projectId: asProjectId("project-1"),\n title: "Plan Source",\n modelSelection: {\n- provider: "codex",\n+ instanceId: ProviderInstanceId.make("codex"),\n model: "gpt-5-codex",\n },\n interactionMode: "plan",\n@@ -1284,7 +1299,7 @@ describe("ProviderRuntimeIngestion", () => {\n projectId: asProjectId("project-1"),\n title: "Plan Target",\n modelSelection: {\n- provider: "codex",\n+ instanceId: ProviderInstanceId.make("codex"),\n model: "gpt-5-codex",\n },\n interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,\n@@ -1315,7 +1330,7 @@ describe("ProviderRuntimeIngestion", () => {\n harness.emit({\n type: "turn.proposed.completed",\n eventId: asEventId("evt-plan-source-completed-unrelated"),\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n createdAt,\n threadId: sourceThreadId,\n turnId: sourceTurnId,\n@@ -1366,7 +1381,7 @@ describe("ProviderRuntimeIngestion", () => {\n );\n \n harness.setProviderSession({\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n status: "running",\n runtimeMode: "approval-required",\n threadId: targetThreadId,\n@@ -1378,7 +1393,7 @@ describe("ProviderRuntimeIngestion", () => {\n harness.emit({\n type: "turn.started",\n eventId: asEventId("evt-turn-started-unrelated-plan-implementation"),\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n createdAt: new Date().toISOString(),\n threadId: targetThreadId,\n turnId: replayedTurnId,\n@@ -1405,7 +1420,7 @@ describe("ProviderRuntimeIngestion", () => {\n harness.emit({\n type: "turn.started",\n eventId: asEventId("evt-turn-started-plan-buffer"),\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n createdAt: now,\n threadId: asThreadId("thread-1"),\n turnId: asTurnId("turn-plan-buffer"),\n@@ -1420,7 +1435,7 @@ describe("ProviderRuntimeIngestion", () => {\n harness.emit({\n type: "turn.proposed.delta",\n eventId: asEventId("evt-plan-delta-1"),\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n createdAt: now,\n threadId: asThreadId("thread-1"),\n turnId: asTurnId("turn-plan-buffer"),\n@@ -1431,7 +1446,7 @@ describe("ProviderRuntimeIngestion", () => {\n harness.emit({\n type: "turn.proposed.delta",\n eventId: asEventId("evt-plan-delta-2"),\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n createdAt: now,\n threadId: asThreadId("thread-1"),\n turnId: asTurnId("turn-plan-buffer"),\n@@ -1442,7 +1457,7 @@ describe("ProviderRuntimeIngestion", () => {\n harness.emit({\n type: "turn.completed",\n eventId: asEventId("evt-turn-completed-plan-buffer"),\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n createdAt: now,\n threadId: asThreadId("thread-1"),\n turnId: asTurnId("turn-plan-buffer"),\n@@ -1471,7 +1486,7 @@ describe("ProviderRuntimeIngestion", () => {\n harness.emit({\n type: "turn.started",\n eventId: asEventId("evt-turn-started-buffered"),\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n createdAt: now,\n threadId: asThreadId("thread-1"),\n turnId: asTurnId("turn-buffered"),\n@@ -1485,7 +1500,7 @@ describe("ProviderRuntimeIngestion", () => {\n harness.emit({\n type: "content.delta",\n eventId: asEventId("evt-message-delta-buffered"),\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n createdAt: now,\n threadId: asThreadId("thread-1"),\n turnId: asTurnId("turn-buffered"),\n@@ -1508,7 +1523,7 @@ describe("ProviderRuntimeIngestion", () => {\n harness.emit({\n type: "item.completed",\n eventId: asEventId("evt-message-completed-buffered"),\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n createdAt: now,\n threadId: asThreadId("thread-1"),\n turnId: asTurnId("turn-buffered"),\n@@ -1539,7 +1554,7 @@ describe("ProviderRuntimeIngestion", () => {\n harness.emit({\n type: "turn.started",\n eventId: asEventId("evt-turn-started-buffered-request-flush"),\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n createdAt: now,\n threadId: asThreadId("thread-1"),\n turnId: asTurnId("turn-buffered-request-flush"),\n@@ -1554,7 +1569,7 @@ describe("ProviderRuntimeIngestion", () => {\n harness.emit({\n type: "content.delta",\n eventId: asEventId("evt-message-delta-buffered-request-flush"),\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n createdAt: now,\n threadId: asThreadId("thread-1"),\n turnId: asTurnId("turn-buffered-request-flush"),\n@@ -1567,7 +1582,7 @@ describe("ProviderRuntimeIngestion", () => {\n harness.emit({\n type: "request.opened",\n eventId: asEventId("evt-request-opened-buffered-request-flush"),\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n createdAt: now,\n threadId: asThreadId("thread-1"),\n turnId: asTurnId("turn-buffered-request-flush"),\n@@ -1599,7 +1614,7 @@ describe("ProviderRuntimeIngestion", () => {\n harness.emit({\n type: "turn.started",\n eventId: asEventId("evt-turn-started-buffered-user-input-flush"),\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n createdAt: now,\n threadId: asThreadId("thread-1"),\n turnId: asTurnId("turn-buffered-user-input-flush"),\n@@ -1614,7 +1629,7 @@ describe("ProviderRuntimeIngestion", () => {\n harness.emit({\n type: "content.delta",\n eventId: asEventId("evt-message-delta-buffered-user-input-flush"),\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n createdAt: now,\n threadId: asThreadId("thread-1"),\n turnId: asTurnId("turn-buffered-user-input-flush"),\n@@ -1627,7 +1642,7 @@ describe("ProviderRuntimeIngestion", () => {\n harness.emit({\n type: "user-input.requested",\n eventId: asEventId("evt-user-input-requested-buffered-user-input-flush"),\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n createdAt: now,\n threadId: asThreadId("thread-1"),\n turnId: asTurnId("turn-buffered-user-input-flush"),\n@@ -1667,7 +1682,7 @@ describe("ProviderRuntimeIngestion", () => {\n harness.emit({\n type: "turn.started",\n eventId: asEventId("evt-turn-started-buffered-whitespace-request"),\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n createdAt: startedAt,\n threadId: asThreadId("thread-1"),\n turnId: asTurnId("turn-buffered-whitespace-request"),\n@@ -1682,7 +1697,7 @@ describe("ProviderRuntimeIngestion", () => {\n harness.emit({\n type: "content.delta",\n eventId: asEventId("evt-message-delta-buffered-whitespace-request"),\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n createdAt: startedAt,\n threadId: asThreadId("thread-1"),\n turnId: asTurnId("turn-buffered-whitespace-request"),\n@@ -1695,7 +1710,7 @@ describe("ProviderRuntimeIngestion", () => {\n harness.emit({\n type: "request.opened",\n eventId: asEventId("evt-request-opened-buffered-whitespace-request"),\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n createdAt: pausedAt,\n threadId: asThreadId("thread-1"),\n turnId: asTurnId("turn-buffered-whitespace-request"),\n@@ -1729,7 +1744,7 @@ describe("ProviderRuntimeIngestion", () => {\n harness.emit({\n type: "turn.started",\n eventId: asEventId("evt-turn-started-buffered-request-append"),\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n createdAt: startedAt,\n threadId: asThreadId("thread-1"),\n turnId: asTurnId("turn-buffered-request-append"),\n@@ -1744,7 +1759,7 @@ describe("ProviderRuntimeIngestion", () => {\n harness.emit({\n type: "content.delta",\n eventId: asEventId("evt-message-delta-buffered-request-append-initial"),\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n createdAt: startedAt,\n threadId: asThreadId("thread-1"),\n turnId: asTurnId("turn-buffered-request-append"),\n@@ -1757,7 +1772,7 @@ describe("ProviderRuntimeIngestion", () => {\n harness.emit({\n type: "request.opened",\n eventId: asEventId("evt-request-opened-buffered-request-append"),\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n createdAt: pausedAt,\n threadId: asThreadId("thread-1"),\n turnId: asTurnId("turn-buffered-request-append"),\n@@ -1780,7 +1795,7 @@ describe("ProviderRuntimeIngestion", () => {\n harness.emit({\n type: "content.delta",\n eventId: asEventId("evt-message-delta-buffered-request-append-followup"),\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n createdAt: resumedAt,\n threadId: asThreadId("thread-1"),\n turnId: asTurnId("turn-buffered-request-append"),\n@@ -1793,7 +1808,7 @@ describe("ProviderRuntimeIngestion", () => {\n harness.emit({\n type: "item.completed",\n eventId: asEventId("evt-message-completed-buffered-request-append"),\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n createdAt: completedAt,\n threadId: asThreadId("thread-1"),\n turnId: asTurnId("turn-buffered-request-append"),\n@@ -1861,7 +1876,7 @@ describe("ProviderRuntimeIngestion", () => {\n harness.emit({\n type: "turn.started",\n eventId: asEventId("evt-turn-started-streaming-request-segment"),\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n createdAt: startedAt,\n threadId: asThreadId("thread-1"),\n turnId: asTurnId("turn-streaming-request-segment"),\n@@ -1876,7 +1891,7 @@ describe("ProviderRuntimeIngestion", () => {\n harness.emit({\n type: "content.delta",\n eventId: asEventId("evt-message-delta-streaming-request-segment-initial"),\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n createdAt: startedAt,\n threadId: asThreadId("thread-1"),\n turnId: asTurnId("turn-streaming-request-segment"),\n@@ -1889,7 +1904,7 @@ describe("ProviderRuntimeIngestion", () => {\n harness.emit({\n type: "request.opened",\n eventId: asEventId("evt-request-opened-streaming-request-segment"),\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n createdAt: pausedAt,\n threadId: asThreadId("thread-1"),\n turnId: asTurnId("turn-streaming-request-segment"),\n@@ -1912,7 +1927,7 @@ describe("ProviderRuntimeIngestion", () => {\n harness.emit({\n type: "content.delta",\n eventId: asEventId("evt-message-delta-streaming-request-segment-followup"),\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n createdAt: resumedAt,\n threadId: asThreadId("thread-1"),\n turnId: asTurnId("turn-streaming-request-segment"),\n@@ -1925,7 +1940,7 @@ describe("ProviderRuntimeIngestion", () => {\n harness.emit({\n type: "item.completed",\n eventId: asEventId("evt-message-completed-streaming-request-segment"),\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n createdAt: completedAt,\n threadId: asThreadId("thread-1"),\n turnId: asTurnId("turn-streaming-request-segment"),\n@@ -1983,7 +1998,7 @@ describe("ProviderRuntimeIngestion", () => {\n harness.emit({\n type: "turn.started",\n eventId: asEventId("evt-turn-started-streaming-mode"),\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n createdAt: now,\n threadId: asThreadId("thread-1"),\n turnId: asTurnId("turn-streaming-mode"),\n@@ -1998,7 +2013,7 @@ describe("ProviderRuntimeIngestion", () => {\n harness.emit({\n type: "content.delta",\n eventId: asEventId("evt-message-delta-streaming-mode"),\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n createdAt: now,\n threadId: asThreadId("thread-1"),\n turnId: asTurnId("turn-streaming-mode"),\n@@ -2025,7 +2040,7 @@ describe("ProviderRuntimeIngestion", () => {\n harness.emit({\n type: "item.completed",\n eventId: asEventId("evt-message-completed-streaming-mode"),\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n createdAt: now,\n threadId: asThreadId("thread-1"),\n turnId: asTurnId("turn-streaming-mode"),\n@@ -2058,7 +2073,7 @@ describe("ProviderRuntimeIngestion", () => {\n harness.emit({\n type: "turn.started",\n eventId: asEventId("evt-turn-started-buffer-spill"),\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n createdAt: now,\n threadId: asThreadId("thread-1"),\n turnId: asTurnId("turn-buffer-spill"),\n@@ -2073,7 +2088,7 @@ describe("ProviderRuntimeIngestion", () => {\n harness.emit({\n type: "content.delta",\n eventId: asEventId("evt-message-delta-buffer-spill"),\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n createdAt: now,\n threadId: asThreadId("thread-1"),\n turnId: asTurnId("turn-buffer-spill"),\n@@ -2086,7 +2101,7 @@ describe("ProviderRuntimeIngestion", () => {\n harness.emit({\n type: "item.completed",\n eventId: asEventId("evt-message-completed-buffer-spill"),\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n createdAt: now,\n threadId: asThreadId("thread-1"),\n turnId: asTurnId("turn-buffer-spill"),\n@@ -2118,7 +2133,7 @@ describe("ProviderRuntimeIngestion", () => {\n harness.emit({\n type: "turn.started",\n eventId: asEventId("evt-turn-started-for-complete-dedup"),\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n createdAt: now,\n threadId: asThreadId("thread-1"),\n turnId: asTurnId("turn-complete-dedup"),\n@@ -2134,7 +2149,7 @@ describe("ProviderRuntimeIngestion", () => {\n harness.emit({\n type: "content.delta",\n eventId: asEventId("evt-message-delta-for-complete-dedup"),\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n createdAt: now,\n threadId: asThreadId("thread-1"),\n turnId: asTurnId("turn-complete-dedup"),\n@@ -2147,7 +2162,7 @@ describe("ProviderRuntimeIngestion", () => {\n harness.emit({\n type: "item.completed",\n eventId: asEventId("evt-message-completed-for-complete-dedup"),\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n createdAt: now,\n threadId: asThreadId("thread-1"),\n turnId: asTurnId("turn-complete-dedup"),\n@@ -2160,7 +2175,7 @@ describe("ProviderRuntimeIngestion", () => {\n harness.emit({\n type: "turn.completed",\n eventId: asEventId("evt-turn-completed-for-complete-dedup"),\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n createdAt: now,\n threadId: asThreadId("thread-1"),\n turnId: asTurnId("turn-complete-dedup"),\n@@ -2204,7 +2219,7 @@ describe("ProviderRuntimeIngestion", () => {\n harness.emit({\n type: "request.opened",\n eventId: asEventId("evt-request-opened"),\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n createdAt: now,\n threadId: asThreadId("thread-1"),\n requestId: ApprovalRequestId.make("req-open"),\n@@ -2217,7 +2232,7 @@ describe("ProviderRuntimeIngestion", () => {\n harness.emit({\n type: "request.resolved",\n eventId: asEventId("evt-request-resolved"),\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n createdAt: now,\n threadId: asThreadId("thread-1"),\n requestId: ApprovalRequestId.make("req-open"),\n@@ -2270,7 +2285,7 @@ describe("ProviderRuntimeIngestion", () => {\n harness.emit({\n type: "runtime.error",\n eventId: asEventId("evt-runtime-error"),\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n createdAt: now,\n threadId: asThreadId("thread-1"),\n turnId: asTurnId("turn-3"),\n@@ -2297,7 +2312,7 @@ describe("ProviderRuntimeIngestion", () => {\n harness.emit({\n type: "runtime.error",\n eventId: asEventId("evt-runtime-error-activity"),\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n createdAt: now,\n threadId: asThreadId("thread-1"),\n turnId: asTurnId("turn-runtime-error-activity"),\n@@ -2328,7 +2343,7 @@ describe("ProviderRuntimeIngestion", () => {\n harness.emit({\n type: "turn.started",\n eventId: asEventId("evt-warning-turn-started"),\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n createdAt: now,\n threadId: asThreadId("thread-1"),\n turnId: asTurnId("turn-warning"),\n@@ -2338,7 +2353,7 @@ describe("ProviderRuntimeIngestion", () => {\n harness.emit({\n type: "runtime.warning",\n eventId: asEventId("evt-warning-runtime"),\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n createdAt: now,\n threadId: asThreadId("thread-1"),\n turnId: asTurnId("turn-warning"),\n@@ -2372,7 +2387,7 @@ describe("ProviderRuntimeIngestion", () => {\n harness.emit({\n type: "session.started",\n eventId: asEventId("evt-session-started"),\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n createdAt: now,\n threadId: asThreadId("thread-1"),\n message: "session started",\n@@ -2380,14 +2395,14 @@ describe("ProviderRuntimeIngestion", () => {\n harness.emit({\n type: "thread.started",\n eventId: asEventId("evt-thread-started"),\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n createdAt: now,\n threadId: asThreadId("thread-1"),\n });\n harness.emit({\n type: "item.started",\n eventId: asEventId("evt-tool-started"),\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n createdAt: now,\n threadId: asThreadId("thread-1"),\n turnId: asTurnId("turn-9"),\n@@ -2424,7 +2439,7 @@ describe("ProviderRuntimeIngestion", () => {\n harness.emit({\n type: "thread.metadata.updated",\n eventId: asEventId("evt-thread-metadata-updated"),\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n createdAt: now,\n threadId: asThreadId("thread-1"),\n payload: {\n@@ -2436,7 +2451,7 @@ describe("ProviderRuntimeIngestion", () => {\n harness.emit({\n type: "turn.plan.updated",\n eventId: asEventId("evt-turn-plan-updated"),\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n createdAt: now,\n threadId: asThreadId("thread-1"),\n turnId: asTurnId("turn-p1"),\n@@ -2452,7 +2467,7 @@ describe("ProviderRuntimeIngestion", () => {\n harness.emit({\n type: "item.updated",\n eventId: asEventId("evt-item-updated"),\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n createdAt: now,\n threadId: asThreadId("thread-1"),\n turnId: asTurnId("turn-p1"),\n@@ -2469,7 +2484,7 @@ describe("ProviderRuntimeIngestion", () => {\n harness.emit({\n type: "runtime.warning",\n eventId: asEventId("evt-runtime-warning"),\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n createdAt: now,\n threadId: asThreadId("thread-1"),\n turnId: asTurnId("turn-p1"),\n@@ -2482,7 +2497,7 @@ describe("ProviderRuntimeIngestion", () => {\n harness.emit({\n type: "turn.diff.updated",\n eventId: asEventId("evt-turn-diff-updated"),\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n createdAt: now,\n threadId: asThreadId("thread-1"),\n turnId: asTurnId("turn-p1"),\n@@ -2558,7 +2573,7 @@ describe("ProviderRuntimeIngestion", () => {\n harness.emit({\n type: "thread.token-usage.updated",\n eventId: asEventId("evt-thread-token-usage-updated"),\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n createdAt: now,\n threadId: asThreadId("thread-1"),\n payload: {\n@@ -2610,7 +2625,7 @@ describe("ProviderRuntimeIngestion", () => {\n harness.emit({\n type: "thread.token-usage.updated",\n eventId: asEventId("evt-thread-token-usage-updated-camel"),\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n createdAt: now,\n threadId: asThreadId("thread-1"),\n payload: {\n@@ -2663,7 +2678,7 @@ describe("ProviderRuntimeIngestion", () => {\n harness.emit({\n type: "thread.token-usage.updated",\n eventId: asEventId("evt-thread-token-usage-updated-claude-window"),\n- provider: "claudeAgent",\n+ provider: ProviderDriverKind.make("claudeAgent"),\n createdAt: now,\n threadId: asThreadId("thread-1"),\n payload: {\n@@ -2707,7 +2722,7 @@ describe("ProviderRuntimeIngestion", () => {\n harness.emit({\n type: "thread.state.changed",\n eventId: asEventId("evt-thread-compacted"),\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n createdAt: now,\n threadId: asThreadId("thread-1"),\n turnId: asTurnId("turn-1"),\n@@ -2737,7 +2752,7 @@ describe("ProviderRuntimeIngestion", () => {\n harness.emit({\n type: "task.started",\n eventId: asEventId("evt-task-started"),\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n createdAt: now,\n threadId: asThreadId("thread-1"),\n turnId: asTurnId("turn-task-1"),\n@@ -2750,7 +2765,7 @@ describe("ProviderRuntimeIngestion", () => {\n harness.emit({\n type: "task.progress",\n eventId: asEventId("evt-task-progress"),\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n createdAt: now,\n threadId: asThreadId("thread-1"),\n turnId: asTurnId("turn-task-1"),\n@@ -2764,7 +2779,7 @@ describe("ProviderRuntimeIngestion", () => {\n harness.emit({\n type: "task.completed",\n eventId: asEventId("evt-task-completed"),\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n createdAt: now,\n threadId: asThreadId("thread-1"),\n turnId: asTurnId("turn-task-1"),\n@@ -2777,7 +2792,7 @@ describe("ProviderRuntimeIngestion", () => {\n harness.emit({\n type: "turn.proposed.completed",\n eventId: asEventId("evt-task-proposed-plan-completed"),\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n createdAt: now,\n threadId: asThreadId("thread-1"),\n turnId: asTurnId("turn-task-1"),\n@@ -2840,7 +2855,7 @@ describe("ProviderRuntimeIngestion", () => {\n harness.emit({\n type: "user-input.requested",\n eventId: asEventId("evt-user-input-requested"),\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n createdAt: now,\n threadId: asThreadId("thread-1"),\n turnId: asTurnId("turn-user-input"),\n@@ -2865,7 +2880,7 @@ describe("ProviderRuntimeIngestion", () => {\n harness.emit({\n type: "user-input.resolved",\n eventId: asEventId("evt-user-input-resolved"),\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n createdAt: new Date().toISOString(),\n threadId: asThreadId("thread-1"),\n turnId: asTurnId("turn-user-input"),\n@@ -2913,7 +2928,7 @@ describe("ProviderRuntimeIngestion", () => {\n harness.emit({\n type: "content.delta",\n eventId: asEventId("evt-invalid-delta"),\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n createdAt: now,\n threadId: asThreadId("thread-1"),\n turnId: asTurnId("turn-invalid"),\n@@ -2927,7 +2942,7 @@ describe("ProviderRuntimeIngestion", () => {\n harness.emit({\n type: "runtime.error",\n eventId: asEventId("evt-runtime-error-after-failure"),\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n createdAt: new Date().toISOString(),\n threadId: asThreadId("thread-1"),\n turnId: asTurnId("turn-after-failure"),\ndiff --git a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts\nindex 7eeeed2d51..b7a4c195a5 100644\n--- a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts\n+++ b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts\n@@ -1211,6 +1211,9 @@ const make = Effect.gen(function* () {\n threadId: thread.id,\n status,\n providerName: event.provider,\n+ ...(event.providerInstanceId !== undefined\n+ ? { providerInstanceId: event.providerInstanceId }\n+ : {}),\n runtimeMode: thread.session?.runtimeMode ?? "full-access",\n activeTurnId: nextActiveTurnId,\n lastError,\n@@ -1456,6 +1459,9 @@ const make = Effect.gen(function* () {\n threadId: thread.id,\n status: "error",\n providerName: event.provider,\n+ ...(event.providerInstanceId !== undefined\n+ ? { providerInstanceId: event.providerInstanceId }\n+ : {}),\n runtimeMode: thread.session?.runtimeMode ?? "full-access",\n activeTurnId: eventTurnId ?? null,\n lastError: runtimeErrorMessage,\ndiff --git a/apps/server/src/orchestration/commandInvariants.test.ts b/apps/server/src/orchestration/commandInvariants.test.ts\nindex a678bcea16..1e33a355d0 100644\n--- a/apps/server/src/orchestration/commandInvariants.test.ts\n+++ b/apps/server/src/orchestration/commandInvariants.test.ts\n@@ -7,6 +7,7 @@ import {\n ThreadId,\n type OrchestrationCommand,\n type OrchestrationReadModel,\n+ ProviderInstanceId,\n } from "@t3tools/contracts";\n import { Effect } from "effect";\n \n@@ -29,7 +30,7 @@ const readModel: OrchestrationReadModel = {\n title: "Project A",\n workspaceRoot: "/tmp/project-a",\n defaultModelSelection: {\n- provider: "codex",\n+ instanceId: ProviderInstanceId.make("codex"),\n model: "gpt-5-codex",\n },\n scripts: [],\n@@ -42,7 +43,7 @@ const readModel: OrchestrationReadModel = {\n title: "Project B",\n workspaceRoot: "/tmp/project-b",\n defaultModelSelection: {\n- provider: "codex",\n+ instanceId: ProviderInstanceId.make("codex"),\n model: "gpt-5-codex",\n },\n scripts: [],\n@@ -57,7 +58,7 @@ const readModel: OrchestrationReadModel = {\n projectId: ProjectId.make("project-a"),\n title: "Thread A",\n modelSelection: {\n- provider: "codex",\n+ instanceId: ProviderInstanceId.make("codex"),\n model: "gpt-5-codex",\n },\n interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,\n@@ -80,7 +81,7 @@ const readModel: OrchestrationReadModel = {\n projectId: ProjectId.make("project-b"),\n title: "Thread B",\n modelSelection: {\n- provider: "codex",\n+ instanceId: ProviderInstanceId.make("codex"),\n model: "gpt-5-codex",\n },\n interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,\n@@ -157,7 +158,7 @@ describe("commandInvariants", () => {\n projectId: ProjectId.make("project-a"),\n title: "new",\n modelSelection: {\n- provider: "codex",\n+ instanceId: ProviderInstanceId.make("codex"),\n model: "gpt-5-codex",\n },\n interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,\n@@ -181,7 +182,7 @@ describe("commandInvariants", () => {\n projectId: ProjectId.make("project-a"),\n title: "dup",\n modelSelection: {\n- provider: "codex",\n+ instanceId: ProviderInstanceId.make("codex"),\n model: "gpt-5-codex",\n },\n interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,\ndiff --git a/apps/server/src/orchestration/decider.delete.test.ts b/apps/server/src/orchestration/decider.delete.test.ts\nindex 2b32371493..548fcc0b68 100644\n--- a/apps/server/src/orchestration/decider.delete.test.ts\n+++ b/apps/server/src/orchestration/decider.delete.test.ts\n@@ -7,6 +7,7 @@ import {\n type OrchestrationCommand,\n type OrchestrationEvent,\n type OrchestrationReadModel,\n+ ProviderInstanceId,\n } from "@t3tools/contracts";\n import { Effect } from "effect";\n import { describe, expect, it } from "vitest";\n@@ -63,7 +64,7 @@ async function seedReadModel(): Promise<OrchestrationReadModel> {\n projectId: asProjectId("project-delete"),\n title: "Thread Delete 1",\n modelSelection: {\n- provider: "codex",\n+ instanceId: ProviderInstanceId.make("codex"),\n model: "gpt-5-codex",\n },\n interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,\n@@ -93,7 +94,7 @@ async function seedReadModel(): Promise<OrchestrationReadModel> {\n projectId: asProjectId("project-delete"),\n title: "Thread Delete 2",\n modelSelection: {\n- provider: "codex",\n+ instanceId: ProviderInstanceId.make("codex"),\n model: "gpt-5-codex",\n },\n interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,\ndiff --git a/apps/server/src/orchestration/decider.projectScripts.test.ts b/apps/server/src/orchestration/decider.projectScripts.test.ts\nindex 1feabb0ed8..2356609919 100644\n--- a/apps/server/src/orchestration/decider.projectScripts.test.ts\n+++ b/apps/server/src/orchestration/decider.projectScripts.test.ts\n@@ -5,6 +5,7 @@ import {\n MessageId,\n ProjectId,\n ThreadId,\n+ ProviderInstanceId,\n } from "@t3tools/contracts";\n import { createModelSelection } from "@t3tools/shared/model";\n import { describe, expect, it } from "vitest";\n@@ -138,7 +139,7 @@ describe("decider project scripts", () => {\n projectId: asProjectId("project-1"),\n title: "Thread",\n modelSelection: {\n- provider: "codex",\n+ instanceId: ProviderInstanceId.make("codex"),\n model: "gpt-5-codex",\n },\n interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,\n@@ -163,7 +164,7 @@ describe("decider project scripts", () => {\n text: "hello",\n attachments: [],\n },\n- modelSelection: createModelSelection("codex", "gpt-5.3-codex", [\n+ modelSelection: createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.3-codex", [\n { id: "reasoningEffort", value: "high" },\n { id: "fastMode", value: true },\n ]),\n@@ -188,7 +189,7 @@ describe("decider project scripts", () => {\n expect(turnStartEvent.payload).toMatchObject({\n threadId: ThreadId.make("thread-1"),\n messageId: asMessageId("message-user-1"),\n- modelSelection: createModelSelection("codex", "gpt-5.3-codex", [\n+ modelSelection: createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.3-codex", [\n { id: "reasoningEffort", value: "high" },\n { id: "fastMode", value: true },\n ]),\n@@ -239,7 +240,7 @@ describe("decider project scripts", () => {\n projectId: asProjectId("project-1"),\n title: "Thread",\n modelSelection: {\n- provider: "codex",\n+ instanceId: ProviderInstanceId.make("codex"),\n model: "gpt-5-codex",\n },\n interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,\n@@ -321,7 +322,7 @@ describe("decider project scripts", () => {\n projectId: asProjectId("project-1"),\n title: "Thread",\n modelSelection: {\n- provider: "codex",\n+ instanceId: ProviderInstanceId.make("codex"),\n model: "gpt-5-codex",\n },\n interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,\ndiff --git a/apps/server/src/orchestration/projector.test.ts b/apps/server/src/orchestration/projector.test.ts\nindex a61153bb52..b50bc2da59 100644\n--- a/apps/server/src/orchestration/projector.test.ts\n+++ b/apps/server/src/orchestration/projector.test.ts\n@@ -2,6 +2,7 @@ import {\n CommandId,\n EventId,\n ProjectId,\n+ ProviderDriverKind,\n ThreadId,\n type OrchestrationEvent,\n } from "@t3tools/contracts";\n@@ -57,7 +58,7 @@ describe("orchestration projector", () => {\n projectId: "project-1",\n title: "demo",\n modelSelection: {\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n model: "gpt-5-codex",\n },\n runtimeMode: "full-access",\n@@ -77,7 +78,7 @@ describe("orchestration projector", () => {\n projectId: "project-1",\n title: "demo",\n modelSelection: {\n- provider: "codex",\n+ instanceId: "codex",\n model: "gpt-5-codex",\n },\n runtimeMode: "full-access",\n@@ -118,7 +119,7 @@ describe("orchestration projector", () => {\n projectId: "project-1",\n title: "demo",\n modelSelection: {\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n model: "gpt-5-codex",\n },\n branch: null,\n@@ -150,7 +151,7 @@ describe("orchestration projector", () => {\n projectId: "project-1",\n title: "demo",\n modelSelection: {\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n model: "gpt-5-codex",\n },\n runtimeMode: "full-access",\n@@ -253,7 +254,7 @@ describe("orchestration projector", () => {\n projectId: "project-1",\n title: "demo",\n modelSelection: {\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n model: "gpt-5.3-codex",\n },\n runtimeMode: "full-access",\n@@ -319,7 +320,7 @@ describe("orchestration projector", () => {\n projectId: "project-1",\n title: "demo",\n modelSelection: {\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n model: "gpt-5.3-codex",\n },\n runtimeMode: "full-access",\n@@ -376,7 +377,7 @@ describe("orchestration projector", () => {\n projectId: "project-1",\n title: "demo",\n modelSelection: {\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n model: "gpt-5.3-codex",\n },\n runtimeMode: "full-access",\n@@ -463,7 +464,7 @@ describe("orchestration projector", () => {\n projectId: "project-1",\n title: "demo",\n modelSelection: {\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n model: "gpt-5.3-codex",\n },\n runtimeMode: "full-access",\n@@ -678,7 +679,7 @@ describe("orchestration projector", () => {\n projectId: "project-1",\n title: "demo",\n modelSelection: {\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n model: "gpt-5.3-codex",\n },\n runtimeMode: "full-access",\n@@ -831,7 +832,7 @@ describe("orchestration projector", () => {\n projectId: "project-1",\n title: "capped",\n modelSelection: {\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n model: "gpt-5-codex",\n },\n runtimeMode: "full-access",\ndiff --git a/apps/server/src/persistence/Layers/ProjectionRepositories.test.ts b/apps/server/src/persistence/Layers/ProjectionRepositories.test.ts\nindex d42be69945..fc5f7a5c15 100644\n--- a/apps/server/src/persistence/Layers/ProjectionRepositories.test.ts\n+++ b/apps/server/src/persistence/Layers/ProjectionRepositories.test.ts\n@@ -1,4 +1,4 @@\n-import { ProjectId, ThreadId } from "@t3tools/contracts";\n+import { ProjectId, ThreadId, ProviderInstanceId } from "@t3tools/contracts";\n import { assert, it } from "@effect/vitest";\n import { Effect, Layer, Option } from "effect";\n import * as SqlClient from "effect/unstable/sql/SqlClient";\n@@ -28,7 +28,7 @@ projectionRepositoriesLayer("Projection repositories", (it) => {\n title: "Null options project",\n workspaceRoot: "/tmp/project-null-options",\n defaultModelSelection: {\n- provider: "codex",\n+ instanceId: ProviderInstanceId.make("codex"),\n model: "gpt-5.4",\n },\n scripts: [],\n@@ -52,7 +52,7 @@ projectionRepositoriesLayer("Projection repositories", (it) => {\n assert.strictEqual(\n row.defaultModelSelection,\n JSON.stringify({\n- provider: "codex",\n+ instanceId: ProviderInstanceId.make("codex"),\n model: "gpt-5.4",\n }),\n );\n@@ -61,7 +61,7 @@ projectionRepositoriesLayer("Projection repositories", (it) => {\n projectId: ProjectId.make("project-null-options"),\n });\n assert.deepStrictEqual(Option.getOrNull(persisted)?.defaultModelSelection, {\n- provider: "codex",\n+ instanceId: ProviderInstanceId.make("codex"),\n model: "gpt-5.4",\n });\n }),\n@@ -77,7 +77,7 @@ projectionRepositoriesLayer("Projection repositories", (it) => {\n projectId: ProjectId.make("project-null-options"),\n title: "Null options thread",\n modelSelection: {\n- provider: "claudeAgent",\n+ instanceId: ProviderInstanceId.make("claudeAgent"),\n model: "claude-opus-4-6",\n },\n runtimeMode: "full-access",\n@@ -110,7 +110,7 @@ projectionRepositoriesLayer("Projection repositories", (it) => {\n assert.strictEqual(\n row.modelSelection,\n JSON.stringify({\n- provider: "claudeAgent",\n+ instanceId: ProviderInstanceId.make("claudeAgent"),\n model: "claude-opus-4-6",\n }),\n );\n@@ -119,7 +119,7 @@ projectionRepositoriesLayer("Projection repositories", (it) => {\n threadId: ThreadId.make("thread-null-options"),\n });\n assert.deepStrictEqual(Option.getOrNull(persisted)?.modelSelection, {\n- provider: "claudeAgent",\n+ instanceId: ProviderInstanceId.make("claudeAgent"),\n model: "claude-opus-4-6",\n });\n }),\ndiff --git a/apps/server/src/persistence/Layers/ProjectionThreadSessions.ts b/apps/server/src/persistence/Layers/ProjectionThreadSessions.ts\nindex 2499eba196..80d241436f 100644\n--- a/apps/server/src/persistence/Layers/ProjectionThreadSessions.ts\n+++ b/apps/server/src/persistence/Layers/ProjectionThreadSessions.ts\n@@ -23,6 +23,7 @@ const makeProjectionThreadSessionRepository = Effect.gen(function* () {\n thread_id,\n status,\n provider_name,\n+ provider_instance_id,\n runtime_mode,\n active_turn_id,\n last_error,\n@@ -32,6 +33,7 @@ const makeProjectionThreadSessionRepository = Effect.gen(function* () {\n ${row.threadId},\n ${row.status},\n ${row.providerName},\n+ ${row.providerInstanceId},\n ${row.runtimeMode},\n ${row.activeTurnId},\n ${row.lastError},\n@@ -41,6 +43,7 @@ const makeProjectionThreadSessionRepository = Effect.gen(function* () {\n DO UPDATE SET\n status = excluded.status,\n provider_name = excluded.provider_name,\n+ provider_instance_id = excluded.provider_instance_id,\n runtime_mode = excluded.runtime_mode,\n active_turn_id = excluded.active_turn_id,\n last_error = excluded.last_error,\n@@ -57,6 +60,7 @@ const makeProjectionThreadSessionRepository = Effect.gen(function* () {\n thread_id AS "threadId",\n status,\n provider_name AS "providerName",\n+ provider_instance_id AS "providerInstanceId",\n runtime_mode AS "runtimeMode",\n active_turn_id AS "activeTurnId",\n last_error AS "lastError",\ndiff --git a/apps/server/src/persistence/Layers/ProviderSessionRuntime.ts b/apps/server/src/persistence/Layers/ProviderSessionRuntime.ts\nindex da3e8bce90..778e0c6d2e 100644\n--- a/apps/server/src/persistence/Layers/ProviderSessionRuntime.ts\n+++ b/apps/server/src/persistence/Layers/ProviderSessionRuntime.ts\n@@ -46,6 +46,7 @@ const makeProviderSessionRuntimeRepository = Effect.gen(function* () {\n INSERT INTO provider_session_runtime (\n thread_id,\n provider_name,\n+ provider_instance_id,\n adapter_key,\n runtime_mode,\n status,\n@@ -56,6 +57,7 @@ const makeProviderSessionRuntimeRepository = Effect.gen(function* () {\n VALUES (\n ${runtime.threadId},\n ${runtime.providerName},\n+ ${runtime.providerInstanceId},\n ${runtime.adapterKey},\n ${runtime.runtimeMode},\n ${runtime.status},\n@@ -66,6 +68,7 @@ const makeProviderSessionRuntimeRepository = Effect.gen(function* () {\n ON CONFLICT (thread_id)\n DO UPDATE SET\n provider_name = excluded.provider_name,\n+ provider_instance_id = excluded.provider_instance_id,\n adapter_key = excluded.adapter_key,\n runtime_mode = excluded.runtime_mode,\n status = excluded.status,\n@@ -83,6 +86,7 @@ const makeProviderSessionRuntimeRepository = Effect.gen(function* () {\n SELECT\n thread_id AS "threadId",\n provider_name AS "providerName",\n+ provider_instance_id AS "providerInstanceId",\n adapter_key AS "adapterKey",\n runtime_mode AS "runtimeMode",\n status,\n@@ -102,6 +106,7 @@ const makeProviderSessionRuntimeRepository = Effect.gen(function* () {\n SELECT\n thread_id AS "threadId",\n provider_name AS "providerName",\n+ provider_instance_id AS "providerInstanceId",\n adapter_key AS "adapterKey",\n runtime_mode AS "runtimeMode",\n status,\ndiff --git a/apps/server/src/persistence/Migrations.ts b/apps/server/src/persistence/Migrations.ts\nindex c8d4647fb7..025e9e4831 100644\n--- a/apps/server/src/persistence/Migrations.ts\n+++ b/apps/server/src/persistence/Migrations.ts\n@@ -39,6 +39,8 @@ import Migration0023 from "./Migrations/023_ProjectionThreadShellSummary.ts";\n import Migration0024 from "./Migrations/024_BackfillProjectionThreadShellSummary.ts";\n import Migration0025 from "./Migrations/025_CleanupInvalidProjectionPendingApprovals.ts";\n import Migration0026 from "./Migrations/026_CanonicalizeModelSelectionOptions.ts";\n+import Migration0027 from "./Migrations/027_ProviderSessionRuntimeInstanceId.ts";\n+import Migration0028 from "./Migrations/028_ProjectionThreadSessionInstanceId.ts";\n \n /**\n * Migration loader with all migrations defined inline.\n@@ -77,6 +79,8 @@ export const migrationEntries = [\n [24, "BackfillProjectionThreadShellSummary", Migration0024],\n [25, "CleanupInvalidProjectionPendingApprovals", Migration0025],\n [26, "CanonicalizeModelSelectionOptions", Migration0026],\n+ [27, "ProviderSessionRuntimeInstanceId", Migration0027],\n+ [28, "ProjectionThreadSessionInstanceId", Migration0028],\n ] as const;\n \n export const makeMigrationLoader = (throughId?: number) =>\ndiff --git a/apps/server/src/persistence/Migrations/027_028_ProviderInstanceIdColumns.test.ts b/apps/server/src/persistence/Migrations/027_028_ProviderInstanceIdColumns.test.ts\nnew file mode 100644\nindex 0000000000..3233f5043a\n--- /dev/null\n+++ b/apps/server/src/persistence/Migrations/027_028_ProviderInstanceIdColumns.test.ts\n@@ -0,0 +1,74 @@\n+import { assert, it } from "@effect/vitest";\n+import { Effect, Layer } from "effect";\n+import * as SqlClient from "effect/unstable/sql/SqlClient";\n+\n+import { runMigrations } from "../Migrations.ts";\n+import * as NodeSqliteClient from "../NodeSqliteClient.ts";\n+\n+const layer = it.layer(Layer.mergeAll(NodeSqliteClient.layerMemory()));\n+\n+layer("027_028_ProviderInstanceIdColumns", (it) => {\n+ it.effect("continues when provider_session_runtime was partially migrated", () =>\n+ Effect.gen(function* () {\n+ const sql = yield* SqlClient.SqlClient;\n+\n+ yield* runMigrations({ toMigrationInclusive: 26 });\n+ yield* sql`\n+ ALTER TABLE provider_session_runtime\n+ ADD COLUMN provider_instance_id TEXT\n+ `;\n+\n+ yield* runMigrations({ toMigrationInclusive: 28 });\n+\n+ const migrations = yield* sql<{\n+ readonly migration_id: number;\n+ readonly name: string;\n+ }>`\n+ SELECT migration_id, name\n+ FROM effect_sql_migrations\n+ WHERE migration_id IN (27, 28)\n+ ORDER BY migration_id\n+ `;\n+ assert.deepStrictEqual(migrations, [\n+ {\n+ migration_id: 27,\n+ name: "ProviderSessionRuntimeInstanceId",\n+ },\n+ {\n+ migration_id: 28,\n+ name: "ProjectionThreadSessionInstanceId",\n+ },\n+ ]);\n+\n+ const providerSessionColumns = yield* sql<{ readonly name: string }>`\n+ PRAGMA table_info(provider_session_runtime)\n+ `;\n+ assert.ok(providerSessionColumns.some((column) => column.name === "provider_instance_id"));\n+\n+ const projectionThreadSessionColumns = yield* sql<{ readonly name: string }>`\n+ PRAGMA table_info(projection_thread_sessions)\n+ `;\n+ assert.ok(\n+ projectionThreadSessionColumns.some((column) => column.name === "provider_instance_id"),\n+ );\n+\n+ const providerSessionIndexes = yield* sql<{ readonly name: string }>`\n+ PRAGMA index_list(provider_session_runtime)\n+ `;\n+ assert.ok(\n+ providerSessionIndexes.some(\n+ (index) => index.name === "idx_provider_session_runtime_instance",\n+ ),\n+ );\n+\n+ const projectionThreadSessionIndexes = yield* sql<{ readonly name: string }>`\n+ PRAGMA index_list(projection_thread_sessions)\n+ `;\n+ assert.ok(\n+ projectionThreadSessionIndexes.some(\n+ (index) => index.name === "idx_projection_thread_sessions_instance",\n+ ),\n+ );\n+ }),\n+ );\n+});\ndiff --git a/apps/server/src/persistence/Migrations/027_ProviderSessionRuntimeInstanceId.ts b/apps/server/src/persistence/Migrations/027_ProviderSessionRuntimeInstanceId.ts\nnew file mode 100644\nindex 0000000000..7ae0e55b13\n--- /dev/null\n+++ b/apps/server/src/persistence/Migrations/027_ProviderSessionRuntimeInstanceId.ts\n@@ -0,0 +1,38 @@\n+/**\n+ * Adds the nullable `provider_instance_id` routing column to\n+ * `provider_session_runtime`.\n+ *\n+ * Slice D of the provider-array refactor splits "driver kind" from\n+ * "configured instance". Existing rows have only the driver name in\n+ * `provider_name`; new rows additionally carry the user-defined instance\n+ * routing key. The column remains nullable so legacy rows can still decode;\n+ * the persistence boundary is responsible for materializing a concrete\n+ * instance id before any hot routing path sees the binding.\n+ *\n+ * The column is nullable on purpose — backfilling it during the migration\n+ * would require knowing which configured instance "owned" each historical\n+ * session, and that mapping is ambiguous when the user later configures\n+ * multiple instances of the same driver. Keeping that compatibility at the\n+ * persistence boundary keeps the fallback out of active routing code.\n+ */\n+import * as SqlClient from "effect/unstable/sql/SqlClient";\n+import * as Effect from "effect/Effect";\n+\n+export default Effect.gen(function* () {\n+ const sql = yield* SqlClient.SqlClient;\n+\n+ const columns = yield* sql<{ readonly name: string }>`\n+ PRAGMA table_info(provider_session_runtime)\n+ `;\n+ if (!columns.some((column) => column.name === "provider_instance_id")) {\n+ yield* sql`\n+ ALTER TABLE provider_session_runtime\n+ ADD COLUMN provider_instance_id TEXT\n+ `;\n+ }\n+\n+ yield* sql`\n+ CREATE INDEX IF NOT EXISTS idx_provider_session_runtime_instance\n+ ON provider_session_runtime(provider_instance_id)\n+ `;\n+});\ndiff --git a/apps/server/src/persistence/Migrations/028_ProjectionThreadSessionInstanceId.ts b/apps/server/src/persistence/Migrations/028_ProjectionThreadSessionInstanceId.ts\nnew file mode 100644\nindex 0000000000..bc4ba98044\n--- /dev/null\n+++ b/apps/server/src/persistence/Migrations/028_ProjectionThreadSessionInstanceId.ts\n@@ -0,0 +1,21 @@\n+import * as SqlClient from "effect/unstable/sql/SqlClient";\n+import * as Effect from "effect/Effect";\n+\n+export default Effect.gen(function* () {\n+ const sql = yield* SqlClient.SqlClient;\n+\n+ const columns = yield* sql<{ readonly name: string }>`\n+ PRAGMA table_info(projection_thread_sessions)\n+ `;\n+ if (!columns.some((column) => column.name === "provider_instance_id")) {\n+ yield* sql`\n+ ALTER TABLE projection_thread_sessions\n+ ADD COLUMN provider_instance_id TEXT\n+ `;\n+ }\n+\n+ yield* sql`\n+ CREATE INDEX IF NOT EXISTS idx_projection_thread_sessions_instance\n+ ON projection_thread_sessions(provider_instance_id)\n+ `;\n+});\ndiff --git a/apps/server/src/persistence/Services/ProjectionThreadSessions.ts b/apps/server/src/persistence/Services/ProjectionThreadSessions.ts\nindex fcd13f068d..5d2c3c87d1 100644\n--- a/apps/server/src/persistence/Services/ProjectionThreadSessions.ts\n+++ b/apps/server/src/persistence/Services/ProjectionThreadSessions.ts\n@@ -10,6 +10,7 @@ import {\n RuntimeMode,\n IsoDateTime,\n OrchestrationSessionStatus,\n+ ProviderInstanceId,\n ThreadId,\n TurnId,\n } from "@t3tools/contracts";\n@@ -22,6 +23,7 @@ export const ProjectionThreadSession = Schema.Struct({\n threadId: ThreadId,\n status: OrchestrationSessionStatus,\n providerName: Schema.NullOr(Schema.String),\n+ providerInstanceId: Schema.NullOr(ProviderInstanceId),\n runtimeMode: RuntimeMode,\n activeTurnId: Schema.NullOr(TurnId),\n lastError: Schema.NullOr(Schema.String),\ndiff --git a/apps/server/src/persistence/Services/ProviderSessionRuntime.ts b/apps/server/src/persistence/Services/ProviderSessionRuntime.ts\nindex bf8e658e8a..6ba15b32d9 100644\n--- a/apps/server/src/persistence/Services/ProviderSessionRuntime.ts\n+++ b/apps/server/src/persistence/Services/ProviderSessionRuntime.ts\n@@ -7,6 +7,7 @@\n */\n import {\n IsoDateTime,\n+ ProviderInstanceId,\n ProviderSessionRuntimeStatus,\n RuntimeMode,\n ThreadId,\n@@ -19,6 +20,14 @@ import type { ProviderSessionRuntimeRepositoryError } from "../Errors.ts";\n export const ProviderSessionRuntime = Schema.Struct({\n threadId: ThreadId,\n providerName: Schema.String,\n+ /**\n+ * User-defined routing key for the configured provider instance that\n+ * owns this session. Nullable only at the storage/migration boundary:\n+ * rows persisted before the driver/instance split carry only\n+ * `providerName`. Repository consumers must materialize a concrete\n+ * instance id before routing.\n+ */\n+ providerInstanceId: Schema.NullOr(ProviderInstanceId),\n adapterKey: Schema.String,\n runtimeMode: RuntimeMode,\n status: ProviderSessionRuntimeStatus,\ndiff --git a/apps/server/src/provider/Drivers/ClaudeDriver.ts b/apps/server/src/provider/Drivers/ClaudeDriver.ts\nnew file mode 100644\nindex 0000000000..feddd3b86b\n--- /dev/null\n+++ b/apps/server/src/provider/Drivers/ClaudeDriver.ts\n@@ -0,0 +1,157 @@\n+/**\n+ * ClaudeDriver — `ProviderDriver` for the Claude Agent SDK runtime.\n+ *\n+ * Mirrors `CodexDriver`: a plain value whose `create()` returns one\n+ * `ProviderInstance` bundling `snapshot` / `adapter` / `textGeneration`\n+ * closures captured over the per-instance `ClaudeSettings`.\n+ *\n+ * Unlike Codex, the Claude snapshot probe may invoke a secondary probe\n+ * (`probeClaudeCapabilities`) to read Anthropic account + slash-command\n+ * metadata. That probe is per-instance and keyed by binary + resolved HOME so\n+ * two concurrent Claude instances don\'t cross-contaminate account metadata.\n+ *\n+ * @module provider/Drivers/ClaudeDriver\n+ */\n+import { ClaudeSettings, ProviderDriverKind, type ServerProvider } from "@t3tools/contracts";\n+import { Cache, Duration, Effect, FileSystem, Path, Schema, Stream } from "effect";\n+import { ChildProcessSpawner } from "effect/unstable/process";\n+\n+import { makeClaudeTextGeneration } from "../../git/Layers/ClaudeTextGeneration.ts";\n+import { ServerConfig } from "../../config.ts";\n+import { ProviderDriverError } from "../Errors.ts";\n+import { makeClaudeAdapter } from "../Layers/ClaudeAdapter.ts";\n+import {\n+ checkClaudeProviderStatus,\n+ makePendingClaudeProvider,\n+ probeClaudeCapabilities,\n+} from "../Layers/ClaudeProvider.ts";\n+import { ProviderEventLoggers } from "../Layers/ProviderEventLoggers.ts";\n+import { makeManagedServerProvider } from "../makeManagedServerProvider.ts";\n+import {\n+ defaultProviderContinuationIdentity,\n+ type ProviderDriver,\n+ type ProviderInstance,\n+} from "../ProviderDriver.ts";\n+import type { ServerProviderDraft } from "../providerSnapshot.ts";\n+import { mergeProviderInstanceEnvironment } from "../ProviderInstanceEnvironment.ts";\n+import { makeClaudeCapabilitiesCacheKey, makeClaudeContinuationGroupKey } from "./ClaudeHome.ts";\n+\n+const DRIVER_KIND = ProviderDriverKind.make("claudeAgent");\n+const SNAPSHOT_REFRESH_INTERVAL = Duration.minutes(5);\n+const CAPABILITIES_PROBE_TTL = Duration.minutes(5);\n+\n+export type ClaudeDriverEnv =\n+ | ChildProcessSpawner.ChildProcessSpawner\n+ | FileSystem.FileSystem\n+ | Path.Path\n+ | ProviderEventLoggers\n+ | ServerConfig;\n+\n+const withInstanceIdentity =\n+ (input: {\n+ readonly instanceId: ProviderInstance["instanceId"];\n+ readonly displayName: string | undefined;\n+ readonly accentColor: string | undefined;\n+ readonly continuationGroupKey: string;\n+ }) =>\n+ (snapshot: ServerProviderDraft): ServerProvider => ({\n+ ...snapshot,\n+ instanceId: input.instanceId,\n+ driver: DRIVER_KIND,\n+ ...(input.displayName ? { displayName: input.displayName } : {}),\n+ ...(input.accentColor ? { accentColor: input.accentColor } : {}),\n+ continuation: { groupKey: input.continuationGroupKey },\n+ });\n+\n+export const ClaudeDriver: ProviderDriver<ClaudeSettings, ClaudeDriverEnv> = {\n+ driverKind: DRIVER_KIND,\n+ metadata: {\n+ displayName: "Claude",\n+ supportsMultipleInstances: true,\n+ },\n+ configSchema: ClaudeSettings,\n+ defaultConfig: (): ClaudeSettings => Schema.decodeSync(ClaudeSettings)({}),\n+ create: ({ instanceId, displayName, accentColor, environment, enabled, config }) =>\n+ Effect.gen(function* () {\n+ const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;\n+ const path = yield* Path.Path;\n+ const eventLoggers = yield* ProviderEventLoggers;\n+ const processEnv = mergeProviderInstanceEnvironment(environment);\n+ const fallbackContinuationIdentity = defaultProviderContinuationIdentity({\n+ driverKind: DRIVER_KIND,\n+ instanceId,\n+ });\n+ const effectiveConfig = { ...config, enabled } satisfies ClaudeSettings;\n+ const continuationGroupKey = yield* makeClaudeContinuationGroupKey(effectiveConfig);\n+ const stampIdentity = withInstanceIdentity({\n+ instanceId,\n+ displayName,\n+ accentColor,\n+ continuationGroupKey,\n+ });\n+\n+ const adapterOptions = {\n+ instanceId,\n+ environment: processEnv,\n+ ...(eventLoggers.native ? { nativeEventLogger: eventLoggers.native } : {}),\n+ };\n+ const adapter = yield* makeClaudeAdapter(effectiveConfig, adapterOptions);\n+ const textGeneration = yield* makeClaudeTextGeneration(effectiveConfig, processEnv);\n+\n+ // Per-instance capabilities cache: keyed on binary + resolved HOME so\n+ // account-specific probes never share auth metadata across instances.\n+ const capabilitiesProbeCache = yield* Cache.make({\n+ capacity: 1,\n+ timeToLive: CAPABILITIES_PROBE_TTL,\n+ lookup: () =>\n+ probeClaudeCapabilities(effectiveConfig, processEnv).pipe(\n+ Effect.provideService(Path.Path, path),\n+ ),\n+ });\n+ const capabilitiesCacheKey = yield* makeClaudeCapabilitiesCacheKey(effectiveConfig);\n+\n+ const checkProvider = checkClaudeProviderStatus(\n+ effectiveConfig,\n+ () => Cache.get(capabilitiesProbeCache, capabilitiesCacheKey),\n+ processEnv,\n+ ).pipe(\n+ Effect.map(stampIdentity),\n+ Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),\n+ Effect.provideService(Path.Path, path),\n+ );\n+\n+ const snapshot = yield* makeManagedServerProvider<ClaudeSettings>({\n+ getSettings: Effect.succeed(effectiveConfig),\n+ streamSettings: Stream.never,\n+ haveSettingsChanged: () => false,\n+ initialSnapshot: (settings) => stampIdentity(makePendingClaudeProvider(settings)),\n+ checkProvider,\n+ refreshInterval: SNAPSHOT_REFRESH_INTERVAL,\n+ }).pipe(\n+ Effect.mapError(\n+ (cause) =>\n+ new ProviderDriverError({\n+ driver: DRIVER_KIND,\n+ instanceId,\n+ detail: `Failed to build Claude snapshot: ${cause.message ?? String(cause)}`,\n+ cause,\n+ }),\n+ ),\n+ );\n+\n+ return {\n+ instanceId,\n+ driverKind: DRIVER_KIND,\n+ continuationIdentity: {\n+ ...fallbackContinuationIdentity,\n+ continuationKey: continuationGroupKey,\n+ },\n+ displayName,\n+ accentColor,\n+ enabled,\n+ snapshot,\n+ adapter,\n+ textGeneration,\n+ } satisfies ProviderInstance;\n+ }),\n+};\ndiff --git a/apps/server/src/provider/Drivers/ClaudeHome.test.ts b/apps/server/src/provider/Drivers/ClaudeHome.test.ts\nnew file mode 100644\nindex 0000000000..84c9c331cc\n--- /dev/null\n+++ b/apps/server/src/provider/Drivers/ClaudeHome.test.ts\n@@ -0,0 +1,52 @@\n+import * as NodeOS from "node:os";\n+\n+import * as NodeServices from "@effect/platform-node/NodeServices";\n+import { describe, expect, it } from "@effect/vitest";\n+import { Effect, Path } from "effect";\n+\n+import {\n+ makeClaudeCapabilitiesCacheKey,\n+ makeClaudeContinuationGroupKey,\n+ makeClaudeEnvironment,\n+ resolveClaudeHomePath,\n+} from "./ClaudeHome.ts";\n+\n+it.layer(NodeServices.layer)("ClaudeHome", (it) => {\n+ describe("Claude home resolution", () => {\n+ it.effect("uses the process home when no Claude home override is configured", () =>\n+ Effect.gen(function* () {\n+ const path = yield* Path.Path;\n+ const resolved = path.resolve(NodeOS.homedir());\n+\n+ expect(yield* resolveClaudeHomePath({ homePath: "" })).toBe(resolved);\n+ expect(yield* makeClaudeEnvironment({ homePath: "" })).toBe(process.env);\n+ }),\n+ );\n+\n+ it.effect("resolves configured Claude HOME and stamps continuation/cache keys with it", () =>\n+ Effect.gen(function* () {\n+ const path = yield* Path.Path;\n+ const homePath = "~/.claude-work";\n+ const resolved = path.resolve(NodeOS.homedir(), ".claude-work");\n+\n+ expect(yield* resolveClaudeHomePath({ homePath })).toBe(resolved);\n+ expect((yield* makeClaudeEnvironment({ homePath })).HOME).toBe(resolved);\n+ expect(yield* makeClaudeContinuationGroupKey({ homePath })).toBe(`claude:home:${resolved}`);\n+ expect(yield* makeClaudeCapabilitiesCacheKey({ binaryPath: "claude", homePath })).toBe(\n+ `claude\\0${resolved}`,\n+ );\n+ }),\n+ );\n+\n+ it.effect("keeps continuation compatible across instances with the same Claude HOME", () =>\n+ Effect.gen(function* () {\n+ const path = yield* Path.Path;\n+ const resolved = path.resolve(NodeOS.homedir());\n+\n+ expect(yield* makeClaudeContinuationGroupKey({ homePath: "" })).toBe(\n+ `claude:home:${resolved}`,\n+ );\n+ }),\n+ );\n+ });\n+});\ndiff --git a/apps/server/src/provider/Drivers/ClaudeHome.ts b/apps/server/src/provider/Drivers/ClaudeHome.ts\nnew file mode 100644\nindex 0000000000..c959096677\n--- /dev/null\n+++ b/apps/server/src/provider/Drivers/ClaudeHome.ts\n@@ -0,0 +1,43 @@\n+import * as NodeOS from "node:os";\n+\n+import type { ClaudeSettings } from "@t3tools/contracts";\n+import { Effect, Path } from "effect";\n+\n+import { expandHomePath } from "../../pathExpansion.ts";\n+\n+export const resolveClaudeHomePath = Effect.fn("resolveClaudeHomePath")(function* (\n+ config: Pick<ClaudeSettings, "homePath">,\n+): Effect.fn.Return<string, never, Path.Path> {\n+ const path = yield* Path.Path;\n+ const homePath = config.homePath.trim();\n+ return path.resolve(homePath.length > 0 ? expandHomePath(homePath) : NodeOS.homedir());\n+});\n+\n+export const makeClaudeEnvironment = Effect.fn("makeClaudeEnvironment")(function* (\n+ config: Pick<ClaudeSettings, "homePath">,\n+ baseEnv: NodeJS.ProcessEnv = process.env,\n+): Effect.fn.Return<NodeJS.ProcessEnv, never, Path.Path> {\n+ const homePath = config.homePath.trim();\n+ if (homePath.length === 0) return baseEnv;\n+ const resolvedHomePath = yield* resolveClaudeHomePath(config);\n+ return {\n+ ...baseEnv,\n+ HOME: resolvedHomePath,\n+ };\n+});\n+\n+export const makeClaudeContinuationGroupKey = Effect.fn("makeClaudeContinuationGroupKey")(\n+ function* (config: Pick<ClaudeSettings, "homePath">): Effect.fn.Return<string, never, Path.Path> {\n+ const resolvedHomePath = yield* resolveClaudeHomePath(config);\n+ return `claude:home:${resolvedHomePath}`;\n+ },\n+);\n+\n+export const makeClaudeCapabilitiesCacheKey = Effect.fn("makeClaudeCapabilitiesCacheKey")(\n+ function* (\n+ config: Pick<ClaudeSettings, "binaryPath" | "homePath">,\n+ ): Effect.fn.Return<string, never, Path.Path> {\n+ const resolvedHomePath = yield* resolveClaudeHomePath(config);\n+ return `${config.binaryPath}\\0${resolvedHomePath}`;\n+ },\n+);\ndiff --git a/apps/server/src/provider/Drivers/CodexDriver.ts b/apps/server/src/provider/Drivers/CodexDriver.ts\nnew file mode 100644\nindex 0000000000..13598ab5f6\n--- /dev/null\n+++ b/apps/server/src/provider/Drivers/CodexDriver.ts\n@@ -0,0 +1,171 @@\n+/**\n+ * CodexDriver — first concrete `ProviderDriver` in the new per-instance model.\n+ *\n+ * A driver is a plain value (not a Context.Service) whose `create()` returns\n+ * one `ProviderInstance` bundling:\n+ * - `snapshot` — the live `ServerProviderShape` for this instance;\n+ * - `adapter` — the Codex session/turn/approval runtime;\n+ * - `textGeneration` — commit/PR/branch/title generation via `codex exec`.\n+ *\n+ * Each call to `create()` captures the `codexConfig` argument in closures\n+ * owned by the returned instance. Two instances created with different\n+ * `homePath`s (e.g. `codex_personal` + `codex_work`) therefore run with\n+ * fully independent Codex app-server processes and `CODEX_HOME`\n+ * environments — no shared mutable state.\n+ *\n+ * Resource lifecycle: `create()` runs in a scope handed in by the registry.\n+ * Closing that scope releases the adapter\'s child processes, the managed\n+ * snapshot\'s refresh fibre, and the text-generation binaries\' transient\n+ * scratch files. The registry uses this to tear down an instance when its\n+ * `providerInstances` entry disappears or its config changes.\n+ *\n+ * @module provider/Drivers/CodexDriver\n+ */\n+import { CodexSettings, ProviderDriverKind, type ServerProvider } from "@t3tools/contracts";\n+import { Duration, Effect, FileSystem, Path, Schema, Stream } from "effect";\n+import { ChildProcessSpawner } from "effect/unstable/process";\n+\n+import { makeCodexTextGeneration } from "../../git/Layers/CodexTextGeneration.ts";\n+import { ServerConfig } from "../../config.ts";\n+import { ProviderDriverError } from "../Errors.ts";\n+import { makeCodexAdapter } from "../Layers/CodexAdapter.ts";\n+import { checkCodexProviderStatus, makePendingCodexProvider } from "../Layers/CodexProvider.ts";\n+import { ProviderEventLoggers } from "../Layers/ProviderEventLoggers.ts";\n+import { makeManagedServerProvider } from "../makeManagedServerProvider.ts";\n+import type { ProviderDriver, ProviderInstance } from "../ProviderDriver.ts";\n+import type { ServerProviderDraft } from "../providerSnapshot.ts";\n+import { mergeProviderInstanceEnvironment } from "../ProviderInstanceEnvironment.ts";\n+import {\n+ codexContinuationIdentity,\n+ materializeCodexShadowHome,\n+ resolveCodexHomeLayout,\n+} from "./CodexHomeLayout.ts";\n+\n+const DRIVER_KIND = ProviderDriverKind.make("codex");\n+const SNAPSHOT_REFRESH_INTERVAL = Duration.minutes(5);\n+\n+/**\n+ * Services the driver needs to materialize an instance. Surfaced as the\n+ * driver\'s `R` so the registry layer aggregates these across every\n+ * registered driver and the runtime satisfies them once.\n+ */\n+export type CodexDriverEnv =\n+ | ChildProcessSpawner.ChildProcessSpawner\n+ | FileSystem.FileSystem\n+ | Path.Path\n+ | ProviderEventLoggers\n+ | ServerConfig;\n+\n+/**\n+ * Stamp instance identity onto a `ServerProvider` snapshot produced by the\n+ * driver-kind-only codex helpers. Once `buildServerProvider` in\n+ * `providerSnapshot.ts` is widened to accept `instanceId`/`driver`, this\n+ * wrapper disappears.\n+ */\n+const withInstanceIdentity =\n+ (input: {\n+ readonly instanceId: ProviderInstance["instanceId"];\n+ readonly displayName: string | undefined;\n+ readonly accentColor: string | undefined;\n+ readonly continuationGroupKey: string;\n+ }) =>\n+ (snapshot: ServerProviderDraft): ServerProvider => ({\n+ ...snapshot,\n+ instanceId: input.instanceId,\n+ driver: DRIVER_KIND,\n+ ...(input.displayName ? { displayName: input.displayName } : {}),\n+ ...(input.accentColor ? { accentColor: input.accentColor } : {}),\n+ continuation: { groupKey: input.continuationGroupKey },\n+ });\n+\n+export const CodexDriver: ProviderDriver<CodexSettings, CodexDriverEnv> = {\n+ driverKind: DRIVER_KIND,\n+ metadata: {\n+ displayName: "Codex",\n+ supportsMultipleInstances: true,\n+ },\n+ configSchema: CodexSettings,\n+ defaultConfig: (): CodexSettings => Schema.decodeSync(CodexSettings)({}),\n+ create: ({ instanceId, displayName, accentColor, environment, enabled, config }) =>\n+ Effect.gen(function* () {\n+ const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;\n+ const eventLoggers = yield* ProviderEventLoggers;\n+ const processEnv = mergeProviderInstanceEnvironment(environment);\n+ const homeLayout = yield* resolveCodexHomeLayout(config);\n+ const continuationIdentity = codexContinuationIdentity(homeLayout);\n+ const stampIdentity = withInstanceIdentity({\n+ instanceId,\n+ displayName,\n+ accentColor,\n+ continuationGroupKey: continuationIdentity.continuationKey,\n+ });\n+ yield* materializeCodexShadowHome(homeLayout).pipe(\n+ Effect.mapError(\n+ (cause) =>\n+ new ProviderDriverError({\n+ driver: DRIVER_KIND,\n+ instanceId,\n+ detail: cause.message,\n+ cause,\n+ }),\n+ ),\n+ );\n+ const effectiveConfig = {\n+ ...config,\n+ enabled,\n+ homePath: homeLayout.effectiveHomePath ?? "",\n+ } satisfies CodexSettings;\n+\n+ // `makeCodexAdapter` and `makeCodexTextGeneration` have `never` error\n+ // channels at construction time — their failure modes are all on the\n+ // per-operation closures they return. No `mapError` wrapper is needed\n+ // here; the registry only has to worry about snapshot-build and\n+ // spawner-availability failures surfaced from `checkCodexProviderStatus`\n+ // below.\n+ const adapter = yield* makeCodexAdapter(effectiveConfig, {\n+ instanceId,\n+ environment: processEnv,\n+ ...(eventLoggers.native ? { nativeEventLogger: eventLoggers.native } : {}),\n+ });\n+ const textGeneration = yield* makeCodexTextGeneration(effectiveConfig, processEnv);\n+\n+ // Build a managed snapshot whose settings never change — mutations come\n+ // in as instance rebuilds from the registry rather than in-place\n+ // updates. Pre-provide `ChildProcessSpawner` so the check fits\n+ // `makeManagedServerProvider.checkProvider`\'s `R = never`.\n+ const checkProvider = checkCodexProviderStatus(effectiveConfig, undefined, processEnv).pipe(\n+ Effect.map(stampIdentity),\n+ Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),\n+ );\n+ const snapshot = yield* makeManagedServerProvider<CodexSettings>({\n+ getSettings: Effect.succeed(effectiveConfig),\n+ streamSettings: Stream.never,\n+ haveSettingsChanged: () => false,\n+ initialSnapshot: (settings) => stampIdentity(makePendingCodexProvider(settings)),\n+ checkProvider,\n+ refreshInterval: SNAPSHOT_REFRESH_INTERVAL,\n+ }).pipe(\n+ Effect.mapError(\n+ (cause) =>\n+ new ProviderDriverError({\n+ driver: DRIVER_KIND,\n+ instanceId,\n+ detail: `Failed to build Codex snapshot: ${cause.message ?? String(cause)}`,\n+ cause,\n+ }),\n+ ),\n+ );\n+\n+ return {\n+ instanceId,\n+ driverKind: DRIVER_KIND,\n+ continuationIdentity,\n+ displayName,\n+ accentColor,\n+ enabled,\n+ snapshot,\n+ adapter,\n+ textGeneration,\n+ } satisfies ProviderInstance;\n+ }),\n+};\ndiff --git a/apps/server/src/provider/Drivers/CodexHomeLayout.test.ts b/apps/server/src/provider/Drivers/CodexHomeLayout.test.ts\nnew file mode 100644\nindex 0000000000..b84a43c403\n--- /dev/null\n+++ b/apps/server/src/provider/Drivers/CodexHomeLayout.test.ts\n@@ -0,0 +1,209 @@\n+import * as NodeServices from "@effect/platform-node/NodeServices";\n+import { describe, expect, it } from "@effect/vitest";\n+import { Effect, FileSystem, Path, Schema } from "effect";\n+\n+import { CodexSettings } from "@t3tools/contracts";\n+import {\n+ CodexShadowHomeError,\n+ materializeCodexShadowHome,\n+ resolveCodexHomeLayout,\n+} from "./CodexHomeLayout.ts";\n+\n+const decodeCodexSettings = (input: {\n+ readonly enabled?: boolean;\n+ readonly homePath?: string;\n+ readonly shadowHomePath?: string;\n+ readonly customModels?: readonly string[];\n+ readonly binaryPath?: string;\n+}): CodexSettings => Schema.decodeSync(CodexSettings)(input);\n+\n+const makeTempDir = Effect.fn("CodexHomeLayout.test.makeTempDir")(function* (prefix: string) {\n+ const fileSystem = yield* FileSystem.FileSystem;\n+ return yield* fileSystem.makeTempDirectoryScoped({ prefix });\n+});\n+\n+const writeTextFile = Effect.fn("CodexHomeLayout.test.writeTextFile")(function* (\n+ filePath: string,\n+ contents: string,\n+) {\n+ const fileSystem = yield* FileSystem.FileSystem;\n+ const path = yield* Path.Path;\n+ yield* fileSystem.makeDirectory(path.dirname(filePath), { recursive: true });\n+ yield* fileSystem.writeFileString(filePath, contents);\n+});\n+\n+it.layer(NodeServices.layer)("CodexHomeLayout", (it) => {\n+ describe("resolveCodexHomeLayout", () => {\n+ it.effect("uses direct CODEX_HOME when no shadow home is configured", () =>\n+ Effect.gen(function* () {\n+ const homePath = yield* makeTempDir("t3code-codex-home-");\n+\n+ const layout = yield* resolveCodexHomeLayout(\n+ decodeCodexSettings({\n+ homePath,\n+ }),\n+ );\n+\n+ expect(layout).toMatchObject({\n+ mode: "direct",\n+ sharedHomePath: homePath,\n+ effectiveHomePath: homePath,\n+ continuationKey: `codex:home:${homePath}`,\n+ });\n+ }),\n+ );\n+\n+ it.effect("uses the shared home for continuation and the shadow home for runtime", () =>\n+ Effect.gen(function* () {\n+ const path = yield* Path.Path;\n+ const sharedHome = yield* makeTempDir("t3code-codex-shared-");\n+ const shadowRoot = yield* makeTempDir("t3code-codex-shadow-root-");\n+ const shadowHome = path.join(shadowRoot, "shadow");\n+\n+ const layout = yield* resolveCodexHomeLayout(\n+ decodeCodexSettings({\n+ homePath: sharedHome,\n+ shadowHomePath: shadowHome,\n+ }),\n+ );\n+\n+ expect(layout).toMatchObject({\n+ mode: "authOverlay",\n+ sharedHomePath: sharedHome,\n+ effectiveHomePath: shadowHome,\n+ continuationKey: `codex:home:${sharedHome}`,\n+ });\n+ }),\n+ );\n+ });\n+\n+ describe("materializeCodexShadowHome", () => {\n+ it.effect("materializes a shadow home with shared state links and private auth", () =>\n+ Effect.gen(function* () {\n+ const fileSystem = yield* FileSystem.FileSystem;\n+ const path = yield* Path.Path;\n+ const sharedHome = yield* makeTempDir("t3code-codex-shared-");\n+ const shadowRoot = yield* makeTempDir("t3code-codex-shadow-root-");\n+ const shadowHome = path.join(shadowRoot, "shadow");\n+\n+ yield* fileSystem.makeDirectory(path.join(sharedHome, "sessions"));\n+ yield* writeTextFile(path.join(sharedHome, "config.toml"), \'model = "gpt-5-codex"\\n\');\n+ yield* writeTextFile(path.join(sharedHome, "models_cache.json"), \'{"models":["shared"]}\\n\');\n+ yield* writeTextFile(path.join(sharedHome, "auth.json"), \'{"shared":true}\\n\');\n+ yield* fileSystem.makeDirectory(shadowHome, { recursive: true });\n+ yield* writeTextFile(path.join(shadowHome, "auth.json"), \'{"shadow":true}\\n\');\n+ yield* fileSystem.symlink(\n+ path.join(sharedHome, "models_cache.json"),\n+ path.join(shadowHome, "models_cache.json"),\n+ );\n+\n+ const layout = yield* resolveCodexHomeLayout(\n+ decodeCodexSettings({\n+ homePath: sharedHome,\n+ shadowHomePath: shadowHome,\n+ }),\n+ );\n+\n+ yield* materializeCodexShadowHome(layout);\n+\n+ const sessionsTarget = yield* fileSystem.readLink(path.join(shadowHome, "sessions"));\n+ const configTarget = yield* fileSystem.readLink(path.join(shadowHome, "config.toml"));\n+ const modelsCacheExists = yield* fileSystem.exists(\n+ path.join(shadowHome, "models_cache.json"),\n+ );\n+ const authLinkResult = yield* fileSystem\n+ .readLink(path.join(shadowHome, "auth.json"))\n+ .pipe(Effect.result);\n+ const authContents = yield* fileSystem.readFileString(path.join(shadowHome, "auth.json"));\n+\n+ expect(sessionsTarget).toBe(path.join(sharedHome, "sessions"));\n+ expect(configTarget).toBe(path.join(sharedHome, "config.toml"));\n+ expect(modelsCacheExists).toBe(false);\n+ expect(authLinkResult._tag).toBe("Failure");\n+ expect(authContents).toContain("shadow");\n+ }),\n+ );\n+\n+ it.effect("accepts Codex-created shadow-local runtime directories", () =>\n+ Effect.gen(function* () {\n+ const fileSystem = yield* FileSystem.FileSystem;\n+ const path = yield* Path.Path;\n+ const sharedHome = yield* makeTempDir("t3code-codex-shared-");\n+ const shadowRoot = yield* makeTempDir("t3code-codex-shadow-root-");\n+ const shadowHome = path.join(shadowRoot, "shadow");\n+\n+ yield* fileSystem.makeDirectory(path.join(sharedHome, "log"));\n+ yield* fileSystem.makeDirectory(path.join(sharedHome, "memories"));\n+ yield* fileSystem.makeDirectory(path.join(sharedHome, "tmp"));\n+ yield* writeTextFile(path.join(sharedHome, "config.toml"), \'model = "gpt-5-codex"\\n\');\n+ yield* writeTextFile(path.join(shadowHome, "auth.json"), \'{"shadow":true}\\n\');\n+ yield* fileSystem.makeDirectory(path.join(shadowHome, "log"), { recursive: true });\n+ yield* fileSystem.makeDirectory(path.join(shadowHome, "memories"), { recursive: true });\n+ yield* fileSystem.makeDirectory(path.join(shadowHome, "tmp"), { recursive: true });\n+\n+ const layout = yield* resolveCodexHomeLayout(\n+ decodeCodexSettings({\n+ homePath: sharedHome,\n+ shadowHomePath: shadowHome,\n+ }),\n+ );\n+\n+ yield* materializeCodexShadowHome(layout);\n+\n+ const configTarget = yield* fileSystem.readLink(path.join(shadowHome, "config.toml"));\n+ const logLinkResult = yield* fileSystem\n+ .readLink(path.join(shadowHome, "log"))\n+ .pipe(Effect.result);\n+ const memoriesLinkResult = yield* fileSystem\n+ .readLink(path.join(shadowHome, "memories"))\n+ .pipe(Effect.result);\n+ const tmpLinkResult = yield* fileSystem\n+ .readLink(path.join(shadowHome, "tmp"))\n+ .pipe(Effect.result);\n+\n+ expect(configTarget).toBe(path.join(sharedHome, "config.toml"));\n+ expect(logLinkResult._tag).toBe("Failure");\n+ expect(memoriesLinkResult._tag).toBe("Failure");\n+ expect(tmpLinkResult._tag).toBe("Failure");\n+ }),\n+ );\n+\n+ it.effect("rejects shadow homes that point at the shared home", () =>\n+ Effect.gen(function* () {\n+ const sharedHome = yield* makeTempDir("t3code-codex-shared-");\n+ const layout = yield* resolveCodexHomeLayout(\n+ decodeCodexSettings({\n+ homePath: sharedHome,\n+ shadowHomePath: sharedHome,\n+ }),\n+ );\n+\n+ const error = yield* materializeCodexShadowHome(layout).pipe(Effect.flip);\n+\n+ expect(error).toBeInstanceOf(CodexShadowHomeError);\n+ }),\n+ );\n+\n+ it.effect("rejects shared entries that already exist in the shadow home as real files", () =>\n+ Effect.gen(function* () {\n+ const path = yield* Path.Path;\n+ const sharedHome = yield* makeTempDir("t3code-codex-shared-");\n+ const shadowRoot = yield* makeTempDir("t3code-codex-shadow-root-");\n+ const shadowHome = path.join(shadowRoot, "shadow");\n+ yield* writeTextFile(path.join(sharedHome, "config.toml"), \'model = "gpt-5-codex"\\n\');\n+ yield* writeTextFile(path.join(shadowHome, "config.toml"), \'model = "local"\\n\');\n+\n+ const layout = yield* resolveCodexHomeLayout(\n+ decodeCodexSettings({\n+ homePath: sharedHome,\n+ shadowHomePath: shadowHome,\n+ }),\n+ );\n+\n+ const error = yield* materializeCodexShadowHome(layout).pipe(Effect.flip);\n+\n+ expect(error.detail).toContain("already exists and is not a symlink");\n+ }),\n+ );\n+ });\n+});\ndiff --git a/apps/server/src/provider/Drivers/CodexHomeLayout.ts b/apps/server/src/provider/Drivers/CodexHomeLayout.ts\nnew file mode 100644\nindex 0000000000..0b6cd6b891\n--- /dev/null\n+++ b/apps/server/src/provider/Drivers/CodexHomeLayout.ts\n@@ -0,0 +1,263 @@\n+import * as NodeOS from "node:os";\n+\n+import { ProviderDriverKind, type CodexSettings } from "@t3tools/contracts";\n+import { Effect, FileSystem, Path, Schema } from "effect";\n+import * as PlatformError from "effect/PlatformError";\n+\n+import { expandHomePath } from "../../pathExpansion.ts";\n+\n+export interface CodexHomeLayout {\n+ readonly mode: "direct" | "authOverlay";\n+ readonly sharedHomePath: string;\n+ readonly effectiveHomePath: string | undefined;\n+ readonly continuationKey: string;\n+}\n+\n+const KNOWN_SHARED_DIRECTORIES = [\n+ "sessions",\n+ "archived_sessions",\n+ "sqlite",\n+ "shell_snapshots",\n+ "worktrees",\n+ "skills",\n+ "plugins",\n+ "cache",\n+ "logs",\n+] as const;\n+\n+const PRIVATE_ENTRY_NAMES = new Set(["auth.json", "models_cache.json"]);\n+const SHADOW_LOCAL_ENTRY_NAMES = new Set(["log", "memories", "tmp"]);\n+\n+function resolveHomePath(path: Path.Path, value: string | undefined): string {\n+ const expanded =\n+ value && value.trim().length > 0\n+ ? expandHomePath(value)\n+ : path.join(NodeOS.homedir(), ".codex");\n+ return path.resolve(expanded);\n+}\n+\n+export const resolveCodexHomeLayout = Effect.fn("resolveCodexHomeLayout")(function* (\n+ config: CodexSettings,\n+): Effect.fn.Return<CodexHomeLayout, never, Path.Path> {\n+ const path = yield* Path.Path;\n+ const sharedHomePath = resolveHomePath(path, config.homePath);\n+ const shadowHomePath = config.shadowHomePath.trim();\n+ if (shadowHomePath.length === 0) {\n+ return {\n+ mode: "direct",\n+ sharedHomePath,\n+ effectiveHomePath: config.homePath.trim().length > 0 ? sharedHomePath : undefined,\n+ continuationKey: `codex:home:${sharedHomePath}`,\n+ };\n+ }\n+\n+ const effectiveHomePath = path.resolve(expandHomePath(shadowHomePath));\n+ return {\n+ mode: "authOverlay",\n+ sharedHomePath,\n+ effectiveHomePath,\n+ continuationKey: `codex:home:${sharedHomePath}`,\n+ };\n+});\n+\n+export class CodexShadowHomeError extends Schema.TaggedErrorClass<CodexShadowHomeError>()(\n+ "CodexShadowHomeError",\n+ {\n+ detail: Schema.String,\n+ cause: Schema.optional(Schema.Unknown),\n+ },\n+) {\n+ override get message(): string {\n+ return this.detail;\n+ }\n+}\n+\n+type LinkState =\n+ | {\n+ readonly _tag: "Missing";\n+ }\n+ | {\n+ readonly _tag: "NotSymlink";\n+ }\n+ | {\n+ readonly _tag: "Symlink";\n+ readonly target: string;\n+ };\n+\n+function toShadowHomeError(cause: unknown): CodexShadowHomeError {\n+ return Schema.is(CodexShadowHomeError)(cause)\n+ ? cause\n+ : new CodexShadowHomeError({\n+ detail: "Failed to materialize Codex shadow home.",\n+ cause,\n+ });\n+}\n+\n+function normalizeShadowHomeError<A, E, R>(\n+ effect: Effect.Effect<A, E, R>,\n+): Effect.Effect<A, CodexShadowHomeError, R> {\n+ return effect.pipe(Effect.mapError(toShadowHomeError));\n+}\n+\n+function isNotSymlinkError(error: PlatformError.PlatformError): boolean {\n+ const cause = error.reason.cause;\n+ return (\n+ error.reason._tag === "Unknown" &&\n+ typeof cause === "object" &&\n+ cause !== null &&\n+ "code" in cause &&\n+ cause.code === "EINVAL"\n+ );\n+}\n+\n+const readLinkState = Effect.fn("CodexHomeLayout.readLinkState")(function* (\n+ fileSystem: FileSystem.FileSystem,\n+ linkPath: string,\n+): Effect.fn.Return<LinkState, CodexShadowHomeError> {\n+ return yield* fileSystem.readLink(linkPath).pipe(\n+ Effect.map((target): LinkState => ({ _tag: "Symlink", target })),\n+ Effect.catch((error) => {\n+ if (error.reason._tag === "NotFound") {\n+ return Effect.succeed<LinkState>({ _tag: "Missing" });\n+ }\n+ if (isNotSymlinkError(error)) {\n+ return Effect.succeed<LinkState>({ _tag: "NotSymlink" });\n+ }\n+ return Effect.fail(toShadowHomeError(error));\n+ }),\n+ );\n+});\n+\n+const removePrivateSymlink = Effect.fn("CodexHomeLayout.removePrivateSymlink")(function* (input: {\n+ readonly fileSystem: FileSystem.FileSystem;\n+ readonly shadowPath: string;\n+ readonly entryName: string;\n+}): Effect.fn.Return<void, CodexShadowHomeError, Path.Path> {\n+ const path = yield* Path.Path;\n+ const privatePath = path.join(input.shadowPath, input.entryName);\n+ const state = yield* readLinkState(input.fileSystem, privatePath);\n+ if (state._tag === "Symlink") {\n+ yield* normalizeShadowHomeError(input.fileSystem.remove(privatePath));\n+ }\n+});\n+\n+const ensureSymlink = Effect.fn("CodexHomeLayout.ensureSymlink")(function* (input: {\n+ readonly fileSystem: FileSystem.FileSystem;\n+ readonly shadowPath: string;\n+ readonly sharedPath: string;\n+ readonly entryName: string;\n+}): Effect.fn.Return<void, CodexShadowHomeError, Path.Path> {\n+ const path = yield* Path.Path;\n+ const target = path.join(input.sharedPath, input.entryName);\n+ const link = path.join(input.shadowPath, input.entryName);\n+ const state = yield* readLinkState(input.fileSystem, link);\n+\n+ if (state._tag === "NotSymlink") {\n+ return yield* new CodexShadowHomeError({\n+ detail: `Cannot create Codex shadow home because \'${link}\' already exists and is not a symlink.`,\n+ });\n+ }\n+\n+ if (state._tag === "Missing") {\n+ return yield* normalizeShadowHomeError(input.fileSystem.symlink(target, link));\n+ }\n+\n+ const resolvedExisting = path.resolve(path.dirname(link), state.target);\n+ if (resolvedExisting !== target) {\n+ yield* normalizeShadowHomeError(input.fileSystem.remove(link));\n+ yield* normalizeShadowHomeError(input.fileSystem.symlink(target, link));\n+ }\n+});\n+\n+const ensureShadowAuthIsPrivate = Effect.fn("CodexHomeLayout.ensureShadowAuthIsPrivate")(function* (\n+ fileSystem: FileSystem.FileSystem,\n+ shadowPath: string,\n+): Effect.fn.Return<void, CodexShadowHomeError, Path.Path> {\n+ const path = yield* Path.Path;\n+ const authPath = path.join(shadowPath, "auth.json");\n+ const state = yield* readLinkState(fileSystem, authPath);\n+ if (state._tag === "Symlink") {\n+ return yield* new CodexShadowHomeError({\n+ detail: `Codex shadow auth file \'${authPath}\' must be a real file, not a symlink.`,\n+ });\n+ }\n+});\n+\n+export const materializeCodexShadowHome = Effect.fn("materializeCodexShadowHome")(function* (\n+ layout: CodexHomeLayout,\n+) {\n+ if (layout.mode !== "authOverlay") return;\n+ const effectiveHomePath = layout.effectiveHomePath;\n+ if (!effectiveHomePath) return;\n+ if (layout.sharedHomePath === effectiveHomePath) {\n+ return yield* new CodexShadowHomeError({\n+ detail: "Codex shadow home path must be different from the shared home path.",\n+ });\n+ }\n+\n+ const fileSystem = yield* FileSystem.FileSystem;\n+ const path = yield* Path.Path;\n+\n+ yield* normalizeShadowHomeError(\n+ Effect.all(\n+ [\n+ fileSystem.makeDirectory(layout.sharedHomePath, { recursive: true }),\n+ fileSystem.makeDirectory(effectiveHomePath, { recursive: true }),\n+ ...KNOWN_SHARED_DIRECTORIES.map((directory) =>\n+ fileSystem.makeDirectory(path.join(layout.sharedHomePath, directory), {\n+ recursive: true,\n+ }),\n+ ),\n+ ],\n+ { concurrency: "unbounded" },\n+ ),\n+ );\n+\n+ const sharedEntryNames = yield* normalizeShadowHomeError(\n+ fileSystem.readDirectory(layout.sharedHomePath),\n+ );\n+ const entries = new Set<string>(KNOWN_SHARED_DIRECTORIES);\n+ for (const entryName of sharedEntryNames) {\n+ if (!PRIVATE_ENTRY_NAMES.has(entryName) && !SHADOW_LOCAL_ENTRY_NAMES.has(entryName)) {\n+ entries.add(entryName);\n+ }\n+ }\n+\n+ yield* Effect.forEach(\n+ PRIVATE_ENTRY_NAMES,\n+ (entryName) =>\n+ entryName === "auth.json"\n+ ? Effect.void\n+ : removePrivateSymlink({\n+ fileSystem,\n+ shadowPath: effectiveHomePath,\n+ entryName,\n+ }),\n+ { discard: true },\n+ );\n+\n+ yield* Effect.forEach(\n+ entries,\n+ (entryName) => {\n+ if (PRIVATE_ENTRY_NAMES.has(entryName)) {\n+ return Effect.void;\n+ }\n+ return ensureSymlink({\n+ fileSystem,\n+ shadowPath: effectiveHomePath,\n+ sharedPath: layout.sharedHomePath,\n+ entryName,\n+ });\n+ },\n+ { discard: true },\n+ );\n+\n+ yield* ensureShadowAuthIsPrivate(fileSystem, effectiveHomePath);\n+});\n+\n+export function codexContinuationIdentity(layout: CodexHomeLayout) {\n+ return {\n+ driverKind: ProviderDriverKind.make("codex"),\n+ continuationKey: layout.continuationKey,\n+ };\n+}\ndiff --git a/apps/server/src/provider/Drivers/CursorDriver.ts b/apps/server/src/provider/Drivers/CursorDriver.ts\nnew file mode 100644\nindex 0000000000..b7eda591bc\n--- /dev/null\n+++ b/apps/server/src/provider/Drivers/CursorDriver.ts\n@@ -0,0 +1,148 @@\n+/**\n+ * CursorDriver — `ProviderDriver` for the Cursor Agent (`agent`) runtime.\n+ *\n+ * Cursor exposes an ACP-based CLI. The driver is still a plain value, but\n+ * its snapshot uses `makeManagedServerProvider`\'s optional `enrichSnapshot`\n+ * hook to run the slow ACP model-capability probe in the background without\n+ * blocking the initial `ready`-state publish.\n+ *\n+ * Text generation is supported via the ACP runtime — `makeCursorTextGeneration`\n+ * drives `runtime.prompt` with a structured-output schema and collects the\n+ * agent\'s `agent_message_chunk` stream into a single JSON blob.\n+ *\n+ * @module provider/Drivers/CursorDriver\n+ */\n+import { CursorSettings, ProviderDriverKind, type ServerProvider } from "@t3tools/contracts";\n+import { Duration, Effect, FileSystem, Path, Schema, Stream } from "effect";\n+import { ChildProcessSpawner } from "effect/unstable/process";\n+\n+import { ServerConfig } from "../../config.ts";\n+import { makeCursorTextGeneration } from "../../git/Layers/CursorTextGeneration.ts";\n+import { ProviderDriverError } from "../Errors.ts";\n+import { makeCursorAdapter } from "../Layers/CursorAdapter.ts";\n+import {\n+ buildInitialCursorProviderSnapshot,\n+ checkCursorProviderStatus,\n+ enrichCursorSnapshot,\n+} from "../Layers/CursorProvider.ts";\n+import { ProviderEventLoggers } from "../Layers/ProviderEventLoggers.ts";\n+import { makeManagedServerProvider } from "../makeManagedServerProvider.ts";\n+import {\n+ defaultProviderContinuationIdentity,\n+ type ProviderDriver,\n+ type ProviderInstance,\n+} from "../ProviderDriver.ts";\n+import type { ServerProviderDraft } from "../providerSnapshot.ts";\n+import { mergeProviderInstanceEnvironment } from "../ProviderInstanceEnvironment.ts";\n+\n+const DRIVER_KIND = ProviderDriverKind.make("cursor");\n+const SNAPSHOT_REFRESH_INTERVAL = Duration.minutes(5);\n+\n+export type CursorDriverEnv =\n+ | ChildProcessSpawner.ChildProcessSpawner\n+ | FileSystem.FileSystem\n+ | Path.Path\n+ | ProviderEventLoggers\n+ | ServerConfig;\n+\n+const withInstanceIdentity =\n+ (input: {\n+ readonly instanceId: ProviderInstance["instanceId"];\n+ readonly displayName: string | undefined;\n+ readonly accentColor: string | undefined;\n+ readonly continuationGroupKey: string;\n+ }) =>\n+ (snapshot: ServerProviderDraft): ServerProvider => ({\n+ ...snapshot,\n+ instanceId: input.instanceId,\n+ driver: DRIVER_KIND,\n+ ...(input.displayName ? { displayName: input.displayName } : {}),\n+ ...(input.accentColor ? { accentColor: input.accentColor } : {}),\n+ continuation: { groupKey: input.continuationGroupKey },\n+ });\n+\n+export const CursorDriver: ProviderDriver<CursorSettings, CursorDriverEnv> = {\n+ driverKind: DRIVER_KIND,\n+ metadata: {\n+ displayName: "Cursor",\n+ supportsMultipleInstances: true,\n+ },\n+ configSchema: CursorSettings,\n+ defaultConfig: (): CursorSettings => Schema.decodeSync(CursorSettings)({}),\n+ create: ({ instanceId, displayName, accentColor, environment, enabled, config }) =>\n+ Effect.gen(function* () {\n+ const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;\n+ const fileSystem = yield* FileSystem.FileSystem;\n+ const path = yield* Path.Path;\n+ const eventLoggers = yield* ProviderEventLoggers;\n+ const processEnv = mergeProviderInstanceEnvironment(environment);\n+ const continuationIdentity = defaultProviderContinuationIdentity({\n+ driverKind: DRIVER_KIND,\n+ instanceId,\n+ });\n+ const stampIdentity = withInstanceIdentity({\n+ instanceId,\n+ displayName,\n+ accentColor,\n+ continuationGroupKey: continuationIdentity.continuationKey,\n+ });\n+ const effectiveConfig = { ...config, enabled } satisfies CursorSettings;\n+\n+ const adapter = yield* makeCursorAdapter(effectiveConfig, {\n+ environment: processEnv,\n+ ...(eventLoggers.native ? { nativeEventLogger: eventLoggers.native } : {}),\n+ instanceId,\n+ });\n+ const textGeneration = yield* makeCursorTextGeneration(effectiveConfig, processEnv);\n+\n+ const checkProvider = checkCursorProviderStatus(effectiveConfig, processEnv).pipe(\n+ Effect.map(stampIdentity),\n+ Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),\n+ Effect.provideService(FileSystem.FileSystem, fileSystem),\n+ Effect.provideService(Path.Path, path),\n+ );\n+\n+ const snapshot = yield* makeManagedServerProvider<CursorSettings>({\n+ getSettings: Effect.succeed(effectiveConfig),\n+ streamSettings: Stream.never,\n+ haveSettingsChanged: () => false,\n+ initialSnapshot: (settings) => stampIdentity(buildInitialCursorProviderSnapshot(settings)),\n+ checkProvider,\n+ // Preserve the background ACP model-capability probe that used to\n+ // live on `CursorProviderLive`. Only fires when the snapshot reports\n+ // an authenticated, enabled provider with at least one non-custom\n+ // model whose capabilities haven\'t been captured yet.\n+ enrichSnapshot: ({ settings, snapshot: currentSnapshot, publishSnapshot }) =>\n+ enrichCursorSnapshot({\n+ settings,\n+ environment: processEnv,\n+ snapshot: currentSnapshot,\n+ publishSnapshot,\n+ stampIdentity,\n+ }).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner)),\n+ refreshInterval: SNAPSHOT_REFRESH_INTERVAL,\n+ }).pipe(\n+ Effect.mapError(\n+ (cause) =>\n+ new ProviderDriverError({\n+ driver: DRIVER_KIND,\n+ instanceId,\n+ detail: `Failed to build Cursor snapshot: ${cause.message ?? String(cause)}`,\n+ cause,\n+ }),\n+ ),\n+ );\n+\n+ return {\n+ instanceId,\n+ driverKind: DRIVER_KIND,\n+ continuationIdentity,\n+ displayName,\n+ accentColor,\n+ enabled,\n+ snapshot,\n+ adapter,\n+ textGeneration,\n+ } satisfies ProviderInstance;\n+ }),\n+};\ndiff --git a/apps/server/src/provider/Drivers/OpenCodeDriver.ts b/apps/server/src/provider/Drivers/OpenCodeDriver.ts\nnew file mode 100644\nindex 0000000000..29f74ead02\n--- /dev/null\n+++ b/apps/server/src/provider/Drivers/OpenCodeDriver.ts\n@@ -0,0 +1,135 @@\n+/**\n+ * OpenCodeDriver — `ProviderDriver` for the OpenCode runtime.\n+ *\n+ * Mirrors the Codex / Claude drivers: a plain value whose `create()`\n+ * bundles `snapshot` / `adapter` / `textGeneration` closures over the\n+ * per-instance `OpenCodeSettings`.\n+ *\n+ * Two instances with different `serverUrl`s therefore talk to independent\n+ * OpenCode servers; when no `serverUrl` is set, the adapter + text-generation\n+ * shares spin up their own scoped child processes, and those child\n+ * processes are released when the registry scope closes.\n+ *\n+ * @module provider/Drivers/OpenCodeDriver\n+ */\n+import { OpenCodeSettings, ProviderDriverKind, type ServerProvider } from "@t3tools/contracts";\n+import { Duration, Effect, FileSystem, Path, Schema, Stream } from "effect";\n+import { ChildProcessSpawner } from "effect/unstable/process";\n+\n+import { makeOpenCodeTextGeneration } from "../../git/Layers/OpenCodeTextGeneration.ts";\n+import { ServerConfig } from "../../config.ts";\n+import { ProviderDriverError } from "../Errors.ts";\n+import { makeOpenCodeAdapter } from "../Layers/OpenCodeAdapter.ts";\n+import {\n+ checkOpenCodeProviderStatus,\n+ makePendingOpenCodeProvider,\n+} from "../Layers/OpenCodeProvider.ts";\n+import { ProviderEventLoggers } from "../Layers/ProviderEventLoggers.ts";\n+import { makeManagedServerProvider } from "../makeManagedServerProvider.ts";\n+import { OpenCodeRuntime } from "../opencodeRuntime.ts";\n+import {\n+ defaultProviderContinuationIdentity,\n+ type ProviderDriver,\n+ type ProviderInstance,\n+} from "../ProviderDriver.ts";\n+import type { ServerProviderDraft } from "../providerSnapshot.ts";\n+import { mergeProviderInstanceEnvironment } from "../ProviderInstanceEnvironment.ts";\n+\n+const DRIVER_KIND = ProviderDriverKind.make("opencode");\n+const SNAPSHOT_REFRESH_INTERVAL = Duration.minutes(5);\n+\n+export type OpenCodeDriverEnv =\n+ | ChildProcessSpawner.ChildProcessSpawner\n+ | FileSystem.FileSystem\n+ | OpenCodeRuntime\n+ | Path.Path\n+ | ProviderEventLoggers\n+ | ServerConfig;\n+\n+const withInstanceIdentity =\n+ (input: {\n+ readonly instanceId: ProviderInstance["instanceId"];\n+ readonly displayName: string | undefined;\n+ readonly accentColor: string | undefined;\n+ readonly continuationGroupKey: string;\n+ }) =>\n+ (snapshot: ServerProviderDraft): ServerProvider => ({\n+ ...snapshot,\n+ instanceId: input.instanceId,\n+ driver: DRIVER_KIND,\n+ ...(input.displayName ? { displayName: input.displayName } : {}),\n+ ...(input.accentColor ? { accentColor: input.accentColor } : {}),\n+ continuation: { groupKey: input.continuationGroupKey },\n+ });\n+\n+export const OpenCodeDriver: ProviderDriver<OpenCodeSettings, OpenCodeDriverEnv> = {\n+ driverKind: DRIVER_KIND,\n+ metadata: {\n+ displayName: "OpenCode",\n+ supportsMultipleInstances: true,\n+ },\n+ configSchema: OpenCodeSettings,\n+ defaultConfig: (): OpenCodeSettings => Schema.decodeSync(OpenCodeSettings)({}),\n+ create: ({ instanceId, displayName, accentColor, environment, enabled, config }) =>\n+ Effect.gen(function* () {\n+ const openCodeRuntime = yield* OpenCodeRuntime;\n+ const serverConfig = yield* ServerConfig;\n+ const eventLoggers = yield* ProviderEventLoggers;\n+ const processEnv = mergeProviderInstanceEnvironment(environment);\n+ const continuationIdentity = defaultProviderContinuationIdentity({\n+ driverKind: DRIVER_KIND,\n+ instanceId,\n+ });\n+ const stampIdentity = withInstanceIdentity({\n+ instanceId,\n+ displayName,\n+ accentColor,\n+ continuationGroupKey: continuationIdentity.continuationKey,\n+ });\n+ const effectiveConfig = { ...config, enabled } satisfies OpenCodeSettings;\n+\n+ const adapter = yield* makeOpenCodeAdapter(effectiveConfig, {\n+ instanceId,\n+ environment: processEnv,\n+ ...(eventLoggers.native ? { nativeEventLogger: eventLoggers.native } : {}),\n+ });\n+ const textGeneration = yield* makeOpenCodeTextGeneration(effectiveConfig, processEnv);\n+\n+ const checkProvider = checkOpenCodeProviderStatus(\n+ effectiveConfig,\n+ serverConfig.cwd,\n+ processEnv,\n+ ).pipe(Effect.map(stampIdentity), Effect.provideService(OpenCodeRuntime, openCodeRuntime));\n+\n+ const snapshot = yield* makeManagedServerProvider<OpenCodeSettings>({\n+ getSettings: Effect.succeed(effectiveConfig),\n+ streamSettings: Stream.never,\n+ haveSettingsChanged: () => false,\n+ initialSnapshot: (settings) => stampIdentity(makePendingOpenCodeProvider(settings)),\n+ checkProvider,\n+ refreshInterval: SNAPSHOT_REFRESH_INTERVAL,\n+ }).pipe(\n+ Effect.mapError(\n+ (cause) =>\n+ new ProviderDriverError({\n+ driver: DRIVER_KIND,\n+ instanceId,\n+ detail: `Failed to build OpenCode snapshot: ${cause.message ?? String(cause)}`,\n+ cause,\n+ }),\n+ ),\n+ );\n+\n+ return {\n+ instanceId,\n+ driverKind: DRIVER_KIND,\n+ continuationIdentity,\n+ displayName,\n+ accentColor,\n+ enabled,\n+ snapshot,\n+ adapter,\n+ textGeneration,\n+ } satisfies ProviderInstance;\n+ }),\n+};\ndiff --git a/apps/server/src/provider/Errors.ts b/apps/server/src/provider/Errors.ts\nindex e4e46d3748..2bd926512e 100644\n--- a/apps/server/src/provider/Errors.ts\n+++ b/apps/server/src/provider/Errors.ts\n@@ -116,6 +116,46 @@ export class ProviderUnsupportedError extends Schema.TaggedErrorClass<ProviderUn\n }\n }\n \n+/**\n+ * ProviderInstanceNotFoundError - Lookup against the instance registry failed.\n+ *\n+ * Distinct from `ProviderUnsupportedError`: the driver is registered, but no\n+ * instance with the requested id has been bootstrapped — typically because\n+ * the persisted instance id refers to an instance the user removed from\n+ * settings, or because routing is asked for an instance before the registry\n+ * has finished its first reload.\n+ */\n+export class ProviderInstanceNotFoundError extends Schema.TaggedErrorClass<ProviderInstanceNotFoundError>()(\n+ "ProviderInstanceNotFoundError",\n+ {\n+ instanceId: Schema.String,\n+ cause: Schema.optional(Schema.Defect),\n+ },\n+) {\n+ override get message(): string {\n+ return `No provider instance bound to id \'${this.instanceId}\'`;\n+ }\n+}\n+\n+/**\n+ * ProviderDriverError - A driver `create` call failed before producing an\n+ * instance. Surfaced to the registry, which marks the offending entry as\n+ * an "unavailable" shadow snapshot rather than crashing the server.\n+ */\n+export class ProviderDriverError extends Schema.TaggedErrorClass<ProviderDriverError>()(\n+ "ProviderDriverError",\n+ {\n+ driver: Schema.String,\n+ instanceId: Schema.String,\n+ detail: Schema.String,\n+ cause: Schema.optional(Schema.Defect),\n+ },\n+) {\n+ override get message(): string {\n+ return `Provider driver \'${this.driver}\' failed to create instance \'${this.instanceId}\': ${this.detail}`;\n+ }\n+}\n+\n /**\n * ProviderSessionNotFoundError - Provider-facing session not found.\n */\n@@ -157,6 +197,7 @@ export type ProviderAdapterError =\n export type ProviderServiceError =\n | ProviderValidationError\n | ProviderUnsupportedError\n+ | ProviderInstanceNotFoundError\n | ProviderSessionNotFoundError\n | ProviderSessionDirectoryPersistenceError\n | ProviderAdapterError\ndiff --git a/apps/server/src/provider/Layers/ClaudeAdapter.test.ts b/apps/server/src/provider/Layers/ClaudeAdapter.test.ts\nindex 9c83bce858..14cca34b20 100644\n--- a/apps/server/src/provider/Layers/ClaudeAdapter.test.ts\n+++ b/apps/server/src/provider/Layers/ClaudeAdapter.test.ts\n@@ -12,21 +12,29 @@ import type {\n } from "@anthropic-ai/claude-agent-sdk";\n import {\n ApprovalRequestId,\n+ ClaudeSettings,\n+ ProviderDriverKind,\n ProviderItemId,\n ProviderRuntimeEvent,\n type RuntimeMode,\n ThreadId,\n+ ProviderInstanceId,\n } from "@t3tools/contracts";\n import { createModelSelection } from "@t3tools/shared/model";\n import { assert, describe, it } from "@effect/vitest";\n-import { Effect, Fiber, Layer, Random, Stream } from "effect";\n+import { Context, Effect, Fiber, Layer, Random, Schema, Stream } from "effect";\n \n import { attachmentRelativePath } from "../../attachmentStore.ts";\n import { ServerConfig } from "../../config.ts";\n import { ServerSettingsService } from "../../serverSettings.ts";\n import { ProviderAdapterValidationError } from "../Errors.ts";\n-import { ClaudeAdapter } from "../Services/ClaudeAdapter.ts";\n-import { makeClaudeAdapterLive, type ClaudeAdapterLiveOptions } from "./ClaudeAdapter.ts";\n+import type { ClaudeAdapterShape } from "../Services/ClaudeAdapter.ts";\n+import { makeClaudeAdapter, type ClaudeAdapterLiveOptions } from "./ClaudeAdapter.ts";\n+\n+// Test-local service tag so the rest of the file can keep using `yield* ClaudeAdapter`.\n+class ClaudeAdapter extends Context.Service<ClaudeAdapter, ClaudeAdapterShape>()(\n+ "test/ClaudeAdapter",\n+) {}\n \n class FakeClaudeQuery implements AsyncIterable<SDKMessage> {\n private readonly queue: Array<SDKMessage> = [];\n@@ -137,6 +145,8 @@ function makeHarness(config?: {\n readonly nativeEventLogger?: ClaudeAdapterLiveOptions["nativeEventLogger"];\n readonly cwd?: string;\n readonly baseDir?: string;\n+ readonly claudeConfig?: Partial<ClaudeSettings>;\n+ readonly instanceId?: ProviderInstanceId;\n }) {\n const query = new FakeClaudeQuery();\n let createInput:\n@@ -147,6 +157,7 @@ function makeHarness(config?: {\n | undefined;\n \n const adapterOptions: ClaudeAdapterLiveOptions = {\n+ ...(config?.instanceId ? { instanceId: config.instanceId } : {}),\n createQuery: (input) => {\n createInput = input;\n return query;\n@@ -164,7 +175,13 @@ function makeHarness(config?: {\n };\n \n return {\n- layer: makeClaudeAdapterLive(adapterOptions).pipe(\n+ layer: Layer.effect(\n+ ClaudeAdapter,\n+ Effect.gen(function* () {\n+ const claudeConfig = Schema.decodeSync(ClaudeSettings)(config?.claudeConfig ?? {});\n+ return yield* makeClaudeAdapter(claudeConfig, adapterOptions);\n+ }),\n+ ).pipe(\n Layer.provideMerge(\n ServerConfig.layerTest(\n config?.cwd ?? "/tmp/claude-adapter-test",\n@@ -247,7 +264,11 @@ describe("ClaudeAdapterLive", () => {\n return Effect.gen(function* () {\n const adapter = yield* ClaudeAdapter;\n const result = yield* adapter\n- .startSession({ threadId: THREAD_ID, provider: "codex", runtimeMode: "full-access" })\n+ .startSession({\n+ threadId: THREAD_ID,\n+ provider: ProviderDriverKind.make("codex"),\n+ runtimeMode: "full-access",\n+ })\n .pipe(Effect.result);\n \n assert.equal(result._tag, "Failure");\n@@ -257,7 +278,7 @@ describe("ClaudeAdapterLive", () => {\n assert.deepEqual(\n result.failure,\n new ProviderAdapterValidationError({\n- provider: "claudeAgent",\n+ provider: ProviderDriverKind.make("claudeAgent"),\n operation: "startSession",\n issue: "Expected provider \'claudeAgent\' but received \'codex\'.",\n }),\n@@ -274,7 +295,7 @@ describe("ClaudeAdapterLive", () => {\n const adapter = yield* ClaudeAdapter;\n yield* adapter.startSession({\n threadId: THREAD_ID,\n- provider: "claudeAgent",\n+ provider: ProviderDriverKind.make("claudeAgent"),\n runtimeMode: "full-access",\n });\n \n@@ -294,7 +315,7 @@ describe("ClaudeAdapterLive", () => {\n const adapter = yield* ClaudeAdapter;\n yield* adapter.startSession({\n threadId: THREAD_ID,\n- provider: "claudeAgent",\n+ provider: ProviderDriverKind.make("claudeAgent"),\n runtimeMode: "approval-required",\n });\n \n@@ -314,7 +335,7 @@ describe("ClaudeAdapterLive", () => {\n const adapter = yield* ClaudeAdapter;\n yield* adapter.startSession({\n threadId: THREAD_ID,\n- provider: "claudeAgent",\n+ provider: ProviderDriverKind.make("claudeAgent"),\n runtimeMode: "full-access",\n });\n \n@@ -333,10 +354,12 @@ describe("ClaudeAdapterLive", () => {\n const adapter = yield* ClaudeAdapter;\n yield* adapter.startSession({\n threadId: THREAD_ID,\n- provider: "claudeAgent",\n- modelSelection: createModelSelection("claudeAgent", "claude-opus-4-6", [\n- { id: "effort", value: "max" },\n- ]),\n+ provider: ProviderDriverKind.make("claudeAgent"),\n+ modelSelection: createModelSelection(\n+ ProviderInstanceId.make("claudeAgent"),\n+ "claude-opus-4-6",\n+ [{ id: "effort", value: "max" }],\n+ ),\n runtimeMode: "full-access",\n });\n \n@@ -348,15 +371,37 @@ describe("ClaudeAdapterLive", () => {\n );\n });\n \n+ it.effect("runs Claude SDK sessions with the configured Claude HOME", () => {\n+ const harness = makeHarness({ claudeConfig: { homePath: "~/.claude-work" } });\n+ return Effect.gen(function* () {\n+ const adapter = yield* ClaudeAdapter;\n+ yield* adapter.startSession({\n+ threadId: THREAD_ID,\n+ provider: ProviderDriverKind.make("claudeAgent"),\n+ modelSelection: createModelSelection(\n+ ProviderInstanceId.make("claudeAgent"),\n+ "claude-opus-4-6",\n+ ),\n+ runtimeMode: "full-access",\n+ });\n+\n+ const createInput = harness.getLastCreateQueryInput();\n+ assert.equal(createInput?.options.env?.HOME, path.join(os.homedir(), ".claude-work"));\n+ }).pipe(\n+ Effect.provideService(Random.Random, makeDeterministicRandomService()),\n+ Effect.provide(harness.layer),\n+ );\n+ });\n+\n it.effect("maps the Claude Opus 4.7 default effort to the SDK-supported max value", () => {\n const harness = makeHarness();\n return Effect.gen(function* () {\n const adapter = yield* ClaudeAdapter;\n yield* adapter.startSession({\n threadId: THREAD_ID,\n- provider: "claudeAgent",\n+ provider: ProviderDriverKind.make("claudeAgent"),\n modelSelection: {\n- provider: "claudeAgent",\n+ instanceId: ProviderInstanceId.make("claudeAgent"),\n model: "claude-opus-4-7",\n },\n runtimeMode: "full-access",\n@@ -376,10 +421,12 @@ describe("ClaudeAdapterLive", () => {\n const adapter = yield* ClaudeAdapter;\n yield* adapter.startSession({\n threadId: THREAD_ID,\n- provider: "claudeAgent",\n- modelSelection: createModelSelection("claudeAgent", "claude-opus-4-7", [\n- { id: "effort", value: "xhigh" },\n- ]),\n+ provider: ProviderDriverKind.make("claudeAgent"),\n+ modelSelection: createModelSelection(\n+ ProviderInstanceId.make("claudeAgent"),\n+ "claude-opus-4-7",\n+ [{ id: "effort", value: "xhigh" }],\n+ ),\n runtimeMode: "full-access",\n });\n \n@@ -397,10 +444,12 @@ describe("ClaudeAdapterLive", () => {\n const adapter = yield* ClaudeAdapter;\n yield* adapter.startSession({\n threadId: THREAD_ID,\n- provider: "claudeAgent",\n- modelSelection: createModelSelection("claudeAgent", "claude-sonnet-4-6", [\n- { id: "effort", value: "max" },\n- ]),\n+ provider: ProviderDriverKind.make("claudeAgent"),\n+ modelSelection: createModelSelection(\n+ ProviderInstanceId.make("claudeAgent"),\n+ "claude-sonnet-4-6",\n+ [{ id: "effort", value: "max" }],\n+ ),\n runtimeMode: "full-access",\n });\n \n@@ -418,10 +467,12 @@ describe("ClaudeAdapterLive", () => {\n const adapter = yield* ClaudeAdapter;\n yield* adapter.startSession({\n threadId: THREAD_ID,\n- provider: "claudeAgent",\n- modelSelection: createModelSelection("claudeAgent", "claude-haiku-4-5", [\n- { id: "effort", value: "high" },\n- ]),\n+ provider: ProviderDriverKind.make("claudeAgent"),\n+ modelSelection: createModelSelection(\n+ ProviderInstanceId.make("claudeAgent"),\n+ "claude-haiku-4-5",\n+ [{ id: "effort", value: "high" }],\n+ ),\n runtimeMode: "full-access",\n });\n \n@@ -439,10 +490,12 @@ describe("ClaudeAdapterLive", () => {\n const adapter = yield* ClaudeAdapter;\n yield* adapter.startSession({\n threadId: THREAD_ID,\n- provider: "claudeAgent",\n- modelSelection: createModelSelection("claudeAgent", "claude-haiku-4-5", [\n- { id: "thinking", value: false },\n- ]),\n+ provider: ProviderDriverKind.make("claudeAgent"),\n+ modelSelection: createModelSelection(\n+ ProviderInstanceId.make("claudeAgent"),\n+ "claude-haiku-4-5",\n+ [{ id: "thinking", value: false }],\n+ ),\n runtimeMode: "full-access",\n });\n \n@@ -462,10 +515,12 @@ describe("ClaudeAdapterLive", () => {\n const adapter = yield* ClaudeAdapter;\n yield* adapter.startSession({\n threadId: THREAD_ID,\n- provider: "claudeAgent",\n- modelSelection: createModelSelection("claudeAgent", "claude-sonnet-4-6", [\n- { id: "thinking", value: false },\n- ]),\n+ provider: ProviderDriverKind.make("claudeAgent"),\n+ modelSelection: createModelSelection(\n+ ProviderInstanceId.make("claudeAgent"),\n+ "claude-sonnet-4-6",\n+ [{ id: "thinking", value: false }],\n+ ),\n runtimeMode: "full-access",\n });\n \n@@ -483,10 +538,12 @@ describe("ClaudeAdapterLive", () => {\n const adapter = yield* ClaudeAdapter;\n yield* adapter.startSession({\n threadId: THREAD_ID,\n- provider: "claudeAgent",\n- modelSelection: createModelSelection("claudeAgent", "claude-opus-4-6", [\n- { id: "fastMode", value: true },\n- ]),\n+ provider: ProviderDriverKind.make("claudeAgent"),\n+ modelSelection: createModelSelection(\n+ ProviderInstanceId.make("claudeAgent"),\n+ "claude-opus-4-6",\n+ [{ id: "fastMode", value: true }],\n+ ),\n runtimeMode: "full-access",\n });\n \n@@ -506,10 +563,12 @@ describe("ClaudeAdapterLive", () => {\n const adapter = yield* ClaudeAdapter;\n yield* adapter.startSession({\n threadId: THREAD_ID,\n- provider: "claudeAgent",\n- modelSelection: createModelSelection("claudeAgent", "claude-sonnet-4-6", [\n- { id: "fastMode", value: true },\n- ]),\n+ provider: ProviderDriverKind.make("claudeAgent"),\n+ modelSelection: createModelSelection(\n+ ProviderInstanceId.make("claudeAgent"),\n+ "claude-sonnet-4-6",\n+ [{ id: "fastMode", value: true }],\n+ ),\n runtimeMode: "full-access",\n });\n \n@@ -527,10 +586,12 @@ describe("ClaudeAdapterLive", () => {\n const adapter = yield* ClaudeAdapter;\n const session = yield* adapter.startSession({\n threadId: THREAD_ID,\n- provider: "claudeAgent",\n- modelSelection: createModelSelection("claudeAgent", "claude-sonnet-4-6", [\n- { id: "effort", value: "ultrathink" },\n- ]),\n+ provider: ProviderDriverKind.make("claudeAgent"),\n+ modelSelection: createModelSelection(\n+ ProviderInstanceId.make("claudeAgent"),\n+ "claude-sonnet-4-6",\n+ [{ id: "effort", value: "ultrathink" }],\n+ ),\n runtimeMode: "full-access",\n });\n \n@@ -538,9 +599,11 @@ describe("ClaudeAdapterLive", () => {\n threadId: session.threadId,\n input: "Investigate the edge cases",\n attachments: [],\n- modelSelection: createModelSelection("claudeAgent", "claude-sonnet-4-6", [\n- { id: "effort", value: "ultrathink" },\n- ]),\n+ modelSelection: createModelSelection(\n+ ProviderInstanceId.make("claudeAgent"),\n+ "claude-sonnet-4-6",\n+ [{ id: "effort", value: "ultrathink" }],\n+ ),\n });\n \n const createInput = harness.getLastCreateQueryInput();\n@@ -585,7 +648,7 @@ describe("ClaudeAdapterLive", () => {\n \n const session = yield* adapter.startSession({\n threadId: THREAD_ID,\n- provider: "claudeAgent",\n+ provider: ProviderDriverKind.make("claudeAgent"),\n runtimeMode: "full-access",\n });\n \n@@ -630,9 +693,9 @@ describe("ClaudeAdapterLive", () => {\n \n const session = yield* adapter.startSession({\n threadId: THREAD_ID,\n- provider: "claudeAgent",\n+ provider: ProviderDriverKind.make("claudeAgent"),\n modelSelection: {\n- provider: "claudeAgent",\n+ instanceId: ProviderInstanceId.make("claudeAgent"),\n model: "claude-sonnet-4-5",\n },\n runtimeMode: "full-access",\n@@ -807,7 +870,7 @@ describe("ClaudeAdapterLive", () => {\n \n const session = yield* adapter.startSession({\n threadId: THREAD_ID,\n- provider: "claudeAgent",\n+ provider: ProviderDriverKind.make("claudeAgent"),\n runtimeMode: "full-access",\n });\n \n@@ -986,7 +1049,7 @@ describe("ClaudeAdapterLive", () => {\n \n const session = yield* adapter.startSession({\n threadId: THREAD_ID,\n- provider: "claudeAgent",\n+ provider: ProviderDriverKind.make("claudeAgent"),\n runtimeMode: "full-access",\n });\n \n@@ -1077,7 +1140,7 @@ describe("ClaudeAdapterLive", () => {\n \n const session = yield* adapter.startSession({\n threadId: THREAD_ID,\n- provider: "claudeAgent",\n+ provider: ProviderDriverKind.make("claudeAgent"),\n runtimeMode: "full-access",\n });\n \n@@ -1153,7 +1216,7 @@ describe("ClaudeAdapterLive", () => {\n \n const session = yield* adapter.startSession({\n threadId: THREAD_ID,\n- provider: "claudeAgent",\n+ provider: ProviderDriverKind.make("claudeAgent"),\n runtimeMode: "full-access",\n });\n \n@@ -1219,7 +1282,7 @@ describe("ClaudeAdapterLive", () => {\n \n yield* adapter.startSession({\n threadId: THREAD_ID,\n- provider: "claudeAgent",\n+ provider: ProviderDriverKind.make("claudeAgent"),\n runtimeMode: "full-access",\n });\n \n@@ -1270,13 +1333,19 @@ describe("ClaudeAdapterLive", () => {\n \n it.effect("closes the previous session before replacing an existing thread session", () => {\n const queries: FakeClaudeQuery[] = [];\n- const layer = makeClaudeAdapterLive({\n- createQuery: () => {\n- const query = new FakeClaudeQuery();\n- queries.push(query);\n- return query;\n- },\n- }).pipe(\n+ const layer = Layer.effect(\n+ ClaudeAdapter,\n+ Effect.gen(function* () {\n+ const claudeConfig = Schema.decodeSync(ClaudeSettings)({});\n+ return yield* makeClaudeAdapter(claudeConfig, {\n+ createQuery: () => {\n+ const query = new FakeClaudeQuery();\n+ queries.push(query);\n+ return query;\n+ },\n+ });\n+ }),\n+ ).pipe(\n Layer.provideMerge(ServerConfig.layerTest("/tmp/claude-adapter-test", "/tmp")),\n Layer.provideMerge(ServerSettingsService.layerTest()),\n Layer.provideMerge(NodeServices.layer),\n@@ -1292,13 +1361,13 @@ describe("ClaudeAdapterLive", () => {\n \n const firstSession = yield* adapter.startSession({\n threadId: THREAD_ID,\n- provider: "claudeAgent",\n+ provider: ProviderDriverKind.make("claudeAgent"),\n runtimeMode: "full-access",\n });\n \n const secondSession = yield* adapter.startSession({\n threadId: THREAD_ID,\n- provider: "claudeAgent",\n+ provider: ProviderDriverKind.make("claudeAgent"),\n runtimeMode: "full-access",\n resumeCursor: firstSession.resumeCursor,\n });\n@@ -1347,21 +1416,27 @@ describe("ClaudeAdapterLive", () => {\n \n let promptConsumerError: unknown = undefined;\n \n- const layer = makeClaudeAdapterLive({\n- createQuery: (input) => {\n- // Simulate the SDK consuming the prompt iterable\n- (async () => {\n- try {\n- for await (const _message of input.prompt) {\n- /* SDK processes user messages */\n- }\n- } catch (error) {\n- promptConsumerError = error;\n- }\n- })();\n- return query;\n- },\n- }).pipe(\n+ const layer = Layer.effect(\n+ ClaudeAdapter,\n+ Effect.gen(function* () {\n+ const claudeConfig = Schema.decodeSync(ClaudeSettings)({});\n+ return yield* makeClaudeAdapter(claudeConfig, {\n+ createQuery: (input) => {\n+ // Simulate the SDK consuming the prompt iterable\n+ (async () => {\n+ try {\n+ for await (const _message of input.prompt) {\n+ /* SDK processes user messages */\n+ }\n+ } catch (error) {\n+ promptConsumerError = error;\n+ }\n+ })();\n+ return query;\n+ },\n+ });\n+ }),\n+ ).pipe(\n Layer.provideMerge(ServerConfig.layerTest("/tmp/claude-adapter-test", "/tmp")),\n Layer.provideMerge(ServerSettingsService.layerTest()),\n Layer.provideMerge(NodeServices.layer),\n@@ -1379,7 +1454,7 @@ describe("ClaudeAdapterLive", () => {\n \n yield* adapter.startSession({\n threadId: THREAD_ID,\n- provider: "claudeAgent",\n+ provider: ProviderDriverKind.make("claudeAgent"),\n runtimeMode: "full-access",\n });\n \n@@ -1416,7 +1491,7 @@ describe("ClaudeAdapterLive", () => {\n \n yield* adapter.startSession({\n threadId: THREAD_ID,\n- provider: "claudeAgent",\n+ provider: ProviderDriverKind.make("claudeAgent"),\n runtimeMode: "full-access",\n });\n \n@@ -1463,7 +1538,7 @@ describe("ClaudeAdapterLive", () => {\n \n yield* adapter.startSession({\n threadId: THREAD_ID,\n- provider: "claudeAgent",\n+ provider: ProviderDriverKind.make("claudeAgent"),\n runtimeMode: "full-access",\n });\n \n@@ -1517,7 +1592,7 @@ describe("ClaudeAdapterLive", () => {\n \n yield* adapter.startSession({\n threadId: THREAD_ID,\n- provider: "claudeAgent",\n+ provider: ProviderDriverKind.make("claudeAgent"),\n runtimeMode: "full-access",\n });\n \n@@ -1584,7 +1659,7 @@ describe("ClaudeAdapterLive", () => {\n \n yield* adapter.startSession({\n threadId: THREAD_ID,\n- provider: "claudeAgent",\n+ provider: ProviderDriverKind.make("claudeAgent"),\n runtimeMode: "full-access",\n });\n \n@@ -1649,7 +1724,7 @@ describe("ClaudeAdapterLive", () => {\n \n yield* adapter.startSession({\n threadId: THREAD_ID,\n- provider: "claudeAgent",\n+ provider: ProviderDriverKind.make("claudeAgent"),\n runtimeMode: "full-access",\n });\n \n@@ -1730,7 +1805,7 @@ describe("ClaudeAdapterLive", () => {\n \n const session = yield* adapter.startSession({\n threadId: THREAD_ID,\n- provider: "claudeAgent",\n+ provider: ProviderDriverKind.make("claudeAgent"),\n runtimeMode: "full-access",\n });\n \n@@ -1821,7 +1896,7 @@ describe("ClaudeAdapterLive", () => {\n \n const session = yield* adapter.startSession({\n threadId: THREAD_ID,\n- provider: "claudeAgent",\n+ provider: ProviderDriverKind.make("claudeAgent"),\n runtimeMode: "full-access",\n });\n \n@@ -1987,7 +2062,7 @@ describe("ClaudeAdapterLive", () => {\n \n const session = yield* adapter.startSession({\n threadId: THREAD_ID,\n- provider: "claudeAgent",\n+ provider: ProviderDriverKind.make("claudeAgent"),\n runtimeMode: "full-access",\n });\n \n@@ -2056,7 +2131,7 @@ describe("ClaudeAdapterLive", () => {\n \n const session = yield* adapter.startSession({\n threadId: THREAD_ID,\n- provider: "claudeAgent",\n+ provider: ProviderDriverKind.make("claudeAgent"),\n runtimeMode: "full-access",\n });\n \n@@ -2278,7 +2353,7 @@ describe("ClaudeAdapterLive", () => {\n \n const session = yield* adapter.startSession({\n threadId: THREAD_ID,\n- provider: "claudeAgent",\n+ provider: ProviderDriverKind.make("claudeAgent"),\n runtimeMode: "full-access",\n });\n assert.equal(session.threadId, THREAD_ID);\n@@ -2351,7 +2426,7 @@ describe("ClaudeAdapterLive", () => {\n \n const session = yield* adapter.startSession({\n threadId: THREAD_ID,\n- provider: "claudeAgent",\n+ provider: ProviderDriverKind.make("claudeAgent"),\n runtimeMode: "approval-required",\n });\n \n@@ -2460,7 +2535,7 @@ describe("ClaudeAdapterLive", () => {\n \n const session = yield* adapter.startSession({\n threadId: THREAD_ID,\n- provider: "claudeAgent",\n+ provider: ProviderDriverKind.make("claudeAgent"),\n runtimeMode: "approval-required",\n });\n \n@@ -2533,7 +2608,7 @@ describe("ClaudeAdapterLive", () => {\n \n const session = yield* adapter.startSession({\n threadId: RESUME_THREAD_ID,\n- provider: "claudeAgent",\n+ provider: ProviderDriverKind.make("claudeAgent"),\n resumeCursor: {\n threadId: "resume-thread-1",\n resume: "550e8400-e29b-41d4-a716-446655440000",\n@@ -2575,7 +2650,7 @@ describe("ClaudeAdapterLive", () => {\n \n yield* adapter.startSession({\n threadId: RESUME_THREAD_ID,\n- provider: "claudeAgent",\n+ provider: ProviderDriverKind.make("claudeAgent"),\n resumeCursor: {\n threadId: RESUME_THREAD_ID,\n resume: durableSessionId,\n@@ -2658,7 +2733,7 @@ describe("ClaudeAdapterLive", () => {\n \n const session = yield* adapter.startSession({\n threadId: THREAD_ID,\n- provider: "claudeAgent",\n+ provider: ProviderDriverKind.make("claudeAgent"),\n runtimeMode: "full-access",\n });\n \n@@ -2692,7 +2767,7 @@ describe("ClaudeAdapterLive", () => {\n \n const session = yield* adapter.startSession({\n threadId: THREAD_ID,\n- provider: "claudeAgent",\n+ provider: ProviderDriverKind.make("claudeAgent"),\n runtimeMode: "full-access",\n });\n \n@@ -2772,14 +2847,14 @@ describe("ClaudeAdapterLive", () => {\n \n const session = yield* adapter.startSession({\n threadId: THREAD_ID,\n- provider: "claudeAgent",\n+ provider: ProviderDriverKind.make("claudeAgent"),\n runtimeMode: "full-access",\n });\n yield* adapter.sendTurn({\n threadId: session.threadId,\n input: "hello",\n modelSelection: {\n- provider: "claudeAgent",\n+ instanceId: ProviderInstanceId.make("claudeAgent"),\n model: "claude-opus-4-6",\n },\n attachments: [],\n@@ -2792,6 +2867,34 @@ describe("ClaudeAdapterLive", () => {\n );\n });\n \n+ it.effect("updates model on sendTurn for the adapter\'s bound custom instance id", () => {\n+ const customInstanceId = ProviderInstanceId.make("claude_openrouter");\n+ const harness = makeHarness({ instanceId: customInstanceId });\n+ return Effect.gen(function* () {\n+ const adapter = yield* ClaudeAdapter;\n+\n+ const session = yield* adapter.startSession({\n+ threadId: THREAD_ID,\n+ provider: ProviderDriverKind.make("claudeAgent"),\n+ runtimeMode: "full-access",\n+ });\n+ yield* adapter.sendTurn({\n+ threadId: session.threadId,\n+ input: "hello",\n+ modelSelection: {\n+ instanceId: customInstanceId,\n+ model: "openai/gpt-5.5",\n+ },\n+ attachments: [],\n+ });\n+\n+ assert.deepEqual(harness.query.setModelCalls, ["openai/gpt-5.5"]);\n+ }).pipe(\n+ Effect.provideService(Random.Random, makeDeterministicRandomService()),\n+ Effect.provide(harness.layer),\n+ );\n+ });\n+\n it.effect(\n "does not re-set the Claude model when the session already uses the same effective API model",\n () => {\n@@ -2799,13 +2902,13 @@ describe("ClaudeAdapterLive", () => {\n return Effect.gen(function* () {\n const adapter = yield* ClaudeAdapter;\n const modelSelection = {\n- provider: "claudeAgent" as const,\n+ instanceId: ProviderInstanceId.make("claudeAgent"),\n model: "claude-opus-4-6",\n };\n \n const session = yield* adapter.startSession({\n threadId: THREAD_ID,\n- provider: "claudeAgent",\n+ provider: ProviderDriverKind.make("claudeAgent"),\n modelSelection,\n runtimeMode: "full-access",\n });\n@@ -2838,23 +2941,25 @@ describe("ClaudeAdapterLive", () => {\n \n const session = yield* adapter.startSession({\n threadId: THREAD_ID,\n- provider: "claudeAgent",\n+ provider: ProviderDriverKind.make("claudeAgent"),\n runtimeMode: "full-access",\n });\n \n yield* adapter.sendTurn({\n threadId: session.threadId,\n input: "hello",\n- modelSelection: createModelSelection("claudeAgent", "claude-opus-4-6", [\n- { id: "contextWindow", value: "1m" },\n- ]),\n+ modelSelection: createModelSelection(\n+ ProviderInstanceId.make("claudeAgent"),\n+ "claude-opus-4-6",\n+ [{ id: "contextWindow", value: "1m" }],\n+ ),\n attachments: [],\n });\n yield* adapter.sendTurn({\n threadId: session.threadId,\n input: "hello again",\n modelSelection: {\n- provider: "claudeAgent",\n+ instanceId: ProviderInstanceId.make("claudeAgent"),\n model: "claude-opus-4-6",\n },\n attachments: [],\n@@ -2874,7 +2979,7 @@ describe("ClaudeAdapterLive", () => {\n \n const session = yield* adapter.startSession({\n threadId: THREAD_ID,\n- provider: "claudeAgent",\n+ provider: ProviderDriverKind.make("claudeAgent"),\n runtimeMode: "full-access",\n });\n yield* adapter.sendTurn({\n@@ -2904,7 +3009,7 @@ describe("ClaudeAdapterLive", () => {\n \n const session = yield* adapter.startSession({\n threadId: THREAD_ID,\n- provider: "claudeAgent",\n+ provider: ProviderDriverKind.make("claudeAgent"),\n runtimeMode,\n });\n \n@@ -2956,7 +3061,7 @@ describe("ClaudeAdapterLive", () => {\n \n const session = yield* adapter.startSession({\n threadId: THREAD_ID,\n- provider: "claudeAgent",\n+ provider: ProviderDriverKind.make("claudeAgent"),\n runtimeMode: "full-access",\n });\n yield* adapter.sendTurn({\n@@ -2979,7 +3084,7 @@ describe("ClaudeAdapterLive", () => {\n \n const session = yield* adapter.startSession({\n threadId: THREAD_ID,\n- provider: "claudeAgent",\n+ provider: ProviderDriverKind.make("claudeAgent"),\n runtimeMode: "full-access",\n });\n \n@@ -3045,7 +3150,7 @@ describe("ClaudeAdapterLive", () => {\n \n const session = yield* adapter.startSession({\n threadId: THREAD_ID,\n- provider: "claudeAgent",\n+ provider: ProviderDriverKind.make("claudeAgent"),\n runtimeMode: "full-access",\n });\n \n@@ -3117,7 +3222,7 @@ describe("ClaudeAdapterLive", () => {\n // Start session in approval-required mode so canUseTool fires.\n const session = yield* adapter.startSession({\n threadId: THREAD_ID,\n- provider: "claudeAgent",\n+ provider: ProviderDriverKind.make("claudeAgent"),\n runtimeMode: "approval-required",\n });\n \n@@ -3240,7 +3345,7 @@ describe("ClaudeAdapterLive", () => {\n // AskUserQuestion should still go through the user-input flow.\n const session = yield* adapter.startSession({\n threadId: THREAD_ID,\n- provider: "claudeAgent",\n+ provider: ProviderDriverKind.make("claudeAgent"),\n runtimeMode: "full-access",\n });\n \n@@ -3306,7 +3411,7 @@ describe("ClaudeAdapterLive", () => {\n \n const session = yield* adapter.startSession({\n threadId: THREAD_ID,\n- provider: "claudeAgent",\n+ provider: ProviderDriverKind.make("claudeAgent"),\n runtimeMode: "approval-required",\n });\n \n@@ -3393,7 +3498,7 @@ describe("ClaudeAdapterLive", () => {\n \n const session = yield* adapter.startSession({\n threadId: THREAD_ID,\n- provider: "claudeAgent",\n+ provider: ProviderDriverKind.make("claudeAgent"),\n runtimeMode: "full-access",\n });\n const turn = yield* adapter.sendTurn({\ndiff --git a/apps/server/src/provider/Layers/ClaudeAdapter.ts b/apps/server/src/provider/Layers/ClaudeAdapter.ts\nindex 35f326af07..c4cffbb16e 100644\n--- a/apps/server/src/provider/Layers/ClaudeAdapter.ts\n+++ b/apps/server/src/provider/Layers/ClaudeAdapter.ts\n@@ -24,8 +24,11 @@ import {\n ApprovalRequestId,\n type CanonicalItemType,\n type CanonicalRequestType,\n+ type ClaudeSettings,\n EventId,\n type ProviderApprovalDecision,\n+ ProviderDriverKind,\n+ ProviderInstanceId,\n ProviderItemId,\n type ProviderRuntimeEvent,\n type ProviderRuntimeTurnStatus,\n@@ -56,7 +59,7 @@ import {\n Exit,\n FileSystem,\n Fiber,\n- Layer,\n+ Path,\n Queue,\n Random,\n Ref,\n@@ -65,7 +68,7 @@ import {\n \n import { resolveAttachmentPath } from "../../attachmentStore.ts";\n import { ServerConfig } from "../../config.ts";\n-import { ServerSettingsService } from "../../serverSettings.ts";\n+import { makeClaudeEnvironment } from "../Drivers/ClaudeHome.ts";\n import {\n getClaudeModelCapabilities,\n normalizeClaudeCliEffort,\n@@ -80,10 +83,10 @@ import {\n ProviderAdapterValidationError,\n type ProviderAdapterError,\n } from "../Errors.ts";\n-import { ClaudeAdapter, type ClaudeAdapterShape } from "../Services/ClaudeAdapter.ts";\n+import { type ClaudeAdapterShape } from "../Services/ClaudeAdapter.ts";\n import { type EventNdjsonLogger, makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";\n \n-const PROVIDER = "claudeAgent" as const;\n+const PROVIDER = ProviderDriverKind.make("claudeAgent");\n type ClaudeTextStreamKind = Extract<RuntimeContentStreamKind, "assistant_text" | "reasoning_text">;\n type ClaudeToolResultStreamKind = Extract<\n RuntimeContentStreamKind,\n@@ -182,6 +185,8 @@ interface ClaudeQueryRuntime extends AsyncIterable<SDKMessage> {\n }\n \n export interface ClaudeAdapterLiveOptions {\n+ readonly instanceId?: ProviderInstanceId;\n+ readonly environment?: NodeJS.ProcessEnv;\n readonly createQuery?: (input: {\n readonly prompt: AsyncIterable<SDKUserMessage>;\n readonly options: ClaudeQueryOptions;\n@@ -565,13 +570,16 @@ const CLAUDE_SETTING_SOURCES = [\n "local",\n ] as const satisfies ReadonlyArray<SettingSource>;\n \n-function buildPromptText(input: ProviderSendTurnInput): string {\n+function buildPromptText(\n+ input: ProviderSendTurnInput,\n+ boundInstanceId: ProviderInstanceId,\n+): string {\n const rawEffort =\n- input.modelSelection?.provider === "claudeAgent"\n+ input.modelSelection?.instanceId === boundInstanceId\n ? getModelSelectionStringOptionValue(input.modelSelection, "effort")\n : null;\n const claudeModel =\n- input.modelSelection?.provider === "claudeAgent" ? input.modelSelection.model : undefined;\n+ input.modelSelection?.instanceId === boundInstanceId ? input.modelSelection.model : undefined;\n const caps = getClaudeModelCapabilities(claudeModel);\n \n const promptEffort = resolvePromptInjectedEffort(caps, rawEffort);\n@@ -611,9 +619,10 @@ const buildUserMessageEffect = Effect.fn("buildUserMessageEffect")(function* (\n dependencies: {\n readonly fileSystem: FileSystem.FileSystem;\n readonly attachmentsDir: string;\n+ readonly boundInstanceId: ProviderInstanceId;\n },\n ) {\n- const text = buildPromptText(input);\n+ const text = buildPromptText(input, dependencies.boundInstanceId);\n const sdkContent: Array<Record<string, unknown>> = [];\n \n if (text.length > 0) {\n@@ -963,11 +972,17 @@ function sdkNativeItemId(message: SDKMessage): string | undefined {\n return undefined;\n }\n \n-const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (\n+export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (\n+ claudeSettings: ClaudeSettings,\n options?: ClaudeAdapterLiveOptions,\n ) {\n+ const boundInstanceId = options?.instanceId ?? ProviderInstanceId.make("claudeAgent");\n const fileSystem = yield* FileSystem.FileSystem;\n+ const path = yield* Path.Path;\n const serverConfig = yield* ServerConfig;\n+ const claudeEnvironment = yield* makeClaudeEnvironment(claudeSettings, options?.environment).pipe(\n+ Effect.provideService(Path.Path, path),\n+ );\n const nativeEventLogger =\n options?.nativeEventLogger ??\n (options?.nativeEventLogPath !== undefined\n@@ -989,7 +1004,6 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (\n \n const sessions = new Map<ThreadId, ClaudeSessionContext>();\n const runtimeEventQueue = yield* Queue.unbounded<ProviderRuntimeEvent>();\n- const serverSettingsService = yield* ServerSettingsService;\n \n const nowIso = Effect.map(DateTime.now, DateTime.formatIso);\n const nextEventId = Effect.map(Random.nextUUIDv4, (id) => EventId.make(id));\n@@ -2820,22 +2834,10 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (\n const canUseTool: CanUseTool = (toolName, toolInput, callbackOptions) =>\n runPromise(canUseToolEffect(toolName, toolInput, callbackOptions));\n \n- const claudeSettings = yield* serverSettingsService.getSettings.pipe(\n- Effect.map((settings) => settings.providers.claudeAgent),\n- Effect.mapError(\n- (error) =>\n- new ProviderAdapterProcessError({\n- provider: PROVIDER,\n- threadId: input.threadId,\n- detail: error.message,\n- cause: error,\n- }),\n- ),\n- );\n const claudeBinaryPath = claudeSettings.binaryPath;\n const extraArgs = parseCliArgs(claudeSettings.launchArgs).flags;\n const modelSelection =\n- input.modelSelection?.provider === "claudeAgent" ? input.modelSelection : undefined;\n+ input.modelSelection?.instanceId === boundInstanceId ? input.modelSelection : undefined;\n const caps = getClaudeModelCapabilities(modelSelection?.model);\n const descriptors = getProviderOptionDescriptors({ caps });\n const apiModelId = modelSelection ? resolveClaudeApiModelId(modelSelection) : undefined;\n@@ -2863,7 +2865,6 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (\n ...(typeof thinking === "boolean" ? { alwaysThinkingEnabled: thinking } : {}),\n ...(fastMode ? { fastMode: true } : {}),\n };\n-\n const queryOptions: ClaudeQueryOptions = {\n ...(input.cwd ? { cwd: input.cwd } : {}),\n ...(apiModelId ? { model: apiModelId } : {}),\n@@ -2885,7 +2886,7 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (\n ...(newSessionId ? { sessionId: newSessionId } : {}),\n includePartialMessages: true,\n canUseTool,\n- env: process.env,\n+ env: claudeEnvironment,\n ...(input.cwd ? { additionalDirectories: [input.cwd] } : {}),\n ...(Object.keys(extraArgs).length > 0 ? { extraArgs } : {}),\n };\n@@ -2933,6 +2934,7 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (\n const session: ProviderSession = {\n threadId,\n provider: PROVIDER,\n+ providerInstanceId: boundInstanceId,\n status: "ready",\n runtimeMode: input.runtimeMode,\n ...(input.cwd ? { cwd: input.cwd } : {}),\n@@ -3044,7 +3046,9 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (\n const sendTurn: ClaudeAdapterShape["sendTurn"] = Effect.fn("sendTurn")(function* (input) {\n const context = yield* requireSession(input.threadId);\n const modelSelection =\n- input.modelSelection?.provider === "claudeAgent" ? input.modelSelection : undefined;\n+ input.modelSelection !== undefined && input.modelSelection.instanceId === boundInstanceId\n+ ? input.modelSelection\n+ : undefined;\n \n if (context.turnState) {\n // Auto-close a stale synthetic turn (from background agent responses\n@@ -3118,6 +3122,7 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (\n const message = yield* buildUserMessageEffect(input, {\n fileSystem,\n attachmentsDir: serverConfig.attachmentsDir,\n+ boundInstanceId,\n });\n \n yield* Queue.offer(context.promptQueue, {\n@@ -3255,9 +3260,3 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (\n },\n } satisfies ClaudeAdapterShape;\n });\n-\n-export const ClaudeAdapterLive = Layer.effect(ClaudeAdapter, makeClaudeAdapter());\n-\n-export function makeClaudeAdapterLive(options?: ClaudeAdapterLiveOptions) {\n- return Layer.effect(ClaudeAdapter, makeClaudeAdapter(options));\n-}\ndiff --git a/apps/server/src/provider/Layers/ClaudeProvider.ts b/apps/server/src/provider/Layers/ClaudeProvider.ts\nindex f41082bbba..4350596700 100644\n--- a/apps/server/src/provider/Layers/ClaudeProvider.ts\n+++ b/apps/server/src/provider/Layers/ClaudeProvider.ts\n@@ -1,16 +1,13 @@\n-import type {\n- ClaudeSettings,\n- ClaudeModelSelection,\n- ModelCapabilities,\n- ServerProvider,\n- ServerProviderModel,\n- ServerProviderAuth,\n- ServerProviderSlashCommand,\n- ServerProviderState,\n+import {\n+ type ClaudeSettings,\n+ type ModelCapabilities,\n+ type ModelSelection,\n+ ProviderDriverKind,\n+ type ServerProviderModel,\n+ type ServerProviderSlashCommand,\n } from "@t3tools/contracts";\n-import { Cache, Duration, Effect, Equal, Layer, Option, Result, Schema, Stream } from "effect";\n+import { Effect, Option, Path, Result } from "effect";\n import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";\n-import { decodeJsonResult } from "@t3tools/shared/schemaJson";\n import {\n createModelCapabilities,\n getModelSelectionStringOptionValue,\n@@ -27,27 +24,22 @@ import {\n buildBooleanOptionDescriptor,\n buildSelectOptionDescriptor,\n buildServerProvider,\n- AUTH_PROBE_TIMEOUT_MS,\n DEFAULT_TIMEOUT_MS,\n detailFromResult,\n- extractAuthBoolean,\n isCommandMissingCause,\n parseGenericCliVersion,\n providerModelsFromSettings,\n spawnAndCollect,\n- type CommandResult,\n+ type ServerProviderDraft,\n } from "../providerSnapshot.ts";\n import { compareCliVersions } from "../cliVersion.ts";\n-import { makeManagedServerProvider } from "../makeManagedServerProvider.ts";\n-import { ClaudeProvider } from "../Services/ClaudeProvider.ts";\n-import { ServerSettingsService } from "../../serverSettings.ts";\n-import { ServerSettingsError } from "@t3tools/contracts";\n+import { makeClaudeEnvironment } from "../Drivers/ClaudeHome.ts";\n \n const DEFAULT_CLAUDE_MODEL_CAPABILITIES: ModelCapabilities = createModelCapabilities({\n optionDescriptors: [],\n });\n \n-const PROVIDER = "claudeAgent" as const;\n+const PROVIDER = ProviderDriverKind.make("claudeAgent");\n const CLAUDE_PRESENTATION = {\n displayName: "Claude",\n showInteractionModeToggle: true,\n@@ -242,7 +234,7 @@ export function normalizeClaudeCliEffort(effort: string | null | undefined): str\n return effort;\n }\n \n-export function resolveClaudeApiModelId(modelSelection: ClaudeModelSelection): string {\n+export function resolveClaudeApiModelId(modelSelection: ModelSelection): string {\n switch (getModelSelectionStringOptionValue(modelSelection, "contextWindow")) {\n case "1m":\n return `${modelSelection.model}[1m]`;\n@@ -250,181 +242,6 @@ export function resolveClaudeApiModelId(modelSelection: ClaudeModelSelection): s\n return modelSelection.model;\n }\n }\n-export function parseClaudeAuthStatusFromOutput(result: CommandResult): {\n- readonly status: Exclude<ServerProviderState, "disabled">;\n- readonly auth: Pick<ServerProviderAuth, "status">;\n- readonly message?: string;\n-} {\n- const lowerOutput = `${result.stdout}\\n${result.stderr}`.toLowerCase();\n-\n- if (\n- lowerOutput.includes("unknown command") ||\n- lowerOutput.includes("unrecognized command") ||\n- lowerOutput.includes("unexpected argument")\n- ) {\n- return {\n- status: "warning",\n- auth: { status: "unknown" },\n- message:\n- "Claude Agent authentication status command is unavailable in this version of Claude.",\n- };\n- }\n-\n- if (\n- lowerOutput.includes("not logged in") ||\n- lowerOutput.includes("login required") ||\n- lowerOutput.includes("authentication required") ||\n- lowerOutput.includes("run `claude login`") ||\n- lowerOutput.includes("run claude login")\n- ) {\n- return {\n- status: "error",\n- auth: { status: "unauthenticated" },\n- message: "Claude is not authenticated. Run `claude auth login` and try again.",\n- };\n- }\n-\n- const parsedAuth = (() => {\n- const trimmed = result.stdout.trim();\n- if (!trimmed || (!trimmed.startsWith("{") && !trimmed.startsWith("["))) {\n- return { attemptedJsonParse: false as const, auth: undefined as boolean | undefined };\n- }\n- try {\n- return {\n- attemptedJsonParse: true as const,\n- auth: extractAuthBoolean(JSON.parse(trimmed)),\n- };\n- } catch {\n- return { attemptedJsonParse: false as const, auth: undefined as boolean | undefined };\n- }\n- })();\n-\n- if (parsedAuth.auth === true) {\n- return { status: "ready", auth: { status: "authenticated" } };\n- }\n- if (parsedAuth.auth === false) {\n- return {\n- status: "error",\n- auth: { status: "unauthenticated" },\n- message: "Claude is not authenticated. Run `claude auth login` and try again.",\n- };\n- }\n- if (parsedAuth.attemptedJsonParse) {\n- return {\n- status: "warning",\n- auth: { status: "unknown" },\n- message:\n- "Could not verify Claude authentication status from JSON output (missing auth marker).",\n- };\n- }\n- if (result.code === 0) {\n- return { status: "ready", auth: { status: "authenticated" } };\n- }\n-\n- const detail = detailFromResult(result);\n- return {\n- status: "warning",\n- auth: { status: "unknown" },\n- message: detail\n- ? `Could not verify Claude authentication status. ${detail}`\n- : "Could not verify Claude authentication status.",\n- };\n-}\n-\n-// ── Subscription type detection ─────────────────────────────────────\n-//\n-// The SDK probe returns typed `AccountInfo.subscriptionType` directly.\n-// This walker is a best-effort fallback for the `claude auth status`\n-// JSON output whose shape is not guaranteed.\n-\n-/** Keys that directly hold a subscription/plan identifier. */\n-const SUBSCRIPTION_TYPE_KEYS = [\n- "subscriptionType",\n- "subscription_type",\n- "plan",\n- "tier",\n- "planType",\n- "plan_type",\n-] as const;\n-\n-/** Keys whose value may be a nested object containing subscription info. */\n-const SUBSCRIPTION_CONTAINER_KEYS = ["account", "subscription", "user", "billing"] as const;\n-const AUTH_METHOD_KEYS = ["authMethod", "auth_method"] as const;\n-const AUTH_METHOD_CONTAINER_KEYS = ["auth", "account", "session"] as const;\n-\n-/** Lift an unknown value into `Option<string>` if it is a non-empty string. */\n-const asNonEmptyString = (v: unknown): Option.Option<string> =>\n- typeof v === "string" && v.length > 0 ? Option.some(v) : Option.none();\n-\n-/** Lift an unknown value into `Option<Record>` if it is a plain object. */\n-const asRecord = (v: unknown): Option.Option<Record<string, unknown>> =>\n- typeof v === "object" && v !== null && !globalThis.Array.isArray(v)\n- ? Option.some(v as Record<string, unknown>)\n- : Option.none();\n-\n-/**\n- * Walk an unknown parsed JSON value looking for a subscription/plan\n- * identifier, returning the first match as an `Option`.\n- */\n-function findSubscriptionType(value: unknown): Option.Option<string> {\n- if (globalThis.Array.isArray(value)) {\n- return Option.firstSomeOf(value.map(findSubscriptionType));\n- }\n-\n- return asRecord(value).pipe(\n- Option.flatMap((record) => {\n- const direct = Option.firstSomeOf(\n- SUBSCRIPTION_TYPE_KEYS.map((key) => asNonEmptyString(record[key])),\n- );\n- if (Option.isSome(direct)) return direct;\n-\n- return Option.firstSomeOf(\n- SUBSCRIPTION_CONTAINER_KEYS.map((key) =>\n- asRecord(record[key]).pipe(Option.flatMap(findSubscriptionType)),\n- ),\n- );\n- }),\n- );\n-}\n-\n-function findAuthMethod(value: unknown): Option.Option<string> {\n- if (globalThis.Array.isArray(value)) {\n- return Option.firstSomeOf(value.map(findAuthMethod));\n- }\n-\n- return asRecord(value).pipe(\n- Option.flatMap((record) => {\n- const direct = Option.firstSomeOf(\n- AUTH_METHOD_KEYS.map((key) => asNonEmptyString(record[key])),\n- );\n- if (Option.isSome(direct)) return direct;\n-\n- return Option.firstSomeOf(\n- AUTH_METHOD_CONTAINER_KEYS.map((key) =>\n- asRecord(record[key]).pipe(Option.flatMap(findAuthMethod)),\n- ),\n- );\n- }),\n- );\n-}\n-\n-/**\n- * Try to extract a subscription type from the `claude auth status` JSON\n- * output. This is a zero-cost operation on data we already have.\n- */\n-const decodeUnknownJson = decodeJsonResult(Schema.Unknown);\n-\n-function extractSubscriptionTypeFromOutput(result: CommandResult): string | undefined {\n- const parsed = decodeUnknownJson(result.stdout.trim());\n- if (Result.isFailure(parsed)) return undefined;\n- return Option.getOrUndefined(findSubscriptionType(parsed.success));\n-}\n-\n-function extractClaudeAuthMethodFromOutput(result: CommandResult): string | undefined {\n- const parsed = decodeUnknownJson(result.stdout.trim());\n- if (Result.isFailure(parsed)) return undefined;\n- return Option.getOrUndefined(findAuthMethod(parsed.success));\n-}\n \n function toTitleCaseWords(value: string): string {\n return value\n@@ -439,11 +256,27 @@ function claudeSubscriptionLabel(subscriptionType: string | undefined): string |\n if (!normalized) return undefined;\n \n switch (normalized) {\n+ case "claudemaxsubscription":\n+ return "Max";\n+ case "claudemax5xsubscription":\n+ return "Max 5x";\n+ case "claudemax20xsubscription":\n+ return "Max 20x";\n+ case "claudeenterprisesubscription":\n+ return "Enterprise";\n+ case "claudeteamsubscription":\n+ return "Team";\n+ case "claudeprosubscription":\n+ return "Pro";\n+ case "claudefreesubscription":\n+ return "Free";\n case "max":\n case "maxplan":\n+ return "Max";\n case "max5":\n+ return "Max 5x";\n case "max20":\n- return "Max";\n+ return "Max 20x";\n case "enterprise":\n return "Enterprise";\n case "team":\n@@ -460,10 +293,33 @@ function claudeSubscriptionLabel(subscriptionType: string | undefined): string |\n function normalizeClaudeAuthMethod(authMethod: string | undefined): string | undefined {\n const normalized = authMethod?.toLowerCase().replace(/[\\s_-]+/g, "");\n if (!normalized) return undefined;\n- if (normalized === "apikey") return "apiKey";\n+ if (\n+ normalized === "apikey" ||\n+ normalized === "anthropicapikey" ||\n+ normalized === "anthropicauthtoken"\n+ ) {\n+ return "apiKey";\n+ }\n return undefined;\n }\n \n+function formatClaudeSubscriptionAuthLabel(subscriptionType: string): string {\n+ const subscriptionLabel =\n+ claudeSubscriptionLabel(subscriptionType) ?? toTitleCaseWords(subscriptionType);\n+ const normalized = subscriptionLabel.toLowerCase().replace(/[\\s_-]+/g, "");\n+\n+ if (normalized.startsWith("claude") && normalized.endsWith("subscription")) {\n+ return subscriptionLabel;\n+ }\n+ if (normalized.startsWith("claude")) {\n+ return `${subscriptionLabel} Subscription`;\n+ }\n+ if (normalized.endsWith("subscription")) {\n+ return `Claude ${subscriptionLabel}`;\n+ }\n+ return `Claude ${subscriptionLabel} Subscription`;\n+}\n+\n function claudeAuthMetadata(input: {\n readonly subscriptionType: string | undefined;\n readonly authMethod: string | undefined;\n@@ -476,10 +332,9 @@ function claudeAuthMetadata(input: {\n }\n \n if (input.subscriptionType) {\n- const subscriptionLabel = claudeSubscriptionLabel(input.subscriptionType);\n return {\n type: input.subscriptionType,\n- label: `Claude ${subscriptionLabel ?? toTitleCaseWords(input.subscriptionType)} Subscription`,\n+ label: formatClaudeSubscriptionAuthLabel(input.subscriptionType),\n };\n }\n \n@@ -495,6 +350,13 @@ function nonEmptyProbeString(value: string): string | undefined {\n return candidate ? candidate : undefined;\n }\n \n+type ClaudeCapabilitiesProbe = {\n+ readonly email: string | undefined;\n+ readonly subscriptionType: string | undefined;\n+ readonly tokenSource: string | undefined;\n+ readonly slashCommands: ReadonlyArray<ServerProviderSlashCommand>;\n+};\n+\n function parseClaudeInitializationCommands(\n commands: ReadonlyArray<ClaudeSlashCommand> | undefined,\n ): ReadonlyArray<ServerProviderSlashCommand> {\n@@ -580,30 +442,46 @@ function waitForAbortSignal(signal: AbortSignal): Promise<void> {\n * This is used as a fallback when `claude auth status` does not include\n * subscription type information.\n */\n-const probeClaudeCapabilities = (binaryPath: string) => {\n+const probeClaudeCapabilities = (\n+ claudeSettings: ClaudeSettings,\n+ environment: NodeJS.ProcessEnv = process.env,\n+) => {\n const abort = new AbortController();\n- return Effect.tryPromise(async () => {\n- const q = claudeQuery({\n- // Never yield — we only need initialization data, not a conversation.\n- // This prevents any prompt from reaching the Anthropic API.\n- // oxlint-disable-next-line require-yield\n- prompt: (async function* (): AsyncGenerator<SDKUserMessage> {\n- await waitForAbortSignal(abort.signal);\n- })(),\n- options: {\n- persistSession: false,\n- pathToClaudeCodeExecutable: binaryPath,\n- abortController: abort,\n- settingSources: ["user", "project", "local"],\n- allowedTools: [],\n- stderr: () => {},\n- },\n+ return Effect.gen(function* () {\n+ const claudeEnvironment = yield* makeClaudeEnvironment(claudeSettings, environment);\n+ return yield* Effect.tryPromise(async () => {\n+ const q = claudeQuery({\n+ // Never yield — we only need initialization data, not a conversation.\n+ // This prevents any prompt from reaching the Anthropic API.\n+ // oxlint-disable-next-line require-yield\n+ prompt: (async function* (): AsyncGenerator<SDKUserMessage> {\n+ await waitForAbortSignal(abort.signal);\n+ })(),\n+ options: {\n+ persistSession: false,\n+ pathToClaudeCodeExecutable: claudeSettings.binaryPath,\n+ abortController: abort,\n+ settingSources: ["user", "project", "local"],\n+ allowedTools: [],\n+ env: claudeEnvironment,\n+ stderr: () => {},\n+ },\n+ });\n+ const init = await q.initializationResult();\n+ const account = init.account as\n+ | {\n+ readonly email?: string;\n+ readonly subscriptionType?: string;\n+ readonly tokenSource?: string;\n+ }\n+ | undefined;\n+ return {\n+ email: account?.email,\n+ subscriptionType: account?.subscriptionType,\n+ tokenSource: account?.tokenSource,\n+ slashCommands: parseClaudeInitializationCommands(init.commands),\n+ } satisfies ClaudeCapabilitiesProbe;\n });\n- const init = await q.initializationResult();\n- return {\n- subscriptionType: init.account?.subscriptionType,\n- slashCommands: parseClaudeInitializationCommands(init.commands),\n- };\n }).pipe(\n Effect.ensuring(\n Effect.sync(() => {\n@@ -619,31 +497,30 @@ const probeClaudeCapabilities = (binaryPath: string) => {\n );\n };\n \n-const runClaudeCommand = Effect.fn("runClaudeCommand")(function* (args: ReadonlyArray<string>) {\n- const claudeSettings = yield* Effect.service(ServerSettingsService).pipe(\n- Effect.flatMap((service) => service.getSettings),\n- Effect.map((settings) => settings.providers.claudeAgent),\n- );\n+const runClaudeCommand = Effect.fn("runClaudeCommand")(function* (\n+ claudeSettings: ClaudeSettings,\n+ args: ReadonlyArray<string>,\n+ environment: NodeJS.ProcessEnv = process.env,\n+) {\n+ const claudeEnvironment = yield* makeClaudeEnvironment(claudeSettings, environment);\n const command = ChildProcess.make(claudeSettings.binaryPath, [...args], {\n+ env: claudeEnvironment,\n shell: process.platform === "win32",\n });\n return yield* spawnAndCollect(claudeSettings.binaryPath, command);\n });\n \n export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(function* (\n- resolveSubscriptionType?: (binaryPath: string) => Effect.Effect<string | undefined>,\n- resolveSlashCommands?: (\n- binaryPath: string,\n- ) => Effect.Effect<ReadonlyArray<ServerProviderSlashCommand> | undefined>,\n+ claudeSettings: ClaudeSettings,\n+ resolveCapabilities?: (\n+ claudeSettings: ClaudeSettings,\n+ ) => Effect.Effect<ClaudeCapabilitiesProbe | undefined>,\n+ environment: NodeJS.ProcessEnv = process.env,\n ): Effect.fn.Return<\n- ServerProvider,\n- ServerSettingsError,\n- ChildProcessSpawner.ChildProcessSpawner | ServerSettingsService\n+ ServerProviderDraft,\n+ never,\n+ ChildProcessSpawner.ChildProcessSpawner | Path.Path\n > {\n- const claudeSettings = yield* Effect.service(ServerSettingsService).pipe(\n- Effect.flatMap((service) => service.getSettings),\n- Effect.map((settings) => settings.providers.claudeAgent),\n- );\n const checkedAt = new Date().toISOString();\n const allModels = providerModelsFromSettings(\n BUILT_IN_MODELS,\n@@ -654,7 +531,6 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(\n \n if (!claudeSettings.enabled) {\n return buildServerProvider({\n- provider: PROVIDER,\n presentation: CLAUDE_PRESENTATION,\n enabled: false,\n checkedAt,\n@@ -669,7 +545,7 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(\n });\n }\n \n- const versionProbe = yield* runClaudeCommand(["--version"]).pipe(\n+ const versionProbe = yield* runClaudeCommand(claudeSettings, ["--version"], environment).pipe(\n Effect.timeoutOption(DEFAULT_TIMEOUT_MS),\n Effect.result,\n );\n@@ -677,7 +553,6 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(\n if (Result.isFailure(versionProbe)) {\n const error = versionProbe.failure;\n return buildServerProvider({\n- provider: PROVIDER,\n presentation: CLAUDE_PRESENTATION,\n enabled: claudeSettings.enabled,\n checkedAt,\n@@ -696,7 +571,6 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(\n \n if (Option.isNone(versionProbe.success)) {\n return buildServerProvider({\n- provider: PROVIDER,\n presentation: CLAUDE_PRESENTATION,\n enabled: claudeSettings.enabled,\n checkedAt,\n@@ -717,7 +591,6 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(\n if (version.code !== 0) {\n const detail = detailFromResult(version);\n return buildServerProvider({\n- provider: PROVIDER,\n presentation: CLAUDE_PRESENTATION,\n enabled: claudeSettings.enabled,\n checkedAt,\n@@ -744,66 +617,14 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(\n ? undefined\n : formatClaudeOpus47UpgradeMessage(parsedVersion);\n \n- const slashCommands =\n- (resolveSlashCommands\n- ? yield* resolveSlashCommands(claudeSettings.binaryPath).pipe(\n- Effect.orElseSucceed(() => undefined),\n- )\n- : undefined) ?? [];\n+ const capabilities = resolveCapabilities\n+ ? yield* resolveCapabilities(claudeSettings).pipe(Effect.orElseSucceed(() => undefined))\n+ : undefined;\n+ const slashCommands = capabilities?.slashCommands ?? [];\n const dedupedSlashCommands = dedupeSlashCommands(slashCommands);\n \n- // ── Auth check + subscription detection ────────────────────────────\n-\n- const authProbe = yield* runClaudeCommand(["auth", "status"]).pipe(\n- Effect.timeoutOption(AUTH_PROBE_TIMEOUT_MS),\n- Effect.result,\n- );\n-\n- // Determine subscription type from multiple sources (cheapest first):\n- // 1. `claude auth status` JSON output (may or may not contain it)\n- // 2. Cached SDK probe (spawns a Claude process on miss, reads\n- // `initializationResult()` for account metadata, then aborts\n- // immediately — no API tokens are consumed)\n-\n- let subscriptionType: string | undefined;\n- let authMethod: string | undefined;\n-\n- if (Result.isSuccess(authProbe) && Option.isSome(authProbe.success)) {\n- subscriptionType = extractSubscriptionTypeFromOutput(authProbe.success.value);\n- authMethod = extractClaudeAuthMethodFromOutput(authProbe.success.value);\n- }\n-\n- if (!subscriptionType && resolveSubscriptionType) {\n- subscriptionType = yield* resolveSubscriptionType(claudeSettings.binaryPath);\n- }\n-\n- // ── Handle auth results (same logic as before, adjusted models) ──\n-\n- if (Result.isFailure(authProbe)) {\n- const error = authProbe.failure;\n- return buildServerProvider({\n- provider: PROVIDER,\n- presentation: CLAUDE_PRESENTATION,\n- enabled: claudeSettings.enabled,\n- checkedAt,\n- models,\n- slashCommands: dedupedSlashCommands,\n- probe: {\n- installed: true,\n- version: parsedVersion,\n- status: "warning",\n- auth: { status: "unknown" },\n- message:\n- error instanceof Error\n- ? `Could not verify Claude authentication status: ${error.message}.`\n- : "Could not verify Claude authentication status.",\n- },\n- });\n- }\n-\n- if (Option.isNone(authProbe.success)) {\n+ if (!capabilities) {\n return buildServerProvider({\n- provider: PROVIDER,\n presentation: CLAUDE_PRESENTATION,\n enabled: claudeSettings.enabled,\n checkedAt,\n@@ -814,15 +635,16 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(\n version: parsedVersion,\n status: "warning",\n auth: { status: "unknown" },\n- message: "Could not verify Claude authentication status. Timed out while running command.",\n+ message: "Could not verify Claude authentication status from initialization result.",\n },\n });\n }\n \n- const parsed = parseClaudeAuthStatusFromOutput(authProbe.success.value);\n- const authMetadata = claudeAuthMetadata({ subscriptionType, authMethod });\n+ const authMetadata = claudeAuthMetadata({\n+ subscriptionType: capabilities.subscriptionType,\n+ authMethod: capabilities.tokenSource,\n+ });\n return buildServerProvider({\n- provider: PROVIDER,\n presentation: CLAUDE_PRESENTATION,\n enabled: claudeSettings.enabled,\n checkedAt,\n@@ -831,21 +653,18 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(\n probe: {\n installed: true,\n version: parsedVersion,\n- status: parsed.status,\n+ status: "ready",\n auth: {\n- ...parsed.auth,\n+ status: "authenticated",\n+ ...(capabilities.email ? { email: capabilities.email } : {}),\n ...(authMetadata ? authMetadata : {}),\n },\n- ...(parsed.message\n- ? { message: parsed.message }\n- : opus47UpgradeMessage\n- ? { message: opus47UpgradeMessage }\n- : {}),\n+ ...(opus47UpgradeMessage ? { message: opus47UpgradeMessage } : {}),\n },\n });\n });\n \n-const makePendingClaudeProvider = (claudeSettings: ClaudeSettings): ServerProvider => {\n+export const makePendingClaudeProvider = (claudeSettings: ClaudeSettings): ServerProviderDraft => {\n const checkedAt = new Date().toISOString();\n const models = providerModelsFromSettings(\n BUILT_IN_MODELS,\n@@ -856,7 +675,6 @@ const makePendingClaudeProvider = (claudeSettings: ClaudeSettings): ServerProvid\n \n if (!claudeSettings.enabled) {\n return buildServerProvider({\n- provider: PROVIDER,\n presentation: CLAUDE_PRESENTATION,\n enabled: false,\n checkedAt,\n@@ -872,7 +690,6 @@ const makePendingClaudeProvider = (claudeSettings: ClaudeSettings): ServerProvid\n }\n \n return buildServerProvider({\n- provider: PROVIDER,\n presentation: CLAUDE_PRESENTATION,\n enabled: true,\n checkedAt,\n@@ -887,43 +704,4 @@ const makePendingClaudeProvider = (claudeSettings: ClaudeSettings): ServerProvid\n });\n };\n \n-export const ClaudeProviderLive = Layer.effect(\n- ClaudeProvider,\n- Effect.gen(function* () {\n- const serverSettings = yield* ServerSettingsService;\n- const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;\n-\n- const subscriptionProbeCache = yield* Cache.make({\n- capacity: 1,\n- timeToLive: Duration.minutes(5),\n- lookup: (binaryPath: string) => probeClaudeCapabilities(binaryPath),\n- });\n-\n- const checkProvider = checkClaudeProviderStatus(\n- (binaryPath) =>\n- Cache.get(subscriptionProbeCache, binaryPath).pipe(\n- Effect.map((probe) => probe?.subscriptionType),\n- ),\n- (binaryPath) =>\n- Cache.get(subscriptionProbeCache, binaryPath).pipe(\n- Effect.map((probe) => probe?.slashCommands),\n- ),\n- ).pipe(\n- Effect.provideService(ServerSettingsService, serverSettings),\n- Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),\n- );\n-\n- return yield* makeManagedServerProvider<ClaudeSettings>({\n- getSettings: serverSettings.getSettings.pipe(\n- Effect.map((settings) => settings.providers.claudeAgent),\n- Effect.orDie,\n- ),\n- streamSettings: serverSettings.streamChanges.pipe(\n- Stream.map((settings) => settings.providers.claudeAgent),\n- ),\n- haveSettingsChanged: (previous, next) => !Equal.equals(previous, next),\n- initialSnapshot: makePendingClaudeProvider,\n- checkProvider,\n- });\n- }),\n-);\n+export { probeClaudeCapabilities };\ndiff --git a/apps/server/src/provider/Layers/CodexAdapter.test.ts b/apps/server/src/provider/Layers/CodexAdapter.test.ts\nindex ad6fddab1c..4df4fb5d32 100644\n--- a/apps/server/src/provider/Layers/CodexAdapter.test.ts\n+++ b/apps/server/src/provider/Layers/CodexAdapter.test.ts\n@@ -4,7 +4,10 @@ import os from "node:os";\n import path from "node:path";\n import {\n ApprovalRequestId,\n+ CodexSettings,\n EventId,\n+ ProviderDriverKind,\n+ ProviderInstanceId,\n ProviderItemId,\n type ProviderApprovalDecision,\n type ProviderEvent,\n@@ -18,13 +21,13 @@ import { createModelSelection } from "@t3tools/shared/model";\n import * as NodeServices from "@effect/platform-node/NodeServices";\n import { it, vi } from "@effect/vitest";\n \n-import { Effect, Exit, Fiber, Layer, Option, Queue, Scope, Stream } from "effect";\n+import { Context, Effect, Exit, Fiber, Layer, Option, Queue, Schema, Scope, Stream } from "effect";\n import * as CodexErrors from "effect-codex-app-server/errors";\n \n import { ServerConfig } from "../../config.ts";\n import { ServerSettingsService } from "../../serverSettings.ts";\n import { ProviderAdapterValidationError } from "../Errors.ts";\n-import { CodexAdapter } from "../Services/CodexAdapter.ts";\n+import type { CodexAdapterShape } from "../Services/CodexAdapter.ts";\n import { ProviderSessionDirectory } from "../Services/ProviderSessionDirectory.ts";\n import {\n type CodexSessionRuntimeOptions,\n@@ -32,7 +35,12 @@ import {\n type CodexSessionRuntimeShape,\n type CodexThreadSnapshot,\n } from "./CodexSessionRuntime.ts";\n-import { makeCodexAdapterLive } from "./CodexAdapter.ts";\n+import { makeCodexAdapter } from "./CodexAdapter.ts";\n+\n+// Test-local service tag so the rest of the file can keep using `yield* CodexAdapter`.\n+class CodexAdapter extends Context.Service<CodexAdapter, CodexAdapterShape>()(\n+ "test/CodexAdapter",\n+) {}\n \n const asThreadId = (value: string): ThreadId => ThreadId.make(value);\n const asTurnId = (value: string): TurnId => TurnId.make(value);\n@@ -45,7 +53,7 @@ class FakeCodexRuntime implements CodexSessionRuntimeShape {\n \n public readonly startImpl = vi.fn(() =>\n Promise.resolve({\n- provider: "codex" as const,\n+ provider: ProviderDriverKind.make("codex"),\n status: "ready" as const,\n runtimeMode: this.options.runtimeMode,\n threadId: this.options.threadId,\n@@ -203,7 +211,15 @@ const providerSessionDirectoryTestLayer = Layer.succeed(ProviderSessionDirectory\n \n const validationRuntimeFactory = makeRuntimeFactory();\n const validationLayer = it.layer(\n- makeCodexAdapterLive({ makeRuntime: validationRuntimeFactory.factory }).pipe(\n+ Layer.effect(\n+ CodexAdapter,\n+ Effect.gen(function* () {\n+ const codexConfig = Schema.decodeSync(CodexSettings)({});\n+ return yield* makeCodexAdapter(codexConfig, {\n+ makeRuntime: validationRuntimeFactory.factory,\n+ });\n+ }),\n+ ).pipe(\n Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),\n Layer.provideMerge(ServerSettingsService.layerTest()),\n Layer.provideMerge(providerSessionDirectoryTestLayer),\n@@ -217,7 +233,7 @@ validationLayer("CodexAdapterLive validation", (it) => {\n const adapter = yield* CodexAdapter;\n const result = yield* adapter\n .startSession({\n- provider: "claudeAgent",\n+ provider: ProviderDriverKind.make("claudeAgent"),\n threadId: asThreadId("thread-1"),\n runtimeMode: "full-access",\n })\n@@ -227,7 +243,7 @@ validationLayer("CodexAdapterLive validation", (it) => {\n assert.deepStrictEqual(\n result.failure,\n new ProviderAdapterValidationError({\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n operation: "startSession",\n issue: "Expected provider \'codex\' but received \'claudeAgent\'.",\n }),\n@@ -241,9 +257,9 @@ validationLayer("CodexAdapterLive validation", (it) => {\n const adapter = yield* CodexAdapter;\n \n yield* adapter.startSession({\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n threadId: asThreadId("thread-1"),\n- modelSelection: createModelSelection("codex", "gpt-5.3-codex", [\n+ modelSelection: createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.3-codex", [\n { id: "fastMode", value: true },\n ]),\n runtimeMode: "full-access",\n@@ -253,6 +269,7 @@ validationLayer("CodexAdapterLive validation", (it) => {\n binaryPath: "codex",\n cwd: process.cwd(),\n model: "gpt-5.3-codex",\n+ providerInstanceId: ProviderInstanceId.make("codex"),\n serviceTier: "fast",\n threadId: asThreadId("thread-1"),\n runtimeMode: "full-access",\n@@ -263,7 +280,15 @@ validationLayer("CodexAdapterLive validation", (it) => {\n \n const sessionRuntimeFactory = makeRuntimeFactory();\n const sessionErrorLayer = it.layer(\n- makeCodexAdapterLive({ makeRuntime: sessionRuntimeFactory.factory }).pipe(\n+ Layer.effect(\n+ CodexAdapter,\n+ Effect.gen(function* () {\n+ const codexConfig = Schema.decodeSync(CodexSettings)({});\n+ return yield* makeCodexAdapter(codexConfig, {\n+ makeRuntime: sessionRuntimeFactory.factory,\n+ });\n+ }),\n+ ).pipe(\n Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),\n Layer.provideMerge(ServerSettingsService.layerTest()),\n Layer.provideMerge(providerSessionDirectoryTestLayer),\n@@ -294,7 +319,7 @@ sessionErrorLayer("CodexAdapterLive session errors", (it) => {\n Effect.gen(function* () {\n const adapter = yield* CodexAdapter;\n yield* adapter.startSession({\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n threadId: asThreadId("sess-missing"),\n runtimeMode: "full-access",\n });\n@@ -306,7 +331,7 @@ sessionErrorLayer("CodexAdapterLive session errors", (it) => {\n adapter.sendTurn({\n threadId: asThreadId("sess-missing"),\n input: "hello",\n- modelSelection: createModelSelection("codex", "gpt-5.3-codex", [\n+ modelSelection: createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.3-codex", [\n { id: "reasoningEffort", value: "high" },\n { id: "fastMode", value: true },\n ]),\n@@ -322,11 +347,74 @@ sessionErrorLayer("CodexAdapterLive session errors", (it) => {\n });\n }),\n );\n+\n+ it.effect("maps codex model options for the adapter\'s bound custom instance id", () => {\n+ const customInstanceId = ProviderInstanceId.make("codex_personal");\n+ const customRuntimeFactory = makeRuntimeFactory();\n+ const customLayer = Layer.effect(\n+ CodexAdapter,\n+ Effect.gen(function* () {\n+ const codexConfig = Schema.decodeSync(CodexSettings)({});\n+ return yield* makeCodexAdapter(codexConfig, {\n+ instanceId: customInstanceId,\n+ makeRuntime: customRuntimeFactory.factory,\n+ });\n+ }),\n+ ).pipe(\n+ Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),\n+ Layer.provideMerge(ServerSettingsService.layerTest()),\n+ Layer.provideMerge(providerSessionDirectoryTestLayer),\n+ Layer.provideMerge(NodeServices.layer),\n+ );\n+\n+ return Effect.gen(function* () {\n+ const adapter = yield* CodexAdapter;\n+ yield* adapter.startSession({\n+ provider: ProviderDriverKind.make("codex"),\n+ threadId: asThreadId("sess-custom-instance"),\n+ runtimeMode: "full-access",\n+ });\n+ const runtime = customRuntimeFactory.lastRuntime;\n+ assert.ok(runtime);\n+ runtime.sendTurnImpl.mockClear();\n+\n+ yield* Effect.ignore(\n+ adapter.sendTurn({\n+ threadId: asThreadId("sess-custom-instance"),\n+ input: "hello",\n+ modelSelection: createModelSelection(\n+ ProviderInstanceId.make("codex_personal"),\n+ "gpt-5.3-codex",\n+ [\n+ { id: "reasoningEffort", value: "high" },\n+ { id: "fastMode", value: true },\n+ ],\n+ ),\n+ attachments: [],\n+ }),\n+ );\n+\n+ assert.deepStrictEqual(runtime.sendTurnImpl.mock.calls[0]?.[0], {\n+ input: "hello",\n+ model: "gpt-5.3-codex",\n+ effort: "high",\n+ serviceTier: "fast",\n+ });\n+ }).pipe(Effect.provide(customLayer));\n+ });\n });\n \n const lifecycleRuntimeFactory = makeRuntimeFactory();\n const lifecycleLayer = it.layer(\n- makeCodexAdapterLive({ makeRuntime: lifecycleRuntimeFactory.factory }).pipe(\n+ Layer.effect(\n+ CodexAdapter,\n+ Effect.gen(function* () {\n+ const codexConfig = Schema.decodeSync(CodexSettings)({});\n+ return yield* makeCodexAdapter(codexConfig, {\n+ makeRuntime: lifecycleRuntimeFactory.factory,\n+ });\n+ }),\n+ ).pipe(\n Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),\n Layer.provideMerge(ServerSettingsService.layerTest()),\n Layer.provideMerge(providerSessionDirectoryTestLayer),\n@@ -338,7 +426,7 @@ function startLifecycleRuntime() {\n return Effect.gen(function* () {\n const adapter = yield* CodexAdapter;\n yield* adapter.startSession({\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n threadId: asThreadId("thread-1"),\n runtimeMode: "full-access",\n });\n@@ -357,7 +445,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {\n const event: ProviderEvent = {\n id: asEventId("evt-msg-complete"),\n kind: "notification",\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n createdAt: new Date().toISOString(),\n method: "item/completed",\n threadId: asThreadId("thread-1"),\n@@ -399,7 +487,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {\n const event: ProviderEvent = {\n id: asEventId("evt-plan-complete"),\n kind: "notification",\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n createdAt: new Date().toISOString(),\n method: "item/completed",\n threadId: asThreadId("thread-1"),\n@@ -440,7 +528,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {\n yield* runtime.emit({\n id: asEventId("evt-plan-delta"),\n kind: "notification",\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n createdAt: new Date().toISOString(),\n method: "item/plan/delta",\n threadId: asThreadId("thread-1"),\n@@ -477,7 +565,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {\n const event: ProviderEvent = {\n id: asEventId("evt-session-closed"),\n kind: "session",\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n threadId: asThreadId("thread-1"),\n createdAt: new Date().toISOString(),\n method: "session/closed",\n@@ -508,7 +596,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {\n yield* runtime.emit({\n id: asEventId("evt-retryable-error"),\n kind: "notification",\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n threadId: asThreadId("thread-1"),\n createdAt: new Date().toISOString(),\n method: "error",\n@@ -546,7 +634,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {\n yield* runtime.emit({\n id: asEventId("evt-process-stderr"),\n kind: "notification",\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n threadId: asThreadId("thread-1"),\n createdAt: new Date().toISOString(),\n method: "process/stderr",\n@@ -580,7 +668,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {\n yield* runtime.emit({\n id: asEventId("evt-process-stderr-websocket"),\n kind: "notification",\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n threadId: asThreadId("thread-1"),\n createdAt: new Date().toISOString(),\n method: "process/stderr",\n@@ -616,7 +704,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {\n const event: ProviderEvent = {\n id: asEventId("evt-request-resolved"),\n kind: "notification",\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n threadId: asThreadId("thread-1"),\n createdAt: new Date().toISOString(),\n method: "serverRequest/resolved",\n@@ -651,7 +739,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {\n const event: ProviderEvent = {\n id: asEventId("evt-file-read-request-resolved"),\n kind: "notification",\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n threadId: asThreadId("thread-1"),\n createdAt: new Date().toISOString(),\n method: "serverRequest/resolved",\n@@ -686,7 +774,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {\n const event: ProviderEvent = {\n id: asEventId("evt-user-input-empty"),\n kind: "notification",\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n threadId: asThreadId("thread-1"),\n createdAt: new Date().toISOString(),\n method: "item/tool/requestUserInput/answered",\n@@ -726,7 +814,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {\n const event: ProviderEvent = {\n id: asEventId("evt-windows-sandbox-failed"),\n kind: "notification",\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n threadId: asThreadId("thread-1"),\n createdAt: new Date().toISOString(),\n method: "windowsSandbox/setupCompleted",\n@@ -771,7 +859,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {\n yield* runtime.emit({\n id: asEventId("evt-user-input-requested"),\n kind: "request",\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n threadId: asThreadId("thread-1"),\n createdAt: new Date().toISOString(),\n method: "item/tool/requestUserInput",\n@@ -798,7 +886,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {\n yield* runtime.emit({\n id: asEventId("evt-user-input-resolved"),\n kind: "notification",\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n threadId: asThreadId("thread-1"),\n createdAt: new Date().toISOString(),\n method: "item/tool/requestUserInput/answered",\n@@ -838,7 +926,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {\n yield* runtime.emit({\n id: asEventId("evt-codex-thread-token-usage-updated"),\n kind: "notification",\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n threadId: asThreadId("thread-1"),\n turnId: asTurnId("turn-1"),\n createdAt: new Date().toISOString(),\n@@ -897,7 +985,15 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {\n \n const scopedLifecycleRuntimeFactory = makeScopedRuntimeFactory();\n const scopedLifecycleLayer = it.layer(\n- makeCodexAdapterLive({ makeRuntime: scopedLifecycleRuntimeFactory.factory }).pipe(\n+ Layer.effect(\n+ CodexAdapter,\n+ Effect.gen(function* () {\n+ const codexConfig = Schema.decodeSync(CodexSettings)({});\n+ return yield* makeCodexAdapter(codexConfig, {\n+ makeRuntime: scopedLifecycleRuntimeFactory.factory,\n+ });\n+ }),\n+ ).pipe(\n Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),\n Layer.provideMerge(ServerSettingsService.layerTest()),\n Layer.provideMerge(providerSessionDirectoryTestLayer),\n@@ -912,7 +1008,7 @@ scopedLifecycleLayer("CodexAdapterLive scoped lifecycle", (it) => {\n const adapter = yield* CodexAdapter;\n \n yield* adapter.startSession({\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n threadId: asThreadId("thread-stop"),\n runtimeMode: "full-access",\n });\n@@ -933,7 +1029,15 @@ scopedLifecycleLayer("CodexAdapterLive scoped lifecycle", (it) => {\n \n const scopedFailureRuntimeFactory = makeScopedRuntimeFactory({ failConstruction: true });\n const scopedFailureLayer = it.layer(\n- makeCodexAdapterLive({ makeRuntime: scopedFailureRuntimeFactory.factory }).pipe(\n+ Layer.effect(\n+ CodexAdapter,\n+ Effect.gen(function* () {\n+ const codexConfig = Schema.decodeSync(CodexSettings)({});\n+ return yield* makeCodexAdapter(codexConfig, {\n+ makeRuntime: scopedFailureRuntimeFactory.factory,\n+ });\n+ }),\n+ ).pipe(\n Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),\n Layer.provideMerge(ServerSettingsService.layerTest()),\n Layer.provideMerge(providerSessionDirectoryTestLayer),\n@@ -949,7 +1053,7 @@ scopedFailureLayer("CodexAdapterLive scoped startup failure", (it) => {\n \n const result = yield* adapter\n .startSession({\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n threadId: asThreadId("thread-fail"),\n runtimeMode: "full-access",\n })\n@@ -974,10 +1078,16 @@ it.effect("flushes managed native logs when the adapter layer shuts down", () =>\n let scopeClosed = false;\n \n try {\n- const layer = makeCodexAdapterLive({\n- makeRuntime: runtimeFactory.factory,\n- nativeEventLogPath: basePath,\n- }).pipe(\n+ const layer = Layer.effect(\n+ CodexAdapter,\n+ Effect.gen(function* () {\n+ const codexConfig = Schema.decodeSync(CodexSettings)({});\n+ return yield* makeCodexAdapter(codexConfig, {\n+ makeRuntime: runtimeFactory.factory,\n+ nativeEventLogPath: basePath,\n+ });\n+ }),\n+ ).pipe(\n Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),\n Layer.provideMerge(ServerSettingsService.layerTest()),\n Layer.provideMerge(providerSessionDirectoryTestLayer),\n@@ -987,7 +1097,7 @@ it.effect("flushes managed native logs when the adapter layer shuts down", () =>\n const adapter = yield* Effect.service(CodexAdapter).pipe(Effect.provide(context));\n \n yield* adapter.startSession({\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n threadId: asThreadId("thread-logger"),\n runtimeMode: "full-access",\n });\n@@ -999,7 +1109,7 @@ it.effect("flushes managed native logs when the adapter layer shuts down", () =>\n yield* runtime.emit({\n id: asEventId("evt-native-log"),\n kind: "notification",\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n threadId: asThreadId("thread-logger"),\n createdAt: new Date().toISOString(),\n method: "process/stderr",\ndiff --git a/apps/server/src/provider/Layers/CodexAdapter.ts b/apps/server/src/provider/Layers/CodexAdapter.ts\nindex 5c824dc730..5186dc2962 100644\n--- a/apps/server/src/provider/Layers/CodexAdapter.ts\n+++ b/apps/server/src/provider/Layers/CodexAdapter.ts\n@@ -10,7 +10,10 @@\n import {\n type CanonicalItemType,\n type CanonicalRequestType,\n+ type CodexSettings,\n+ ProviderDriverKind,\n type ProviderEvent,\n+ ProviderInstanceId,\n type ProviderRuntimeEvent,\n type ProviderRequestKind,\n type ThreadTokenUsageSnapshot,\n@@ -21,7 +24,7 @@ import {\n ThreadId,\n ProviderSendTurnInput,\n } from "@t3tools/contracts";\n-import { Effect, Exit, Fiber, FileSystem, Layer, Queue, Schema, Scope, Stream } from "effect";\n+import { Effect, Exit, Fiber, FileSystem, Queue, Schema, Scope, Stream } from "effect";\n import { ChildProcessSpawner } from "effect/unstable/process";\n import * as CodexErrors from "effect-codex-app-server/errors";\n import * as EffectCodexSchema from "effect-codex-app-server/schema";\n@@ -39,10 +42,9 @@ import {\n ProviderAdapterValidationError,\n type ProviderAdapterError,\n } from "../Errors.ts";\n-import { CodexAdapter, type CodexAdapterShape } from "../Services/CodexAdapter.ts";\n+import { type CodexAdapterShape } from "../Services/CodexAdapter.ts";\n import { resolveAttachmentPath } from "../../attachmentStore.ts";\n import { ServerConfig } from "../../config.ts";\n-import { ServerSettingsService } from "../../serverSettings.ts";\n import {\n CodexResumeCursorSchema,\n CodexSessionRuntimeThreadIdMissingError,\n@@ -53,9 +55,11 @@ import {\n } from "./CodexSessionRuntime.ts";\n import { type EventNdjsonLogger, makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";\n \n-const PROVIDER = "codex" as const;\n+const PROVIDER = ProviderDriverKind.make("codex");\n \n export interface CodexAdapterLiveOptions {\n+ readonly instanceId?: ProviderInstanceId;\n+ readonly environment?: NodeJS.ProcessEnv;\n readonly makeRuntime?: (\n options: CodexSessionRuntimeOptions,\n ) => Effect.Effect<\n@@ -1318,9 +1322,20 @@ function mapToRuntimeEvents(\n return [];\n }\n \n-const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (\n+/**\n+ * Build a Codex provider adapter bound to a specific `CodexSettings` payload.\n+ *\n+ * The adapter is a captured closure over `codexConfig` — the `binaryPath` and\n+ * `homePath` are read from that payload, not from `ServerSettingsService`.\n+ * This is what makes multi-instance routing possible: each `ProviderInstance`\n+ * in the registry owns its own closure with its own config, so two Codex\n+ * instances with different `homePath`s cannot step on each other.\n+ */\n+export const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (\n+ codexConfig: CodexSettings,\n options?: CodexAdapterLiveOptions,\n ) {\n+ const boundInstanceId = options?.instanceId ?? ProviderInstanceId.make("codex");\n const fileSystem = yield* FileSystem.FileSystem;\n const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;\n const serverConfig = yield* Effect.service(ServerConfig);\n@@ -1333,7 +1348,6 @@ const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (\n : undefined);\n const managedNativeEventLogger =\n options?.nativeEventLogger === undefined ? nativeEventLogger : undefined;\n- const serverSettingsService = yield* ServerSettingsService;\n const runtimeEventQueue = yield* Queue.unbounded<ProviderRuntimeEvent>();\n const sessions = new Map<ThreadId, CodexAdapterSessionContext>();\n \n@@ -1353,31 +1367,21 @@ const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (\n yield* Effect.suspend(() => stopSessionInternal(existing));\n }\n \n- const codexSettings = yield* serverSettingsService.getSettings.pipe(\n- Effect.map((settings) => settings.providers.codex),\n- Effect.mapError(\n- (error) =>\n- new ProviderAdapterProcessError({\n- provider: PROVIDER,\n- threadId: input.threadId,\n- detail: error.message,\n- cause: error,\n- }),\n- ),\n- );\n const runtimeInput: CodexSessionRuntimeOptions = {\n threadId: input.threadId,\n+ providerInstanceId: boundInstanceId,\n cwd: input.cwd ?? process.cwd(),\n- binaryPath: codexSettings.binaryPath,\n- ...(codexSettings.homePath ? { homePath: codexSettings.homePath } : {}),\n+ binaryPath: codexConfig.binaryPath,\n+ ...(options?.environment ? { environment: options.environment } : {}),\n+ ...(codexConfig.homePath ? { homePath: codexConfig.homePath } : {}),\n ...(Schema.is(CodexResumeCursorSchema)(input.resumeCursor)\n ? { resumeCursor: input.resumeCursor }\n : {}),\n runtimeMode: input.runtimeMode,\n- ...(input.modelSelection?.provider === "codex"\n+ ...(input.modelSelection?.instanceId === boundInstanceId\n ? { model: input.modelSelection.model }\n : {}),\n- ...(input.modelSelection?.provider === "codex" &&\n+ ...(input.modelSelection?.instanceId === boundInstanceId &&\n getModelSelectionBooleanOptionValue(input.modelSelection, "fastMode") === true\n ? { serviceTier: "fast" }\n : {}),\n@@ -1492,17 +1496,17 @@ const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (\n \n const session = yield* requireSession(input.threadId);\n const reasoningEffort =\n- input.modelSelection?.provider === "codex"\n+ input.modelSelection?.instanceId === boundInstanceId\n ? getModelSelectionStringOptionValue(input.modelSelection, "reasoningEffort")\n : undefined;\n const fastMode =\n- input.modelSelection?.provider === "codex"\n+ input.modelSelection?.instanceId === boundInstanceId\n ? getModelSelectionBooleanOptionValue(input.modelSelection, "fastMode")\n : undefined;\n return yield* session.runtime\n .sendTurn({\n ...(input.input !== undefined ? { input: input.input } : {}),\n- ...(input.modelSelection?.provider === "codex"\n+ ...(input.modelSelection?.instanceId === boundInstanceId\n ? { model: input.modelSelection.model }\n : {}),\n ...(reasoningEffort\n@@ -1676,8 +1680,9 @@ const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (\n } satisfies CodexAdapterShape;\n });\n \n-export const CodexAdapterLive = Layer.effect(CodexAdapter, makeCodexAdapter());\n-\n-export function makeCodexAdapterLive(options?: CodexAdapterLiveOptions) {\n- return Layer.effect(CodexAdapter, makeCodexAdapter(options));\n-}\n+// NOTE: the old `CodexAdapterLive` / `makeCodexAdapterLive` singleton Layer\n+// exports have been removed as part of the per-instance-driver refactor.\n+// `makeCodexAdapter(codexConfig, options?)` is now invoked directly by\n+// `CodexDriver.create()` for each configured instance; downstream consumers\n+// (server bootstrap, integration harness, this module\'s tests) will be\n+// migrated to the registry in a follow-up pass.\ndiff --git a/apps/server/src/provider/Layers/CodexProvider.ts b/apps/server/src/provider/Layers/CodexProvider.ts\nindex 915609ca21..0917d842a6 100644\n--- a/apps/server/src/provider/Layers/CodexProvider.ts\n+++ b/apps/server/src/provider/Layers/CodexProvider.ts\n@@ -1,15 +1,4 @@\n-import {\n- DateTime,\n- Duration,\n- Effect,\n- Equal,\n- Layer,\n- Option,\n- Result,\n- Schema,\n- Stream,\n- Types,\n-} from "effect";\n+import { DateTime, Duration, Effect, Layer, Option, Result, Schema, Types } from "effect";\n import { ChildProcessSpawner } from "effect/unstable/process";\n import * as CodexClient from "effect-codex-app-server/client";\n import * as CodexSchema from "effect-codex-app-server/schema";\n@@ -27,14 +16,11 @@ import { ServerSettingsError } from "@t3tools/contracts";\n \n import { createModelCapabilities } from "@t3tools/shared/model";\n \n-import { makeManagedServerProvider } from "../makeManagedServerProvider.ts";\n-import { buildServerProvider } from "../providerSnapshot.ts";\n-import { CodexProvider } from "../Services/CodexProvider.ts";\n+import { buildServerProvider, type ServerProviderDraft } from "../providerSnapshot.ts";\n import { expandHomePath } from "../../pathExpansion.ts";\n-import { ServerSettingsService } from "../../serverSettings.ts";\n+import { scopedSafeTeardown } from "./scopedSafeTeardown.ts";\n import packageJson from "../../../package.json" with { type: "json" };\n \n-const PROVIDER = "codex" as const;\n const PROVIDER_PROBE_TIMEOUT_MS = 8_000;\n const CODEX_PRESENTATION = {\n displayName: "Codex",\n@@ -90,6 +76,11 @@ function codexAccountAuthLabel(account: CodexSchema.V2GetAccountResponse["accoun\n }\n }\n \n+function codexAccountEmail(account: CodexSchema.V2GetAccountResponse["account"]) {\n+ if (!account || account.type !== "chatgpt") return undefined;\n+ return account.email;\n+}\n+\n function mapCodexModelCapabilities(\n model: CodexSchema.V2ModelListResponse__Model,\n ): ModelCapabilities {\n@@ -245,18 +236,33 @@ export function buildCodexInitializeParams(): CodexSchema.V1InitializeParams {\n };\n }\n \n+// Wrapped with `scopedSafeTeardown("codex-probe")` rather than the usual\n+// `Effect.scoped` so that a defect from the `Layer.build` finalizer (e.g.\n+// `ChildProcess.kill` throwing because the `codex app-server` child exited\n+// early) cannot override a successful probe body. Without this guard the\n+// defect bubbles past `Effect.result` in `checkCodexProviderStatus`, dies\n+// `refreshOneSource`, and `providersRef` never receives the snapshot.\n const probeCodexAppServerProvider = Effect.fn("probeCodexAppServerProvider")(function* (input: {\n readonly binaryPath: string;\n readonly homePath?: string;\n readonly cwd: string;\n readonly customModels?: ReadonlyArray<string>;\n+ readonly environment?: NodeJS.ProcessEnv;\n }) {\n+ // `~` is not shell-expanded when env vars are set via `child_process.spawn`,\n+ // so `CODEX_HOME=~/.codex_work` would reach codex verbatim and trip\n+ // "CODEX_HOME points to \'~/.codex_work\', but that path does not exist".\n+ // Expand here for parity with `CodexTextGeneration`/`CodexSessionRuntime`.\n+ const resolvedHomePath = input.homePath ? expandHomePath(input.homePath) : undefined;\n const clientContext = yield* Layer.build(\n CodexClient.layerCommand({\n command: input.binaryPath,\n args: ["app-server"],\n cwd: input.cwd,\n- ...(input.homePath ? { env: { CODEX_HOME: expandHomePath(input.homePath) } } : {}),\n+ env: {\n+ ...(input.environment ?? process.env),\n+ ...(resolvedHomePath ? { CODEX_HOME: resolvedHomePath } : {}),\n+ },\n }),\n );\n const client = yield* Effect.service(CodexClient.CodexAppServerClient).pipe(\n@@ -305,7 +311,7 @@ const probeCodexAppServerProvider = Effect.fn("probeCodexAppServerProvider")(fun\n models: appendCustomCodexModels(models, input.customModels ?? []),\n skills: parseCodexSkillsListResponse(skillsResponse, input.cwd),\n } satisfies CodexAppServerProviderSnapshot;\n-}, Effect.scoped);\n+}, scopedSafeTeardown("codex-probe"));\n \n const emptyCodexModelsFromSettings = (codexSettings: CodexSettings): ServerProvider["models"] =>\n codexSettings.customModels\n@@ -318,13 +324,12 @@ const emptyCodexModelsFromSettings = (codexSettings: CodexSettings): ServerProvi\n capabilities: null,\n }));\n \n-const makePendingCodexProvider = (codexSettings: CodexSettings): ServerProvider => {\n+const makePendingCodexProvider = (codexSettings: CodexSettings): ServerProviderDraft => {\n const checkedAt = new Date().toISOString();\n const models = emptyCodexModelsFromSettings(codexSettings);\n \n if (!codexSettings.enabled) {\n return buildServerProvider({\n- provider: PROVIDER,\n presentation: CODEX_PRESENTATION,\n enabled: false,\n checkedAt,\n@@ -341,7 +346,6 @@ const makePendingCodexProvider = (codexSettings: CodexSettings): ServerProvider\n }\n \n return buildServerProvider({\n- provider: PROVIDER,\n presentation: CODEX_PRESENTATION,\n enabled: true,\n checkedAt,\n@@ -363,10 +367,12 @@ function accountProbeStatus(account: CodexAppServerProviderSnapshot["account"]):\n readonly message?: string;\n } {\n const authLabel = codexAccountAuthLabel(account.account);\n+ const authEmail = codexAccountEmail(account.account);\n const auth = {\n status: account.account ? ("authenticated" as const) : ("unknown" as const),\n ...(account.account?.type ? { type: account.account?.type } : {}),\n ...(authLabel ? { label: authLabel } : {}),\n+ ...(authEmail ? { email: authEmail } : {}),\n } satisfies ServerProvider["auth"];\n \n if (account.account) {\n@@ -385,31 +391,29 @@ function accountProbeStatus(account: CodexAppServerProviderSnapshot["account"]):\n }\n \n export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(function* (\n+ codexSettings: CodexSettings,\n probe: (input: {\n readonly binaryPath: string;\n readonly homePath?: string;\n readonly cwd: string;\n readonly customModels: ReadonlyArray<string>;\n+ readonly environment?: NodeJS.ProcessEnv;\n }) => Effect.Effect<\n CodexAppServerProviderSnapshot,\n CodexErrors.CodexAppServerError,\n ChildProcessSpawner.ChildProcessSpawner\n > = probeCodexAppServerProvider,\n+ environment: NodeJS.ProcessEnv = process.env,\n ): Effect.fn.Return<\n- ServerProvider,\n+ ServerProviderDraft,\n ServerSettingsError,\n- ServerSettingsService | ChildProcessSpawner.ChildProcessSpawner\n+ ChildProcessSpawner.ChildProcessSpawner\n > {\n- const codexSettings = yield* Effect.service(ServerSettingsService).pipe(\n- Effect.flatMap((service) => service.getSettings),\n- Effect.map((settings) => settings.providers.codex),\n- );\n const checkedAt = DateTime.formatIso(yield* DateTime.now);\n const emptyModels = emptyCodexModelsFromSettings(codexSettings);\n \n if (!codexSettings.enabled) {\n return buildServerProvider({\n- provider: PROVIDER,\n presentation: CODEX_PRESENTATION,\n enabled: false,\n checkedAt,\n@@ -430,13 +434,13 @@ export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(fu\n homePath: codexSettings.homePath,\n cwd: process.cwd(),\n customModels: codexSettings.customModels,\n+ environment,\n }).pipe(Effect.timeoutOption(Duration.millis(PROVIDER_PROBE_TIMEOUT_MS)), Effect.result);\n \n if (Result.isFailure(probeResult)) {\n const error = probeResult.failure;\n const installed = !Schema.is(CodexErrors.CodexAppServerSpawnError)(error);\n return buildServerProvider({\n- provider: PROVIDER,\n presentation: CODEX_PRESENTATION,\n enabled: codexSettings.enabled,\n checkedAt,\n@@ -456,7 +460,6 @@ export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(fu\n \n if (Option.isNone(probeResult.success)) {\n return buildServerProvider({\n- provider: PROVIDER,\n presentation: CODEX_PRESENTATION,\n enabled: codexSettings.enabled,\n checkedAt,\n@@ -476,7 +479,6 @@ export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(fu\n const accountStatus = accountProbeStatus(snapshot.account);\n \n return buildServerProvider({\n- provider: PROVIDER,\n presentation: CODEX_PRESENTATION,\n enabled: codexSettings.enabled,\n checkedAt,\n@@ -492,28 +494,11 @@ export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(fu\n });\n });\n \n-export const CodexProviderLive = Layer.effect(\n- CodexProvider,\n- Effect.gen(function* () {\n- const serverSettings = yield* ServerSettingsService;\n- const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;\n- const checkProvider = checkCodexProviderStatus().pipe(\n- Effect.provideService(ServerSettingsService, serverSettings),\n- Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),\n- );\n-\n- return yield* makeManagedServerProvider<CodexSettings>({\n- getSettings: serverSettings.getSettings.pipe(\n- Effect.map((settings) => settings.providers.codex),\n- Effect.orDie,\n- ),\n- streamSettings: serverSettings.streamChanges.pipe(\n- Stream.map((settings) => settings.providers.codex),\n- ),\n- haveSettingsChanged: (previous, next) => !Equal.equals(previous, next),\n- initialSnapshot: makePendingCodexProvider,\n- checkProvider,\n- refreshInterval: Duration.minutes(5),\n- });\n- }),\n-);\n+// NOTE: the singleton `CodexProviderLive` Layer has been removed as part of\n+// the per-instance-driver refactor. `CodexDriver.create()` builds a managed\n+// snapshot per instance (each with its own `CodexSettings`) and hands the\n+// resulting `ServerProviderShape` back as `ProviderInstance.snapshot`.\n+//\n+// The `makePendingCodexProvider` and `checkCodexProviderStatus` helpers are\n+// re-exported for use by `CodexDriver`.\n+export { makePendingCodexProvider };\ndiff --git a/apps/server/src/provider/Layers/CodexSessionRuntime.ts b/apps/server/src/provider/Layers/CodexSessionRuntime.ts\nindex e45e1825ee..4f9011fba0 100644\n--- a/apps/server/src/provider/Layers/CodexSessionRuntime.ts\n+++ b/apps/server/src/provider/Layers/CodexSessionRuntime.ts\n@@ -1,10 +1,10 @@\n-import { randomUUID } from "node:crypto";\n-\n import {\n ApprovalRequestId,\n- DEFAULT_MODEL_BY_PROVIDER,\n+ DEFAULT_MODEL,\n EventId,\n+ ProviderDriverKind,\n ProviderItemId,\n+ type ProviderInstanceId,\n type ProviderApprovalDecision,\n type ProviderEvent,\n type ProviderInteractionMode,\n@@ -17,7 +17,7 @@ import {\n TurnId,\n } from "@t3tools/contracts";\n import { normalizeModelSlug } from "@t3tools/shared/model";\n-import { Deferred, Effect, Exit, Layer, Queue, Ref, Scope, Schema, Stream } from "effect";\n+import { Deferred, Effect, Exit, Layer, Queue, Ref, Scope, Random, Schema, Stream } from "effect";\n import * as SchemaIssue from "effect/SchemaIssue";\n import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";\n import * as CodexClient from "effect-codex-app-server/client";\n@@ -26,13 +26,13 @@ import * as CodexRpc from "effect-codex-app-server/rpc";\n import * as EffectCodexSchema from "effect-codex-app-server/schema";\n \n import { buildCodexInitializeParams } from "./CodexProvider.ts";\n+import { expandHomePath } from "../../pathExpansion.ts";\n import {\n CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS,\n CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS,\n } from "../CodexDeveloperInstructions.ts";\n-import { expandHomePath } from "../../pathExpansion.ts";\n \n-const PROVIDER = "codex" as const;\n+const PROVIDER = ProviderDriverKind.make("codex");\n \n const ANSI_ESCAPE_CHAR = String.fromCharCode(27);\n const ANSI_ESCAPE_REGEX = new RegExp(`${ANSI_ESCAPE_CHAR}\\\\[[0-9;]*m`, "g");\n@@ -76,8 +76,10 @@ type CodexThreadItem =\n \n export interface CodexSessionRuntimeOptions {\n readonly threadId: ThreadId;\n+ readonly providerInstanceId?: ProviderInstanceId;\n readonly binaryPath: string;\n readonly homePath?: string;\n+ readonly environment?: NodeJS.ProcessEnv;\n readonly cwd: string;\n readonly runtimeMode: RuntimeMode;\n readonly model?: string;\n@@ -87,7 +89,10 @@ export interface CodexSessionRuntimeOptions {\n \n export interface CodexSessionRuntimeSendTurnInput {\n readonly input?: string;\n- readonly attachments?: ReadonlyArray<{ readonly type: "image"; readonly url: string }>;\n+ readonly attachments?: ReadonlyArray<{\n+ readonly type: "image";\n+ readonly url: string;\n+ }>;\n readonly model?: string;\n readonly serviceTier?: EffectCodexSchema.V2TurnStartParams__ServiceTier | undefined;\n readonly effort?: EffectCodexSchema.V2TurnStartParams__ReasoningEffort | undefined;\n@@ -303,7 +308,7 @@ function buildCodexCollaborationMode(input: {\n if (input.interactionMode === undefined) {\n return undefined;\n }\n- const model = normalizeCodexModelSlug(input.model) ?? DEFAULT_MODEL_BY_PROVIDER.codex;\n+ const model = normalizeCodexModelSlug(input.model) ?? DEFAULT_MODEL;\n return {\n mode: input.interactionMode,\n settings: {\n@@ -321,7 +326,10 @@ export function buildTurnStartParams(input: {\n readonly threadId: string;\n readonly runtimeMode: RuntimeMode;\n readonly prompt?: string;\n- readonly attachments?: ReadonlyArray<{ readonly type: "image"; readonly url: string }>;\n+ readonly attachments?: ReadonlyArray<{\n+ readonly type: "image";\n+ readonly url: string;\n+ }>;\n readonly model?: string;\n readonly serviceTier?: EffectCodexSchema.V2TurnStartParams__ServiceTier;\n readonly effort?: EffectCodexSchema.V2TurnStartParams__ReasoningEffort;\n@@ -680,13 +688,19 @@ export const makeCodexSessionRuntime = (\n const collabReceiverTurnsRef = yield* Ref.make(new Map<string, TurnId>());\n const closedRef = yield* Ref.make(false);\n \n+ // `~` is not shell-expanded when env vars are set via\n+ // `child_process.spawn`; `expandHomePath` lets a configured\n+ // `CODEX_HOME=~/.codex_work` reach codex as an absolute path.\n+ const resolvedHomePath = options.homePath ? expandHomePath(options.homePath) : undefined;\n+ const env = {\n+ ...(options.environment ?? process.env),\n+ ...(resolvedHomePath ? { CODEX_HOME: resolvedHomePath } : {}),\n+ };\n const child = yield* spawner\n .spawn(\n ChildProcess.make(options.binaryPath, ["app-server"], {\n cwd: options.cwd,\n- ...(options.homePath\n- ? { env: { ...process.env, CODEX_HOME: expandHomePath(options.homePath) } }\n- : {}),\n+ env,\n shell: process.platform === "win32",\n }),\n )\n@@ -712,6 +726,7 @@ export const makeCodexSessionRuntime = (\n \n const initialSession = {\n provider: PROVIDER,\n+ ...(options.providerInstanceId ? { providerInstanceId: options.providerInstanceId } : {}),\n status: "connecting",\n runtimeMode: options.runtimeMode,\n cwd: options.cwd,\n@@ -725,13 +740,15 @@ export const makeCodexSessionRuntime = (\n const offerEvent = (event: ProviderEvent) => Queue.offer(events, event).pipe(Effect.asVoid);\n \n const emitEvent = (event: Omit<ProviderEvent, "id" | "provider" | "createdAt">) =>\n- offerEvent({\n- id: EventId.make(randomUUID()),\n- provider: PROVIDER,\n- createdAt: new Date().toISOString(),\n- ...event,\n- });\n-\n+ Effect.flatMap(Random.nextUUIDv4, (id) =>\n+ offerEvent({\n+ id: EventId.make(id),\n+ provider: PROVIDER,\n+ ...(options.providerInstanceId ? { providerInstanceId: options.providerInstanceId } : {}),\n+ createdAt: new Date().toISOString(),\n+ ...event,\n+ }),\n+ );\n const emitSessionEvent = (method: string, message: string) =>\n emitEvent({\n kind: "session",\n@@ -891,7 +908,7 @@ export const makeCodexSessionRuntime = (\n \n yield* client.handleServerRequest("item/commandExecution/requestApproval", (payload) =>\n Effect.gen(function* () {\n- const requestId = ApprovalRequestId.make(randomUUID());\n+ const requestId = ApprovalRequestId.make(yield* Random.nextUUIDv4);\n const turnId = TurnId.make(payload.turnId);\n const itemId = ProviderItemId.make(payload.itemId);\n const decision = yield* Deferred.make<ProviderApprovalDecision>();\n@@ -947,7 +964,7 @@ export const makeCodexSessionRuntime = (\n \n yield* client.handleServerRequest("item/fileChange/requestApproval", (payload) =>\n Effect.gen(function* () {\n- const requestId = ApprovalRequestId.make(randomUUID());\n+ const requestId = ApprovalRequestId.make(yield* Random.nextUUIDv4);\n const turnId = TurnId.make(payload.turnId);\n const itemId = ProviderItemId.make(payload.itemId);\n const decision = yield* Deferred.make<ProviderApprovalDecision>();\n@@ -1003,7 +1020,7 @@ export const makeCodexSessionRuntime = (\n \n yield* client.handleServerRequest("item/tool/requestUserInput", (payload) =>\n Effect.gen(function* () {\n- const requestId = ApprovalRequestId.make(randomUUID());\n+ const requestId = ApprovalRequestId.make(yield* Random.nextUUIDv4);\n const turnId = TurnId.make(payload.turnId);\n const itemId = ProviderItemId.make(payload.itemId);\n const answers = yield* Deferred.make<ProviderUserInputAnswers>();\ndiff --git a/apps/server/src/provider/Layers/CursorAdapter.test.ts b/apps/server/src/provider/Layers/CursorAdapter.test.ts\nindex 1f619d49f1..375eec049a 100644\n--- a/apps/server/src/provider/Layers/CursorAdapter.test.ts\n+++ b/apps/server/src/provider/Layers/CursorAdapter.test.ts\n@@ -5,15 +5,27 @@ import { fileURLToPath } from "node:url";\n \n import * as NodeServices from "@effect/platform-node/NodeServices";\n import { assert, it } from "@effect/vitest";\n-import { Deferred, Effect, Fiber, Layer, Stream } from "effect";\n+import { Context, Deferred, Effect, Fiber, Layer, Schema, Stream } from "effect";\n import { createModelSelection } from "@t3tools/shared/model";\n \n-import { ApprovalRequestId, type ProviderRuntimeEvent, ThreadId } from "@t3tools/contracts";\n+import {\n+ ApprovalRequestId,\n+ CursorSettings,\n+ ProviderDriverKind,\n+ type ProviderRuntimeEvent,\n+ ThreadId,\n+ ProviderInstanceId,\n+} from "@t3tools/contracts";\n \n import { ServerConfig } from "../../config.ts";\n import { ServerSettingsService } from "../../serverSettings.ts";\n-import { CursorAdapter } from "../Services/CursorAdapter.ts";\n-import { makeCursorAdapterLive } from "./CursorAdapter.ts";\n+import type { CursorAdapterShape } from "../Services/CursorAdapter.ts";\n+import { makeCursorAdapter } from "./CursorAdapter.ts";\n+\n+// Test-local service tag so the rest of the file can keep using `yield* CursorAdapter`.\n+class CursorAdapter extends Context.Service<CursorAdapter, CursorAdapterShape>()(\n+ "test/CursorAdapter",\n+) {}\n \n const __dirname = path.dirname(fileURLToPath(import.meta.url));\n const mockAgentPath = path.join(__dirname, "../../../scripts/acp-mock-agent.ts");\n@@ -91,8 +103,31 @@ async function waitForFileContent(filePath: string, attempts = 40) {\n throw new Error(`Timed out waiting for file content at ${filePath}`);\n }\n \n+// Tests mutate `ServerSettingsService` mid-flight (e.g. setting\n+// `providers.cursor.binaryPath` to a mock ACP wrapper). The adapter\n+// captures `cursorSettings` once at construction, so without a resolver\n+// the mutation is invisible — sessions would spawn the constructor\'s\n+// (empty) binary path. Wiring `resolveSettings` through\n+// `ServerSettingsService.getSettings` makes each session read the latest\n+// snapshot, matching the old "always read live" behavior that these\n+// tests assumed.\n+const makeResolveCursorSettings = Effect.gen(function* () {\n+ const serverSettings = yield* ServerSettingsService;\n+ return serverSettings.getSettings.pipe(\n+ Effect.map((snapshot) => snapshot.providers.cursor),\n+ Effect.orDie,\n+ );\n+});\n+\n const cursorAdapterTestLayer = it.layer(\n- makeCursorAdapterLive().pipe(\n+ Layer.effect(\n+ CursorAdapter,\n+ Effect.gen(function* () {\n+ const cursorConfig = Schema.decodeSync(CursorSettings)({});\n+ const resolveSettings = yield* makeResolveCursorSettings;\n+ return yield* makeCursorAdapter(cursorConfig, { resolveSettings });\n+ }),\n+ ).pipe(\n Layer.provideMerge(ServerSettingsService.layerTest()),\n Layer.provideMerge(\n ServerConfig.layerTest(process.cwd(), {\n@@ -120,10 +155,10 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {\n \n const session = yield* adapter.startSession({\n threadId,\n- provider: "cursor",\n+ provider: ProviderDriverKind.make("cursor"),\n cwd: process.cwd(),\n runtimeMode: "full-access",\n- modelSelection: { provider: "cursor", model: "default" },\n+ modelSelection: { instanceId: ProviderInstanceId.make("cursor"), model: "default" },\n });\n \n assert.equal(session.provider, "cursor");\n@@ -205,10 +240,10 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {\n \n yield* adapter.startSession({\n threadId,\n- provider: "cursor",\n+ provider: ProviderDriverKind.make("cursor"),\n cwd: process.cwd(),\n runtimeMode: "full-access",\n- modelSelection: { provider: "cursor", model: "default" },\n+ modelSelection: { instanceId: ProviderInstanceId.make("cursor"), model: "default" },\n });\n \n yield* adapter.stopSession(threadId);\n@@ -244,17 +279,17 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {\n [\n adapter.startSession({\n threadId,\n- provider: "cursor",\n+ provider: ProviderDriverKind.make("cursor"),\n cwd: process.cwd(),\n runtimeMode: "full-access",\n- modelSelection: { provider: "cursor", model: "default" },\n+ modelSelection: { instanceId: ProviderInstanceId.make("cursor"), model: "default" },\n }),\n adapter.startSession({\n threadId,\n- provider: "cursor",\n+ provider: ProviderDriverKind.make("cursor"),\n cwd: process.cwd(),\n runtimeMode: "full-access",\n- modelSelection: { provider: "cursor", model: "default" },\n+ modelSelection: { instanceId: ProviderInstanceId.make("cursor"), model: "default" },\n }),\n ],\n { concurrency: "unbounded" },\n@@ -276,7 +311,7 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {\n const result = yield* adapter\n .startSession({\n threadId: ThreadId.make("bad-provider"),\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n cwd: process.cwd(),\n runtimeMode: "full-access",\n })\n@@ -302,10 +337,10 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {\n \n yield* adapter.startSession({\n threadId,\n- provider: "cursor",\n+ provider: ProviderDriverKind.make("cursor"),\n cwd: process.cwd(),\n runtimeMode: "full-access",\n- modelSelection: { provider: "cursor", model: "composer-2" },\n+ modelSelection: { instanceId: ProviderInstanceId.make("cursor"), model: "composer-2" },\n });\n \n yield* adapter.sendTurn({\n@@ -358,7 +393,7 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {\n providers: { cursor: { binaryPath: wrapperPath } },\n });\n \n- const modelSelection = createModelSelection("cursor", "gpt-5.4", [\n+ const modelSelection = createModelSelection(ProviderInstanceId.make("cursor"), "gpt-5.4", [\n { id: "reasoning", value: "xhigh" },\n { id: "contextWindow", value: "1m" },\n { id: "fastMode", value: true },\n@@ -366,7 +401,7 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {\n \n yield* adapter.startSession({\n threadId,\n- provider: "cursor",\n+ provider: ProviderDriverKind.make("cursor"),\n cwd: process.cwd(),\n runtimeMode: "full-access",\n modelSelection,\n@@ -460,10 +495,10 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {\n const program = Effect.gen(function* () {\n yield* adapter.startSession({\n threadId,\n- provider: "cursor",\n+ provider: ProviderDriverKind.make("cursor"),\n cwd: process.cwd(),\n runtimeMode: "approval-required",\n- modelSelection: { provider: "cursor", model: "default" },\n+ modelSelection: { instanceId: ProviderInstanceId.make("cursor"), model: "default" },\n });\n \n const turn = yield* adapter.sendTurn({\n@@ -560,7 +595,14 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {\n );\n }).pipe(\n Effect.provide(\n- makeCursorAdapterLive().pipe(\n+ Layer.effect(\n+ CursorAdapter,\n+ Effect.gen(function* () {\n+ const cursorConfig = Schema.decodeSync(CursorSettings)({});\n+ const resolveSettings = yield* makeResolveCursorSettings;\n+ return yield* makeCursorAdapter(cursorConfig, { resolveSettings });\n+ }),\n+ ).pipe(\n Layer.provideMerge(ServerSettingsService.layerTest()),\n Layer.provideMerge(\n ServerConfig.layerTest(process.cwd(), {\n@@ -615,10 +657,10 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {\n \n yield* adapter.startSession({\n threadId,\n- provider: "cursor",\n+ provider: ProviderDriverKind.make("cursor"),\n cwd: process.cwd(),\n runtimeMode: "full-access",\n- modelSelection: { provider: "cursor", model: "default" },\n+ modelSelection: { instanceId: ProviderInstanceId.make("cursor"), model: "default" },\n });\n \n const turn = yield* adapter.sendTurn({\n@@ -714,10 +756,10 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {\n \n yield* adapter.startSession({\n threadId,\n- provider: "cursor",\n+ provider: ProviderDriverKind.make("cursor"),\n cwd: process.cwd(),\n runtimeMode: "full-access",\n- modelSelection: { provider: "cursor", model: "default" },\n+ modelSelection: { instanceId: ProviderInstanceId.make("cursor"), model: "default" },\n });\n \n const turn = yield* adapter.sendTurn({\n@@ -836,10 +878,10 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {\n \n yield* adapter.startSession({\n threadId,\n- provider: "cursor",\n+ provider: ProviderDriverKind.make("cursor"),\n cwd: process.cwd(),\n runtimeMode: "approval-required",\n- modelSelection: { provider: "cursor", model: "default" },\n+ modelSelection: { instanceId: ProviderInstanceId.make("cursor"), model: "default" },\n });\n \n const sendTurnFiber = yield* adapter\n@@ -906,10 +948,10 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {\n \n yield* adapter.startSession({\n threadId,\n- provider: "cursor",\n+ provider: ProviderDriverKind.make("cursor"),\n cwd: process.cwd(),\n runtimeMode: "approval-required",\n- modelSelection: { provider: "cursor", model: "default" },\n+ modelSelection: { instanceId: ProviderInstanceId.make("cursor"), model: "default" },\n });\n \n const sendTurnFiber = yield* adapter\n@@ -949,10 +991,10 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {\n \n yield* adapter.startSession({\n threadId,\n- provider: "cursor",\n+ provider: ProviderDriverKind.make("cursor"),\n cwd: process.cwd(),\n runtimeMode: "full-access",\n- modelSelection: { provider: "cursor", model: "default" },\n+ modelSelection: { instanceId: ProviderInstanceId.make("cursor"), model: "default" },\n });\n \n const sendTurnFiber = yield* adapter\n@@ -992,10 +1034,10 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {\n \n yield* adapter.startSession({\n threadId,\n- provider: "cursor",\n+ provider: ProviderDriverKind.make("cursor"),\n cwd: process.cwd(),\n runtimeMode: "full-access",\n- modelSelection: { provider: "cursor", model: "default" },\n+ modelSelection: { instanceId: ProviderInstanceId.make("cursor"), model: "default" },\n });\n \n const sendTurnFiber = yield* adapter\n@@ -1035,10 +1077,10 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {\n \n yield* adapter.startSession({\n threadId,\n- provider: "cursor",\n+ provider: ProviderDriverKind.make("cursor"),\n cwd: process.cwd(),\n runtimeMode: "full-access",\n- modelSelection: { provider: "cursor", model: "default" },\n+ modelSelection: { instanceId: ProviderInstanceId.make("cursor"), model: "default" },\n });\n \n const firstEvents = Array.from(yield* Fiber.join(firstConsumer));\n@@ -1073,10 +1115,10 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {\n \n yield* adapter.startSession({\n threadId,\n- provider: "cursor",\n+ provider: ProviderDriverKind.make("cursor"),\n cwd: process.cwd(),\n runtimeMode: "full-access",\n- modelSelection: { provider: "cursor", model: "composer-2" },\n+ modelSelection: { instanceId: ProviderInstanceId.make("cursor"), model: "composer-2" },\n });\n \n yield* adapter.sendTurn({\n@@ -1089,7 +1131,7 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {\n threadId,\n input: "second turn after switching model",\n attachments: [],\n- modelSelection: createModelSelection("cursor", "composer-2", [\n+ modelSelection: createModelSelection(ProviderInstanceId.make("cursor"), "composer-2", [\n { id: "fastMode", value: true },\n ]),\n });\n@@ -1136,17 +1178,17 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {\n \n yield* adapter.startSession({\n threadId,\n- provider: "cursor",\n+ provider: ProviderDriverKind.make("cursor"),\n cwd: process.cwd(),\n runtimeMode: "full-access",\n- modelSelection: { provider: "cursor", model: "composer-2" },\n+ modelSelection: { instanceId: ProviderInstanceId.make("cursor"), model: "composer-2" },\n });\n \n yield* adapter.sendTurn({\n threadId,\n input: "first turn with fast mode",\n attachments: [],\n- modelSelection: createModelSelection("cursor", "composer-2", [\n+ modelSelection: createModelSelection(ProviderInstanceId.make("cursor"), "composer-2", [\n { id: "fastMode", value: true },\n ]),\n });\n@@ -1155,7 +1197,7 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {\n threadId,\n input: "second turn without fast mode",\n attachments: [],\n- modelSelection: createModelSelection("cursor", "composer-2", [\n+ modelSelection: createModelSelection(ProviderInstanceId.make("cursor"), "composer-2", [\n { id: "fastMode", value: false },\n ]),\n });\n@@ -1174,4 +1216,91 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {\n yield* adapter.stopSession(threadId);\n }),\n );\n+\n+ it.effect(\n+ "applies fast mode on the first turn when modelSelection uses a non-default instance id",\n+ () => {\n+ const customInstanceId = ProviderInstanceId.make("cursor_secondary");\n+ // Custom-instance cases can\'t share the suite-level `CursorAdapter`\n+ // layer because that one binds `instanceId: "cursor"`. We build a\n+ // fresh layer graph — including a fresh `ServerSettingsService` — so\n+ // mid-test `updateSettings` calls target the same service instance the\n+ // adapter\'s `resolveSettings` reads from, and so the outer\n+ // `yield* ServerSettingsService` sees the same snapshot as well.\n+ const customAdapterLayer = Layer.effect(\n+ CursorAdapter,\n+ Effect.gen(function* () {\n+ const cursorConfig = Schema.decodeSync(CursorSettings)({});\n+ const resolveSettings = yield* makeResolveCursorSettings;\n+ return yield* makeCursorAdapter(cursorConfig, {\n+ instanceId: customInstanceId,\n+ resolveSettings,\n+ });\n+ }),\n+ ).pipe(\n+ Layer.provideMerge(ServerSettingsService.layerTest()),\n+ Layer.provideMerge(\n+ ServerConfig.layerTest(process.cwd(), {\n+ prefix: "t3code-cursor-adapter-custom-instance-",\n+ }),\n+ ),\n+ Layer.provideMerge(NodeServices.layer),\n+ );\n+\n+ return Effect.gen(function* () {\n+ const adapter = yield* CursorAdapter;\n+ const serverSettings = yield* ServerSettingsService;\n+ const threadId = ThreadId.make("cursor-fast-mode-custom-instance");\n+ const tempDir = yield* Effect.promise(() => mkdtemp(path.join(os.tmpdir(), "cursor-acp-")));\n+ const requestLogPath = path.join(tempDir, "requests.ndjson");\n+ const argvLogPath = path.join(tempDir, "argv.txt");\n+ yield* Effect.promise(() => writeFile(requestLogPath, "", "utf8"));\n+ const wrapperPath = yield* Effect.promise(() =>\n+ makeProbeWrapper(requestLogPath, argvLogPath),\n+ );\n+ yield* serverSettings.updateSettings({\n+ providers: { cursor: { binaryPath: wrapperPath } },\n+ });\n+\n+ yield* adapter.startSession({\n+ threadId,\n+ provider: ProviderDriverKind.make("cursor"),\n+ cwd: process.cwd(),\n+ runtimeMode: "full-access",\n+ modelSelection: {\n+ instanceId: customInstanceId,\n+ model: "composer-2",\n+ },\n+ });\n+\n+ yield* adapter.sendTurn({\n+ threadId,\n+ input: "first turn with fast mode",\n+ attachments: [],\n+ modelSelection: {\n+ ...createModelSelection(ProviderInstanceId.make("cursor"), "composer-2", [\n+ { id: "fastMode", value: true },\n+ ]),\n+ instanceId: customInstanceId,\n+ },\n+ });\n+\n+ const requests = yield* Effect.promise(() => readJsonLines(requestLogPath));\n+ const fastConfigRequests = requests.filter(\n+ (entry) =>\n+ entry.method === "session/set_config_option" &&\n+ (entry.params as Record<string, unknown> | undefined)?.configId === "fast",\n+ );\n+ assert.isAbove(\n+ fastConfigRequests.length,\n+ 0,\n+ "fast mode should apply when instance id matches the adapter binding",\n+ );\n+ const lastFastConfig = fastConfigRequests[fastConfigRequests.length - 1];\n+ assert.equal((lastFastConfig?.params as Record<string, unknown>)?.value, "true");\n+\n+ yield* adapter.stopSession(threadId);\n+ }).pipe(Effect.provide(customAdapterLayer));\n+ },\n+ );\n });\ndiff --git a/apps/server/src/provider/Layers/CursorAdapter.ts b/apps/server/src/provider/Layers/CursorAdapter.ts\nindex 5e12bfbefe..34d1221b02 100644\n--- a/apps/server/src/provider/Layers/CursorAdapter.ts\n+++ b/apps/server/src/provider/Layers/CursorAdapter.ts\n@@ -7,6 +7,7 @@ import * as nodePath from "node:path";\n \n import {\n ApprovalRequestId,\n+ type CursorSettings,\n type ProviderOptionSelection,\n EventId,\n type ProviderApprovalDecision,\n@@ -14,6 +15,8 @@ import {\n type ProviderRuntimeEvent,\n type ProviderSession,\n type ProviderUserInputAnswers,\n+ ProviderDriverKind,\n+ ProviderInstanceId,\n RuntimeRequestId,\n type RuntimeMode,\n type ThreadId,\n@@ -26,7 +29,6 @@ import {\n Exit,\n Fiber,\n FileSystem,\n- Layer,\n Option,\n PubSub,\n Random,\n@@ -40,7 +42,6 @@ import type * as EffectAcpSchema from "effect-acp/schema";\n \n import { resolveAttachmentPath } from "../../attachmentStore.ts";\n import { ServerConfig } from "../../config.ts";\n-import { ServerSettingsService } from "../../serverSettings.ts";\n import {\n ProviderAdapterProcessError,\n ProviderAdapterRequestError,\n@@ -72,19 +73,37 @@ import {\n extractPlanMarkdown,\n extractTodosAsPlan,\n } from "../acp/CursorAcpExtension.ts";\n-import { CursorAdapter, type CursorAdapterShape } from "../Services/CursorAdapter.ts";\n+import { type CursorAdapterShape } from "../Services/CursorAdapter.ts";\n import { resolveCursorAcpBaseModelId } from "./CursorProvider.ts";\n import { type EventNdjsonLogger, makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";\n \n-const PROVIDER = "cursor" as const;\n+const PROVIDER = ProviderDriverKind.make("cursor");\n const CURSOR_RESUME_VERSION = 1 as const;\n const ACP_PLAN_MODE_ALIASES = ["plan", "architect"];\n const ACP_IMPLEMENT_MODE_ALIASES = ["code", "agent", "default", "chat", "implement"];\n const ACP_APPROVAL_MODE_ALIASES = ["ask"];\n \n export interface CursorAdapterLiveOptions {\n+ readonly environment?: NodeJS.ProcessEnv;\n readonly nativeEventLogPath?: string;\n readonly nativeEventLogger?: EventNdjsonLogger;\n+ /**\n+ * Selections are honored when `modelSelection.instanceId` matches this value.\n+ * Defaults to the legacy built-in instance id (`cursor`).\n+ */\n+ readonly instanceId?: typeof ProviderInstanceId.Type;\n+ /**\n+ * Optional per-session settings resolver. When provided the adapter yields\n+ * this effect at the start of every session and uses the result instead of\n+ * the `cursorSettings` captured at construction.\n+ *\n+ * Production instances bind settings to the instance scope (the hydration\n+ * layer rebuilds the adapter on config change) and leave this undefined.\n+ * Test suites that mutate `ServerSettingsService` mid-flight — e.g. to\n+ * swap `binaryPath` to a mock ACP wrapper — pass a resolver that reads\n+ * the latest snapshot so the closure isn\'t stale.\n+ */\n+ readonly resolveSettings?: Effect.Effect<CursorSettings>;\n }\n \n interface PendingApproval {\n@@ -280,12 +299,15 @@ function selectAutoApprovedPermissionOption(\n return undefined;\n }\n \n-function makeCursorAdapter(options?: CursorAdapterLiveOptions) {\n+export function makeCursorAdapter(\n+ cursorSettings: CursorSettings,\n+ options?: CursorAdapterLiveOptions,\n+) {\n return Effect.gen(function* () {\n+ const boundInstanceId = options?.instanceId ?? ProviderInstanceId.make("cursor");\n const fileSystem = yield* FileSystem.FileSystem;\n const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;\n const serverConfig = yield* Effect.service(ServerConfig);\n- const serverSettingsService = yield* ServerSettingsService;\n const nativeEventLogger =\n options?.nativeEventLogger ??\n (options?.nativeEventLogPath !== undefined\n@@ -440,25 +462,12 @@ function makeCursorAdapter(options?: CursorAdapterLiveOptions) {\n \n const cwd = nodePath.resolve(input.cwd.trim());\n const cursorModelSelection =\n- input.modelSelection?.provider === "cursor" ? input.modelSelection : undefined;\n+ input.modelSelection?.instanceId === boundInstanceId ? input.modelSelection : undefined;\n const existing = sessions.get(input.threadId);\n if (existing && !existing.stopped) {\n yield* stopSessionInternal(existing);\n }\n \n- const cursorSettings = yield* serverSettingsService.getSettings.pipe(\n- Effect.map((settings) => settings.providers.cursor),\n- Effect.mapError(\n- (error) =>\n- new ProviderAdapterProcessError({\n- provider: PROVIDER,\n- threadId: input.threadId,\n- detail: error.message,\n- cause: error,\n- }),\n- ),\n- );\n-\n const pendingApprovals = new Map<ApprovalRequestId, PendingApproval>();\n const pendingUserInputs = new Map<ApprovalRequestId, PendingUserInput>();\n const sessionScope = yield* Scope.make("sequential");\n@@ -475,8 +484,21 @@ function makeCursorAdapter(options?: CursorAdapterLiveOptions) {\n threadId: input.threadId,\n });\n \n+ // Resolve the CursorSettings used to spawn the ACP child. Production\n+ // leaves `options.resolveSettings` undefined so we use the value\n+ // captured at adapter construction — per-instance isolation is\n+ // enforced by the hydration layer rebuilding this adapter whenever\n+ // its config changes. Tests set `resolveSettings` to pull the latest\n+ // snapshot from `ServerSettingsService` so that mid-suite\n+ // `updateSettings({ providers: { cursor: { binaryPath } } })` calls\n+ // actually take effect when the next session spawns.\n+ const effectiveCursorSettings = options?.resolveSettings\n+ ? yield* options.resolveSettings\n+ : cursorSettings;\n+\n const acp = yield* makeCursorAcpRuntime({\n- cursorSettings,\n+ cursorSettings: effectiveCursorSettings,\n+ ...(options?.environment ? { environment: options.environment } : {}),\n childProcessSpawner,\n cwd,\n ...(resumeSessionId ? { resumeSessionId } : {}),\n@@ -666,6 +688,7 @@ function makeCursorAdapter(options?: CursorAdapterLiveOptions) {\n const now = yield* nowIso;\n const session: ProviderSession = {\n provider: PROVIDER,\n+ providerInstanceId: boundInstanceId,\n status: "ready",\n runtimeMode: input.runtimeMode,\n cwd,\n@@ -815,7 +838,7 @@ function makeCursorAdapter(options?: CursorAdapterLiveOptions) {\n const ctx = yield* requireSession(input.threadId);\n const turnId = TurnId.make(crypto.randomUUID());\n const turnModelSelection =\n- input.modelSelection?.provider === "cursor" ? input.modelSelection : undefined;\n+ input.modelSelection?.instanceId === boundInstanceId ? input.modelSelection : undefined;\n const model = turnModelSelection?.model ?? ctx.session.model;\n const resolvedModel = resolveCursorAcpBaseModelId(model);\n yield* applyRequestedSessionConfiguration({\n@@ -1049,9 +1072,3 @@ function makeCursorAdapter(options?: CursorAdapterLiveOptions) {\n } satisfies CursorAdapterShape;\n });\n }\n-\n-export const CursorAdapterLive = Layer.effect(CursorAdapter, makeCursorAdapter());\n-\n-export function makeCursorAdapterLive(opts?: CursorAdapterLiveOptions) {\n- return Layer.effect(CursorAdapter, makeCursorAdapter(opts));\n-}\ndiff --git a/apps/server/src/provider/Layers/CursorProvider.test.ts b/apps/server/src/provider/Layers/CursorProvider.test.ts\nindex c0ac5d20b0..33ef20acf2 100644\n--- a/apps/server/src/provider/Layers/CursorProvider.test.ts\n+++ b/apps/server/src/provider/Layers/CursorProvider.test.ts\n@@ -1,10 +1,7 @@\n-import * as path from "node:path";\n-import * as os from "node:os";\n-import { chmod, mkdtemp, readFile, writeFile } from "node:fs/promises";\n-import { fileURLToPath } from "node:url";\n+import * as NodeOS from "node:os";\n \n import * as NodeServices from "@effect/platform-node/NodeServices";\n-import { Effect } from "effect";\n+import { Effect, FileSystem, Path } from "effect";\n import { describe, expect, it } from "vitest";\n import type * as EffectAcpSchema from "effect-acp/schema";\n import type { CursorSettings, ServerProviderModel } from "@t3tools/contracts";\n@@ -14,6 +11,7 @@ import {\n buildCursorProviderSnapshot,\n buildCursorCapabilitiesFromConfigOptions,\n buildCursorDiscoveredModelsFromConfigOptions,\n+ checkCursorProviderStatus,\n discoverCursorModelCapabilitiesViaAcp,\n discoverCursorModelsViaAcp,\n getCursorFallbackModels,\n@@ -25,8 +23,14 @@ import {\n resolveCursorAcpConfigUpdates,\n } from "./CursorProvider.ts";\n \n-const __dirname = path.dirname(fileURLToPath(import.meta.url));\n-const mockAgentPath = path.join(__dirname, "../../../scripts/acp-mock-agent.ts");\n+const runNode = <A, E>(\n+ effect: Effect.Effect<A, E, FileSystem.FileSystem | Path.Path>,\n+): Promise<A> => Effect.runPromise(effect.pipe(Effect.provide(NodeServices.layer)));\n+\n+const resolveMockAgentPath = Effect.fn("resolveMockAgentPath")(function* () {\n+ const path = yield* Path.Path;\n+ return yield* path.fromFileUrl(new URL("../../../scripts/acp-mock-agent.ts", import.meta.url));\n+});\n \n function selectDescriptor(\n id: string,\n@@ -53,8 +57,16 @@ function booleanDescriptor(id: string, label: string, currentValue?: boolean) {\n };\n }\n \n-async function makeMockAgentWrapper(extraEnv?: Record<string, string>) {\n- const dir = await mkdtemp(path.join(os.tmpdir(), "cursor-provider-mock-"));\n+const makeMockAgentWrapper = Effect.fn("makeMockAgentWrapper")(function* (\n+ extraEnv?: Record<string, string>,\n+) {\n+ const fileSystem = yield* FileSystem.FileSystem;\n+ const path = yield* Path.Path;\n+ const mockAgentPath = yield* resolveMockAgentPath();\n+ const dir = yield* fileSystem.makeTempDirectory({\n+ directory: NodeOS.tmpdir(),\n+ prefix: "cursor-provider-mock-",\n+ });\n const wrapperPath = path.join(dir, "fake-agent.sh");\n const envExports = Object.entries(extraEnv ?? {})\n .map(([key, value]) => `export ${key}=${JSON.stringify(value)}`)\n@@ -63,23 +75,80 @@ async function makeMockAgentWrapper(extraEnv?: Record<string, string>) {\n ${envExports}\n exec ${JSON.stringify("bun")} ${JSON.stringify(mockAgentPath)} "$@"\n `;\n- await writeFile(wrapperPath, script, "utf8");\n- await chmod(wrapperPath, 0o755);\n+ yield* fileSystem.writeFileString(wrapperPath, script);\n+ yield* fileSystem.chmod(wrapperPath, 0o755);\n return wrapperPath;\n-}\n+});\n+\n+const makeMockAgentWithAboutWrapper = Effect.fn("makeMockAgentWithAboutWrapper")(function* () {\n+ const fileSystem = yield* FileSystem.FileSystem;\n+ const path = yield* Path.Path;\n+ const mockAgentPath = yield* resolveMockAgentPath();\n+ const dir = yield* fileSystem.makeTempDirectory({\n+ directory: NodeOS.tmpdir(),\n+ prefix: "cursor-provider-about-mock-",\n+ });\n+ const wrapperPath = path.join(dir, "fake-agent.sh");\n+ const script = `#!/bin/sh\n+if [ "$1" = "about" ]; then\n+ printf \'CLI Version 2026.04.09-f2b0fcd\\\\n\'\n+ printf \'User Email cursor@example.com\\\\n\'\n+ exit 0\n+fi\n+exec ${JSON.stringify("bun")} ${JSON.stringify(mockAgentPath)} "$@"\n+`;\n+ yield* fileSystem.writeFileString(wrapperPath, script);\n+ yield* fileSystem.chmod(wrapperPath, 0o755);\n+ return wrapperPath;\n+});\n \n-async function waitForFileContent(filePath: string, attempts = 40): Promise<string> {\n+const waitForFileContent = Effect.fn("waitForFileContent")(function* (\n+ filePath: string,\n+ attempts = 40,\n+) {\n+ const fileSystem = yield* FileSystem.FileSystem;\n for (let attempt = 0; attempt < attempts; attempt += 1) {\n- try {\n- const content = await readFile(filePath, "utf8");\n+ const content = yield* fileSystem\n+ .readFileString(filePath)\n+ .pipe(Effect.catch(() => Effect.void));\n+ if (content !== undefined) {\n if (content.trim().length > 0) {\n return content;\n }\n- } catch {}\n- await new Promise((resolve) => setTimeout(resolve, 50));\n+ }\n+ yield* Effect.sleep("50 millis");\n }\n- throw new Error(`Timed out waiting for file content at ${filePath}`);\n-}\n+ return yield* Effect.fail(new Error(`Timed out waiting for file content at ${filePath}`));\n+});\n+\n+const makeProviderStatusEnvFixture = Effect.fn("makeProviderStatusEnvFixture")(function* () {\n+ const fileSystem = yield* FileSystem.FileSystem;\n+ const path = yield* Path.Path;\n+ const tempDir = yield* fileSystem.makeTempDirectory({\n+ directory: NodeOS.tmpdir(),\n+ prefix: "cursor-provider-status-env-",\n+ });\n+ return {\n+ requestLogPath: path.join(tempDir, "requests.ndjson"),\n+ wrapperPath: yield* makeMockAgentWithAboutWrapper(),\n+ };\n+});\n+\n+const makeExitLogFixture = Effect.fn("makeExitLogFixture")(function* (prefix: string) {\n+ const fileSystem = yield* FileSystem.FileSystem;\n+ const path = yield* Path.Path;\n+ const tempDir = yield* fileSystem.makeTempDirectory({\n+ directory: NodeOS.tmpdir(),\n+ prefix,\n+ });\n+ const exitLogPath = path.join(tempDir, "exit.log");\n+ return {\n+ exitLogPath,\n+ wrapperPath: yield* makeMockAgentWrapper({\n+ T3_ACP_EXIT_LOG_PATH: exitLogPath,\n+ }),\n+ };\n+});\n \n const parameterizedGpt54ConfigOptions = [\n {\n@@ -428,9 +497,38 @@ describe("buildCursorDiscoveredModelsFromConfigOptions", () => {\n });\n });\n \n+describe("checkCursorProviderStatus", () => {\n+ it("passes the injected environment to ACP model discovery", async () => {\n+ const { requestLogPath, wrapperPath } = await runNode(makeProviderStatusEnvFixture());\n+\n+ const provider = await Effect.runPromise(\n+ checkCursorProviderStatus(\n+ {\n+ enabled: true,\n+ binaryPath: wrapperPath,\n+ apiEndpoint: "",\n+ customModels: [],\n+ },\n+ {\n+ ...process.env,\n+ T3_ACP_REQUEST_LOG_PATH: requestLogPath,\n+ },\n+ ).pipe(Effect.provide(NodeServices.layer)),\n+ );\n+\n+ expect(provider.models.map((model) => model.slug)).toEqual([\n+ "default",\n+ "composer-2",\n+ "gpt-5.4",\n+ "claude-opus-4-6",\n+ ]);\n+ await expect(runNode(waitForFileContent(requestLogPath))).resolves.toContain("initialize");\n+ });\n+});\n+\n describe("discoverCursorModelsViaAcp", () => {\n it("keeps the ACP probe runtime alive long enough to discover models", async () => {\n- const wrapperPath = await makeMockAgentWrapper();\n+ const wrapperPath = await runNode(makeMockAgentWrapper());\n \n const models = await Effect.runPromise(\n discoverCursorModelsViaAcp({\n@@ -450,11 +548,9 @@ describe("discoverCursorModelsViaAcp", () => {\n });\n \n it("closes the ACP probe runtime after discovery completes", async () => {\n- const tempDir = await mkdtemp(path.join(os.tmpdir(), "cursor-provider-exit-log-"));\n- const exitLogPath = path.join(tempDir, "exit.log");\n- const wrapperPath = await makeMockAgentWrapper({\n- T3_ACP_EXIT_LOG_PATH: exitLogPath,\n- });\n+ const { exitLogPath, wrapperPath } = await runNode(\n+ makeExitLogFixture("cursor-provider-exit-log-"),\n+ );\n \n await Effect.runPromise(\n discoverCursorModelsViaAcp({\n@@ -465,18 +561,16 @@ describe("discoverCursorModelsViaAcp", () => {\n }).pipe(Effect.provide(NodeServices.layer)),\n );\n \n- const exitLog = await waitForFileContent(exitLogPath);\n+ const exitLog = await runNode(waitForFileContent(exitLogPath));\n expect(exitLog).toContain("SIGTERM");\n });\n });\n \n describe("discoverCursorModelCapabilitiesViaAcp", () => {\n it("closes all ACP probe runtimes after capability enrichment completes", async () => {\n- const tempDir = await mkdtemp(path.join(os.tmpdir(), "cursor-capabilities-exit-log-"));\n- const exitLogPath = path.join(tempDir, "exit.log");\n- const wrapperPath = await makeMockAgentWrapper({\n- T3_ACP_EXIT_LOG_PATH: exitLogPath,\n- });\n+ const { exitLogPath, wrapperPath } = await runNode(\n+ makeExitLogFixture("cursor-capabilities-exit-log-"),\n+ );\n const existingModels: ReadonlyArray<ServerProviderModel> = [\n { slug: "default", name: "Auto", isCustom: false, capabilities: emptyCapabilities },\n { slug: "composer-2", name: "Composer 2", isCustom: false, capabilities: emptyCapabilities },\n@@ -508,7 +602,7 @@ describe("discoverCursorModelCapabilitiesViaAcp", () => {\n "claude-opus-4-6",\n ]);\n \n- const exitLog = await waitForFileContent(exitLogPath);\n+ const exitLog = await runNode(waitForFileContent(exitLogPath));\n expect(exitLog.match(/SIGTERM/g)?.length ?? 0).toBe(4);\n });\n });\n@@ -530,6 +624,7 @@ describe("parseCursorAboutOutput", () => {\n status: "ready",\n auth: {\n status: "authenticated",\n+ email: "jmarminge@gmail.com",\n type: "Team",\n label: "Cursor Team Subscription",\n },\ndiff --git a/apps/server/src/provider/Layers/CursorProvider.ts b/apps/server/src/provider/Layers/CursorProvider.ts\nindex 4225023f7d..ad52f63fbb 100644\n--- a/apps/server/src/provider/Layers/CursorProvider.ts\n+++ b/apps/server/src/provider/Layers/CursorProvider.ts\n@@ -1,6 +1,4 @@\n-import * as nodeFs from "node:fs";\n import * as nodeOs from "node:os";\n-import * as nodePath from "node:path";\n \n import type {\n CursorSettings,\n@@ -10,10 +8,10 @@ import type {\n ServerProviderAuth,\n ServerProviderModel,\n ServerProviderState,\n- ServerSettingsError,\n } from "@t3tools/contracts";\n+import { ProviderDriverKind } from "@t3tools/contracts";\n import type * as EffectAcpSchema from "effect-acp/schema";\n-import { Cause, Effect, Equal, Exit, Layer, Option, Result, Stream } from "effect";\n+import { Cause, Effect, Exit, FileSystem, Layer, Option, Path, Result } from "effect";\n import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";\n import {\n createModelCapabilities,\n@@ -29,13 +27,11 @@ import {\n isCommandMissingCause,\n providerModelsFromSettings,\n type CommandResult,\n+ type ServerProviderDraft,\n } from "../providerSnapshot.ts";\n-import { makeManagedServerProvider } from "../makeManagedServerProvider.ts";\n-import { CursorProvider } from "../Services/CursorProvider.ts";\n import { AcpSessionRuntime } from "../acp/AcpSessionRuntime.ts";\n-import { ServerSettingsService } from "../../serverSettings.ts";\n \n-const PROVIDER = "cursor" as const;\n+const PROVIDER = ProviderDriverKind.make("cursor");\n const CURSOR_PRESENTATION = {\n displayName: "Cursor",\n badgeLabel: "Early Access",\n@@ -48,7 +44,6 @@ const EMPTY_CAPABILITIES: ModelCapabilities = createModelCapabilities({\n const CURSOR_ACP_MODEL_DISCOVERY_TIMEOUT_MS = 15_000;\n const CURSOR_ACP_MODEL_CAPABILITY_TIMEOUT = "4 seconds";\n const CURSOR_ACP_MODEL_DISCOVERY_CONCURRENCY = 4;\n-const CURSOR_REFRESH_INTERVAL = "1 hour";\n const CURSOR_PARAMETERIZED_MODEL_PICKER_MIN_VERSION_DATE = 2026_04_08;\n export const CURSOR_PARAMETERIZED_MODEL_PICKER_CAPABILITIES = {\n _meta: {\n@@ -56,13 +51,14 @@ export const CURSOR_PARAMETERIZED_MODEL_PICKER_CAPABILITIES = {\n },\n } satisfies NonNullable<EffectAcpSchema.InitializeRequest["clientCapabilities"]>;\n \n-function buildInitialCursorProviderSnapshot(cursorSettings: CursorSettings): ServerProvider {\n+export function buildInitialCursorProviderSnapshot(\n+ cursorSettings: CursorSettings,\n+): ServerProviderDraft {\n const checkedAt = new Date().toISOString();\n const models = getCursorFallbackModels(cursorSettings);\n \n if (!cursorSettings.enabled) {\n return buildServerProvider({\n- provider: PROVIDER,\n presentation: CURSOR_PRESENTATION,\n enabled: false,\n checkedAt,\n@@ -78,7 +74,6 @@ function buildInitialCursorProviderSnapshot(cursorSettings: CursorSettings): Ser\n }\n \n return buildServerProvider({\n- provider: PROVIDER,\n presentation: CURSOR_PRESENTATION,\n enabled: true,\n checkedAt,\n@@ -112,7 +107,12 @@ function flattenSessionConfigSelectOptions(\n }\n return configOption.options.flatMap((entry) =>\n "value" in entry\n- ? [{ value: entry.value.trim(), name: entry.name.trim() } satisfies CursorSessionSelectOption]\n+ ? [\n+ {\n+ value: entry.value.trim(),\n+ name: entry.name.trim(),\n+ } satisfies CursorSessionSelectOption,\n+ ]\n : entry.options.map(\n (option) =>\n ({\n@@ -392,7 +392,10 @@ export function buildCursorDiscoveredModelsFromConfigOptions(\n );\n }\n \n-const makeCursorAcpProbeRuntime = (cursorSettings: CursorSettings) =>\n+const makeCursorAcpProbeRuntime = (\n+ cursorSettings: CursorSettings,\n+ environment: NodeJS.ProcessEnv = process.env,\n+) =>\n Effect.gen(function* () {\n const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;\n const acpContext = yield* Layer.build(\n@@ -404,6 +407,7 @@ const makeCursorAcpProbeRuntime = (cursorSettings: CursorSettings) =>\n "acp",\n ],\n cwd: process.cwd(),\n+ env: environment,\n },\n cwd: process.cwd(),\n clientInfo: { name: "t3-code-provider-probe", version: "0.0.0" },\n@@ -417,7 +421,12 @@ const makeCursorAcpProbeRuntime = (cursorSettings: CursorSettings) =>\n const withCursorAcpProbeRuntime = <A, E, R>(\n cursorSettings: CursorSettings,\n useRuntime: (acp: AcpSessionRuntime["Service"]) => Effect.Effect<A, E, R>,\n-) => makeCursorAcpProbeRuntime(cursorSettings).pipe(Effect.flatMap(useRuntime), Effect.scoped);\n+ environment: NodeJS.ProcessEnv = process.env,\n+) =>\n+ makeCursorAcpProbeRuntime(cursorSettings, environment).pipe(\n+ Effect.flatMap(useRuntime),\n+ Effect.scoped,\n+ );\n \n function normalizeCursorConfigOptionToken(value: string | null | undefined): string {\n return (\n@@ -460,12 +469,18 @@ export function resolveCursorAcpBaseModelId(model: string | null | undefined): s\n export function resolveCursorAcpConfigUpdates(\n configOptions: ReadonlyArray<EffectAcpSchema.SessionConfigOption> | null | undefined,\n selections: ReadonlyArray<ProviderOptionSelection> | null | undefined,\n-): ReadonlyArray<{ readonly configId: string; readonly value: string | boolean }> {\n+): ReadonlyArray<{\n+ readonly configId: string;\n+ readonly value: string | boolean;\n+}> {\n if (!configOptions || configOptions.length === 0) {\n return [];\n }\n \n- const updates: Array<{ readonly configId: string; readonly value: string | boolean }> = [];\n+ const updates: Array<{\n+ readonly configId: string;\n+ readonly value: string | boolean;\n+ }> = [];\n \n const reasoningOption = findCursorEffortConfigOption(configOptions);\n const requestedReasoning = normalizeCursorReasoningValue(\n@@ -525,43 +540,129 @@ export function resolveCursorAcpConfigUpdates(\n return updates;\n }\n \n-export const discoverCursorModelsViaAcp = (cursorSettings: CursorSettings) =>\n- withCursorAcpProbeRuntime(cursorSettings, (acp) =>\n- Effect.map(acp.start(), (started) =>\n- buildCursorDiscoveredModelsFromConfigOptions(started.sessionSetupResult.configOptions ?? []),\n- ),\n+export const discoverCursorModelsViaAcp = (\n+ cursorSettings: CursorSettings,\n+ environment: NodeJS.ProcessEnv = process.env,\n+) =>\n+ withCursorAcpProbeRuntime(\n+ cursorSettings,\n+ (acp) =>\n+ Effect.map(acp.start(), (started) =>\n+ buildCursorDiscoveredModelsFromConfigOptions(\n+ started.sessionSetupResult.configOptions ?? [],\n+ ),\n+ ),\n+ environment,\n );\n \n export const discoverCursorModelCapabilitiesViaAcp = (\n cursorSettings: CursorSettings,\n existingModels: ReadonlyArray<ServerProviderModel>,\n+ environment: NodeJS.ProcessEnv = process.env,\n ) =>\n- withCursorAcpProbeRuntime(cursorSettings, (acp) =>\n- Effect.gen(function* () {\n- const started = yield* acp.start();\n- const initialConfigOptions = started.sessionSetupResult.configOptions ?? [];\n- const modelOption = findCursorModelConfigOption(initialConfigOptions);\n- const modelChoices = flattenSessionConfigSelectOptions(modelOption);\n- if (!modelOption || modelChoices.length === 0) {\n- return [];\n- }\n+ withCursorAcpProbeRuntime(\n+ cursorSettings,\n+ (acp) =>\n+ Effect.gen(function* () {\n+ const started = yield* acp.start();\n+ const initialConfigOptions = started.sessionSetupResult.configOptions ?? [];\n+ const modelOption = findCursorModelConfigOption(initialConfigOptions);\n+ const modelChoices = flattenSessionConfigSelectOptions(modelOption);\n+ if (!modelOption || modelChoices.length === 0) {\n+ return [];\n+ }\n+\n+ const currentModelValue =\n+ modelOption.type === "select" ? modelOption.currentValue?.trim() || undefined : undefined;\n+ const capabilitiesBySlug = new Map<string, ModelCapabilities>();\n+ if (currentModelValue) {\n+ capabilitiesBySlug.set(\n+ currentModelValue,\n+ buildCursorCapabilitiesFromConfigOptions(initialConfigOptions),\n+ );\n+ }\n \n- const currentModelValue =\n- modelOption.type === "select" ? modelOption.currentValue?.trim() || undefined : undefined;\n- const capabilitiesBySlug = new Map<string, ModelCapabilities>();\n- if (currentModelValue) {\n- capabilitiesBySlug.set(\n- currentModelValue,\n- buildCursorCapabilitiesFromConfigOptions(initialConfigOptions),\n+ const targetModelSlugs = new Set(\n+ existingModels\n+ .filter((model) => !model.isCustom && !hasCursorModelCapabilities(model))\n+ .map((model) => model.slug),\n );\n- }\n+ if (targetModelSlugs.size === 0) {\n+ return buildCursorDiscoveredModels(\n+ modelChoices.map((modelChoice) => ({\n+ slug: modelChoice.value.trim(),\n+ name: modelChoice.name.trim(),\n+ capabilities: capabilitiesBySlug.get(modelChoice.value.trim()) ?? EMPTY_CAPABILITIES,\n+ })),\n+ );\n+ }\n+\n+ const probedCapabilities = yield* Effect.forEach(\n+ modelChoices,\n+ (modelChoice) => {\n+ const modelSlug = modelChoice.value.trim();\n+ if (\n+ !modelSlug ||\n+ !targetModelSlugs.has(modelSlug) ||\n+ capabilitiesBySlug.has(modelSlug)\n+ ) {\n+ return Effect.void.pipe(\n+ Effect.as<readonly [string, ModelCapabilities] | undefined>(undefined),\n+ );\n+ }\n+\n+ return withCursorAcpProbeRuntime(\n+ cursorSettings,\n+ (probeAcp) =>\n+ Effect.gen(function* () {\n+ const probeStarted = yield* probeAcp.start();\n+ const probeConfigOptions = probeStarted.sessionSetupResult.configOptions ?? [];\n+ const probeModelOption = findCursorModelConfigOption(probeConfigOptions);\n+ const probeCurrentModelValue =\n+ probeModelOption?.type === "select"\n+ ? probeModelOption.currentValue?.trim() || undefined\n+ : undefined;\n+ yield* Effect.annotateCurrentSpan({\n+ "cursor.acp.model.value": modelSlug,\n+ "cursor.acp.model.currentValue": probeCurrentModelValue,\n+ "cursor.acp.config_option_id": probeModelOption?.id ?? modelOption.id,\n+ });\n+ const nextConfigOptions =\n+ probeCurrentModelValue === modelSlug\n+ ? probeConfigOptions\n+ : yield* probeAcp\n+ .setConfigOption(probeModelOption?.id ?? modelOption.id, modelSlug)\n+ .pipe(\n+ Effect.map((response) => response.configOptions ?? probeConfigOptions),\n+ );\n+ return [\n+ modelSlug,\n+ buildCursorCapabilitiesFromConfigOptions(nextConfigOptions),\n+ ] as const;\n+ }),\n+ environment,\n+ ).pipe(\n+ Effect.timeout(CURSOR_ACP_MODEL_CAPABILITY_TIMEOUT),\n+ Effect.retry({ times: 3 }),\n+ Effect.withSpan("cursor-acp-model-capability-probe"),\n+ Effect.catchCause((cause) =>\n+ Effect.logWarning("Cursor ACP capability probe failed", {\n+ modelSlug,\n+ cause: Cause.pretty(cause),\n+ }),\n+ ),\n+ );\n+ },\n+ { concurrency: CURSOR_ACP_MODEL_DISCOVERY_CONCURRENCY },\n+ );\n+\n+ for (const entry of probedCapabilities) {\n+ if (!entry) {\n+ continue;\n+ }\n+ capabilitiesBySlug.set(entry[0], entry[1]);\n+ }\n \n- const targetModelSlugs = new Set(\n- existingModels\n- .filter((model) => !model.isCustom && !hasCursorModelCapabilities(model))\n- .map((model) => model.slug),\n- );\n- if (targetModelSlugs.size === 0) {\n return buildCursorDiscoveredModels(\n modelChoices.map((modelChoice) => ({\n slug: modelChoice.value.trim(),\n@@ -569,73 +670,8 @@ export const discoverCursorModelCapabilitiesViaAcp = (\n capabilities: capabilitiesBySlug.get(modelChoice.value.trim()) ?? EMPTY_CAPABILITIES,\n })),\n );\n- }\n-\n- const probedCapabilities = yield* Effect.forEach(\n- modelChoices,\n- (modelChoice) => {\n- const modelSlug = modelChoice.value.trim();\n- if (!modelSlug || !targetModelSlugs.has(modelSlug) || capabilitiesBySlug.has(modelSlug)) {\n- return Effect.void.pipe(\n- Effect.as<readonly [string, ModelCapabilities] | undefined>(undefined),\n- );\n- }\n-\n- return withCursorAcpProbeRuntime(cursorSettings, (probeAcp) =>\n- Effect.gen(function* () {\n- const probeStarted = yield* probeAcp.start();\n- const probeConfigOptions = probeStarted.sessionSetupResult.configOptions ?? [];\n- const probeModelOption = findCursorModelConfigOption(probeConfigOptions);\n- const probeCurrentModelValue =\n- probeModelOption?.type === "select"\n- ? probeModelOption.currentValue?.trim() || undefined\n- : undefined;\n- yield* Effect.annotateCurrentSpan({\n- "cursor.acp.model.value": modelSlug,\n- "cursor.acp.model.currentValue": probeCurrentModelValue,\n- "cursor.acp.config_option_id": probeModelOption?.id ?? modelOption.id,\n- });\n- const nextConfigOptions =\n- probeCurrentModelValue === modelSlug\n- ? probeConfigOptions\n- : yield* probeAcp\n- .setConfigOption(probeModelOption?.id ?? modelOption.id, modelSlug)\n- .pipe(Effect.map((response) => response.configOptions ?? probeConfigOptions));\n- return [\n- modelSlug,\n- buildCursorCapabilitiesFromConfigOptions(nextConfigOptions),\n- ] as const;\n- }),\n- ).pipe(\n- Effect.timeout(CURSOR_ACP_MODEL_CAPABILITY_TIMEOUT),\n- Effect.retry({ times: 3 }),\n- Effect.withSpan("cursor-acp-model-capability-probe"),\n- Effect.catchCause((cause) =>\n- Effect.logWarning("Cursor ACP capability probe failed", {\n- modelSlug,\n- cause: Cause.pretty(cause),\n- }),\n- ),\n- );\n- },\n- { concurrency: CURSOR_ACP_MODEL_DISCOVERY_CONCURRENCY },\n- );\n-\n- for (const entry of probedCapabilities) {\n- if (!entry) {\n- continue;\n- }\n- capabilitiesBySlug.set(entry[0], entry[1]);\n- }\n-\n- return buildCursorDiscoveredModels(\n- modelChoices.map((modelChoice) => ({\n- slug: modelChoice.value.trim(),\n- name: modelChoice.name.trim(),\n- capabilities: capabilitiesBySlug.get(modelChoice.value.trim()) ?? EMPTY_CAPABILITIES,\n- })),\n- );\n- }).pipe(Effect.withSpan("cursor-acp-model-capability-discovery", {})),\n+ }).pipe(Effect.withSpan("cursor-acp-model-capability-discovery", {})),\n+ environment,\n );\n \n export function getCursorFallbackModels(\n@@ -683,10 +719,9 @@ export function buildCursorProviderSnapshot(input: {\n readonly parsed: CursorAboutResult;\n readonly discoveredModels?: ReadonlyArray<ServerProviderModel>;\n readonly discoveryWarning?: string;\n-}): ServerProvider {\n+}): ServerProviderDraft {\n const message = joinProviderMessages(input.parsed.message, input.discoveryWarning);\n return buildServerProvider({\n- provider: PROVIDER,\n presentation: CURSOR_PRESENTATION,\n enabled: input.cursorSettings.enabled,\n checkedAt: input.checkedAt,\n@@ -811,14 +846,13 @@ function isCursorAboutJsonFormatUnsupported(result: CommandResult): boolean {\n );\n }\n \n-function readCursorCliConfigChannel(): string | undefined {\n- try {\n- const configPath = nodePath.join(nodeOs.homedir(), ".cursor", "cli-config.json");\n- return parseCursorCliConfigChannel(nodeFs.readFileSync(configPath, "utf8"));\n- } catch {\n- return undefined;\n- }\n-}\n+const readCursorCliConfigChannel = Effect.fn("readCursorCliConfigChannel")(function* () {\n+ const fileSystem = yield* FileSystem.FileSystem;\n+ const path = yield* Path.Path;\n+ const configPath = path.join(nodeOs.homedir(), ".cursor", "cli-config.json");\n+ const raw = yield* fileSystem.readFileString(configPath).pipe(Effect.orElseSucceed(() => ""));\n+ return parseCursorCliConfigChannel(raw);\n+});\n \n export function getCursorParameterizedModelPickerUnsupportedMessage(input: {\n readonly version: string | null | undefined;\n@@ -934,6 +968,7 @@ export function parseCursorAboutOutput(result: CommandResult): CursorAboutResult\n status: "ready",\n auth: {\n status: "authenticated",\n+ email: userEmail,\n ...authMetadata,\n },\n };\n@@ -989,17 +1024,22 @@ export function parseCursorAboutOutput(result: CommandResult): CursorAboutResult\n }\n \n // Any non-empty email value means authenticated.\n- return { version, status: "ready", auth: { status: "authenticated" } };\n+ return {\n+ version,\n+ status: "ready",\n+ auth: { status: "authenticated", email: userEmail },\n+ };\n }\n \n-const runCursorCommand = (args: ReadonlyArray<string>) =>\n+const runCursorCommand = (\n+ cursorSettings: CursorSettings,\n+ args: ReadonlyArray<string>,\n+ environment: NodeJS.ProcessEnv = process.env,\n+) =>\n Effect.gen(function* () {\n const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;\n- const cursorSettings = yield* Effect.service(ServerSettingsService).pipe(\n- Effect.flatMap((service) => service.getSettings),\n- Effect.map((settings) => settings.providers.cursor),\n- );\n const command = ChildProcess.make(cursorSettings.binaryPath, [...args], {\n+ env: environment,\n shell: process.platform === "win32",\n });\n \n@@ -1016,203 +1056,202 @@ const runCursorCommand = (args: ReadonlyArray<string>) =>\n return { stdout, stderr, code: exitCode } satisfies CommandResult;\n }).pipe(Effect.scoped);\n \n-const runCursorAboutCommand = Effect.gen(function* () {\n- const jsonResult = yield* runCursorCommand(["about", "--format", "json"]);\n- if (!isCursorAboutJsonFormatUnsupported(jsonResult)) {\n- return jsonResult;\n- }\n- return yield* runCursorCommand(["about"]);\n-});\n-\n-export const checkCursorProviderStatus = Effect.fn("checkCursorProviderStatus")(\n- function* (): Effect.fn.Return<\n- ServerProvider,\n- ServerSettingsError,\n- ChildProcessSpawner.ChildProcessSpawner | ServerSettingsService\n- > {\n- const cursorSettings = yield* Effect.service(ServerSettingsService).pipe(\n- Effect.flatMap((service) => service.getSettings),\n- Effect.map((settings) => settings.providers.cursor),\n+const runCursorAboutCommand = (\n+ cursorSettings: CursorSettings,\n+ environment: NodeJS.ProcessEnv = process.env,\n+) =>\n+ Effect.gen(function* () {\n+ const jsonResult = yield* runCursorCommand(\n+ cursorSettings,\n+ ["about", "--format", "json"],\n+ environment,\n );\n- const checkedAt = new Date().toISOString();\n- const fallbackModels = getCursorFallbackModels(cursorSettings);\n-\n- if (!cursorSettings.enabled) {\n- return buildServerProvider({\n- provider: PROVIDER,\n- presentation: CURSOR_PRESENTATION,\n- enabled: false,\n- checkedAt,\n- models: fallbackModels,\n- probe: {\n- installed: false,\n- version: null,\n- status: "warning",\n- auth: { status: "unknown" },\n- message: "Cursor is disabled in T3 Code settings.",\n- },\n- });\n+ if (!isCursorAboutJsonFormatUnsupported(jsonResult)) {\n+ return jsonResult;\n }\n+ return yield* runCursorCommand(cursorSettings, ["about"], environment);\n+ });\n \n- // Single `agent about` probe: returns version + auth status in one call.\n- const aboutProbe = yield* runCursorAboutCommand.pipe(\n- Effect.timeoutOption(ABOUT_TIMEOUT_MS),\n- Effect.result,\n- );\n+export const checkCursorProviderStatus = Effect.fn("checkCursorProviderStatus")(function* (\n+ cursorSettings: CursorSettings,\n+ environment: NodeJS.ProcessEnv = process.env,\n+): Effect.fn.Return<\n+ ServerProviderDraft,\n+ never,\n+ ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path\n+> {\n+ const checkedAt = new Date().toISOString();\n+ const fallbackModels = getCursorFallbackModels(cursorSettings);\n \n- if (Result.isFailure(aboutProbe)) {\n- const error = aboutProbe.failure;\n- return buildServerProvider({\n- provider: PROVIDER,\n- presentation: CURSOR_PRESENTATION,\n- enabled: cursorSettings.enabled,\n- checkedAt,\n- models: fallbackModels,\n- probe: {\n- installed: !isCommandMissingCause(error),\n- version: null,\n- status: "error",\n- auth: { status: "unknown" },\n- message: isCommandMissingCause(error)\n- ? "Cursor Agent CLI (`agent`) is not installed or not on PATH."\n- : `Failed to execute Cursor Agent CLI health check: ${error instanceof Error ? error.message : String(error)}.`,\n- },\n- });\n- }\n+ if (!cursorSettings.enabled) {\n+ return buildServerProvider({\n+ presentation: CURSOR_PRESENTATION,\n+ enabled: false,\n+ checkedAt,\n+ models: fallbackModels,\n+ probe: {\n+ installed: false,\n+ version: null,\n+ status: "warning",\n+ auth: { status: "unknown" },\n+ message: "Cursor is disabled in T3 Code settings.",\n+ },\n+ });\n+ }\n \n- if (Option.isNone(aboutProbe.success)) {\n- return buildServerProvider({\n- provider: PROVIDER,\n- presentation: CURSOR_PRESENTATION,\n- enabled: cursorSettings.enabled,\n- checkedAt,\n- models: fallbackModels,\n- probe: {\n- installed: true,\n- version: null,\n- status: "error",\n- auth: { status: "unknown" },\n- message: "Cursor Agent CLI is installed but timed out while running `agent about`.",\n- },\n- });\n- }\n+ // Single `agent about` probe: returns version + auth status in one call.\n+ const aboutProbe = yield* runCursorAboutCommand(cursorSettings, environment).pipe(\n+ Effect.timeoutOption(ABOUT_TIMEOUT_MS),\n+ Effect.result,\n+ );\n \n- const parsed = parseCursorAboutOutput(aboutProbe.success.value);\n- const parameterizedModelPickerUnsupportedMessage =\n- getCursorParameterizedModelPickerUnsupportedMessage({\n- version: parsed.version,\n- channel: readCursorCliConfigChannel(),\n- });\n- if (parameterizedModelPickerUnsupportedMessage) {\n- return buildServerProvider({\n- provider: PROVIDER,\n- presentation: CURSOR_PRESENTATION,\n- enabled: cursorSettings.enabled,\n- checkedAt,\n- models: fallbackModels,\n- probe: {\n- installed: true,\n- version: parsed.version,\n- status: "error",\n- auth: parsed.auth,\n- message:\n- parsed.auth.status === "unauthenticated" && parsed.message\n- ? `${parameterizedModelPickerUnsupportedMessage} ${parsed.message}`\n- : parameterizedModelPickerUnsupportedMessage,\n- },\n- });\n- }\n- let discoveredModels = Option.none<ReadonlyArray<ServerProviderModel>>();\n- let discoveryWarning: string | undefined;\n- if (parsed.auth.status !== "unauthenticated") {\n- const discoveryExit = yield* Effect.exit(\n- discoverCursorModelsViaAcp(cursorSettings).pipe(\n- Effect.timeoutOption(CURSOR_ACP_MODEL_DISCOVERY_TIMEOUT_MS),\n- ),\n- );\n- if (Exit.isFailure(discoveryExit)) {\n- yield* Effect.logWarning("Cursor ACP model discovery failed", {\n- cause: Cause.pretty(discoveryExit.cause),\n- });\n- discoveryWarning = "Cursor ACP model discovery failed. Check server logs for details.";\n- } else if (Option.isNone(discoveryExit.value)) {\n- discoveryWarning = `Cursor ACP model discovery timed out after ${CURSOR_ACP_MODEL_DISCOVERY_TIMEOUT_MS}ms.`;\n- } else if (discoveryExit.value.value.length === 0) {\n- discoveryWarning = "Cursor ACP model discovery returned no built-in models.";\n- } else {\n- discoveredModels = discoveryExit.value;\n- }\n- }\n- return buildCursorProviderSnapshot({\n+ if (Result.isFailure(aboutProbe)) {\n+ const error = aboutProbe.failure;\n+ return buildServerProvider({\n+ presentation: CURSOR_PRESENTATION,\n+ enabled: cursorSettings.enabled,\n checkedAt,\n- cursorSettings,\n- parsed,\n- discoveredModels: Option.getOrElse(\n- Option.filter(discoveredModels, (models) => models.length > 0),\n- () => [] as const,\n- ),\n- ...(discoveryWarning ? { discoveryWarning } : {}),\n+ models: fallbackModels,\n+ probe: {\n+ installed: !isCommandMissingCause(error),\n+ version: null,\n+ status: "error",\n+ auth: { status: "unknown" },\n+ message: isCommandMissingCause(error)\n+ ? "Cursor Agent CLI (`agent`) is not installed or not on PATH."\n+ : `Failed to execute Cursor Agent CLI health check: ${error instanceof Error ? error.message : String(error)}.`,\n+ },\n });\n- },\n-);\n+ }\n \n-export const CursorProviderLive = Layer.effect(\n- CursorProvider,\n- Effect.gen(function* () {\n- const serverSettings = yield* ServerSettingsService;\n- const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;\n+ if (Option.isNone(aboutProbe.success)) {\n+ return buildServerProvider({\n+ presentation: CURSOR_PRESENTATION,\n+ enabled: cursorSettings.enabled,\n+ checkedAt,\n+ models: fallbackModels,\n+ probe: {\n+ installed: true,\n+ version: null,\n+ status: "error",\n+ auth: { status: "unknown" },\n+ message: "Cursor Agent CLI is installed but timed out while running `agent about`.",\n+ },\n+ });\n+ }\n \n- const checkProvider = checkCursorProviderStatus().pipe(\n- Effect.provideService(ServerSettingsService, serverSettings),\n- Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),\n+ const parsed = parseCursorAboutOutput(aboutProbe.success.value);\n+ const cursorCliConfigChannel = yield* readCursorCliConfigChannel();\n+ const parameterizedModelPickerUnsupportedMessage =\n+ getCursorParameterizedModelPickerUnsupportedMessage({\n+ version: parsed.version,\n+ channel: cursorCliConfigChannel,\n+ });\n+ if (parameterizedModelPickerUnsupportedMessage) {\n+ return buildServerProvider({\n+ presentation: CURSOR_PRESENTATION,\n+ enabled: cursorSettings.enabled,\n+ checkedAt,\n+ models: fallbackModels,\n+ probe: {\n+ installed: true,\n+ version: parsed.version,\n+ status: "error",\n+ auth: parsed.auth,\n+ message:\n+ parsed.auth.status === "unauthenticated" && parsed.message\n+ ? `${parameterizedModelPickerUnsupportedMessage} ${parsed.message}`\n+ : parameterizedModelPickerUnsupportedMessage,\n+ },\n+ });\n+ }\n+ let discoveredModels = Option.none<ReadonlyArray<ServerProviderModel>>();\n+ let discoveryWarning: string | undefined;\n+ if (parsed.auth.status !== "unauthenticated") {\n+ const discoveryExit = yield* Effect.exit(\n+ discoverCursorModelsViaAcp(cursorSettings, environment).pipe(\n+ Effect.timeoutOption(CURSOR_ACP_MODEL_DISCOVERY_TIMEOUT_MS),\n+ ),\n );\n+ if (Exit.isFailure(discoveryExit)) {\n+ yield* Effect.logWarning("Cursor ACP model discovery failed", {\n+ cause: Cause.pretty(discoveryExit.cause),\n+ });\n+ discoveryWarning = "Cursor ACP model discovery failed. Check server logs for details.";\n+ } else if (Option.isNone(discoveryExit.value)) {\n+ discoveryWarning = `Cursor ACP model discovery timed out after ${CURSOR_ACP_MODEL_DISCOVERY_TIMEOUT_MS}ms.`;\n+ } else if (discoveryExit.value.value.length === 0) {\n+ discoveryWarning = "Cursor ACP model discovery returned no built-in models.";\n+ } else {\n+ discoveredModels = discoveryExit.value;\n+ }\n+ }\n+ return buildCursorProviderSnapshot({\n+ checkedAt,\n+ cursorSettings,\n+ parsed,\n+ discoveredModels: Option.getOrElse(\n+ Option.filter(discoveredModels, (models) => models.length > 0),\n+ () => [] as const,\n+ ),\n+ ...(discoveryWarning ? { discoveryWarning } : {}),\n+ });\n+});\n \n- return yield* makeManagedServerProvider<CursorSettings>({\n- getSettings: serverSettings.getSettings.pipe(\n- Effect.map((settings) => settings.providers.cursor),\n- Effect.orDie,\n- ),\n- streamSettings: serverSettings.streamChanges.pipe(\n- Stream.map((settings) => settings.providers.cursor),\n- ),\n- haveSettingsChanged: (previous, next) => !Equal.equals(previous, next),\n- initialSnapshot: buildInitialCursorProviderSnapshot,\n- checkProvider,\n- enrichSnapshot: ({ settings, snapshot, publishSnapshot }) => {\n- if (\n- !settings.enabled ||\n- snapshot.auth.status === "unauthenticated" ||\n- !snapshot.models.some((model) => !model.isCustom && !hasCursorModelCapabilities(model))\n- ) {\n- return Effect.void;\n- }\n+export function hasUncapturedCursorModels(snapshot: Pick<ServerProvider, "models">): boolean {\n+ return snapshot.models.some((model) => !model.isCustom && !hasCursorModelCapabilities(model));\n+}\n \n- return discoverCursorModelCapabilitiesViaAcp(settings, snapshot.models).pipe(\n- Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),\n- Effect.flatMap((discoveredModels) => {\n- if (discoveredModels.length === 0) {\n- return Effect.void;\n- }\n+/**\n+ * Background capability enrichment for a Cursor snapshot.\n+ *\n+ * Used by `CursorDriver` as the `makeManagedServerProvider.enrichSnapshot`\n+ * hook: runs the slow ACP per-model capability probe, and republishes the\n+ * snapshot through `publishSnapshot` when new capabilities arrive. Skips\n+ * the probe when the provider is disabled, unauthenticated, or has no\n+ * uncaptured models. Keeps `EMPTY_CAPABILITIES` and the `PROVIDER` literal\n+ * private to this module.\n+ */\n+export const enrichCursorSnapshot = (input: {\n+ readonly settings: CursorSettings;\n+ readonly environment?: NodeJS.ProcessEnv;\n+ readonly snapshot: ServerProvider;\n+ readonly publishSnapshot: (snapshot: ServerProvider) => Effect.Effect<void>;\n+ readonly stampIdentity?: (snapshot: ServerProvider) => ServerProvider;\n+}): Effect.Effect<void, never, ChildProcessSpawner.ChildProcessSpawner> => {\n+ const { settings, snapshot, publishSnapshot } = input;\n+ const stampIdentity = input.stampIdentity ?? ((value) => value);\n \n- return publishSnapshot({\n- ...snapshot,\n- models: providerModelsFromSettings(\n- discoveredModels,\n- PROVIDER,\n- settings.customModels,\n- EMPTY_CAPABILITIES,\n- ),\n- });\n- }),\n- Effect.catchCause((cause) =>\n- Effect.logWarning("Cursor ACP background capability enrichment failed", {\n- models: snapshot.models.map((model) => model.slug),\n- cause: Cause.pretty(cause),\n- }).pipe(Effect.asVoid),\n+ if (\n+ !settings.enabled ||\n+ snapshot.auth.status === "unauthenticated" ||\n+ !hasUncapturedCursorModels(snapshot)\n+ ) {\n+ return Effect.void;\n+ }\n+\n+ return discoverCursorModelCapabilitiesViaAcp(settings, snapshot.models, input.environment).pipe(\n+ Effect.flatMap((discoveredModels) => {\n+ if (discoveredModels.length === 0) {\n+ return Effect.void;\n+ }\n+ return publishSnapshot(\n+ stampIdentity({\n+ ...snapshot,\n+ models: providerModelsFromSettings(\n+ discoveredModels,\n+ PROVIDER,\n+ settings.customModels,\n+ EMPTY_CAPABILITIES,\n ),\n- );\n- },\n- refreshInterval: CURSOR_REFRESH_INTERVAL,\n- });\n- }),\n-);\n+ }),\n+ );\n+ }),\n+ Effect.catchCause((cause) =>\n+ Effect.logWarning("Cursor ACP background capability enrichment failed", {\n+ models: snapshot.models.map((model) => model.slug),\n+ cause: Cause.pretty(cause),\n+ }).pipe(Effect.asVoid),\n+ ),\n+ );\n+};\ndiff --git a/apps/server/src/provider/Layers/OpenCodeAdapter.test.ts b/apps/server/src/provider/Layers/OpenCodeAdapter.test.ts\nindex 9a391b5539..370e5c028f 100644\n--- a/apps/server/src/provider/Layers/OpenCodeAdapter.test.ts\n+++ b/apps/server/src/provider/Layers/OpenCodeAdapter.test.ts\n@@ -2,14 +2,20 @@ import assert from "node:assert/strict";\n \n import * as NodeServices from "@effect/platform-node/NodeServices";\n import { it } from "@effect/vitest";\n-import { Effect, Layer, Option } from "effect";\n+import { Context, Effect, Exit, Fiber, Layer, Option, Schema, Scope, Stream } from "effect";\n import { beforeEach } from "vitest";\n \n-import { ThreadId } from "@t3tools/contracts";\n+import {\n+ OpenCodeSettings,\n+ ProviderDriverKind,\n+ ProviderInstanceId,\n+ ThreadId,\n+} from "@t3tools/contracts";\n+import { createModelSelection } from "@t3tools/shared/model";\n import { ServerConfig } from "../../config.ts";\n import { ServerSettingsService } from "../../serverSettings.ts";\n import { ProviderSessionDirectory } from "../Services/ProviderSessionDirectory.ts";\n-import { OpenCodeAdapter } from "../Services/OpenCodeAdapter.ts";\n+import type { OpenCodeAdapterShape } from "../Services/OpenCodeAdapter.ts";\n import {\n OpenCodeRuntime,\n OpenCodeRuntimeError,\n@@ -17,10 +23,15 @@ import {\n } from "../opencodeRuntime.ts";\n import {\n appendOpenCodeAssistantTextDelta,\n- makeOpenCodeAdapterLive,\n+ makeOpenCodeAdapter,\n mergeOpenCodeAssistantText,\n } from "./OpenCodeAdapter.ts";\n \n+// Test-local service tag so the rest of the file can keep using `yield* OpenCodeAdapter`.\n+class OpenCodeAdapter extends Context.Service<OpenCodeAdapter, OpenCodeAdapterShape>()(\n+ "test/OpenCodeAdapter",\n+) {}\n+\n const asThreadId = (value: string): ThreadId => ThreadId.make(value);\n \n type MessageEntry = {\n@@ -39,6 +50,7 @@ const runtimeMock = {\n abortCalls: [] as string[],\n closeCalls: [] as string[],\n revertCalls: [] as Array<{ sessionID: string; messageID?: string }>,\n+ promptCalls: [] as Array<unknown>,\n promptAsyncError: null as Error | null,\n closeError: null as Error | null,\n messages: [] as MessageEntry[],\n@@ -51,6 +63,7 @@ const runtimeMock = {\n this.state.abortCalls.length = 0;\n this.state.closeCalls.length = 0;\n this.state.revertCalls.length = 0;\n+ this.state.promptCalls.length = 0;\n this.state.promptAsyncError = null;\n this.state.closeError = null;\n this.state.messages = [];\n@@ -111,7 +124,8 @@ const OpenCodeRuntimeTestDouble: OpenCodeRuntimeShape = {\n abort: async ({ sessionID }: { sessionID: string }) => {\n runtimeMock.state.abortCalls.push(sessionID);\n },\n- promptAsync: async () => {\n+ promptAsync: async (input: unknown) => {\n+ runtimeMock.state.promptCalls.push(input);\n if (runtimeMock.state.promptAsyncError) {\n throw runtimeMock.state.promptAsyncError;\n }\n@@ -165,7 +179,24 @@ const providerSessionDirectoryTestLayer = Layer.succeed(ProviderSessionDirectory\n listBindings: () => Effect.succeed([]),\n });\n \n-const OpenCodeAdapterTestLayer = makeOpenCodeAdapterLive().pipe(\n+// The adapter now receives its settings as a plain argument (the old design\n+// read from `ServerSettingsService` internally). The test-only\n+// `ServerSettingsService` below is still kept because other dependencies in\n+// the layer graph reach for it — but the routing values the assertions\n+// probe (serverUrl, serverPassword) must be threaded directly through the\n+// decoded `OpenCodeSettings`.\n+const openCodeAdapterTestSettings = Schema.decodeSync(OpenCodeSettings)({\n+ binaryPath: "fake-opencode",\n+ serverUrl: "http://127.0.0.1:9999",\n+ serverPassword: "secret-password",\n+});\n+\n+const OpenCodeAdapterTestLayer = Layer.effect(\n+ OpenCodeAdapter,\n+ Effect.gen(function* () {\n+ return yield* makeOpenCodeAdapter(openCodeAdapterTestSettings);\n+ }),\n+).pipe(\n Layer.provideMerge(Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble)),\n Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),\n Layer.provideMerge(\n@@ -196,7 +227,7 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => {\n const adapter = yield* OpenCodeAdapter;\n \n const session = yield* adapter.startSession({\n- provider: "opencode",\n+ provider: ProviderDriverKind.make("opencode"),\n threadId: asThreadId("thread-opencode"),\n runtimeMode: "full-access",\n });\n@@ -215,7 +246,7 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => {\n Effect.gen(function* () {\n const adapter = yield* OpenCodeAdapter;\n yield* adapter.startSession({\n- provider: "opencode",\n+ provider: ProviderDriverKind.make("opencode"),\n threadId: asThreadId("thread-opencode"),\n runtimeMode: "full-access",\n });\n@@ -230,16 +261,42 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => {\n }),\n );\n \n+ it.effect("emits one session.exited event when stopping a session", () =>\n+ Effect.gen(function* () {\n+ const adapter = yield* OpenCodeAdapter;\n+ const threadId = asThreadId("thread-opencode-stop-event");\n+ const eventsFiber = yield* adapter.streamEvents.pipe(\n+ Stream.filter((event) => event.threadId === threadId),\n+ Stream.take(3),\n+ Stream.runCollect,\n+ Effect.forkChild,\n+ );\n+\n+ yield* adapter.startSession({\n+ provider: ProviderDriverKind.make("opencode"),\n+ threadId,\n+ runtimeMode: "full-access",\n+ });\n+ yield* adapter.stopSession(threadId);\n+\n+ const events = Array.from(yield* Fiber.join(eventsFiber).pipe(Effect.timeout("1 second")));\n+ assert.deepEqual(\n+ events.map((event) => event.type),\n+ ["session.started", "thread.started", "session.exited"],\n+ );\n+ }),\n+ );\n+\n it.effect("clears session state even when cleanup finalizers throw", () =>\n Effect.gen(function* () {\n const adapter = yield* OpenCodeAdapter;\n yield* adapter.startSession({\n- provider: "opencode",\n+ provider: ProviderDriverKind.make("opencode"),\n threadId: asThreadId("thread-stop-all-a"),\n runtimeMode: "full-access",\n });\n yield* adapter.startSession({\n- provider: "opencode",\n+ provider: ProviderDriverKind.make("opencode"),\n threadId: asThreadId("thread-stop-all-b"),\n runtimeMode: "full-access",\n });\n@@ -261,11 +318,44 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => {\n }),\n );\n \n+ it.effect("completes streamEvents when the adapter scope closes", () =>\n+ Effect.gen(function* () {\n+ const scope = yield* Scope.make("sequential");\n+ let scopeClosed = false;\n+\n+ try {\n+ const adapterLayer = Layer.effect(\n+ OpenCodeAdapter,\n+ makeOpenCodeAdapter(openCodeAdapterTestSettings),\n+ ).pipe(\n+ Layer.provideMerge(Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble)),\n+ Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),\n+ Layer.provideMerge(ServerSettingsService.layerTest()),\n+ Layer.provideMerge(providerSessionDirectoryTestLayer),\n+ Layer.provideMerge(NodeServices.layer),\n+ );\n+ const context = yield* Layer.buildWithScope(adapterLayer, scope);\n+ const adapter = yield* Effect.service(OpenCodeAdapter).pipe(Effect.provide(context));\n+ const eventsFiber = yield* adapter.streamEvents.pipe(Stream.runCollect, Effect.forkChild);\n+\n+ yield* Scope.close(scope, Exit.void);\n+ scopeClosed = true;\n+\n+ const exit = yield* Fiber.await(eventsFiber).pipe(Effect.timeout("1 second"));\n+ assert.equal(Exit.hasInterrupts(exit), true);\n+ } finally {\n+ if (!scopeClosed) {\n+ yield* Scope.close(scope, Exit.void).pipe(Effect.ignore);\n+ }\n+ }\n+ }),\n+ );\n+\n it.effect("rolls back session state when sendTurn fails before OpenCode accepts the prompt", () =>\n Effect.gen(function* () {\n const adapter = yield* OpenCodeAdapter;\n yield* adapter.startSession({\n- provider: "opencode",\n+ provider: ProviderDriverKind.make("opencode"),\n threadId: asThreadId("thread-send-turn-failure"),\n runtimeMode: "full-access",\n });\n@@ -276,7 +366,7 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => {\n threadId: asThreadId("thread-send-turn-failure"),\n input: "Fix it",\n modelSelection: {\n- provider: "opencode",\n+ instanceId: ProviderInstanceId.make("opencode"),\n model: "openai/gpt-5",\n },\n })\n@@ -299,12 +389,158 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => {\n }),\n );\n \n+ it.effect("passes agent and variant options for the adapter\'s bound custom instance id", () => {\n+ const customInstanceId = ProviderInstanceId.make("opencode_zen");\n+ const adapterLayer = Layer.effect(\n+ OpenCodeAdapter,\n+ Effect.gen(function* () {\n+ return yield* makeOpenCodeAdapter(openCodeAdapterTestSettings, {\n+ instanceId: customInstanceId,\n+ });\n+ }),\n+ ).pipe(\n+ Layer.provideMerge(Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble)),\n+ Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),\n+ Layer.provideMerge(ServerSettingsService.layerTest()),\n+ Layer.provideMerge(providerSessionDirectoryTestLayer),\n+ Layer.provideMerge(NodeServices.layer),\n+ );\n+\n+ return Effect.gen(function* () {\n+ const adapter = yield* OpenCodeAdapter;\n+ yield* adapter.startSession({\n+ provider: ProviderDriverKind.make("opencode"),\n+ threadId: asThreadId("thread-custom-instance"),\n+ runtimeMode: "full-access",\n+ });\n+\n+ yield* adapter.sendTurn({\n+ threadId: asThreadId("thread-custom-instance"),\n+ input: "Fix it",\n+ modelSelection: createModelSelection(\n+ ProviderInstanceId.make("opencode_zen"),\n+ "anthropic/claude-sonnet-4-5",\n+ [\n+ { id: "agent", value: "github-copilot" },\n+ { id: "variant", value: "high" },\n+ ],\n+ ),\n+ });\n+\n+ assert.deepEqual(runtimeMock.state.promptCalls.at(-1), {\n+ sessionID: "http://127.0.0.1:9999/session",\n+ model: {\n+ providerID: "anthropic",\n+ modelID: "claude-sonnet-4-5",\n+ },\n+ agent: "github-copilot",\n+ variant: "high",\n+ parts: [{ type: "text", text: "Fix it" }],\n+ });\n+ }).pipe(Effect.provide(adapterLayer));\n+ });\n+\n+ it.effect("uses the bound custom instance id for fallback sendTurn model selection", () => {\n+ const customInstanceId = ProviderInstanceId.make("opencode_zen");\n+ const adapterLayer = Layer.effect(\n+ OpenCodeAdapter,\n+ Effect.gen(function* () {\n+ return yield* makeOpenCodeAdapter(openCodeAdapterTestSettings, {\n+ instanceId: customInstanceId,\n+ });\n+ }),\n+ ).pipe(\n+ Layer.provideMerge(Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble)),\n+ Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),\n+ Layer.provideMerge(ServerSettingsService.layerTest()),\n+ Layer.provideMerge(providerSessionDirectoryTestLayer),\n+ Layer.provideMerge(NodeServices.layer),\n+ );\n+\n+ return Effect.gen(function* () {\n+ const adapter = yield* OpenCodeAdapter;\n+ const threadId = asThreadId("thread-custom-instance-fallback-model");\n+ yield* adapter.startSession({\n+ provider: ProviderDriverKind.make("opencode"),\n+ threadId,\n+ runtimeMode: "full-access",\n+ modelSelection: createModelSelection(\n+ ProviderInstanceId.make("opencode_zen"),\n+ "anthropic/claude-sonnet-4-5",\n+ ),\n+ });\n+\n+ yield* adapter.sendTurn({\n+ threadId,\n+ input: "Fix it",\n+ });\n+\n+ assert.deepEqual(runtimeMock.state.promptCalls.at(-1), {\n+ sessionID: "http://127.0.0.1:9999/session",\n+ model: {\n+ providerID: "anthropic",\n+ modelID: "claude-sonnet-4-5",\n+ },\n+ parts: [{ type: "text", text: "Fix it" }],\n+ });\n+ }).pipe(Effect.provide(adapterLayer));\n+ });\n+\n+ it.effect("rejects sendTurn model selections for another instance id", () => {\n+ const customInstanceId = ProviderInstanceId.make("opencode_zen");\n+ const adapterLayer = Layer.effect(\n+ OpenCodeAdapter,\n+ Effect.gen(function* () {\n+ return yield* makeOpenCodeAdapter(openCodeAdapterTestSettings, {\n+ instanceId: customInstanceId,\n+ });\n+ }),\n+ ).pipe(\n+ Layer.provideMerge(Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble)),\n+ Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),\n+ Layer.provideMerge(ServerSettingsService.layerTest()),\n+ Layer.provideMerge(providerSessionDirectoryTestLayer),\n+ Layer.provideMerge(NodeServices.layer),\n+ );\n+\n+ return Effect.gen(function* () {\n+ const adapter = yield* OpenCodeAdapter;\n+ const threadId = asThreadId("thread-custom-instance-wrong-selection");\n+ yield* adapter.startSession({\n+ provider: ProviderDriverKind.make("opencode"),\n+ threadId,\n+ runtimeMode: "full-access",\n+ });\n+\n+ const error = yield* adapter\n+ .sendTurn({\n+ threadId,\n+ input: "Fix it",\n+ modelSelection: createModelSelection(\n+ ProviderInstanceId.make("opencode"),\n+ "anthropic/claude-sonnet-4-5",\n+ ),\n+ })\n+ .pipe(Effect.flip);\n+\n+ assert.equal(error._tag, "ProviderAdapterValidationError");\n+ if (error._tag !== "ProviderAdapterValidationError") {\n+ throw new Error("Unexpected error type");\n+ }\n+ assert.equal(\n+ error.issue,\n+ "OpenCode model selection is bound to instance \'opencode\', expected \'opencode_zen\'.",\n+ );\n+ assert.deepEqual(runtimeMock.state.promptCalls, []);\n+ }).pipe(Effect.provide(adapterLayer));\n+ });\n+\n it.effect("reverts the full thread when rollback removes every assistant turn", () =>\n Effect.gen(function* () {\n const adapter = yield* OpenCodeAdapter;\n const threadId = asThreadId("thread-rollback-all");\n yield* adapter.startSession({\n- provider: "opencode",\n+ provider: ProviderDriverKind.make("opencode"),\n threadId,\n runtimeMode: "full-access",\n });\n@@ -396,9 +632,14 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => {\n close: () => Effect.void,\n };\n \n- const adapterLayer = makeOpenCodeAdapterLive({\n- nativeEventLogger,\n- }).pipe(\n+ const adapterLayer = Layer.effect(\n+ OpenCodeAdapter,\n+ Effect.gen(function* () {\n+ return yield* makeOpenCodeAdapter(openCodeAdapterTestSettings, {\n+ nativeEventLogger,\n+ });\n+ }),\n+ ).pipe(\n Layer.provideMerge(Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble)),\n Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),\n Layer.provideMerge(\n@@ -419,7 +660,7 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => {\n const session = yield* Effect.gen(function* () {\n const adapter = yield* OpenCodeAdapter;\n const started = yield* adapter.startSession({\n- provider: "opencode",\n+ provider: ProviderDriverKind.make("opencode"),\n threadId: asThreadId("thread-native-log"),\n runtimeMode: "full-access",\n });\n@@ -475,9 +716,12 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => {\n close: () => Effect.void,\n };\n \n- const adapterLayer = makeOpenCodeAdapterLive({\n- nativeEventLogger,\n- }).pipe(\n+ const adapterLayer = Layer.effect(\n+ OpenCodeAdapter,\n+ makeOpenCodeAdapter(openCodeAdapterTestSettings, {\n+ nativeEventLogger,\n+ }),\n+ ).pipe(\n Layer.provideMerge(Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble)),\n Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),\n Layer.provideMerge(\n@@ -504,7 +748,7 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => {\n const { sessions, closeCallsDuringRun } = yield* Effect.gen(function* () {\n const adapter = yield* OpenCodeAdapter;\n yield* adapter.startSession({\n- provider: "opencode",\n+ provider: ProviderDriverKind.make("opencode"),\n threadId: asThreadId("thread-native-log-failure"),\n runtimeMode: "full-access",\n });\ndiff --git a/apps/server/src/provider/Layers/OpenCodeAdapter.ts b/apps/server/src/provider/Layers/OpenCodeAdapter.ts\nindex aa504d5b96..a7b179ab1c 100644\n--- a/apps/server/src/provider/Layers/OpenCodeAdapter.ts\n+++ b/apps/server/src/provider/Layers/OpenCodeAdapter.ts\n@@ -1,7 +1,8 @@\n-import { randomUUID } from "node:crypto";\n-\n import {\n EventId,\n+ type OpenCodeSettings,\n+ ProviderDriverKind,\n+ ProviderInstanceId,\n type ProviderRuntimeEvent,\n type ProviderSession,\n RuntimeItemId,\n@@ -11,13 +12,12 @@ import {\n TurnId,\n type UserInputQuestion,\n } from "@t3tools/contracts";\n-import { Cause, Effect, Exit, Layer, Queue, Ref, Scope, Stream } from "effect";\n+import { Cause, Effect, Exit, Queue, Random, Ref, Scope, Stream } from "effect";\n import type { OpencodeClient, Part, PermissionRequest, QuestionRequest } from "@opencode-ai/sdk/v2";\n import { getModelSelectionStringOptionValue } from "@t3tools/shared/model";\n \n import { resolveAttachmentPath } from "../../attachmentStore.ts";\n import { ServerConfig } from "../../config.ts";\n-import { ServerSettingsService } from "../../serverSettings.ts";\n import { type EventNdjsonLogger, makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";\n import {\n ProviderAdapterProcessError,\n@@ -26,7 +26,7 @@ import {\n ProviderAdapterSessionNotFoundError,\n ProviderAdapterValidationError,\n } from "../Errors.ts";\n-import { OpenCodeAdapter, type OpenCodeAdapterShape } from "../Services/OpenCodeAdapter.ts";\n+import { type OpenCodeAdapterShape } from "../Services/OpenCodeAdapter.ts";\n import {\n buildOpenCodePermissionRules,\n OpenCodeRuntime,\n@@ -41,7 +41,7 @@ import {\n type OpenCodeServerConnection,\n } from "../opencodeRuntime.ts";\n \n-const PROVIDER = "opencode" as const;\n+const PROVIDER = ProviderDriverKind.make("opencode");\n \n interface OpenCodeTurnSnapshot {\n readonly id: TurnId;\n@@ -89,6 +89,8 @@ interface OpenCodeSessionContext {\n }\n \n export interface OpenCodeAdapterLiveOptions {\n+ readonly instanceId?: ProviderInstanceId;\n+ readonly environment?: NodeJS.ProcessEnv;\n readonly nativeEventLogPath?: string;\n readonly nativeEventLogger?: EventNdjsonLogger;\n }\n@@ -125,35 +127,38 @@ const toProcessError = (threadId: ThreadId, cause: unknown): ProviderAdapterProc\n cause,\n });\n \n-function buildEventBase(input: {\n+const buildEventBase = (input: {\n readonly threadId: ThreadId;\n readonly turnId?: TurnId | undefined;\n readonly itemId?: string | undefined;\n readonly requestId?: string | undefined;\n readonly createdAt?: string | undefined;\n readonly raw?: unknown;\n-}): Pick<\n- ProviderRuntimeEvent,\n- "eventId" | "provider" | "threadId" | "createdAt" | "turnId" | "itemId" | "requestId" | "raw"\n-> {\n- return {\n- eventId: EventId.make(randomUUID()),\n- provider: PROVIDER,\n- threadId: input.threadId,\n- createdAt: input.createdAt ?? nowIso(),\n- ...(input.turnId ? { turnId: input.turnId } : {}),\n- ...(input.itemId ? { itemId: RuntimeItemId.make(input.itemId) } : {}),\n- ...(input.requestId ? { requestId: RuntimeRequestId.make(input.requestId) } : {}),\n- ...(input.raw !== undefined\n- ? {\n- raw: {\n- source: "opencode.sdk.event",\n- payload: input.raw,\n- },\n- }\n- : {}),\n- };\n-}\n+}): Effect.Effect<\n+ Pick<\n+ ProviderRuntimeEvent,\n+ "eventId" | "provider" | "threadId" | "createdAt" | "turnId" | "itemId" | "requestId" | "raw"\n+ >\n+> =>\n+ Random.nextUUIDv4.pipe(\n+ Effect.map((uuid) => ({\n+ eventId: EventId.make(uuid),\n+ provider: PROVIDER,\n+ threadId: input.threadId,\n+ createdAt: input.createdAt ?? nowIso(),\n+ ...(input.turnId ? { turnId: input.turnId } : {}),\n+ ...(input.itemId ? { itemId: RuntimeItemId.make(input.itemId) } : {}),\n+ ...(input.requestId ? { requestId: RuntimeRequestId.make(input.requestId) } : {}),\n+ ...(input.raw !== undefined\n+ ? {\n+ raw: {\n+ source: "opencode.sdk.event",\n+ payload: input.raw,\n+ },\n+ }\n+ : {}),\n+ })),\n+ );\n \n function toToolLifecycleItemType(toolName: string): ToolLifecycleItemType {\n const normalized = toolName.toLowerCase();\n@@ -245,13 +250,19 @@ function ensureSessionContext(\n ): OpenCodeSessionContext {\n const session = sessions.get(threadId);\n if (!session) {\n- throw new ProviderAdapterSessionNotFoundError({ provider: PROVIDER, threadId });\n+ throw new ProviderAdapterSessionNotFoundError({\n+ provider: PROVIDER,\n+ threadId,\n+ });\n }\n // `ensureSessionContext` is a sync gate used from both sync helpers and\n // Effect bodies. `Ref.getUnsafe` is an atomic read of the backing cell —\n // no fiber suspension required, which keeps this callable everywhere.\n if (Ref.getUnsafe(session.stopped)) {\n- throw new ProviderAdapterSessionClosedError({ provider: PROVIDER, threadId });\n+ throw new ProviderAdapterSessionClosedError({\n+ provider: PROVIDER,\n+ threadId,\n+ });\n }\n return session;\n }\n@@ -419,7 +430,7 @@ const stopOpenCodeContext = Effect.fn("stopOpenCodeContext")(function* (\n ) {\n // Race-safe one-shot: first caller flips the flag, everyone else no-ops.\n if (yield* Ref.getAndSet(context.stopped, true)) {\n- return;\n+ return false;\n }\n \n // Best-effort remote abort. The scope close below tears down the local\n@@ -433,957 +444,990 @@ const stopOpenCodeContext = Effect.fn("stopOpenCodeContext")(function* (\n // runs each finalizer we registered — the `AbortController.abort()` call,\n // the child-process termination, etc.\n yield* Scope.close(context.sessionScope, Exit.void);\n+ return true;\n });\n \n-export function makeOpenCodeAdapterLive(options?: OpenCodeAdapterLiveOptions) {\n- return Layer.effect(\n- OpenCodeAdapter,\n- Effect.gen(function* () {\n- const serverConfig = yield* ServerConfig;\n- const serverSettings = yield* ServerSettingsService;\n- const openCodeRuntime = yield* OpenCodeRuntime;\n- const nativeEventLogger =\n- options?.nativeEventLogger ??\n- (options?.nativeEventLogPath !== undefined\n- ? yield* makeEventNdjsonLogger(options.nativeEventLogPath, {\n- stream: "native",\n- })\n- : undefined);\n- // Only close loggers we created. If the caller passed one in via\n- // `options.nativeEventLogger`, they own its lifecycle.\n- const managedNativeEventLogger =\n- options?.nativeEventLogger === undefined ? nativeEventLogger : undefined;\n- const runtimeEvents = yield* Queue.unbounded<ProviderRuntimeEvent>();\n- const sessions = new Map<ThreadId, OpenCodeSessionContext>();\n-\n- // Layer-level finalizer: when the adapter layer shuts down, stop every\n- // session. Each session\'s `Scope.close` tears down its spawned OpenCode\n- // server (via the `ChildProcessSpawner` finalizer installed in\n- // `startOpenCodeServerProcess`) and interrupts the forked event/exit\n- // fibers. Consumers that can\'t reason about Effect scopes therefore\n- // cannot leak OpenCode child processes by forgetting to call `stopAll`.\n- yield* Effect.addFinalizer(() =>\n- Effect.gen(function* () {\n- const contexts = [...sessions.values()];\n- sessions.clear();\n- // `ignoreCause` swallows both typed failures (none here) and defects\n- // from throwing scope finalizers so a sibling\'s death can\'t interrupt\n- // the remaining cleanups.\n- yield* Effect.forEach(\n- contexts,\n- (context) => Effect.ignoreCause(stopOpenCodeContext(context)),\n- { concurrency: "unbounded", discard: true },\n- );\n- // Close the logger AFTER session teardown so any final lifecycle\n- // events emitted during shutdown still get written. `close` flushes\n- // the `Logger.batched` window and closes each per-thread\n- // `RotatingFileSink` handle owned by the logger\'s internal scope.\n- if (managedNativeEventLogger !== undefined) {\n- yield* managedNativeEventLogger.close();\n- }\n- }),\n- );\n-\n- const emit = (event: ProviderRuntimeEvent) =>\n- Queue.offer(runtimeEvents, event).pipe(Effect.asVoid);\n- const writeNativeEvent = (\n- threadId: ThreadId,\n- event: {\n- readonly observedAt: string;\n- readonly event: Record<string, unknown>;\n+export function makeOpenCodeAdapter(\n+ openCodeSettings: OpenCodeSettings,\n+ options?: OpenCodeAdapterLiveOptions,\n+) {\n+ return Effect.gen(function* () {\n+ const boundInstanceId = options?.instanceId ?? ProviderInstanceId.make("opencode");\n+ const serverConfig = yield* ServerConfig;\n+ const openCodeRuntime = yield* OpenCodeRuntime;\n+ const nativeEventLogger =\n+ options?.nativeEventLogger ??\n+ (options?.nativeEventLogPath !== undefined\n+ ? yield* makeEventNdjsonLogger(options.nativeEventLogPath, {\n+ stream: "native",\n+ })\n+ : undefined);\n+ // Only close loggers we created. If the caller passed one in via\n+ // `options.nativeEventLogger`, they own its lifecycle.\n+ const managedNativeEventLogger =\n+ options?.nativeEventLogger === undefined ? nativeEventLogger : undefined;\n+ const runtimeEvents = yield* Queue.unbounded<ProviderRuntimeEvent>();\n+ const sessions = new Map<ThreadId, OpenCodeSessionContext>();\n+\n+ // Layer-level finalizer: when the adapter layer shuts down, stop every\n+ // session. Each session\'s `Scope.close` tears down its spawned OpenCode\n+ // server (via the `ChildProcessSpawner` finalizer installed in\n+ // `startOpenCodeServerProcess`) and interrupts the forked event/exit\n+ // fibers. Consumers that can\'t reason about Effect scopes therefore\n+ // cannot leak OpenCode child processes by forgetting to call `stopAll`.\n+ yield* Effect.addFinalizer(() =>\n+ Effect.gen(function* () {\n+ const contexts = [...sessions.values()];\n+ sessions.clear();\n+ // `ignoreCause` swallows both typed failures (none here) and defects\n+ // from throwing scope finalizers so a sibling\'s death can\'t interrupt\n+ // the remaining cleanups.\n+ yield* Effect.forEach(\n+ contexts,\n+ (context) => Effect.ignoreCause(stopOpenCodeContext(context)),\n+ { concurrency: "unbounded", discard: true },\n+ );\n+ // Close the logger AFTER session teardown so any final lifecycle\n+ // events emitted during shutdown still get written. `close` flushes\n+ // the `Logger.batched` window and closes each per-thread\n+ // `RotatingFileSink` handle owned by the logger\'s internal scope.\n+ if (managedNativeEventLogger !== undefined) {\n+ yield* managedNativeEventLogger.close();\n+ }\n+ }).pipe(Effect.ensuring(Queue.shutdown(runtimeEvents))),\n+ );\n+\n+ const emit = (event: ProviderRuntimeEvent) =>\n+ Queue.offer(runtimeEvents, event).pipe(Effect.asVoid);\n+ const writeNativeEvent = (\n+ threadId: ThreadId,\n+ event: {\n+ readonly observedAt: string;\n+ readonly event: Record<string, unknown>;\n+ },\n+ ) => (nativeEventLogger ? nativeEventLogger.write(event, threadId) : Effect.void);\n+ const writeNativeEventBestEffort = (\n+ threadId: ThreadId,\n+ event: {\n+ readonly observedAt: string;\n+ readonly event: Record<string, unknown>;\n+ },\n+ ) => writeNativeEvent(threadId, event).pipe(Effect.catchCause(() => Effect.void));\n+\n+ const emitUnexpectedExit = Effect.fn("emitUnexpectedExit")(function* (\n+ context: OpenCodeSessionContext,\n+ message: string,\n+ ) {\n+ // Atomic one-shot: two fibers can race here (the event-pump on stream\n+ // failure and the server-exit watcher). `getAndSet` flips the flag in\n+ // a single step so the loser observes `true` and returns; a plain\n+ // `Ref.get` would let both racers slip past and emit duplicates.\n+ if (yield* Ref.getAndSet(context.stopped, true)) {\n+ return;\n+ }\n+ const turnId = context.activeTurnId;\n+ sessions.delete(context.session.threadId);\n+ // Emit lifecycle events BEFORE tearing down the scope. Both call sites\n+ // run this inside a fiber forked via `Effect.forkIn(context.sessionScope)`;\n+ // closing that scope triggers the fiber-interrupt finalizer, so any\n+ // subsequent yield point would unwind and silently drop these emits.\n+ yield* emit({\n+ ...(yield* buildEventBase({\n+ threadId: context.session.threadId,\n+ turnId,\n+ })),\n+ type: "runtime.error",\n+ payload: {\n+ message,\n+ class: "transport_error",\n },\n- ) => (nativeEventLogger ? nativeEventLogger.write(event, threadId) : Effect.void);\n- const writeNativeEventBestEffort = (\n- threadId: ThreadId,\n- event: {\n- readonly observedAt: string;\n- readonly event: Record<string, unknown>;\n+ }).pipe(Effect.ignore);\n+ yield* emit({\n+ ...(yield* buildEventBase({\n+ threadId: context.session.threadId,\n+ turnId,\n+ })),\n+ type: "session.exited",\n+ payload: {\n+ reason: message,\n+ recoverable: false,\n+ exitKind: "error",\n },\n- ) => writeNativeEvent(threadId, event).pipe(Effect.catchCause(() => Effect.void));\n-\n- const emitUnexpectedExit = Effect.fn("emitUnexpectedExit")(function* (\n- context: OpenCodeSessionContext,\n- message: string,\n- ) {\n- // Atomic one-shot: two fibers can race here (the event-pump on stream\n- // failure and the server-exit watcher). `getAndSet` flips the flag in\n- // a single step so the loser observes `true` and returns; a plain\n- // `Ref.get` would let both racers slip past and emit duplicates.\n- if (yield* Ref.getAndSet(context.stopped, true)) {\n- return;\n- }\n- const turnId = context.activeTurnId;\n- sessions.delete(context.session.threadId);\n- // Emit lifecycle events BEFORE tearing down the scope. Both call sites\n- // run this inside a fiber forked via `Effect.forkIn(context.sessionScope)`;\n- // closing that scope triggers the fiber-interrupt finalizer, so any\n- // subsequent yield point would unwind and silently drop these emits.\n+ }).pipe(Effect.ignore);\n+ // Inline the teardown that `stopOpenCodeContext` would do; we can\'t\n+ // delegate to it because our `getAndSet` above already flipped the\n+ // one-shot guard, so the call would no-op.\n+ yield* runOpenCodeSdk("session.abort", () =>\n+ context.client.session.abort({ sessionID: context.openCodeSessionId }),\n+ ).pipe(Effect.ignore({ log: true }));\n+ yield* Scope.close(context.sessionScope, Exit.void);\n+ });\n+\n+ /** Emit content.delta and item.completed events for an assistant text part. */\n+ const emitAssistantTextDelta = Effect.fn("emitAssistantTextDelta")(function* (\n+ context: OpenCodeSessionContext,\n+ part: Part,\n+ turnId: TurnId | undefined,\n+ raw: unknown,\n+ ) {\n+ const text = textFromPart(part);\n+ if (text === undefined) {\n+ return;\n+ }\n+ const previousText = context.emittedTextByPartId.get(part.id);\n+ const { latestText, deltaToEmit } = mergeOpenCodeAssistantText(previousText, text);\n+ context.emittedTextByPartId.set(part.id, latestText);\n+ if (latestText !== text) {\n+ context.partById.set(\n+ part.id,\n+ (part.type === "text" || part.type === "reasoning"\n+ ? { ...part, text: latestText }\n+ : part) satisfies Part,\n+ );\n+ }\n+ if (deltaToEmit.length > 0) {\n yield* emit({\n- ...buildEventBase({ threadId: context.session.threadId, turnId }),\n- type: "runtime.error",\n+ ...(yield* buildEventBase({\n+ threadId: context.session.threadId,\n+ turnId,\n+ itemId: part.id,\n+ createdAt:\n+ part.type === "text" || part.type === "reasoning"\n+ ? isoFromEpochMs(part.time?.start)\n+ : undefined,\n+ raw,\n+ })),\n+ type: "content.delta",\n payload: {\n- message,\n- class: "transport_error",\n+ streamKind: resolveTextStreamKind(part),\n+ delta: deltaToEmit,\n },\n- }).pipe(Effect.ignore);\n+ });\n+ }\n+\n+ if (\n+ part.type === "text" &&\n+ part.time?.end !== undefined &&\n+ !context.completedAssistantPartIds.has(part.id)\n+ ) {\n+ context.completedAssistantPartIds.add(part.id);\n yield* emit({\n- ...buildEventBase({ threadId: context.session.threadId, turnId }),\n- type: "session.exited",\n+ ...(yield* buildEventBase({\n+ threadId: context.session.threadId,\n+ turnId,\n+ itemId: part.id,\n+ createdAt: isoFromEpochMs(part.time.end),\n+ raw,\n+ })),\n+ type: "item.completed",\n payload: {\n- reason: message,\n- recoverable: false,\n- exitKind: "error",\n+ itemType: "assistant_message",\n+ status: "completed",\n+ title: "Assistant message",\n+ ...(latestText.length > 0 ? { detail: latestText } : {}),\n },\n- }).pipe(Effect.ignore);\n- // Inline the teardown that `stopOpenCodeContext` would do; we can\'t\n- // delegate to it because our `getAndSet` above already flipped the\n- // one-shot guard, so the call would no-op.\n- yield* runOpenCodeSdk("session.abort", () =>\n- context.client.session.abort({ sessionID: context.openCodeSessionId }),\n- ).pipe(Effect.ignore({ log: true }));\n- yield* Scope.close(context.sessionScope, Exit.void);\n+ });\n+ }\n+ });\n+\n+ const handleSubscribedEvent = Effect.fn("handleSubscribedEvent")(function* (\n+ context: OpenCodeSessionContext,\n+ event: OpenCodeSubscribedEvent,\n+ ) {\n+ const payloadSessionId =\n+ "properties" in event ? (event.properties as { sessionID?: unknown }).sessionID : undefined;\n+ if (payloadSessionId !== context.openCodeSessionId) {\n+ return;\n+ }\n+\n+ const turnId = context.activeTurnId;\n+ yield* writeNativeEventBestEffort(context.session.threadId, {\n+ observedAt: nowIso(),\n+ event: {\n+ provider: PROVIDER,\n+ threadId: context.session.threadId,\n+ providerThreadId: context.openCodeSessionId,\n+ type: event.type,\n+ ...(turnId ? { turnId } : {}),\n+ payload: event,\n+ },\n });\n \n- /** Emit content.delta and item.completed events for an assistant text part. */\n- const emitAssistantTextDelta = Effect.fn("emitAssistantTextDelta")(function* (\n- context: OpenCodeSessionContext,\n- part: Part,\n- turnId: TurnId | undefined,\n- raw: unknown,\n- ) {\n- const text = textFromPart(part);\n- if (text === undefined) {\n- return;\n+ switch (event.type) {\n+ case "message.updated": {\n+ context.messageRoleById.set(event.properties.info.id, event.properties.info.role);\n+ if (event.properties.info.role === "assistant") {\n+ for (const part of context.partById.values()) {\n+ if (part.messageID !== event.properties.info.id) {\n+ continue;\n+ }\n+ yield* emitAssistantTextDelta(context, part, turnId, event);\n+ }\n+ }\n+ break;\n }\n- const previousText = context.emittedTextByPartId.get(part.id);\n- const { latestText, deltaToEmit } = mergeOpenCodeAssistantText(previousText, text);\n- context.emittedTextByPartId.set(part.id, latestText);\n- if (latestText !== text) {\n- context.partById.set(\n- part.id,\n- (part.type === "text" || part.type === "reasoning"\n- ? { ...part, text: latestText }\n- : part) satisfies Part,\n- );\n+\n+ case "message.removed": {\n+ context.messageRoleById.delete(event.properties.messageID);\n+ break;\n }\n- if (deltaToEmit.length > 0) {\n+\n+ case "message.part.delta": {\n+ const existingPart = context.partById.get(event.properties.partID);\n+ if (!existingPart) {\n+ break;\n+ }\n+ const role = messageRoleForPart(context, existingPart);\n+ if (role !== "assistant") {\n+ break;\n+ }\n+ const streamKind = resolveTextStreamKind(existingPart);\n+ const delta = event.properties.delta;\n+ if (delta.length === 0) {\n+ break;\n+ }\n+ const previousText =\n+ context.emittedTextByPartId.get(event.properties.partID) ??\n+ textFromPart(existingPart) ??\n+ "";\n+ const { nextText, deltaToEmit } = appendOpenCodeAssistantTextDelta(previousText, delta);\n+ if (deltaToEmit.length === 0) {\n+ break;\n+ }\n+ context.emittedTextByPartId.set(event.properties.partID, nextText);\n+ if (existingPart.type === "text" || existingPart.type === "reasoning") {\n+ context.partById.set(event.properties.partID, {\n+ ...existingPart,\n+ text: nextText,\n+ });\n+ }\n yield* emit({\n- ...buildEventBase({\n+ ...(yield* buildEventBase({\n threadId: context.session.threadId,\n turnId,\n- itemId: part.id,\n- createdAt:\n- part.type === "text" || part.type === "reasoning"\n- ? isoFromEpochMs(part.time?.start)\n- : undefined,\n- raw,\n- }),\n+ itemId: event.properties.partID,\n+ raw: event,\n+ })),\n type: "content.delta",\n payload: {\n- streamKind: resolveTextStreamKind(part),\n+ streamKind,\n delta: deltaToEmit,\n },\n });\n+ break;\n }\n \n- if (\n- part.type === "text" &&\n- part.time?.end !== undefined &&\n- !context.completedAssistantPartIds.has(part.id)\n- ) {\n- context.completedAssistantPartIds.add(part.id);\n+ case "message.part.updated": {\n+ const part = event.properties.part;\n+ context.partById.set(part.id, part);\n+ const messageRole = messageRoleForPart(context, part);\n+\n+ if (messageRole === "assistant") {\n+ yield* emitAssistantTextDelta(context, part, turnId, event);\n+ }\n+\n+ if (part.type === "tool") {\n+ const itemType = toToolLifecycleItemType(part.tool);\n+ const title =\n+ part.state.status === "running" ? (part.state.title ?? part.tool) : part.tool;\n+ const detail = detailFromToolPart(part);\n+ const payload = {\n+ itemType,\n+ ...(part.state.status === "error"\n+ ? { status: "failed" as const }\n+ : part.state.status === "completed"\n+ ? { status: "completed" as const }\n+ : { status: "inProgress" as const }),\n+ ...(title ? { title } : {}),\n+ ...(detail ? { detail } : {}),\n+ data: {\n+ tool: part.tool,\n+ state: part.state,\n+ },\n+ };\n+ const runtimeEvent: ProviderRuntimeEvent = {\n+ ...(yield* buildEventBase({\n+ threadId: context.session.threadId,\n+ turnId,\n+ itemId: part.callID,\n+ createdAt: toolStateCreatedAt(part),\n+ raw: event,\n+ })),\n+ type:\n+ part.state.status === "pending"\n+ ? "item.started"\n+ : part.state.status === "completed" || part.state.status === "error"\n+ ? "item.completed"\n+ : "item.updated",\n+ payload,\n+ };\n+ appendTurnItem(context, turnId, part);\n+ yield* emit(runtimeEvent);\n+ }\n+ break;\n+ }\n+\n+ case "permission.asked": {\n+ context.pendingPermissions.set(event.properties.id, event.properties);\n yield* emit({\n- ...buildEventBase({\n+ ...(yield* buildEventBase({\n threadId: context.session.threadId,\n turnId,\n- itemId: part.id,\n- createdAt: isoFromEpochMs(part.time.end),\n- raw,\n- }),\n- type: "item.completed",\n+ requestId: event.properties.id,\n+ raw: event,\n+ })),\n+ type: "request.opened",\n payload: {\n- itemType: "assistant_message",\n- status: "completed",\n- title: "Assistant message",\n- ...(latestText.length > 0 ? { detail: latestText } : {}),\n+ requestType: mapPermissionToRequestType(event.properties.permission),\n+ detail:\n+ event.properties.patterns.length > 0\n+ ? event.properties.patterns.join("\\n")\n+ : event.properties.permission,\n+ args: event.properties.metadata,\n },\n });\n+ break;\n }\n- });\n \n- const handleSubscribedEvent = Effect.fn("handleSubscribedEvent")(function* (\n- context: OpenCodeSessionContext,\n- event: OpenCodeSubscribedEvent,\n- ) {\n- const payloadSessionId =\n- "properties" in event\n- ? (event.properties as { sessionID?: unknown }).sessionID\n- : undefined;\n- if (payloadSessionId !== context.openCodeSessionId) {\n- return;\n+ case "permission.replied": {\n+ context.pendingPermissions.delete(event.properties.requestID);\n+ yield* emit({\n+ ...(yield* buildEventBase({\n+ threadId: context.session.threadId,\n+ turnId,\n+ requestId: event.properties.requestID,\n+ raw: event,\n+ })),\n+ type: "request.resolved",\n+ payload: {\n+ requestType: "unknown",\n+ decision: mapPermissionDecision(event.properties.reply),\n+ },\n+ });\n+ break;\n }\n \n- const turnId = context.activeTurnId;\n- yield* writeNativeEventBestEffort(context.session.threadId, {\n- observedAt: nowIso(),\n- event: {\n- provider: PROVIDER,\n- threadId: context.session.threadId,\n- providerThreadId: context.openCodeSessionId,\n- type: event.type,\n- ...(turnId ? { turnId } : {}),\n- payload: event,\n- },\n- });\n+ case "question.asked": {\n+ context.pendingQuestions.set(event.properties.id, event.properties);\n+ yield* emit({\n+ ...(yield* buildEventBase({\n+ threadId: context.session.threadId,\n+ turnId,\n+ requestId: event.properties.id,\n+ raw: event,\n+ })),\n+ type: "user-input.requested",\n+ payload: {\n+ questions: normalizeQuestionRequest(event.properties),\n+ },\n+ });\n+ break;\n+ }\n \n- switch (event.type) {\n- case "message.updated": {\n- context.messageRoleById.set(event.properties.info.id, event.properties.info.role);\n- if (event.properties.info.role === "assistant") {\n- for (const part of context.partById.values()) {\n- if (part.messageID !== event.properties.info.id) {\n- continue;\n- }\n- yield* emitAssistantTextDelta(context, part, turnId, event);\n- }\n- }\n- break;\n- }\n+ case "question.replied": {\n+ const request = context.pendingQuestions.get(event.properties.requestID);\n+ context.pendingQuestions.delete(event.properties.requestID);\n+ const answers = Object.fromEntries(\n+ (request?.questions ?? []).map((question, index) => [\n+ openCodeQuestionId(index, question),\n+ event.properties.answers[index]?.join(", ") ?? "",\n+ ]),\n+ );\n+ yield* emit({\n+ ...(yield* buildEventBase({\n+ threadId: context.session.threadId,\n+ turnId,\n+ requestId: event.properties.requestID,\n+ raw: event,\n+ })),\n+ type: "user-input.resolved",\n+ payload: { answers },\n+ });\n+ break;\n+ }\n \n- case "message.removed": {\n- context.messageRoleById.delete(event.properties.messageID);\n- break;\n- }\n+ case "question.rejected": {\n+ context.pendingQuestions.delete(event.properties.requestID);\n+ yield* emit({\n+ ...(yield* buildEventBase({\n+ threadId: context.session.threadId,\n+ turnId,\n+ requestId: event.properties.requestID,\n+ raw: event,\n+ })),\n+ type: "user-input.resolved",\n+ payload: { answers: {} },\n+ });\n+ break;\n+ }\n \n- case "message.part.delta": {\n- const existingPart = context.partById.get(event.properties.partID);\n- if (!existingPart) {\n- break;\n- }\n- const role = messageRoleForPart(context, existingPart);\n- if (role !== "assistant") {\n- break;\n- }\n- const streamKind = resolveTextStreamKind(existingPart);\n- const delta = event.properties.delta;\n- if (delta.length === 0) {\n- break;\n- }\n- const previousText =\n- context.emittedTextByPartId.get(event.properties.partID) ??\n- textFromPart(existingPart) ??\n- "";\n- const { nextText, deltaToEmit } = appendOpenCodeAssistantTextDelta(previousText, delta);\n- if (deltaToEmit.length === 0) {\n- break;\n- }\n- context.emittedTextByPartId.set(event.properties.partID, nextText);\n- if (existingPart.type === "text" || existingPart.type === "reasoning") {\n- context.partById.set(event.properties.partID, {\n- ...existingPart,\n- text: nextText,\n- });\n- }\n- yield* emit({\n- ...buildEventBase({\n- threadId: context.session.threadId,\n- turnId,\n- itemId: event.properties.partID,\n- raw: event,\n- }),\n- type: "content.delta",\n- payload: {\n- streamKind,\n- delta: deltaToEmit,\n- },\n+ case "session.status": {\n+ if (event.properties.status.type === "busy") {\n+ updateProviderSession(context, {\n+ status: "running",\n+ activeTurnId: turnId,\n });\n- break;\n- }\n-\n- case "message.part.updated": {\n- const part = event.properties.part;\n- context.partById.set(part.id, part);\n- const messageRole = messageRoleForPart(context, part);\n-\n- if (messageRole === "assistant") {\n- yield* emitAssistantTextDelta(context, part, turnId, event);\n- }\n-\n- if (part.type === "tool") {\n- const itemType = toToolLifecycleItemType(part.tool);\n- const title =\n- part.state.status === "running" ? (part.state.title ?? part.tool) : part.tool;\n- const detail = detailFromToolPart(part);\n- const payload = {\n- itemType,\n- ...(part.state.status === "error"\n- ? { status: "failed" as const }\n- : part.state.status === "completed"\n- ? { status: "completed" as const }\n- : { status: "inProgress" as const }),\n- ...(title ? { title } : {}),\n- ...(detail ? { detail } : {}),\n- data: {\n- tool: part.tool,\n- state: part.state,\n- },\n- };\n- const runtimeEvent: ProviderRuntimeEvent = {\n- ...buildEventBase({\n- threadId: context.session.threadId,\n- turnId,\n- itemId: part.callID,\n- createdAt: toolStateCreatedAt(part),\n- raw: event,\n- }),\n- type:\n- part.state.status === "pending"\n- ? "item.started"\n- : part.state.status === "completed" || part.state.status === "error"\n- ? "item.completed"\n- : "item.updated",\n- payload,\n- };\n- appendTurnItem(context, turnId, part);\n- yield* emit(runtimeEvent);\n- }\n- break;\n }\n \n- case "permission.asked": {\n- context.pendingPermissions.set(event.properties.id, event.properties);\n+ if (event.properties.status.type === "retry") {\n yield* emit({\n- ...buildEventBase({\n+ ...(yield* buildEventBase({\n threadId: context.session.threadId,\n turnId,\n- requestId: event.properties.id,\n raw: event,\n- }),\n- type: "request.opened",\n+ })),\n+ type: "runtime.warning",\n payload: {\n- requestType: mapPermissionToRequestType(event.properties.permission),\n- detail:\n- event.properties.patterns.length > 0\n- ? event.properties.patterns.join("\\n")\n- : event.properties.permission,\n- args: event.properties.metadata,\n+ message: event.properties.status.message,\n+ detail: event.properties.status,\n },\n });\n break;\n }\n \n- case "permission.replied": {\n- context.pendingPermissions.delete(event.properties.requestID);\n+ if (event.properties.status.type === "idle" && turnId) {\n+ context.activeTurnId = undefined;\n+ updateProviderSession(context, { status: "ready" }, { clearActiveTurnId: true });\n yield* emit({\n- ...buildEventBase({\n+ ...(yield* buildEventBase({\n threadId: context.session.threadId,\n turnId,\n- requestId: event.properties.requestID,\n raw: event,\n- }),\n- type: "request.resolved",\n+ })),\n+ type: "turn.completed",\n payload: {\n- requestType: "unknown",\n- decision: mapPermissionDecision(event.properties.reply),\n+ state: "completed",\n },\n });\n- break;\n }\n+ break;\n+ }\n \n- case "question.asked": {\n- context.pendingQuestions.set(event.properties.id, event.properties);\n+ case "session.error": {\n+ const message = sessionErrorMessage(event.properties.error);\n+ const activeTurnId = context.activeTurnId;\n+ context.activeTurnId = undefined;\n+ updateProviderSession(\n+ context,\n+ {\n+ status: "error",\n+ lastError: message,\n+ },\n+ { clearActiveTurnId: true },\n+ );\n+ if (activeTurnId) {\n yield* emit({\n- ...buildEventBase({\n+ ...(yield* buildEventBase({\n threadId: context.session.threadId,\n- turnId,\n- requestId: event.properties.id,\n+ turnId: activeTurnId,\n raw: event,\n- }),\n- type: "user-input.requested",\n+ })),\n+ type: "turn.completed",\n payload: {\n- questions: normalizeQuestionRequest(event.properties),\n+ state: "failed",\n+ errorMessage: message,\n },\n });\n- break;\n }\n+ yield* emit({\n+ ...(yield* buildEventBase({\n+ threadId: context.session.threadId,\n+ raw: event,\n+ })),\n+ type: "runtime.error",\n+ payload: {\n+ message,\n+ class: "provider_error",\n+ detail: event.properties.error,\n+ },\n+ });\n+ break;\n+ }\n \n- case "question.replied": {\n- const request = context.pendingQuestions.get(event.properties.requestID);\n- context.pendingQuestions.delete(event.properties.requestID);\n- const answers = Object.fromEntries(\n- (request?.questions ?? []).map((question, index) => [\n- openCodeQuestionId(index, question),\n- event.properties.answers[index]?.join(", ") ?? "",\n- ]),\n- );\n- yield* emit({\n- ...buildEventBase({\n- threadId: context.session.threadId,\n- turnId,\n- requestId: event.properties.requestID,\n- raw: event,\n- }),\n- type: "user-input.resolved",\n- payload: { answers },\n- });\n- break;\n- }\n+ default:\n+ break;\n+ }\n+ });\n+\n+ const startEventPump = Effect.fn("startEventPump")(function* (context: OpenCodeSessionContext) {\n+ // One AbortController per session scope. The finalizer fires when\n+ // the scope closes (explicit stop, unexpected exit, or layer\n+ // shutdown) and cancels the in-flight `event.subscribe` fetch so\n+ // the async iterable unwinds cleanly.\n+ const eventsAbortController = new AbortController();\n+ yield* Scope.addFinalizer(\n+ context.sessionScope,\n+ Effect.sync(() => eventsAbortController.abort()),\n+ );\n \n- case "question.rejected": {\n- context.pendingQuestions.delete(event.properties.requestID);\n- yield* emit({\n- ...buildEventBase({\n- threadId: context.session.threadId,\n- turnId,\n- requestId: event.properties.requestID,\n- raw: event,\n+ // Fibers forked into `context.sessionScope` are interrupted\n+ // automatically when the scope closes — no bookkeeping required.\n+ yield* Effect.flatMap(\n+ runOpenCodeSdk("event.subscribe", () =>\n+ context.client.event.subscribe(undefined, {\n+ signal: eventsAbortController.signal,\n+ }),\n+ ),\n+ (subscription) =>\n+ Stream.fromAsyncIterable(\n+ subscription.stream,\n+ (cause) =>\n+ new OpenCodeRuntimeError({\n+ operation: "event.subscribe",\n+ detail: openCodeRuntimeErrorDetail(cause),\n+ cause,\n }),\n- type: "user-input.resolved",\n- payload: { answers: {} },\n- });\n- break;\n- }\n-\n- case "session.status": {\n- if (event.properties.status.type === "busy") {\n- updateProviderSession(context, { status: "running", activeTurnId: turnId });\n+ ).pipe(Stream.runForEach((event) => handleSubscribedEvent(context, event))),\n+ ).pipe(\n+ Effect.exit,\n+ Effect.flatMap((exit) =>\n+ Effect.gen(function* () {\n+ // Expected paths: caller aborted the fetch or the session\n+ // has already been marked stopped. Treat as a clean exit.\n+ if (eventsAbortController.signal.aborted || (yield* Ref.get(context.stopped))) {\n+ return;\n }\n-\n- if (event.properties.status.type === "retry") {\n- yield* emit({\n- ...buildEventBase({ threadId: context.session.threadId, turnId, raw: event }),\n- type: "runtime.warning",\n- payload: {\n- message: event.properties.status.message,\n- detail: event.properties.status,\n- },\n- });\n- break;\n- }\n-\n- if (event.properties.status.type === "idle" && turnId) {\n- context.activeTurnId = undefined;\n- updateProviderSession(context, { status: "ready" }, { clearActiveTurnId: true });\n- yield* emit({\n- ...buildEventBase({ threadId: context.session.threadId, turnId, raw: event }),\n- type: "turn.completed",\n- payload: {\n- state: "completed",\n- },\n- });\n- }\n- break;\n- }\n-\n- case "session.error": {\n- const message = sessionErrorMessage(event.properties.error);\n- const activeTurnId = context.activeTurnId;\n- context.activeTurnId = undefined;\n- updateProviderSession(\n- context,\n- {\n- status: "error",\n- lastError: message,\n- },\n- { clearActiveTurnId: true },\n- );\n- if (activeTurnId) {\n- yield* emit({\n- ...buildEventBase({\n- threadId: context.session.threadId,\n- turnId: activeTurnId,\n- raw: event,\n- }),\n- type: "turn.completed",\n- payload: {\n- state: "failed",\n- errorMessage: message,\n- },\n- });\n+ if (Exit.isFailure(exit)) {\n+ yield* emitUnexpectedExit(\n+ context,\n+ openCodeRuntimeErrorDetail(Cause.squash(exit.cause)),\n+ );\n }\n- yield* emit({\n- ...buildEventBase({ threadId: context.session.threadId, raw: event }),\n- type: "runtime.error",\n- payload: {\n- message,\n- class: "provider_error",\n- detail: event.properties.error,\n- },\n- });\n- break;\n- }\n-\n- default:\n- break;\n- }\n- });\n-\n- const startEventPump = Effect.fn("startEventPump")(function* (\n- context: OpenCodeSessionContext,\n- ) {\n- // One AbortController per session scope. The finalizer fires when\n- // the scope closes (explicit stop, unexpected exit, or layer\n- // shutdown) and cancels the in-flight `event.subscribe` fetch so\n- // the async iterable unwinds cleanly.\n- const eventsAbortController = new AbortController();\n- yield* Scope.addFinalizer(\n- context.sessionScope,\n- Effect.sync(() => eventsAbortController.abort()),\n- );\n+ }),\n+ ),\n+ Effect.forkIn(context.sessionScope),\n+ );\n \n- // Fibers forked into `context.sessionScope` are interrupted\n- // automatically when the scope closes — no bookkeeping required.\n- yield* Effect.flatMap(\n- runOpenCodeSdk("event.subscribe", () =>\n- context.client.event.subscribe(undefined, {\n- signal: eventsAbortController.signal,\n- }),\n- ),\n- (subscription) =>\n- Stream.fromAsyncIterable(\n- subscription.stream,\n- (cause) =>\n- new OpenCodeRuntimeError({\n- operation: "event.subscribe",\n- detail: openCodeRuntimeErrorDetail(cause),\n- cause,\n- }),\n- ).pipe(Stream.runForEach((event) => handleSubscribedEvent(context, event))),\n- ).pipe(\n- Effect.exit,\n- Effect.flatMap((exit) =>\n+ if (!context.server.external && context.server.exitCode !== null) {\n+ yield* context.server.exitCode.pipe(\n+ Effect.flatMap((code) =>\n Effect.gen(function* () {\n- // Expected paths: caller aborted the fetch or the session\n- // has already been marked stopped. Treat as a clean exit.\n- if (eventsAbortController.signal.aborted || (yield* Ref.get(context.stopped))) {\n+ if (yield* Ref.get(context.stopped)) {\n return;\n }\n- if (Exit.isFailure(exit)) {\n- yield* emitUnexpectedExit(\n- context,\n- openCodeRuntimeErrorDetail(Cause.squash(exit.cause)),\n- );\n- }\n+ yield* emitUnexpectedExit(context, `OpenCode server exited unexpectedly (${code}).`);\n }),\n ),\n Effect.forkIn(context.sessionScope),\n );\n-\n- if (!context.server.external && context.server.exitCode !== null) {\n- yield* context.server.exitCode.pipe(\n- Effect.flatMap((code) =>\n- Effect.gen(function* () {\n- if (yield* Ref.get(context.stopped)) {\n- return;\n- }\n- yield* emitUnexpectedExit(\n- context,\n- `OpenCode server exited unexpectedly (${code}).`,\n- );\n- }),\n- ),\n- Effect.forkIn(context.sessionScope),\n- );\n+ }\n+ });\n+\n+ const startSession: OpenCodeAdapterShape["startSession"] = Effect.fn("startSession")(\n+ function* (input) {\n+ const binaryPath = openCodeSettings.binaryPath;\n+ const serverUrl = openCodeSettings.serverUrl;\n+ const serverPassword = openCodeSettings.serverPassword;\n+ const directory = input.cwd ?? serverConfig.cwd;\n+ const existing = sessions.get(input.threadId);\n+ if (existing) {\n+ yield* stopOpenCodeContext(existing);\n+ sessions.delete(input.threadId);\n }\n- });\n \n- const startSession: OpenCodeAdapterShape["startSession"] = Effect.fn("startSession")(\n- function* (input) {\n- const settings = yield* serverSettings.getSettings.pipe(\n- Effect.mapError(\n- (cause) =>\n- new ProviderAdapterProcessError({\n- provider: PROVIDER,\n- threadId: input.threadId,\n- detail: "Failed to read OpenCode settings.",\n- cause,\n+ const started = yield* Effect.gen(function* () {\n+ const sessionScope = yield* Scope.make();\n+ const startedExit = yield* Effect.exit(\n+ Effect.gen(function* () {\n+ // The runtime binds the server\'s lifetime to the Scope.Scope\n+ // we provide below — closing `sessionScope` kills the child\n+ // process automatically. No manual `server.close()` needed.\n+ const server = yield* openCodeRuntime.connectToOpenCodeServer({\n+ binaryPath,\n+ serverUrl,\n+ ...(options?.environment ? { environment: options.environment } : {}),\n+ });\n+ const client = openCodeRuntime.createOpenCodeSdkClient({\n+ baseUrl: server.url,\n+ directory,\n+ ...(server.external && serverPassword ? { serverPassword } : {}),\n+ });\n+ const openCodeSession = yield* runOpenCodeSdk("session.create", () =>\n+ client.session.create({\n+ title: `T3 Code ${input.threadId}`,\n+ permission: buildOpenCodePermissionRules(input.runtimeMode),\n }),\n- ),\n- );\n- const binaryPath = settings.providers.opencode.binaryPath;\n- const serverUrl = settings.providers.opencode.serverUrl;\n- const serverPassword = settings.providers.opencode.serverPassword;\n- const directory = input.cwd ?? serverConfig.cwd;\n- const existing = sessions.get(input.threadId);\n- if (existing) {\n- yield* stopOpenCodeContext(existing);\n- sessions.delete(input.threadId);\n- }\n-\n- const started = yield* Effect.gen(function* () {\n- const sessionScope = yield* Scope.make();\n- const startedExit = yield* Effect.exit(\n- Effect.gen(function* () {\n- // The runtime binds the server\'s lifetime to the Scope.Scope\n- // we provide below — closing `sessionScope` kills the child\n- // process automatically. No manual `server.close()` needed.\n- const server = yield* openCodeRuntime.connectToOpenCodeServer({\n- binaryPath,\n- serverUrl,\n- });\n- const client = openCodeRuntime.createOpenCodeSdkClient({\n- baseUrl: server.url,\n- directory,\n- ...(server.external && serverPassword ? { serverPassword } : {}),\n+ );\n+ if (!openCodeSession.data) {\n+ return yield* new OpenCodeRuntimeError({\n+ operation: "session.create",\n+ detail: "OpenCode session.create returned no session payload.",\n });\n- const openCodeSession = yield* runOpenCodeSdk("session.create", () =>\n- client.session.create({\n- title: `T3 Code ${input.threadId}`,\n- permission: buildOpenCodePermissionRules(input.runtimeMode),\n- }),\n- );\n- if (!openCodeSession.data) {\n- return yield* new OpenCodeRuntimeError({\n- operation: "session.create",\n- detail: "OpenCode session.create returned no session payload.",\n- });\n- }\n- return { sessionScope, server, client, openCodeSession: openCodeSession.data };\n- }).pipe(Effect.provideService(Scope.Scope, sessionScope)),\n- );\n- if (Exit.isFailure(startedExit)) {\n- yield* Scope.close(sessionScope, Exit.void).pipe(Effect.ignore);\n- return yield* toProcessError(input.threadId, Cause.squash(startedExit.cause));\n- }\n- return startedExit.value;\n- });\n-\n- // Guard against a concurrent startSession call that may have raced\n- // and already inserted a session while we were awaiting async work.\n- const raceWinner = sessions.get(input.threadId);\n- if (raceWinner) {\n- // Another call won the race – clean up the session we just created\n- // (including the remote SDK session) and return the existing one.\n- yield* runOpenCodeSdk("session.abort", () =>\n- started.client.session.abort({ sessionID: started.openCodeSession.id }),\n- ).pipe(Effect.ignore);\n- yield* Scope.close(started.sessionScope, Exit.void).pipe(Effect.ignore);\n- return raceWinner.session;\n+ }\n+ return {\n+ sessionScope,\n+ server,\n+ client,\n+ openCodeSession: openCodeSession.data,\n+ };\n+ }).pipe(Effect.provideService(Scope.Scope, sessionScope)),\n+ );\n+ if (Exit.isFailure(startedExit)) {\n+ yield* Scope.close(sessionScope, Exit.void).pipe(Effect.ignore);\n+ return yield* toProcessError(input.threadId, Cause.squash(startedExit.cause));\n }\n+ return startedExit.value;\n+ });\n \n- const createdAt = nowIso();\n- const session: ProviderSession = {\n- provider: PROVIDER,\n- status: "ready",\n- runtimeMode: input.runtimeMode,\n- cwd: directory,\n- ...(input.modelSelection ? { model: input.modelSelection.model } : {}),\n- threadId: input.threadId,\n- createdAt,\n- updatedAt: createdAt,\n- };\n-\n- const context: OpenCodeSessionContext = {\n- session,\n- client: started.client,\n- server: started.server,\n- directory,\n- openCodeSessionId: started.openCodeSession.id,\n- pendingPermissions: new Map(),\n- pendingQuestions: new Map(),\n- partById: new Map(),\n- emittedTextByPartId: new Map(),\n- messageRoleById: new Map(),\n- completedAssistantPartIds: new Set(),\n- turns: [],\n- activeTurnId: undefined,\n- activeAgent: undefined,\n- activeVariant: undefined,\n- stopped: yield* Ref.make(false),\n- sessionScope: started.sessionScope,\n- };\n- sessions.set(input.threadId, context);\n- yield* startEventPump(context);\n-\n- yield* emit({\n- ...buildEventBase({ threadId: input.threadId }),\n- type: "session.started",\n- payload: {\n- message: "OpenCode session started",\n- },\n- });\n- yield* emit({\n- ...buildEventBase({ threadId: input.threadId }),\n- type: "thread.started",\n- payload: {\n- providerThreadId: started.openCodeSession.id,\n- },\n- });\n-\n- return session;\n- },\n- );\n-\n- const sendTurn: OpenCodeAdapterShape["sendTurn"] = Effect.fn("sendTurn")(function* (input) {\n- const context = ensureSessionContext(sessions, input.threadId);\n- const turnId = TurnId.make(`opencode-turn-${randomUUID()}`);\n- const modelSelection =\n- input.modelSelection ??\n- (context.session.model\n- ? { provider: PROVIDER, model: context.session.model }\n- : undefined);\n- const parsedModel = parseOpenCodeModelSlug(modelSelection?.model);\n- if (!parsedModel) {\n- return yield* new ProviderAdapterValidationError({\n- provider: PROVIDER,\n- operation: "sendTurn",\n- issue: "OpenCode model selection must use the \'provider/model\' format.",\n- });\n+ // Guard against a concurrent startSession call that may have raced\n+ // and already inserted a session while we were awaiting async work.\n+ const raceWinner = sessions.get(input.threadId);\n+ if (raceWinner) {\n+ // Another call won the race – clean up the session we just created\n+ // (including the remote SDK session) and return the existing one.\n+ yield* runOpenCodeSdk("session.abort", () =>\n+ started.client.session.abort({\n+ sessionID: started.openCodeSession.id,\n+ }),\n+ ).pipe(Effect.ignore);\n+ yield* Scope.close(started.sessionScope, Exit.void).pipe(Effect.ignore);\n+ return raceWinner.session;\n }\n \n- const text = input.input?.trim();\n- const fileParts = toOpenCodeFileParts({\n- attachments: input.attachments,\n- resolveAttachmentPath: (attachment) =>\n- resolveAttachmentPath({ attachmentsDir: serverConfig.attachmentsDir, attachment }),\n- });\n- if ((!text || text.length === 0) && fileParts.length === 0) {\n- return yield* new ProviderAdapterValidationError({\n- provider: PROVIDER,\n- operation: "sendTurn",\n- issue: "OpenCode turns require text input or at least one attachment.",\n- });\n- }\n+ const createdAt = nowIso();\n+ const session: ProviderSession = {\n+ provider: PROVIDER,\n+ providerInstanceId: boundInstanceId,\n+ status: "ready",\n+ runtimeMode: input.runtimeMode,\n+ cwd: directory,\n+ ...(input.modelSelection ? { model: input.modelSelection.model } : {}),\n+ threadId: input.threadId,\n+ createdAt,\n+ updatedAt: createdAt,\n+ };\n \n- const agent =\n- input.modelSelection?.provider === PROVIDER\n- ? getModelSelectionStringOptionValue(input.modelSelection, "agent")\n- : undefined;\n- const variant =\n- input.modelSelection?.provider === PROVIDER\n- ? getModelSelectionStringOptionValue(input.modelSelection, "variant")\n- : undefined;\n-\n- context.activeTurnId = turnId;\n- context.activeAgent = agent ?? (input.interactionMode === "plan" ? "plan" : undefined);\n- context.activeVariant = variant;\n- updateProviderSession(\n- context,\n- {\n- status: "running",\n- activeTurnId: turnId,\n- model: modelSelection?.model ?? context.session.model,\n- },\n- { clearLastError: true },\n- );\n+ const context: OpenCodeSessionContext = {\n+ session,\n+ client: started.client,\n+ server: started.server,\n+ directory,\n+ openCodeSessionId: started.openCodeSession.id,\n+ pendingPermissions: new Map(),\n+ pendingQuestions: new Map(),\n+ partById: new Map(),\n+ emittedTextByPartId: new Map(),\n+ messageRoleById: new Map(),\n+ completedAssistantPartIds: new Set(),\n+ turns: [],\n+ activeTurnId: undefined,\n+ activeAgent: undefined,\n+ activeVariant: undefined,\n+ stopped: yield* Ref.make(false),\n+ sessionScope: started.sessionScope,\n+ };\n+ sessions.set(input.threadId, context);\n+ yield* startEventPump(context);\n \n yield* emit({\n- ...buildEventBase({ threadId: input.threadId, turnId }),\n- type: "turn.started",\n+ ...(yield* buildEventBase({ threadId: input.threadId })),\n+ type: "session.started",\n payload: {\n- model: modelSelection?.model ?? context.session.model,\n- ...(variant ? { effort: variant } : {}),\n+ message: "OpenCode session started",\n+ },\n+ });\n+ yield* emit({\n+ ...(yield* buildEventBase({ threadId: input.threadId })),\n+ type: "thread.started",\n+ payload: {\n+ providerThreadId: started.openCodeSession.id,\n },\n });\n \n- yield* runOpenCodeSdk("session.promptAsync", () =>\n- context.client.session.promptAsync({\n- sessionID: context.openCodeSessionId,\n- model: parsedModel,\n- ...(context.activeAgent ? { agent: context.activeAgent } : {}),\n- ...(context.activeVariant ? { variant: context.activeVariant } : {}),\n- parts: [...(text ? [{ type: "text" as const, text }] : []), ...fileParts],\n+ return session;\n+ },\n+ );\n+\n+ const sendTurn: OpenCodeAdapterShape["sendTurn"] = Effect.fn("sendTurn")(function* (input) {\n+ const context = ensureSessionContext(sessions, input.threadId);\n+ const turnId = TurnId.make(`opencode-turn-${yield* Random.nextUUIDv4}`);\n+ const modelSelection =\n+ input.modelSelection ??\n+ (context.session.model\n+ ? { instanceId: boundInstanceId, model: context.session.model }\n+ : undefined);\n+ if (modelSelection !== undefined && modelSelection.instanceId !== boundInstanceId) {\n+ return yield* new ProviderAdapterValidationError({\n+ provider: PROVIDER,\n+ operation: "sendTurn",\n+ issue: `OpenCode model selection is bound to instance \'${modelSelection?.instanceId}\', expected \'${boundInstanceId}\'.`,\n+ });\n+ }\n+ const parsedModel = parseOpenCodeModelSlug(modelSelection?.model);\n+ if (!parsedModel) {\n+ return yield* new ProviderAdapterValidationError({\n+ provider: PROVIDER,\n+ operation: "sendTurn",\n+ issue: "OpenCode model selection must use the \'provider/model\' format.",\n+ });\n+ }\n+\n+ const text = input.input?.trim();\n+ const fileParts = toOpenCodeFileParts({\n+ attachments: input.attachments,\n+ resolveAttachmentPath: (attachment) =>\n+ resolveAttachmentPath({\n+ attachmentsDir: serverConfig.attachmentsDir,\n+ attachment,\n }),\n- ).pipe(\n- Effect.mapError(toRequestError),\n- // On failure: clear active-turn state, flip the session back to ready\n- // with lastError set, emit turn.aborted, then let the typed error\n- // propagate. We don\'t need to rebuild the error here — `toRequestError`\n- // already produced the right shape.\n- Effect.tapError((requestError) =>\n- Effect.gen(function* () {\n- context.activeTurnId = undefined;\n- context.activeAgent = undefined;\n- context.activeVariant = undefined;\n- updateProviderSession(\n- context,\n- {\n- status: "ready",\n- model: modelSelection?.model ?? context.session.model,\n- lastError: requestError.detail,\n- },\n- { clearActiveTurnId: true },\n- );\n- yield* emit({\n- ...buildEventBase({ threadId: input.threadId, turnId }),\n- type: "turn.aborted",\n- payload: {\n- reason: requestError.detail,\n- },\n- });\n- }),\n- ),\n- );\n+ });\n+ if ((!text || text.length === 0) && fileParts.length === 0) {\n+ return yield* new ProviderAdapterValidationError({\n+ provider: PROVIDER,\n+ operation: "sendTurn",\n+ issue: "OpenCode turns require text input or at least one attachment.",\n+ });\n+ }\n+\n+ const agent = getModelSelectionStringOptionValue(modelSelection, "agent");\n+ const variant = getModelSelectionStringOptionValue(modelSelection, "variant");\n+\n+ context.activeTurnId = turnId;\n+ context.activeAgent = agent ?? (input.interactionMode === "plan" ? "plan" : undefined);\n+ context.activeVariant = variant;\n+ updateProviderSession(\n+ context,\n+ {\n+ status: "running",\n+ activeTurnId: turnId,\n+ model: modelSelection?.model ?? context.session.model,\n+ },\n+ { clearLastError: true },\n+ );\n \n- return {\n- threadId: input.threadId,\n- turnId,\n- };\n+ yield* emit({\n+ ...(yield* buildEventBase({ threadId: input.threadId, turnId })),\n+ type: "turn.started",\n+ payload: {\n+ model: modelSelection?.model ?? context.session.model,\n+ ...(variant ? { effort: variant } : {}),\n+ },\n });\n \n- const interruptTurn: OpenCodeAdapterShape["interruptTurn"] = Effect.fn("interruptTurn")(\n- function* (threadId, turnId) {\n- const context = ensureSessionContext(sessions, threadId);\n- yield* runOpenCodeSdk("session.abort", () =>\n- context.client.session.abort({ sessionID: context.openCodeSessionId }),\n- ).pipe(Effect.mapError(toRequestError));\n- if (turnId ?? context.activeTurnId) {\n+ yield* runOpenCodeSdk("session.promptAsync", () =>\n+ context.client.session.promptAsync({\n+ sessionID: context.openCodeSessionId,\n+ model: parsedModel,\n+ ...(context.activeAgent ? { agent: context.activeAgent } : {}),\n+ ...(context.activeVariant ? { variant: context.activeVariant } : {}),\n+ parts: [...(text ? [{ type: "text" as const, text }] : []), ...fileParts],\n+ }),\n+ ).pipe(\n+ Effect.mapError(toRequestError),\n+ // On failure: clear active-turn state, flip the session back to ready\n+ // with lastError set, emit turn.aborted, then let the typed error\n+ // propagate. We don\'t need to rebuild the error here — `toRequestError`\n+ // already produced the right shape.\n+ Effect.tapError((requestError) =>\n+ Effect.gen(function* () {\n+ context.activeTurnId = undefined;\n+ context.activeAgent = undefined;\n+ context.activeVariant = undefined;\n+ updateProviderSession(\n+ context,\n+ {\n+ status: "ready",\n+ model: modelSelection?.model ?? context.session.model,\n+ lastError: requestError.detail,\n+ },\n+ { clearActiveTurnId: true },\n+ );\n yield* emit({\n- ...buildEventBase({ threadId, turnId: turnId ?? context.activeTurnId }),\n+ ...(yield* buildEventBase({\n+ threadId: input.threadId,\n+ turnId,\n+ })),\n type: "turn.aborted",\n payload: {\n- reason: "Interrupted by user.",\n+ reason: requestError.detail,\n },\n });\n- }\n- },\n+ }),\n+ ),\n );\n \n- const respondToRequest: OpenCodeAdapterShape["respondToRequest"] = Effect.fn(\n- "respondToRequest",\n- )(function* (threadId, requestId, decision) {\n- const context = ensureSessionContext(sessions, threadId);\n- if (!context.pendingPermissions.has(requestId)) {\n- return yield* new ProviderAdapterRequestError({\n- provider: PROVIDER,\n- method: "permission.reply",\n- detail: `Unknown pending permission request: ${requestId}`,\n- });\n- }\n-\n- yield* runOpenCodeSdk("permission.reply", () =>\n- context.client.permission.reply({\n- requestID: requestId,\n- reply: toOpenCodePermissionReply(decision),\n- }),\n- ).pipe(Effect.mapError(toRequestError));\n- });\n+ return {\n+ threadId: input.threadId,\n+ turnId,\n+ };\n+ });\n \n- const respondToUserInput: OpenCodeAdapterShape["respondToUserInput"] = Effect.fn(\n- "respondToUserInput",\n- )(function* (threadId, requestId, answers) {\n+ const interruptTurn: OpenCodeAdapterShape["interruptTurn"] = Effect.fn("interruptTurn")(\n+ function* (threadId, turnId) {\n const context = ensureSessionContext(sessions, threadId);\n- const request = context.pendingQuestions.get(requestId);\n- if (!request) {\n- return yield* new ProviderAdapterRequestError({\n- provider: PROVIDER,\n- method: "question.reply",\n- detail: `Unknown pending user-input request: ${requestId}`,\n- });\n- }\n-\n- yield* runOpenCodeSdk("question.reply", () =>\n- context.client.question.reply({\n- requestID: requestId,\n- answers: toOpenCodeQuestionAnswers(request, answers),\n- }),\n+ yield* runOpenCodeSdk("session.abort", () =>\n+ context.client.session.abort({ sessionID: context.openCodeSessionId }),\n ).pipe(Effect.mapError(toRequestError));\n- });\n-\n- const stopSession: OpenCodeAdapterShape["stopSession"] = Effect.fn("stopSession")(\n- function* (threadId) {\n- const context = ensureSessionContext(sessions, threadId);\n- yield* stopOpenCodeContext(context);\n- sessions.delete(threadId);\n+ if (turnId ?? context.activeTurnId) {\n yield* emit({\n- ...buildEventBase({ threadId }),\n- type: "session.exited",\n+ ...(yield* buildEventBase({\n+ threadId,\n+ turnId: turnId ?? context.activeTurnId,\n+ })),\n+ type: "turn.aborted",\n payload: {\n- reason: "Session stopped.",\n- recoverable: false,\n- exitKind: "graceful",\n+ reason: "Interrupted by user.",\n },\n });\n- },\n- );\n+ }\n+ },\n+ );\n+\n+ const respondToRequest: OpenCodeAdapterShape["respondToRequest"] = Effect.fn(\n+ "respondToRequest",\n+ )(function* (threadId, requestId, decision) {\n+ const context = ensureSessionContext(sessions, threadId);\n+ if (!context.pendingPermissions.has(requestId)) {\n+ return yield* new ProviderAdapterRequestError({\n+ provider: PROVIDER,\n+ method: "permission.reply",\n+ detail: `Unknown pending permission request: ${requestId}`,\n+ });\n+ }\n+\n+ yield* runOpenCodeSdk("permission.reply", () =>\n+ context.client.permission.reply({\n+ requestID: requestId,\n+ reply: toOpenCodePermissionReply(decision),\n+ }),\n+ ).pipe(Effect.mapError(toRequestError));\n+ });\n+\n+ const respondToUserInput: OpenCodeAdapterShape["respondToUserInput"] = Effect.fn(\n+ "respondToUserInput",\n+ )(function* (threadId, requestId, answers) {\n+ const context = ensureSessionContext(sessions, threadId);\n+ const request = context.pendingQuestions.get(requestId);\n+ if (!request) {\n+ return yield* new ProviderAdapterRequestError({\n+ provider: PROVIDER,\n+ method: "question.reply",\n+ detail: `Unknown pending user-input request: ${requestId}`,\n+ });\n+ }\n \n- const listSessions: OpenCodeAdapterShape["listSessions"] = () =>\n- Effect.sync(() => [...sessions.values()].map((context) => context.session));\n+ yield* runOpenCodeSdk("question.reply", () =>\n+ context.client.question.reply({\n+ requestID: requestId,\n+ answers: toOpenCodeQuestionAnswers(request, answers),\n+ }),\n+ ).pipe(Effect.mapError(toRequestError));\n+ });\n+\n+ const stopSession: OpenCodeAdapterShape["stopSession"] = Effect.fn("stopSession")(\n+ function* (threadId) {\n+ const context = sessions.get(threadId);\n+ if (!context) {\n+ throw new ProviderAdapterSessionNotFoundError({\n+ provider: PROVIDER,\n+ threadId,\n+ });\n+ }\n+ const stopped = yield* stopOpenCodeContext(context);\n+ sessions.delete(threadId);\n+ if (!stopped) {\n+ return;\n+ }\n+ yield* emit({\n+ ...(yield* buildEventBase({ threadId })),\n+ type: "session.exited",\n+ payload: {\n+ reason: "Session stopped.",\n+ recoverable: false,\n+ exitKind: "graceful",\n+ },\n+ });\n+ },\n+ );\n \n- const hasSession: OpenCodeAdapterShape["hasSession"] = (threadId) =>\n- Effect.sync(() => sessions.has(threadId));\n+ const listSessions: OpenCodeAdapterShape["listSessions"] = () =>\n+ Effect.sync(() => [...sessions.values()].map((context) => context.session));\n \n- const readThread: OpenCodeAdapterShape["readThread"] = Effect.fn("readThread")(\n- function* (threadId) {\n- const context = ensureSessionContext(sessions, threadId);\n- const messages = yield* runOpenCodeSdk("session.messages", () =>\n- context.client.session.messages({ sessionID: context.openCodeSessionId }),\n- ).pipe(Effect.mapError(toRequestError));\n+ const hasSession: OpenCodeAdapterShape["hasSession"] = (threadId) =>\n+ Effect.sync(() => sessions.has(threadId));\n \n- const turns = (messages.data ?? [])\n- .filter((entry) => entry.info.role === "assistant")\n- .map((entry) => ({\n- id: TurnId.make(entry.info.id),\n- items: [entry.info, ...entry.parts],\n- }));\n+ const readThread: OpenCodeAdapterShape["readThread"] = Effect.fn("readThread")(\n+ function* (threadId) {\n+ const context = ensureSessionContext(sessions, threadId);\n+ const messages = yield* runOpenCodeSdk("session.messages", () =>\n+ context.client.session.messages({\n+ sessionID: context.openCodeSessionId,\n+ }),\n+ ).pipe(Effect.mapError(toRequestError));\n \n- return {\n- threadId,\n- turns,\n- };\n- },\n- );\n+ const turns = (messages.data ?? [])\n+ .filter((entry) => entry.info.role === "assistant")\n+ .map((entry) => ({\n+ id: TurnId.make(entry.info.id),\n+ items: [entry.info, ...entry.parts],\n+ }));\n \n- const rollbackThread: OpenCodeAdapterShape["rollbackThread"] = Effect.fn("rollbackThread")(\n- function* (threadId, numTurns) {\n- const context = ensureSessionContext(sessions, threadId);\n- const messages = yield* runOpenCodeSdk("session.messages", () =>\n- context.client.session.messages({ sessionID: context.openCodeSessionId }),\n- ).pipe(Effect.mapError(toRequestError));\n+ return {\n+ threadId,\n+ turns,\n+ };\n+ },\n+ );\n \n- const assistantMessages = (messages.data ?? []).filter(\n- (entry) => entry.info.role === "assistant",\n- );\n- const targetIndex = assistantMessages.length - numTurns - 1;\n- const target = targetIndex >= 0 ? assistantMessages[targetIndex] : null;\n- yield* runOpenCodeSdk("session.revert", () =>\n- context.client.session.revert({\n- sessionID: context.openCodeSessionId,\n- ...(target ? { messageID: target.info.id } : {}),\n- }),\n- ).pipe(Effect.mapError(toRequestError));\n+ const rollbackThread: OpenCodeAdapterShape["rollbackThread"] = Effect.fn("rollbackThread")(\n+ function* (threadId, numTurns) {\n+ const context = ensureSessionContext(sessions, threadId);\n+ const messages = yield* runOpenCodeSdk("session.messages", () =>\n+ context.client.session.messages({\n+ sessionID: context.openCodeSessionId,\n+ }),\n+ ).pipe(Effect.mapError(toRequestError));\n \n- return yield* readThread(threadId);\n- },\n- );\n+ const assistantMessages = (messages.data ?? []).filter(\n+ (entry) => entry.info.role === "assistant",\n+ );\n+ const targetIndex = assistantMessages.length - numTurns - 1;\n+ const target = targetIndex >= 0 ? assistantMessages[targetIndex] : null;\n+ yield* runOpenCodeSdk("session.revert", () =>\n+ context.client.session.revert({\n+ sessionID: context.openCodeSessionId,\n+ ...(target ? { messageID: target.info.id } : {}),\n+ }),\n+ ).pipe(Effect.mapError(toRequestError));\n \n- const stopAll: OpenCodeAdapterShape["stopAll"] = () =>\n- Effect.gen(function* () {\n- const contexts = [...sessions.values()];\n- sessions.clear();\n- // `stopOpenCodeContext` is typed as never-failing — SDK aborts are\n- // already `Effect.ignore`\'d inside it. `ignoreCause` here also\n- // swallows defects from throwing finalizers so one bad close can\'t\n- // interrupt the sibling fibers. Same pattern as the layer finalizer.\n- yield* Effect.forEach(\n- contexts,\n- (context) => Effect.ignoreCause(stopOpenCodeContext(context)),\n- { concurrency: "unbounded", discard: true },\n- );\n- });\n+ return yield* readThread(threadId);\n+ },\n+ );\n+\n+ const stopAll: OpenCodeAdapterShape["stopAll"] = () =>\n+ Effect.gen(function* () {\n+ const contexts = [...sessions.values()];\n+ sessions.clear();\n+ // `stopOpenCodeContext` is typed as never-failing — SDK aborts are\n+ // already `Effect.ignore`\'d inside it. `ignoreCause` here also\n+ // swallows defects from throwing finalizers so one bad close can\'t\n+ // interrupt the sibling fibers. Same pattern as the layer finalizer.\n+ yield* Effect.forEach(\n+ contexts,\n+ (context) => Effect.ignoreCause(stopOpenCodeContext(context)),\n+ { concurrency: "unbounded", discard: true },\n+ );\n+ });\n \n- return {\n- provider: PROVIDER,\n- capabilities: {\n- sessionModelSwitch: "in-session",\n- },\n- startSession,\n- sendTurn,\n- interruptTurn,\n- respondToRequest,\n- respondToUserInput,\n- stopSession,\n- listSessions,\n- hasSession,\n- readThread,\n- rollbackThread,\n- stopAll,\n- get streamEvents() {\n- return Stream.fromQueue(runtimeEvents);\n- },\n- } satisfies OpenCodeAdapterShape;\n- }),\n- );\n+ return {\n+ provider: PROVIDER,\n+ capabilities: {\n+ sessionModelSwitch: "in-session",\n+ },\n+ startSession,\n+ sendTurn,\n+ interruptTurn,\n+ respondToRequest,\n+ respondToUserInput,\n+ stopSession,\n+ listSessions,\n+ hasSession,\n+ readThread,\n+ rollbackThread,\n+ stopAll,\n+ get streamEvents() {\n+ return Stream.fromQueue(runtimeEvents);\n+ },\n+ } satisfies OpenCodeAdapterShape;\n+ });\n }\n-\n-export const OpenCodeAdapterLive = makeOpenCodeAdapterLive();\ndiff --git a/apps/server/src/provider/Layers/OpenCodeProvider.test.ts b/apps/server/src/provider/Layers/OpenCodeProvider.test.ts\nindex 75622281c5..7abe0be981 100644\n--- a/apps/server/src/provider/Layers/OpenCodeProvider.test.ts\n+++ b/apps/server/src/provider/Layers/OpenCodeProvider.test.ts\n@@ -2,22 +2,30 @@ import assert from "node:assert/strict";\n \n import * as NodeServices from "@effect/platform-node/NodeServices";\n import { it } from "@effect/vitest";\n-import { Effect, Layer } from "effect";\n+import { Effect, Layer, Schema } from "effect";\n import { beforeEach } from "vitest";\n \n+import { OpenCodeSettings } from "@t3tools/contracts";\n import { ServerConfig } from "../../config.ts";\n-import { ServerSettingsService } from "../../serverSettings.ts";\n-import { OpenCodeProvider } from "../Services/OpenCodeProvider.ts";\n import {\n OpenCodeRuntime,\n OpenCodeRuntimeError,\n type OpenCodeRuntimeShape,\n } from "../opencodeRuntime.ts";\n-import { OpenCodeProviderLive } from "./OpenCodeProvider.ts";\n+import { checkOpenCodeProviderStatus } from "./OpenCodeProvider.ts";\n import type { OpenCodeInventory } from "../opencodeRuntime.ts";\n \n const DEFAULT_VERSION_STDOUT = "opencode 1.14.19\\n";\n \n+/**\n+ * The legacy `OpenCodeProviderLive` Layer + `OpenCodeProvider` service tag\n+ * are deleted. The snapshot-producing logic they wrapped now lives in the\n+ * standalone `checkOpenCodeProviderStatus(settings, cwd)` Effect, which\n+ * drivers call directly when building their per-instance snapshot\n+ * `ServerProviderShape`. Tests mirror that shape: build a settings payload,\n+ * invoke the check, assert on the returned snapshot.\n+ */\n+\n const runtimeMock = {\n state: {\n runVersionError: null as Error | null,\n@@ -90,20 +98,26 @@ beforeEach(() => {\n runtimeMock.reset();\n });\n \n-const makeTestLayer = (settingsOverrides?: Parameters<typeof ServerSettingsService.layerTest>[0]) =>\n- OpenCodeProviderLive.pipe(\n- Layer.provideMerge(Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble)),\n- Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),\n- Layer.provideMerge(ServerSettingsService.layerTest(settingsOverrides)),\n- Layer.provideMerge(NodeServices.layer),\n- );\n-\n-it.layer(makeTestLayer())("OpenCodeProviderLive", (it) => {\n+const testLayer = Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble).pipe(\n+ Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),\n+ Layer.provideMerge(NodeServices.layer),\n+);\n+\n+const makeOpenCodeSettings = (overrides?: Partial<OpenCodeSettings>): OpenCodeSettings =>\n+ Schema.decodeSync(OpenCodeSettings)({\n+ enabled: true,\n+ binaryPath: "opencode",\n+ serverUrl: "",\n+ serverPassword: "",\n+ customModels: [],\n+ ...overrides,\n+ });\n+\n+it.layer(testLayer)("checkOpenCodeProviderStatus", (it) => {\n it.effect("shows a codex-style missing binary message", () =>\n Effect.gen(function* () {\n runtimeMock.state.runVersionError = new Error("spawn opencode ENOENT");\n- const provider = yield* OpenCodeProvider;\n- const snapshot = yield* provider.refresh;\n+ const snapshot = yield* checkOpenCodeProviderStatus(makeOpenCodeSettings(), process.cwd());\n \n assert.equal(snapshot.status, "error");\n assert.equal(snapshot.installed, false);\n@@ -114,8 +128,7 @@ it.layer(makeTestLayer())("OpenCodeProviderLive", (it) => {\n it.effect("hides generic Effect.tryPromise text for local CLI probe failures", () =>\n Effect.gen(function* () {\n runtimeMock.state.runVersionError = new Error("An error occurred in Effect.tryPromise");\n- const provider = yield* OpenCodeProvider;\n- const snapshot = yield* provider.refresh;\n+ const snapshot = yield* checkOpenCodeProviderStatus(makeOpenCodeSettings(), process.cwd());\n \n assert.equal(snapshot.status, "error");\n assert.equal(snapshot.installed, true);\n@@ -123,33 +136,6 @@ it.layer(makeTestLayer())("OpenCodeProviderLive", (it) => {\n }),\n );\n \n- it.effect("refuses to probe when opencode is older than the required minimum", () =>\n- Effect.gen(function* () {\n- runtimeMock.state.versionStdout = "opencode 1.4.7\\n";\n- const provider = yield* OpenCodeProvider;\n- const snapshot = yield* provider.refresh;\n-\n- assert.equal(snapshot.status, "error");\n- assert.equal(snapshot.installed, true);\n- assert.equal(snapshot.version, "1.4.7");\n- assert.ok(snapshot.message?.includes("1.14.19"));\n- assert.ok(snapshot.message?.toLowerCase().includes("upgrade"));\n- }),\n- );\n-\n- it.effect("refuses to probe when opencode --version output is unparseable", () =>\n- Effect.gen(function* () {\n- runtimeMock.state.versionStdout = "garbled binary output\\n";\n- const provider = yield* OpenCodeProvider;\n- const snapshot = yield* provider.refresh;\n-\n- assert.equal(snapshot.status, "error");\n- assert.equal(snapshot.installed, true);\n- assert.equal(snapshot.version, null);\n- assert.ok(snapshot.message?.includes("1.14.19"));\n- }),\n- );\n-\n it.effect("emits OpenCode variant defaults so trait picker can resolve a visible selection", () =>\n Effect.gen(function* () {\n runtimeMock.state.inventory = {\n@@ -182,8 +168,7 @@ it.layer(makeTestLayer())("OpenCodeProviderLive", (it) => {\n ],\n };\n \n- const provider = yield* OpenCodeProvider;\n- const snapshot = yield* provider.refresh;\n+ const snapshot = yield* checkOpenCodeProviderStatus(makeOpenCodeSettings(), process.cwd());\n const model = snapshot.models.find((entry) => entry.slug === "openai/gpt-5.4");\n \n assert.ok(model);\n@@ -191,40 +176,41 @@ it.layer(makeTestLayer())("OpenCodeProviderLive", (it) => {\n (descriptor) => descriptor.id === "variant" && descriptor.type === "select",\n );\n assert.ok(variantDescriptor && variantDescriptor.type === "select");\n- assert.equal(variantDescriptor.options.find((option) => option.isDefault)?.id, "medium");\n+ assert.equal(\n+ variantDescriptor.options.find((option) => option.isDefault === true)?.id,\n+ "medium",\n+ );\n const agentDescriptor = model.capabilities?.optionDescriptors?.find(\n (descriptor) => descriptor.id === "agent" && descriptor.type === "select",\n );\n assert.ok(agentDescriptor && agentDescriptor.type === "select");\n- assert.equal(agentDescriptor.options.find((option) => option.isDefault)?.id, "build");\n+ assert.equal(\n+ agentDescriptor.options.find((option) => option.isDefault === true)?.id,\n+ "build",\n+ );\n }),\n );\n \n it.effect("closes the local OpenCode server scope after provider refresh", () =>\n Effect.gen(function* () {\n- const provider = yield* OpenCodeProvider;\n- yield* provider.refresh;\n+ yield* checkOpenCodeProviderStatus(makeOpenCodeSettings(), process.cwd());\n \n assert.equal(runtimeMock.state.closeCalls, 1);\n }),\n );\n });\n \n-it.layer(\n- makeTestLayer({\n- providers: {\n- opencode: {\n- serverUrl: "http://127.0.0.1:9999",\n- serverPassword: "secret-password",\n- },\n- },\n- }),\n-)("OpenCodeProviderLive with configured server URL", (it) => {\n+it.layer(testLayer)("checkOpenCodeProviderStatus with configured server URL", (it) => {\n it.effect("surfaces a friendly auth error for configured servers", () =>\n Effect.gen(function* () {\n runtimeMock.state.inventoryError = new Error("401 Unauthorized");\n- const provider = yield* OpenCodeProvider;\n- const snapshot = yield* provider.refresh;\n+ const snapshot = yield* checkOpenCodeProviderStatus(\n+ makeOpenCodeSettings({\n+ serverUrl: "http://127.0.0.1:9999",\n+ serverPassword: "secret-password",\n+ }),\n+ process.cwd(),\n+ );\n \n assert.equal(snapshot.status, "error");\n assert.equal(snapshot.installed, true);\n@@ -240,8 +226,13 @@ it.layer(\n runtimeMock.state.inventoryError = new Error(\n "fetch failed: connect ECONNREFUSED 127.0.0.1:9999",\n );\n- const provider = yield* OpenCodeProvider;\n- const snapshot = yield* provider.refresh;\n+ const snapshot = yield* checkOpenCodeProviderStatus(\n+ makeOpenCodeSettings({\n+ serverUrl: "http://127.0.0.1:9999",\n+ serverPassword: "secret-password",\n+ }),\n+ process.cwd(),\n+ );\n \n assert.equal(snapshot.status, "error");\n assert.equal(snapshot.installed, true);\ndiff --git a/apps/server/src/provider/Layers/OpenCodeProvider.ts b/apps/server/src/provider/Layers/OpenCodeProvider.ts\nindex b94840015e..c7487d7d52 100644\n--- a/apps/server/src/provider/Layers/OpenCodeProvider.ts\n+++ b/apps/server/src/provider/Layers/OpenCodeProvider.ts\n@@ -1,24 +1,21 @@\n-import type {\n- ModelCapabilities,\n- OpenCodeSettings,\n- ServerProvider,\n- ServerProviderModel,\n+import {\n+ ProviderDriverKind,\n+ type ModelCapabilities,\n+ type OpenCodeSettings,\n+ type ServerProviderModel,\n } from "@t3tools/contracts";\n-import { Cause, Data, Effect, Equal, Layer, Stream } from "effect";\n+import { Cause, Data, Effect } from "effect";\n \n import { createModelCapabilities } from "@t3tools/shared/model";\n \n-import { ServerConfig } from "../../config.ts";\n-import { ServerSettingsService } from "../../serverSettings.ts";\n-import { makeManagedServerProvider } from "../makeManagedServerProvider.ts";\n import {\n buildServerProvider,\n nonEmptyTrimmed,\n parseGenericCliVersion,\n providerModelsFromSettings,\n+ type ServerProviderDraft,\n } from "../providerSnapshot.ts";\n import { compareCliVersions } from "../cliVersion.ts";\n-import { OpenCodeProvider } from "../Services/OpenCodeProvider.ts";\n import {\n OpenCodeRuntime,\n openCodeRuntimeErrorDetail,\n@@ -26,7 +23,7 @@ import {\n } from "../opencodeRuntime.ts";\n import type { Agent, ProviderListResponse } from "@opencode-ai/sdk/v2";\n \n-const PROVIDER = "opencode" as const;\n+const PROVIDER = ProviderDriverKind.make("opencode");\n const OPENCODE_PRESENTATION = {\n displayName: "OpenCode",\n showInteractionModeToggle: false,\n@@ -251,7 +248,9 @@ function flattenOpenCodeModels(input: OpenCodeInventory): ReadonlyArray<ServerPr\n return models.toSorted((left, right) => left.name.localeCompare(right.name));\n }\n \n-const makePendingOpenCodeProvider = (openCodeSettings: OpenCodeSettings): ServerProvider => {\n+export const makePendingOpenCodeProvider = (\n+ openCodeSettings: OpenCodeSettings,\n+): ServerProviderDraft => {\n const checkedAt = new Date().toISOString();\n const models = providerModelsFromSettings(\n [],\n@@ -262,7 +261,6 @@ const makePendingOpenCodeProvider = (openCodeSettings: OpenCodeSettings): Server\n \n if (!openCodeSettings.enabled) {\n return buildServerProvider({\n- provider: PROVIDER,\n presentation: OPENCODE_PRESENTATION,\n enabled: false,\n checkedAt,\n@@ -281,7 +279,6 @@ const makePendingOpenCodeProvider = (openCodeSettings: OpenCodeSettings): Server\n }\n \n return buildServerProvider({\n- provider: PROVIDER,\n presentation: OPENCODE_PRESENTATION,\n enabled: true,\n checkedAt,\n@@ -296,210 +293,179 @@ const makePendingOpenCodeProvider = (openCodeSettings: OpenCodeSettings): Server\n });\n };\n \n-export const OpenCodeProviderLive = Layer.effect(\n- OpenCodeProvider,\n- Effect.gen(function* () {\n- const serverSettings = yield* ServerSettingsService;\n- const serverConfig = yield* ServerConfig;\n- const openCodeRuntime = yield* OpenCodeRuntime;\n-\n- const checkOpenCodeProviderStatus = Effect.fn("checkOpenCodeProviderStatus")(function* (input: {\n- readonly settings: OpenCodeSettings;\n- readonly cwd: string;\n- }): Effect.fn.Return<ServerProvider, never> {\n- const checkedAt = new Date().toISOString();\n- const customModels = input.settings.customModels;\n- const isExternalServer = input.settings.serverUrl.trim().length > 0;\n-\n- const fallback = (cause: unknown, version: string | null = null) => {\n- const failure = formatOpenCodeProbeError({\n- cause,\n- isExternalServer,\n- serverUrl: input.settings.serverUrl,\n- });\n- return buildServerProvider({\n- provider: PROVIDER,\n- presentation: OPENCODE_PRESENTATION,\n- enabled: input.settings.enabled,\n- checkedAt,\n- models: providerModelsFromSettings(\n- [],\n- PROVIDER,\n- customModels,\n- DEFAULT_OPENCODE_MODEL_CAPABILITIES,\n- ),\n- probe: {\n- installed: failure.installed,\n- version,\n- status: "error",\n- auth: { status: "unknown" },\n- message: failure.message,\n- },\n- });\n- };\n-\n- if (!input.settings.enabled) {\n- return buildServerProvider({\n- provider: PROVIDER,\n- presentation: OPENCODE_PRESENTATION,\n- enabled: false,\n- checkedAt,\n- models: providerModelsFromSettings(\n- [],\n- PROVIDER,\n- customModels,\n- DEFAULT_OPENCODE_MODEL_CAPABILITIES,\n- ),\n- probe: {\n- installed: false,\n- version: null,\n- status: "warning",\n- auth: { status: "unknown" },\n- message: isExternalServer\n- ? "OpenCode is disabled in T3 Code settings. A server URL is configured."\n- : "OpenCode is disabled in T3 Code settings.",\n- },\n- });\n- }\n-\n- let version: string | null = null;\n- if (!isExternalServer) {\n- const versionExit = yield* Effect.exit(\n- openCodeRuntime\n- .runOpenCodeCommand({\n- binaryPath: input.settings.binaryPath,\n- args: ["--version"],\n- })\n- .pipe(\n- Effect.mapError(\n- (cause) =>\n- new OpenCodeProbeError({ cause, detail: openCodeRuntimeErrorDetail(cause) }),\n- ),\n- ),\n- );\n- if (versionExit._tag === "Failure") {\n- return fallback(Cause.squash(versionExit.cause));\n- }\n- version = parseGenericCliVersion(versionExit.value.stdout) ?? null;\n-\n- if (!version) {\n- return fallback(\n- new Error(\n- `Unable to determine OpenCode version from \\`opencode --version\\` output. T3 Code requires OpenCode v${MINIMUM_OPENCODE_VERSION} or newer.`,\n- ),\n- null,\n- );\n- }\n- if (compareCliVersions(version, MINIMUM_OPENCODE_VERSION) < 0) {\n- return buildServerProvider({\n- provider: PROVIDER,\n- presentation: OPENCODE_PRESENTATION,\n- enabled: input.settings.enabled,\n- checkedAt,\n- models: providerModelsFromSettings(\n- [],\n- PROVIDER,\n- customModels,\n- DEFAULT_OPENCODE_MODEL_CAPABILITIES,\n- ),\n- probe: {\n- installed: true,\n- version,\n- status: "error",\n- auth: { status: "unknown" },\n- message: `OpenCode v${version} is too old. Upgrade to v${MINIMUM_OPENCODE_VERSION} or newer.`,\n- },\n- });\n- }\n- }\n-\n- const inventoryExit = yield* Effect.exit(\n- Effect.scoped(\n- Effect.gen(function* () {\n- const server = yield* openCodeRuntime\n- .connectToOpenCodeServer({\n- binaryPath: input.settings.binaryPath,\n- serverUrl: input.settings.serverUrl,\n- })\n- .pipe(\n- Effect.mapError(\n- (cause) =>\n- new OpenCodeProbeError({ cause, detail: openCodeRuntimeErrorDetail(cause) }),\n- ),\n- );\n- return yield* openCodeRuntime\n- .loadOpenCodeInventory(\n- openCodeRuntime.createOpenCodeSdkClient({\n- baseUrl: server.url,\n- directory: input.cwd,\n- ...(isExternalServer && input.settings.serverPassword\n- ? { serverPassword: input.settings.serverPassword }\n- : {}),\n- }),\n- )\n- .pipe(\n- Effect.mapError(\n- (cause) =>\n- new OpenCodeProbeError({ cause, detail: openCodeRuntimeErrorDetail(cause) }),\n- ),\n- );\n- }),\n- ),\n- );\n- if (inventoryExit._tag === "Failure") {\n- return fallback(Cause.squash(inventoryExit.cause), version);\n- }\n+export const checkOpenCodeProviderStatus = Effect.fn("checkOpenCodeProviderStatus")(function* (\n+ openCodeSettings: OpenCodeSettings,\n+ cwd: string,\n+ environment: NodeJS.ProcessEnv = process.env,\n+): Effect.fn.Return<ServerProviderDraft, never, OpenCodeRuntime> {\n+ const openCodeRuntime = yield* OpenCodeRuntime;\n+ const checkedAt = new Date().toISOString();\n+ const customModels = openCodeSettings.customModels;\n+ const isExternalServer = openCodeSettings.serverUrl.trim().length > 0;\n+\n+ const fallback = (cause: unknown, version: string | null = null) => {\n+ const failure = formatOpenCodeProbeError({\n+ cause,\n+ isExternalServer,\n+ serverUrl: openCodeSettings.serverUrl,\n+ });\n+ return buildServerProvider({\n+ presentation: OPENCODE_PRESENTATION,\n+ enabled: openCodeSettings.enabled,\n+ checkedAt,\n+ models: providerModelsFromSettings(\n+ [],\n+ PROVIDER,\n+ customModels,\n+ DEFAULT_OPENCODE_MODEL_CAPABILITIES,\n+ ),\n+ probe: {\n+ installed: failure.installed,\n+ version,\n+ status: "error",\n+ auth: { status: "unknown" },\n+ message: failure.message,\n+ },\n+ });\n+ };\n \n- const models = providerModelsFromSettings(\n- flattenOpenCodeModels(inventoryExit.value),\n+ if (!openCodeSettings.enabled) {\n+ return buildServerProvider({\n+ presentation: OPENCODE_PRESENTATION,\n+ enabled: false,\n+ checkedAt,\n+ models: providerModelsFromSettings(\n+ [],\n PROVIDER,\n customModels,\n DEFAULT_OPENCODE_MODEL_CAPABILITIES,\n+ ),\n+ probe: {\n+ installed: false,\n+ version: null,\n+ status: "warning",\n+ auth: { status: "unknown" },\n+ message: isExternalServer\n+ ? "OpenCode is disabled in T3 Code settings. A server URL is configured."\n+ : "OpenCode is disabled in T3 Code settings.",\n+ },\n+ });\n+ }\n+\n+ let version: string | null = null;\n+ if (!isExternalServer) {\n+ const versionExit = yield* Effect.exit(\n+ openCodeRuntime\n+ .runOpenCodeCommand({\n+ binaryPath: openCodeSettings.binaryPath,\n+ args: ["--version"],\n+ environment,\n+ })\n+ .pipe(\n+ Effect.mapError(\n+ (cause) => new OpenCodeProbeError({ cause, detail: openCodeRuntimeErrorDetail(cause) }),\n+ ),\n+ ),\n+ );\n+ if (versionExit._tag === "Failure") {\n+ return fallback(Cause.squash(versionExit.cause));\n+ }\n+ version = parseGenericCliVersion(versionExit.value.stdout) ?? null;\n+\n+ if (!version) {\n+ return fallback(\n+ new Error(\n+ `Unable to determine OpenCode version from \\`opencode --version\\` output. T3 Code requires OpenCode v${MINIMUM_OPENCODE_VERSION} or newer.`,\n+ ),\n+ null,\n );\n- const connectedCount = inventoryExit.value.providerList.connected.length;\n+ }\n+ if (compareCliVersions(version, MINIMUM_OPENCODE_VERSION) < 0) {\n return buildServerProvider({\n- provider: PROVIDER,\n presentation: OPENCODE_PRESENTATION,\n- enabled: true,\n+ enabled: openCodeSettings.enabled,\n checkedAt,\n- models,\n+ models: providerModelsFromSettings(\n+ [],\n+ PROVIDER,\n+ customModels,\n+ DEFAULT_OPENCODE_MODEL_CAPABILITIES,\n+ ),\n probe: {\n installed: true,\n version,\n- status: connectedCount > 0 ? "ready" : "warning",\n- auth: {\n- status: connectedCount > 0 ? "authenticated" : "unknown",\n- type: "opencode",\n- },\n- message:\n- connectedCount > 0\n- ? `${connectedCount} upstream provider${connectedCount === 1 ? "" : "s"} connected through ${isExternalServer ? "the configured OpenCode server" : "OpenCode"}.`\n- : isExternalServer\n- ? "Connected to the configured OpenCode server, but it did not report any connected upstream providers."\n- : "OpenCode is available, but it did not report any connected upstream providers.",\n+ status: "error",\n+ auth: { status: "unknown" },\n+ message: `OpenCode v${version} is too old. Upgrade to v${MINIMUM_OPENCODE_VERSION} or newer.`,\n },\n });\n- });\n+ }\n+ }\n \n- const getProviderSettings = serverSettings.getSettings.pipe(\n- Effect.map((settings) => settings.providers.opencode),\n- );\n+ const inventoryExit = yield* Effect.exit(\n+ Effect.scoped(\n+ Effect.gen(function* () {\n+ const server = yield* openCodeRuntime\n+ .connectToOpenCodeServer({\n+ binaryPath: openCodeSettings.binaryPath,\n+ serverUrl: openCodeSettings.serverUrl,\n+ environment,\n+ })\n+ .pipe(\n+ Effect.mapError(\n+ (cause) =>\n+ new OpenCodeProbeError({ cause, detail: openCodeRuntimeErrorDetail(cause) }),\n+ ),\n+ );\n+ return yield* openCodeRuntime\n+ .loadOpenCodeInventory(\n+ openCodeRuntime.createOpenCodeSdkClient({\n+ baseUrl: server.url,\n+ directory: cwd,\n+ ...(isExternalServer && openCodeSettings.serverPassword\n+ ? { serverPassword: openCodeSettings.serverPassword }\n+ : {}),\n+ }),\n+ )\n+ .pipe(\n+ Effect.mapError(\n+ (cause) =>\n+ new OpenCodeProbeError({ cause, detail: openCodeRuntimeErrorDetail(cause) }),\n+ ),\n+ );\n+ }),\n+ ),\n+ );\n+ if (inventoryExit._tag === "Failure") {\n+ return fallback(Cause.squash(inventoryExit.cause), version);\n+ }\n \n- return yield* makeManagedServerProvider<OpenCodeSettings>({\n- getSettings: getProviderSettings.pipe(Effect.orDie),\n- streamSettings: serverSettings.streamChanges.pipe(\n- Stream.map((settings) => settings.providers.opencode),\n- ),\n- haveSettingsChanged: (previous, next) => !Equal.equals(previous, next),\n- initialSnapshot: makePendingOpenCodeProvider,\n- checkProvider: getProviderSettings.pipe(\n- Effect.flatMap((settings) =>\n- checkOpenCodeProviderStatus({\n- settings,\n- cwd: serverConfig.cwd,\n- }),\n- ),\n- ),\n- });\n- }),\n-);\n+ const models = providerModelsFromSettings(\n+ flattenOpenCodeModels(inventoryExit.value),\n+ PROVIDER,\n+ customModels,\n+ DEFAULT_OPENCODE_MODEL_CAPABILITIES,\n+ );\n+ const connectedCount = inventoryExit.value.providerList.connected.length;\n+ return buildServerProvider({\n+ presentation: OPENCODE_PRESENTATION,\n+ enabled: true,\n+ checkedAt,\n+ models,\n+ probe: {\n+ installed: true,\n+ version,\n+ status: connectedCount > 0 ? "ready" : "warning",\n+ auth: {\n+ status: connectedCount > 0 ? "authenticated" : "unknown",\n+ type: "opencode",\n+ },\n+ message:\n+ connectedCount > 0\n+ ? `${connectedCount} upstream provider${connectedCount === 1 ? "" : "s"} connected through ${isExternalServer ? "the configured OpenCode server" : "OpenCode"}.`\n+ : isExternalServer\n+ ? "Connected to the configured OpenCode server, but it did not report any connected upstream providers."\n+ : "OpenCode is available, but it did not report any connected upstream providers.",\n+ },\n+ });\n+});\ndiff --git a/apps/server/src/provider/Layers/ProviderAdapterRegistry.test.ts b/apps/server/src/provider/Layers/ProviderAdapterRegistry.test.ts\nindex e0a68f68b6..05735f3a50 100644\n--- a/apps/server/src/provider/Layers/ProviderAdapterRegistry.test.ts\n+++ b/apps/server/src/provider/Layers/ProviderAdapterRegistry.test.ts\n@@ -1,24 +1,30 @@\n-import type { ProviderKind } from "@t3tools/contracts";\n+import {\n+ defaultInstanceIdForDriver,\n+ ProviderDriverKind,\n+ type ServerProvider,\n+} from "@t3tools/contracts";\n import { it, assert, vi } from "@effect/vitest";\n-import { assertFailure } from "@effect/vitest/utils";\n \n-import { Effect, Layer, Stream } from "effect";\n+import { Effect, Layer, PubSub, Stream } from "effect";\n \n-import { ClaudeAdapter } from "../Services/ClaudeAdapter.ts";\n import type { ClaudeAdapterShape } from "../Services/ClaudeAdapter.ts";\n-import { CodexAdapter } from "../Services/CodexAdapter.ts";\n import type { CodexAdapterShape } from "../Services/CodexAdapter.ts";\n-import { CursorAdapter } from "../Services/CursorAdapter.ts";\n import type { CursorAdapterShape } from "../Services/CursorAdapter.ts";\n-import { OpenCodeAdapter } from "../Services/OpenCodeAdapter.ts";\n import type { OpenCodeAdapterShape } from "../Services/OpenCodeAdapter.ts";\n import { ProviderAdapterRegistry } from "../Services/ProviderAdapterRegistry.ts";\n+import { ProviderInstanceRegistry } from "../Services/ProviderInstanceRegistry.ts";\n+import type { ProviderInstance } from "../ProviderDriver.ts";\n+import type { TextGenerationShape } from "../../git/Services/TextGeneration.ts";\n import { ProviderAdapterRegistryLive } from "./ProviderAdapterRegistry.ts";\n-import { ProviderUnsupportedError } from "../Errors.ts";\n import * as NodeServices from "@effect/platform-node/NodeServices";\n \n+const CODEX_DRIVER = ProviderDriverKind.make("codex");\n+const CLAUDE_AGENT_DRIVER = ProviderDriverKind.make("claudeAgent");\n+const OPENCODE_DRIVER = ProviderDriverKind.make("opencode");\n+const CURSOR_DRIVER = ProviderDriverKind.make("cursor");\n+\n const fakeCodexAdapter: CodexAdapterShape = {\n- provider: "codex",\n+ provider: CODEX_DRIVER,\n capabilities: { sessionModelSwitch: "in-session" },\n startSession: vi.fn(),\n sendTurn: vi.fn(),\n@@ -35,7 +41,7 @@ const fakeCodexAdapter: CodexAdapterShape = {\n };\n \n const fakeClaudeAdapter: ClaudeAdapterShape = {\n- provider: "claudeAgent",\n+ provider: CLAUDE_AGENT_DRIVER,\n capabilities: { sessionModelSwitch: "in-session" },\n startSession: vi.fn(),\n sendTurn: vi.fn(),\n@@ -52,7 +58,7 @@ const fakeClaudeAdapter: ClaudeAdapterShape = {\n };\n \n const fakeOpenCodeAdapter: OpenCodeAdapterShape = {\n- provider: "opencode",\n+ provider: OPENCODE_DRIVER,\n capabilities: { sessionModelSwitch: "in-session" },\n startSession: vi.fn(),\n sendTurn: vi.fn(),\n@@ -69,7 +75,7 @@ const fakeOpenCodeAdapter: OpenCodeAdapterShape = {\n };\n \n const fakeCursorAdapter: CursorAdapterShape = {\n- provider: "cursor",\n+ provider: CURSOR_DRIVER,\n capabilities: { sessionModelSwitch: "in-session" },\n startSession: vi.fn(),\n sendTurn: vi.fn(),\n@@ -85,44 +91,94 @@ const fakeCursorAdapter: CursorAdapterShape = {\n streamEvents: Stream.empty,\n };\n \n-const layer = it.layer(\n- Layer.mergeAll(\n- Layer.provide(\n- ProviderAdapterRegistryLive,\n- Layer.mergeAll(\n- Layer.succeed(CodexAdapter, fakeCodexAdapter),\n- Layer.succeed(ClaudeAdapter, fakeClaudeAdapter),\n- Layer.succeed(OpenCodeAdapter, fakeOpenCodeAdapter),\n- Layer.succeed(CursorAdapter, fakeCursorAdapter),\n- ),\n- ),\n- NodeServices.layer,\n- ),\n+// ProviderAdapterRegistryLive is now a facade over ProviderInstanceRegistry —\n+// it walks `listInstances` once at boot and surfaces the default-instance\n+// adapter keyed by its driver kind. To test the facade we supply four fake\n+// instances whose `instanceId === defaultInstanceIdForDriver(driverKind)` so\n+// they pass the default-instance filter.\n+const makeFakeInstance = (\n+ driverKindString: "codex" | "claudeAgent" | "cursor" | "opencode",\n+ adapter: ProviderInstance["adapter"],\n+): ProviderInstance => {\n+ const driverKind = ProviderDriverKind.make(driverKindString);\n+ return {\n+ instanceId: defaultInstanceIdForDriver(driverKind),\n+ driverKind,\n+ continuationIdentity: {\n+ driverKind,\n+ continuationKey: `${driverKind}:instance:${defaultInstanceIdForDriver(driverKind)}`,\n+ },\n+ displayName: undefined,\n+ enabled: true,\n+ snapshot: {\n+ getSnapshot: Effect.succeed({} as unknown as ServerProvider),\n+ refresh: Effect.succeed({} as unknown as ServerProvider),\n+ streamChanges: Stream.empty,\n+ },\n+ adapter,\n+ textGeneration: {} as unknown as TextGenerationShape,\n+ };\n+};\n+\n+const fakeInstances: ReadonlyArray<ProviderInstance> = [\n+ makeFakeInstance("codex", fakeCodexAdapter),\n+ makeFakeInstance("claudeAgent", fakeClaudeAdapter),\n+ makeFakeInstance("opencode", fakeOpenCodeAdapter),\n+ makeFakeInstance("cursor", fakeCursorAdapter),\n+];\n+\n+const fakeInstanceRegistryLayer = Layer.succeed(ProviderInstanceRegistry, {\n+ getInstance: (instanceId) =>\n+ Effect.succeed(fakeInstances.find((instance) => instance.instanceId === instanceId)),\n+ listInstances: Effect.succeed(fakeInstances),\n+ listUnavailable: Effect.succeed([]),\n+ streamChanges: Stream.empty,\n+ // Tests never drive changes through this fake; acquire a throwaway\n+ // subscription on an unused PubSub so the shape is satisfied.\n+ subscribeChanges: Effect.flatMap(PubSub.unbounded<void>(), (pubsub) => PubSub.subscribe(pubsub)),\n+});\n+\n+const layer = Layer.mergeAll(\n+ Layer.provide(ProviderAdapterRegistryLive, fakeInstanceRegistryLayer),\n+ NodeServices.layer,\n );\n \n-layer("ProviderAdapterRegistryLive", (it) => {\n- it.effect("resolves a registered provider adapter", () =>\n+it.layer(layer)("ProviderAdapterRegistryLive", (it) => {\n+ it("resolves adapters and routing metadata from provider instances", () =>\n Effect.gen(function* () {\n const registry = yield* ProviderAdapterRegistry;\n- const codex = yield* registry.getByProvider("codex");\n- const claude = yield* registry.getByProvider("claudeAgent");\n- const openCode = yield* registry.getByProvider("opencode");\n- const cursor = yield* registry.getByProvider("cursor");\n- assert.equal(codex, fakeCodexAdapter);\n- assert.equal(claude, fakeClaudeAdapter);\n- assert.equal(openCode, fakeOpenCodeAdapter);\n- assert.equal(cursor, fakeCursorAdapter);\n+ const claudeInstanceId = defaultInstanceIdForDriver(CLAUDE_AGENT_DRIVER);\n \n- const providers = yield* registry.listProviders();\n- assert.deepEqual(providers, ["codex", "claudeAgent", "opencode", "cursor"]);\n- }),\n- );\n+ const adapter = yield* registry.getByInstance(claudeInstanceId);\n+ assert.strictEqual(adapter, fakeClaudeAdapter);\n \n- it.effect("fails with ProviderUnsupportedError for unknown providers", () =>\n- Effect.gen(function* () {\n- const registry = yield* ProviderAdapterRegistry;\n- const adapter = yield* registry.getByProvider("unknown" as ProviderKind).pipe(Effect.result);\n- assertFailure(adapter, new ProviderUnsupportedError({ provider: "unknown" }));\n- }),\n- );\n+ const info = yield* registry.getInstanceInfo(claudeInstanceId);\n+ assert.deepStrictEqual(info, {\n+ instanceId: claudeInstanceId,\n+ driverKind: CLAUDE_AGENT_DRIVER,\n+ displayName: undefined,\n+ accentColor: undefined,\n+ enabled: true,\n+ continuationIdentity: {\n+ driverKind: CLAUDE_AGENT_DRIVER,\n+ continuationKey: "claudeAgent:instance:claudeAgent",\n+ },\n+ });\n+\n+ const instances = yield* registry.listInstances();\n+ assert.deepStrictEqual(instances, [\n+ defaultInstanceIdForDriver(CODEX_DRIVER),\n+ claudeInstanceId,\n+ defaultInstanceIdForDriver(OPENCODE_DRIVER),\n+ defaultInstanceIdForDriver(CURSOR_DRIVER),\n+ ]);\n+\n+ const providers = yield* registry.listProviders();\n+ assert.deepStrictEqual(providers, [\n+ CODEX_DRIVER,\n+ CLAUDE_AGENT_DRIVER,\n+ OPENCODE_DRIVER,\n+ CURSOR_DRIVER,\n+ ]);\n+ }));\n });\ndiff --git a/apps/server/src/provider/Layers/ProviderAdapterRegistry.ts b/apps/server/src/provider/Layers/ProviderAdapterRegistry.ts\nindex dabe5b8581..f2eeaa1aae 100644\n--- a/apps/server/src/provider/Layers/ProviderAdapterRegistry.ts\n+++ b/apps/server/src/provider/Layers/ProviderAdapterRegistry.ts\n@@ -1,59 +1,101 @@\n /**\n- * ProviderAdapterRegistryLive - In-memory provider adapter lookup layer.\n+ * ProviderAdapterRegistryLive — facade over `ProviderInstanceRegistry`.\n *\n- * Binds provider kinds (codex/claudeAgent/...) to concrete adapter services.\n- * This layer only performs adapter lookup; it does not route session-scoped\n- * calls or own provider lifecycle workflows.\n+ * `ProviderAdapterRegistry` historically mapped one `ProviderDriverKind` to one\n+ * adapter via the four `<X>AdapterLive` singleton Layers. The per-instance\n+ * refactor moved adapter construction inside each `ProviderDriver.create()`:\n+ * adapters are now bundled on the `ProviderInstance` that the\n+ * `ProviderInstanceRegistry` owns.\n+ *\n+ * This facade fulfills the `ProviderAdapterRegistryShape` contract by doing\n+ * dynamic look-ups against `ProviderInstanceRegistry` on every call. That\n+ * means settings-driven hot-reload shows up here automatically — adding a\n+ * new instance via settings makes `getByInstance` resolve immediately\n+ * without rebuilding the facade.\n *\n * @module ProviderAdapterRegistryLive\n */\n+import {\n+ defaultInstanceIdForDriver,\n+ ProviderInstanceId,\n+ type ProviderDriverKind,\n+} from "@t3tools/contracts";\n import { Effect, Layer } from "effect";\n \n-import { ProviderUnsupportedError, type ProviderAdapterError } from "../Errors.ts";\n-import type { ProviderAdapterShape } from "../Services/ProviderAdapter.ts";\n+import { ProviderUnsupportedError } from "../Errors.ts";\n+import { ProviderInstanceRegistry } from "../Services/ProviderInstanceRegistry.ts";\n import {\n ProviderAdapterRegistry,\n type ProviderAdapterRegistryShape,\n } from "../Services/ProviderAdapterRegistry.ts";\n-import { ClaudeAdapter } from "../Services/ClaudeAdapter.ts";\n-import { CodexAdapter } from "../Services/CodexAdapter.ts";\n-import { CursorAdapter } from "../Services/CursorAdapter.ts";\n-import { OpenCodeAdapter } from "../Services/OpenCodeAdapter.ts";\n-import { createBuiltInAdapterList } from "../builtInProviderCatalog.ts";\n-\n-export interface ProviderAdapterRegistryLiveOptions {\n- readonly adapters?: ReadonlyArray<ProviderAdapterShape<ProviderAdapterError>>;\n-}\n-\n-const makeProviderAdapterRegistry = Effect.fn("makeProviderAdapterRegistry")(function* (\n- options?: ProviderAdapterRegistryLiveOptions,\n-) {\n- const cursorAdapterOption = yield* Effect.serviceOption(CursorAdapter);\n- const adapters =\n- options?.adapters !== undefined\n- ? options.adapters\n- : createBuiltInAdapterList({\n- codex: yield* CodexAdapter,\n- claudeAgent: yield* ClaudeAdapter,\n- opencode: yield* OpenCodeAdapter,\n- ...(cursorAdapterOption._tag === "Some" ? { cursor: cursorAdapterOption.value } : {}),\n- });\n- const byProvider = new Map(adapters.map((adapter) => [adapter.provider, adapter]));\n-\n- const getByProvider: ProviderAdapterRegistryShape["getByProvider"] = (provider) => {\n- const adapter = byProvider.get(provider);\n- if (!adapter) {\n- return Effect.fail(new ProviderUnsupportedError({ provider }));\n- }\n- return Effect.succeed(adapter);\n- };\n+\n+const makeProviderAdapterRegistry = Effect.fn("makeProviderAdapterRegistry")(function* () {\n+ const registry = yield* ProviderInstanceRegistry;\n+\n+ const getByInstance: ProviderAdapterRegistryShape["getByInstance"] = (instanceId) =>\n+ registry.getInstance(instanceId).pipe(\n+ Effect.flatMap((instance) =>\n+ instance === undefined\n+ ? Effect.fail(\n+ new ProviderUnsupportedError({\n+ provider: instanceId,\n+ }),\n+ )\n+ : Effect.succeed(instance.adapter),\n+ ),\n+ );\n+\n+ const getInstanceInfo: ProviderAdapterRegistryShape["getInstanceInfo"] = (instanceId) =>\n+ registry.getInstance(instanceId).pipe(\n+ Effect.flatMap((instance) =>\n+ instance === undefined\n+ ? Effect.fail(\n+ new ProviderUnsupportedError({\n+ provider: instanceId,\n+ }),\n+ )\n+ : Effect.succeed({\n+ instanceId: instance.instanceId,\n+ driverKind: instance.driverKind,\n+ displayName: instance.displayName,\n+ accentColor: instance.accentColor,\n+ enabled: instance.enabled,\n+ continuationIdentity: instance.continuationIdentity,\n+ }),\n+ ),\n+ );\n+\n+ const listInstances: ProviderAdapterRegistryShape["listInstances"] = () =>\n+ registry.listInstances.pipe(\n+ Effect.map((instances) => instances.map((instance) => instance.instanceId)),\n+ );\n \n const listProviders: ProviderAdapterRegistryShape["listProviders"] = () =>\n- Effect.sync(() => Array.from(byProvider.keys()));\n+ registry.listInstances.pipe(\n+ Effect.map((instances) => {\n+ const kinds = new Set<ProviderDriverKind>();\n+ for (const instance of instances) {\n+ const defaultId = defaultInstanceIdForDriver(instance.driverKind);\n+ if (instance.instanceId === defaultId) {\n+ // Only the default-instance rows show up through the legacy\n+ // shim — custom instances like `codex_personal` have no\n+ // `ProviderDriverKind` equivalent.\n+ kinds.add(instance.driverKind);\n+ }\n+ }\n+ return Array.from(kinds);\n+ }),\n+ );\n \n return {\n- getByProvider,\n+ getByInstance,\n+ getInstanceInfo,\n+ listInstances,\n listProviders,\n+ // Proxy directly — the facade has no state of its own; the instance\n+ // registry already coalesces adds/removes/rebuilds into one emission.\n+ streamChanges: registry.streamChanges,\n+ subscribeChanges: registry.subscribeChanges,\n } satisfies ProviderAdapterRegistryShape;\n });\n \n@@ -61,3 +103,14 @@ export const ProviderAdapterRegistryLive = Layer.effect(\n ProviderAdapterRegistry,\n makeProviderAdapterRegistry(),\n );\n+\n+// Exposed for tests that want to build a facade over a pre-assembled\n+// `ProviderInstanceRegistry` without pulling in the whole boot graph.\n+export { makeProviderAdapterRegistry };\n+\n+// Re-export for consumers that need the accessor shape. The service tag\n+// itself lives in `Services/ProviderAdapterRegistry.ts`.\n+export { ProviderAdapterRegistry } from "../Services/ProviderAdapterRegistry.ts";\n+// Re-export for consumers (including tests) that construct a\n+// `ProviderInstanceId` before calling `getByInstance`.\n+export { ProviderInstanceId };\ndiff --git a/apps/server/src/provider/Layers/ProviderEventLoggers.ts b/apps/server/src/provider/Layers/ProviderEventLoggers.ts\nnew file mode 100644\nindex 0000000000..4a15fdd685\n--- /dev/null\n+++ b/apps/server/src/provider/Layers/ProviderEventLoggers.ts\n@@ -0,0 +1,83 @@\n+/**\n+ * ProviderEventLoggers — single observability service that owns the two\n+ * shared NDJSON streams the provider runtime writes:\n+ *\n+ * - `native` — provider-protocol events as the SDK emits them, written\n+ * from inside each `<X>Adapter` factory.\n+ * - `canonical` — runtime events after `ProviderService` has normalized\n+ * them onto `ProviderRuntimeEvent`.\n+ *\n+ * Why a service tag and not constructor options?\n+ *\n+ * - Adapters are now constructed *inside* drivers (`<X>Driver.create()`),\n+ * not at the boot Layer. There is no longer a single `make<X>AdapterLive(options)`\n+ * call site where we can hand an `EventNdjsonLogger` in by hand.\n+ * - Multiple driver instances per kind (`codex_personal`, `codex_work`)\n+ * should share one underlying log writer per stream — opening N writers\n+ * against the same rotating file would race the rotation logic. Owning\n+ * the loggers on a single tag keeps that invariant intact.\n+ * - Tests can swap one (or both) loggers with in-memory recorders by\n+ * `Layer.succeed(ProviderEventLoggers, { native, canonical })` instead of\n+ * juggling per-Layer option threading.\n+ *\n+ * Both fields are optional. `makeEventNdjsonLogger` returns `undefined` when\n+ * the target directory cannot be created; we forward that as `undefined`\n+ * rather than failing the boot Layer, matching the previous best-effort\n+ * behavior of `server.ts`.\n+ *\n+ * @module provider/Layers/ProviderEventLoggers\n+ */\n+import { Context, Effect, Layer } from "effect";\n+\n+import { ServerConfig } from "../../config.ts";\n+import { type EventNdjsonLogger, makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";\n+\n+export interface ProviderEventLoggersShape {\n+ readonly native: EventNdjsonLogger | undefined;\n+ readonly canonical: EventNdjsonLogger | undefined;\n+}\n+\n+/**\n+ * Shared logger pair for native + canonical provider event streams.\n+ *\n+ * Service value is intentionally a struct of two optional loggers rather\n+ * than two parallel tags. Construction site is one place\n+ * (`ProviderEventLoggersLive`); consumers (drivers, `ProviderService`) read\n+ * one tag and pluck the field they need.\n+ */\n+export class ProviderEventLoggers extends Context.Service<\n+ ProviderEventLoggers,\n+ ProviderEventLoggersShape\n+>()("t3/provider/ProviderEventLoggers") {}\n+\n+/**\n+ * Constant value used by tests / boot layers that want to opt out of native\n+ * + canonical logging entirely. Keeps the tag non-optional in the type\n+ * system while letting the runtime treat absence as a no-op.\n+ */\n+export const NoOpProviderEventLoggers: ProviderEventLoggersShape = {\n+ native: undefined,\n+ canonical: undefined,\n+};\n+\n+/**\n+ * Live Layer that builds both loggers from `ServerConfig.providerEventLogPath`.\n+ * If the directory create fails for either stream, the corresponding field\n+ * is `undefined` and writes from that stream become no-ops downstream.\n+ */\n+export const ProviderEventLoggersLive = Layer.effect(\n+ ProviderEventLoggers,\n+ Effect.gen(function* () {\n+ const { providerEventLogPath } = yield* ServerConfig;\n+ const native = yield* makeEventNdjsonLogger(providerEventLogPath, {\n+ stream: "native",\n+ });\n+ const canonical = yield* makeEventNdjsonLogger(providerEventLogPath, {\n+ stream: "canonical",\n+ });\n+ return {\n+ native,\n+ canonical,\n+ } satisfies ProviderEventLoggersShape;\n+ }),\n+);\ndiff --git a/apps/server/src/provider/Layers/ProviderInstanceRegistryHydration.ts b/apps/server/src/provider/Layers/ProviderInstanceRegistryHydration.ts\nnew file mode 100644\nindex 0000000000..b6c44306f9\n--- /dev/null\n+++ b/apps/server/src/provider/Layers/ProviderInstanceRegistryHydration.ts\n@@ -0,0 +1,176 @@\n+/**\n+ * ProviderInstanceRegistryHydration — derive a `ProviderInstanceConfigMap`\n+ * from `ServerSettings` and keep `ProviderInstanceRegistry` in sync with it.\n+ *\n+ * The server still reads two shapes:\n+ *\n+ * 1. `settings.providerInstances` — the new driver-agnostic map the\n+ * registry expects. Keyed by `ProviderInstanceId`, values are\n+ * `ProviderInstanceConfig` envelopes.\n+ * 2. `settings.providers.<kind>` — the legacy single-instance-per-driver\n+ * fields (`providers.codex`, `providers.claudeAgent`, …). These are\n+ * the source of truth for every deployment that hasn\'t been migrated\n+ * yet to an explicit `providerInstances` entry.\n+ *\n+ * This module bridges (2) into (1) and wires the resulting map into a\n+ * mutable registry. For every built-in driver whose id is not already\n+ * present in `providerInstances` (keyed on\n+ * `defaultInstanceIdForDriver(driverKind)` — literally the driver kind as a\n+ * routing slug), we synthesize an envelope from the legacy field. The\n+ * registry decodes both flavours through the same `configSchema` and ends\n+ * up with one uniform `ProviderInstance` per entry.\n+ *\n+ * Explicit `providerInstances` entries always win — users can already\n+ * override the legacy `providers.<kind>` blob by authoring a\n+ * `providerInstances.codex` entry with a matching driver, and we don\'t\n+ * want the synthesized envelope to silently stomp their config.\n+ *\n+ * Hot-reload\n+ * ----------\n+ * On layer build we:\n+ * 1. Read the current `ServerSettings` once and use it to seed the\n+ * registry\'s initial state via `ProviderInstanceRegistryMutableLayer`.\n+ * 2. Fork a daemon fiber (lifetime tied to the layer\'s scope) that\n+ * subscribes to `ServerSettingsService.streamChanges` and calls\n+ * `ProviderInstanceRegistryMutator.reconcile` on every emission.\n+ *\n+ * Failures inside the watcher are logged and swallowed so a single bad\n+ * settings emission cannot kill the registry. Unknown drivers and invalid\n+ * configs already round-trip through the registry\'s own "unavailable"\n+ * shadow bucket.\n+ *\n+ * @module provider/Layers/ProviderInstanceRegistryHydration\n+ */\n+import {\n+ defaultInstanceIdForDriver,\n+ type ProviderInstanceConfig,\n+ type ProviderInstanceConfigMap,\n+ ServerSettings,\n+} from "@t3tools/contracts";\n+import { Effect, Layer, Stream } from "effect";\n+\n+import { ServerSettingsService } from "../../serverSettings.ts";\n+import { BUILT_IN_DRIVERS, type BuiltInDriversEnv } from "../builtInDrivers.ts";\n+import { ProviderInstanceRegistry } from "../Services/ProviderInstanceRegistry.ts";\n+import { ProviderInstanceRegistryMutator } from "../Services/ProviderInstanceRegistryMutator.ts";\n+import { ProviderInstanceRegistryMutableLayer } from "./ProviderInstanceRegistryLive.ts";\n+\n+/**\n+ * Synthesize a `ProviderInstanceConfigMap` from a `ServerSettings` snapshot.\n+ *\n+ * Strategy:\n+ * 1. Copy all explicit `settings.providerInstances` entries verbatim.\n+ * 2. For each built-in driver whose `defaultInstanceIdForDriver(id)` key\n+ * is *not* already in the explicit map, synthesize an entry from the\n+ * matching legacy `settings.providers.<kind>` blob.\n+ *\n+ * The returned map is the input the registry consumes; pure & exported\n+ * separately so the hydration logic can be exercised by unit tests\n+ * without layering.\n+ */\n+export const deriveProviderInstanceConfigMap = (\n+ settings: ServerSettings,\n+): ProviderInstanceConfigMap => {\n+ const merged: Record<string, ProviderInstanceConfig> = { ...settings.providerInstances };\n+\n+ for (const driver of BUILT_IN_DRIVERS) {\n+ const instanceId = defaultInstanceIdForDriver(driver.driverKind);\n+ if (instanceId in merged) {\n+ // Explicit `providerInstances` entry for this slot — user-authored\n+ // config always wins over the legacy mirror.\n+ continue;\n+ }\n+\n+ // Only built-in drivers have a legacy mirror; the registry\'s\n+ // `providers` struct is keyed on the same literal slug as\n+ // `driverKind`. Access is dynamic (the driver kind is a branded string),\n+ // but it\'s constrained to `keyof settings.providers` by the union of\n+ // built-in driver kinds.\n+ const legacyKey = driver.driverKind as keyof ServerSettings["providers"];\n+ const legacyConfig = settings.providers[legacyKey];\n+ if (legacyConfig === undefined) {\n+ continue;\n+ }\n+\n+ merged[instanceId] = {\n+ driver: driver.driverKind,\n+ config: legacyConfig,\n+ };\n+ }\n+\n+ return merged as ProviderInstanceConfigMap;\n+};\n+\n+/**\n+ * Layer that consumes `ProviderInstanceRegistryMutator` and forks a\n+ * settings-watcher fiber. The fiber\'s lifetime is tied to the enclosing\n+ * layer scope (process lifetime in production), so it is interrupted on\n+ * shutdown without leaking.\n+ *\n+ * Errors inside the watcher are logged and swallowed — the registry\'s own\n+ * "unavailable" bucket already absorbs unknown drivers and invalid\n+ * configs, so the only way the watcher could fail is a settings stream\n+ * tear-down, which logs and exits cleanly.\n+ */\n+const SettingsWatcherLive: Layer.Layer<\n+ never,\n+ never,\n+ ProviderInstanceRegistryMutator | ServerSettingsService\n+> = Layer.effectDiscard(\n+ Effect.gen(function* () {\n+ const mutator = yield* ProviderInstanceRegistryMutator;\n+ const serverSettings = yield* ServerSettingsService;\n+ yield* serverSettings.streamChanges.pipe(\n+ Stream.runForEach((next) =>\n+ mutator\n+ .reconcile(deriveProviderInstanceConfigMap(next))\n+ .pipe(\n+ Effect.catchCause((cause) =>\n+ Effect.logError("ProviderInstanceRegistry reconcile failed", cause),\n+ ),\n+ ),\n+ ),\n+ Effect.forkScoped,\n+ );\n+ }),\n+);\n+\n+/**\n+ * Hydrate `ProviderInstanceRegistry` from `ServerSettings` and keep it in\n+ * sync with subsequent `streamChanges` emissions.\n+ *\n+ * The Layer\'s two halves:\n+ * - `ProviderInstanceRegistryMutableLayer` produces the registry +\n+ * mutator from the initial config map. Its scope owns every\n+ * per-instance child scope created during reconcile.\n+ * - `SettingsWatcherLive` consumes the mutator and runs a daemon fiber\n+ * in the same scope.\n+ *\n+ * Composing via `Layer.provideMerge` makes the watcher\'s deps available\n+ * from the mutable layer while still surfacing the registry as an output.\n+ * The mutator tag is technically also exposed; only this module imports\n+ * it, so the visibility leak is harmless in practice.\n+ */\n+export const ProviderInstanceRegistryHydrationLive: Layer.Layer<\n+ ProviderInstanceRegistry,\n+ never,\n+ BuiltInDriversEnv | ServerSettingsService\n+> = Layer.unwrap(\n+ Effect.gen(function* () {\n+ const serverSettings = yield* ServerSettingsService;\n+ const initialSettings: ServerSettings | undefined = yield* serverSettings.getSettings.pipe(\n+ Effect.orElseSucceed(() => undefined),\n+ );\n+ const initialConfigMap =\n+ initialSettings === undefined\n+ ? ({} as ProviderInstanceConfigMap)\n+ : deriveProviderInstanceConfigMap(initialSettings);\n+\n+ const mutableLayer = ProviderInstanceRegistryMutableLayer({\n+ drivers: BUILT_IN_DRIVERS,\n+ configMap: initialConfigMap,\n+ });\n+\n+ return SettingsWatcherLive.pipe(Layer.provideMerge(mutableLayer));\n+ }),\n+) as Layer.Layer<ProviderInstanceRegistry, never, BuiltInDriversEnv | ServerSettingsService>;\ndiff --git a/apps/server/src/provider/Layers/ProviderInstanceRegistryLive.test.ts b/apps/server/src/provider/Layers/ProviderInstanceRegistryLive.test.ts\nnew file mode 100644\nindex 0000000000..2246a2ae47\n--- /dev/null\n+++ b/apps/server/src/provider/Layers/ProviderInstanceRegistryLive.test.ts\n@@ -0,0 +1,357 @@\n+/**\n+ * Multi-instance validation slices for `ProviderInstanceRegistryLive`.\n+ *\n+ * Two axes of the driver/registry refactor are exercised here:\n+ *\n+ * 1. **Same driver, many instances** — the "multi-instance codex slice"\n+ * describe block below configures two independent `codex` instances and\n+ * asserts each gets its own closures and identity. This is the\n+ * multi-codex capability the refactor exists to unlock.\n+ *\n+ * 2. **Many drivers, one registry** — the "all drivers slice" describe\n+ * block below configures one instance of every shipped driver\n+ * (`codex`, `claudeAgent`, `cursor`, `opencode`) in a single\n+ * `ProviderInstanceConfigMap` and asserts the registry boots them all\n+ * without cross-contamination. This proves the driver SPI is uniform\n+ * across every provider — any driver plugs into the registry through\n+ * the same `ProviderDriver` value contract.\n+ *\n+ * Every instance in these tests is configured with `enabled: false` so the\n+ * provider-status checks short-circuit to pending/disabled snapshots\n+ * without trying to spawn real `codex` / `claude` / `agent` / `opencode`\n+ * binaries. That keeps the assertions focused on registry routing\n+ * behaviour rather than the runtime details of each provider.\n+ */\n+import { describe, expect, it } from "@effect/vitest";\n+import * as NodeServices from "@effect/platform-node/NodeServices";\n+import {\n+ type ClaudeSettings,\n+ type CodexSettings,\n+ type CursorSettings,\n+ type OpenCodeSettings,\n+ ProviderDriverKind,\n+ type ProviderInstanceConfigMap,\n+ ProviderInstanceId,\n+} from "@t3tools/contracts";\n+import { Effect, Layer } from "effect";\n+\n+import { ServerConfig } from "../../config.ts";\n+import { ClaudeDriver } from "../Drivers/ClaudeDriver.ts";\n+import { CodexDriver } from "../Drivers/CodexDriver.ts";\n+import { CursorDriver } from "../Drivers/CursorDriver.ts";\n+import { OpenCodeDriver } from "../Drivers/OpenCodeDriver.ts";\n+import { OpenCodeRuntimeLive } from "../opencodeRuntime.ts";\n+import { NoOpProviderEventLoggers, ProviderEventLoggers } from "./ProviderEventLoggers.ts";\n+import { makeProviderInstanceRegistry } from "./ProviderInstanceRegistryLive.ts";\n+\n+const makeCodexConfig = (overrides: Partial<CodexSettings>): CodexSettings => ({\n+ enabled: false,\n+ binaryPath: "codex",\n+ homePath: "",\n+ shadowHomePath: "",\n+ customModels: [],\n+ ...overrides,\n+});\n+\n+const makeClaudeConfig = (overrides: Partial<ClaudeSettings>): ClaudeSettings => ({\n+ enabled: false,\n+ binaryPath: "claude",\n+ homePath: "",\n+ customModels: [],\n+ launchArgs: "",\n+ ...overrides,\n+});\n+\n+const makeCursorConfig = (overrides: Partial<CursorSettings>): CursorSettings => ({\n+ enabled: false,\n+ binaryPath: "agent",\n+ apiEndpoint: "",\n+ customModels: [],\n+ ...overrides,\n+});\n+\n+const makeOpenCodeConfig = (overrides: Partial<OpenCodeSettings>): OpenCodeSettings => ({\n+ enabled: false,\n+ binaryPath: "opencode",\n+ serverUrl: "",\n+ serverPassword: "",\n+ customModels: [],\n+ ...overrides,\n+});\n+\n+describe("ProviderInstanceRegistryLive — multi-instance codex slice", () => {\n+ // `ServerConfig.layerTest` needs `FileSystem` to materialize its scratch\n+ // directory. `Layer.merge` just unions requirements, so we have to push\n+ // `NodeServices.layer` through `Layer.provideMerge` to satisfy that\n+ // dependency while still surfacing NodeServices to the test body (the\n+ // codex driver\'s `create` yields `ChildProcessSpawner` directly).\n+ const testLayer = ServerConfig.layerTest(process.cwd(), {\n+ prefix: "provider-instance-registry-test",\n+ }).pipe(\n+ Layer.provideMerge(NodeServices.layer),\n+ Layer.provideMerge(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)),\n+ );\n+\n+ it.live("boots two independent codex instances from a ProviderInstanceConfigMap", () =>\n+ Effect.gen(function* () {\n+ const personalId = ProviderInstanceId.make("codex_personal");\n+ const workId = ProviderInstanceId.make("codex_work");\n+ const codexDriverKind = ProviderDriverKind.make("codex");\n+\n+ const configMap: ProviderInstanceConfigMap = {\n+ [personalId]: {\n+ driver: codexDriverKind,\n+ displayName: "Codex (personal)",\n+ enabled: false,\n+ config: makeCodexConfig({\n+ binaryPath: "/opt/codex-personal/bin/codex",\n+ homePath: "/home/julius/.codex_personal",\n+ customModels: ["personal-preview"],\n+ }),\n+ },\n+ [workId]: {\n+ driver: codexDriverKind,\n+ displayName: "Codex (work)",\n+ enabled: false,\n+ config: makeCodexConfig({\n+ binaryPath: "/opt/codex-work/bin/codex",\n+ homePath: "/home/julius/.codex",\n+ customModels: ["work-preview"],\n+ }),\n+ },\n+ };\n+\n+ const { registry } = yield* makeProviderInstanceRegistry({\n+ drivers: [CodexDriver],\n+ configMap,\n+ });\n+\n+ const instances = yield* registry.listInstances;\n+ expect(instances.map((instance) => instance.instanceId).toSorted()).toEqual(\n+ [personalId, workId].toSorted(),\n+ );\n+ expect(instances.every((instance) => instance.driverKind === codexDriverKind)).toBe(true);\n+ expect(instances.map((instance) => instance.displayName).toSorted()).toEqual(\n+ ["Codex (personal)", "Codex (work)"].toSorted(),\n+ );\n+\n+ // Each instance must be retrievable by id and carry its *own* closures.\n+ const personal = yield* registry.getInstance(personalId);\n+ const work = yield* registry.getInstance(workId);\n+ expect(personal).toBeDefined();\n+ expect(work).toBeDefined();\n+ expect(personal!.adapter).not.toBe(work!.adapter);\n+ expect(personal!.textGeneration).not.toBe(work!.textGeneration);\n+ expect(personal!.snapshot).not.toBe(work!.snapshot);\n+\n+ // Snapshots identify themselves by instanceId + driver — this is\n+ // what makes per-instance routing distinguishable downstream.\n+ const personalSnapshot = yield* personal!.snapshot.getSnapshot;\n+ expect(personalSnapshot.instanceId).toBe(personalId);\n+ expect(personalSnapshot.driver).toBe(codexDriverKind);\n+ expect(personalSnapshot.enabled).toBe(false);\n+ expect(personalSnapshot.continuation?.groupKey).toBe(\n+ "codex:home:/home/julius/.codex_personal",\n+ );\n+\n+ const workSnapshot = yield* work!.snapshot.getSnapshot;\n+ expect(workSnapshot.instanceId).toBe(workId);\n+ expect(workSnapshot.driver).toBe(codexDriverKind);\n+ expect(workSnapshot.enabled).toBe(false);\n+ expect(workSnapshot.continuation?.groupKey).toBe("codex:home:/home/julius/.codex");\n+\n+ // Nothing goes to the unavailable bucket — both drivers are registered.\n+ const unavailable = yield* registry.listUnavailable;\n+ expect(unavailable).toEqual([]);\n+ }).pipe(Effect.provide(testLayer)),\n+ );\n+\n+ it.live(\n+ "shadows instances whose driver is not registered in this build without failing boot",\n+ () =>\n+ Effect.gen(function* () {\n+ const codexId = ProviderInstanceId.make("codex_main");\n+ const ghostId = ProviderInstanceId.make("ghost_main");\n+\n+ const configMap: ProviderInstanceConfigMap = {\n+ [codexId]: {\n+ driver: ProviderDriverKind.make("codex"),\n+ enabled: false,\n+ config: makeCodexConfig({}),\n+ },\n+ [ghostId]: {\n+ driver: ProviderDriverKind.make("ghostDriver"),\n+ displayName: "A fork-only driver we don\'t ship",\n+ enabled: false,\n+ config: { arbitrary: "payload", preserved: true },\n+ },\n+ };\n+\n+ const { registry } = yield* makeProviderInstanceRegistry({\n+ drivers: [CodexDriver],\n+ configMap,\n+ });\n+\n+ const instances = yield* registry.listInstances;\n+ expect(instances).toHaveLength(1);\n+ expect(instances[0]!.instanceId).toBe(codexId);\n+\n+ const unavailable = yield* registry.listUnavailable;\n+ expect(unavailable).toHaveLength(1);\n+ const ghost = unavailable[0]!;\n+ expect(ghost.instanceId).toBe(ghostId);\n+ expect(ghost.driver).toBe("ghostDriver");\n+ expect(ghost.availability).toBe("unavailable");\n+ expect(ghost.unavailableReason).toMatch(/ghostDriver/);\n+ }).pipe(Effect.provide(testLayer)),\n+ );\n+});\n+\n+describe("ProviderInstanceRegistryLive — all drivers slice", () => {\n+ // All four drivers need `NodeServices` (ChildProcessSpawner + FileSystem +\n+ // Path). `OpenCodeDriver.create` additionally yields `OpenCodeRuntime`\n+ // at construction time, so we wire `OpenCodeRuntimeLive` into the stack.\n+ // `OpenCodeRuntimeLive` bundles its own `NetService.layer` via\n+ // `Layer.provide`, so the only external requirement it still exposes is\n+ // `ChildProcessSpawner` — resolved here by piping it through\n+ // `provideMerge(NodeServices.layer)`.\n+ //\n+ // The nested `provideMerge`s read bottom-up: `NodeServices.layer`\n+ // provides `OpenCodeRuntimeLive`\'s deps while keeping its own outputs\n+ // surfaced; that merged layer then provides `ServerConfig.layerTest`\'s\n+ // `FileSystem` dep while keeping everything else surfaced to the test.\n+ const infraLayer = OpenCodeRuntimeLive.pipe(Layer.provideMerge(NodeServices.layer));\n+ const testLayer = ServerConfig.layerTest(process.cwd(), {\n+ prefix: "provider-instance-registry-all-drivers-test",\n+ }).pipe(\n+ Layer.provideMerge(infraLayer),\n+ Layer.provideMerge(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)),\n+ );\n+\n+ it.live("boots one instance of every shipped driver from a single config map", () =>\n+ Effect.gen(function* () {\n+ const codexId = ProviderInstanceId.make("codex_default");\n+ const claudeId = ProviderInstanceId.make("claude_default");\n+ const cursorId = ProviderInstanceId.make("cursor_default");\n+ const openCodeId = ProviderInstanceId.make("opencode_default");\n+\n+ const codexDriverKind = ProviderDriverKind.make("codex");\n+ const claudeDriverKind = ProviderDriverKind.make("claudeAgent");\n+ const cursorDriverKind = ProviderDriverKind.make("cursor");\n+ const openCodeDriverKind = ProviderDriverKind.make("opencode");\n+\n+ const configMap: ProviderInstanceConfigMap = {\n+ [codexId]: {\n+ driver: codexDriverKind,\n+ displayName: "Codex",\n+ enabled: false,\n+ config: makeCodexConfig({ homePath: "/home/julius/.codex" }),\n+ },\n+ [claudeId]: {\n+ driver: claudeDriverKind,\n+ displayName: "Claude",\n+ enabled: false,\n+ config: makeClaudeConfig({\n+ homePath: "/home/julius/.claude-work",\n+ launchArgs: "--verbose",\n+ }),\n+ },\n+ [cursorId]: {\n+ driver: cursorDriverKind,\n+ displayName: "Cursor",\n+ enabled: false,\n+ config: makeCursorConfig({}),\n+ },\n+ [openCodeId]: {\n+ driver: openCodeDriverKind,\n+ displayName: "OpenCode",\n+ enabled: false,\n+ config: makeOpenCodeConfig({}),\n+ },\n+ };\n+\n+ const { registry } = yield* makeProviderInstanceRegistry({\n+ drivers: [CodexDriver, ClaudeDriver, CursorDriver, OpenCodeDriver],\n+ configMap,\n+ });\n+\n+ // Every configured instance must materialize — none downgraded to a\n+ // shadow snapshot, because every driver in the map is registered.\n+ const unavailable = yield* registry.listUnavailable;\n+ expect(unavailable).toEqual([]);\n+\n+ const instances = yield* registry.listInstances;\n+ expect(instances).toHaveLength(4);\n+ expect(instances.map((instance) => instance.instanceId).toSorted()).toEqual(\n+ [codexId, claudeId, cursorId, openCodeId].toSorted(),\n+ );\n+\n+ // Instance lookup by id resolves each instance to its own bundle —\n+ // this is how rest-of-server routes turn/session calls in the new\n+ // model. Each driver\'s bundle carries its advertised `driverKind`.\n+ const codex = yield* registry.getInstance(codexId);\n+ const claude = yield* registry.getInstance(claudeId);\n+ const cursor = yield* registry.getInstance(cursorId);\n+ const openCode = yield* registry.getInstance(openCodeId);\n+ expect(codex?.driverKind).toBe(codexDriverKind);\n+ expect(claude?.driverKind).toBe(claudeDriverKind);\n+ expect(cursor?.driverKind).toBe(cursorDriverKind);\n+ expect(openCode?.driverKind).toBe(openCodeDriverKind);\n+ expect(codex?.displayName).toBe("Codex");\n+ expect(claude?.displayName).toBe("Claude");\n+ expect(cursor?.displayName).toBe("Cursor");\n+ expect(openCode?.displayName).toBe("OpenCode");\n+\n+ // Every instance owns its own set of closures — no sharing across\n+ // drivers. `adapter` / `textGeneration` / `snapshot` are all\n+ // distinct references even when two instances happen to share a\n+ // trait (e.g. Cursor + others all use a stub-or-real\n+ // `textGeneration`; they must still be different object values).\n+ const adapters = [codex!.adapter, claude!.adapter, cursor!.adapter, openCode!.adapter];\n+ expect(new Set(adapters).size).toBe(adapters.length);\n+ const textGenerations = [\n+ codex!.textGeneration,\n+ claude!.textGeneration,\n+ cursor!.textGeneration,\n+ openCode!.textGeneration,\n+ ];\n+ expect(new Set(textGenerations).size).toBe(textGenerations.length);\n+ const snapshots = [codex!.snapshot, claude!.snapshot, cursor!.snapshot, openCode!.snapshot];\n+ expect(new Set(snapshots).size).toBe(snapshots.length);\n+\n+ // Snapshots identify themselves by `instanceId` + `driver` so\n+ // downstream aggregation in `ProviderRegistry` can tell instances\n+ // apart even when two share a driver. With `enabled: false`, the\n+ // check short-circuits and we get a disabled/pending snapshot back\n+ // — that\'s enough signal to validate the stamping wrapper without\n+ // spawning real binaries.\n+ const codexSnapshot = yield* codex!.snapshot.getSnapshot;\n+ expect(codexSnapshot.instanceId).toBe(codexId);\n+ expect(codexSnapshot.driver).toBe(codexDriverKind);\n+ expect(codexSnapshot.enabled).toBe(false);\n+ expect(codexSnapshot.continuation?.groupKey).toBe("codex:home:/home/julius/.codex");\n+\n+ const claudeSnapshot = yield* claude!.snapshot.getSnapshot;\n+ expect(claudeSnapshot.instanceId).toBe(claudeId);\n+ expect(claudeSnapshot.driver).toBe(claudeDriverKind);\n+ expect(claudeSnapshot.enabled).toBe(false);\n+ expect(claudeSnapshot.continuation?.groupKey).toBe("claude:home:/home/julius/.claude-work");\n+\n+ const cursorSnapshot = yield* cursor!.snapshot.getSnapshot;\n+ expect(cursorSnapshot.instanceId).toBe(cursorId);\n+ expect(cursorSnapshot.driver).toBe(cursorDriverKind);\n+ expect(cursorSnapshot.enabled).toBe(false);\n+ expect(cursorSnapshot.continuation?.groupKey).toBe(\n+ `${cursorDriverKind}:instance:${cursorId}`,\n+ );\n+\n+ const openCodeSnapshot = yield* openCode!.snapshot.getSnapshot;\n+ expect(openCodeSnapshot.instanceId).toBe(openCodeId);\n+ expect(openCodeSnapshot.driver).toBe(openCodeDriverKind);\n+ expect(openCodeSnapshot.enabled).toBe(false);\n+ expect(openCodeSnapshot.continuation?.groupKey).toBe(\n+ `${openCodeDriverKind}:instance:${openCodeId}`,\n+ );\n+ }).pipe(Effect.provide(testLayer)),\n+ );\n+});\ndiff --git a/apps/server/src/provider/Layers/ProviderInstanceRegistryLive.ts b/apps/server/src/provider/Layers/ProviderInstanceRegistryLive.ts\nnew file mode 100644\nindex 0000000000..63f687f55b\n--- /dev/null\n+++ b/apps/server/src/provider/Layers/ProviderInstanceRegistryLive.ts\n@@ -0,0 +1,434 @@\n+/**\n+ * ProviderInstanceRegistryLive — runtime implementation of\n+ * `ProviderInstanceRegistry` plus its sibling mutator.\n+ *\n+ * Materializes every entry in a `ProviderInstanceConfigMap`:\n+ *\n+ * - When the entry\'s `driver` matches a registered driver, the registry\n+ * decodes the opaque `config` envelope through `driver.configSchema`\n+ * and calls `driver.create()` inside a fresh child scope. The\n+ * resulting `ProviderInstance` is stored keyed by instance id,\n+ * alongside its scope so the entry can be torn down independently.\n+ * - When the entry\'s `driver` is unknown to this build (fork, rollback,\n+ * in-flight PR branch), the registry emits an `"unavailable"` shadow\n+ * `ServerProvider` snapshot instead of failing. This is what makes\n+ * downgrades and fork-hopping safe per the\n+ * `forward/backward compatibility invariant` in\n+ * `packages/contracts/src/providerInstance.ts`.\n+ * - When the entry\'s config fails schema decode, the registry logs and\n+ * emits a shadow snapshot with the schema detail — same bucket as an\n+ * unknown driver.\n+ *\n+ * Unlike the pre-Slice-D layer, the registry now holds mutable state\n+ * (`Ref`s + `PubSub`) and exposes an internal mutator\n+ * (`ProviderInstanceRegistryMutator`) whose `reconcile` method diffs a\n+ * fresh config map against the live state, tearing down removed instances\n+ * and building new ones without disturbing unaffected instances.\n+ *\n+ * Every live instance runs inside its own child `Scope`. The registry\'s\n+ * own scope owns all child scopes via finalizers, so closing the registry\n+ * tears every instance down in reverse order; closing a single instance\n+ * (via `reconcile` removing it) leaves the rest untouched.\n+ *\n+ * @module provider/Layers/ProviderInstanceRegistryLive\n+ */\n+import {\n+ defaultInstanceIdForDriver,\n+ ProviderInstanceId,\n+ type ProviderInstanceConfig,\n+ type ProviderInstanceConfigMap,\n+ type ProviderDriverKind,\n+ type ServerProvider,\n+} from "@t3tools/contracts";\n+import { Context, Effect, Equal, Exit, Layer, PubSub, Ref, Schema, Scope, Stream } from "effect";\n+\n+import { buildUnavailableProviderSnapshot } from "../unavailableProviderSnapshot.ts";\n+import {\n+ ProviderInstanceRegistry,\n+ type ProviderInstanceRegistryShape,\n+} from "../Services/ProviderInstanceRegistry.ts";\n+import {\n+ ProviderInstanceRegistryMutator,\n+ type ProviderInstanceRegistryMutatorShape,\n+} from "../Services/ProviderInstanceRegistryMutator.ts";\n+import type { AnyProviderDriver, ProviderInstance } from "../ProviderDriver.ts";\n+\n+/**\n+ * Live registry entry: the materialized `ProviderInstance` + the fresh\n+ * child scope its `create` effect ran in + the original `entry` envelope\n+ * so `reconcile` can cheaply detect "no-op" updates.\n+ */\n+interface LiveEntry {\n+ readonly instance: ProviderInstance;\n+ readonly scope: Scope.Closeable;\n+ readonly entry: ProviderInstanceConfig;\n+}\n+\n+/**\n+ * Internal state shared between the public registry service and the\n+ * mutator service. Both services are thin shells around these refs.\n+ */\n+interface RegistryState {\n+ readonly entries: Ref.Ref<ReadonlyMap<ProviderInstanceId, LiveEntry>>;\n+ readonly unavailable: Ref.Ref<ReadonlyMap<ProviderInstanceId, ServerProvider>>;\n+ readonly changes: PubSub.PubSub<void>;\n+}\n+\n+/**\n+ * Structural equality on `ProviderInstanceConfig` envelopes. Used by\n+ * `reconcile` to skip rebuilds when settings arrive unchanged. Config\n+ * payloads are opaque `unknown` at the envelope layer; `Equal.equals`\n+ * falls back to structural equality for plain records, which matches how\n+ * the schema decode output is constructed.\n+ */\n+const entryEqual = (a: ProviderInstanceConfig, b: ProviderInstanceConfig): boolean =>\n+ Equal.equals(a, b);\n+\n+const decodedConfigEnabled = (config: unknown): boolean | undefined => {\n+ if (!config || typeof config !== "object" || globalThis.Array.isArray(config)) {\n+ return undefined;\n+ }\n+ const enabled = (config as { readonly enabled?: unknown }).enabled;\n+ return typeof enabled === "boolean" ? enabled : undefined;\n+};\n+\n+/**\n+ * Build one live entry from a raw config envelope. Returns either a\n+ * `LiveEntry` plus undefined unavailable shadow, or a shadow snapshot and\n+ * undefined entry — callers dispatch to the appropriate Ref bucket.\n+ */\n+const buildEntry = <R>(input: {\n+ readonly driversById: ReadonlyMap<ProviderDriverKind, AnyProviderDriver<R>>;\n+ readonly parentScope: Scope.Scope;\n+ readonly instanceId: ProviderInstanceId;\n+ readonly rawInstanceId: string;\n+ readonly entry: ProviderInstanceConfig;\n+}): Effect.Effect<\n+ | { readonly kind: "live"; readonly live: LiveEntry }\n+ | { readonly kind: "unavailable"; readonly snapshot: ServerProvider },\n+ never,\n+ R\n+> =>\n+ Effect.gen(function* () {\n+ const { driversById, parentScope, instanceId, rawInstanceId, entry } = input;\n+ const driver = driversById.get(entry.driver);\n+ if (!driver) {\n+ return {\n+ kind: "unavailable" as const,\n+ snapshot: buildUnavailableProviderSnapshot({\n+ driverKind: entry.driver,\n+ instanceId,\n+ displayName: entry.displayName,\n+ accentColor: entry.accentColor,\n+ reason: `Driver \'${entry.driver}\' is not registered in this build.`,\n+ }),\n+ };\n+ }\n+\n+ const decoder = Schema.decodeUnknownEffect(driver.configSchema);\n+ const decodeResult = yield* decoder(entry.config ?? driver.defaultConfig()).pipe(Effect.result);\n+ if (decodeResult._tag === "Failure") {\n+ const issue = decodeResult.failure;\n+ const detail = issue.message ?? String(issue);\n+ yield* Effect.logError("Failed to decode provider instance config", {\n+ instanceId: rawInstanceId,\n+ driver: entry.driver,\n+ detail,\n+ });\n+ return {\n+ kind: "unavailable" as const,\n+ snapshot: buildUnavailableProviderSnapshot({\n+ driverKind: entry.driver,\n+ instanceId,\n+ displayName: entry.displayName,\n+ accentColor: entry.accentColor,\n+ reason: `Invalid config for instance \'${rawInstanceId}\': ${detail}`,\n+ }),\n+ };\n+ }\n+\n+ const typedConfig = decodeResult.success;\n+ const childScope = yield* Scope.make();\n+ // Attach the child scope to the registry\'s parent scope: if the\n+ // registry scope closes, each surviving instance\'s child scope is\n+ // closed through this finalizer. `reconcile` manually closes the\n+ // child scope on remove/replace; subsequent close via the parent\'s\n+ // finalizer is a no-op because `Scope.close` is idempotent.\n+ yield* Scope.addFinalizer(parentScope, Scope.close(childScope, Exit.void).pipe(Effect.ignore));\n+\n+ const createResult = yield* driver\n+ .create({\n+ instanceId,\n+ displayName: entry.displayName,\n+ accentColor: entry.accentColor,\n+ environment: entry.environment ?? [],\n+ enabled: entry.enabled ?? decodedConfigEnabled(typedConfig) ?? true,\n+ config: typedConfig,\n+ })\n+ .pipe(Effect.provideService(Scope.Scope, childScope), Effect.result);\n+ if (createResult._tag === "Failure") {\n+ yield* Effect.logError("Failed to create provider instance", {\n+ instanceId: rawInstanceId,\n+ driver: entry.driver,\n+ detail: createResult.failure.detail,\n+ });\n+ yield* Scope.close(childScope, Exit.void).pipe(Effect.ignore);\n+ return {\n+ kind: "unavailable" as const,\n+ snapshot: buildUnavailableProviderSnapshot({\n+ driverKind: entry.driver,\n+ instanceId,\n+ displayName: entry.displayName,\n+ accentColor: entry.accentColor,\n+ reason: `Driver \'${entry.driver}\' failed to create instance: ${createResult.failure.detail}`,\n+ }),\n+ };\n+ }\n+\n+ return {\n+ kind: "live" as const,\n+ live: {\n+ instance: createResult.success,\n+ scope: childScope,\n+ entry,\n+ },\n+ };\n+ });\n+\n+/**\n+ * Reconcile-only implementation of the mutator. Exposed to the hydration\n+ * layer; never called directly by the rest of the server.\n+ */\n+const makeReconcile = <R>(input: {\n+ readonly state: RegistryState;\n+ readonly driversById: ReadonlyMap<ProviderDriverKind, AnyProviderDriver<R>>;\n+ readonly parentScope: Scope.Scope;\n+}): ((configMap: ProviderInstanceConfigMap) => Effect.Effect<void, never, R>) => {\n+ const { state, driversById, parentScope } = input;\n+ return (configMap: ProviderInstanceConfigMap) =>\n+ Effect.gen(function* () {\n+ const previousEntries = yield* Ref.get(state.entries);\n+ const previousUnavailable = yield* Ref.get(state.unavailable);\n+ const nextRaw = Object.entries(configMap);\n+ const nextKeys = new Set<ProviderInstanceId>(\n+ nextRaw.map(([raw]) => ProviderInstanceId.make(raw)),\n+ );\n+\n+ // 1. Close scopes for instances that disappeared or whose config\n+ // changed. Do this BEFORE creating replacements so ids map 1-to-1\n+ // to live scopes at all times.\n+ const removedIds: Array<ProviderInstanceId> = [];\n+ const replacedIds = new Set<ProviderInstanceId>();\n+ for (const [instanceId, live] of previousEntries) {\n+ if (!nextKeys.has(instanceId)) {\n+ removedIds.push(instanceId);\n+ continue;\n+ }\n+ const nextEntry = configMap[instanceId];\n+ if (nextEntry !== undefined && !entryEqual(live.entry, nextEntry)) {\n+ replacedIds.add(instanceId);\n+ }\n+ }\n+ for (const id of [...removedIds, ...replacedIds]) {\n+ const live = previousEntries.get(id);\n+ if (live) {\n+ yield* Scope.close(live.scope, Exit.void).pipe(Effect.ignore);\n+ }\n+ }\n+\n+ // 2. Build additions and replacements. Walk `nextRaw` so the final\n+ // entry order follows settings-author order.\n+ const builtEntries = new Map<ProviderInstanceId, LiveEntry>();\n+ const builtUnavailable = new Map<ProviderInstanceId, ServerProvider>();\n+ let orderChanged = false;\n+ const previousOrder = [...previousEntries.keys()];\n+ const nextOrder: Array<ProviderInstanceId> = [];\n+\n+ for (const [rawInstanceId, entry] of nextRaw) {\n+ const instanceId = ProviderInstanceId.make(rawInstanceId);\n+ nextOrder.push(instanceId);\n+\n+ const existing = previousEntries.get(instanceId);\n+ if (existing !== undefined && !replacedIds.has(instanceId)) {\n+ // No-op update: keep the existing live entry and scope.\n+ builtEntries.set(instanceId, existing);\n+ continue;\n+ }\n+\n+ const result = yield* buildEntry({\n+ driversById,\n+ parentScope,\n+ instanceId,\n+ rawInstanceId,\n+ entry,\n+ });\n+ if (result.kind === "live") {\n+ builtEntries.set(instanceId, result.live);\n+ } else {\n+ builtUnavailable.set(instanceId, result.snapshot);\n+ }\n+ }\n+\n+ if (previousOrder.length === nextOrder.length) {\n+ for (let i = 0; i < previousOrder.length; i++) {\n+ if (previousOrder[i] !== nextOrder[i]) {\n+ orderChanged = true;\n+ break;\n+ }\n+ }\n+ } else {\n+ orderChanged = true;\n+ }\n+\n+ const entriesChanged =\n+ orderChanged ||\n+ removedIds.length > 0 ||\n+ replacedIds.size > 0 ||\n+ builtEntries.size !== previousEntries.size;\n+ const unavailableChanged =\n+ builtUnavailable.size !== previousUnavailable.size ||\n+ [...builtUnavailable].some(([id, snapshot]) => {\n+ const prev = previousUnavailable.get(id);\n+ return prev === undefined || !Equal.equals(prev, snapshot);\n+ }) ||\n+ [...previousUnavailable].some(([id]) => !builtUnavailable.has(id));\n+\n+ yield* Ref.set(state.entries, builtEntries);\n+ yield* Ref.set(state.unavailable, builtUnavailable);\n+\n+ if (entriesChanged || unavailableChanged) {\n+ yield* PubSub.publish(state.changes, undefined);\n+ }\n+ });\n+};\n+\n+/**\n+ * Build the registry\'s runtime state from a concrete configMap. Returns a\n+ * record containing:\n+ *\n+ * - `registry`: the read-only `ProviderInstanceRegistryShape` to expose\n+ * under `ProviderInstanceRegistry`.\n+ * - `mutator`: the `ProviderInstanceRegistryMutatorShape` to expose\n+ * under `ProviderInstanceRegistryMutator`.\n+ * - `reconcile`: the raw reconcile function, provided for convenience so\n+ * boot-time layers can hydrate an initial map before publishing the\n+ * services.\n+ *\n+ * The scope that this effect runs in owns every per-instance child scope\n+ * created during `reconcile`. Closing that scope closes every live\n+ * instance.\n+ */\n+export const makeProviderInstanceRegistry = <R>(input: {\n+ readonly drivers: ReadonlyArray<AnyProviderDriver<R>>;\n+ readonly configMap: ProviderInstanceConfigMap;\n+}): Effect.Effect<\n+ {\n+ readonly registry: ProviderInstanceRegistryShape;\n+ readonly mutator: ProviderInstanceRegistryMutatorShape;\n+ },\n+ never,\n+ R | Scope.Scope\n+> =>\n+ Effect.gen(function* () {\n+ const driversById = new Map<ProviderDriverKind, AnyProviderDriver<R>>(\n+ input.drivers.map((driver) => [driver.driverKind, driver]),\n+ );\n+\n+ // Capture the enclosing scope so per-instance child scopes can be\n+ // attached to it at `reconcile` time. Without this, `reconcile`\n+ // called later (e.g. from the hydration layer) would attach child\n+ // scopes to the *caller\'s* scope instead of the registry\'s.\n+ const parentScope = yield* Scope.Scope;\n+\n+ // Capture the driver R context at construction time so `reconcile`\n+ // can be invoked later without re-providing driver dependencies.\n+ // The service tag\'s declared `reconcile: Effect<void>` hides R from\n+ // consumers — we materialize that here.\n+ const driverContext = yield* Effect.context<R>();\n+\n+ const entries = yield* Ref.make<ReadonlyMap<ProviderInstanceId, LiveEntry>>(new Map());\n+ const unavailable = yield* Ref.make<ReadonlyMap<ProviderInstanceId, ServerProvider>>(new Map());\n+ const changes = yield* PubSub.unbounded<void>();\n+ yield* Effect.addFinalizer(() => PubSub.shutdown(changes));\n+\n+ const state: RegistryState = { entries, unavailable, changes };\n+ const reconcileWithR = makeReconcile({ state, driversById, parentScope });\n+ const reconcile: ProviderInstanceRegistryMutatorShape["reconcile"] = (configMap) =>\n+ reconcileWithR(configMap).pipe(Effect.provideContext(driverContext));\n+\n+ // Hydrate the initial configMap synchronously so callers can read\n+ // `listInstances` immediately after this effect completes.\n+ yield* reconcile(input.configMap);\n+\n+ const registry: ProviderInstanceRegistryShape = {\n+ getInstance: (id) => Ref.get(entries).pipe(Effect.map((map) => map.get(id)?.instance)),\n+ listInstances: Ref.get(entries).pipe(\n+ Effect.map(\n+ (map) =>\n+ Array.from(map.values(), (live) => live.instance) as ReadonlyArray<ProviderInstance>,\n+ ),\n+ ),\n+ listUnavailable: Ref.get(unavailable).pipe(\n+ Effect.map((map) => Array.from(map.values()) as ReadonlyArray<ServerProvider>),\n+ ),\n+ // Getters: each read constructs a fresh Stream / Effect descriptor\n+ // so multiple consumers don\'t share a single already-started\n+ // Channel or subscription. Matches the pattern `ProviderRegistry`\n+ // uses for its own `streamChanges`.\n+ get streamChanges() {\n+ return Stream.fromPubSub(changes);\n+ },\n+ // Synchronous subscribe — callers that need to consume changes\n+ // from a forked fibre must acquire the subscription in their own\n+ // fibre first (via `yield* registry.subscribeChanges`) and only\n+ // then fork a consumer loop on `Stream.fromSubscription(...)` /\n+ // `PubSub.take(...)`. See the shape docs for the race this avoids.\n+ get subscribeChanges() {\n+ return PubSub.subscribe(changes);\n+ },\n+ };\n+\n+ const mutator: ProviderInstanceRegistryMutatorShape = { reconcile };\n+\n+ return { registry, mutator };\n+ });\n+\n+/**\n+ * Assemble a `ProviderInstanceRegistry` Layer bound to a fixed set of\n+ * drivers and a pre-resolved `ProviderInstanceConfigMap`. Used by tests\n+ * that want explicit control over the registry\'s source-of-truth without\n+ * wiring up the settings watcher.\n+ *\n+ * Only exposes the public registry tag — hot-reload consumers should use\n+ * `ProviderInstanceRegistryMutableLayer` (below) or the hydration layer.\n+ */\n+export const ProviderInstanceRegistryLayer = <R>(input: {\n+ readonly drivers: ReadonlyArray<AnyProviderDriver<R>>;\n+ readonly configMap: ProviderInstanceConfigMap;\n+}): Layer.Layer<ProviderInstanceRegistry, never, R> =>\n+ Layer.effect(\n+ ProviderInstanceRegistry,\n+ makeProviderInstanceRegistry(input).pipe(Effect.map((built) => built.registry)),\n+ ) as Layer.Layer<ProviderInstanceRegistry, never, R>;\n+\n+/**\n+ * Layer variant that also exposes the mutator tag. Consumed by\n+ * `ProviderInstanceRegistryHydrationLive` to reconcile on settings\n+ * changes. Tests that exercise the mutator directly can pair this Layer\n+ * with a test-local `ServerSettingsService`.\n+ */\n+export const ProviderInstanceRegistryMutableLayer = <R>(input: {\n+ readonly drivers: ReadonlyArray<AnyProviderDriver<R>>;\n+ readonly configMap: ProviderInstanceConfigMap;\n+}): Layer.Layer<ProviderInstanceRegistry | ProviderInstanceRegistryMutator, never, R> =>\n+ Layer.effectContext(\n+ makeProviderInstanceRegistry(input).pipe(\n+ Effect.map(({ registry, mutator }) =>\n+ Context.make(ProviderInstanceRegistry, registry).pipe(\n+ Context.add(ProviderInstanceRegistryMutator, mutator),\n+ ),\n+ ),\n+ ),\n+ ) as Layer.Layer<ProviderInstanceRegistry | ProviderInstanceRegistryMutator, never, R>;\n+\n+export { defaultInstanceIdForDriver };\ndiff --git a/apps/server/src/provider/Layers/ProviderRegistry.test.ts b/apps/server/src/provider/Layers/ProviderRegistry.test.ts\nindex 1df9da6774..75f9c42936 100644\n--- a/apps/server/src/provider/Layers/ProviderRegistry.test.ts\n+++ b/apps/server/src/provider/Layers/ProviderRegistry.test.ts\n@@ -1,11 +1,16 @@\n import * as NodeServices from "@effect/platform-node/NodeServices";\n-import { describe, it, assert } from "@effect/vitest";\n+import { describe, it, assert, live } from "@effect/vitest";\n import { Effect, Exit, Layer, PubSub, Ref, Schema, Scope, Sink, Stream } from "effect";\n import * as CodexErrors from "effect-codex-app-server/errors";\n import {\n+ ClaudeSettings,\n+ CodexSettings,\n DEFAULT_SERVER_SETTINGS,\n+ ProviderDriverKind,\n+ ProviderInstanceId,\n ServerSettings,\n type ServerProvider,\n+ type ServerProviderSlashCommand,\n type ServerSettings as ContractServerSettings,\n } from "@t3tools/contracts";\n import * as PlatformError from "effect/PlatformError";\n@@ -14,7 +19,10 @@ import { deepMerge } from "@t3tools/shared/Struct";\n import { createModelCapabilities } from "@t3tools/shared/model";\n \n import { checkCodexProviderStatus, type CodexAppServerProviderSnapshot } from "./CodexProvider.ts";\n-import { checkClaudeProviderStatus, parseClaudeAuthStatusFromOutput } from "./ClaudeProvider.ts";\n+import { checkClaudeProviderStatus } from "./ClaudeProvider.ts";\n+import { OpenCodeRuntimeLive } from "../opencodeRuntime.ts";\n+import { NoOpProviderEventLoggers, ProviderEventLoggers } from "./ProviderEventLoggers.ts";\n+import { ProviderInstanceRegistryHydrationLive } from "./ProviderInstanceRegistryHydration.ts";\n import {\n haveProvidersChanged,\n mergeProviderSnapshot,\n@@ -22,8 +30,16 @@ import {\n } from "./ProviderRegistry.ts";\n import { ServerConfig } from "../../config.ts";\n import { ServerSettingsService, type ServerSettingsShape } from "../../serverSettings.ts";\n+import type { ProviderInstance } from "../ProviderDriver.ts";\n+import { ProviderInstanceRegistry } from "../Services/ProviderInstanceRegistry.ts";\n import { ProviderRegistry } from "../Services/ProviderRegistry.ts";\n \n+const defaultClaudeSettings: ClaudeSettings = Schema.decodeSync(ClaudeSettings)({});\n+const defaultCodexSettings: CodexSettings = Schema.decodeSync(CodexSettings)({});\n+const disabledCodexSettings: CodexSettings = Schema.decodeSync(CodexSettings)({\n+ enabled: false,\n+});\n+\n process.env.T3CODE_CURSOR_ENABLED = "1";\n \n // ── Test helpers ────────────────────────────────────────────────────\n@@ -54,6 +70,27 @@ function booleanDescriptor(id: string, label: string) {\n };\n }\n \n+type TestClaudeCapabilities = {\n+ readonly email: string | undefined;\n+ readonly subscriptionType: string | undefined;\n+ readonly tokenSource: string | undefined;\n+ readonly slashCommands: ReadonlyArray<ServerProviderSlashCommand>;\n+};\n+\n+function claudeCapabilities(overrides: Partial<TestClaudeCapabilities> = {}) {\n+ return () =>\n+ Effect.succeed({\n+ email: undefined,\n+ subscriptionType: undefined,\n+ tokenSource: undefined,\n+ slashCommands: [],\n+ ...overrides,\n+ });\n+}\n+\n+const noClaudeCapabilities = () =>\n+ Effect.sync(() => undefined as TestClaudeCapabilities | undefined);\n+\n function mockHandle(result: { stdout: string; stderr: string; code: number }) {\n return ChildProcessSpawner.makeHandle({\n pid: ChildProcessSpawner.ProcessId(1),\n@@ -71,7 +108,11 @@ function mockHandle(result: { stdout: string; stderr: string; code: number }) {\n }\n \n function mockSpawnerLayer(\n- handler: (args: ReadonlyArray<string>) => { stdout: string; stderr: string; code: number },\n+ handler: (args: ReadonlyArray<string>) => {\n+ stdout: string;\n+ stderr: string;\n+ code: number;\n+ },\n ) {\n return Layer.succeed(\n ChildProcessSpawner.ChildProcessSpawner,\n@@ -82,6 +123,33 @@ function mockSpawnerLayer(\n );\n }\n \n+function recordingMockSpawnerLayer(\n+ handler: (args: ReadonlyArray<string>) => {\n+ stdout: string;\n+ stderr: string;\n+ code: number;\n+ },\n+) {\n+ const commands: Array<{\n+ readonly args: ReadonlyArray<string>;\n+ readonly env: NodeJS.ProcessEnv | undefined;\n+ }> = [];\n+ const layer = Layer.succeed(\n+ ChildProcessSpawner.ChildProcessSpawner,\n+ ChildProcessSpawner.make((command) => {\n+ const cmd = command as unknown as {\n+ args: ReadonlyArray<string>;\n+ options?: {\n+ readonly env?: NodeJS.ProcessEnv;\n+ };\n+ };\n+ commands.push({ args: cmd.args, env: cmd.options?.env });\n+ return Effect.succeed(mockHandle(handler(cmd.args)));\n+ }),\n+ );\n+ return { layer, commands };\n+}\n+\n function mockCommandSpawnerLayer(\n handler: (\n command: string,\n@@ -91,7 +159,10 @@ function mockCommandSpawnerLayer(\n return Layer.succeed(\n ChildProcessSpawner.ChildProcessSpawner,\n ChildProcessSpawner.make((command) => {\n- const cmd = command as unknown as { command: string; args: ReadonlyArray<string> };\n+ const cmd = command as unknown as {\n+ command: string;\n+ args: ReadonlyArray<string>;\n+ };\n return Effect.succeed(mockHandle(handler(cmd.command, cmd.args)));\n }),\n );\n@@ -181,7 +252,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(\n describe("checkCodexProviderStatus", () => {\n it.effect("uses the app-server account and model list for provider status", () =>\n Effect.gen(function* () {\n- const status = yield* checkCodexProviderStatus(() =>\n+ const status = yield* checkCodexProviderStatus(defaultCodexSettings, () =>\n Effect.succeed(\n makeCodexProbeSnapshot({\n skills: [\n@@ -196,14 +267,13 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(\n }),\n ),\n );\n-\n- assert.strictEqual(status.provider, "codex");\n assert.strictEqual(status.status, "ready");\n assert.strictEqual(status.installed, true);\n assert.strictEqual(status.version, "1.0.0");\n assert.strictEqual(status.auth.status, "authenticated");\n assert.strictEqual(status.auth.type, "chatgpt");\n assert.strictEqual(status.auth.label, "ChatGPT Pro 20x Subscription");\n+ assert.strictEqual(status.auth.email, "test@example.com");\n assert.deepStrictEqual(status.models, [\n {\n slug: "gpt-live-codex",\n@@ -226,7 +296,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(\n \n it.effect("returns unauthenticated when app-server requires OpenAI auth", () =>\n Effect.gen(function* () {\n- const status = yield* checkCodexProviderStatus(() =>\n+ const status = yield* checkCodexProviderStatus(defaultCodexSettings, () =>\n Effect.succeed(\n makeCodexProbeSnapshot({\n account: {\n@@ -250,7 +320,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(\n "returns ready with unknown auth when app-server does not require OpenAI auth",\n () =>\n Effect.gen(function* () {\n- const status = yield* checkCodexProviderStatus(() =>\n+ const status = yield* checkCodexProviderStatus(defaultCodexSettings, () =>\n Effect.succeed(\n makeCodexProbeSnapshot({\n account: {\n@@ -268,7 +338,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(\n \n it.effect("returns an api key label for codex api key auth", () =>\n Effect.gen(function* () {\n- const status = yield* checkCodexProviderStatus(() =>\n+ const status = yield* checkCodexProviderStatus(defaultCodexSettings, () =>\n Effect.succeed(\n makeCodexProbeSnapshot({\n account: {\n@@ -288,7 +358,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(\n \n it.effect("returns unavailable when codex is missing", () =>\n Effect.gen(function* () {\n- const status = yield* checkCodexProviderStatus(() =>\n+ const status = yield* checkCodexProviderStatus(defaultCodexSettings, () =>\n Effect.fail(\n new CodexErrors.CodexAppServerSpawnError({\n command: "codex app-server",\n@@ -296,7 +366,6 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(\n }),\n ),\n );\n- assert.strictEqual(status.provider, "codex");\n assert.strictEqual(status.status, "error");\n assert.strictEqual(status.installed, false);\n assert.strictEqual(status.auth.status, "unknown");\n@@ -312,7 +381,8 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(\n it("treats equal provider snapshots as unchanged", () => {\n const providers = [\n {\n- provider: "codex",\n+ instanceId: ProviderInstanceId.make("codex"),\n+ driver: ProviderDriverKind.make("codex"),\n status: "ready",\n enabled: true,\n installed: true,\n@@ -324,7 +394,8 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(\n skills: [],\n },\n {\n- provider: "claudeAgent",\n+ instanceId: ProviderInstanceId.make("claudeAgent"),\n+ driver: ProviderDriverKind.make("claudeAgent"),\n status: "warning",\n enabled: true,\n installed: true,\n@@ -342,7 +413,8 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(\n \n it("preserves previously discovered provider models when a refresh returns none", () => {\n const previousProvider = {\n- provider: "cursor",\n+ instanceId: ProviderInstanceId.make("cursor"),\n+ driver: ProviderDriverKind.make("cursor"),\n status: "ready",\n enabled: true,\n installed: true,\n@@ -381,7 +453,8 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(\n \n it("fills missing capabilities from the previous provider snapshot", () => {\n const previousProvider = {\n- provider: "cursor",\n+ instanceId: ProviderInstanceId.make("cursor"),\n+ driver: ProviderDriverKind.make("cursor"),\n status: "ready",\n enabled: true,\n installed: true,\n@@ -427,41 +500,345 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(\n ]);\n });\n \n- it.effect("probes enabled providers in the background during registry startup", () =>\n+ it.effect("returns the cached provider list when a manual refresh fails", () =>\n+ Effect.gen(function* () {\n+ const codexDriver = ProviderDriverKind.make("codex");\n+ const codexInstanceId = ProviderInstanceId.make("codex");\n+ const cachedProvider = {\n+ instanceId: codexInstanceId,\n+ driver: codexDriver,\n+ status: "ready",\n+ enabled: true,\n+ installed: true,\n+ auth: { status: "authenticated" },\n+ checkedAt: "2026-04-29T10:00:00.000Z",\n+ version: "1.0.0",\n+ models: [],\n+ slashCommands: [],\n+ skills: [],\n+ } as const satisfies ServerProvider;\n+ const instance = {\n+ instanceId: codexInstanceId,\n+ driverKind: codexDriver,\n+ continuationIdentity: {\n+ driverKind: codexDriver,\n+ continuationKey: "codex:instance:codex",\n+ },\n+ displayName: undefined,\n+ enabled: true,\n+ snapshot: {\n+ getSnapshot: Effect.succeed(cachedProvider),\n+ refresh: Effect.die(new Error("simulated refresh failure")),\n+ streamChanges: Stream.empty,\n+ },\n+ adapter: {} as ProviderInstance["adapter"],\n+ textGeneration: {} as ProviderInstance["textGeneration"],\n+ } satisfies ProviderInstance;\n+ const instanceRegistryLayer = Layer.succeed(ProviderInstanceRegistry, {\n+ getInstance: (instanceId) =>\n+ Effect.succeed(instanceId === codexInstanceId ? instance : undefined),\n+ listInstances: Effect.succeed([instance]),\n+ listUnavailable: Effect.succeed([]),\n+ streamChanges: Stream.empty,\n+ subscribeChanges: Effect.flatMap(PubSub.unbounded<void>(), (pubsub) =>\n+ PubSub.subscribe(pubsub),\n+ ),\n+ });\n+ const scope = yield* Scope.make();\n+ yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void));\n+ const runtimeServices = yield* Layer.build(\n+ ProviderRegistryLive.pipe(\n+ Layer.provideMerge(instanceRegistryLayer),\n+ Layer.provideMerge(\n+ ServerConfig.layerTest(process.cwd(), {\n+ prefix: "t3-provider-registry-refresh-failure-",\n+ }),\n+ ),\n+ Layer.provideMerge(NodeServices.layer),\n+ ),\n+ ).pipe(Scope.provide(scope));\n+\n+ yield* Effect.gen(function* () {\n+ const registry = yield* ProviderRegistry;\n+\n+ assert.deepStrictEqual(yield* registry.getProviders, [cachedProvider]);\n+ assert.deepStrictEqual(yield* registry.refresh(codexDriver), [cachedProvider]);\n+ assert.deepStrictEqual(yield* registry.refreshInstance(codexInstanceId), [\n+ cachedProvider,\n+ ]);\n+ }).pipe(Effect.provide(runtimeServices));\n+ }),\n+ );\n+\n+ it.effect("keeps consuming registry changes after one sync fails", () =>\n+ Effect.gen(function* () {\n+ const codexDriver = ProviderDriverKind.make("codex");\n+ const codexInstanceId = ProviderInstanceId.make("codex");\n+ const claudeDriver = ProviderDriverKind.make("claudeAgent");\n+ const claudeInstanceId = ProviderInstanceId.make("claudeAgent");\n+ const codexProvider = {\n+ instanceId: codexInstanceId,\n+ driver: codexDriver,\n+ status: "ready",\n+ enabled: true,\n+ installed: true,\n+ auth: { status: "authenticated" },\n+ checkedAt: "2026-04-29T10:00:00.000Z",\n+ version: "1.0.0",\n+ models: [],\n+ slashCommands: [],\n+ skills: [],\n+ } as const satisfies ServerProvider;\n+ const claudeProvider = {\n+ instanceId: claudeInstanceId,\n+ driver: claudeDriver,\n+ status: "ready",\n+ enabled: true,\n+ installed: true,\n+ auth: { status: "authenticated" },\n+ checkedAt: "2026-04-29T10:01:00.000Z",\n+ version: "1.0.0",\n+ models: [],\n+ slashCommands: [],\n+ skills: [],\n+ } as const satisfies ServerProvider;\n+ const makeInstance = (provider: ServerProvider): ProviderInstance => ({\n+ instanceId: provider.instanceId,\n+ driverKind: provider.driver,\n+ continuationIdentity: {\n+ driverKind: provider.driver,\n+ continuationKey: `${provider.driver}:instance:${provider.instanceId}`,\n+ },\n+ displayName: undefined,\n+ enabled: true,\n+ snapshot: {\n+ getSnapshot: Effect.succeed(provider),\n+ refresh: Effect.succeed(provider),\n+ streamChanges: Stream.empty,\n+ },\n+ adapter: {} as ProviderInstance["adapter"],\n+ textGeneration: {} as ProviderInstance["textGeneration"],\n+ });\n+ const codexInstance = makeInstance(codexProvider);\n+ const claudeInstance = makeInstance(claudeProvider);\n+ const changes = yield* PubSub.unbounded<void>();\n+ const instancesRef = yield* Ref.make<ReadonlyArray<ProviderInstance>>([codexInstance]);\n+ const failNextList = yield* Ref.make(false);\n+ const wait = (millis: number) =>\n+ Effect.promise<void>(() => new Promise((resolve) => setTimeout(resolve, millis)));\n+ const instanceRegistryLayer = Layer.succeed(ProviderInstanceRegistry, {\n+ getInstance: (instanceId) =>\n+ Ref.get(instancesRef).pipe(\n+ Effect.map((instances) =>\n+ instances.find((instance) => instance.instanceId === instanceId),\n+ ),\n+ ),\n+ listInstances: Effect.gen(function* () {\n+ const shouldFail = yield* Ref.get(failNextList);\n+ if (shouldFail) {\n+ yield* Ref.set(failNextList, false);\n+ return yield* Effect.die(new Error("simulated registry list failure"));\n+ }\n+ return yield* Ref.get(instancesRef);\n+ }),\n+ listUnavailable: Effect.succeed([]),\n+ streamChanges: Stream.fromPubSub(changes),\n+ subscribeChanges: PubSub.subscribe(changes),\n+ });\n+ const scope = yield* Scope.make();\n+ yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void));\n+ const runtimeServices = yield* Layer.build(\n+ ProviderRegistryLive.pipe(\n+ Layer.provideMerge(instanceRegistryLayer),\n+ Layer.provideMerge(\n+ ServerConfig.layerTest(process.cwd(), {\n+ prefix: "t3-provider-registry-sync-failure-",\n+ }),\n+ ),\n+ Layer.provideMerge(NodeServices.layer),\n+ ),\n+ ).pipe(Scope.provide(scope));\n+\n+ yield* Effect.gen(function* () {\n+ const registry = yield* ProviderRegistry;\n+ assert.deepStrictEqual(yield* registry.getProviders, [codexProvider]);\n+\n+ yield* Ref.set(failNextList, true);\n+ yield* PubSub.publish(changes, undefined);\n+\n+ yield* Ref.set(instancesRef, [codexInstance, claudeInstance]);\n+ yield* PubSub.publish(changes, undefined);\n+\n+ let providers = yield* registry.getProviders;\n+ for (\n+ let attempt = 0;\n+ attempt < 50 &&\n+ !providers.some((provider) => provider.instanceId === claudeInstanceId);\n+ attempt += 1\n+ ) {\n+ yield* wait(10);\n+ providers = yield* registry.getProviders;\n+ }\n+\n+ assert.deepStrictEqual(\n+ providers.map((provider) => provider.instanceId).toSorted(),\n+ [codexInstanceId, claudeInstanceId].toSorted(),\n+ );\n+ }).pipe(Effect.provide(runtimeServices));\n+ }),\n+ );\n+\n+ // This test intentionally avoids `mockCommandSpawnerLayer` so the real\n+ // `probeCodexAppServerProvider` path runs — including the full\n+ // `codex app-server` RPC handshake via `CodexClient.layerCommand`.\n+ // We point `binaryPath` at a name that cannot exist on any machine so\n+ // the real `ChildProcessSpawner` deterministically returns ENOENT; the\n+ // probe wraps that as `CodexAppServerSpawnError` and\n+ // `checkCodexProviderStatus` turns it into the user-visible "not\n+ // installed" error snapshot. If the aggregator\'s `syncLiveSources`\n+ // breaks — the `codex_personal`-never-probes bug we are guarding\n+ // against — that snapshot never lands in `getProviders` and the\n+ // assertions below fail.\n+ it.effect("propagates real Codex probe failures to the aggregator at boot", () =>\n Effect.gen(function* () {\n- let spawnCount = 0;\n+ const missingBinary = `t3code_codex_missing_${process.pid}_${Date.now()}`;\n const serverSettings = yield* makeMutableServerSettingsService(\n Schema.decodeSync(ServerSettings)(\n deepMerge(DEFAULT_SERVER_SETTINGS, {\n providers: {\n+ // Disable every built-in probe that would otherwise spawn\n+ // on the CI host. `enabled: false` short-circuits each\n+ // driver\'s probe *before* it touches the spawner, so the\n+ // test environment stays isolated from the dev\n+ // machine\'s PATH.\n codex: { enabled: false },\n+ claudeAgent: { enabled: false },\n cursor: { enabled: false },\n+ opencode: { enabled: false },\n },\n+ // `providerInstances` keys are branded `ProviderInstanceId`;\n+ // the branded index signature rejects plain string literals\n+ // at the TS level even though the runtime schema happily\n+ // accepts + decodes them. Cast the patch to `unknown` so\n+ // the `Schema.decodeSync` below does the real validation.\n+ providerInstances: {\n+ // Matches the shape the user had in `.t3/dev/settings.json`\n+ // when the bug was reported: a custom enabled Codex instance\n+ // pointing at a binary the server has to actually spawn.\n+ codex_personal: {\n+ driver: "codex",\n+ displayName: "Codex Personal",\n+ enabled: true,\n+ config: {\n+ binaryPath: missingBinary,\n+ homePath: `/tmp/${missingBinary}_home`,\n+ },\n+ },\n+ } as unknown as ContractServerSettings["providerInstances"],\n }),\n ),\n );\n const scope = yield* Scope.make();\n yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void));\n const providerRegistryLayer = ProviderRegistryLive.pipe(\n+ Layer.provideMerge(ProviderInstanceRegistryHydrationLive),\n Layer.provideMerge(Layer.succeed(ServerSettingsService, serverSettings)),\n Layer.provideMerge(\n ServerConfig.layerTest(process.cwd(), {\n prefix: "t3-provider-registry-",\n }),\n ),\n+ Layer.provideMerge(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)),\n+ Layer.provideMerge(OpenCodeRuntimeLive),\n+ // NO spawner mock — `ChildProcessSpawner` is supplied by the\n+ // outer `NodeServices.layer` on `it.layer(...)` and will\n+ // genuinely spawn a subprocess. The missing-binary ENOENT is\n+ // what exercises the same failure mode as a misconfigured\n+ // production `binaryPath`.\n+ );\n+ const runtimeServices = yield* Layer.build(providerRegistryLayer).pipe(\n+ Scope.provide(scope),\n+ );\n+\n+ yield* Effect.gen(function* () {\n+ const registry = yield* ProviderRegistry;\n+ const providers = yield* registry.getProviders;\n+ const codexPersonal = providers.find(\n+ (provider) => provider.instanceId === "codex_personal",\n+ );\n+ assert.notStrictEqual(\n+ codexPersonal,\n+ undefined,\n+ `Expected the aggregator to know about codex_personal; instead saw: ${providers\n+ .map((provider) => provider.instanceId)\n+ .join(", ")}`,\n+ );\n+ assert.strictEqual(\n+ codexPersonal?.status,\n+ "error",\n+ "Real Codex probe against a missing binary should surface as \'error\' in the aggregator",\n+ );\n+ assert.strictEqual(codexPersonal?.installed, false);\n+ assert.strictEqual(\n+ codexPersonal?.message,\n+ "Codex CLI (`codex`) is not installed or not on PATH.",\n+ );\n+ }).pipe(Effect.provide(runtimeServices));\n+ }),\n+ );\n+\n+ // Guards the second half of the reported bug: changing\n+ // `providers.codex.binaryPath` in settings must tear down the live\n+ // instance and rebuild it so a fresh probe runs with the new binary.\n+ // This test drives the real settings stream → registry reconcile →\n+ // aggregator sync pipeline and asserts that `getProviders` reflects\n+ // the new probe\'s outcome. If `syncLiveSources` stops awaiting the\n+ // rebuilt instance\'s refresh (previous bug mode), the aggregator\n+ // keeps the old snapshot and this test fails.\n+ //\n+ // `live` (imported from `@effect/vitest`) is used instead of\n+ // `it.effect` so real timers coordinate the fibres that drive the\n+ // settings → reconcile → sync pipeline. Under `it.effect`\'s\n+ // TestClock, `Effect.sleep` blocks until `TestClock.adjust`, which\n+ // would require this test to reach into the internals of the\n+ // reconcile pipeline to advance it step by step.\n+ //\n+ // The nested `it` handed to `it.layer(…, (it) => …)` is the\n+ // `MethodsNonLive` variant and therefore lacks `.live`; the\n+ // top-level `live` export from `@effect/vitest` is the equivalent.\n+ live("re-probes when settings change the codex binaryPath", () =>\n+ Effect.gen(function* () {\n+ const firstMissing = `t3code_codex_first_${process.pid}_${Date.now()}`;\n+ const secondMissing = `t3code_codex_second_${process.pid}_${Date.now()}`;\n+ const serverSettings = yield* makeMutableServerSettingsService(\n+ Schema.decodeSync(ServerSettings)(\n+ deepMerge(DEFAULT_SERVER_SETTINGS, {\n+ providers: {\n+ codex: { enabled: true, binaryPath: firstMissing },\n+ claudeAgent: { enabled: false },\n+ cursor: { enabled: false },\n+ opencode: { enabled: false },\n+ },\n+ }),\n+ ),\n+ );\n+ const scope = yield* Scope.make();\n+ yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void));\n+ const providerRegistryLayer = ProviderRegistryLive.pipe(\n+ Layer.provideMerge(ProviderInstanceRegistryHydrationLive),\n+ Layer.provideMerge(Layer.succeed(ServerSettingsService, serverSettings)),\n Layer.provideMerge(\n- mockCommandSpawnerLayer((command, args) => {\n- spawnCount += 1;\n- const joined = args.join(" ");\n- if (joined === "--version") {\n- return { stdout: "claude 1.0.0\\n", stderr: "", code: 0 };\n- }\n- if (joined === "auth status") {\n- return { stdout: \'{"authenticated":true}\\n\', stderr: "", code: 0 };\n- }\n- throw new Error(`Unexpected args: ${command} ${joined}`);\n+ ServerConfig.layerTest(process.cwd(), {\n+ prefix: "t3-provider-registry-",\n }),\n ),\n+ Layer.provideMerge(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)),\n+ Layer.provideMerge(OpenCodeRuntimeLive),\n+ // `it.live` does not inherit layers from the outer `it.layer`\n+ // wrapper, so provide `NodeServices.layer` inline. This is the\n+ // same real `ChildProcessSpawner` + `FileSystem` + `Path`\n+ // services that production uses.\n+ Layer.provideMerge(NodeServices.layer),\n );\n const runtimeServices = yield* Layer.build(providerRegistryLayer).pipe(\n Scope.provide(scope),\n@@ -469,24 +846,113 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(\n \n yield* Effect.gen(function* () {\n const registry = yield* ProviderRegistry;\n- assert.strictEqual(spawnCount > 0, true);\n+ // Boot-time probe: the default codex instance is enabled with\n+ // `firstMissing`, so the real spawner yields ENOENT and the\n+ // snapshot should be `status: "error"`. What *distinguishes*\n+ // the two probe runs is `checkedAt` — each probe stamps a\n+ // fresh DateTime, so we capture it and assert it advances\n+ // after the settings mutation.\n+ const initialProviders = yield* registry.getProviders;\n+ const initialCodex = initialProviders.find(\n+ (provider) => provider.instanceId === "codex",\n+ );\n+ assert.strictEqual(initialCodex?.status, "error");\n+ assert.strictEqual(initialCodex?.installed, false);\n+ const initialCheckedAt = initialCodex?.checkedAt;\n+ assert.notStrictEqual(initialCheckedAt, undefined);\n+\n+ // Drive a settings change. The Hydration layer\'s\n+ // `SettingsWatcherLive` consumes this via `streamChanges`,\n+ // calls `reconcile`, which rebuilds the codex instance (the\n+ // envelope changed because `binaryPath` differs → `entryEqual`\n+ // is false). The registry\'s `Stream.runForEach(\n+ // instanceRegistry.streamChanges, () => syncLiveSources)`\n+ // fires `syncLiveSources`, which subscribes + awaits a fresh\n+ // refresh on the rebuilt instance.\n+ yield* serverSettings.updateSettings({\n+ providers: {\n+ codex: { enabled: true, binaryPath: secondMissing },\n+ },\n+ });\n+\n+ // Poll with real timers (via `it.live`) until `checkedAt`\n+ // advances or we hit a generous 3-second ceiling. Anything\n+ // slower than that is a regression — the real probe fails\n+ // fast on ENOENT, and the reconcile + sync pipeline is\n+ // purely in-process.\n const refreshed = yield* Effect.gen(function* () {\n- for (let remainingAttempts = 50; remainingAttempts > 0; remainingAttempts -= 1) {\n+ for (let attempts = 0; attempts < 60; attempts += 1) {\n const providers = yield* registry.getProviders;\n- const claudeProvider = providers.find(\n- (provider) => provider.provider === "claudeAgent",\n- );\n- if (claudeProvider?.status === "ready") {\n+ const codex = providers.find((provider) => provider.instanceId === "codex");\n+ if (codex !== undefined && codex.checkedAt !== initialCheckedAt) {\n return providers;\n }\n- yield* Effect.sleep("10 millis");\n+ yield* Effect.sleep("50 millis");\n }\n return yield* registry.getProviders;\n });\n- assert.strictEqual(\n- refreshed.find((provider) => provider.provider === "claudeAgent")?.status,\n- "ready",\n+\n+ const reprobedCodex = refreshed.find((provider) => provider.instanceId === "codex");\n+ assert.notStrictEqual(\n+ reprobedCodex?.checkedAt,\n+ initialCheckedAt,\n+ "Expected a fresh probe after settings change, got the stale snapshot",\n );\n+ assert.strictEqual(reprobedCodex?.status, "error");\n+ assert.strictEqual(reprobedCodex?.installed, false);\n+ }).pipe(Effect.provide(runtimeServices));\n+ }),\n+ );\n+\n+ it.effect("includes unavailable instance snapshots in getProviders", () =>\n+ Effect.gen(function* () {\n+ const serverSettings = yield* makeMutableServerSettingsService(\n+ Schema.decodeSync(ServerSettings)(\n+ deepMerge(DEFAULT_SERVER_SETTINGS, {\n+ providers: {\n+ codex: { enabled: false },\n+ claudeAgent: { enabled: false },\n+ cursor: { enabled: false },\n+ opencode: { enabled: false },\n+ },\n+ providerInstances: {\n+ ghost_main: {\n+ driver: "ghostDriver",\n+ displayName: "A fork-only driver we don\'t ship",\n+ enabled: false,\n+ config: { arbitrary: "payload" },\n+ },\n+ } as unknown as ContractServerSettings["providerInstances"],\n+ }),\n+ ),\n+ );\n+ const scope = yield* Scope.make();\n+ yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void));\n+ const providerRegistryLayer = ProviderRegistryLive.pipe(\n+ Layer.provideMerge(ProviderInstanceRegistryHydrationLive),\n+ Layer.provideMerge(Layer.succeed(ServerSettingsService, serverSettings)),\n+ Layer.provideMerge(\n+ ServerConfig.layerTest(process.cwd(), {\n+ prefix: "t3-provider-registry-",\n+ }),\n+ ),\n+ Layer.provideMerge(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)),\n+ Layer.provideMerge(OpenCodeRuntimeLive),\n+ Layer.provideMerge(NodeServices.layer),\n+ );\n+ const runtimeServices = yield* Layer.build(providerRegistryLayer).pipe(\n+ Scope.provide(scope),\n+ );\n+\n+ yield* Effect.gen(function* () {\n+ const registry = yield* ProviderRegistry;\n+ const providers = yield* registry.getProviders;\n+ const ghost = providers.find((provider) => provider.instanceId === "ghost_main");\n+\n+ assert.notStrictEqual(ghost, undefined);\n+ assert.strictEqual(ghost?.driver, "ghostDriver");\n+ assert.strictEqual(ghost?.availability, "unavailable");\n+ assert.match(ghost?.unavailableReason ?? "", /ghostDriver/);\n }).pipe(Effect.provide(runtimeServices));\n }),\n );\n@@ -513,12 +979,15 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(\n const scope = yield* Scope.make();\n yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void));\n const providerRegistryLayer = ProviderRegistryLive.pipe(\n+ Layer.provideMerge(ProviderInstanceRegistryHydrationLive),\n Layer.provideMerge(Layer.succeed(ServerSettingsService, serverSettings)),\n Layer.provideMerge(\n ServerConfig.layerTest(process.cwd(), {\n prefix: "t3-provider-registry-",\n }),\n ),\n+ Layer.provideMerge(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)),\n+ Layer.provideMerge(OpenCodeRuntimeLive),\n Layer.provideMerge(\n mockCommandSpawnerLayer((command, args) => {\n if (command === "agent") {\n@@ -526,10 +995,18 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(\n }\n const joined = args.join(" ");\n if (joined === "--version") {\n- return { stdout: `${command} 1.0.0\\n`, stderr: "", code: 0 };\n+ return {\n+ stdout: `${command} 1.0.0\\n`,\n+ stderr: "",\n+ code: 0,\n+ };\n }\n if (joined === "auth status") {\n- return { stdout: \'{"authenticated":true}\\n\', stderr: "", code: 0 };\n+ return {\n+ stdout: \'{"authenticated":true}\\n\',\n+ stderr: "",\n+ code: 0,\n+ };\n }\n throw new Error(`Unexpected args: ${command} ${joined}`);\n }),\n@@ -545,12 +1022,16 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(\n yield* Effect.gen(function* () {\n const registry = yield* ProviderRegistry;\n const providers = yield* registry.getProviders;\n- const cursorProvider = providers.find((provider) => provider.provider === "cursor");\n-\n- assert.deepStrictEqual(\n- providers.map((provider) => provider.provider),\n- ["codex", "claudeAgent", "opencode", "cursor"],\n+ const cursorProvider = providers.find(\n+ (provider) => provider.instanceId === ProviderInstanceId.make("cursor"),\n );\n+\n+ assert.deepStrictEqual(providers.map((provider) => provider.instanceId).toSorted(), [\n+ "claudeAgent",\n+ "codex",\n+ "cursor",\n+ "opencode",\n+ ]);\n assert.strictEqual(cursorProvider?.enabled, false);\n assert.strictEqual(cursorProvider?.status, "disabled");\n assert.strictEqual(\n@@ -564,20 +1045,9 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(\n \n it.effect("skips codex probes entirely when the provider is disabled", () =>\n Effect.gen(function* () {\n- const serverSettingsLayer = ServerSettingsService.layerTest({\n- providers: {\n- codex: {\n- enabled: false,\n- },\n- },\n- });\n-\n- const status = yield* checkCodexProviderStatus().pipe(\n- Effect.provide(\n- Layer.mergeAll(serverSettingsLayer, failingSpawnerLayer("spawn codex ENOENT")),\n- ),\n+ const status = yield* checkCodexProviderStatus(disabledCodexSettings).pipe(\n+ Effect.provide(failingSpawnerLayer("spawn codex ENOENT")),\n );\n- assert.strictEqual(status.provider, "codex");\n assert.strictEqual(status.enabled, false);\n assert.strictEqual(status.status, "disabled");\n assert.strictEqual(status.installed, false);\n@@ -591,8 +1061,10 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(\n describe("checkClaudeProviderStatus", () => {\n it.effect("returns ready when claude is installed and authenticated", () =>\n Effect.gen(function* () {\n- const status = yield* checkClaudeProviderStatus();\n- assert.strictEqual(status.provider, "claudeAgent");\n+ const status = yield* checkClaudeProviderStatus(\n+ defaultClaudeSettings,\n+ claudeCapabilities(),\n+ );\n assert.strictEqual(status.status, "ready");\n assert.strictEqual(status.installed, true);\n assert.strictEqual(status.auth.status, "authenticated");\n@@ -617,7 +1089,10 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(\n "includes Claude Opus 4.7 with xhigh as the default effort on supported versions",\n () =>\n Effect.gen(function* () {\n- const status = yield* checkClaudeProviderStatus();\n+ const status = yield* checkClaudeProviderStatus(\n+ defaultClaudeSettings,\n+ claudeCapabilities(),\n+ );\n const opus47 = status.models.find((model) => model.slug === "claude-opus-4-7");\n if (!opus47) {\n assert.fail("Expected Claude Opus 4.7 to be present for Claude Code v2.1.111.");\n@@ -655,7 +1130,10 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(\n \n it.effect("hides Claude Opus 4.7 on older Claude Code versions", () =>\n Effect.gen(function* () {\n- const status = yield* checkClaudeProviderStatus();\n+ const status = yield* checkClaudeProviderStatus(\n+ defaultClaudeSettings,\n+ claudeCapabilities(),\n+ );\n assert.strictEqual(\n status.models.some((model) => model.slug === "claude-opus-4-7"),\n false,\n@@ -683,8 +1161,10 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(\n \n it.effect("returns a display label for claude subscription types", () =>\n Effect.gen(function* () {\n- const status = yield* checkClaudeProviderStatus(() => Effect.succeed("maxplan"));\n- assert.strictEqual(status.provider, "claudeAgent");\n+ const status = yield* checkClaudeProviderStatus(\n+ defaultClaudeSettings,\n+ claudeCapabilities({ subscriptionType: "maxplan" }),\n+ );\n assert.strictEqual(status.status, "ready");\n assert.strictEqual(status.auth.status, "authenticated");\n assert.strictEqual(status.auth.type, "maxplan");\n@@ -706,18 +1186,120 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(\n ),\n );\n \n+ it.effect("does not duplicate Claude in full subscription labels", () =>\n+ Effect.gen(function* () {\n+ const status = yield* checkClaudeProviderStatus(\n+ defaultClaudeSettings,\n+ claudeCapabilities({\n+ subscriptionType: "Claude Max Subscription",\n+ }),\n+ );\n+ assert.strictEqual(status.auth.status, "authenticated");\n+ assert.strictEqual(status.auth.type, "Claude Max Subscription");\n+ assert.strictEqual(status.auth.label, "Claude Max Subscription");\n+ }).pipe(\n+ Effect.provide(\n+ mockSpawnerLayer((args) => {\n+ const joined = args.join(" ");\n+ if (joined === "--version") return { stdout: "1.0.0\\n", stderr: "", code: 0 };\n+ throw new Error(`Unexpected args: ${joined}`);\n+ }),\n+ ),\n+ ),\n+ );\n+\n+ it.effect("does not duplicate Claude in provider-prefixed subscription names", () =>\n+ Effect.gen(function* () {\n+ const status = yield* checkClaudeProviderStatus(\n+ defaultClaudeSettings,\n+ claudeCapabilities({\n+ subscriptionType: "Claude Max",\n+ }),\n+ );\n+ assert.strictEqual(status.auth.status, "authenticated");\n+ assert.strictEqual(status.auth.type, "Claude Max");\n+ assert.strictEqual(status.auth.label, "Claude Max Subscription");\n+ }).pipe(\n+ Effect.provide(\n+ mockSpawnerLayer((args) => {\n+ const joined = args.join(" ");\n+ if (joined === "--version") return { stdout: "1.0.0\\n", stderr: "", code: 0 };\n+ throw new Error(`Unexpected args: ${joined}`);\n+ }),\n+ ),\n+ ),\n+ );\n+\n+ it.effect("returns claude auth email from initialization result", () =>\n+ Effect.gen(function* () {\n+ const status = yield* checkClaudeProviderStatus(\n+ defaultClaudeSettings,\n+ claudeCapabilities({ email: "claude@example.com" }),\n+ );\n+ assert.strictEqual(status.auth.status, "authenticated");\n+ assert.strictEqual(status.auth.email, "claude@example.com");\n+ }).pipe(\n+ Effect.provide(\n+ mockSpawnerLayer((args) => {\n+ const joined = args.join(" ");\n+ if (joined === "--version") return { stdout: "1.0.0\\n", stderr: "", code: 0 };\n+ if (joined === "auth status")\n+ return {\n+ stdout:\n+ \'{"loggedIn":true,"authMethod":"claude.ai","account":{"email":"claude@example.com"}}\\n\',\n+ stderr: "",\n+ code: 0,\n+ };\n+ throw new Error(`Unexpected args: ${joined}`);\n+ }),\n+ ),\n+ ),\n+ );\n+\n+ it.effect("runs Claude status probes with the configured Claude HOME", () => {\n+ const claudeHome = "/tmp/t3code-claude-home";\n+ const recorded = recordingMockSpawnerLayer((args) => {\n+ const joined = args.join(" ");\n+ if (joined === "--version") return { stdout: "1.0.0\\n", stderr: "", code: 0 };\n+ if (joined === "auth status")\n+ return {\n+ stdout: \'{"loggedIn":true,"authMethod":"claude.ai"}\\n\',\n+ stderr: "",\n+ code: 0,\n+ };\n+ throw new Error(`Unexpected args: ${joined}`);\n+ });\n+\n+ return Effect.gen(function* () {\n+ const status = yield* checkClaudeProviderStatus(\n+ {\n+ ...defaultClaudeSettings,\n+ homePath: claudeHome,\n+ },\n+ claudeCapabilities(),\n+ );\n+ assert.strictEqual(status.status, "ready");\n+ assert.deepStrictEqual(\n+ recorded.commands.map((command) => command.env?.HOME),\n+ [claudeHome],\n+ );\n+ }).pipe(Effect.provide(recorded.layer));\n+ });\n+\n it.effect("includes probed claude slash commands in the provider snapshot", () =>\n Effect.gen(function* () {\n const status = yield* checkClaudeProviderStatus(\n- () => Effect.succeed("maxplan"),\n- () =>\n- Effect.succeed([\n+ defaultClaudeSettings,\n+ claudeCapabilities({\n+ subscriptionType: "maxplan",\n+ slashCommands: [\n {\n name: "review",\n description: "Review a pull request",\n input: { hint: "pr-or-branch" },\n },\n- ]),\n+ ],\n+ }),\n );\n \n assert.deepStrictEqual(status.slashCommands, [\n@@ -747,9 +1329,10 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(\n it.effect("deduplicates probed claude slash commands by name", () =>\n Effect.gen(function* () {\n const status = yield* checkClaudeProviderStatus(\n- () => Effect.succeed("maxplan"),\n- () =>\n- Effect.succeed([\n+ defaultClaudeSettings,\n+ claudeCapabilities({\n+ subscriptionType: "maxplan",\n+ slashCommands: [\n {\n name: "ui",\n description: "Explore and refine UI",\n@@ -758,7 +1341,8 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(\n name: "ui",\n input: { hint: "component-or-screen" },\n },\n- ]),\n+ ],\n+ }),\n );\n \n assert.deepStrictEqual(status.slashCommands, [\n@@ -787,8 +1371,10 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(\n \n it.effect("returns an api key label for claude api key auth", () =>\n Effect.gen(function* () {\n- const status = yield* checkClaudeProviderStatus();\n- assert.strictEqual(status.provider, "claudeAgent");\n+ const status = yield* checkClaudeProviderStatus(\n+ defaultClaudeSettings,\n+ claudeCapabilities({ tokenSource: "ANTHROPIC_AUTH_TOKEN" }),\n+ );\n assert.strictEqual(status.status, "ready");\n assert.strictEqual(status.auth.status, "authenticated");\n assert.strictEqual(status.auth.type, "apiKey");\n@@ -812,8 +1398,10 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(\n \n it.effect("returns unavailable when claude is missing", () =>\n Effect.gen(function* () {\n- const status = yield* checkClaudeProviderStatus();\n- assert.strictEqual(status.provider, "claudeAgent");\n+ const status = yield* checkClaudeProviderStatus(\n+ defaultClaudeSettings,\n+ claudeCapabilities(),\n+ );\n assert.strictEqual(status.status, "error");\n assert.strictEqual(status.installed, false);\n assert.strictEqual(status.auth.status, "unknown");\n@@ -826,8 +1414,10 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(\n \n it.effect("returns error when version check fails with non-zero exit code", () =>\n Effect.gen(function* () {\n- const status = yield* checkClaudeProviderStatus();\n- assert.strictEqual(status.provider, "claudeAgent");\n+ const status = yield* checkClaudeProviderStatus(\n+ defaultClaudeSettings,\n+ claudeCapabilities(),\n+ );\n assert.strictEqual(status.status, "error");\n assert.strictEqual(status.installed, true);\n }).pipe(\n@@ -835,33 +1425,9 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(\n mockSpawnerLayer((args) => {\n const joined = args.join(" ");\n if (joined === "--version")\n- return { stdout: "", stderr: "Something went wrong", code: 1 };\n- throw new Error(`Unexpected args: ${joined}`);\n- }),\n- ),\n- ),\n- );\n-\n- it.effect("returns unauthenticated when auth status reports not logged in", () =>\n- Effect.gen(function* () {\n- const status = yield* checkClaudeProviderStatus();\n- assert.strictEqual(status.provider, "claudeAgent");\n- assert.strictEqual(status.status, "error");\n- assert.strictEqual(status.installed, true);\n- assert.strictEqual(status.auth.status, "unauthenticated");\n- assert.strictEqual(\n- status.message,\n- "Claude is not authenticated. Run `claude auth login` and try again.",\n- );\n- }).pipe(\n- Effect.provide(\n- mockSpawnerLayer((args) => {\n- const joined = args.join(" ");\n- if (joined === "--version") return { stdout: "1.0.0\\n", stderr: "", code: 0 };\n- if (joined === "auth status")\n return {\n- stdout: \'{"loggedIn":false}\\n\',\n- stderr: "",\n+ stdout: "",\n+ stderr: "Something went wrong",\n code: 1,\n };\n throw new Error(`Unexpected args: ${joined}`);\n@@ -870,36 +1436,18 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(\n ),\n );\n \n- it.effect("returns unauthenticated when output includes \'not logged in\'", () =>\n- Effect.gen(function* () {\n- const status = yield* checkClaudeProviderStatus();\n- assert.strictEqual(status.provider, "claudeAgent");\n- assert.strictEqual(status.status, "error");\n- assert.strictEqual(status.installed, true);\n- assert.strictEqual(status.auth.status, "unauthenticated");\n- }).pipe(\n- Effect.provide(\n- mockSpawnerLayer((args) => {\n- const joined = args.join(" ");\n- if (joined === "--version") return { stdout: "1.0.0\\n", stderr: "", code: 0 };\n- if (joined === "auth status")\n- return { stdout: "Not logged in\\n", stderr: "", code: 1 };\n- throw new Error(`Unexpected args: ${joined}`);\n- }),\n- ),\n- ),\n- );\n-\n- it.effect("returns warning when auth status command is unsupported", () =>\n+ it.effect("returns warning when the Claude initialization result is unavailable", () =>\n Effect.gen(function* () {\n- const status = yield* checkClaudeProviderStatus();\n- assert.strictEqual(status.provider, "claudeAgent");\n+ const status = yield* checkClaudeProviderStatus(\n+ defaultClaudeSettings,\n+ noClaudeCapabilities,\n+ );\n assert.strictEqual(status.status, "warning");\n assert.strictEqual(status.installed, true);\n assert.strictEqual(status.auth.status, "unknown");\n assert.strictEqual(\n status.message,\n- "Claude Agent authentication status command is unavailable in this version of Claude.",\n+ "Could not verify Claude authentication status from initialization result.",\n );\n }).pipe(\n Effect.provide(\n@@ -907,52 +1455,16 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(\n const joined = args.join(" ");\n if (joined === "--version") return { stdout: "1.0.0\\n", stderr: "", code: 0 };\n if (joined === "auth status")\n- return { stdout: "", stderr: "error: unknown command \'auth\'", code: 2 };\n+ return {\n+ stdout: \'{"loggedIn":false}\\n\',\n+ stderr: "",\n+ code: 1,\n+ };\n throw new Error(`Unexpected args: ${joined}`);\n }),\n ),\n ),\n );\n });\n-\n- // ── parseClaudeAuthStatusFromOutput pure tests ────────────────────\n-\n- describe("parseClaudeAuthStatusFromOutput", () => {\n- it("exit code 0 with no auth markers is ready", () => {\n- const parsed = parseClaudeAuthStatusFromOutput({ stdout: "OK\\n", stderr: "", code: 0 });\n- assert.strictEqual(parsed.status, "ready");\n- assert.strictEqual(parsed.auth.status, "authenticated");\n- });\n-\n- it("JSON with loggedIn=true is authenticated", () => {\n- const parsed = parseClaudeAuthStatusFromOutput({\n- stdout: \'{"loggedIn":true,"authMethod":"claude.ai"}\\n\',\n- stderr: "",\n- code: 0,\n- });\n- assert.strictEqual(parsed.status, "ready");\n- assert.strictEqual(parsed.auth.status, "authenticated");\n- });\n-\n- it("JSON with loggedIn=false is unauthenticated", () => {\n- const parsed = parseClaudeAuthStatusFromOutput({\n- stdout: \'{"loggedIn":false}\\n\',\n- stderr: "",\n- code: 0,\n- });\n- assert.strictEqual(parsed.status, "error");\n- assert.strictEqual(parsed.auth.status, "unauthenticated");\n- });\n-\n- it("JSON without auth marker is warning", () => {\n- const parsed = parseClaudeAuthStatusFromOutput({\n- stdout: \'{"ok":true}\\n\',\n- stderr: "",\n- code: 0,\n- });\n- assert.strictEqual(parsed.status, "warning");\n- assert.strictEqual(parsed.auth.status, "unknown");\n- });\n- });\n },\n );\ndiff --git a/apps/server/src/provider/Layers/ProviderRegistry.ts b/apps/server/src/provider/Layers/ProviderRegistry.ts\nindex ddd1701a94..4f586d881e 100644\n--- a/apps/server/src/provider/Layers/ProviderRegistry.ts\n+++ b/apps/server/src/provider/Layers/ProviderRegistry.ts\n@@ -1,39 +1,63 @@\n /**\n- * ProviderRegistryLive - Aggregates provider-specific snapshot services.\n+ * ProviderRegistryLive — aggregates per-instance snapshot streams into a\n+ * single materialized list.\n+ *\n+ * Historically this Layer composed four per-kind Live Layers\n+ * (`CodexProviderLive`, `ClaudeProviderLive`, …) that each exposed a\n+ * `ServerProviderShape`. Those Lives were deleted during the driver /\n+ * instance refactor — every driver now carries its `snapshot: ServerProviderShape`\n+ * bundled onto the `ProviderInstance` the registry produces.\n+ *\n+ * Each configured instance (including multi-instance setups like\n+ * `codex_personal` + `codex_work`) contributes one `ProviderSnapshotSource`,\n+ * keyed by `instanceId`. Instances whose driver is unavailable or whose\n+ * config failed to decode are merged from `instanceRegistry.listUnavailable`\n+ * as shadow snapshots so the UI can render their exact unavailable reason.\n+ *\n+ * Cache paths on disk are now keyed by `instanceId`. Because\n+ * `defaultInstanceIdForDriver(kind) === kind` for built-in kinds, existing\n+ * `<kind>.json` files remain the on-disk location for that driver\'s default\n+ * instance. Identity-less legacy cache contents are ignored and replaced by\n+ * the first live refresh.\n *\n * @module ProviderRegistryLive\n */\n-import type { ProviderKind, ServerProvider } from "@t3tools/contracts";\n-import { Effect, Equal, FileSystem, Layer, Path, PubSub, Ref, Stream } from "effect";\n+import {\n+ defaultInstanceIdForDriver,\n+ ProviderDriverKind,\n+ type ProviderInstanceId,\n+ type ServerProvider,\n+} from "@t3tools/contracts";\n+import { Cause, Effect, Equal, FileSystem, Layer, Path, PubSub, Ref, Stream } from "effect";\n+import * as Semaphore from "effect/Semaphore";\n \n import { ServerConfig } from "../../config.ts";\n-import { ClaudeProviderLive } from "./ClaudeProvider.ts";\n-import { CodexProviderLive } from "./CodexProvider.ts";\n-import { CursorProviderLive } from "./CursorProvider.ts";\n-import { OpenCodeProviderLive } from "./OpenCodeProvider.ts";\n-import { ClaudeProvider } from "../Services/ClaudeProvider.ts";\n-import { CodexProvider } from "../Services/CodexProvider.ts";\n-import { CursorProvider } from "../Services/CursorProvider.ts";\n-import { OpenCodeProvider } from "../Services/OpenCodeProvider.ts";\n+import { ProviderInstanceRegistry } from "../Services/ProviderInstanceRegistry.ts";\n import { ProviderRegistry, type ProviderRegistryShape } from "../Services/ProviderRegistry.ts";\n-import { OpenCodeRuntimeLive } from "../opencodeRuntime.ts";\n import {\n hydrateCachedProvider,\n- PROVIDER_CACHE_IDS,\n+ isCachedProviderCorrelated,\n orderProviderSnapshots,\n readProviderStatusCache,\n resolveProviderStatusCachePath,\n writeProviderStatusCache,\n } from "../providerStatusCache.ts";\n-import { createBuiltInProviderSources } from "../builtInProviderCatalog.ts";\n+import type { ProviderInstance } from "../ProviderDriver.ts";\n import type { ProviderSnapshotSource } from "../builtInProviderCatalog.ts";\n \n const loadProviders = (\n providerSources: ReadonlyArray<ProviderSnapshotSource>,\n ): Effect.Effect<ReadonlyArray<ServerProvider>> =>\n- Effect.forEach(providerSources, (providerSource) => providerSource.getSnapshot, {\n- concurrency: "unbounded",\n- });\n+ Effect.forEach(\n+ providerSources,\n+ (providerSource) =>\n+ providerSource.getSnapshot.pipe(\n+ Effect.flatMap((snapshot) => correlateSnapshotWithSource(providerSource, snapshot)),\n+ ),\n+ {\n+ concurrency: "unbounded",\n+ },\n+ );\n \n const hasModelCapabilities = (model: ServerProvider["models"][number]): boolean =>\n (model.capabilities?.optionDescriptors?.length ?? 0) > 0;\n@@ -77,63 +101,123 @@ export const haveProvidersChanged = (\n nextProviders: ReadonlyArray<ServerProvider>,\n ): boolean => !Equal.equals(previousProviders, nextProviders);\n \n-const ProviderRegistryLiveBase = Layer.effect(\n+const correlateSnapshotWithSource = (\n+ source: ProviderSnapshotSource,\n+ snapshot: ServerProvider,\n+): Effect.Effect<ServerProvider> => {\n+ if (snapshot.instanceId !== source.instanceId) {\n+ return Effect.die(\n+ new Error(\n+ `Provider snapshot instance mismatch: source \'${source.instanceId}\' emitted \'${snapshot.instanceId}\'.`,\n+ ),\n+ );\n+ }\n+ if (snapshot.driver !== source.driverKind) {\n+ return Effect.die(\n+ new Error(\n+ `Provider snapshot driver mismatch for instance \'${source.instanceId}\': source \'${source.driverKind}\' emitted \'${snapshot.driver}\'.`,\n+ ),\n+ );\n+ }\n+ return Effect.succeed(snapshot);\n+};\n+\n+/**\n+ * Key a snapshot for aggregation and persistence. Snapshot sources\n+ * must be correlated by instance id before reaching this map; missing\n+ * identities are defects, not runtime routing fallbacks.\n+ */\n+const snapshotInstanceKey = (provider: ServerProvider): ProviderInstanceId => {\n+ return provider.instanceId;\n+};\n+\n+// Project a live `ProviderInstance` into the aggregator\'s consumption\n+// shape. Each call re-captures the instance\'s `snapshot` closures, so\n+// after `ProviderInstanceRegistry` rebuilds an instance (e.g. because\n+// its settings changed), a fresh source rides the new PubSub instead\n+// of a closed one.\n+const buildSnapshotSource = (instance: ProviderInstance): ProviderSnapshotSource => ({\n+ instanceId: instance.instanceId,\n+ driverKind: instance.driverKind,\n+ getSnapshot: instance.snapshot.getSnapshot,\n+ refresh: instance.snapshot.refresh,\n+ streamChanges: instance.snapshot.streamChanges,\n+});\n+\n+export const ProviderRegistryLive = Layer.effect(\n ProviderRegistry,\n Effect.gen(function* () {\n- const codexProvider = yield* CodexProvider;\n- const claudeProvider = yield* ClaudeProvider;\n- const openCodeProvider = yield* OpenCodeProvider;\n+ const instanceRegistry = yield* ProviderInstanceRegistry;\n const config = yield* ServerConfig;\n const fileSystem = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n \n- const cursorProvider = yield* CursorProvider;\n-\n- const providerSources = createBuiltInProviderSources({\n- codex: codexProvider,\n- claudeAgent: claudeProvider,\n- opencode: openCodeProvider,\n- cursor: cursorProvider,\n- }) satisfies ReadonlyArray<ProviderSnapshotSource>;\n- const activeProviders = PROVIDER_CACHE_IDS;\n+ // Aggregator PubSub — consumers (WS gateway, etc.) subscribe here for\n+ // coalesced updates across every instance.\n const changesPubSub = yield* Effect.acquireRelease(\n PubSub.unbounded<ReadonlyArray<ServerProvider>>(),\n PubSub.shutdown,\n );\n- const fallbackProviders = yield* loadProviders(providerSources);\n- const cachePathByProvider = new Map(\n- activeProviders.map(\n- (provider) =>\n- [\n- provider,\n- resolveProviderStatusCachePath({\n- cacheDir: config.providerStatusCacheDir,\n- provider,\n- }),\n- ] as const,\n- ),\n- );\n- const fallbackByProvider = new Map(\n- fallbackProviders.map((provider) => [provider.provider, provider] as const),\n- );\n+\n+ // Boot-only: hydrate `providersRef` from the on-disk per-instance\n+ // cache so the UI has something to render during the first refresh.\n+ // Instances added post-boot skip this path; their first entry in\n+ // `providersRef` comes from the reactive `syncLiveSources` pass\n+ // below.\n+ const bootInstances = yield* instanceRegistry.listInstances;\n+ const bootSources = bootInstances.map(buildSnapshotSource);\n+ const fallbackProviders = yield* loadProviders(bootSources);\n+ const fallbackByInstance = new Map<ProviderInstanceId, ServerProvider>();\n+ for (let index = 0; index < fallbackProviders.length; index++) {\n+ const provider = fallbackProviders[index];\n+ const source = bootSources[index];\n+ if (provider === undefined || source === undefined) {\n+ continue;\n+ }\n+ fallbackByInstance.set(source.instanceId, provider);\n+ }\n \n const cachedProviders = yield* Effect.forEach(\n- activeProviders,\n- (provider) => {\n- const filePath = cachePathByProvider.get(provider)!;\n- const fallbackProvider = fallbackByProvider.get(provider)!;\n- return readProviderStatusCache(filePath).pipe(\n- Effect.provideService(FileSystem.FileSystem, fileSystem),\n- Effect.map((cachedProvider) =>\n- cachedProvider === undefined\n- ? undefined\n- : hydrateCachedProvider({\n- cachedProvider,\n- fallbackProvider,\n- }),\n- ),\n- );\n- },\n+ bootSources,\n+ (source) =>\n+ Effect.gen(function* () {\n+ // One cache file per configured instance. For the default\n+ // instance of a built-in kind the path equals `<kind>.json` —\n+ // identical to the legacy filename. We still require the cache\n+ // payload to carry matching instance id + driver kind; old\n+ // identity-less payloads are discarded and the awaited refresh\n+ // below repopulates the cache.\n+ const filePath = yield* resolveProviderStatusCachePath({\n+ cacheDir: config.providerStatusCacheDir,\n+ instanceId: source.instanceId,\n+ }).pipe(Effect.provideService(Path.Path, path));\n+ const fallbackProvider = fallbackByInstance.get(source.instanceId);\n+ if (fallbackProvider === undefined) {\n+ return undefined;\n+ }\n+ return yield* readProviderStatusCache(filePath).pipe(\n+ Effect.provideService(FileSystem.FileSystem, fileSystem),\n+ Effect.flatMap((cachedProvider) => {\n+ if (cachedProvider === undefined) {\n+ return Effect.void.pipe(Effect.as(undefined as ServerProvider | undefined));\n+ }\n+ const correlation = {\n+ cachedProvider,\n+ fallbackProvider,\n+ } as const;\n+ if (!isCachedProviderCorrelated(correlation)) {\n+ return Effect.logWarning("provider status cache identity mismatch, ignoring", {\n+ path: filePath,\n+ instanceId: source.instanceId,\n+ cachedInstanceId: cachedProvider.instanceId ?? null,\n+ driver: source.driverKind,\n+ cachedDriver: cachedProvider.driver ?? null,\n+ }).pipe(Effect.as(undefined as ServerProvider | undefined));\n+ }\n+ return Effect.succeed(hydrateCachedProvider(correlation));\n+ }),\n+ );\n+ }),\n { concurrency: "unbounded" },\n ).pipe(\n Effect.map((providers) =>\n@@ -144,34 +228,64 @@ const ProviderRegistryLiveBase = Layer.effect(\n );\n const providersRef = yield* Ref.make<ReadonlyArray<ServerProvider>>(cachedProviders);\n \n+ // Live-source registry — the dynamic counterpart to the boot-time\n+ // `bootSources`. Keyed by `instanceId`; the stored `ProviderInstance`\n+ // reference is used for identity equality so "no-op" reconciles\n+ // (settings unchanged) skip re-subscribing + re-probing.\n+ const liveSubsRef = yield* Ref.make<ReadonlyMap<ProviderInstanceId, ProviderInstance>>(\n+ new Map(),\n+ );\n+ // Serialize `syncLiveSources` so a rapid burst of reconciles doesn\'t\n+ // interleave two passes clobbering each other\'s fiber bookkeeping.\n+ const syncSemaphore = yield* Semaphore.make(1);\n+\n+ const getLiveSources: Effect.Effect<ReadonlyArray<ProviderSnapshotSource>> = Ref.get(\n+ liveSubsRef,\n+ ).pipe(Effect.map((map) => Array.from(map.values(), buildSnapshotSource)));\n+\n const persistProvider = (provider: ServerProvider) =>\n- writeProviderStatusCache({\n- filePath: cachePathByProvider.get(provider.provider)!,\n- provider,\n- }).pipe(\n- Effect.provideService(FileSystem.FileSystem, fileSystem),\n- Effect.provideService(Path.Path, path),\n- Effect.tapError(Effect.logError),\n- Effect.ignore,\n- );\n+ Effect.gen(function* () {\n+ // Persist every instance — the file name is the instance id, so\n+ // multi-instance setups (e.g. `codex_personal`, `codex_work`) each\n+ // get their own cache. We resolve the path fresh so snapshots\n+ // produced by newly-added instances post-boot still land on disk\n+ // without the aggregator holding a stale `cachePathByInstance`\n+ // entry.\n+ const key = snapshotInstanceKey(provider);\n+ const filePath = yield* resolveProviderStatusCachePath({\n+ cacheDir: config.providerStatusCacheDir,\n+ instanceId: key,\n+ }).pipe(Effect.provideService(Path.Path, path));\n+ yield* writeProviderStatusCache({ filePath, provider }).pipe(\n+ Effect.provideService(FileSystem.FileSystem, fileSystem),\n+ Effect.provideService(Path.Path, path),\n+ Effect.tapError(Effect.logError),\n+ Effect.ignore,\n+ );\n+ });\n \n const upsertProviders = Effect.fn("upsertProviders")(function* (\n nextProviders: ReadonlyArray<ServerProvider>,\n options?: {\n readonly publish?: boolean;\n+ readonly persist?: boolean;\n+ readonly replace?: boolean;\n },\n ) {\n const [previousProviders, providers] = yield* Ref.modify(\n providersRef,\n (previousProviders) => {\n const mergedProviders = new Map(\n- previousProviders.map((provider) => [provider.provider, provider] as const),\n+ previousProviders.map((provider) => [snapshotInstanceKey(provider), provider] as const),\n );\n \n for (const provider of nextProviders) {\n+ const key = snapshotInstanceKey(provider);\n mergedProviders.set(\n- provider.provider,\n- mergeProviderSnapshot(mergedProviders.get(provider.provider), provider),\n+ key,\n+ options?.replace === true\n+ ? provider\n+ : mergeProviderSnapshot(mergedProviders.get(key), provider),\n );\n }\n \n@@ -181,10 +295,12 @@ const ProviderRegistryLiveBase = Layer.effect(\n );\n \n if (haveProvidersChanged(previousProviders, providers)) {\n- yield* Effect.forEach(nextProviders, persistProvider, {\n- concurrency: "unbounded",\n- discard: true,\n- });\n+ if (options?.persist !== false) {\n+ yield* Effect.forEach(nextProviders, persistProvider, {\n+ concurrency: "unbounded",\n+ discard: true,\n+ });\n+ }\n if (options?.publish !== false) {\n yield* PubSub.publish(changesPubSub, providers);\n }\n@@ -202,64 +318,246 @@ const ProviderRegistryLiveBase = Layer.effect(\n return yield* upsertProviders([provider], options);\n });\n \n- const refresh = Effect.fn("refresh")(function* (provider?: ProviderKind) {\n- if (provider) {\n- const providerSource = providerSources.find((candidate) => candidate.provider === provider);\n- if (!providerSource) {\n- return yield* Ref.get(providersRef);\n- }\n- return yield* providerSource.refresh.pipe(\n- Effect.flatMap((nextProvider) => syncProvider(nextProvider)),\n- );\n- }\n-\n- return yield* Effect.forEach(\n- providerSources,\n- (providerSource) => providerSource.refresh.pipe(Effect.flatMap(syncProvider)),\n- {\n- concurrency: "unbounded",\n- discard: true,\n- },\n- ).pipe(Effect.andThen(Ref.get(providersRef)));\n+ const refreshOneSource = Effect.fn("refreshOneSource")(function* (\n+ providerSource: ProviderSnapshotSource,\n+ ) {\n+ return yield* providerSource.refresh.pipe(\n+ Effect.flatMap((nextProvider) =>\n+ correlateSnapshotWithSource(providerSource, nextProvider).pipe(\n+ Effect.flatMap(syncProvider),\n+ ),\n+ ),\n+ );\n });\n \n- yield* Effect.forEach(\n- providerSources,\n- (providerSource) =>\n- Stream.runForEach(providerSource.streamChanges, (provider) => syncProvider(provider)).pipe(\n- Effect.forkScoped,\n- ),\n- {\n+ const refreshAll = Effect.fn("refreshAll")(function* () {\n+ const sources = yield* getLiveSources;\n+ return yield* Effect.forEach(sources, (source) => refreshOneSource(source), {\n concurrency: "unbounded",\n discard: true,\n- },\n+ }).pipe(Effect.andThen(Ref.get(providersRef)));\n+ });\n+\n+ const refresh = Effect.fn("refresh")(function* (provider?: ProviderDriverKind) {\n+ if (provider === undefined) {\n+ return yield* refreshAll();\n+ }\n+ // Kind-scoped refreshes target the default instance for that driver.\n+ const defaultInstanceId = defaultInstanceIdForDriver(provider);\n+ const sources = yield* getLiveSources;\n+ const providerSource = sources.find(\n+ (candidate) => candidate.instanceId === defaultInstanceId,\n+ );\n+ if (!providerSource) {\n+ return yield* Ref.get(providersRef);\n+ }\n+ return yield* refreshOneSource(providerSource);\n+ });\n+\n+ const refreshInstance = Effect.fn("refreshInstance")(function* (\n+ instanceId: ProviderInstanceId,\n+ ) {\n+ const sources = yield* getLiveSources;\n+ const providerSource = sources.find((candidate) => candidate.instanceId === instanceId);\n+ if (!providerSource) {\n+ return yield* Ref.get(providersRef);\n+ }\n+ return yield* refreshOneSource(providerSource);\n+ });\n+\n+ /**\n+ * Diff the aggregator\'s live-source set against the current\n+ * `ProviderInstanceRegistry` and:\n+ * - subscribe to each newly-added or rebuilt instance\'s\n+ * `streamChanges` (so periodic + enrichment refreshes land in\n+ * `providersRef`);\n+ * - force-refresh each newly-added/rebuilt instance and feed the\n+ * result directly into `providersRef`, bypassing the PubSub\n+ * attachment race that otherwise drops the initial probe;\n+ * - prune `providersRef` of instances that no longer exist.\n+ *\n+ * Initial refreshes are awaited in parallel rather than forked, so\n+ * callers (layer build; `streamChanges` watcher) see fully-probed\n+ * state on return. This matters for layer build in particular:\n+ * consumers reading `getProviders` immediately after layer build\n+ * expect the probe to have already landed.\n+ *\n+ * Per-instance subscription fibers are not tracked explicitly. When\n+ * a rebuilt instance\'s old child scope closes, its PubSub shuts\n+ * down and our `Stream.runForEach` fiber exits naturally.\n+ */\n+ const syncLiveSources = syncSemaphore.withPermits(1)(\n+ Effect.gen(function* () {\n+ const instances = yield* instanceRegistry.listInstances;\n+ const unavailableProviders = yield* instanceRegistry.listUnavailable;\n+ const nextByInstance = new Map<ProviderInstanceId, ProviderInstance>(\n+ instances.map((instance) => [instance.instanceId, instance] as const),\n+ );\n+ const knownInstanceIds = new Set<ProviderInstanceId>(nextByInstance.keys());\n+ for (const provider of unavailableProviders) {\n+ knownInstanceIds.add(snapshotInstanceKey(provider));\n+ }\n+ const previousSubs = yield* Ref.get(liveSubsRef);\n+\n+ // Carry over subscriptions for instances whose identity is\n+ // unchanged (reconcile treated them as no-op). Instances that\n+ // disappeared, or were rebuilt with a different reference,\n+ // fall through to the "newly-added" branch below.\n+ const carriedOver = new Map<ProviderInstanceId, ProviderInstance>();\n+ for (const [instanceId, previousInstance] of previousSubs) {\n+ const nextInstance = nextByInstance.get(instanceId);\n+ if (nextInstance !== undefined && nextInstance === previousInstance) {\n+ carriedOver.set(instanceId, previousInstance);\n+ }\n+ }\n+\n+ // Collect new/rebuilt instances in `nextByInstance` insertion\n+ // order (which preserves settings-author order).\n+ const newlyAdded: Array<readonly [ProviderInstanceId, ProviderInstance]> = [];\n+ for (const [instanceId, instance] of nextByInstance) {\n+ if (carriedOver.has(instanceId)) {\n+ continue;\n+ }\n+ newlyAdded.push([instanceId, instance] as const);\n+ }\n+\n+ // Fork long-lived subscriptions to each new/rebuilt instance\'s\n+ // change stream BEFORE kicking off refreshes — if the driver\'s\n+ // own initial probe (line 140 in `makeManagedServerProvider`)\n+ // wins the refreshSemaphore race, its PubSub publish must land\n+ // in an active subscriber or the result is dropped.\n+ for (const [, instance] of newlyAdded) {\n+ const source = buildSnapshotSource(instance);\n+ yield* Stream.runForEach(source.streamChanges, (provider) =>\n+ correlateSnapshotWithSource(source, provider).pipe(Effect.flatMap(syncProvider)),\n+ ).pipe(Effect.forkScoped);\n+ }\n+\n+ // Force-refresh every new/rebuilt instance in parallel and wait\n+ // for them all to complete. The refresh\'s result is piped\n+ // directly into `syncProvider`, so `providersRef` is populated\n+ // deterministically by the time this block returns — regardless\n+ // of PubSub subscription timing. Failures are logged and\n+ // swallowed so one bad driver can\'t wedge the whole registry.\n+ yield* Effect.forEach(\n+ newlyAdded,\n+ ([, instance]) =>\n+ refreshOneSource(buildSnapshotSource(instance)).pipe(Effect.ignoreCause({ log: true })),\n+ { concurrency: "unbounded", discard: true },\n+ );\n+ yield* upsertProviders(unavailableProviders, {\n+ persist: false,\n+ replace: true,\n+ });\n+\n+ const nextSubs = new Map(carriedOver);\n+ for (const [instanceId, instance] of newlyAdded) {\n+ nextSubs.set(instanceId, instance);\n+ }\n+ yield* Ref.set(liveSubsRef, nextSubs);\n+\n+ // Drop aggregator state for instances that have disappeared —\n+ // otherwise the UI would keep rendering ghosts.\n+ const [previousProviders, providers] = yield* Ref.modify(\n+ providersRef,\n+ (previousProviders) => {\n+ const providers = orderProviderSnapshots(\n+ previousProviders.filter((provider) =>\n+ knownInstanceIds.has(snapshotInstanceKey(provider)),\n+ ),\n+ );\n+ return [[previousProviders, providers] as const, providers];\n+ },\n+ );\n+ if (haveProvidersChanged(previousProviders, providers)) {\n+ yield* PubSub.publish(changesPubSub, providers);\n+ }\n+ }),\n );\n- yield* loadProviders(providerSources).pipe(\n- Effect.flatMap((providers) => upsertProviders(providers, { publish: false })),\n+ const syncLiveSourcesAndContinue = syncLiveSources.pipe(\n+ Effect.catchCause((cause) => {\n+ if (Cause.hasInterruptsOnly(cause)) {\n+ return Effect.interrupt;\n+ }\n+ return Effect.logError(\n+ "provider registry instance sync failed; keeping subscription alive",\n+ {\n+ cause: Cause.pretty(cause),\n+ },\n+ );\n+ }),\n );\n \n+ // Seed `providersRef` with the boot-time fallback snapshots so\n+ // consumers calling `getProviders` immediately after layer build see\n+ // a populated list — even before the first `syncLiveSources` refresh\n+ // resolves. Cached snapshots (already in `providersRef`) merge with\n+ // these via `upsertProviders` so on-disk state wins where present\n+ // and pending fallbacks fill the gaps.\n+ yield* upsertProviders(fallbackProviders, { publish: false });\n+ // Subscribe to registry mutations BEFORE running the initial sync.\n+ // `subscribeChanges` acquires the dequeue synchronously in this\n+ // fibre; the subscription is active the instant this `yield*`\n+ // returns. Forking the consumer loop later cannot lose a publish\n+ // because no publish can reach a not-yet-subscribed dequeue.\n+ //\n+ // (Contrast with the pre-fix code that did\n+ // `Stream.runForEach(instanceRegistry.streamChanges, …).pipe(Effect.forkScoped)`.\n+ // `Stream.fromPubSub` defers `PubSub.subscribe` to stream start,\n+ // and `forkScoped` only schedules the fibre — so a reconcile that\n+ // published between "fibre scheduled" and "fibre starts running"\n+ // was dropped, which made any settings change that replaced an\n+ // instance never propagate to the aggregator\'s `providersRef`.)\n+ // Subscribe to registry mutations BEFORE running the initial sync.\n+ // `subscribeChanges` acquires the `PubSub.Subscription` synchronously\n+ // in this fibre; the subscription is registered with the PubSub the\n+ // instant this `yield*` returns, so any subsequent publish is\n+ // buffered in the subscription regardless of when the consumer\n+ // fibre below actually starts running.\n+ //\n+ // (Contrast with the pre-fix code that did\n+ // `Stream.runForEach(instanceRegistry.streamChanges, …).pipe(Effect.forkScoped)`.\n+ // `instanceRegistry.streamChanges` is `Stream.fromPubSub(changes)`,\n+ // which defers `PubSub.subscribe` to stream start. `forkScoped` only\n+ // schedules the consumer fibre — so a reconcile that published\n+ // between "fibre scheduled" and "fibre starts running + subscribes"\n+ // was dropped, which made any settings change that replaced an\n+ // instance never propagate to the aggregator\'s `providersRef`.)\n+ const instanceChanges = yield* instanceRegistry.subscribeChanges;\n+ // Initial sync: subscribe + kick off refreshes for every instance\n+ // present at boot. Run synchronously so consumers pulling immediately\n+ // after the layer build see the correct aggregator state.\n+ yield* syncLiveSources;\n+ // React to registry mutations — instance added / removed / rebuilt.\n+ // `Stream.fromSubscription` builds a stream over the pre-acquired\n+ // subscription rather than subscribing on stream start, which is\n+ // what closes the race.\n+ yield* Stream.runForEach(\n+ Stream.fromSubscription(instanceChanges),\n+ () => syncLiveSourcesAndContinue,\n+ ).pipe(Effect.forkScoped);\n+\n+ const recoverRefreshFailure = Effect.fn("recoverRefreshFailure")(function* (\n+ cause: Cause.Cause<unknown>,\n+ ) {\n+ if (Cause.hasInterruptsOnly(cause)) {\n+ return yield* Effect.interrupt;\n+ }\n+ yield* Effect.logError("provider registry refresh failed; preserving cached providers", {\n+ cause: Cause.pretty(cause),\n+ });\n+ return yield* Ref.get(providersRef);\n+ });\n+\n return {\n getProviders: Ref.get(providersRef),\n- refresh: (provider?: ProviderKind) =>\n- refresh(provider).pipe(\n- Effect.tapError(Effect.logError),\n- Effect.orElseSucceed(() => [] as ReadonlyArray<ServerProvider>),\n- ),\n+ refresh: (provider?: ProviderDriverKind) =>\n+ refresh(provider).pipe(Effect.catchCause(recoverRefreshFailure)),\n+ refreshInstance: (instanceId: ProviderInstanceId) =>\n+ refreshInstance(instanceId).pipe(Effect.catchCause(recoverRefreshFailure)),\n get streamChanges() {\n return Stream.fromPubSub(changesPubSub);\n },\n } satisfies ProviderRegistryShape;\n }),\n );\n-\n-export const ProviderRegistryLive = Layer.unwrap(\n- Effect.sync(() =>\n- ProviderRegistryLiveBase.pipe(\n- Layer.provideMerge(CursorProviderLive),\n- Layer.provideMerge(CodexProviderLive),\n- Layer.provideMerge(ClaudeProviderLive),\n- Layer.provideMerge(OpenCodeProviderLive),\n- Layer.provideMerge(OpenCodeRuntimeLive),\n- ),\n- ),\n-);\ndiff --git a/apps/server/src/provider/Layers/ProviderService.test.ts b/apps/server/src/provider/Layers/ProviderService.test.ts\nindex 09606ba35a..7e77125143 100644\n--- a/apps/server/src/provider/Layers/ProviderService.test.ts\n+++ b/apps/server/src/provider/Layers/ProviderService.test.ts\n@@ -12,7 +12,8 @@ import type {\n import {\n ApprovalRequestId,\n EventId,\n- type ProviderKind,\n+ ProviderDriverKind,\n+ ProviderInstanceId,\n ProviderSessionStartInput,\n ThreadId,\n TurnId,\n@@ -20,20 +21,25 @@ import {\n import { createModelSelection } from "@t3tools/shared/model";\n import { it, assert, vi } from "@effect/vitest";\n \n-import { Effect, Fiber, Layer, Metric, Option, PubSub, Ref, Stream } from "effect";\n+import { Effect, Exit, Fiber, Layer, Metric, Option, PubSub, Ref, Scope, Stream } from "effect";\n import * as SqlClient from "effect/unstable/sql/SqlClient";\n \n import {\n+ ProviderAdapterRequestError,\n ProviderAdapterSessionNotFoundError,\n ProviderUnsupportedError,\n ProviderValidationError,\n type ProviderAdapterError,\n } from "../Errors.ts";\n import type { ProviderAdapterShape } from "../Services/ProviderAdapter.ts";\n-import { ProviderAdapterRegistry } from "../Services/ProviderAdapterRegistry.ts";\n+import {\n+ ProviderAdapterRegistry,\n+ type ProviderAdapterRegistryShape,\n+} from "../Services/ProviderAdapterRegistry.ts";\n import { ProviderService } from "../Services/ProviderService.ts";\n import { ProviderSessionDirectory } from "../Services/ProviderSessionDirectory.ts";\n import { makeProviderServiceLive } from "./ProviderService.ts";\n+import { NoOpProviderEventLoggers, ProviderEventLoggers } from "./ProviderEventLoggers.ts";\n import { ProviderSessionDirectoryLive } from "./ProviderSessionDirectory.ts";\n import * as NodeServices from "@effect/platform-node/NodeServices";\n import { ProviderSessionRuntimeRepositoryLive } from "../../persistence/Layers/ProviderSessionRuntime.ts";\n@@ -44,6 +50,7 @@ import {\n } from "../../persistence/Layers/Sqlite.ts";\n import { ServerSettingsService } from "../../serverSettings.ts";\n import { AnalyticsService } from "../../telemetry/Services/AnalyticsService.ts";\n+import { makeAdapterRegistryMock } from "../testUtils/providerAdapterRegistryMock.ts";\n \n const defaultServerSettingsLayer = ServerSettingsService.layerTest();\n \n@@ -51,11 +58,16 @@ const asRequestId = (value: string): ApprovalRequestId => ApprovalRequestId.make\n const asEventId = (value: string): EventId => EventId.make(value);\n const asThreadId = (value: string): ThreadId => ThreadId.make(value);\n const asTurnId = (value: string): TurnId => TurnId.make(value);\n+const codexInstanceId = ProviderInstanceId.make("codex");\n+const claudeAgentInstanceId = ProviderInstanceId.make("claudeAgent");\n+const CODEX_DRIVER = ProviderDriverKind.make("codex");\n+const CLAUDE_AGENT_DRIVER = ProviderDriverKind.make("claudeAgent");\n+const CURSOR_DRIVER = ProviderDriverKind.make("cursor");\n \n type LegacyProviderRuntimeEvent = {\n readonly type: string;\n readonly eventId: EventId;\n- readonly provider: ProviderKind;\n+ readonly provider: ProviderDriverKind;\n readonly createdAt: string;\n readonly threadId: ThreadId;\n readonly turnId?: string | undefined;\n@@ -65,7 +77,7 @@ type LegacyProviderRuntimeEvent = {\n readonly [key: string]: unknown;\n };\n \n-function makeFakeCodexAdapter(provider: ProviderKind = "codex") {\n+function makeFakeCodexAdapter(provider: ProviderDriverKind = CODEX_DRIVER) {\n const sessions = new Map<ThreadId, ProviderSession>();\n const runtimeEventPubSub = Effect.runSync(PubSub.unbounded<ProviderRuntimeEvent>());\n \n@@ -74,10 +86,15 @@ function makeFakeCodexAdapter(provider: ProviderKind = "codex") {\n const now = new Date().toISOString();\n const session: ProviderSession = {\n provider,\n+ ...(input.providerInstanceId !== undefined\n+ ? { providerInstanceId: input.providerInstanceId }\n+ : {}),\n status: "ready",\n runtimeMode: input.runtimeMode,\n threadId: input.threadId,\n- resumeCursor: input.resumeCursor ?? { opaque: `resume-${String(input.threadId)}` },\n+ resumeCursor: input.resumeCursor ?? {\n+ opaque: `resume-${String(input.threadId)}`,\n+ },\n cwd: input.cwd ?? process.cwd(),\n createdAt: now,\n updatedAt: now,\n@@ -245,19 +262,13 @@ const hasMetricSnapshot = (\n \n function makeProviderServiceLayer() {\n const codex = makeFakeCodexAdapter();\n- const claude = makeFakeCodexAdapter("claudeAgent");\n- const cursor = makeFakeCodexAdapter("cursor");\n- const registry: typeof ProviderAdapterRegistry.Service = {\n- getByProvider: (provider) =>\n- provider === "codex"\n- ? Effect.succeed(codex.adapter)\n- : provider === "claudeAgent"\n- ? Effect.succeed(claude.adapter)\n- : provider === "cursor"\n- ? Effect.succeed(cursor.adapter)\n- : Effect.fail(new ProviderUnsupportedError({ provider })),\n- listProviders: () => Effect.succeed(["codex", "claudeAgent", "cursor"]),\n- };\n+ const claude = makeFakeCodexAdapter(CLAUDE_AGENT_DRIVER);\n+ const cursor = makeFakeCodexAdapter(CURSOR_DRIVER);\n+ const registry = makeAdapterRegistryMock({\n+ [ProviderDriverKind.make("codex")]: codex.adapter,\n+ [ProviderDriverKind.make("claudeAgent")]: claude.adapter,\n+ [ProviderDriverKind.make("cursor")]: cursor.adapter,\n+ });\n \n const providerAdapterLayer = Layer.succeed(ProviderAdapterRegistry, registry);\n const runtimeRepositoryLayer = ProviderSessionRuntimeRepositoryLive.pipe(\n@@ -272,6 +283,7 @@ function makeProviderServiceLayer() {\n Layer.provide(directoryLayer),\n Layer.provide(defaultServerSettingsLayer),\n Layer.provideMerge(AnalyticsService.layerTest),\n+ Layer.provide(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)),\n ),\n directoryLayer,\n \n@@ -288,27 +300,76 @@ function makeProviderServiceLayer() {\n };\n }\n \n+it.effect("ProviderServiceLive catches stopAll failures during shutdown", () =>\n+ Effect.gen(function* () {\n+ const codex = makeFakeCodexAdapter();\n+ codex.stopAll.mockImplementation(() =>\n+ Effect.fail(\n+ new ProviderAdapterRequestError({\n+ provider: String(CODEX_DRIVER),\n+ method: "stopAll",\n+ detail: "simulated stopAll failure",\n+ }),\n+ ),\n+ );\n+ const registry = makeAdapterRegistryMock({\n+ [CODEX_DRIVER]: codex.adapter,\n+ });\n+ const providerAdapterLayer = Layer.succeed(ProviderAdapterRegistry, registry);\n+ const runtimeRepositoryLayer = ProviderSessionRuntimeRepositoryLive.pipe(\n+ Layer.provide(SqlitePersistenceMemory),\n+ );\n+ const directoryLayer = ProviderSessionDirectoryLive.pipe(Layer.provide(runtimeRepositoryLayer));\n+ const providerLayer = Layer.mergeAll(\n+ makeProviderServiceLive().pipe(\n+ Layer.provide(providerAdapterLayer),\n+ Layer.provide(directoryLayer),\n+ Layer.provide(defaultServerSettingsLayer),\n+ Layer.provideMerge(AnalyticsService.layerTest),\n+ Layer.provide(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)),\n+ ),\n+ directoryLayer,\n+ runtimeRepositoryLayer,\n+ NodeServices.layer,\n+ );\n+ const scope = yield* Scope.make();\n+ const runtimeServices = yield* Layer.build(providerLayer).pipe(Scope.provide(scope));\n+\n+ yield* Effect.gen(function* () {\n+ yield* ProviderService;\n+ }).pipe(Effect.provide(runtimeServices));\n+ const closeExit = yield* Scope.close(scope, Exit.void).pipe(Effect.exit);\n+\n+ assert.equal(Exit.isSuccess(closeExit), true);\n+ assert.equal(codex.stopAll.mock.calls.length, 1);\n+ }),\n+);\n+\n it.effect("ProviderServiceLive rejects new sessions for disabled providers", () =>\n Effect.gen(function* () {\n const codex = makeFakeCodexAdapter();\n- const claude = makeFakeCodexAdapter("claudeAgent");\n- const registry: typeof ProviderAdapterRegistry.Service = {\n- getByProvider: (provider) =>\n- provider === "codex"\n- ? Effect.succeed(codex.adapter)\n- : provider === "claudeAgent"\n- ? Effect.succeed(claude.adapter)\n- : Effect.fail(new ProviderUnsupportedError({ provider })),\n- listProviders: () => Effect.succeed(["codex", "claudeAgent"]),\n+ const claude = makeFakeCodexAdapter(CLAUDE_AGENT_DRIVER);\n+ const registryBase = makeAdapterRegistryMock({\n+ [CODEX_DRIVER]: codex.adapter,\n+ [CLAUDE_AGENT_DRIVER]: claude.adapter,\n+ });\n+ const registry: ProviderAdapterRegistryShape = {\n+ ...registryBase,\n+ getInstanceInfo: (instanceId) =>\n+ instanceId === claudeAgentInstanceId\n+ ? Effect.succeed({\n+ instanceId,\n+ driverKind: CLAUDE_AGENT_DRIVER,\n+ displayName: undefined,\n+ enabled: false,\n+ continuationIdentity: {\n+ driverKind: CLAUDE_AGENT_DRIVER,\n+ continuationKey: "claudeAgent:instance:claudeAgent",\n+ },\n+ })\n+ : registryBase.getInstanceInfo(instanceId),\n };\n const providerAdapterLayer = Layer.succeed(ProviderAdapterRegistry, registry);\n- const serverSettingsLayer = ServerSettingsService.layerTest({\n- providers: {\n- claudeAgent: {\n- enabled: false,\n- },\n- },\n- });\n const runtimeRepositoryLayer = ProviderSessionRuntimeRepositoryLive.pipe(\n Layer.provide(SqlitePersistenceMemory),\n );\n@@ -316,15 +377,17 @@ it.effect("ProviderServiceLive rejects new sessions for disabled providers", ()\n const providerLayer = makeProviderServiceLive().pipe(\n Layer.provide(providerAdapterLayer),\n Layer.provide(directoryLayer),\n- Layer.provide(serverSettingsLayer),\n+ Layer.provide(defaultServerSettingsLayer),\n Layer.provide(AnalyticsService.layerTest),\n+ Layer.provide(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)),\n );\n \n const failure = yield* Effect.flip(\n Effect.gen(function* () {\n const provider = yield* ProviderService;\n return yield* provider.startSession(asThreadId("thread-disabled"), {\n- provider: "claudeAgent",\n+ provider: ProviderDriverKind.make("claudeAgent"),\n+ providerInstanceId: claudeAgentInstanceId,\n threadId: asThreadId("thread-disabled"),\n runtimeMode: "full-access",\n });\n@@ -332,11 +395,149 @@ it.effect("ProviderServiceLive rejects new sessions for disabled providers", ()\n );\n \n assert.instanceOf(failure, ProviderValidationError);\n- assert.include(failure.issue, "Provider \'claudeAgent\' is disabled in T3 Code settings.");\n+ assert.include(failure.issue, "Provider instance \'claudeAgent\' is disabled");\n assert.equal(claude.startSession.mock.calls.length, 0);\n }).pipe(Effect.provide(NodeServices.layer)),\n );\n \n+it.effect(\n+ "ProviderServiceLive allows enabled custom instances when legacy driver is disabled",\n+ () =>\n+ Effect.gen(function* () {\n+ const instanceId = ProviderInstanceId.make("codex_personal");\n+ const driverKind = CODEX_DRIVER;\n+ const codex = makeFakeCodexAdapter();\n+ const unsupported = () =>\n+ new ProviderUnsupportedError({\n+ provider: driverKind,\n+ });\n+ const registry: ProviderAdapterRegistryShape = {\n+ getByInstance: (requestedInstanceId) =>\n+ requestedInstanceId === instanceId\n+ ? Effect.succeed(codex.adapter)\n+ : Effect.fail(unsupported()),\n+ getInstanceInfo: (requestedInstanceId) =>\n+ requestedInstanceId === instanceId\n+ ? Effect.succeed({\n+ instanceId,\n+ driverKind,\n+ displayName: "Codex Personal",\n+ enabled: true,\n+ continuationIdentity: {\n+ driverKind,\n+ continuationKey: "codex:/Users/example/.codex",\n+ },\n+ })\n+ : Effect.fail(unsupported()),\n+ listInstances: () => Effect.succeed([instanceId]),\n+ listProviders: () => Effect.succeed([driverKind] as const),\n+ streamChanges: Stream.empty,\n+ subscribeChanges: Effect.flatMap(PubSub.unbounded<void>(), (pubsub) =>\n+ PubSub.subscribe(pubsub),\n+ ),\n+ };\n+ const providerAdapterLayer = Layer.succeed(ProviderAdapterRegistry, registry);\n+ const serverSettingsLayer = ServerSettingsService.layerTest({\n+ providers: {\n+ codex: {\n+ enabled: false,\n+ },\n+ },\n+ });\n+ const runtimeRepositoryLayer = ProviderSessionRuntimeRepositoryLive.pipe(\n+ Layer.provide(SqlitePersistenceMemory),\n+ );\n+ const directoryLayer = ProviderSessionDirectoryLive.pipe(\n+ Layer.provide(runtimeRepositoryLayer),\n+ );\n+ const providerLayer = makeProviderServiceLive().pipe(\n+ Layer.provide(providerAdapterLayer),\n+ Layer.provide(directoryLayer),\n+ Layer.provide(serverSettingsLayer),\n+ Layer.provide(AnalyticsService.layerTest),\n+ Layer.provide(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)),\n+ );\n+\n+ const session = yield* Effect.gen(function* () {\n+ const provider = yield* ProviderService;\n+ return yield* provider.startSession(asThreadId("thread-enabled-custom"), {\n+ provider: driverKind,\n+ providerInstanceId: instanceId,\n+ threadId: asThreadId("thread-enabled-custom"),\n+ runtimeMode: "full-access",\n+ });\n+ }).pipe(Effect.provide(providerLayer));\n+\n+ assert.equal(session.providerInstanceId, instanceId);\n+ assert.equal(codex.startSession.mock.calls.length, 1);\n+ }).pipe(Effect.provide(NodeServices.layer)),\n+);\n+\n+it.effect("ProviderServiceLive rejects new sessions for disabled custom instances", () =>\n+ Effect.gen(function* () {\n+ const instanceId = ProviderInstanceId.make("codex_personal");\n+ const driverKind = ProviderDriverKind.make("codex");\n+ const codex = makeFakeCodexAdapter();\n+ const unsupported = () =>\n+ new ProviderUnsupportedError({\n+ provider: ProviderDriverKind.make("codex"),\n+ });\n+ const registry: ProviderAdapterRegistryShape = {\n+ getByInstance: (requestedInstanceId) =>\n+ requestedInstanceId === instanceId\n+ ? Effect.succeed(codex.adapter)\n+ : Effect.fail(unsupported()),\n+ getInstanceInfo: (requestedInstanceId) =>\n+ requestedInstanceId === instanceId\n+ ? Effect.succeed({\n+ instanceId,\n+ driverKind,\n+ displayName: "Codex Personal",\n+ enabled: false,\n+ continuationIdentity: {\n+ driverKind,\n+ continuationKey: "codex:/Users/example/.codex",\n+ },\n+ })\n+ : Effect.fail(unsupported()),\n+ listInstances: () => Effect.succeed([instanceId]),\n+ listProviders: () => Effect.succeed([CODEX_DRIVER] as const),\n+ streamChanges: Stream.empty,\n+ subscribeChanges: Effect.flatMap(PubSub.unbounded<void>(), (pubsub) =>\n+ PubSub.subscribe(pubsub),\n+ ),\n+ };\n+ const providerAdapterLayer = Layer.succeed(ProviderAdapterRegistry, registry);\n+ const runtimeRepositoryLayer = ProviderSessionRuntimeRepositoryLive.pipe(\n+ Layer.provide(SqlitePersistenceMemory),\n+ );\n+ const directoryLayer = ProviderSessionDirectoryLive.pipe(Layer.provide(runtimeRepositoryLayer));\n+ const providerLayer = makeProviderServiceLive().pipe(\n+ Layer.provide(providerAdapterLayer),\n+ Layer.provide(directoryLayer),\n+ Layer.provide(defaultServerSettingsLayer),\n+ Layer.provide(AnalyticsService.layerTest),\n+ Layer.provide(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)),\n+ );\n+\n+ const failure = yield* Effect.flip(\n+ Effect.gen(function* () {\n+ const provider = yield* ProviderService;\n+ return yield* provider.startSession(asThreadId("thread-disabled-instance"), {\n+ provider: ProviderDriverKind.make("codex"),\n+ providerInstanceId: instanceId,\n+ threadId: asThreadId("thread-disabled-instance"),\n+ runtimeMode: "full-access",\n+ });\n+ }).pipe(Effect.provide(providerLayer)),\n+ );\n+\n+ assert.instanceOf(failure, ProviderValidationError);\n+ assert.include(failure.issue, "Provider instance \'codex_personal\' is disabled");\n+ assert.equal(codex.startSession.mock.calls.length, 0);\n+ }).pipe(Effect.provide(NodeServices.layer)),\n+);\n+\n const routing = makeProviderServiceLayer();\n \n it.effect("ProviderServiceLive writes canonical events to the emitting thread segment", () =>\n@@ -344,13 +545,9 @@ it.effect("ProviderServiceLive writes canonical events to the emitting thread se\n const codex = makeFakeCodexAdapter();\n const canonicalEvents: ProviderRuntimeEvent[] = [];\n const canonicalThreadIds: Array<string | null> = [];\n- const registry: typeof ProviderAdapterRegistry.Service = {\n- getByProvider: (provider) =>\n- provider === "codex"\n- ? Effect.succeed(codex.adapter)\n- : Effect.fail(new ProviderUnsupportedError({ provider })),\n- listProviders: () => Effect.succeed(["codex"]),\n- };\n+ const registry = makeAdapterRegistryMock({\n+ [ProviderDriverKind.make("codex")]: codex.adapter,\n+ });\n const runtimeRepositoryLayer = ProviderSessionRuntimeRepositoryLive.pipe(\n Layer.provide(SqlitePersistenceMemory),\n );\n@@ -370,6 +567,7 @@ it.effect("ProviderServiceLive writes canonical events to the emitting thread se\n Layer.provide(directoryLayer),\n Layer.provide(defaultServerSettingsLayer),\n Layer.provide(AnalyticsService.layerTest),\n+ Layer.provide(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)),\n );\n \n yield* Effect.gen(function* () {\n@@ -377,7 +575,7 @@ it.effect("ProviderServiceLive writes canonical events to the emitting thread se\n yield* sleep(10);\n codex.emit({\n eventId: asEventId("evt-canonical-thread-segment"),\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n threadId: asThreadId("thread-canonical-thread-segment"),\n createdAt: new Date().toISOString(),\n type: "turn.completed",\n@@ -400,13 +598,9 @@ it.effect("ProviderServiceLive keeps persisted resumable sessions on startup", (\n const dbPath = path.join(tempDir, "orchestration.sqlite");\n \n const codex = makeFakeCodexAdapter();\n- const registry: typeof ProviderAdapterRegistry.Service = {\n- getByProvider: (provider) =>\n- provider === "codex"\n- ? Effect.succeed(codex.adapter)\n- : Effect.fail(new ProviderUnsupportedError({ provider })),\n- listProviders: () => Effect.succeed(["codex"]),\n- };\n+ const registry = makeAdapterRegistryMock({\n+ [ProviderDriverKind.make("codex")]: codex.adapter,\n+ });\n \n const persistenceLayer = makeSqlitePersistenceLive(dbPath);\n const runtimeRepositoryLayer = ProviderSessionRuntimeRepositoryLive.pipe(\n@@ -417,7 +611,8 @@ it.effect("ProviderServiceLive keeps persisted resumable sessions on startup", (\n yield* Effect.gen(function* () {\n const directory = yield* ProviderSessionDirectory;\n yield* directory.upsert({\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n+ providerInstanceId: codexInstanceId,\n threadId: ThreadId.make("thread-stale"),\n });\n }).pipe(Effect.provide(directoryLayer));\n@@ -427,6 +622,7 @@ it.effect("ProviderServiceLive keeps persisted resumable sessions on startup", (\n Layer.provide(directoryLayer),\n Layer.provide(defaultServerSettingsLayer),\n Layer.provide(AnalyticsService.layerTest),\n+ Layer.provide(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)),\n );\n \n yield* Effect.gen(function* () {\n@@ -441,7 +637,9 @@ it.effect("ProviderServiceLive keeps persisted resumable sessions on startup", (\n \n const runtime = yield* Effect.gen(function* () {\n const repository = yield* ProviderSessionRuntimeRepository;\n- return yield* repository.getByThreadId({ threadId: asThreadId("thread-stale") });\n+ return yield* repository.getByThreadId({\n+ threadId: asThreadId("thread-stale"),\n+ });\n }).pipe(Effect.provide(runtimeRepositoryLayer));\n assert.equal(Option.isSome(runtime), true);\n \n@@ -471,13 +669,9 @@ it.effect(\n );\n \n const firstCodex = makeFakeCodexAdapter();\n- const firstRegistry: typeof ProviderAdapterRegistry.Service = {\n- getByProvider: (provider) =>\n- provider === "codex"\n- ? Effect.succeed(firstCodex.adapter)\n- : Effect.fail(new ProviderUnsupportedError({ provider })),\n- listProviders: () => Effect.succeed(["codex"]),\n- };\n+ const firstRegistry = makeAdapterRegistryMock({\n+ [ProviderDriverKind.make("codex")]: firstCodex.adapter,\n+ });\n \n const firstDirectoryLayer = ProviderSessionDirectoryLive.pipe(\n Layer.provide(runtimeRepositoryLayer),\n@@ -487,6 +681,7 @@ it.effect(\n Layer.provide(firstDirectoryLayer),\n Layer.provide(defaultServerSettingsLayer),\n Layer.provide(AnalyticsService.layerTest),\n+ Layer.provide(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)),\n );\n const updatedResumeCursor = {\n threadId: asThreadId("thread-1"),\n@@ -499,7 +694,8 @@ it.effect(\n const provider = yield* ProviderService;\n const threadId = asThreadId("thread-1");\n const session = yield* provider.startSession(threadId, {\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n+ providerInstanceId: codexInstanceId,\n cwd: "/tmp/project",\n runtimeMode: "full-access",\n threadId,\n@@ -515,7 +711,9 @@ it.effect(\n \n const persistedAfterStopAll = yield* Effect.gen(function* () {\n const repository = yield* ProviderSessionRuntimeRepository;\n- return yield* repository.getByThreadId({ threadId: startedSession.threadId });\n+ return yield* repository.getByThreadId({\n+ threadId: startedSession.threadId,\n+ });\n }).pipe(Effect.provide(runtimeRepositoryLayer));\n assert.equal(Option.isSome(persistedAfterStopAll), true);\n if (Option.isSome(persistedAfterStopAll)) {\n@@ -524,13 +722,9 @@ it.effect(\n }\n \n const secondCodex = makeFakeCodexAdapter();\n- const secondRegistry: typeof ProviderAdapterRegistry.Service = {\n- getByProvider: (provider) =>\n- provider === "codex"\n- ? Effect.succeed(secondCodex.adapter)\n- : Effect.fail(new ProviderUnsupportedError({ provider })),\n- listProviders: () => Effect.succeed(["codex"]),\n- };\n+ const secondRegistry = makeAdapterRegistryMock({\n+ [ProviderDriverKind.make("codex")]: secondCodex.adapter,\n+ });\n const secondDirectoryLayer = ProviderSessionDirectoryLive.pipe(\n Layer.provide(runtimeRepositoryLayer),\n );\n@@ -539,6 +733,7 @@ it.effect(\n Layer.provide(secondDirectoryLayer),\n Layer.provide(defaultServerSettingsLayer),\n Layer.provide(AnalyticsService.layerTest),\n+ Layer.provide(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)),\n );\n \n secondCodex.startSession.mockClear();\n@@ -582,7 +777,8 @@ routing.layer("ProviderServiceLive routing", (it) => {\n const provider = yield* ProviderService;\n \n const session = yield* provider.startSession(asThreadId("thread-1"), {\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n+ providerInstanceId: codexInstanceId,\n threadId: asThreadId("thread-1"),\n cwd: "/tmp/project",\n runtimeMode: "full-access",\n@@ -667,7 +863,8 @@ routing.layer("ProviderServiceLive routing", (it) => {\n const provider = yield* ProviderService;\n \n const initial = yield* provider.startSession(asThreadId("thread-1"), {\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n+ providerInstanceId: codexInstanceId,\n threadId: asThreadId("thread-1"),\n cwd: "/tmp/project",\n runtimeMode: "full-access",\n@@ -708,7 +905,8 @@ routing.layer("ProviderServiceLive routing", (it) => {\n const runtimeRepository = yield* ProviderSessionRuntimeRepository;\n \n const initial = yield* provider.startSession(asThreadId("thread-reap-preserve"), {\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n+ providerInstanceId: codexInstanceId,\n threadId: asThreadId("thread-reap-preserve"),\n cwd: "/tmp/project-reap-preserve",\n runtimeMode: "full-access",\n@@ -758,7 +956,8 @@ routing.layer("ProviderServiceLive routing", (it) => {\n const provider = yield* ProviderService;\n \n const session = yield* provider.startSession(asThreadId("thread-claude"), {\n- provider: "claudeAgent",\n+ provider: ProviderDriverKind.make("claudeAgent"),\n+ providerInstanceId: claudeAgentInstanceId,\n threadId: asThreadId("thread-claude"),\n cwd: "/tmp/project-claude",\n runtimeMode: "full-access",\n@@ -769,20 +968,57 @@ routing.layer("ProviderServiceLive routing", (it) => {\n const startInput = routing.claude.startSession.mock.calls[0]?.[0];\n assert.equal(typeof startInput === "object" && startInput !== null, true);\n if (startInput && typeof startInput === "object") {\n- const startPayload = startInput as { provider?: string; cwd?: string };\n+ const startPayload = startInput as {\n+ provider?: string;\n+ providerInstanceId?: ProviderInstanceId;\n+ cwd?: string;\n+ };\n assert.equal(startPayload.provider, "claudeAgent");\n+ assert.equal(startPayload.providerInstanceId, claudeAgentInstanceId);\n assert.equal(startPayload.cwd, "/tmp/project-claude");\n }\n }),\n );\n \n+ it.effect("dies when an active session conflicts with its persisted binding", () =>\n+ Effect.gen(function* () {\n+ const provider = yield* ProviderService;\n+ const directory = yield* ProviderSessionDirectory;\n+ const threadId = asThreadId("thread-binding-mismatch");\n+\n+ yield* provider.startSession(threadId, {\n+ provider: ProviderDriverKind.make("codex"),\n+ providerInstanceId: codexInstanceId,\n+ threadId,\n+ cwd: "/tmp/project-binding-mismatch",\n+ runtimeMode: "full-access",\n+ });\n+ yield* directory.upsert({\n+ threadId,\n+ provider: ProviderDriverKind.make("claudeAgent"),\n+ providerInstanceId: claudeAgentInstanceId,\n+ runtimeMode: "full-access",\n+ });\n+\n+ const exit = yield* Effect.exit(provider.listSessions());\n+ assert.equal(Exit.hasDies(exit), true);\n+ yield* directory.upsert({\n+ threadId,\n+ provider: ProviderDriverKind.make("codex"),\n+ providerInstanceId: codexInstanceId,\n+ runtimeMode: "full-access",\n+ });\n+ }),\n+ );\n+\n it.effect("stops stale sessions in other providers after a successful replacement start", () =>\n Effect.gen(function* () {\n const provider = yield* ProviderService;\n const threadId = asThreadId("thread-provider-replacement");\n \n const codexSession = yield* provider.startSession(threadId, {\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n+ providerInstanceId: codexInstanceId,\n threadId,\n cwd: "/tmp/project-provider-replacement",\n runtimeMode: "full-access",\n@@ -792,7 +1028,8 @@ routing.layer("ProviderServiceLive routing", (it) => {\n routing.claude.stopSession.mockClear();\n \n const claudeSession = yield* provider.startSession(threadId, {\n- provider: "claudeAgent",\n+ provider: ProviderDriverKind.make("claudeAgent"),\n+ providerInstanceId: claudeAgentInstanceId,\n threadId,\n cwd: "/tmp/project-provider-replacement",\n runtimeMode: "full-access",\n@@ -818,7 +1055,8 @@ routing.layer("ProviderServiceLive routing", (it) => {\n const provider = yield* ProviderService;\n \n const initial = yield* provider.startSession(asThreadId("thread-1"), {\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n+ providerInstanceId: codexInstanceId,\n threadId: asThreadId("thread-1"),\n cwd: "/tmp/project-send-turn",\n runtimeMode: "full-access",\n@@ -858,12 +1096,15 @@ routing.layer("ProviderServiceLive routing", (it) => {\n const provider = yield* ProviderService;\n \n const initial = yield* provider.startSession(asThreadId("thread-claude-send-turn"), {\n- provider: "claudeAgent",\n+ provider: ProviderDriverKind.make("claudeAgent"),\n+ providerInstanceId: claudeAgentInstanceId,\n threadId: asThreadId("thread-claude-send-turn"),\n cwd: "/tmp/project-claude-send-turn",\n- modelSelection: createModelSelection("claudeAgent", "claude-opus-4-6", [\n- { id: "effort", value: "max" },\n- ]),\n+ modelSelection: createModelSelection(\n+ ProviderInstanceId.make("claudeAgent"),\n+ "claude-opus-4-6",\n+ [{ id: "effort", value: "max" }],\n+ ),\n runtimeMode: "full-access",\n });\n \n@@ -892,7 +1133,9 @@ routing.layer("ProviderServiceLive routing", (it) => {\n assert.equal(startPayload.cwd, "/tmp/project-claude-send-turn");\n assert.deepEqual(\n startPayload.modelSelection,\n- createModelSelection("claudeAgent", "claude-opus-4-6", [{ id: "effort", value: "max" }]),\n+ createModelSelection(ProviderInstanceId.make("claudeAgent"), "claude-opus-4-6", [\n+ { id: "effort", value: "max" },\n+ ]),\n );\n assert.deepEqual(startPayload.resumeCursor, initial.resumeCursor);\n assert.equal(startPayload.threadId, initial.threadId);\n@@ -906,12 +1149,14 @@ routing.layer("ProviderServiceLive routing", (it) => {\n const provider = yield* ProviderService;\n \n yield* provider.startSession(asThreadId("thread-1"), {\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n+ providerInstanceId: codexInstanceId,\n threadId: asThreadId("thread-1"),\n runtimeMode: "full-access",\n });\n yield* provider.startSession(asThreadId("thread-2"), {\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n+ providerInstanceId: codexInstanceId,\n threadId: asThreadId("thread-2"),\n runtimeMode: "full-access",\n });\n@@ -931,7 +1176,8 @@ routing.layer("ProviderServiceLive routing", (it) => {\n \n const threadId = asThreadId("thread-runtime-status");\n const session = yield* provider.startSession(threadId, {\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n+ providerInstanceId: codexInstanceId,\n threadId,\n runtimeMode: "full-access",\n });\n@@ -977,14 +1223,10 @@ routing.layer("ProviderServiceLive routing", (it) => {\n Layer.provide(persistenceLayer),\n );\n \n- const firstClaude = makeFakeCodexAdapter("claudeAgent");\n- const firstRegistry: typeof ProviderAdapterRegistry.Service = {\n- getByProvider: (provider) =>\n- provider === "claudeAgent"\n- ? Effect.succeed(firstClaude.adapter)\n- : Effect.fail(new ProviderUnsupportedError({ provider })),\n- listProviders: () => Effect.succeed(["claudeAgent"]),\n- };\n+ const firstClaude = makeFakeCodexAdapter(CLAUDE_AGENT_DRIVER);\n+ const firstRegistry = makeAdapterRegistryMock({\n+ [ProviderDriverKind.make("claudeAgent")]: firstClaude.adapter,\n+ });\n const firstDirectoryLayer = ProviderSessionDirectoryLive.pipe(\n Layer.provide(runtimeRepositoryLayer),\n );\n@@ -993,12 +1235,14 @@ routing.layer("ProviderServiceLive routing", (it) => {\n Layer.provide(firstDirectoryLayer),\n Layer.provide(defaultServerSettingsLayer),\n Layer.provide(AnalyticsService.layerTest),\n+ Layer.provide(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)),\n );\n \n const initial = yield* Effect.gen(function* () {\n const provider = yield* ProviderService;\n return yield* provider.startSession(asThreadId("thread-claude-start"), {\n- provider: "claudeAgent",\n+ provider: ProviderDriverKind.make("claudeAgent"),\n+ providerInstanceId: claudeAgentInstanceId,\n threadId: asThreadId("thread-claude-start"),\n cwd: "/tmp/project-claude-start",\n runtimeMode: "full-access",\n@@ -1010,14 +1254,10 @@ routing.layer("ProviderServiceLive routing", (it) => {\n yield* provider.listSessions();\n }).pipe(Effect.provide(firstProviderLayer));\n \n- const secondClaude = makeFakeCodexAdapter("claudeAgent");\n- const secondRegistry: typeof ProviderAdapterRegistry.Service = {\n- getByProvider: (provider) =>\n- provider === "claudeAgent"\n- ? Effect.succeed(secondClaude.adapter)\n- : Effect.fail(new ProviderUnsupportedError({ provider })),\n- listProviders: () => Effect.succeed(["claudeAgent"]),\n- };\n+ const secondClaude = makeFakeCodexAdapter(CLAUDE_AGENT_DRIVER);\n+ const secondRegistry = makeAdapterRegistryMock({\n+ [ProviderDriverKind.make("claudeAgent")]: secondClaude.adapter,\n+ });\n const secondDirectoryLayer = ProviderSessionDirectoryLive.pipe(\n Layer.provide(runtimeRepositoryLayer),\n );\n@@ -1026,6 +1266,7 @@ routing.layer("ProviderServiceLive routing", (it) => {\n Layer.provide(secondDirectoryLayer),\n Layer.provide(defaultServerSettingsLayer),\n Layer.provide(AnalyticsService.layerTest),\n+ Layer.provide(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)),\n );\n \n secondClaude.startSession.mockClear();\n@@ -1033,7 +1274,8 @@ routing.layer("ProviderServiceLive routing", (it) => {\n yield* Effect.gen(function* () {\n const provider = yield* ProviderService;\n yield* provider.startSession(initial.threadId, {\n- provider: "claudeAgent",\n+ provider: ProviderDriverKind.make("claudeAgent"),\n+ providerInstanceId: claudeAgentInstanceId,\n threadId: initial.threadId,\n cwd: "/tmp/project-claude-start",\n runtimeMode: "full-access",\n@@ -1071,14 +1313,10 @@ routing.layer("ProviderServiceLive routing", (it) => {\n Layer.provide(persistenceLayer),\n );\n \n- const firstClaude = makeFakeCodexAdapter("claudeAgent");\n- const firstRegistry: typeof ProviderAdapterRegistry.Service = {\n- getByProvider: (provider) =>\n- provider === "claudeAgent"\n- ? Effect.succeed(firstClaude.adapter)\n- : Effect.fail(new ProviderUnsupportedError({ provider })),\n- listProviders: () => Effect.succeed(["claudeAgent"]),\n- };\n+ const firstClaude = makeFakeCodexAdapter(CLAUDE_AGENT_DRIVER);\n+ const firstRegistry = makeAdapterRegistryMock({\n+ [ProviderDriverKind.make("claudeAgent")]: firstClaude.adapter,\n+ });\n const firstDirectoryLayer = ProviderSessionDirectoryLive.pipe(\n Layer.provide(runtimeRepositoryLayer),\n );\n@@ -1087,26 +1325,24 @@ routing.layer("ProviderServiceLive routing", (it) => {\n Layer.provide(firstDirectoryLayer),\n Layer.provide(defaultServerSettingsLayer),\n Layer.provide(AnalyticsService.layerTest),\n+ Layer.provide(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)),\n );\n \n const initial = yield* Effect.gen(function* () {\n const provider = yield* ProviderService;\n return yield* provider.startSession(asThreadId("thread-claude-cwd"), {\n- provider: "claudeAgent",\n+ provider: ProviderDriverKind.make("claudeAgent"),\n+ providerInstanceId: claudeAgentInstanceId,\n threadId: asThreadId("thread-claude-cwd"),\n cwd: "/tmp/project-claude-cwd",\n runtimeMode: "full-access",\n });\n }).pipe(Effect.provide(firstProviderLayer));\n \n- const secondClaude = makeFakeCodexAdapter("claudeAgent");\n- const secondRegistry: typeof ProviderAdapterRegistry.Service = {\n- getByProvider: (provider) =>\n- provider === "claudeAgent"\n- ? Effect.succeed(secondClaude.adapter)\n- : Effect.fail(new ProviderUnsupportedError({ provider })),\n- listProviders: () => Effect.succeed(["claudeAgent"]),\n- };\n+ const secondClaude = makeFakeCodexAdapter(CLAUDE_AGENT_DRIVER);\n+ const secondRegistry = makeAdapterRegistryMock({\n+ [ProviderDriverKind.make("claudeAgent")]: secondClaude.adapter,\n+ });\n const secondDirectoryLayer = ProviderSessionDirectoryLive.pipe(\n Layer.provide(runtimeRepositoryLayer),\n );\n@@ -1115,6 +1351,7 @@ routing.layer("ProviderServiceLive routing", (it) => {\n Layer.provide(secondDirectoryLayer),\n Layer.provide(defaultServerSettingsLayer),\n Layer.provide(AnalyticsService.layerTest),\n+ Layer.provide(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)),\n );\n \n secondClaude.startSession.mockClear();\n@@ -1122,7 +1359,8 @@ routing.layer("ProviderServiceLive routing", (it) => {\n yield* Effect.gen(function* () {\n const provider = yield* ProviderService;\n yield* provider.startSession(initial.threadId, {\n- provider: "claudeAgent",\n+ provider: ProviderDriverKind.make("claudeAgent"),\n+ providerInstanceId: claudeAgentInstanceId,\n threadId: initial.threadId,\n runtimeMode: "full-access",\n });\n@@ -1155,7 +1393,8 @@ fanout.layer("ProviderServiceLive fanout", (it) => {\n Effect.gen(function* () {\n const provider = yield* ProviderService;\n const session = yield* provider.startSession(asThreadId("thread-1"), {\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n+ providerInstanceId: codexInstanceId,\n threadId: asThreadId("thread-1"),\n runtimeMode: "full-access",\n });\n@@ -1169,7 +1408,7 @@ fanout.layer("ProviderServiceLive fanout", (it) => {\n const completedEvent: LegacyProviderRuntimeEvent = {\n type: "turn.completed",\n eventId: asEventId("evt-1"),\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n createdAt: new Date().toISOString(),\n threadId: session.threadId,\n turnId: asTurnId("turn-1"),\n@@ -1186,6 +1425,13 @@ fanout.layer("ProviderServiceLive fanout", (it) => {\n events.some((entry) => entry.type === "turn.completed"),\n true,\n );\n+ assert.equal(\n+ events.some(\n+ (entry) =>\n+ entry.type === "turn.completed" && entry.providerInstanceId === codexInstanceId,\n+ ),\n+ true,\n+ );\n }),\n );\n \n@@ -1193,7 +1439,8 @@ fanout.layer("ProviderServiceLive fanout", (it) => {\n Effect.gen(function* () {\n const provider = yield* ProviderService;\n const session = yield* provider.startSession(asThreadId("thread-seq"), {\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n+ providerInstanceId: codexInstanceId,\n threadId: asThreadId("thread-seq"),\n runtimeMode: "full-access",\n });\n@@ -1208,7 +1455,7 @@ fanout.layer("ProviderServiceLive fanout", (it) => {\n fanout.codex.emit({\n type: "tool.started",\n eventId: asEventId("evt-seq-1"),\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n createdAt: new Date().toISOString(),\n threadId: session.threadId,\n turnId: asTurnId("turn-1"),\n@@ -1218,7 +1465,7 @@ fanout.layer("ProviderServiceLive fanout", (it) => {\n fanout.codex.emit({\n type: "tool.completed",\n eventId: asEventId("evt-seq-2"),\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n createdAt: new Date().toISOString(),\n threadId: session.threadId,\n turnId: asTurnId("turn-1"),\n@@ -1228,7 +1475,7 @@ fanout.layer("ProviderServiceLive fanout", (it) => {\n fanout.codex.emit({\n type: "turn.completed",\n eventId: asEventId("evt-seq-3"),\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n createdAt: new Date().toISOString(),\n threadId: session.threadId,\n turnId: asTurnId("turn-1"),\n@@ -1248,7 +1495,8 @@ fanout.layer("ProviderServiceLive fanout", (it) => {\n Effect.gen(function* () {\n const provider = yield* ProviderService;\n const session = yield* provider.startSession(asThreadId("thread-1"), {\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n+ providerInstanceId: codexInstanceId,\n threadId: asThreadId("thread-1"),\n runtimeMode: "full-access",\n });\n@@ -1273,7 +1521,7 @@ fanout.layer("ProviderServiceLive fanout", (it) => {\n {\n type: "tool.completed",\n eventId: asEventId("evt-ordered-1"),\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n createdAt: new Date().toISOString(),\n threadId: session.threadId,\n turnId: asTurnId("turn-1"),\n@@ -1284,7 +1532,7 @@ fanout.layer("ProviderServiceLive fanout", (it) => {\n {\n type: "message.delta",\n eventId: asEventId("evt-ordered-2"),\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n createdAt: new Date().toISOString(),\n threadId: session.threadId,\n turnId: asTurnId("turn-1"),\n@@ -1293,7 +1541,7 @@ fanout.layer("ProviderServiceLive fanout", (it) => {\n {\n type: "turn.completed",\n eventId: asEventId("evt-ordered-3"),\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n createdAt: new Date().toISOString(),\n threadId: session.threadId,\n turnId: asTurnId("turn-1"),\n@@ -1320,7 +1568,8 @@ fanout.layer("ProviderServiceLive fanout", (it) => {\n const provider = yield* ProviderService;\n \n const session = yield* provider.startSession(asThreadId("thread-metrics"), {\n- provider: "claudeAgent",\n+ provider: ProviderDriverKind.make("claudeAgent"),\n+ providerInstanceId: claudeAgentInstanceId,\n threadId: asThreadId("thread-metrics"),\n cwd: "/tmp/project",\n runtimeMode: "full-access",\n@@ -1349,7 +1598,7 @@ fanout.layer("ProviderServiceLive fanout", (it) => {\n \n assert.equal(\n hasMetricSnapshot(snapshots, "t3_provider_turns_total", {\n- provider: "claudeAgent",\n+ provider: ProviderDriverKind.make("claudeAgent"),\n operation: "interrupt",\n outcome: "success",\n }),\n@@ -1357,7 +1606,7 @@ fanout.layer("ProviderServiceLive fanout", (it) => {\n );\n assert.equal(\n hasMetricSnapshot(snapshots, "t3_provider_turns_total", {\n- provider: "claudeAgent",\n+ provider: ProviderDriverKind.make("claudeAgent"),\n operation: "approval-response",\n outcome: "success",\n }),\n@@ -1365,7 +1614,7 @@ fanout.layer("ProviderServiceLive fanout", (it) => {\n );\n assert.equal(\n hasMetricSnapshot(snapshots, "t3_provider_turns_total", {\n- provider: "claudeAgent",\n+ provider: ProviderDriverKind.make("claudeAgent"),\n operation: "user-input-response",\n outcome: "success",\n }),\n@@ -1373,7 +1622,7 @@ fanout.layer("ProviderServiceLive fanout", (it) => {\n );\n assert.equal(\n hasMetricSnapshot(snapshots, "t3_provider_turns_total", {\n- provider: "claudeAgent",\n+ provider: ProviderDriverKind.make("claudeAgent"),\n operation: "rollback",\n outcome: "success",\n }),\n@@ -1381,7 +1630,7 @@ fanout.layer("ProviderServiceLive fanout", (it) => {\n );\n assert.equal(\n hasMetricSnapshot(snapshots, "t3_provider_sessions_total", {\n- provider: "claudeAgent",\n+ provider: ProviderDriverKind.make("claudeAgent"),\n operation: "stop",\n outcome: "success",\n }),\n@@ -1397,7 +1646,8 @@ fanout.layer("ProviderServiceLive fanout", (it) => {\n const provider = yield* ProviderService;\n \n const session = yield* provider.startSession(asThreadId("thread-send-metrics"), {\n- provider: "claudeAgent",\n+ provider: ProviderDriverKind.make("claudeAgent"),\n+ providerInstanceId: claudeAgentInstanceId,\n threadId: asThreadId("thread-send-metrics"),\n cwd: "/tmp/project-send-metrics",\n runtimeMode: "full-access",\n@@ -1413,7 +1663,7 @@ fanout.layer("ProviderServiceLive fanout", (it) => {\n \n assert.equal(\n hasMetricSnapshot(snapshots, "t3_provider_turns_total", {\n- provider: "claudeAgent",\n+ provider: ProviderDriverKind.make("claudeAgent"),\n operation: "send",\n outcome: "success",\n }),\n@@ -1421,7 +1671,7 @@ fanout.layer("ProviderServiceLive fanout", (it) => {\n );\n assert.equal(\n hasMetricSnapshot(snapshots, "t3_provider_turn_duration", {\n- provider: "claudeAgent",\n+ provider: ProviderDriverKind.make("claudeAgent"),\n operation: "send",\n }),\n true,\n@@ -1432,6 +1682,50 @@ fanout.layer("ProviderServiceLive fanout", (it) => {\n \n const validation = makeProviderServiceLayer();\n validation.layer("ProviderServiceLive validation", (it) => {\n+ it.effect("rejects session starts without an explicit provider instance id", () =>\n+ Effect.gen(function* () {\n+ const provider = yield* ProviderService;\n+\n+ validation.codex.startSession.mockClear();\n+ const failure = yield* Effect.flip(\n+ provider.startSession(asThreadId("thread-missing-instance-id"), {\n+ provider: ProviderDriverKind.make("codex"),\n+ threadId: asThreadId("thread-missing-instance-id"),\n+ runtimeMode: "full-access",\n+ }),\n+ );\n+\n+ assert.instanceOf(failure, ProviderValidationError);\n+ assert.include(failure.issue, "Provider instance id is required for provider \'codex\'.");\n+ assert.equal(validation.codex.startSession.mock.calls.length, 0);\n+ }),\n+ );\n+\n+ it.effect("rejects mismatched provider kind and provider instance id", () =>\n+ Effect.gen(function* () {\n+ const provider = yield* ProviderService;\n+\n+ validation.codex.startSession.mockClear();\n+ validation.claude.startSession.mockClear();\n+ const failure = yield* Effect.flip(\n+ provider.startSession(asThreadId("thread-instance-mismatch"), {\n+ provider: ProviderDriverKind.make("codex"),\n+ providerInstanceId: claudeAgentInstanceId,\n+ threadId: asThreadId("thread-instance-mismatch"),\n+ runtimeMode: "full-access",\n+ }),\n+ );\n+\n+ assert.instanceOf(failure, ProviderValidationError);\n+ assert.include(\n+ failure.issue,\n+ "Provider instance \'claudeAgent\' belongs to driver \'claudeAgent\', not \'codex\'.",\n+ );\n+ assert.equal(validation.codex.startSession.mock.calls.length, 0);\n+ assert.equal(validation.claude.startSession.mock.calls.length, 0);\n+ }),\n+ );\n+\n it.effect("returns ProviderValidationError for invalid input payloads", () =>\n Effect.gen(function* () {\n const provider = yield* ProviderService;\n@@ -1466,7 +1760,7 @@ validation.layer("ProviderServiceLive validation", (it) => {\n Effect.sync(() => {\n const now = new Date().toISOString();\n return {\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n status: "ready",\n threadId: input.threadId,\n runtimeMode: input.runtimeMode,\n@@ -1478,7 +1772,8 @@ validation.layer("ProviderServiceLive validation", (it) => {\n );\n \n const session = yield* provider.startSession(asThreadId("thread-missing"), {\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n+ providerInstanceId: codexInstanceId,\n threadId: asThreadId("thread-missing"),\n cwd: "/tmp/project",\n runtimeMode: "full-access",\ndiff --git a/apps/server/src/provider/Layers/ProviderService.ts b/apps/server/src/provider/Layers/ProviderService.ts\nindex 94630d3bca..05b4e72ec1 100644\n--- a/apps/server/src/provider/Layers/ProviderService.ts\n+++ b/apps/server/src/provider/Layers/ProviderService.ts\n@@ -19,10 +19,12 @@ import {\n ProviderSendTurnInput,\n ProviderSessionStartInput,\n ProviderStopSessionInput,\n+ type ProviderInstanceId,\n+ type ProviderDriverKind,\n type ProviderRuntimeEvent,\n type ProviderSession,\n } from "@t3tools/contracts";\n-import { Effect, Layer, Option, PubSub, Schema, SchemaIssue, Stream } from "effect";\n+import { Cause, Effect, Layer, Option, PubSub, Ref, Schema, SchemaIssue, Stream } from "effect";\n \n import {\n increment,\n@@ -34,19 +36,24 @@ import {\n providerTurnMetricAttributes,\n withMetrics,\n } from "../../observability/Metrics.ts";\n-import { ProviderValidationError } from "../Errors.ts";\n+import { type ProviderAdapterError, ProviderValidationError } from "../Errors.ts";\n+import type { ProviderAdapterShape } from "../Services/ProviderAdapter.ts";\n import { ProviderAdapterRegistry } from "../Services/ProviderAdapterRegistry.ts";\n import { ProviderService, type ProviderServiceShape } from "../Services/ProviderService.ts";\n import {\n ProviderSessionDirectory,\n type ProviderRuntimeBinding,\n } from "../Services/ProviderSessionDirectory.ts";\n-import { type EventNdjsonLogger, makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";\n+import { type EventNdjsonLogger } from "./EventNdjsonLogger.ts";\n+import { ProviderEventLoggers } from "./ProviderEventLoggers.ts";\n import { AnalyticsService } from "../../telemetry/Services/AnalyticsService.ts";\n-import { ServerSettingsService } from "../../serverSettings.ts";\n \n+/**\n+ * Hook for tests that want to override the canonical event logger pulled\n+ * from `ProviderEventLoggers`. Production wiring leaves this undefined and\n+ * reads the logger off the tag.\n+ */\n export interface ProviderServiceLiveOptions {\n- readonly canonicalEventLogPath?: string;\n readonly canonicalEventLogger?: EventNdjsonLogger;\n }\n \n@@ -141,18 +148,53 @@ function readPersistedCwd(\n return trimmed.length > 0 ? trimmed : undefined;\n }\n \n+const dieOnMissingBindingInstanceId = (\n+ operation: string,\n+ payload: {\n+ readonly providerInstanceId?: ProviderInstanceId | undefined;\n+ readonly provider?: ProviderDriverKind | undefined;\n+ },\n+): ProviderInstanceId => {\n+ if (payload.providerInstanceId !== undefined) {\n+ return payload.providerInstanceId;\n+ }\n+ throw new Error(\n+ payload.provider\n+ ? `${operation}: provider instance id is required for provider \'${payload.provider}\'.`\n+ : `${operation}: provider instance id is required.`,\n+ );\n+};\n+\n+const correlateRuntimeEventWithInstance = (\n+ source: {\n+ readonly instanceId: ProviderInstanceId;\n+ readonly provider: ProviderDriverKind;\n+ },\n+ event: ProviderRuntimeEvent,\n+): ProviderRuntimeEvent => {\n+ if (event.provider !== source.provider) {\n+ throw new Error(\n+ `ProviderService.streamEvents: provider instance \'${source.instanceId}\' is backed by driver \'${source.provider}\' but emitted driver \'${event.provider}\'.`,\n+ );\n+ }\n+ if (event.providerInstanceId !== undefined && event.providerInstanceId !== source.instanceId) {\n+ throw new Error(\n+ `ProviderService.streamEvents: provider instance \'${source.instanceId}\' emitted event for instance \'${event.providerInstanceId}\'.`,\n+ );\n+ }\n+ return { ...event, providerInstanceId: source.instanceId };\n+};\n+\n const makeProviderService = Effect.fn("makeProviderService")(function* (\n options?: ProviderServiceLiveOptions,\n ) {\n const analytics = yield* Effect.service(AnalyticsService);\n- const serverSettings = yield* ServerSettingsService;\n- const canonicalEventLogger =\n- options?.canonicalEventLogger ??\n- (options?.canonicalEventLogPath !== undefined\n- ? yield* makeEventNdjsonLogger(options.canonicalEventLogPath, {\n- stream: "canonical",\n- })\n- : undefined);\n+ const eventLoggers = yield* ProviderEventLoggers;\n+ // Options-provided logger wins (test overrides); otherwise we take whatever\n+ // the `ProviderEventLoggers` tag exposes — `undefined` means "no canonical\n+ // log writer is attached", which downstream code already handles as a\n+ // no-op.\n+ const canonicalEventLogger = options?.canonicalEventLogger ?? eventLoggers.canonical;\n \n const registry = yield* ProviderAdapterRegistry;\n const directory = yield* ProviderSessionDirectory;\n@@ -169,6 +211,24 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (\n Effect.asVoid,\n );\n \n+ const requireBindingInstanceId = (\n+ operation: string,\n+ payload: {\n+ readonly providerInstanceId?: ProviderInstanceId | undefined;\n+ readonly provider?: ProviderDriverKind | undefined;\n+ },\n+ ): Effect.Effect<ProviderInstanceId, ProviderValidationError> =>\n+ payload.providerInstanceId !== undefined\n+ ? Effect.succeed(payload.providerInstanceId)\n+ : Effect.fail(\n+ toValidationError(\n+ operation,\n+ payload.provider\n+ ? `Provider instance id is required for provider \'${payload.provider}\'.`\n+ : "Provider instance id is required.",\n+ ),\n+ );\n+\n const upsertSessionBinding = (\n session: ProviderSession,\n threadId: ThreadId,\n@@ -178,38 +238,106 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (\n readonly lastRuntimeEventAt?: string;\n },\n ) =>\n- directory.upsert({\n- threadId,\n- provider: session.provider,\n- runtimeMode: session.runtimeMode,\n- status: toRuntimeStatus(session),\n- ...(session.resumeCursor !== undefined ? { resumeCursor: session.resumeCursor } : {}),\n- runtimePayload: toRuntimePayloadFromSession(session, extra),\n+ Effect.gen(function* () {\n+ const providerInstanceId = yield* requireBindingInstanceId(\n+ "ProviderService.upsertSessionBinding",\n+ session,\n+ );\n+ yield* directory.upsert({\n+ threadId,\n+ provider: session.provider,\n+ providerInstanceId,\n+ runtimeMode: session.runtimeMode,\n+ status: toRuntimeStatus(session),\n+ ...(session.resumeCursor !== undefined ? { resumeCursor: session.resumeCursor } : {}),\n+ runtimePayload: toRuntimePayloadFromSession(session, extra),\n+ });\n });\n \n- const providers = yield* registry.listProviders();\n- const adapters = yield* Effect.forEach(providers, (provider) => registry.getByProvider(provider));\n- const processRuntimeEvent = (event: ProviderRuntimeEvent): Effect.Effect<void> =>\n- increment(providerRuntimeEventsTotal, {\n- provider: event.provider,\n- eventType: event.type,\n- }).pipe(Effect.andThen(publishRuntimeEvent(event)));\n+ const processRuntimeEvent = (\n+ source: {\n+ readonly instanceId: ProviderInstanceId;\n+ readonly provider: ProviderDriverKind;\n+ },\n+ event: ProviderRuntimeEvent,\n+ ): Effect.Effect<void> =>\n+ Effect.sync(() => correlateRuntimeEventWithInstance(source, event)).pipe(\n+ Effect.flatMap((canonicalEvent) =>\n+ increment(providerRuntimeEventsTotal, {\n+ provider: canonicalEvent.provider,\n+ eventType: canonicalEvent.type,\n+ }).pipe(Effect.andThen(publishRuntimeEvent(canonicalEvent))),\n+ ),\n+ );\n+\n+ // `subscribedAdapters` is our source-of-truth for "which instance adapters\n+ // are currently wired into the runtime event bus". It both tracks the set\n+ // of live subscriptions (so `reconcileInstanceSubscriptions` can diff and\n+ // fork only the *new* or *rebuilt* ones) and serves as the dynamic adapter\n+ // list consumed by `stopStaleSessionsForThread`, `listSessions`, and\n+ // `runStopAll` — replacing the pre-Slice-D startup snapshot so hot-added\n+ // instances become visible to those call sites as soon as settings edits\n+ // land.\n+ const subscribedAdapters = yield* Ref.make(\n+ new Map<ProviderInstanceId, ProviderAdapterShape<ProviderAdapterError>>(),\n+ );\n \n- yield* Effect.forEach(adapters, (adapter) =>\n- Stream.runForEach(adapter.streamEvents, processRuntimeEvent).pipe(Effect.forkScoped),\n- ).pipe(Effect.asVoid);\n+ const getAdapterEntries = Ref.get(subscribedAdapters).pipe(\n+ Effect.map((map) => Array.from(map.entries())),\n+ );\n+\n+ // Rebuild the map of id → adapter from the registry and fork a new event\n+ // subscription for every instance that is either brand new or whose adapter\n+ // identity changed (indicating the underlying `ProviderInstance` was torn\n+ // down and rebuilt by `ProviderInstanceRegistry.reconcile`). Orphaned\n+ // fibers for removed/replaced instances exit on their own because their\n+ // adapter\'s `streamEvents` source terminates when the old scope closes.\n+ const reconcileInstanceSubscriptions = Effect.gen(function* () {\n+ const previous = yield* Ref.get(subscribedAdapters);\n+ const currentIds = yield* registry.listInstances();\n+ const next = new Map<ProviderInstanceId, ProviderAdapterShape<ProviderAdapterError>>();\n+ for (const id of currentIds) {\n+ const adapterOption = yield* registry\n+ .getByInstance(id)\n+ .pipe(Effect.tapError(Effect.logWarning), Effect.option);\n+ if (Option.isNone(adapterOption)) continue;\n+ const adapter = adapterOption.value;\n+ next.set(id, adapter);\n+ if (previous.get(id) !== adapter) {\n+ yield* Stream.runForEach(adapter.streamEvents, (event) =>\n+ processRuntimeEvent(\n+ {\n+ instanceId: id,\n+ provider: adapter.provider,\n+ },\n+ event,\n+ ),\n+ ).pipe(Effect.forkScoped);\n+ }\n+ }\n+ yield* Ref.set(subscribedAdapters, next);\n+ });\n+\n+ const instanceChanges = yield* registry.subscribeChanges;\n+ yield* reconcileInstanceSubscriptions;\n+ yield* Stream.runForEach(\n+ Stream.fromSubscription(instanceChanges),\n+ () => reconcileInstanceSubscriptions,\n+ ).pipe(Effect.forkScoped);\n \n const recoverSessionForThread = Effect.fn("recoverSessionForThread")(function* (input: {\n readonly binding: ProviderRuntimeBinding;\n readonly operation: string;\n }) {\n+ const bindingInstanceId = yield* requireBindingInstanceId(input.operation, input.binding);\n yield* Effect.annotateCurrentSpan({\n "provider.operation": "recover-session",\n "provider.kind": input.binding.provider,\n+ "provider.instance_id": bindingInstanceId,\n "provider.thread_id": input.binding.threadId,\n });\n return yield* Effect.gen(function* () {\n- const adapter = yield* registry.getByProvider(input.binding.provider);\n+ const adapter = yield* registry.getByInstance(bindingInstanceId);\n const hasResumeCursor =\n input.binding.resumeCursor !== null && input.binding.resumeCursor !== undefined;\n const hasActiveSession = yield* adapter.hasSession(input.binding.threadId);\n@@ -219,7 +347,10 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (\n (session) => session.threadId === input.binding.threadId,\n );\n if (existing) {\n- yield* upsertSessionBinding(existing, input.binding.threadId);\n+ yield* upsertSessionBinding(\n+ { ...existing, providerInstanceId: bindingInstanceId },\n+ input.binding.threadId,\n+ );\n yield* analytics.record("provider.session.recovered", {\n provider: existing.provider,\n strategy: "adopt-existing",\n@@ -242,6 +373,7 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (\n const resumed = yield* adapter.startSession({\n threadId: input.binding.threadId,\n provider: input.binding.provider,\n+ providerInstanceId: bindingInstanceId,\n ...(persistedCwd ? { cwd: persistedCwd } : {}),\n ...(persistedModelSelection ? { modelSelection: persistedModelSelection } : {}),\n ...(hasResumeCursor ? { resumeCursor: input.binding.resumeCursor } : {}),\n@@ -254,7 +386,10 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (\n );\n }\n \n- yield* upsertSessionBinding(resumed, input.binding.threadId);\n+ yield* upsertSessionBinding(\n+ { ...resumed, providerInstanceId: bindingInstanceId },\n+ input.binding.threadId,\n+ );\n yield* analytics.record("provider.session.recovered", {\n provider: resumed.provider,\n strategy: "resume-thread",\n@@ -284,29 +419,49 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (\n `Cannot route thread \'${input.threadId}\' because no persisted provider binding exists.`,\n );\n }\n- const adapter = yield* registry.getByProvider(binding.provider);\n+ const instanceId = yield* requireBindingInstanceId(input.operation, binding);\n+ const adapter = yield* registry.getByInstance(instanceId);\n \n const hasRequestedSession = yield* adapter.hasSession(input.threadId);\n if (hasRequestedSession) {\n- return { adapter, threadId: input.threadId, isActive: true } as const;\n+ return {\n+ adapter,\n+ instanceId,\n+ threadId: input.threadId,\n+ isActive: true,\n+ } as const;\n }\n \n if (!input.allowRecovery) {\n- return { adapter, threadId: input.threadId, isActive: false } as const;\n+ return {\n+ adapter,\n+ instanceId,\n+ threadId: input.threadId,\n+ isActive: false,\n+ } as const;\n }\n \n- const recovered = yield* recoverSessionForThread({ binding, operation: input.operation });\n- return { adapter: recovered.adapter, threadId: input.threadId, isActive: true } as const;\n+ const recovered = yield* recoverSessionForThread({\n+ binding,\n+ operation: input.operation,\n+ });\n+ return {\n+ adapter: recovered.adapter,\n+ instanceId,\n+ threadId: input.threadId,\n+ isActive: true,\n+ } as const;\n });\n \n const stopStaleSessionsForThread = Effect.fn("stopStaleSessionsForThread")(function* (input: {\n readonly threadId: ThreadId;\n- readonly currentProvider: ProviderSession["provider"];\n+ readonly currentInstanceId: ProviderInstanceId;\n }) {\n+ const currentAdapters = yield* getAdapterEntries;\n yield* Effect.forEach(\n- adapters,\n- (adapter) =>\n- adapter.provider === input.currentProvider\n+ currentAdapters,\n+ ([instanceId, adapter]) =>\n+ instanceId === input.currentInstanceId\n ? Effect.void\n : Effect.gen(function* () {\n const hasSession = yield* adapter.hasSession(input.threadId);\n@@ -341,63 +496,72 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (\n payload: rawInput,\n });\n \n- const input = {\n- ...parsed,\n- threadId,\n- provider: parsed.provider ?? "codex",\n- };\n+ const resolvedInstanceId = yield* requireBindingInstanceId(\n+ "ProviderService.startSession",\n+ parsed,\n+ );\n+ let metricProvider = parsed.provider ?? String(resolvedInstanceId);\n yield* Effect.annotateCurrentSpan({\n "provider.operation": "start-session",\n- "provider.kind": input.provider,\n+ "provider.instance_id": resolvedInstanceId,\n "provider.thread_id": threadId,\n- "provider.runtime_mode": input.runtimeMode,\n+ "provider.runtime_mode": parsed.runtimeMode,\n });\n return yield* Effect.gen(function* () {\n- const settings = yield* serverSettings.getSettings.pipe(\n- Effect.mapError((error) =>\n- toValidationError(\n- "ProviderService.startSession",\n- `Failed to load provider settings: ${error.message}`,\n- error,\n- ),\n- ),\n- );\n- if (!settings.providers[input.provider].enabled) {\n+ const instanceInfo = yield* registry.getInstanceInfo(resolvedInstanceId);\n+ const resolvedProvider = instanceInfo.driverKind;\n+ metricProvider = resolvedProvider;\n+ if (parsed.provider !== undefined && parsed.provider !== resolvedProvider) {\n return yield* toValidationError(\n "ProviderService.startSession",\n- `Provider \'${input.provider}\' is disabled in T3 Code settings.`,\n+ `Provider instance \'${resolvedInstanceId}\' belongs to driver \'${resolvedProvider}\', not \'${parsed.provider}\'.`,\n+ );\n+ }\n+ const input = {\n+ ...parsed,\n+ threadId,\n+ provider: resolvedProvider,\n+ };\n+ if (!instanceInfo.enabled) {\n+ return yield* toValidationError(\n+ "ProviderService.startSession",\n+ `Provider instance \'${resolvedInstanceId}\' is disabled in T3 Code settings.`,\n );\n }\n const persistedBinding = Option.getOrUndefined(yield* directory.getBinding(threadId));\n const effectiveResumeCursor =\n input.resumeCursor ??\n- (persistedBinding?.provider === input.provider\n+ (persistedBinding?.providerInstanceId === resolvedInstanceId\n ? persistedBinding.resumeCursor\n : undefined);\n const effectiveCwd =\n input.cwd ??\n- (persistedBinding?.provider === input.provider\n+ (persistedBinding?.providerInstanceId === resolvedInstanceId\n ? readPersistedCwd(persistedBinding.runtimePayload)\n : undefined);\n yield* Effect.annotateCurrentSpan({\n+ "provider.kind": resolvedProvider,\n "provider.resume_cursor.source":\n input.resumeCursor !== undefined\n ? "request"\n- : effectiveResumeCursor !== undefined && persistedBinding?.provider === input.provider\n+ : effectiveResumeCursor !== undefined &&\n+ persistedBinding?.providerInstanceId === resolvedInstanceId\n ? "persisted"\n : "none",\n "provider.resume_cursor.present": effectiveResumeCursor !== undefined,\n "provider.cwd.source":\n input.cwd !== undefined\n ? "request"\n- : effectiveCwd !== undefined && persistedBinding?.provider === input.provider\n+ : effectiveCwd !== undefined &&\n+ persistedBinding?.providerInstanceId === resolvedInstanceId\n ? "persisted"\n : "none",\n "provider.cwd.effective": effectiveCwd ?? "",\n });\n- const adapter = yield* registry.getByProvider(input.provider);\n+ const adapter = yield* registry.getByInstance(resolvedInstanceId);\n const session = yield* adapter.startSession({\n ...input,\n+ providerInstanceId: resolvedInstanceId,\n ...(effectiveCwd !== undefined ? { cwd: effectiveCwd } : {}),\n ...(effectiveResumeCursor !== undefined ? { resumeCursor: effectiveResumeCursor } : {}),\n });\n@@ -408,31 +572,36 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (\n `Adapter/provider mismatch: requested \'${adapter.provider}\', received \'${session.provider}\'.`,\n );\n }\n+ const sessionWithInstance = {\n+ ...session,\n+ providerInstanceId: resolvedInstanceId,\n+ };\n \n yield* stopStaleSessionsForThread({\n threadId,\n- currentProvider: adapter.provider,\n+ currentInstanceId: resolvedInstanceId,\n });\n- yield* upsertSessionBinding(session, threadId, {\n+ yield* upsertSessionBinding(sessionWithInstance, threadId, {\n modelSelection: input.modelSelection,\n });\n yield* analytics.record("provider.session.started", {\n- provider: session.provider,\n+ provider: sessionWithInstance.provider,\n runtimeMode: input.runtimeMode,\n- hasResumeCursor: session.resumeCursor !== undefined,\n+ hasResumeCursor: sessionWithInstance.resumeCursor !== undefined,\n hasCwd: typeof effectiveCwd === "string" && effectiveCwd.trim().length > 0,\n hasModel:\n typeof input.modelSelection?.model === "string" &&\n input.modelSelection.model.trim().length > 0,\n });\n \n- return session;\n+ return sessionWithInstance;\n }).pipe(\n withMetrics({\n counter: providerSessionsTotal,\n- attributes: providerMetricAttributes(input.provider, {\n- operation: "start",\n- }),\n+ attributes: () =>\n+ providerMetricAttributes(metricProvider, {\n+ operation: "start",\n+ }),\n }),\n );\n },\n@@ -479,6 +648,7 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (\n yield* directory.upsert({\n threadId: input.threadId,\n provider: routed.adapter.provider,\n+ providerInstanceId: routed.instanceId,\n status: "running",\n ...(turn.resumeCursor !== undefined ? { resumeCursor: turn.resumeCursor } : {}),\n runtimePayload: {\n@@ -647,6 +817,7 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (\n yield* directory.upsert({\n threadId: input.threadId,\n provider: routed.adapter.provider,\n+ providerInstanceId: routed.instanceId,\n status: "stopped",\n runtimePayload: {\n activeTurnId: null,\n@@ -669,8 +840,16 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (\n \n const listSessions: ProviderServiceShape["listSessions"] = Effect.fn("listSessions")(\n function* () {\n- const sessionsByProvider = yield* Effect.forEach(adapters, (adapter) =>\n- adapter.listSessions(),\n+ const currentAdapters = yield* getAdapterEntries;\n+ const sessionsByProvider = yield* Effect.forEach(currentAdapters, ([instanceId, adapter]) =>\n+ adapter.listSessions().pipe(\n+ Effect.map((sessions) =>\n+ sessions.map((session) => ({\n+ ...session,\n+ providerInstanceId: instanceId,\n+ })),\n+ ),\n+ ),\n );\n const activeSessions = sessionsByProvider.flatMap((sessions) => sessions);\n const persistedBindings = yield* directory.listThreadIds().pipe(\n@@ -694,29 +873,54 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (\n }\n }\n \n- return activeSessions.map((session) => {\n+ const sessions: ProviderSession[] = [];\n+ for (const session of activeSessions) {\n const binding = bindingsByThreadId.get(session.threadId);\n if (!binding) {\n- return session;\n+ sessions.push(session);\n+ continue;\n }\n \n const overrides: {\n resumeCursor?: ProviderSession["resumeCursor"];\n runtimeMode?: ProviderSession["runtimeMode"];\n+ providerInstanceId?: ProviderSession["providerInstanceId"];\n } = {};\n+ overrides.providerInstanceId = dieOnMissingBindingInstanceId(\n+ "ProviderService.listSessions",\n+ binding,\n+ );\n+ if (binding.provider !== session.provider) {\n+ return yield* Effect.die(\n+ new Error(\n+ `ProviderService.listSessions: thread \'${session.threadId}\' is active on provider \'${session.provider}\' but persisted binding names provider \'${binding.provider}\'.`,\n+ ),\n+ );\n+ }\n+ if (overrides.providerInstanceId !== session.providerInstanceId) {\n+ return yield* Effect.die(\n+ new Error(\n+ `ProviderService.listSessions: thread \'${session.threadId}\' is active on provider instance \'${session.providerInstanceId}\' but persisted binding names \'${overrides.providerInstanceId}\'.`,\n+ ),\n+ );\n+ }\n if (session.resumeCursor === undefined && binding.resumeCursor !== undefined) {\n overrides.resumeCursor = binding.resumeCursor;\n }\n if (binding.runtimeMode !== undefined) {\n overrides.runtimeMode = binding.runtimeMode;\n }\n- return Object.assign({}, session, overrides);\n- });\n+ sessions.push(Object.assign({}, session, overrides));\n+ }\n+ return sessions;\n },\n );\n \n- const getCapabilities: ProviderServiceShape["getCapabilities"] = (provider) =>\n- registry.getByProvider(provider).pipe(Effect.map((adapter) => adapter.capabilities));\n+ const getCapabilities: ProviderServiceShape["getCapabilities"] = (instanceId) =>\n+ registry.getByInstance(instanceId).pipe(Effect.map((adapter) => adapter.capabilities));\n+\n+ const getInstanceInfo: ProviderServiceShape["getInstanceInfo"] = (instanceId) =>\n+ registry.getInstanceInfo(instanceId);\n \n const rollbackConversation: ProviderServiceShape["rollbackConversation"] = Effect.fn(\n "rollbackConversation",\n@@ -761,8 +965,16 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (\n \n const runStopAll = Effect.fn("runStopAll")(function* () {\n const threadIds = yield* directory.listThreadIds();\n- const activeSessions = yield* Effect.forEach(adapters, (adapter) =>\n- adapter.listSessions(),\n+ const currentAdapters = yield* getAdapterEntries;\n+ const activeSessions = yield* Effect.forEach(currentAdapters, ([instanceId, adapter]) =>\n+ adapter.listSessions().pipe(\n+ Effect.map((sessions) =>\n+ sessions.map((session) => ({\n+ ...session,\n+ providerInstanceId: instanceId,\n+ })),\n+ ),\n+ ),\n ).pipe(Effect.map((sessionsByAdapter) => sessionsByAdapter.flatMap((sessions) => sessions)));\n yield* Effect.forEach(activeSessions, (session) =>\n upsertSessionBinding(session, session.threadId, {\n@@ -770,23 +982,22 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (\n lastRuntimeEventAt: new Date().toISOString(),\n }),\n ).pipe(Effect.asVoid);\n- yield* Effect.forEach(adapters, (adapter) => adapter.stopAll()).pipe(Effect.asVoid);\n- yield* Effect.forEach(threadIds, (threadId) =>\n- directory.getProvider(threadId).pipe(\n- Effect.flatMap((provider) =>\n- directory.upsert({\n- threadId,\n- provider,\n- status: "stopped",\n- runtimePayload: {\n- activeTurnId: null,\n- lastRuntimeEvent: "provider.stopAll",\n- lastRuntimeEventAt: new Date().toISOString(),\n- },\n- }),\n- ),\n- ),\n- ).pipe(Effect.asVoid);\n+ yield* Effect.forEach(currentAdapters, ([, adapter]) => adapter.stopAll()).pipe(Effect.asVoid);\n+ const bindings = yield* directory.listBindings().pipe(Effect.orElseSucceed(() => []));\n+ yield* Effect.forEach(bindings, (binding) => {\n+ const providerInstanceId = dieOnMissingBindingInstanceId("ProviderService.stopAll", binding);\n+ return directory.upsert({\n+ threadId: binding.threadId,\n+ provider: binding.provider,\n+ providerInstanceId,\n+ status: "stopped",\n+ runtimePayload: {\n+ activeTurnId: null,\n+ lastRuntimeEvent: "provider.stopAll",\n+ lastRuntimeEventAt: new Date().toISOString(),\n+ },\n+ });\n+ }).pipe(Effect.asVoid);\n yield* analytics.record("provider.sessions.stopped_all", {\n sessionCount: threadIds.length,\n });\n@@ -794,8 +1005,10 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (\n });\n \n yield* Effect.addFinalizer(() =>\n- Effect.catch(runStopAll(), (cause) =>\n- Effect.logWarning("failed to stop provider service", { cause }),\n+ runStopAll().pipe(\n+ Effect.catchCause((cause) =>\n+ Effect.logWarning("failed to stop provider service", { cause: Cause.pretty(cause) }),\n+ ),\n ),\n );\n \n@@ -808,6 +1021,7 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (\n stopSession,\n listSessions,\n getCapabilities,\n+ getInstanceInfo,\n rollbackConversation,\n // Each access creates a fresh PubSub subscription so that multiple\n // consumers (ProviderRuntimeIngestion, CheckpointReactor, etc.) each\ndiff --git a/apps/server/src/provider/Layers/ProviderSessionDirectory.test.ts b/apps/server/src/provider/Layers/ProviderSessionDirectory.test.ts\nindex 35bdec1e37..28a168c43a 100644\n--- a/apps/server/src/provider/Layers/ProviderSessionDirectory.test.ts\n+++ b/apps/server/src/provider/Layers/ProviderSessionDirectory.test.ts\n@@ -3,7 +3,7 @@ import os from "node:os";\n import path from "node:path";\n \n import * as NodeServices from "@effect/platform-node/NodeServices";\n-import { ThreadId } from "@t3tools/contracts";\n+import { ProviderDriverKind, ThreadId } from "@t3tools/contracts";\n import { it, assert } from "@effect/vitest";\n import { assertSome } from "@effect/vitest/utils";\n import { Effect, Layer, Option } from "effect";\n@@ -38,7 +38,7 @@ it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryL\n const initialThreadId = ThreadId.make("thread-1");\n \n yield* directory.upsert({\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n threadId: initialThreadId,\n });\n \n@@ -47,7 +47,7 @@ it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryL\n const resolvedBinding = yield* directory.getBinding(initialThreadId);\n assertSome(resolvedBinding, {\n threadId: initialThreadId,\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n });\n if (Option.isSome(resolvedBinding)) {\n assert.equal(resolvedBinding.value.threadId, initialThreadId);\n@@ -56,7 +56,7 @@ it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryL\n const nextThreadId = ThreadId.make("thread-2");\n \n yield* directory.upsert({\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n threadId: nextThreadId,\n });\n const updatedBinding = yield* directory.getBinding(nextThreadId);\n@@ -85,7 +85,7 @@ it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryL\n const threadId = ThreadId.make("thread-runtime");\n \n yield* directory.upsert({\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n threadId,\n status: "starting",\n resumeCursor: {\n@@ -98,7 +98,7 @@ it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryL\n });\n \n yield* directory.upsert({\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n threadId,\n status: "running",\n runtimePayload: {\n@@ -133,6 +133,7 @@ it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryL\n yield* runtimeRepository.upsert({\n threadId: newerThreadId,\n providerName: "codex",\n+ providerInstanceId: null,\n adapterKey: "codex",\n runtimeMode: "full-access",\n status: "running",\n@@ -148,6 +149,7 @@ it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryL\n yield* runtimeRepository.upsert({\n threadId: olderThreadId,\n providerName: "claudeAgent",\n+ providerInstanceId: null,\n adapterKey: "claudeAgent",\n runtimeMode: "approval-required",\n status: "starting",\n@@ -165,7 +167,7 @@ it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryL\n assert.deepEqual(bindings, [\n {\n threadId: olderThreadId,\n- provider: "claudeAgent",\n+ provider: ProviderDriverKind.make("claudeAgent"),\n adapterKey: "claudeAgent",\n runtimeMode: "approval-required",\n status: "starting",\n@@ -179,7 +181,7 @@ it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryL\n },\n {\n threadId: newerThreadId,\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n adapterKey: "codex",\n runtimeMode: "full-access",\n status: "running",\n@@ -203,6 +205,7 @@ it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryL\n yield* runtimeRepository.upsert({\n threadId,\n providerName: "claudeAgent",\n+ providerInstanceId: null,\n adapterKey: "claudeAgent",\n runtimeMode: "full-access",\n status: "running",\n@@ -212,7 +215,7 @@ it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryL\n });\n \n yield* directory.upsert({\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n threadId,\n });\n \n@@ -235,7 +238,7 @@ it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryL\n yield* Effect.gen(function* () {\n const directory = yield* ProviderSessionDirectory;\n yield* directory.upsert({\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n threadId,\n });\n }).pipe(Effect.provide(directoryLayer));\n@@ -249,7 +252,7 @@ it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryL\n const resolvedBinding = yield* directory.getBinding(threadId);\n assertSome(resolvedBinding, {\n threadId,\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n });\n if (Option.isSome(resolvedBinding)) {\n assert.equal(resolvedBinding.value.threadId, threadId);\ndiff --git a/apps/server/src/provider/Layers/ProviderSessionDirectory.ts b/apps/server/src/provider/Layers/ProviderSessionDirectory.ts\nindex 4cb7147180..e1479082f2 100644\n--- a/apps/server/src/provider/Layers/ProviderSessionDirectory.ts\n+++ b/apps/server/src/provider/Layers/ProviderSessionDirectory.ts\n@@ -1,4 +1,4 @@\n-import { ProviderKind, type ThreadId } from "@t3tools/contracts";\n+import { defaultInstanceIdForDriver, ProviderDriverKind, type ThreadId } from "@t3tools/contracts";\n import { Effect, Layer, Option, Schema } from "effect";\n \n import type { ProviderSessionRuntime } from "../../persistence/Services/ProviderSessionRuntime.ts";\n@@ -20,11 +20,11 @@ function toPersistenceError(operation: string) {\n });\n }\n \n-function decodeProviderKind(\n+function decodeProviderDriverKind(\n providerName: string,\n operation: string,\n-): Effect.Effect<ProviderKind, ProviderSessionDirectoryPersistenceError> {\n- return Schema.decodeUnknownEffect(ProviderKind)(providerName).pipe(\n+): Effect.Effect<ProviderDriverKind, ProviderSessionDirectoryPersistenceError> {\n+ return Schema.decodeUnknownEffect(ProviderDriverKind)(providerName).pipe(\n Effect.mapError(\n (cause) =>\n new ProviderSessionDirectoryPersistenceError({\n@@ -57,12 +57,17 @@ function toRuntimeBinding(\n runtime: ProviderSessionRuntime,\n operation: string,\n ): Effect.Effect<ProviderRuntimeBindingWithMetadata, ProviderSessionDirectoryPersistenceError> {\n- return decodeProviderKind(runtime.providerName, operation).pipe(\n+ return decodeProviderDriverKind(runtime.providerName, operation).pipe(\n Effect.map(\n (provider) =>\n ({\n threadId: runtime.threadId,\n provider,\n+ // Migration boundary only: rows written before the instance split\n+ // have a null provider_instance_id. Promote them as they leave\n+ // persistence so hot routing code never has to infer an instance\n+ // from a driver kind.\n+ providerInstanceId: runtime.providerInstanceId ?? defaultInstanceIdForDriver(provider),\n adapterKey: runtime.adapterKey,\n runtimeMode: runtime.runtimeMode,\n status: runtime.status,\n@@ -108,10 +113,19 @@ const makeProviderSessionDirectory = Effect.gen(function* () {\n const now = new Date().toISOString();\n const providerChanged =\n existingRuntime !== undefined && existingRuntime.providerName !== binding.provider;\n+ const providerInstanceId =\n+ binding.providerInstanceId ?? (!providerChanged ? existingRuntime?.providerInstanceId : null);\n+ if (providerInstanceId === null || providerInstanceId === undefined) {\n+ return yield* new ProviderValidationError({\n+ operation: "ProviderSessionDirectory.upsert",\n+ issue: "providerInstanceId is required for provider session runtime bindings.",\n+ });\n+ }\n yield* repository\n .upsert({\n threadId: resolvedThreadId,\n providerName: binding.provider,\n+ providerInstanceId,\n adapterKey:\n binding.adapterKey ??\n (providerChanged ? binding.provider : (existingRuntime?.adapterKey ?? binding.provider)),\ndiff --git a/apps/server/src/provider/Layers/ProviderSessionReaper.test.ts b/apps/server/src/provider/Layers/ProviderSessionReaper.test.ts\nindex 45199a02b2..91e1a9aef9 100644\n--- a/apps/server/src/provider/Layers/ProviderSessionReaper.test.ts\n+++ b/apps/server/src/provider/Layers/ProviderSessionReaper.test.ts\n@@ -1,5 +1,11 @@\n import * as NodeServices from "@effect/platform-node/NodeServices";\n-import { ProjectId, ThreadId, TurnId } from "@t3tools/contracts";\n+import {\n+ ProjectId,\n+ ThreadId,\n+ TurnId,\n+ ProviderDriverKind,\n+ ProviderInstanceId,\n+} from "@t3tools/contracts";\n import { Effect, Exit, Layer, ManagedRuntime, Option, Scope, Stream } from "effect";\n import { afterEach, describe, expect, it, vi } from "vitest";\n \n@@ -17,7 +23,7 @@ import { ProviderSessionDirectoryLive } from "./ProviderSessionDirectory.ts";\n import { makeProviderSessionReaperLive } from "./ProviderSessionReaper.ts";\n \n const defaultModelSelection = {\n- provider: "codex",\n+ instanceId: ProviderInstanceId.make("codex"),\n model: "gpt-5-codex",\n } as const;\n \n@@ -140,6 +146,19 @@ describe("ProviderSessionReaper", () => {\n stopSession,\n listSessions: () => Effect.succeed([]),\n getCapabilities: () => Effect.succeed({ sessionModelSwitch: "in-session" }),\n+ getInstanceInfo: (instanceId) => {\n+ const driverKind = ProviderDriverKind.make(String(instanceId));\n+ return Effect.succeed({\n+ instanceId,\n+ driverKind,\n+ displayName: undefined,\n+ enabled: true,\n+ continuationIdentity: {\n+ driverKind,\n+ continuationKey: `${driverKind}:instance:${instanceId}`,\n+ },\n+ });\n+ },\n rollbackConversation: () => unsupported(),\n streamEvents: Stream.empty,\n };\n@@ -197,6 +216,7 @@ describe("ProviderSessionReaper", () => {\n repository.upsert({\n threadId,\n providerName: "claudeAgent",\n+ providerInstanceId: null,\n adapterKey: "claudeAgent",\n runtimeMode: "full-access",\n status: "running",\n@@ -244,6 +264,7 @@ describe("ProviderSessionReaper", () => {\n repository.upsert({\n threadId,\n providerName: "claudeAgent",\n+ providerInstanceId: null,\n adapterKey: "claudeAgent",\n runtimeMode: "full-access",\n status: "running",\n@@ -290,6 +311,7 @@ describe("ProviderSessionReaper", () => {\n repository.upsert({\n threadId,\n providerName: "claudeAgent",\n+ providerInstanceId: null,\n adapterKey: "claudeAgent",\n runtimeMode: "full-access",\n status: "running",\n@@ -336,6 +358,7 @@ describe("ProviderSessionReaper", () => {\n repository.upsert({\n threadId,\n providerName: "claudeAgent",\n+ providerInstanceId: null,\n adapterKey: "claudeAgent",\n runtimeMode: "full-access",\n status: "stopped",\n@@ -404,6 +427,7 @@ describe("ProviderSessionReaper", () => {\n repository.upsert({\n threadId: failedThreadId,\n providerName: "claudeAgent",\n+ providerInstanceId: null,\n adapterKey: "claudeAgent",\n runtimeMode: "full-access",\n status: "running",\n@@ -418,6 +442,7 @@ describe("ProviderSessionReaper", () => {\n repository.upsert({\n threadId: reapedThreadId,\n providerName: "codex",\n+ providerInstanceId: null,\n adapterKey: "codex",\n runtimeMode: "full-access",\n status: "running",\n@@ -483,6 +508,7 @@ describe("ProviderSessionReaper", () => {\n repository.upsert({\n threadId: defectThreadId,\n providerName: "claudeAgent",\n+ providerInstanceId: null,\n adapterKey: "claudeAgent",\n runtimeMode: "full-access",\n status: "running",\n@@ -497,6 +523,7 @@ describe("ProviderSessionReaper", () => {\n repository.upsert({\n threadId: reapedThreadId,\n providerName: "codex",\n+ providerInstanceId: null,\n adapterKey: "codex",\n runtimeMode: "full-access",\n status: "running",\ndiff --git a/apps/server/src/provider/Layers/scopedSafeTeardown.test.ts b/apps/server/src/provider/Layers/scopedSafeTeardown.test.ts\nnew file mode 100644\nindex 0000000000..ebbc379b7d\n--- /dev/null\n+++ b/apps/server/src/provider/Layers/scopedSafeTeardown.test.ts\n@@ -0,0 +1,94 @@\n+import { it } from "@effect/vitest";\n+import { Cause, Effect, Exit } from "effect";\n+import { describe, expect } from "vitest";\n+\n+import { scopedSafeTeardown } from "./scopedSafeTeardown.ts";\n+\n+describe("scopedSafeTeardown", () => {\n+ it.effect("returns the body\'s value when teardown is clean", () =>\n+ Effect.gen(function* () {\n+ const finalizers: string[] = [];\n+ const wrapped = Effect.gen(function* () {\n+ yield* Effect.addFinalizer(() =>\n+ Effect.sync(() => {\n+ finalizers.push("clean");\n+ }),\n+ );\n+ return "body-ok";\n+ }).pipe(scopedSafeTeardown("test"));\n+\n+ const value = yield* wrapped;\n+ expect(value).toBe("body-ok");\n+ expect(finalizers).toEqual(["clean"]);\n+ }),\n+ );\n+\n+ it.effect("preserves body success when a finalizer dies", () =>\n+ // The production failure mode: `Layer.build(...)` registers a finalizer\n+ // that kills a subprocess; if the kill fails, the defect would otherwise\n+ // override a successful probe body.\n+ Effect.gen(function* () {\n+ const finalizers: string[] = [];\n+ const wrapped = Effect.gen(function* () {\n+ yield* Effect.addFinalizer(() =>\n+ Effect.sync(() => {\n+ finalizers.push("ran-before-die");\n+ }),\n+ );\n+ yield* Effect.addFinalizer(() =>\n+ Effect.die(new Error("simulated subprocess kill failure")),\n+ );\n+ return "body-ok";\n+ }).pipe(scopedSafeTeardown("test"));\n+\n+ const value = yield* wrapped;\n+ expect(value).toBe("body-ok");\n+ // The clean finalizer still ran; teardown defect was logged + swallowed.\n+ expect(finalizers).toEqual(["ran-before-die"]);\n+ }),\n+ );\n+\n+ it.effect("preserves typed body failures even when teardown is clean", () =>\n+ Effect.gen(function* () {\n+ class BodyError {\n+ readonly _tag = "BodyError" as const;\n+ }\n+ const wrapped = Effect.gen(function* () {\n+ yield* Effect.addFinalizer(() => Effect.void);\n+ return yield* Effect.fail(new BodyError());\n+ }).pipe(scopedSafeTeardown("test"));\n+\n+ const exit = yield* Effect.exit(wrapped);\n+ expect(Exit.isFailure(exit)).toBe(true);\n+ if (Exit.isFailure(exit)) {\n+ // Body\'s typed failure should surface, not a defect.\n+ const squashed = Cause.squash(exit.cause);\n+ expect(squashed).toBeInstanceOf(BodyError);\n+ }\n+ }),\n+ );\n+\n+ it.effect("prefers the body\'s typed failure over a teardown defect", () =>\n+ // Even when both the body fails AND teardown defects, the body\'s typed\n+ // failure is what callers see. This matters because `Effect.result` /\n+ // `.pipe(Effect.exit)` in callers expects a typed Failure, not a Die.\n+ Effect.gen(function* () {\n+ class BodyError {\n+ readonly _tag = "BodyError" as const;\n+ }\n+ const wrapped = Effect.gen(function* () {\n+ yield* Effect.addFinalizer(() =>\n+ Effect.die(new Error("simulated subprocess kill failure")),\n+ );\n+ return yield* Effect.fail(new BodyError());\n+ }).pipe(scopedSafeTeardown("test"));\n+\n+ const exit = yield* Effect.exit(wrapped);\n+ expect(Exit.isFailure(exit)).toBe(true);\n+ if (Exit.isFailure(exit)) {\n+ const squashed = Cause.squash(exit.cause);\n+ expect(squashed).toBeInstanceOf(BodyError);\n+ }\n+ }),\n+ );\n+});\ndiff --git a/apps/server/src/provider/Layers/scopedSafeTeardown.ts b/apps/server/src/provider/Layers/scopedSafeTeardown.ts\nnew file mode 100644\nindex 0000000000..688374590e\n--- /dev/null\n+++ b/apps/server/src/provider/Layers/scopedSafeTeardown.ts\n@@ -0,0 +1,61 @@\n+/**\n+ * scopedSafeTeardown — run a scope-requiring effect so that finalizer\n+ * failures during scope close cannot override the body\'s Exit.\n+ *\n+ * Motivation\n+ * ----------\n+ * The obvious pattern is `body.pipe(Effect.scoped)`: provide a fresh\n+ * Scope, run the body, close the scope with the body\'s Exit. If a\n+ * finalizer (e.g. `ChildProcess.kill` from an effect-codex-app-server\n+ * spawn) dies during that close, the combined Exit becomes the\n+ * finalizer\'s defect — even when the body already succeeded.\n+ *\n+ * Concretely this bit us in the Codex provider probe: a successful\n+ * `initialize` → `account/read` → `skills/list` → `model/list`\n+ * round-trip produced a `CodexAppServerProviderSnapshot`, but the\n+ * `Layer.build(CodexClient.layerCommand(...))` finalizer then failed to\n+ * kill the `codex app-server` subprocess with a `PlatformError`. The\n+ * defect bubbled past `Effect.result` in `checkCodexProviderStatus`,\n+ * died `refreshOneSource`, and `providersRef` never saw the snapshot.\n+ *\n+ * Strategy\n+ * --------\n+ * 1. Make a fresh scope manually.\n+ * 2. Run the body against that scope, capturing its Exit via\n+ * `Effect.exit`.\n+ * 3. Close the scope, catching any cause (typed failure *or* defect)\n+ * with a log.\n+ * 4. Replay the captured Exit so typed body failures still surface and\n+ * successes still return their value.\n+ *\n+ * The helper deliberately logs teardown causes at `Warning` level —\n+ * silently swallowing them is dangerous because they usually indicate a\n+ * real bug in a downstream Layer\'s finalizer.\n+ *\n+ * @module provider/Layers/scopedSafeTeardown\n+ */\n+import { Effect, Exit, Scope } from "effect";\n+\n+/**\n+ * Run `effect` with a freshly made `Scope.Scope`, guaranteeing that\n+ * teardown failures cannot override the body\'s Exit.\n+ *\n+ * Shape matches `Effect.scoped`: takes an effect whose env includes\n+ * `Scope.Scope`, returns one whose env excludes it.\n+ *\n+ * @param label Short label for the warning log emitted when teardown\n+ * fails. Use something like `"codex-probe"`.\n+ */\n+export const scopedSafeTeardown =\n+ (label: string) =>\n+ <A, E, R>(effect: Effect.Effect<A, E, R>): Effect.Effect<A, E, Exclude<R, Scope.Scope>> =>\n+ Effect.gen(function* () {\n+ const scope = yield* Scope.make();\n+ const bodyExit = yield* effect.pipe(Effect.provideService(Scope.Scope, scope), Effect.exit);\n+ yield* Scope.close(scope, Exit.void).pipe(\n+ Effect.catchCause((cause) =>\n+ Effect.logWarning(`${label} teardown errored; preserving body result`, cause),\n+ ),\n+ );\n+ return yield* bodyExit;\n+ }) as Effect.Effect<A, E, Exclude<R, Scope.Scope>>;\ndiff --git a/apps/server/src/provider/ProviderDriver.ts b/apps/server/src/provider/ProviderDriver.ts\nnew file mode 100644\nindex 0000000000..bedfd61194\n--- /dev/null\n+++ b/apps/server/src/provider/ProviderDriver.ts\n@@ -0,0 +1,167 @@\n+/**\n+ * ProviderDriver / ProviderInstance — driver SPI as plain values.\n+ *\n+ * `ProviderDriver` is a record, not a Context.Service. The thing it produces\n+ * (`ProviderInstance`) is also a record — three captured closures\n+ * (`snapshot`, `adapter`, `textGeneration`), an id, and a driver kind. There\n+ * are intentionally no per-driver Context tags because tags are\n+ * singleton-per-runtime and we need many instances of the same driver.\n+ *\n+ * The only Effect service involved is `ProviderInstanceRegistry`, which\n+ * owns the live `Map<InstanceId, ProviderInstance>` and is itself a\n+ * singleton.\n+ *\n+ * Driver factories are functions of `(typed config, env)` where:\n+ * - `typed config` is decoded once by the registry via `configSchema`,\n+ * so drivers never deal with raw `unknown`.\n+ * - `env` flows through Effect\'s R channel. Each driver declares the\n+ * subset of infrastructure services it needs (FileSystem,\n+ * ChildProcessSpawner, …) on its `create` return type; the registry\n+ * layer\'s R is the union of those, and the runtime layer satisfies it.\n+ *\n+ * @module provider/ProviderDriver\n+ */\n+import type {\n+ ProviderDriverKind,\n+ ProviderInstanceEnvironment,\n+ ProviderInstanceId,\n+} from "@t3tools/contracts";\n+import type { Effect, Schema, Scope } from "effect";\n+\n+import type { TextGenerationShape } from "../git/Services/TextGeneration.ts";\n+import type { ProviderAdapterError, ProviderDriverError } from "./Errors.ts";\n+import type { ProviderAdapterShape } from "./Services/ProviderAdapter.ts";\n+import type { ServerProviderShape } from "./Services/ServerProvider.ts";\n+\n+/**\n+ * Static metadata advertised by a driver. Used for default presentation\n+ * and (later) settings UI. Doesn\'t need to be Effect-typed because nothing\n+ * about it is dynamic — drivers are registered at startup.\n+ */\n+export interface ProviderDriverMetadata {\n+ /** Human-readable name for the driver itself (e.g. "Codex"). */\n+ readonly displayName: string;\n+ /**\n+ * Whether the driver may be instantiated more than once concurrently.\n+ * Defaults to `true`. Set to `false` for drivers that wrap a global\n+ * resource (e.g. a single desktop app socket) — the registry then\n+ * rejects multi-instance configurations with a clear error.\n+ */\n+ readonly supportsMultipleInstances?: boolean;\n+}\n+\n+/**\n+ * One materialized provider instance. Held by the registry, looked up by\n+ * `instanceId`, torn down by closing the scope it was created in.\n+ *\n+ * The three "shape" fields are captured closures owned by this instance —\n+ * stopping one instance cannot affect another, and starting a second\n+ * instance of the same driver does not reach into the first instance\'s\n+ * state.\n+ */\n+export interface ProviderInstance {\n+ readonly instanceId: ProviderInstanceId;\n+ readonly driverKind: ProviderDriverKind;\n+ readonly continuationIdentity: ProviderContinuationIdentity;\n+ readonly displayName: string | undefined;\n+ readonly accentColor?: string | undefined;\n+ readonly enabled: boolean;\n+ readonly snapshot: ServerProviderShape;\n+ readonly adapter: ProviderAdapterShape<ProviderAdapterError>;\n+ readonly textGeneration: TextGenerationShape;\n+}\n+\n+export interface ProviderContinuationIdentity {\n+ readonly driverKind: ProviderDriverKind;\n+ readonly continuationKey: string;\n+}\n+\n+export function defaultProviderContinuationIdentity(input: {\n+ readonly driverKind: ProviderDriverKind;\n+ readonly instanceId: ProviderInstanceId;\n+}): ProviderContinuationIdentity {\n+ return {\n+ driverKind: input.driverKind,\n+ continuationKey: `${input.driverKind}:instance:${input.instanceId}`,\n+ };\n+}\n+\n+/**\n+ * Inputs the registry passes to a driver\'s `create` function.\n+ *\n+ * `config` is the typed payload — already decoded by the registry through\n+ * `driver.configSchema`. Drivers never decode their own raw envelope.\n+ */\n+export interface ProviderDriverCreateInput<Config> {\n+ readonly instanceId: ProviderInstanceId;\n+ readonly displayName: string | undefined;\n+ readonly accentColor?: string | undefined;\n+ readonly environment: ProviderInstanceEnvironment;\n+ readonly enabled: boolean;\n+ readonly config: Config;\n+}\n+\n+/**\n+ * Driver SPI — registered as a plain value, not a Layer.\n+ *\n+ * `Config` is whatever the driver decoded from\n+ * `ProviderInstanceConfig.config`. `R` is the union of infrastructure\n+ * services the driver depends on; the registry layer aggregates `R` across\n+ * all registered drivers and the runtime supplies them.\n+ *\n+ * `create` is responsible for *all* per-instance state — process handles,\n+ * pubsub topics, refs, file watchers — and must release them when its\n+ * scope closes. Two calls to `create` with different `instanceId` /\n+ * `config` MUST yield instances with no shared mutable state.\n+ */\n+export interface ProviderDriver<Config, R = never> {\n+ readonly driverKind: ProviderDriverKind;\n+ readonly metadata: ProviderDriverMetadata;\n+ /**\n+ * Decoder for the opaque `ProviderInstanceConfig.config` envelope. The\n+ * registry runs this exactly once per (re)load of an instance; a decode\n+ * failure is surfaced as `ProviderDriverError` and downgraded to an\n+ * unavailable shadow snapshot.\n+ *\n+ * The `Encoded` parameter is intentionally left as `unknown` (not\n+ * `Config`) so schemas with `withDecodingDefault` / transformations — where\n+ * the encoded shape differs from the decoded shape — satisfy the SPI\n+ * without casts. The registry only ever decodes `unknown` envelopes here,\n+ * so the precise encoded type is irrelevant at this boundary.\n+ *\n+ * Using `Codec` rather than `Schema` pins `DecodingServices = never` — if\n+ * we used `Schema<Config>`, the erased `any` in `AnyProviderDriver` would\n+ * widen `DecodingServices` to `unknown` and poison the R channel of every\n+ * caller of `decodeUnknownEffect`.\n+ */\n+ readonly configSchema: Schema.Codec<Config, unknown>;\n+ /**\n+ * Default config payload used when the legacy\n+ * `ServerSettings.providers.<kind>` entry is empty or when the driver\n+ * is auto-bootstrapped without user configuration. Returning a typed\n+ * default keeps the migration path simple — no special-casing needed\n+ * to construct a "blank" instance.\n+ */\n+ readonly defaultConfig: () => Config;\n+ /**\n+ * Materialize one instance. The returned effect runs in a scope owned\n+ * by the registry; closing that scope releases every resource the\n+ * driver opened. Failures become unavailable shadow snapshots — the\n+ * driver MUST NOT throw defects.\n+ */\n+ readonly create: (\n+ input: ProviderDriverCreateInput<Config>,\n+ ) => Effect.Effect<ProviderInstance, ProviderDriverError, R | Scope.Scope>;\n+}\n+\n+/**\n+ * Heterogeneous-array convenience: the registry stores drivers as\n+ * `ReadonlyArray<AnyProviderDriver<R>>` where `R` is the union of all\n+ * registered drivers\' env requirements.\n+ */\n+// `any` here intentionally erases the per-driver Config; the registry\n+// already decoded it before invoking `create`, so downstream code never\n+// needs the original `Config` type. Using `unknown` instead would force\n+// `create` callers into casts since `unknown` is not assignable to a\n+// concrete `Config` from inside the driver body.\n+export type AnyProviderDriver<R = never> = ProviderDriver<any, R>;\ndiff --git a/apps/server/src/provider/ProviderInstanceEnvironment.test.ts b/apps/server/src/provider/ProviderInstanceEnvironment.test.ts\nnew file mode 100644\nindex 0000000000..f37b328b15\n--- /dev/null\n+++ b/apps/server/src/provider/ProviderInstanceEnvironment.test.ts\n@@ -0,0 +1,21 @@\n+import { describe, expect, it } from "vitest";\n+\n+import { mergeProviderInstanceEnvironment } from "./ProviderInstanceEnvironment.ts";\n+\n+describe("mergeProviderInstanceEnvironment", () => {\n+ it("overrides inherited environment values and preserves empty strings", () => {\n+ expect(\n+ mergeProviderInstanceEnvironment(\n+ [\n+ { name: "OPENROUTER_API_KEY", value: "sk-or-test", sensitive: true },\n+ { name: "ANTHROPIC_API_KEY", value: "", sensitive: false },\n+ ],\n+ { ANTHROPIC_API_KEY: "inherited", PATH: "/bin" },\n+ ),\n+ ).toMatchObject({\n+ OPENROUTER_API_KEY: "sk-or-test",\n+ ANTHROPIC_API_KEY: "",\n+ PATH: "/bin",\n+ });\n+ });\n+});\ndiff --git a/apps/server/src/provider/ProviderInstanceEnvironment.ts b/apps/server/src/provider/ProviderInstanceEnvironment.ts\nnew file mode 100644\nindex 0000000000..e469253604\n--- /dev/null\n+++ b/apps/server/src/provider/ProviderInstanceEnvironment.ts\n@@ -0,0 +1,16 @@\n+import type { ProviderInstanceEnvironment } from "@t3tools/contracts";\n+\n+export function mergeProviderInstanceEnvironment(\n+ environment: ProviderInstanceEnvironment | undefined,\n+ baseEnv: NodeJS.ProcessEnv = process.env,\n+): NodeJS.ProcessEnv {\n+ if (!environment || environment.length === 0) {\n+ return baseEnv;\n+ }\n+\n+ const next: NodeJS.ProcessEnv = { ...baseEnv };\n+ for (const variable of environment) {\n+ next[variable.name] = variable.value;\n+ }\n+ return next;\n+}\ndiff --git a/apps/server/src/provider/Services/ClaudeAdapter.ts b/apps/server/src/provider/Services/ClaudeAdapter.ts\nindex e8c33bd8e4..ed9bd7081b 100644\n--- a/apps/server/src/provider/Services/ClaudeAdapter.ts\n+++ b/apps/server/src/provider/Services/ClaudeAdapter.ts\n@@ -1,30 +1,19 @@\n /**\n- * ClaudeAdapter - Claude Agent implementation of the generic provider adapter contract.\n+ * ClaudeAdapter — shape type for the Claude provider adapter.\n *\n- * This service owns Claude runtime/session semantics and emits canonical\n- * provider runtime events. It does not perform cross-provider routing, shared\n- * event fan-out, or checkpoint orchestration.\n- *\n- * Uses Effect `Context.Service` for dependency injection and returns the\n- * shared provider-adapter error channel with `provider: "claudeAgent"` context.\n+ * Historically this module exposed a `Context.Service` tag so consumers\n+ * could inject the adapter through the Effect layer graph. The driver\n+ * model ({@link ../Drivers/ClaudeDriver}) bundles one adapter per\n+ * instance as a captured closure instead, so the tag is gone — we only\n+ * retain the shape interface as a naming anchor for the driver bundle.\n *\n * @module ClaudeAdapter\n */\n-import { Context } from "effect";\n-\n import type { ProviderAdapterError } from "../Errors.ts";\n import type { ProviderAdapterShape } from "./ProviderAdapter.ts";\n \n /**\n- * ClaudeAdapterShape - Service API for the Claude Agent provider adapter.\n- */\n-export interface ClaudeAdapterShape extends ProviderAdapterShape<ProviderAdapterError> {\n- readonly provider: "claudeAgent";\n-}\n-\n-/**\n- * ClaudeAdapter - Service tag for Claude Agent provider adapter operations.\n+ * ClaudeAdapterShape — per-instance Claude adapter contract. Carries\n+ * a branded driver kind as the nominal discriminant.\n */\n-export class ClaudeAdapter extends Context.Service<ClaudeAdapter, ClaudeAdapterShape>()(\n- "t3/provider/Services/ClaudeAdapter",\n-) {}\n+export interface ClaudeAdapterShape extends ProviderAdapterShape<ProviderAdapterError> {}\ndiff --git a/apps/server/src/provider/Services/ClaudeProvider.ts b/apps/server/src/provider/Services/ClaudeProvider.ts\ndeleted file mode 100644\nindex 7e21ac56d9..0000000000\n--- a/apps/server/src/provider/Services/ClaudeProvider.ts\n+++ /dev/null\n@@ -1,9 +0,0 @@\n-import { Context } from "effect";\n-\n-import type { ServerProviderShape } from "./ServerProvider.ts";\n-\n-export interface ClaudeProviderShape extends ServerProviderShape {}\n-\n-export class ClaudeProvider extends Context.Service<ClaudeProvider, ClaudeProviderShape>()(\n- "t3/provider/Services/ClaudeProvider",\n-) {}\ndiff --git a/apps/server/src/provider/Services/CodexAdapter.ts b/apps/server/src/provider/Services/CodexAdapter.ts\nindex e7a5508c9c..33fe0fa12b 100644\n--- a/apps/server/src/provider/Services/CodexAdapter.ts\n+++ b/apps/server/src/provider/Services/CodexAdapter.ts\n@@ -1,30 +1,19 @@\n /**\n- * CodexAdapter - Codex implementation of the generic provider adapter contract.\n+ * CodexAdapter — shape type for the Codex provider adapter.\n *\n- * This service owns Codex app-server process / JSON-RPC semantics and emits\n- * Codex provider events. It does not perform cross-provider routing, shared\n- * event fan-out, or checkpoint orchestration.\n- *\n- * Uses Effect `Context.Service` for dependency injection and returns the\n- * shared provider-adapter error channel with `provider: "codex"` context.\n+ * Historically this module exposed a `Context.Service` tag so consumers\n+ * could inject the adapter through the Effect layer graph. The driver\n+ * model ({@link ../Drivers/CodexDriver}) bundles one adapter per\n+ * instance as a captured closure instead, so the tag is gone — we only\n+ * retain the shape interface as a naming anchor for the driver bundle.\n *\n * @module CodexAdapter\n */\n-import { Context } from "effect";\n-\n import type { ProviderAdapterError } from "../Errors.ts";\n import type { ProviderAdapterShape } from "./ProviderAdapter.ts";\n \n /**\n- * CodexAdapterShape - Service API for the Codex provider adapter.\n- */\n-export interface CodexAdapterShape extends ProviderAdapterShape<ProviderAdapterError> {\n- readonly provider: "codex";\n-}\n-\n-/**\n- * CodexAdapter - Service tag for Codex provider adapter operations.\n+ * CodexAdapterShape — per-instance Codex adapter contract. Carries\n+ * a branded driver kind as the nominal discriminant.\n */\n-export class CodexAdapter extends Context.Service<CodexAdapter, CodexAdapterShape>()(\n- "t3/provider/Services/CodexAdapter",\n-) {}\n+export interface CodexAdapterShape extends ProviderAdapterShape<ProviderAdapterError> {}\ndiff --git a/apps/server/src/provider/Services/CodexProvider.ts b/apps/server/src/provider/Services/CodexProvider.ts\ndeleted file mode 100644\nindex e116f1a761..0000000000\n--- a/apps/server/src/provider/Services/CodexProvider.ts\n+++ /dev/null\n@@ -1,9 +0,0 @@\n-import { Context } from "effect";\n-\n-import type { ServerProviderShape } from "./ServerProvider.ts";\n-\n-export interface CodexProviderShape extends ServerProviderShape {}\n-\n-export class CodexProvider extends Context.Service<CodexProvider, CodexProviderShape>()(\n- "t3/provider/Services/CodexProvider",\n-) {}\ndiff --git a/apps/server/src/provider/Services/CursorAdapter.ts b/apps/server/src/provider/Services/CursorAdapter.ts\nindex f1edb31619..83581f0a45 100644\n--- a/apps/server/src/provider/Services/CursorAdapter.ts\n+++ b/apps/server/src/provider/Services/CursorAdapter.ts\n@@ -1,12 +1,19 @@\n-import { Context } from "effect";\n-\n+/**\n+ * CursorAdapter — shape type for the Cursor provider adapter.\n+ *\n+ * Historically this module exposed a `Context.Service` tag so consumers\n+ * could inject the adapter through the Effect layer graph. The driver\n+ * model ({@link ../Drivers/CursorDriver}) bundles one adapter per\n+ * instance as a captured closure instead, so the tag is gone — we only\n+ * retain the shape interface as a naming anchor for the driver bundle.\n+ *\n+ * @module CursorAdapter\n+ */\n import type { ProviderAdapterError } from "../Errors.ts";\n import type { ProviderAdapterShape } from "./ProviderAdapter.ts";\n \n-export interface CursorAdapterShape extends ProviderAdapterShape<ProviderAdapterError> {\n- readonly provider: "cursor";\n-}\n-\n-export class CursorAdapter extends Context.Service<CursorAdapter, CursorAdapterShape>()(\n- "t3/provider/Services/CursorAdapter",\n-) {}\n+/**\n+ * CursorAdapterShape — per-instance Cursor adapter contract. Carries\n+ * a branded driver kind as the nominal discriminant.\n+ */\n+export interface CursorAdapterShape extends ProviderAdapterShape<ProviderAdapterError> {}\ndiff --git a/apps/server/src/provider/Services/CursorProvider.ts b/apps/server/src/provider/Services/CursorProvider.ts\ndeleted file mode 100644\nindex aa70994f5e..0000000000\n--- a/apps/server/src/provider/Services/CursorProvider.ts\n+++ /dev/null\n@@ -1,9 +0,0 @@\n-import { Context } from "effect";\n-\n-import type { ServerProviderShape } from "./ServerProvider.ts";\n-\n-export interface CursorProviderShape extends ServerProviderShape {}\n-\n-export class CursorProvider extends Context.Service<CursorProvider, CursorProviderShape>()(\n- "t3/provider/Services/CursorProvider",\n-) {}\ndiff --git a/apps/server/src/provider/Services/OpenCodeAdapter.ts b/apps/server/src/provider/Services/OpenCodeAdapter.ts\nindex ad5660022b..e3ad97904d 100644\n--- a/apps/server/src/provider/Services/OpenCodeAdapter.ts\n+++ b/apps/server/src/provider/Services/OpenCodeAdapter.ts\n@@ -1,12 +1,19 @@\n-import { Context } from "effect";\n-\n+/**\n+ * OpenCodeAdapter — shape type for the OpenCode provider adapter.\n+ *\n+ * Historically this module exposed a `Context.Service` tag so consumers\n+ * could inject the adapter through the Effect layer graph. The driver\n+ * model ({@link ../Drivers/OpenCodeDriver}) bundles one adapter per\n+ * instance as a captured closure instead, so the tag is gone — we only\n+ * retain the shape interface as a naming anchor for the driver bundle.\n+ *\n+ * @module OpenCodeAdapter\n+ */\n import type { ProviderAdapterError } from "../Errors.ts";\n import type { ProviderAdapterShape } from "./ProviderAdapter.ts";\n \n-export interface OpenCodeAdapterShape extends ProviderAdapterShape<ProviderAdapterError> {\n- readonly provider: "opencode";\n-}\n-\n-export class OpenCodeAdapter extends Context.Service<OpenCodeAdapter, OpenCodeAdapterShape>()(\n- "t3/provider/Services/OpenCodeAdapter",\n-) {}\n+/**\n+ * OpenCodeAdapterShape — per-instance OpenCode adapter contract. Carries\n+ * a branded driver kind as the nominal discriminant.\n+ */\n+export interface OpenCodeAdapterShape extends ProviderAdapterShape<ProviderAdapterError> {}\ndiff --git a/apps/server/src/provider/Services/OpenCodeProvider.ts b/apps/server/src/provider/Services/OpenCodeProvider.ts\ndeleted file mode 100644\nindex a799830eec..0000000000\n--- a/apps/server/src/provider/Services/OpenCodeProvider.ts\n+++ /dev/null\n@@ -1,9 +0,0 @@\n-import { Context } from "effect";\n-\n-import type { ServerProviderShape } from "./ServerProvider.ts";\n-\n-export interface OpenCodeProviderShape extends ServerProviderShape {}\n-\n-export class OpenCodeProvider extends Context.Service<OpenCodeProvider, OpenCodeProviderShape>()(\n- "t3/provider/Services/OpenCodeProvider",\n-) {}\ndiff --git a/apps/server/src/provider/Services/ProviderAdapter.ts b/apps/server/src/provider/Services/ProviderAdapter.ts\nindex 91155764f1..dd1be73872 100644\n--- a/apps/server/src/provider/Services/ProviderAdapter.ts\n+++ b/apps/server/src/provider/Services/ProviderAdapter.ts\n@@ -10,7 +10,7 @@\n import type {\n ApprovalRequestId,\n ProviderApprovalDecision,\n- ProviderKind,\n+ ProviderDriverKind,\n ProviderUserInputAnswers,\n ProviderRuntimeEvent,\n ProviderSendTurnInput,\n@@ -46,7 +46,7 @@ export interface ProviderAdapterShape<TError> {\n /**\n * Provider kind implemented by this adapter.\n */\n- readonly provider: ProviderKind;\n+ readonly provider: ProviderDriverKind;\n readonly capabilities: ProviderAdapterCapabilities;\n \n /**\ndiff --git a/apps/server/src/provider/Services/ProviderAdapterRegistry.ts b/apps/server/src/provider/Services/ProviderAdapterRegistry.ts\nindex b8e9d4b21c..1161487d5a 100644\n--- a/apps/server/src/provider/Services/ProviderAdapterRegistry.ts\n+++ b/apps/server/src/provider/Services/ProviderAdapterRegistry.ts\n@@ -1,34 +1,91 @@\n /**\n * ProviderAdapterRegistry - Lookup boundary for provider adapter implementations.\n *\n- * Maps a provider kind to the concrete adapter service (Codex, Claude, etc).\n- * It does not own session lifecycle or routing rules; `ProviderService` uses\n- * this registry together with `ProviderSessionDirectory`.\n+ * Maps a `ProviderInstanceId` (the new per-instance routing key) or a\n+ * `ProviderDriverKind` (legacy single-instance-per-driver key) to the concrete\n+ * adapter service (Codex, Claude, etc). It does not own session lifecycle\n+ * or routing rules; `ProviderService` uses this registry together with\n+ * `ProviderSessionDirectory`.\n+ *\n+ * During the driver/instance migration this tag exposes both flavours:\n+ *\n+ * - `getByInstance` / `listInstances` — new per-instance routing. Callers\n+ * that already know an `instanceId` (threads, sessions, events)\n+ * should prefer these.\n+ * (`defaultInstanceIdForDriver(kind) === kind`), matching the pre-Slice-D\n+ * behaviour. New code should not grow additional callers of the kind-keyed\n+ * methods; they exist so the settings UI, WS refresh RPC, and a handful\n+ * of legacy persisted rows can still be routed during the rollout.\n *\n * @module ProviderAdapterRegistry\n */\n-import type { ProviderKind } from "@t3tools/contracts";\n+import type { ProviderDriverKind, ProviderInstanceId } from "@t3tools/contracts";\n import { Context } from "effect";\n-import type { Effect } from "effect";\n+import type { Effect, PubSub, Scope, Stream } from "effect";\n \n import type { ProviderAdapterError, ProviderUnsupportedError } from "../Errors.ts";\n import type { ProviderAdapterShape } from "./ProviderAdapter.ts";\n+import type { ProviderContinuationIdentity } from "../ProviderDriver.ts";\n+\n+export interface ProviderInstanceRoutingInfo {\n+ readonly instanceId: ProviderInstanceId;\n+ readonly driverKind: ProviderDriverKind;\n+ readonly displayName: string | undefined;\n+ readonly accentColor?: string | undefined;\n+ readonly enabled: boolean;\n+ readonly continuationIdentity: ProviderContinuationIdentity;\n+}\n \n /**\n- * ProviderAdapterRegistryShape - Service API for adapter lookup by provider kind.\n+ * ProviderAdapterRegistryShape - Service API for adapter lookup.\n */\n export interface ProviderAdapterRegistryShape {\n /**\n- * Resolve the adapter for a provider kind.\n+ * Resolve the adapter for a specific instance id. Returns\n+ * `ProviderUnsupportedError` if no such instance is currently registered\n+ * (which covers "never configured" *and* "configured but the driver is\n+ * unavailable in this build" — both surface the same failure to callers\n+ * that expect a working adapter).\n */\n- readonly getByProvider: (\n- provider: ProviderKind,\n+ readonly getByInstance: (\n+ instanceId: ProviderInstanceId,\n ) => Effect.Effect<ProviderAdapterShape<ProviderAdapterError>, ProviderUnsupportedError>;\n \n+ readonly getInstanceInfo: (\n+ instanceId: ProviderInstanceId,\n+ ) => Effect.Effect<ProviderInstanceRoutingInfo, ProviderUnsupportedError>;\n+\n+ /**\n+ * List all live instance ids. Excludes unavailable/shadow instances —\n+ * callers of this method want something they can pass to `getByInstance`.\n+ */\n+ readonly listInstances: () => Effect.Effect<ReadonlyArray<ProviderInstanceId>>;\n+\n /**\n- * List provider kinds currently registered.\n+ * Legacy: list provider kinds whose default instance is currently\n+ * registered.\n+ *\n+ * @deprecated Prefer `listInstances`. Retained for migration-era call\n+ * sites that iterate providers to build UI/metrics.\n */\n- readonly listProviders: () => Effect.Effect<ReadonlyArray<ProviderKind>>;\n+ readonly listProviders: () => Effect.Effect<ReadonlyArray<ProviderDriverKind>>;\n+\n+ /**\n+ * Change notification stream mirroring `ProviderInstanceRegistry.streamChanges`.\n+ * Emits one `void` tick whenever the set of live instances changes\n+ * (instance added, removed, or rebuilt after a settings edit). Consumers\n+ * that fan out `adapter.streamEvents` per instance — e.g. `ProviderService`\'s\n+ * runtime event bus — re-pull `listInstances` on each tick and fork new\n+ * subscriptions for instances they haven\'t seen yet.\n+ */\n+ readonly streamChanges: Stream.Stream<void>;\n+\n+ /**\n+ * Acquire a change subscription synchronously in the caller\'s current fiber.\n+ * Consumers that must avoid missing a publish between initial reconciliation\n+ * and watcher startup should use this, then fork `Stream.fromSubscription`.\n+ */\n+ readonly subscribeChanges: Effect.Effect<PubSub.Subscription<void>, never, Scope.Scope>;\n }\n \n /**\n@@ -38,5 +95,3 @@ export class ProviderAdapterRegistry extends Context.Service<\n ProviderAdapterRegistry,\n ProviderAdapterRegistryShape\n >()("t3/provider/Services/ProviderAdapterRegistry") {}\n-\n-// Dummy comment for workflow testing.\ndiff --git a/apps/server/src/provider/Services/ProviderInstanceRegistry.ts b/apps/server/src/provider/Services/ProviderInstanceRegistry.ts\nnew file mode 100644\nindex 0000000000..f642475a24\n--- /dev/null\n+++ b/apps/server/src/provider/Services/ProviderInstanceRegistry.ts\n@@ -0,0 +1,84 @@\n+/**\n+ * ProviderInstanceRegistry — the single Effect service in the new model.\n+ *\n+ * Owns a `Map<ProviderInstanceId, ProviderInstance>` produced by running\n+ * registered driver factories against `ServerSettings.providerInstances`.\n+ * The registry watches settings; when an instance\'s config changes (or\n+ * the entry disappears), the registry tears down the affected instance\'s\n+ * scope and rebuilds — that\'s the entire hot-reload story.\n+ *\n+ * What rest-of-server reads from here:\n+ * - `getInstance(instanceId)` — for routing turn/session calls.\n+ * - `listInstances` — for snapshot aggregation in `ProviderRegistry`.\n+ * - `listUnavailable` — `ServerProvider` shadows for instances whose\n+ * driver is not registered in this build (rollback / fork tolerance).\n+ * - `streamChanges` — coalesced "registry mutated" pings so consumers\n+ * can re-pull lists or re-broadcast.\n+ *\n+ * @module provider/Services/ProviderInstanceRegistry\n+ */\n+import type { ProviderInstanceId, ServerProvider } from "@t3tools/contracts";\n+import { Context } from "effect";\n+import type { Effect, PubSub, Scope, Stream } from "effect";\n+\n+import type { ProviderInstance } from "../ProviderDriver.ts";\n+\n+export interface ProviderInstanceRegistryShape {\n+ /**\n+ * Look up one instance by id. Returns `undefined` (not Option) when the\n+ * id is unknown — callers branch on falsy and emit\n+ * `ProviderInstanceNotFoundError`.\n+ */\n+ readonly getInstance: (\n+ instanceId: ProviderInstanceId,\n+ ) => Effect.Effect<ProviderInstance | undefined>;\n+ /**\n+ * Every available (driver-registered, successfully created) instance,\n+ * in stable settings-author order.\n+ */\n+ readonly listInstances: Effect.Effect<ReadonlyArray<ProviderInstance>>;\n+ /**\n+ * Wire-shape shadow snapshots for instances whose driver is unknown to\n+ * this build (or whose config failed to decode). Suitable for merging\n+ * directly into `ProviderRegistry` output.\n+ */\n+ readonly listUnavailable: Effect.Effect<ReadonlyArray<ServerProvider>>;\n+ /**\n+ * Push notification stream emitted whenever the registry\'s contents\n+ * change — instance added, removed, or rebuilt. The payload is `void`\n+ * because consumers always want to re-pull `listInstances` /\n+ * `listUnavailable` together.\n+ *\n+ * NOTE: because `Stream.fromPubSub` defers `PubSub.subscribe` until the\n+ * stream starts running, forking a consumer via\n+ * `Stream.runForEach(...).pipe(Effect.forkScoped)` races the next\n+ * publish — the forked fiber may not have subscribed yet when the\n+ * publish lands. Hot-reload consumers that must not miss a publish\n+ * should use `subscribeChanges` below instead, which acquires the\n+ * subscription synchronously in the caller\'s fiber before the consumer\n+ * loop is forked.\n+ */\n+ readonly streamChanges: Stream.Stream<void>;\n+ /**\n+ * Acquire a subscription to the registry\'s change channel synchronously\n+ * in the caller\'s fiber. Returns a `PubSub.Subscription<void>` whose\n+ * lifetime is scoped to the provided `Scope` (the subscription is\n+ * released when the scope closes). Consumers typically `yield*` this\n+ * in the same fiber that forks their consumer loop, then drain with\n+ * `PubSub.take(subscription)` inside `Effect.forever`. Because the\n+ * subscription is registered with the PubSub before this `yield*`\n+ * returns, no subsequent publish can land in a gap.\n+ *\n+ * This exists because the `ProviderInstanceRegistry` publishes on a\n+ * PubSub and `Stream.fromPubSub` defers subscription until the stream\n+ * starts executing — a consumer that `forkScoped`s the stream\n+ * consumption can miss a publish that lands in the narrow window\n+ * between "fiber scheduled" and "fiber starts running".\n+ */\n+ readonly subscribeChanges: Effect.Effect<PubSub.Subscription<void>, never, Scope.Scope>;\n+}\n+\n+export class ProviderInstanceRegistry extends Context.Service<\n+ ProviderInstanceRegistry,\n+ ProviderInstanceRegistryShape\n+>()("t3/provider/Services/ProviderInstanceRegistry") {}\ndiff --git a/apps/server/src/provider/Services/ProviderInstanceRegistryMutator.ts b/apps/server/src/provider/Services/ProviderInstanceRegistryMutator.ts\nnew file mode 100644\nindex 0000000000..ff861f961c\n--- /dev/null\n+++ b/apps/server/src/provider/Services/ProviderInstanceRegistryMutator.ts\n@@ -0,0 +1,52 @@\n+/**\n+ * ProviderInstanceRegistryMutator — internal handle used by the hydration\n+ * layer to reconcile the live registry with a fresh\n+ * `ProviderInstanceConfigMap`.\n+ *\n+ * Kept separate from the public `ProviderInstanceRegistry` service tag so\n+ * downstream consumers (drivers, reactors, `ProviderService`) can only read\n+ * from the registry. Only the hydration layer — which watches\n+ * `ServerSettingsService.streamChanges` and applies diffs — imports this\n+ * tag.\n+ *\n+ * The mutator exposes a single entry point, `reconcile(configMap)`, which:\n+ *\n+ * 1. Diffs the incoming map against the live one keyed by instance id.\n+ * 2. Closes the per-instance `Scope` of every removed or replaced entry\n+ * (tearing down adapter processes, refresh fibres, temp files) BEFORE\n+ * creating the replacement — `reconcile` guarantees "at most one live\n+ * instance per id" at all times.\n+ * 3. Opens a fresh child `Scope` for every added or replaced entry, runs\n+ * the driver\'s `create`, and stores the resulting `ProviderInstance`\n+ * plus its scope.\n+ * 4. Publishes one `void` tick on the registry\'s `streamChanges` PubSub at\n+ * the end of the batch — consumers re-pull `listInstances` /\n+ * `listUnavailable`.\n+ *\n+ * `reconcile` is idempotent: calling it with an unchanged config map is a\n+ * no-op (no scope churn, no pubsub emission).\n+ *\n+ * @module provider/Services/ProviderInstanceRegistryMutator\n+ */\n+import type { ProviderInstanceConfigMap } from "@t3tools/contracts";\n+import { Context } from "effect";\n+import type { Effect } from "effect";\n+\n+export interface ProviderInstanceRegistryMutatorShape {\n+ /**\n+ * Bring the live registry in line with the supplied config map. See\n+ * module docs for the add / remove / replace semantics.\n+ *\n+ * The effect never fails: individual driver `create` failures are\n+ * captured as "unavailable" shadow snapshots inside the registry, the\n+ * same way boot-time failures are handled by\n+ * `makeProviderInstanceRegistry`. This keeps settings-watcher loops from\n+ * erroring out on a single bad entry.\n+ */\n+ readonly reconcile: (configMap: ProviderInstanceConfigMap) => Effect.Effect<void>;\n+}\n+\n+export class ProviderInstanceRegistryMutator extends Context.Service<\n+ ProviderInstanceRegistryMutator,\n+ ProviderInstanceRegistryMutatorShape\n+>()("t3/provider/Services/ProviderInstanceRegistryMutator") {}\ndiff --git a/apps/server/src/provider/Services/ProviderRegistry.ts b/apps/server/src/provider/Services/ProviderRegistry.ts\nindex 2e04fa253b..13a87bd873 100644\n--- a/apps/server/src/provider/Services/ProviderRegistry.ts\n+++ b/apps/server/src/provider/Services/ProviderRegistry.ts\n@@ -6,23 +6,42 @@\n *\n * @module ProviderRegistry\n */\n-import type { ProviderKind, ServerProvider } from "@t3tools/contracts";\n+import type { ProviderInstanceId, ProviderDriverKind, ServerProvider } from "@t3tools/contracts";\n import { Context } from "effect";\n import type { Effect, Stream } from "effect";\n \n export interface ProviderRegistryShape {\n /**\n- * Read the latest provider snapshots.\n+ * Read the latest provider snapshots for every configured instance.\n+ * Multiple snapshots may share the same `provider` kind (multiple\n+ * instances of the same driver) and disambiguate via `instanceId`.\n */\n readonly getProviders: Effect.Effect<ReadonlyArray<ServerProvider>>;\n \n /**\n- * Refresh all providers, or a single provider when specified.\n+ * Refresh all providers, or the default instance of the specified\n+ * kind when supplied.\n+ *\n+ * Retained for back-compat with legacy call sites (WS refresh RPC,\n+ * orchestration metrics). New code should prefer `refreshInstance`.\n+ *\n+ * @deprecated prefer `refreshInstance` for new call sites.\n */\n- readonly refresh: (provider?: ProviderKind) => Effect.Effect<ReadonlyArray<ServerProvider>>;\n+ readonly refresh: (provider?: ProviderDriverKind) => Effect.Effect<ReadonlyArray<ServerProvider>>;\n \n /**\n- * Stream of provider snapshot updates.\n+ * Refresh the specific configured instance. Returns the updated snapshot\n+ * list. When the instance id is unknown the call resolves with the\n+ * currently cached list (no error) — matching the legacy `refresh` shim\n+ * behaviour so transport layers don\'t have to special-case unknowns.\n+ */\n+ readonly refreshInstance: (\n+ instanceId: ProviderInstanceId,\n+ ) => Effect.Effect<ReadonlyArray<ServerProvider>>;\n+\n+ /**\n+ * Stream of provider snapshot updates — one emission per aggregated\n+ * change. The array contains the full current state.\n */\n readonly streamChanges: Stream.Stream<ReadonlyArray<ServerProvider>>;\n }\ndiff --git a/apps/server/src/provider/Services/ProviderService.ts b/apps/server/src/provider/Services/ProviderService.ts\nindex 1e461fcd1c..17a64689b4 100644\n--- a/apps/server/src/provider/Services/ProviderService.ts\n+++ b/apps/server/src/provider/Services/ProviderService.ts\n@@ -13,7 +13,7 @@\n */\n import type {\n ProviderInterruptTurnInput,\n- ProviderKind,\n+ ProviderInstanceId,\n ProviderRespondToRequestInput,\n ProviderRespondToUserInputInput,\n ProviderRuntimeEvent,\n@@ -29,6 +29,7 @@ import type { Effect, Stream } from "effect";\n \n import type { ProviderServiceError } from "../Errors.ts";\n import type { ProviderAdapterCapabilities } from "./ProviderAdapter.ts";\n+import type { ProviderInstanceRoutingInfo } from "./ProviderAdapterRegistry.ts";\n \n /**\n * ProviderServiceShape - Service API for provider session and turn orchestration.\n@@ -85,12 +86,16 @@ export interface ProviderServiceShape {\n readonly listSessions: () => Effect.Effect<ReadonlyArray<ProviderSession>>;\n \n /**\n- * Read static capabilities for a provider adapter.\n+ * Read capabilities for the adapter bound to a configured provider instance.\n */\n readonly getCapabilities: (\n- provider: ProviderKind,\n+ instanceId: ProviderInstanceId,\n ) => Effect.Effect<ProviderAdapterCapabilities, ProviderServiceError>;\n \n+ readonly getInstanceInfo: (\n+ instanceId: ProviderInstanceId,\n+ ) => Effect.Effect<ProviderInstanceRoutingInfo, ProviderServiceError>;\n+\n /**\n * Roll back provider conversation state by a number of turns.\n */\ndiff --git a/apps/server/src/provider/Services/ProviderSessionDirectory.ts b/apps/server/src/provider/Services/ProviderSessionDirectory.ts\nindex bee7a1b373..99ffb800f9 100644\n--- a/apps/server/src/provider/Services/ProviderSessionDirectory.ts\n+++ b/apps/server/src/provider/Services/ProviderSessionDirectory.ts\n@@ -1,5 +1,6 @@\n import type {\n- ProviderKind,\n+ ProviderInstanceId,\n+ ProviderDriverKind,\n ProviderSessionRuntimeStatus,\n RuntimeMode,\n ThreadId,\n@@ -14,7 +15,13 @@ import type {\n \n export interface ProviderRuntimeBinding {\n readonly threadId: ThreadId;\n- readonly provider: ProviderKind;\n+ readonly provider: ProviderDriverKind;\n+ /**\n+ * Routing key for the configured provider instance that owns this\n+ * session. The persistence layer promotes legacy null rows before\n+ * exposing bindings; runtime callers must not infer this from `provider`.\n+ */\n+ readonly providerInstanceId?: ProviderInstanceId;\n readonly adapterKey?: string;\n readonly status?: ProviderSessionRuntimeStatus;\n readonly resumeCursor?: unknown | null;\n@@ -39,7 +46,7 @@ export interface ProviderSessionDirectoryShape {\n \n readonly getProvider: (\n threadId: ThreadId,\n- ) => Effect.Effect<ProviderKind, ProviderSessionDirectoryReadError>;\n+ ) => Effect.Effect<ProviderDriverKind, ProviderSessionDirectoryReadError>;\n \n readonly getBinding: (\n threadId: ThreadId,\ndiff --git a/apps/server/src/provider/acp/AcpAdapterSupport.test.ts b/apps/server/src/provider/acp/AcpAdapterSupport.test.ts\nindex 7457713e0a..a7fcdc4c82 100644\n--- a/apps/server/src/provider/acp/AcpAdapterSupport.test.ts\n+++ b/apps/server/src/provider/acp/AcpAdapterSupport.test.ts\n@@ -1,5 +1,6 @@\n import { describe, expect, it } from "vitest";\n import * as EffectAcpErrors from "effect-acp/errors";\n+import { ProviderDriverKind } from "@t3tools/contracts";\n \n import { acpPermissionOutcome, mapAcpToAdapterError } from "./AcpAdapterSupport.ts";\n \n@@ -12,7 +13,7 @@ describe("AcpAdapterSupport", () => {\n \n it("maps ACP request errors to provider adapter request errors", () => {\n const error = mapAcpToAdapterError(\n- "cursor",\n+ ProviderDriverKind.make("cursor"),\n "thread-1" as never,\n "session/prompt",\n new EffectAcpErrors.AcpRequestError({\ndiff --git a/apps/server/src/provider/acp/AcpAdapterSupport.ts b/apps/server/src/provider/acp/AcpAdapterSupport.ts\nindex 914bb7e8c3..499ebd2e70 100644\n--- a/apps/server/src/provider/acp/AcpAdapterSupport.ts\n+++ b/apps/server/src/provider/acp/AcpAdapterSupport.ts\n@@ -1,6 +1,6 @@\n import {\n type ProviderApprovalDecision,\n- type ProviderKind,\n+ type ProviderDriverKind,\n type ThreadId,\n } from "@t3tools/contracts";\n import { Schema } from "effect";\n@@ -13,7 +13,7 @@ import {\n } from "../Errors.ts";\n \n export function mapAcpToAdapterError(\n- provider: ProviderKind,\n+ provider: ProviderDriverKind,\n threadId: ThreadId,\n method: string,\n error: EffectAcpErrors.AcpError,\ndiff --git a/apps/server/src/provider/acp/AcpCoreRuntimeEvents.test.ts b/apps/server/src/provider/acp/AcpCoreRuntimeEvents.test.ts\nindex 79b51f585b..713d066892 100644\n--- a/apps/server/src/provider/acp/AcpCoreRuntimeEvents.test.ts\n+++ b/apps/server/src/provider/acp/AcpCoreRuntimeEvents.test.ts\n@@ -1,4 +1,4 @@\n-import { RuntimeRequestId, TurnId } from "@t3tools/contracts";\n+import { ProviderDriverKind, RuntimeRequestId, TurnId } from "@t3tools/contracts";\n import { describe, expect, it } from "vitest";\n \n import {\n@@ -30,7 +30,7 @@ describe("AcpCoreRuntimeEvents", () => {\n expect(\n makeAcpRequestOpenedEvent({\n stamp,\n- provider: "cursor",\n+ provider: ProviderDriverKind.make("cursor"),\n threadId: "thread-1" as never,\n turnId,\n requestId: RuntimeRequestId.make("request-1"),\n@@ -52,7 +52,7 @@ describe("AcpCoreRuntimeEvents", () => {\n expect(\n makeAcpRequestResolvedEvent({\n stamp,\n- provider: "cursor",\n+ provider: ProviderDriverKind.make("cursor"),\n threadId: "thread-1" as never,\n turnId,\n requestId: RuntimeRequestId.make("request-1"),\n@@ -75,7 +75,7 @@ describe("AcpCoreRuntimeEvents", () => {\n expect(\n makeAcpPlanUpdatedEvent({\n stamp,\n- provider: "cursor",\n+ provider: ProviderDriverKind.make("cursor"),\n threadId: "thread-1" as never,\n turnId,\n payload: {\n@@ -95,7 +95,7 @@ describe("AcpCoreRuntimeEvents", () => {\n expect(\n makeAcpToolCallEvent({\n stamp,\n- provider: "cursor",\n+ provider: ProviderDriverKind.make("cursor"),\n threadId: "thread-1" as never,\n turnId,\n toolCall: {\n@@ -119,7 +119,7 @@ describe("AcpCoreRuntimeEvents", () => {\n expect(\n makeAcpContentDeltaEvent({\n stamp,\n- provider: "cursor",\n+ provider: ProviderDriverKind.make("cursor"),\n threadId: "thread-1" as never,\n turnId,\n itemId: "assistant:session-1:segment:0",\n@@ -137,7 +137,7 @@ describe("AcpCoreRuntimeEvents", () => {\n expect(\n makeAcpAssistantItemEvent({\n stamp,\n- provider: "cursor",\n+ provider: ProviderDriverKind.make("cursor"),\n threadId: "thread-1" as never,\n turnId,\n itemId: "assistant:session-1:segment:0",\ndiff --git a/apps/server/src/provider/acp/AcpCoreRuntimeEvents.ts b/apps/server/src/provider/acp/AcpCoreRuntimeEvents.ts\nindex 0c0f06cc62..c93e61dc37 100644\n--- a/apps/server/src/provider/acp/AcpCoreRuntimeEvents.ts\n+++ b/apps/server/src/provider/acp/AcpCoreRuntimeEvents.ts\n@@ -4,7 +4,7 @@ import {\n type CanonicalRequestType,\n type EventId,\n type ProviderApprovalDecision,\n- type ProviderKind,\n+ type ProviderDriverKind,\n type ProviderRuntimeEvent,\n type RuntimeRequestId,\n type ThreadId,\n@@ -78,7 +78,7 @@ function runtimeItemStatusFromAcpToolStatus(\n \n export function makeAcpRequestOpenedEvent(input: {\n readonly stamp: AcpEventStamp;\n- readonly provider: ProviderKind;\n+ readonly provider: ProviderDriverKind;\n readonly threadId: ThreadId;\n readonly turnId: TurnId | undefined;\n readonly requestId: RuntimeRequestId;\n@@ -111,7 +111,7 @@ export function makeAcpRequestOpenedEvent(input: {\n \n export function makeAcpRequestResolvedEvent(input: {\n readonly stamp: AcpEventStamp;\n- readonly provider: ProviderKind;\n+ readonly provider: ProviderDriverKind;\n readonly threadId: ThreadId;\n readonly turnId: TurnId | undefined;\n readonly requestId: RuntimeRequestId;\n@@ -134,7 +134,7 @@ export function makeAcpRequestResolvedEvent(input: {\n \n export function makeAcpPlanUpdatedEvent(input: {\n readonly stamp: AcpEventStamp;\n- readonly provider: ProviderKind;\n+ readonly provider: ProviderDriverKind;\n readonly threadId: ThreadId;\n readonly turnId: TurnId | undefined;\n readonly payload: AcpPlanUpdate;\n@@ -159,7 +159,7 @@ export function makeAcpPlanUpdatedEvent(input: {\n \n export function makeAcpToolCallEvent(input: {\n readonly stamp: AcpEventStamp;\n- readonly provider: ProviderKind;\n+ readonly provider: ProviderDriverKind;\n readonly threadId: ThreadId;\n readonly turnId: TurnId | undefined;\n readonly toolCall: AcpToolCallState;\n@@ -193,7 +193,7 @@ export function makeAcpToolCallEvent(input: {\n \n export function makeAcpAssistantItemEvent(input: {\n readonly stamp: AcpEventStamp;\n- readonly provider: ProviderKind;\n+ readonly provider: ProviderDriverKind;\n readonly threadId: ThreadId;\n readonly turnId: TurnId | undefined;\n readonly itemId: string;\n@@ -215,7 +215,7 @@ export function makeAcpAssistantItemEvent(input: {\n \n export function makeAcpContentDeltaEvent(input: {\n readonly stamp: AcpEventStamp;\n- readonly provider: ProviderKind;\n+ readonly provider: ProviderDriverKind;\n readonly threadId: ThreadId;\n readonly turnId: TurnId | undefined;\n readonly itemId?: string;\ndiff --git a/apps/server/src/provider/acp/AcpNativeLogging.ts b/apps/server/src/provider/acp/AcpNativeLogging.ts\nindex 2fb3f4e833..3d44aac0a4 100644\n--- a/apps/server/src/provider/acp/AcpNativeLogging.ts\n+++ b/apps/server/src/provider/acp/AcpNativeLogging.ts\n@@ -1,4 +1,4 @@\n-import type { ProviderKind, ThreadId } from "@t3tools/contracts";\n+import type { ProviderDriverKind, ThreadId } from "@t3tools/contracts";\n import { Cause, Effect } from "effect";\n import type * as EffectAcpProtocol from "effect-acp/protocol";\n \n@@ -7,7 +7,7 @@ import type { AcpSessionRequestLogEvent, AcpSessionRuntimeOptions } from "./AcpS\n \n function writeNativeAcpLog(input: {\n readonly nativeEventLogger: EventNdjsonLogger | undefined;\n- readonly provider: ProviderKind;\n+ readonly provider: ProviderDriverKind;\n readonly threadId: ThreadId;\n readonly kind: "request" | "protocol";\n readonly payload: unknown;\n@@ -44,7 +44,7 @@ function formatRequestLogPayload(event: AcpSessionRequestLogEvent) {\n \n export function makeAcpNativeLoggers(input: {\n readonly nativeEventLogger: EventNdjsonLogger | undefined;\n- readonly provider: ProviderKind;\n+ readonly provider: ProviderDriverKind;\n readonly threadId: ThreadId;\n }): Pick<AcpSessionRuntimeOptions, "requestLogger" | "protocolLogging"> {\n return {\ndiff --git a/apps/server/src/provider/acp/AcpSessionRuntime.ts b/apps/server/src/provider/acp/AcpSessionRuntime.ts\nindex d32e70cb4c..b4cf665608 100644\n--- a/apps/server/src/provider/acp/AcpSessionRuntime.ts\n+++ b/apps/server/src/provider/acp/AcpSessionRuntime.ts\n@@ -21,7 +21,7 @@ export interface AcpSpawnInput {\n readonly command: string;\n readonly args: ReadonlyArray<string>;\n readonly cwd?: string;\n- readonly env?: Readonly<Record<string, string>>;\n+ readonly env?: NodeJS.ProcessEnv;\n }\n \n export interface AcpSessionRuntimeOptions {\ndiff --git a/apps/server/src/provider/acp/CursorAcpSupport.ts b/apps/server/src/provider/acp/CursorAcpSupport.ts\nindex 25e342f0d0..3e405dd7ff 100644\n--- a/apps/server/src/provider/acp/CursorAcpSupport.ts\n+++ b/apps/server/src/provider/acp/CursorAcpSupport.ts\n@@ -23,6 +23,7 @@ export interface CursorAcpRuntimeInput extends Omit<\n > {\n readonly childProcessSpawner: ChildProcessSpawner.ChildProcessSpawner["Service"];\n readonly cursorSettings: CursorAcpRuntimeCursorSettings | null | undefined;\n+ readonly environment?: NodeJS.ProcessEnv;\n }\n \n export interface CursorAcpModelSelectionErrorContext {\n@@ -34,6 +35,7 @@ export interface CursorAcpModelSelectionErrorContext {\n export function buildCursorAcpSpawnInput(\n cursorSettings: CursorAcpRuntimeCursorSettings | null | undefined,\n cwd: string,\n+ environment?: NodeJS.ProcessEnv,\n ): AcpSpawnInput {\n return {\n command: cursorSettings?.binaryPath || "agent",\n@@ -42,6 +44,7 @@ export function buildCursorAcpSpawnInput(\n "acp",\n ],\n cwd,\n+ ...(environment ? { env: environment } : {}),\n };\n }\n \n@@ -52,7 +55,7 @@ export const makeCursorAcpRuntime = (\n const acpContext = yield* Layer.build(\n AcpSessionRuntime.layer({\n ...input,\n- spawn: buildCursorAcpSpawnInput(input.cursorSettings, input.cwd),\n+ spawn: buildCursorAcpSpawnInput(input.cursorSettings, input.cwd, input.environment),\n authMethodId: "cursor_login",\n clientCapabilities: CURSOR_PARAMETERIZED_MODEL_PICKER_CAPABILITIES,\n }).pipe(\ndiff --git a/apps/server/src/provider/builtInDrivers.ts b/apps/server/src/provider/builtInDrivers.ts\nnew file mode 100644\nindex 0000000000..5af56dc6b0\n--- /dev/null\n+++ b/apps/server/src/provider/builtInDrivers.ts\n@@ -0,0 +1,50 @@\n+/**\n+ * BUILT_IN_DRIVERS — the static set of `ProviderDriver`s this build ships\n+ * with.\n+ *\n+ * Every driver that the server knows how to instantiate from settings is\n+ * listed here. The `ProviderInstanceRegistry` iterates this array when\n+ * resolving `providerInstances` entries; anything not in the array surfaces\n+ * as an `"unavailable"` shadow snapshot at runtime (see\n+ * `buildUnavailableProviderSnapshot`).\n+ *\n+ * Adding a new first-party driver means:\n+ * 1. implement `ProviderDriver` in a sibling `Drivers/<Name>Driver.ts`,\n+ * 2. add it to this array,\n+ * 3. ensure the runtime layer satisfies its declared `R`.\n+ *\n+ * The aggregated `BuiltInDriversEnv` type is the union of every driver\'s\n+ * env requirement — the registry layer\'s `R` is this type, and the runtime\n+ * layer (ChildProcessSpawner, FileSystem, Path, ServerConfig,\n+ * OpenCodeRuntime, …) must satisfy it.\n+ *\n+ * @module provider/builtInDrivers\n+ */\n+import { ClaudeDriver, type ClaudeDriverEnv } from "./Drivers/ClaudeDriver.ts";\n+import { CodexDriver, type CodexDriverEnv } from "./Drivers/CodexDriver.ts";\n+import { CursorDriver, type CursorDriverEnv } from "./Drivers/CursorDriver.ts";\n+import { OpenCodeDriver, type OpenCodeDriverEnv } from "./Drivers/OpenCodeDriver.ts";\n+import type { AnyProviderDriver } from "./ProviderDriver.ts";\n+\n+/**\n+ * Union of infrastructure services required to construct any built-in\n+ * driver. The registry layer declares `R = BuiltInDriversEnv`; the runtime\n+ * layer must provide every service in this union.\n+ */\n+export type BuiltInDriversEnv =\n+ | ClaudeDriverEnv\n+ | CodexDriverEnv\n+ | CursorDriverEnv\n+ | OpenCodeDriverEnv;\n+\n+/**\n+ * Ordered list of built-in drivers. Order matters only for tie-breaking in\n+ * UI presentation — the registry itself is keyed by `driverKind`, so\n+ * iteration order has no functional effect on instance lookup.\n+ */\n+export const BUILT_IN_DRIVERS: ReadonlyArray<AnyProviderDriver<BuiltInDriversEnv>> = [\n+ CodexDriver,\n+ ClaudeDriver,\n+ CursorDriver,\n+ OpenCodeDriver,\n+];\ndiff --git a/apps/server/src/provider/builtInProviderCatalog.ts b/apps/server/src/provider/builtInProviderCatalog.ts\nindex 1fd10a85d9..ee25b6d018 100644\n--- a/apps/server/src/provider/builtInProviderCatalog.ts\n+++ b/apps/server/src/provider/builtInProviderCatalog.ts\n@@ -1,49 +1,17 @@\n-import type { ProviderKind, ServerProvider } from "@t3tools/contracts";\n+import type { ProviderDriverKind, ProviderInstanceId, ServerProvider } from "@t3tools/contracts";\n import type { Stream } from "effect";\n-import type { ProviderAdapterError } from "./Errors.ts";\n-import type { ProviderAdapterShape } from "./Services/ProviderAdapter.ts";\n import type { ServerProviderShape } from "./Services/ServerProvider.ts";\n \n export type ProviderSnapshotSource = {\n- readonly provider: ProviderKind;\n+ /**\n+ * Routing key — uniquely identifies this instance in the aggregated\n+ * snapshot list. Two different snapshot sources may share the same\n+ * driver kind (multiple instances of the same driver).\n+ */\n+ readonly instanceId: ProviderInstanceId;\n+ /** Driver implementation kind. */\n+ readonly driverKind: ProviderDriverKind;\n readonly getSnapshot: ServerProviderShape["getSnapshot"];\n readonly refresh: ServerProviderShape["refresh"];\n readonly streamChanges: Stream.Stream<ServerProvider>;\n };\n-\n-type BuiltInProviderServiceMap = Record<ProviderKind, ServerProviderShape>;\n-type BuiltInAdapterMap = {\n- readonly codex: ProviderAdapterShape<ProviderAdapterError>;\n- readonly claudeAgent: ProviderAdapterShape<ProviderAdapterError>;\n- readonly opencode: ProviderAdapterShape<ProviderAdapterError>;\n- readonly cursor?: ProviderAdapterShape<ProviderAdapterError>;\n-};\n-\n-export const BUILT_IN_PROVIDER_ORDER = [\n- "codex",\n- "claudeAgent",\n- "opencode",\n- "cursor",\n-] as const satisfies ReadonlyArray<ProviderKind>;\n-\n-export function createBuiltInProviderSources(\n- services: BuiltInProviderServiceMap,\n-): ReadonlyArray<ProviderSnapshotSource> {\n- return BUILT_IN_PROVIDER_ORDER.map((provider) => ({\n- provider,\n- getSnapshot: services[provider].getSnapshot,\n- refresh: services[provider].refresh,\n- streamChanges: services[provider].streamChanges,\n- }));\n-}\n-\n-export function createBuiltInAdapterList(\n- adapters: BuiltInAdapterMap,\n-): ReadonlyArray<ProviderAdapterShape<ProviderAdapterError>> {\n- return [\n- adapters.codex,\n- adapters.claudeAgent,\n- adapters.opencode,\n- ...(adapters.cursor ? [adapters.cursor] : []),\n- ];\n-}\ndiff --git a/apps/server/src/provider/makeManagedServerProvider.test.ts b/apps/server/src/provider/makeManagedServerProvider.test.ts\nindex 5d50d12e37..ff66476380 100644\n--- a/apps/server/src/provider/makeManagedServerProvider.test.ts\n+++ b/apps/server/src/provider/makeManagedServerProvider.test.ts\n@@ -1,5 +1,5 @@\n import { describe, it, assert } from "@effect/vitest";\n-import type { ServerProvider } from "@t3tools/contracts";\n+import { ProviderDriverKind, ProviderInstanceId, type ServerProvider } from "@t3tools/contracts";\n import { createModelCapabilities } from "@t3tools/shared/model";\n import { Deferred, Effect, Fiber, PubSub, Ref, Stream } from "effect";\n \n@@ -21,7 +21,8 @@ interface TestSettings {\n }\n \n const initialSnapshot: ServerProvider = {\n- provider: "codex",\n+ instanceId: ProviderInstanceId.make("codex"),\n+ driver: ProviderDriverKind.make("codex"),\n enabled: true,\n installed: true,\n version: null,\n@@ -35,7 +36,8 @@ const initialSnapshot: ServerProvider = {\n };\n \n const refreshedSnapshot: ServerProvider = {\n- provider: "codex",\n+ instanceId: ProviderInstanceId.make("codex"),\n+ driver: ProviderDriverKind.make("codex"),\n enabled: true,\n installed: true,\n version: "1.0.0",\ndiff --git a/apps/server/src/provider/opencodeRuntime.ts b/apps/server/src/provider/opencodeRuntime.ts\nindex 086584893c..3269c712a9 100644\n--- a/apps/server/src/provider/opencodeRuntime.ts\n+++ b/apps/server/src/provider/opencodeRuntime.ts\n@@ -109,6 +109,7 @@ export interface OpenCodeRuntimeShape {\n */\n readonly startOpenCodeServerProcess: (input: {\n readonly binaryPath: string;\n+ readonly environment?: NodeJS.ProcessEnv;\n readonly port?: number;\n readonly hostname?: string;\n readonly timeoutMs?: number;\n@@ -121,6 +122,7 @@ export interface OpenCodeRuntimeShape {\n readonly connectToOpenCodeServer: (input: {\n readonly binaryPath: string;\n readonly serverUrl?: string | null;\n+ readonly environment?: NodeJS.ProcessEnv;\n readonly port?: number;\n readonly hostname?: string;\n readonly timeoutMs?: number;\n@@ -128,6 +130,7 @@ export interface OpenCodeRuntimeShape {\n readonly runOpenCodeCommand: (input: {\n readonly binaryPath: string;\n readonly args: ReadonlyArray<string>;\n+ readonly environment?: NodeJS.ProcessEnv;\n }) => Effect.Effect<OpenCodeCommandResult, OpenCodeRuntimeError>;\n readonly createOpenCodeSdkClient: (input: {\n readonly baseUrl: string;\n@@ -274,7 +277,7 @@ const makeOpenCodeRuntime = Effect.gen(function* () {\n const child = yield* spawner.spawn(\n ChildProcess.make(input.binaryPath, [...input.args], {\n shell: process.platform === "win32",\n- env: process.env,\n+ env: input.environment ?? process.env,\n }),\n );\n const [stdout, stderr, code] = yield* Effect.all(\n@@ -332,7 +335,7 @@ const makeOpenCodeRuntime = Effect.gen(function* () {\n ChildProcess.make(input.binaryPath, args, {\n detached: process.platform !== "win32",\n env: {\n- ...process.env,\n+ ...(input.environment ?? process.env),\n OPENCODE_CONFIG_CONTENT: JSON.stringify({}),\n },\n }),\n@@ -472,6 +475,7 @@ const makeOpenCodeRuntime = Effect.gen(function* () {\n \n return startOpenCodeServerProcess({\n binaryPath: input.binaryPath,\n+ ...(input.environment !== undefined ? { environment: input.environment } : {}),\n ...(input.port !== undefined ? { port: input.port } : {}),\n ...(input.hostname !== undefined ? { hostname: input.hostname } : {}),\n ...(input.timeoutMs !== undefined ? { timeoutMs: input.timeoutMs } : {}),\ndiff --git a/apps/server/src/provider/providerSnapshot.test.ts b/apps/server/src/provider/providerSnapshot.test.ts\nindex f990afb2d6..449dca8fc5 100644\n--- a/apps/server/src/provider/providerSnapshot.test.ts\n+++ b/apps/server/src/provider/providerSnapshot.test.ts\n@@ -1,5 +1,5 @@\n import { describe, expect, it } from "vitest";\n-import type { ModelCapabilities } from "@t3tools/contracts";\n+import { ProviderDriverKind, type ModelCapabilities } from "@t3tools/contracts";\n import { createModelCapabilities } from "@t3tools/shared/model";\n \n import { providerModelsFromSettings } from "./providerSnapshot.ts";\n@@ -27,7 +27,7 @@ describe("providerModelsFromSettings", () => {\n it("applies the provided capabilities to custom models", () => {\n const models = providerModelsFromSettings(\n [],\n- "opencode",\n+ ProviderDriverKind.make("opencode"),\n ["openai/gpt-5"],\n OPENCODE_CUSTOM_MODEL_CAPABILITIES,\n );\ndiff --git a/apps/server/src/provider/providerSnapshot.ts b/apps/server/src/provider/providerSnapshot.ts\nindex f1f0307485..af0c91274c 100644\n--- a/apps/server/src/provider/providerSnapshot.ts\n+++ b/apps/server/src/provider/providerSnapshot.ts\n@@ -1,4 +1,5 @@\n import type {\n+ ProviderDriverKind,\n ModelCapabilities,\n ServerProvider,\n ServerProviderAuth,\n@@ -36,6 +37,8 @@ export interface ServerProviderPresentation {\n readonly showInteractionModeToggle?: boolean;\n }\n \n+export type ServerProviderDraft = Omit<ServerProvider, "instanceId" | "driver">;\n+\n export function nonEmptyTrimmed(value: string | undefined): string | undefined {\n if (!value) return undefined;\n const trimmed = value.trim();\n@@ -110,7 +113,7 @@ export function parseGenericCliVersion(output: string): string | null {\n \n export function providerModelsFromSettings(\n builtInModels: ReadonlyArray<ServerProviderModel>,\n- provider: ServerProvider["provider"],\n+ provider: ProviderDriverKind,\n customModels: ReadonlyArray<string>,\n customModelCapabilities: ModelCapabilities,\n ): ReadonlyArray<ServerProviderModel> {\n@@ -179,7 +182,6 @@ export function buildBooleanOptionDescriptor(input: {\n }\n \n export function buildServerProvider(input: {\n- provider: ServerProvider["provider"];\n presentation: ServerProviderPresentation;\n enabled: boolean;\n checkedAt: string;\n@@ -187,9 +189,8 @@ export function buildServerProvider(input: {\n slashCommands?: ReadonlyArray<ServerProviderSlashCommand>;\n skills?: ReadonlyArray<ServerProviderSkill>;\n probe: ProviderProbeResult;\n-}): ServerProvider {\n+}): ServerProviderDraft {\n return {\n- provider: input.provider,\n displayName: input.presentation.displayName,\n ...(input.presentation.badgeLabel ? { badgeLabel: input.presentation.badgeLabel } : {}),\n ...(typeof input.presentation.showInteractionModeToggle === "boolean"\ndiff --git a/apps/server/src/provider/providerStatusCache.test.ts b/apps/server/src/provider/providerStatusCache.test.ts\nindex 5a81341f6d..8986ba48f2 100644\n--- a/apps/server/src/provider/providerStatusCache.test.ts\n+++ b/apps/server/src/provider/providerStatusCache.test.ts\n@@ -1,23 +1,33 @@\n import * as NodeServices from "@effect/platform-node/NodeServices";\n-import type { ServerProvider } from "@t3tools/contracts";\n+import {\n+ defaultInstanceIdForDriver,\n+ ProviderDriverKind,\n+ ProviderInstanceId,\n+ type ServerProvider,\n+} from "@t3tools/contracts";\n import { createModelCapabilities } from "@t3tools/shared/model";\n import { assert, it } from "@effect/vitest";\n import { Effect, FileSystem } from "effect";\n \n import {\n hydrateCachedProvider,\n+ isCachedProviderCorrelated,\n readProviderStatusCache,\n resolveProviderStatusCachePath,\n writeProviderStatusCache,\n } from "./providerStatusCache.ts";\n \n const emptyCapabilities = createModelCapabilities({ optionDescriptors: [] });\n+const CODEX_DRIVER = ProviderDriverKind.make("codex");\n+const CLAUDE_AGENT_DRIVER = ProviderDriverKind.make("claudeAgent");\n+const OPENCODE_DRIVER = ProviderDriverKind.make("opencode");\n \n const makeProvider = (\n- provider: ServerProvider["provider"],\n+ provider: ProviderDriverKind,\n overrides?: Partial<ServerProvider>,\n ): ServerProvider => ({\n- provider,\n+ instanceId: defaultInstanceIdForDriver(provider),\n+ driver: provider,\n enabled: true,\n installed: true,\n version: "1.0.0",\n@@ -35,26 +45,26 @@ it.layer(NodeServices.layer)("providerStatusCache", (it) => {\n Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-provider-cache-" });\n- const codexProvider = makeProvider("codex");\n- const claudeProvider = makeProvider("claudeAgent", {\n+ const codexProvider = makeProvider(CODEX_DRIVER);\n+ const claudeProvider = makeProvider(CLAUDE_AGENT_DRIVER, {\n status: "warning",\n auth: { status: "unknown" },\n });\n- const openCodeProvider = makeProvider("opencode", {\n+ const openCodeProvider = makeProvider(OPENCODE_DRIVER, {\n status: "warning",\n auth: { status: "unknown", type: "opencode" },\n });\n- const codexPath = resolveProviderStatusCachePath({\n+ const codexPath = yield* resolveProviderStatusCachePath({\n cacheDir: tempDir,\n- provider: "codex",\n+ instanceId: defaultInstanceIdForDriver(ProviderDriverKind.make("codex")),\n });\n- const claudePath = resolveProviderStatusCachePath({\n+ const claudePath = yield* resolveProviderStatusCachePath({\n cacheDir: tempDir,\n- provider: "claudeAgent",\n+ instanceId: defaultInstanceIdForDriver(ProviderDriverKind.make("claudeAgent")),\n });\n- const openCodePath = resolveProviderStatusCachePath({\n+ const openCodePath = yield* resolveProviderStatusCachePath({\n cacheDir: tempDir,\n- provider: "opencode",\n+ instanceId: defaultInstanceIdForDriver(ProviderDriverKind.make("opencode")),\n });\n \n yield* writeProviderStatusCache({\n@@ -77,7 +87,7 @@ it.layer(NodeServices.layer)("providerStatusCache", (it) => {\n );\n \n it("hydrates cached provider status while preserving current settings-derived models", () => {\n- const cachedCodex = makeProvider("codex", {\n+ const cachedCodex = makeProvider(CODEX_DRIVER, {\n checkedAt: "2026-04-10T12:00:00.000Z",\n models: [\n {\n@@ -97,7 +107,7 @@ it.layer(NodeServices.layer)("providerStatusCache", (it) => {\n },\n ],\n });\n- const fallbackCodex = makeProvider("codex", {\n+ const fallbackCodex = makeProvider(CODEX_DRIVER, {\n models: [\n {\n slug: "gpt-5.4",\n@@ -138,11 +148,11 @@ it.layer(NodeServices.layer)("providerStatusCache", (it) => {\n });\n \n it("ignores stale cached enabled state when the provider is now disabled", () => {\n- const cachedCodex = makeProvider("codex", {\n+ const cachedCodex = makeProvider(CODEX_DRIVER, {\n checkedAt: "2026-04-10T12:00:00.000Z",\n message: "Cached ready status",\n });\n- const disabledFallback = makeProvider("codex", {\n+ const disabledFallback = makeProvider(CODEX_DRIVER, {\n enabled: false,\n installed: false,\n version: null,\n@@ -159,4 +169,68 @@ it.layer(NodeServices.layer)("providerStatusCache", (it) => {\n disabledFallback,\n );\n });\n+\n+ it("rejects cached snapshots that are not correlated to the fallback instance", () => {\n+ const fallbackCodex = makeProvider(CODEX_DRIVER, {\n+ models: [\n+ {\n+ slug: "gpt-5.4",\n+ name: "GPT-5.4",\n+ isCustom: false,\n+ capabilities: emptyCapabilities,\n+ },\n+ ],\n+ });\n+ const legacyCachedCodex = {\n+ provider: ProviderDriverKind.make("codex"),\n+ enabled: true,\n+ installed: true,\n+ version: "1.0.0",\n+ status: "ready",\n+ auth: { status: "authenticated" },\n+ checkedAt: "2026-04-10T12:00:00.000Z",\n+ models: [\n+ {\n+ slug: "cached-legacy-model",\n+ name: "Cached Legacy Model",\n+ isCustom: false,\n+ capabilities: emptyCapabilities,\n+ },\n+ ],\n+ slashCommands: [],\n+ skills: [],\n+ } as unknown as ServerProvider;\n+ const mismatchedCachedCodex = makeProvider(CODEX_DRIVER, {\n+ instanceId: ProviderInstanceId.make("codex_personal"),\n+ });\n+\n+ assert.strictEqual(\n+ isCachedProviderCorrelated({\n+ cachedProvider: legacyCachedCodex,\n+ fallbackProvider: fallbackCodex,\n+ }),\n+ false,\n+ );\n+ assert.deepStrictEqual(\n+ hydrateCachedProvider({\n+ cachedProvider: legacyCachedCodex,\n+ fallbackProvider: fallbackCodex,\n+ }),\n+ fallbackCodex,\n+ );\n+ assert.strictEqual(\n+ isCachedProviderCorrelated({\n+ cachedProvider: mismatchedCachedCodex,\n+ fallbackProvider: fallbackCodex,\n+ }),\n+ false,\n+ );\n+ assert.deepStrictEqual(\n+ hydrateCachedProvider({\n+ cachedProvider: mismatchedCachedCodex,\n+ fallbackProvider: fallbackCodex,\n+ }),\n+ fallbackCodex,\n+ );\n+ });\n });\ndiff --git a/apps/server/src/provider/providerStatusCache.ts b/apps/server/src/provider/providerStatusCache.ts\nindex fdb31eecbe..d6c051fd56 100644\n--- a/apps/server/src/provider/providerStatusCache.ts\n+++ b/apps/server/src/provider/providerStatusCache.ts\n@@ -1,25 +1,17 @@\n-import * as nodePath from "node:path";\n-import { type ServerProvider, ServerProvider as ServerProviderSchema } from "@t3tools/contracts";\n-import { Cause, Effect, FileSystem, Schema } from "effect";\n+import {\n+ type ProviderDriverKind,\n+ type ProviderInstanceId,\n+ type ServerProvider,\n+ ServerProvider as ServerProviderSchema,\n+} from "@t3tools/contracts";\n+import { Cause, Effect, FileSystem, Path, Schema } from "effect";\n \n import { writeFileStringAtomically } from "../atomicWrite.ts";\n \n-export const PROVIDER_CACHE_IDS = [\n- "codex",\n- "claudeAgent",\n- "opencode",\n- "cursor",\n-] as const satisfies ReadonlyArray<ServerProvider["provider"]>;\n-\n const decodeProviderStatusCache = Schema.decodeUnknownEffect(\n Schema.fromJsonString(ServerProviderSchema),\n );\n \n-const providerOrderRank = (provider: ServerProvider["provider"]): number => {\n- const rank = PROVIDER_CACHE_IDS.indexOf(provider);\n- return rank === -1 ? Number.MAX_SAFE_INTEGER : rank;\n-};\n-\n const mergeProviderModels = (\n fallbackModels: ReadonlyArray<ServerProvider["models"][number]>,\n cachedModels: ReadonlyArray<ServerProvider["models"][number]>,\n@@ -32,13 +24,27 @@ export const orderProviderSnapshots = (\n providers: ReadonlyArray<ServerProvider>,\n ): ReadonlyArray<ServerProvider> =>\n [...providers].toSorted(\n- (left, right) => providerOrderRank(left.provider) - providerOrderRank(right.provider),\n+ (left, right) =>\n+ (left.displayName ?? "").localeCompare(right.displayName ?? "") ||\n+ left.driver.localeCompare(right.driver) ||\n+ left.instanceId.localeCompare(right.instanceId),\n );\n \n+export const isCachedProviderCorrelated = (input: {\n+ readonly cachedProvider: ServerProvider;\n+ readonly fallbackProvider: ServerProvider;\n+}): boolean =>\n+ input.cachedProvider.instanceId === input.fallbackProvider.instanceId &&\n+ input.cachedProvider.driver === input.fallbackProvider.driver;\n+\n export const hydrateCachedProvider = (input: {\n readonly cachedProvider: ServerProvider;\n readonly fallbackProvider: ServerProvider;\n }): ServerProvider => {\n+ if (!isCachedProviderCorrelated(input)) {\n+ return input.fallbackProvider;\n+ }\n+\n if (\n !input.fallbackProvider.enabled ||\n input.cachedProvider.enabled !== input.fallbackProvider.enabled\n@@ -64,10 +70,46 @@ export const hydrateCachedProvider = (input: {\n : hydratedProvider;\n };\n \n-export const resolveProviderStatusCachePath = (input: {\n+/**\n+ * Resolve the on-disk cache path for a provider instance snapshot.\n+ *\n+ * File naming: `<cacheDir>/<instanceId>.json`. For the default instance of\n+ * a built-in kind this equals the legacy `<kind>.json` path (because\n+ * `defaultInstanceIdForDriver(kind).toString() === kind`), so existing\n+ * cached snapshots remain readable without any rename step.\n+ *\n+ * Non-default instances (e.g. `codex_personal`) land in their own files and\n+ * never collide with other instances.\n+ *\n+ * Cache contents must still carry matching `instanceId` + `driver` identity\n+ * before hydration. The filename alone is not trusted as a routing key.\n+ */\n+export const resolveProviderStatusCachePath = Effect.fn("resolveProviderStatusCachePath")(\n+ function* (input: {\n+ readonly cacheDir: string;\n+ readonly instanceId: ProviderInstanceId;\n+ }): Effect.fn.Return<string, never, Path.Path> {\n+ const path = yield* Path.Path;\n+ return path.join(input.cacheDir, `${input.instanceId}.json`);\n+ },\n+);\n+\n+/**\n+ * Legacy kind-keyed path resolver retained for callers that still think in\n+ * terms of `ProviderDriverKind`. Prefer `resolveProviderStatusCachePath` with an\n+ * `instanceId`; new code should route through the instance registry.\n+ *\n+ * @deprecated use `resolveProviderStatusCachePath` with an instance id.\n+ */\n+export const resolveLegacyProviderStatusCachePath = Effect.fn(\n+ "resolveLegacyProviderStatusCachePath",\n+)(function* (input: {\n readonly cacheDir: string;\n- readonly provider: ServerProvider["provider"];\n-}) => nodePath.join(input.cacheDir, `${input.provider}.json`);\n+ readonly provider: ProviderDriverKind;\n+}): Effect.fn.Return<string, never, Path.Path> {\n+ const path = yield* Path.Path;\n+ return path.join(input.cacheDir, `${input.provider}.json`);\n+});\n \n export const readProviderStatusCache = (filePath: string) =>\n Effect.gen(function* () {\ndiff --git a/apps/server/src/provider/testUtils/providerAdapterRegistryMock.ts b/apps/server/src/provider/testUtils/providerAdapterRegistryMock.ts\nnew file mode 100644\nindex 0000000000..9a4f107db8\n--- /dev/null\n+++ b/apps/server/src/provider/testUtils/providerAdapterRegistryMock.ts\n@@ -0,0 +1,95 @@\n+/**\n+ * Test helpers for constructing a `ProviderAdapterRegistryShape` mock from a\n+ * kind-keyed adapter map.\n+ *\n+ * Tests historically assembled a `registry` object with only `getByProvider`\n+ * + `listProviders` populated. Slice D grew the shape with `getByInstance`\n+ * and `listInstances`; this helper fills both in from a single kind-keyed\n+ * input so individual fixtures can stay concise.\n+ *\n+ * Non-default instance ids (e.g. `codex_personal`) are not addressable via\n+ * the shim returned here — the legacy test fixtures only ever had\n+ * single-instance-per-driver data anyway.\n+ *\n+ * @module provider/testUtils/providerAdapterRegistryMock\n+ */\n+import {\n+ defaultInstanceIdForDriver,\n+ ProviderDriverKind,\n+ type ProviderInstanceId,\n+} from "@t3tools/contracts";\n+import { Effect, PubSub, Record, Result, Stream } from "effect";\n+\n+import { ProviderUnsupportedError, type ProviderAdapterError } from "../Errors.ts";\n+import type { ProviderAdapterShape } from "../Services/ProviderAdapter.ts";\n+import type { ProviderAdapterRegistryShape } from "../Services/ProviderAdapterRegistry.ts";\n+\n+export type KindAdapterMap = Partial<\n+ Record<ProviderDriverKind, ProviderAdapterShape<ProviderAdapterError>>\n+>;\n+\n+/**\n+ * Build a `ProviderAdapterRegistryShape` from a kind-keyed adapter map.\n+ * Every adapter present in the map is addressable via both the legacy\n+ * `getByProvider(kind)` path and the new `getByInstance(id)` path (where\n+ * `id = defaultInstanceIdForDriver(kind)`).\n+ */\n+export const makeAdapterRegistryMock = (adapters: KindAdapterMap): ProviderAdapterRegistryShape => {\n+ const byInstanceId = new Map<ProviderInstanceId, ProviderAdapterShape<ProviderAdapterError>>();\n+ for (const [kind, adapter] of Object.entries(adapters)) {\n+ if (!adapter) continue;\n+ const driverKind = ProviderDriverKind.make(kind);\n+ byInstanceId.set(defaultInstanceIdForDriver(driverKind), adapter);\n+ }\n+\n+ const getByInstance: ProviderAdapterRegistryShape["getByInstance"] = (instanceId) => {\n+ const adapter = byInstanceId.get(instanceId);\n+ return adapter\n+ ? Effect.succeed(adapter)\n+ : Effect.fail(\n+ new ProviderUnsupportedError({\n+ provider: ProviderDriverKind.make(instanceId),\n+ }),\n+ );\n+ };\n+\n+ return {\n+ getByInstance,\n+ getInstanceInfo: (instanceId) => {\n+ const adapter = byInstanceId.get(instanceId);\n+ if (!adapter) {\n+ return Effect.fail(\n+ new ProviderUnsupportedError({\n+ provider: ProviderDriverKind.make(instanceId),\n+ }),\n+ );\n+ }\n+ return Effect.succeed({\n+ instanceId,\n+ driverKind: ProviderDriverKind.make(adapter.provider),\n+ displayName: undefined,\n+ enabled: true,\n+ continuationIdentity: {\n+ driverKind: ProviderDriverKind.make(adapter.provider),\n+ continuationKey: `${adapter.provider}:instance:${instanceId}`,\n+ },\n+ });\n+ },\n+ listInstances: () => Effect.succeed(Array.from(byInstanceId.keys())),\n+ listProviders: () =>\n+ Effect.succeed(\n+ Record.keys(\n+ Record.filterMap(adapters, (adapter, kind) =>\n+ adapter !== undefined ? Result.succeed(kind) : Result.failVoid,\n+ ),\n+ ),\n+ ),\n+ // Static test fixtures don\'t reload; an empty stream is enough to\n+ // satisfy the shape. Tests exercising hot-reload build their own\n+ // stream via the real `ProviderInstanceRegistry`.\n+ streamChanges: Stream.empty,\n+ subscribeChanges: Effect.flatMap(PubSub.unbounded<void>(), (pubsub) =>\n+ PubSub.subscribe(pubsub),\n+ ),\n+ };\n+};\ndiff --git a/apps/server/src/provider/unavailableProviderSnapshot.ts b/apps/server/src/provider/unavailableProviderSnapshot.ts\nnew file mode 100644\nindex 0000000000..97a532a9d9\n--- /dev/null\n+++ b/apps/server/src/provider/unavailableProviderSnapshot.ts\n@@ -0,0 +1,72 @@\n+/**\n+ * Helpers for synthesizing "unavailable" `ServerProvider` snapshots.\n+ *\n+ * When `ServerSettings.providerInstances` (or persisted thread/session\n+ * state) references a driver this build does not ship — typical after a\n+ * downgrade from a fork or a feature-branch test session — the runtime\n+ * needs to surface the entry to the UI without crashing. This module\n+ * produces shadow snapshots that satisfy `ServerProvider`\'s wire shape\n+ * while signalling unavailability.\n+ *\n+ * @module unavailableProviderSnapshot\n+ */\n+import {\n+ ProviderDriverKind,\n+ type ProviderInstanceId,\n+ type ServerProvider,\n+} from "@t3tools/contracts";\n+\n+import { buildServerProvider } from "./providerSnapshot.ts";\n+\n+export interface UnavailableProviderSnapshotInput {\n+ readonly driverKind: ProviderDriverKind | string;\n+ readonly instanceId: ProviderInstanceId;\n+ readonly displayName?: string | undefined;\n+ readonly accentColor?: string | undefined;\n+ readonly reason: string;\n+ /**\n+ * Optional override for `checkedAt`. Defaulted to `new Date()` so callers\n+ * (notably tests) don\'t have to pass it.\n+ */\n+ readonly checkedAt?: string;\n+}\n+\n+/**\n+ * Produce a `ServerProvider` snapshot representing a configured instance\n+ * whose driver the running build does not implement. The result is safe\n+ * to broadcast over the wire and is structured so the web UI can render\n+ * a "missing driver" affordance without special-casing.\n+ */\n+export function buildUnavailableProviderSnapshot(\n+ input: UnavailableProviderSnapshotInput,\n+): ServerProvider {\n+ const checkedAt = input.checkedAt ?? new Date().toISOString();\n+ const displayName = input.displayName?.trim() || (input.driverKind as string);\n+\n+ const base = buildServerProvider({\n+ presentation: { displayName },\n+ enabled: false,\n+ checkedAt,\n+ models: [],\n+ skills: [],\n+ probe: {\n+ installed: false,\n+ version: null,\n+ status: "error",\n+ auth: { status: "unknown" },\n+ message: input.reason,\n+ },\n+ });\n+\n+ return {\n+ ...base,\n+ instanceId: input.instanceId,\n+ ...(input.accentColor ? { accentColor: input.accentColor } : {}),\n+ driver:\n+ typeof input.driverKind === "string"\n+ ? ProviderDriverKind.make(input.driverKind)\n+ : input.driverKind,\n+ availability: "unavailable",\n+ unavailableReason: input.reason,\n+ };\n+}\ndiff --git a/apps/server/src/server.test.ts b/apps/server/src/server.test.ts\nindex 47e159d303..e699ad8339 100644\n--- a/apps/server/src/server.test.ts\n+++ b/apps/server/src/server.test.ts\n@@ -17,6 +17,8 @@ import {\n type OrchestrationEvent,\n ORCHESTRATION_WS_METHODS,\n ProjectId,\n+ ProviderDriverKind,\n+ ProviderInstanceId,\n ResolvedKeybindingRule,\n ThreadId,\n WS_METHODS,\n@@ -110,7 +112,7 @@ const defaultProjectId = ProjectId.make("project-default");\n const defaultThreadId = ThreadId.make("thread-default");\n const defaultDesktopBootstrapToken = "test-desktop-bootstrap-token";\n const defaultModelSelection = {\n- provider: "codex",\n+ instanceId: ProviderInstanceId.make("codex"),\n model: "gpt-5-codex",\n } as const;\n const testEnvironmentDescriptor = {\n@@ -1845,7 +1847,8 @@ it.layer(NodeServices.layer)("server router seam", (it) => {\n Effect.gen(function* () {\n const providers = [\n {\n- provider: "codex" as const,\n+ instanceId: ProviderInstanceId.make("codex"),\n+ driver: ProviderDriverKind.make("codex"),\n enabled: true,\n installed: true,\n version: "1.0.0",\n@@ -1915,7 +1918,8 @@ it.layer(NodeServices.layer)("server router seam", (it) => {\n Effect.gen(function* () {\n const nextProviders = [\n {\n- provider: "codex" as const,\n+ instanceId: ProviderInstanceId.make("codex"),\n+ driver: ProviderDriverKind.make("codex"),\n enabled: true,\n installed: true,\n version: "1.0.0",\n@@ -2164,7 +2168,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {\n workspaceRoot: missingWorkspaceRoot,\n createWorkspaceRootIfMissing: true,\n defaultModelSelection: {\n- provider: "codex",\n+ instanceId: ProviderInstanceId.make("codex"),\n model: "gpt-5-codex",\n },\n createdAt: new Date().toISOString(),\ndiff --git a/apps/server/src/server.ts b/apps/server/src/server.ts\nindex f94bbb34b5..85f2d84ad2 100644\n--- a/apps/server/src/server.ts\n+++ b/apps/server/src/server.ts\n@@ -16,22 +16,20 @@ import { OpenLive } from "./open.ts";\n import { layerConfig as SqlitePersistenceLayerLive } from "./persistence/Layers/Sqlite.ts";\n import { ServerLifecycleEventsLive } from "./serverLifecycleEvents.ts";\n import { AnalyticsServiceLayerLive } from "./telemetry/Layers/AnalyticsService.ts";\n-import { makeEventNdjsonLogger } from "./provider/Layers/EventNdjsonLogger.ts";\n import { ProviderSessionDirectoryLive } from "./provider/Layers/ProviderSessionDirectory.ts";\n import { ProviderSessionRuntimeRepositoryLive } from "./persistence/Layers/ProviderSessionRuntime.ts";\n-import { makeCodexAdapterLive } from "./provider/Layers/CodexAdapter.ts";\n-import { makeClaudeAdapterLive } from "./provider/Layers/ClaudeAdapter.ts";\n-import { makeCursorAdapterLive } from "./provider/Layers/CursorAdapter.ts";\n-import { makeOpenCodeAdapterLive } from "./provider/Layers/OpenCodeAdapter.ts";\n import { ProviderAdapterRegistryLive } from "./provider/Layers/ProviderAdapterRegistry.ts";\n-import { makeProviderServiceLive } from "./provider/Layers/ProviderService.ts";\n+import { ProviderEventLoggersLive } from "./provider/Layers/ProviderEventLoggers.ts";\n+import { ProviderServiceLive } from "./provider/Layers/ProviderService.ts";\n import { ProviderSessionReaperLive } from "./provider/Layers/ProviderSessionReaper.ts";\n+import { OpenCodeRuntimeLive } from "./provider/opencodeRuntime.ts";\n import { CheckpointDiffQueryLive } from "./checkpointing/Layers/CheckpointDiffQuery.ts";\n import { CheckpointStoreLive } from "./checkpointing/Layers/CheckpointStore.ts";\n import { GitCoreLive } from "./git/Layers/GitCore.ts";\n import { GitHubCliLive } from "./git/Layers/GitHubCli.ts";\n import { GitStatusBroadcasterLive } from "./git/Layers/GitStatusBroadcaster.ts";\n-import { RoutingTextGenerationLive } from "./git/Layers/RoutingTextGeneration.ts";\n+import { TextGenerationLive } from "./git/Layers/TextGenerationLive.ts";\n+import { ProviderInstanceRegistryHydrationLive } from "./provider/Layers/ProviderInstanceRegistryHydration.ts";\n import { TerminalManagerLive } from "./terminal/Layers/Manager.ts";\n import { GitManagerLive } from "./git/Layers/GitManager.ts";\n import { KeybindingsLive } from "./keybindings.ts";\n@@ -144,41 +142,15 @@ const ProviderSessionDirectoryLayerLive = ProviderSessionDirectoryLive.pipe(\n Layer.provide(ProviderSessionRuntimeRepositoryLive),\n );\n \n-const ProviderLayerLive = Layer.unwrap(\n- Effect.gen(function* () {\n- const { providerEventLogPath } = yield* ServerConfig;\n- const nativeEventLogger = yield* makeEventNdjsonLogger(providerEventLogPath, {\n- stream: "native",\n- });\n- const canonicalEventLogger = yield* makeEventNdjsonLogger(providerEventLogPath, {\n- stream: "canonical",\n- });\n- const codexAdapterLayer = makeCodexAdapterLive(\n- nativeEventLogger ? { nativeEventLogger } : undefined,\n- );\n- const claudeAdapterLayer = makeClaudeAdapterLive(\n- nativeEventLogger ? { nativeEventLogger } : undefined,\n- );\n- const openCodeAdapterLayer = makeOpenCodeAdapterLive(\n- nativeEventLogger ? { nativeEventLogger } : undefined,\n- );\n- const cursorAdapterLayer = makeCursorAdapterLive(\n- nativeEventLogger ? { nativeEventLogger } : undefined,\n- );\n- const adapterRegistryLayer = ProviderAdapterRegistryLive.pipe(\n- Layer.provide(codexAdapterLayer),\n- Layer.provide(claudeAdapterLayer),\n- Layer.provide(openCodeAdapterLayer),\n- Layer.provide(cursorAdapterLayer),\n- Layer.provideMerge(ProviderSessionDirectoryLayerLive),\n- );\n- return makeProviderServiceLive(\n- canonicalEventLogger ? { canonicalEventLogger } : undefined,\n- ).pipe(\n- Layer.provide(adapterRegistryLayer),\n- Layer.provideMerge(ProviderSessionDirectoryLayerLive),\n- );\n- }),\n+// `ProviderAdapterRegistryLive` is now a facade that resolves kind → adapter\n+// by looking up the default `ProviderInstance` per driver in the instance\n+// registry. Adapter construction itself moved inside each driver\'s\n+// `create()`; `ProviderEventLoggersLive` owns the shared native/canonical\n+// NDJSON writers and is provided at the outer runtime layer so both\n+// `ProviderService` and the per-instance drivers read the same logger pair.\n+const ProviderLayerLive = ProviderServiceLive.pipe(\n+ Layer.provide(ProviderAdapterRegistryLive),\n+ Layer.provideMerge(ProviderSessionDirectoryLayerLive),\n );\n \n const PersistenceLayerLive = Layer.empty.pipe(Layer.provideMerge(SqlitePersistenceLayerLive));\n@@ -187,7 +159,7 @@ const GitManagerLayerLive = GitManagerLive.pipe(\n Layer.provideMerge(ProjectSetupScriptRunnerLive),\n Layer.provideMerge(GitCoreLive),\n Layer.provideMerge(GitHubCliLive),\n- Layer.provideMerge(RoutingTextGenerationLive),\n+ Layer.provideMerge(TextGenerationLive),\n );\n \n const GitLayerLive = Layer.empty.pipe(\n@@ -233,6 +205,24 @@ const RuntimeDependenciesLive = ReactorLayerLive.pipe(\n Layer.provideMerge(PersistenceLayerLive),\n Layer.provideMerge(KeybindingsLive),\n Layer.provideMerge(ProviderRegistryLive),\n+ // The instance registry is the new routing keystone — text generation,\n+ // adapter lookup, and runtime ingestion all resolve `ProviderInstanceId`\n+ // through this layer. Built-in drivers come from `BUILT_IN_DRIVERS`;\n+ // `providerInstances` hydration merges `settings.providers.<kind>`\n+ // with explicit `providerInstances` entries on boot.\n+ Layer.provideMerge(ProviderInstanceRegistryHydrationLive),\n+ // Shared native/canonical NDJSON writers used by both the per-instance\n+ // drivers (native stream, written from inside each `<X>Adapter`) and\n+ // `ProviderService` (canonical stream, written after event normalization).\n+ // Provided once at the runtime level so every consumer sees the same\n+ // logger instances.\n+ Layer.provideMerge(ProviderEventLoggersLive),\n+ // `OpenCodeDriver.create()` yields `OpenCodeRuntime`; previously the old\n+ // `ProviderRegistryLive` pulled `OpenCodeRuntimeLive` in for itself, but\n+ // the rewritten registry reads snapshots off the instance registry and\n+ // no longer transitively provides it. Exposing it at the runtime level\n+ // keeps a single Live for all opencode consumers.\n+ Layer.provideMerge(OpenCodeRuntimeLive),\n Layer.provideMerge(ServerSettingsLive),\n Layer.provideMerge(WorkspaceLayerLive),\n Layer.provideMerge(ProjectFaviconResolverLive),\ndiff --git a/apps/server/src/serverRuntimeStartup.test.ts b/apps/server/src/serverRuntimeStartup.test.ts\nindex 836b71c7eb..91b4b215c1 100644\n--- a/apps/server/src/serverRuntimeStartup.test.ts\n+++ b/apps/server/src/serverRuntimeStartup.test.ts\n@@ -1,5 +1,5 @@\n import * as NodeServices from "@effect/platform-node/NodeServices";\n-import { DEFAULT_MODEL_BY_PROVIDER, ProjectId, ThreadId } from "@t3tools/contracts";\n+import { DEFAULT_MODEL, ProjectId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";\n import { assert, it } from "@effect/vitest";\n import { Deferred, Effect, Fiber, Option, Ref, Stream } from "effect";\n \n@@ -21,8 +21,8 @@ import {\n \n it("uses the canonical Codex default for auto-bootstrapped model selection", () => {\n assert.deepStrictEqual(getAutoBootstrapDefaultModelSelection(), {\n- provider: "codex",\n- model: DEFAULT_MODEL_BY_PROVIDER.codex,\n+ instanceId: ProviderInstanceId.make("codex"),\n+ model: DEFAULT_MODEL,\n });\n });\n \ndiff --git a/apps/server/src/serverRuntimeStartup.ts b/apps/server/src/serverRuntimeStartup.ts\nindex 99728f681f..1f164860a6 100644\n--- a/apps/server/src/serverRuntimeStartup.ts\n+++ b/apps/server/src/serverRuntimeStartup.ts\n@@ -1,9 +1,10 @@\n import {\n CommandId,\n- DEFAULT_MODEL_BY_PROVIDER,\n+ DEFAULT_MODEL,\n DEFAULT_PROVIDER_INTERACTION_MODE,\n type ModelSelection,\n ProjectId,\n+ ProviderInstanceId,\n ThreadId,\n } from "@t3tools/contracts";\n import {\n@@ -154,8 +155,8 @@ export const launchStartupHeartbeat = recordStartupHeartbeat.pipe(\n );\n \n export const getAutoBootstrapDefaultModelSelection = (): ModelSelection => ({\n- provider: "codex",\n- model: DEFAULT_MODEL_BY_PROVIDER.codex,\n+ instanceId: ProviderInstanceId.make("codex"),\n+ model: DEFAULT_MODEL,\n });\n \n export const resolveWelcomeBase = Effect.gen(function* () {\ndiff --git a/apps/server/src/serverSettings.test.ts b/apps/server/src/serverSettings.test.ts\nindex 55f598054b..f11c5bf451 100644\n--- a/apps/server/src/serverSettings.test.ts\n+++ b/apps/server/src/serverSettings.test.ts\n@@ -1,5 +1,11 @@\n import * as NodeServices from "@effect/platform-node/NodeServices";\n-import { DEFAULT_SERVER_SETTINGS, ServerSettings, ServerSettingsPatch } from "@t3tools/contracts";\n+import {\n+ DEFAULT_SERVER_SETTINGS,\n+ ProviderDriverKind,\n+ ProviderInstanceId,\n+ ServerSettings,\n+ ServerSettingsPatch,\n+} from "@t3tools/contracts";\n import { createModelSelection } from "@t3tools/shared/model";\n import { assert, it } from "@effect/vitest";\n import { Effect, FileSystem, Layer, Schema } from "effect";\n@@ -49,14 +55,14 @@ it.layer(NodeServices.layer)("server settings", (it) => {\n \n const decoded = decode({\n textGenerationModelSelection: {\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n model: "gpt-5.4-mini",\n options: { reasoningEffort: "low" },\n },\n });\n \n assert.deepEqual(decoded.textGenerationModelSelection, {\n- provider: "codex",\n+ instanceId: ProviderInstanceId.make("codex"),\n model: "gpt-5.4-mini",\n options: [{ id: "reasoningEffort", value: "low" }],\n });\n@@ -79,10 +85,10 @@ it.layer(NodeServices.layer)("server settings", (it) => {\n },\n },\n textGenerationModelSelection: {\n- provider: "codex",\n+ instanceId: ProviderInstanceId.make("codex"),\n model: DEFAULT_SERVER_SETTINGS.textGenerationModelSelection.model,\n options: createModelSelection(\n- "codex",\n+ ProviderInstanceId.make("codex"),\n DEFAULT_SERVER_SETTINGS.textGenerationModelSelection.model,\n [\n { id: "reasoningEffort", value: "high" },\n@@ -107,20 +113,26 @@ it.layer(NodeServices.layer)("server settings", (it) => {\n enabled: true,\n binaryPath: "/opt/homebrew/bin/codex",\n homePath: "/Users/julius/.codex",\n+ shadowHomePath: "",\n customModels: [],\n });\n assert.deepEqual(next.providers.claudeAgent, {\n enabled: true,\n binaryPath: "/usr/local/bin/claude",\n+ homePath: "",\n customModels: ["claude-custom"],\n launchArgs: "",\n });\n assert.deepEqual(\n next.textGenerationModelSelection,\n- createModelSelection("codex", DEFAULT_SERVER_SETTINGS.textGenerationModelSelection.model, [\n- { id: "reasoningEffort", value: "high" },\n- { id: "fastMode", value: false },\n- ]),\n+ createModelSelection(\n+ ProviderInstanceId.make("codex"),\n+ DEFAULT_SERVER_SETTINGS.textGenerationModelSelection.model,\n+ [\n+ { id: "reasoningEffort", value: "high" },\n+ { id: "fastMode", value: false },\n+ ],\n+ ),\n );\n }).pipe(Effect.provide(makeServerSettingsLayer())),\n );\n@@ -132,11 +144,13 @@ it.layer(NodeServices.layer)("server settings", (it) => {\n // Start with Claude text generation selection\n yield* serverSettings.updateSettings({\n textGenerationModelSelection: {\n- provider: "claudeAgent",\n+ instanceId: ProviderInstanceId.make("claudeAgent"),\n model: "claude-sonnet-4-6",\n- options: createModelSelection("claudeAgent", "claude-sonnet-4-6", [\n- { id: "effort", value: "high" },\n- ]).options!,\n+ options: createModelSelection(\n+ ProviderInstanceId.make("claudeAgent"),\n+ "claude-sonnet-4-6",\n+ [{ id: "effort", value: "high" }],\n+ ).options!,\n },\n });\n \n@@ -144,9 +158,9 @@ it.layer(NodeServices.layer)("server settings", (it) => {\n // cause the update to lose the selected model.\n const next = yield* serverSettings.updateSettings({\n textGenerationModelSelection: {\n- provider: "codex",\n+ instanceId: ProviderInstanceId.make("codex"),\n model: "gpt-5.4",\n- options: createModelSelection("codex", "gpt-5.4", [\n+ options: createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.4", [\n { id: "reasoningEffort", value: "high" },\n ]).options!,\n },\n@@ -154,21 +168,107 @@ it.layer(NodeServices.layer)("server settings", (it) => {\n \n assert.deepEqual(\n next.textGenerationModelSelection,\n- createModelSelection("codex", "gpt-5.4", [{ id: "reasoningEffort", value: "high" }]),\n+ createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.4", [\n+ { id: "reasoningEffort", value: "high" },\n+ ]),\n );\n }).pipe(Effect.provide(makeServerSettingsLayer())),\n );\n \n+ it.effect("preserves custom provider instance text generation selections", () =>\n+ Effect.gen(function* () {\n+ const serverSettings = yield* ServerSettingsService;\n+\n+ const next = yield* serverSettings.updateSettings({\n+ providerInstances: {\n+ [ProviderInstanceId.make("claude_openrouter")]: {\n+ driver: ProviderDriverKind.make("claudeAgent"),\n+ enabled: true,\n+ config: { customModels: ["openai/gpt-5.5"] },\n+ },\n+ },\n+ textGenerationModelSelection: {\n+ instanceId: ProviderInstanceId.make("claude_openrouter"),\n+ model: "openai/gpt-5.5",\n+ },\n+ });\n+\n+ assert.deepEqual(next.textGenerationModelSelection, {\n+ instanceId: ProviderInstanceId.make("claude_openrouter"),\n+ model: "openai/gpt-5.5",\n+ });\n+ }).pipe(Effect.provide(makeServerSettingsLayer())),\n+ );\n+\n+ it.effect(\n+ "uses explicit provider instance enabled state over legacy provider enabled state",\n+ () =>\n+ Effect.gen(function* () {\n+ const serverSettings = yield* ServerSettingsService;\n+ const instanceId = ProviderInstanceId.make("claude_openrouter");\n+\n+ const next = yield* serverSettings.updateSettings({\n+ providers: {\n+ claudeAgent: {\n+ enabled: false,\n+ },\n+ },\n+ providerInstances: {\n+ [instanceId]: {\n+ driver: ProviderDriverKind.make("claudeAgent"),\n+ enabled: true,\n+ config: { customModels: ["openai/gpt-5.5"] },\n+ },\n+ },\n+ textGenerationModelSelection: {\n+ instanceId,\n+ model: "openai/gpt-5.5",\n+ },\n+ });\n+\n+ assert.deepEqual(next.textGenerationModelSelection, {\n+ instanceId,\n+ model: "openai/gpt-5.5",\n+ });\n+ }).pipe(Effect.provide(makeServerSettingsLayer())),\n+ );\n+\n+ it.effect("preserves enabled text generation selections for non-built-in drivers", () =>\n+ Effect.gen(function* () {\n+ const serverSettings = yield* ServerSettingsService;\n+ const instanceId = ProviderInstanceId.make("openrouter_text");\n+\n+ const next = yield* serverSettings.updateSettings({\n+ providerInstances: {\n+ [instanceId]: {\n+ driver: ProviderDriverKind.make("openrouter"),\n+ enabled: true,\n+ config: { customModels: ["openai/gpt-5.5"] },\n+ },\n+ },\n+ textGenerationModelSelection: {\n+ instanceId,\n+ model: "openai/gpt-5.5",\n+ },\n+ });\n+\n+ assert.deepEqual(next.textGenerationModelSelection, {\n+ instanceId,\n+ model: "openai/gpt-5.5",\n+ });\n+ }).pipe(Effect.provide(makeServerSettingsLayer())),\n+ );\n+\n it.effect("drops stale text generation options when resetting model selection", () =>\n Effect.gen(function* () {\n const serverSettings = yield* ServerSettingsService;\n \n yield* serverSettings.updateSettings({\n textGenerationModelSelection: {\n- provider: "codex",\n+ instanceId: ProviderInstanceId.make("codex"),\n model: DEFAULT_SERVER_SETTINGS.textGenerationModelSelection.model,\n options: createModelSelection(\n- "codex",\n+ ProviderInstanceId.make("codex"),\n DEFAULT_SERVER_SETTINGS.textGenerationModelSelection.model,\n [\n { id: "reasoningEffort", value: "high" },\n@@ -180,18 +280,55 @@ it.layer(NodeServices.layer)("server settings", (it) => {\n \n const next = yield* serverSettings.updateSettings({\n textGenerationModelSelection: {\n- provider: DEFAULT_SERVER_SETTINGS.textGenerationModelSelection.provider,\n+ instanceId: DEFAULT_SERVER_SETTINGS.textGenerationModelSelection.instanceId,\n model: DEFAULT_SERVER_SETTINGS.textGenerationModelSelection.model,\n },\n });\n \n assert.deepEqual(next.textGenerationModelSelection, {\n- provider: DEFAULT_SERVER_SETTINGS.textGenerationModelSelection.provider,\n+ instanceId: DEFAULT_SERVER_SETTINGS.textGenerationModelSelection.instanceId,\n model: DEFAULT_SERVER_SETTINGS.textGenerationModelSelection.model,\n });\n }).pipe(Effect.provide(makeServerSettingsLayer())),\n );\n \n+ it.effect("replaces provider instance maps when clearing optional fields", () =>\n+ Effect.gen(function* () {\n+ const serverSettings = yield* ServerSettingsService;\n+ const codexId = ProviderInstanceId.make("codex");\n+\n+ yield* serverSettings.updateSettings({\n+ providerInstances: {\n+ [codexId]: {\n+ driver: ProviderDriverKind.make("codex"),\n+ displayName: "Codex Work",\n+ accentColor: "#7c3aed",\n+ enabled: true,\n+ config: { homePath: "~/.codex" },\n+ },\n+ },\n+ });\n+\n+ const next = yield* serverSettings.updateSettings({\n+ providerInstances: {\n+ [codexId]: {\n+ driver: ProviderDriverKind.make("codex"),\n+ displayName: "Codex Work",\n+ enabled: true,\n+ config: { homePath: "~/.codex" },\n+ },\n+ },\n+ });\n+\n+ assert.deepEqual(next.providerInstances[codexId], {\n+ driver: ProviderDriverKind.make("codex"),\n+ displayName: "Codex Work",\n+ enabled: true,\n+ config: { homePath: "~/.codex" },\n+ });\n+ }).pipe(Effect.provide(makeServerSettingsLayer())),\n+ );\n+\n it.effect("trims provider path settings when updates are applied", () =>\n Effect.gen(function* () {\n const serverSettings = yield* ServerSettingsService;\n@@ -217,11 +354,13 @@ it.layer(NodeServices.layer)("server settings", (it) => {\n enabled: true,\n binaryPath: "/opt/homebrew/bin/codex",\n homePath: "",\n+ shadowHomePath: "",\n customModels: [],\n });\n assert.deepEqual(next.providers.claudeAgent, {\n enabled: true,\n binaryPath: "/opt/homebrew/bin/claude",\n+ homePath: "",\n customModels: [],\n launchArgs: "",\n });\n@@ -318,4 +457,67 @@ it.layer(NodeServices.layer)("server settings", (it) => {\n });\n }).pipe(Effect.provide(makeServerSettingsLayer())),\n );\n+\n+ it.effect("stores sensitive provider instance environment values outside settings.json", () =>\n+ Effect.gen(function* () {\n+ const serverSettings = yield* ServerSettingsService;\n+ const serverConfig = yield* ServerConfig;\n+ const fileSystem = yield* FileSystem.FileSystem;\n+ const instanceId = ProviderInstanceId.make("codex_personal");\n+\n+ const next = yield* serverSettings.updateSettings({\n+ providerInstances: {\n+ [instanceId]: {\n+ driver: ProviderDriverKind.make("codex"),\n+ environment: [\n+ { name: "OPENROUTER_API_KEY", value: "sk-or-secret", sensitive: true },\n+ { name: "ANTHROPIC_BASE_URL", value: "https://openrouter.ai/api", sensitive: false },\n+ ],\n+ config: {},\n+ },\n+ },\n+ });\n+\n+ assert.deepEqual(next.providerInstances[instanceId]?.environment, [\n+ {\n+ name: "OPENROUTER_API_KEY",\n+ value: "sk-or-secret",\n+ sensitive: true,\n+ valueRedacted: true,\n+ },\n+ { name: "ANTHROPIC_BASE_URL", value: "https://openrouter.ai/api", sensitive: false },\n+ ]);\n+\n+ const raw = yield* fileSystem.readFileString(serverConfig.settingsPath);\n+ assert.notInclude(raw, "sk-or-secret");\n+ assert.deepEqual(JSON.parse(raw).providerInstances.codex_personal.environment, [\n+ {\n+ name: "OPENROUTER_API_KEY",\n+ value: "",\n+ sensitive: true,\n+ valueRedacted: true,\n+ },\n+ { name: "ANTHROPIC_BASE_URL", value: "https://openrouter.ai/api", sensitive: false },\n+ ]);\n+\n+ const roundTripped = yield* serverSettings.updateSettings({\n+ providerInstances: {\n+ [instanceId]: {\n+ driver: ProviderDriverKind.make("codex"),\n+ displayName: "Codex Personal",\n+ environment: [\n+ { name: "OPENROUTER_API_KEY", value: "", sensitive: true, valueRedacted: true },\n+ { name: "ANTHROPIC_BASE_URL", value: "https://openrouter.ai/api", sensitive: false },\n+ ],\n+ config: {},\n+ },\n+ },\n+ });\n+\n+ assert.equal(\n+ roundTripped.providerInstances[instanceId]?.environment?.[0]?.value,\n+ "sk-or-secret",\n+ );\n+ }).pipe(Effect.provide(makeServerSettingsLayer())),\n+ );\n });\ndiff --git a/apps/server/src/serverSettings.ts b/apps/server/src/serverSettings.ts\nindex c2147a0f45..2b9d8a5295 100644\n--- a/apps/server/src/serverSettings.ts\n+++ b/apps/server/src/serverSettings.ts\n@@ -11,10 +11,15 @@\n * @module ServerSettings\n */\n import {\n+ DEFAULT_GIT_TEXT_GENERATION_MODEL,\n DEFAULT_GIT_TEXT_GENERATION_MODEL_BY_PROVIDER,\n DEFAULT_SERVER_SETTINGS,\n+ isProviderDriverKind,\n type ModelSelection,\n- type ProviderKind,\n+ type ProviderInstanceConfig,\n+ type ProviderInstanceEnvironmentVariable,\n+ ProviderDriverKind,\n+ ProviderInstanceId,\n ServerSettings,\n ServerSettingsError,\n type ServerSettingsPatch,\n@@ -44,6 +49,47 @@ import { ServerConfig } from "./config.ts";\n import { type DeepPartial, deepMerge } from "@t3tools/shared/Struct";\n import { fromLenientJson } from "@t3tools/shared/schemaJson";\n import { applyServerSettingsPatch } from "@t3tools/shared/serverSettings";\n+import { ServerSecretStoreLive } from "./auth/Layers/ServerSecretStore.ts";\n+import { ServerSecretStore } from "./auth/Services/ServerSecretStore.ts";\n+\n+const textEncoder = new TextEncoder();\n+const textDecoder = new TextDecoder();\n+\n+function providerEnvironmentSecretName(input: {\n+ readonly instanceId: string;\n+ readonly name: string;\n+}): string {\n+ return `provider-env-${Buffer.from(input.instanceId, "utf8").toString("base64url")}-${Buffer.from(input.name, "utf8").toString("base64url")}`;\n+}\n+\n+function redactProviderEnvironmentVariable(\n+ variable: ProviderInstanceEnvironmentVariable,\n+): ProviderInstanceEnvironmentVariable {\n+ if (!variable.sensitive) {\n+ const { valueRedacted: _omit, ...rest } = variable;\n+ return rest;\n+ }\n+ return {\n+ ...variable,\n+ value: "",\n+ ...(variable.value.length > 0 || variable.valueRedacted ? { valueRedacted: true } : {}),\n+ };\n+}\n+\n+export function redactServerSettingsForClient(settings: ServerSettings): ServerSettings {\n+ const providerInstances = Object.fromEntries(\n+ Object.entries(settings.providerInstances).map(([instanceId, instance]) => [\n+ instanceId,\n+ instance.environment\n+ ? {\n+ ...instance,\n+ environment: instance.environment.map(redactProviderEnvironmentVariable),\n+ }\n+ : instance,\n+ ]),\n+ );\n+ return { ...settings, providerInstances };\n+}\n \n export interface ServerSettingsShape {\n /** Start the settings runtime and attach file watching. */\n@@ -106,7 +152,13 @@ export class ServerSettingsService extends Context.Service<\n \n const ServerSettingsJson = fromLenientJson(ServerSettings);\n \n-const PROVIDER_ORDER: readonly ProviderKind[] = ["codex", "claudeAgent", "opencode", "cursor"];\n+type LegacyProviderSettings = ServerSettings["providers"][keyof ServerSettings["providers"]];\n+\n+const getLegacyProviderSettings = (\n+ settings: ServerSettings,\n+ provider: ProviderDriverKind,\n+): LegacyProviderSettings | undefined =>\n+ (settings.providers as Record<string, LegacyProviderSettings | undefined>)[provider];\n \n /**\n * Ensure the `textGenerationModelSelection` points to an enabled provider.\n@@ -116,22 +168,36 @@ const PROVIDER_ORDER: readonly ProviderKind[] = ["codex", "claudeAgent", "openco\n */\n function resolveTextGenerationProvider(settings: ServerSettings): ServerSettings {\n const selection = settings.textGenerationModelSelection;\n- if (settings.providers[selection.provider].enabled) {\n+ const instanceConfig = settings.providerInstances[selection.instanceId];\n+ if (instanceConfig !== undefined) {\n+ return (instanceConfig.enabled ?? true) ? settings : fallbackTextGenerationProvider(settings);\n+ }\n+\n+ if (\n+ isProviderDriverKind(selection.instanceId) &&\n+ getLegacyProviderSettings(settings, selection.instanceId)?.enabled\n+ ) {\n return settings;\n }\n \n- const fallback = PROVIDER_ORDER.find((p) => settings.providers[p].enabled);\n+ return fallbackTextGenerationProvider(settings);\n+}\n+\n+function fallbackTextGenerationProvider(settings: ServerSettings): ServerSettings {\n+ const fallbackEntry = Object.entries(settings.providers).find(([, provider]) => provider.enabled);\n+ const fallback = fallbackEntry ? ProviderDriverKind.make(fallbackEntry[0]) : undefined;\n if (!fallback) {\n- // No providers enabled — return as-is; callers will report the error.\n return settings;\n }\n \n return {\n ...settings,\n textGenerationModelSelection: {\n- provider: fallback,\n- model: DEFAULT_GIT_TEXT_GENERATION_MODEL_BY_PROVIDER[fallback],\n- } as ModelSelection,\n+ instanceId: ProviderInstanceId.make(fallback),\n+ model:\n+ DEFAULT_GIT_TEXT_GENERATION_MODEL_BY_PROVIDER[fallback] ??\n+ DEFAULT_GIT_TEXT_GENERATION_MODEL,\n+ } satisfies ModelSelection,\n };\n }\n \n@@ -176,6 +242,7 @@ const makeServerSettings = Effect.gen(function* () {\n const { settingsPath } = yield* ServerConfig;\n const fs = yield* FileSystem.FileSystem;\n const pathService = yield* Path.Path;\n+ const secretStore = yield* ServerSecretStore;\n const writeSemaphore = yield* Semaphore.make(1);\n const cacheKey = "settings" as const;\n const changesPubSub = yield* PubSub.unbounded<ServerSettings>();\n@@ -233,6 +300,138 @@ const makeServerSettings = Effect.gen(function* () {\n \n const getSettingsFromCache = Cache.get(settingsCache, cacheKey);\n \n+ const toSettingsError = (detail: string, cause: unknown) =>\n+ new ServerSettingsError({\n+ settingsPath,\n+ detail,\n+ cause,\n+ });\n+\n+ const materializeProviderEnvironmentSecrets = (\n+ settings: ServerSettings,\n+ ): Effect.Effect<ServerSettings, ServerSettingsError> =>\n+ Effect.gen(function* () {\n+ const providerInstances: Record<string, ProviderInstanceConfig> = {\n+ ...settings.providerInstances,\n+ };\n+ for (const [instanceId, instance] of Object.entries(settings.providerInstances)) {\n+ if (!instance.environment) continue;\n+ const environment: ProviderInstanceEnvironmentVariable[] = [];\n+ for (const variable of instance.environment) {\n+ if (!variable.sensitive || !variable.valueRedacted) {\n+ environment.push(variable);\n+ continue;\n+ }\n+ const secret = yield* secretStore\n+ .get(providerEnvironmentSecretName({ instanceId, name: variable.name }))\n+ .pipe(\n+ Effect.mapError((cause) =>\n+ toSettingsError(\n+ `failed to read sensitive environment variable ${variable.name}`,\n+ cause,\n+ ),\n+ ),\n+ );\n+ environment.push({\n+ ...variable,\n+ value: secret ? textDecoder.decode(secret) : "",\n+ });\n+ }\n+ providerInstances[instanceId] = {\n+ ...instance,\n+ environment,\n+ } satisfies ProviderInstanceConfig;\n+ }\n+ return {\n+ ...settings,\n+ providerInstances: providerInstances as ServerSettings["providerInstances"],\n+ };\n+ });\n+\n+ const persistProviderEnvironmentSecrets = (\n+ current: ServerSettings,\n+ next: ServerSettings,\n+ ): Effect.Effect<ServerSettings, ServerSettingsError> =>\n+ Effect.gen(function* () {\n+ const providerInstances: Record<string, ProviderInstanceConfig> = {\n+ ...next.providerInstances,\n+ };\n+\n+ const nextSecretKeys = new Set<string>();\n+ for (const [instanceId, instance] of Object.entries(next.providerInstances)) {\n+ if (!instance.environment) continue;\n+ const environment: ProviderInstanceEnvironmentVariable[] = [];\n+ for (const variable of instance.environment) {\n+ const secretName = providerEnvironmentSecretName({ instanceId, name: variable.name });\n+ if (!variable.sensitive) {\n+ yield* secretStore\n+ .remove(secretName)\n+ .pipe(\n+ Effect.mapError((cause) =>\n+ toSettingsError(`failed to remove environment secret ${variable.name}`, cause),\n+ ),\n+ );\n+ environment.push(redactProviderEnvironmentVariable(variable));\n+ continue;\n+ }\n+\n+ nextSecretKeys.add(secretName);\n+ if (!variable.valueRedacted) {\n+ if (variable.value.length > 0) {\n+ yield* secretStore\n+ .set(secretName, textEncoder.encode(variable.value))\n+ .pipe(\n+ Effect.mapError((cause) =>\n+ toSettingsError(`failed to persist environment secret ${variable.name}`, cause),\n+ ),\n+ );\n+ environment.push({ ...variable, value: "", valueRedacted: true });\n+ } else {\n+ yield* secretStore\n+ .remove(secretName)\n+ .pipe(\n+ Effect.mapError((cause) =>\n+ toSettingsError(`failed to remove environment secret ${variable.name}`, cause),\n+ ),\n+ );\n+ const { valueRedacted: _omit, ...rest } = variable;\n+ environment.push(rest);\n+ }\n+ continue;\n+ }\n+\n+ environment.push(redactProviderEnvironmentVariable(variable));\n+ }\n+ providerInstances[instanceId] = {\n+ ...instance,\n+ environment,\n+ } satisfies ProviderInstanceConfig;\n+ }\n+\n+ for (const [instanceId, instance] of Object.entries(current.providerInstances)) {\n+ for (const variable of instance.environment ?? []) {\n+ if (!variable.sensitive) continue;\n+ const secretName = providerEnvironmentSecretName({ instanceId, name: variable.name });\n+ if (nextSecretKeys.has(secretName)) continue;\n+ yield* secretStore\n+ .remove(secretName)\n+ .pipe(\n+ Effect.mapError((cause) =>\n+ toSettingsError(\n+ `failed to remove stale environment secret ${variable.name}`,\n+ cause,\n+ ),\n+ ),\n+ );\n+ }\n+ }\n+\n+ return {\n+ ...next,\n+ providerInstances: providerInstances as ServerSettings["providerInstances"],\n+ };\n+ });\n+\n const writeSettingsAtomically = (settings: ServerSettings) => {\n const sparseSettings = stripDefaultServerSettings(settings, DEFAULT_SERVER_SETTINGS) ?? {};\n \n@@ -324,14 +523,19 @@ const makeServerSettings = Effect.gen(function* () {\n return {\n start,\n ready: Deferred.await(startedDeferred),\n- getSettings: getSettingsFromCache.pipe(Effect.map(resolveTextGenerationProvider)),\n+ getSettings: getSettingsFromCache.pipe(\n+ Effect.flatMap(materializeProviderEnvironmentSecrets),\n+ Effect.map(resolveTextGenerationProvider),\n+ ),\n updateSettings: (patch) =>\n writeSemaphore.withPermits(1)(\n Effect.gen(function* () {\n const current = yield* getSettingsFromCache;\n- const next = yield* Schema.decodeEffect(ServerSettings)(\n+ const nextPersisted = yield* persistProviderEnvironmentSecrets(\n+ current,\n applyServerSettingsPatch(current, patch),\n- ).pipe(\n+ );\n+ const next = yield* Schema.decodeEffect(ServerSettings)(nextPersisted).pipe(\n Effect.mapError(\n (cause) =>\n new ServerSettingsError({\n@@ -344,13 +548,27 @@ const makeServerSettings = Effect.gen(function* () {\n yield* writeSettingsAtomically(next);\n yield* Cache.set(settingsCache, cacheKey, next);\n yield* emitChange(next);\n- return resolveTextGenerationProvider(next);\n+ const materialized = yield* materializeProviderEnvironmentSecrets(next);\n+ return resolveTextGenerationProvider(materialized);\n }),\n ),\n get streamChanges() {\n- return Stream.fromPubSub(changesPubSub).pipe(Stream.map(resolveTextGenerationProvider));\n+ return Stream.fromPubSub(changesPubSub).pipe(\n+ Stream.mapEffect((settings) =>\n+ materializeProviderEnvironmentSecrets(settings).pipe(\n+ Effect.catch((error: ServerSettingsError) =>\n+ Effect.logWarning("failed to materialize provider environment secrets", {\n+ detail: error.detail,\n+ }).pipe(Effect.as(settings)),\n+ ),\n+ ),\n+ ),\n+ Stream.map(resolveTextGenerationProvider),\n+ );\n },\n } satisfies ServerSettingsShape;\n });\n \n-export const ServerSettingsLive = Layer.effect(ServerSettingsService, makeServerSettings);\n+export const ServerSettingsLive = Layer.effect(ServerSettingsService, makeServerSettings).pipe(\n+ Layer.provide(ServerSecretStoreLive),\n+);\ndiff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts\nindex aac716cfeb..fd256b32df 100644\n--- a/apps/server/src/ws.ts\n+++ b/apps/server/src/ws.ts\n@@ -45,7 +45,7 @@ import {\n import { ProviderRegistry } from "./provider/Services/ProviderRegistry.ts";\n import { ServerLifecycleEvents } from "./serverLifecycleEvents.ts";\n import { ServerRuntimeStartup } from "./serverRuntimeStartup.ts";\n-import { ServerSettingsService } from "./serverSettings.ts";\n+import { redactServerSettingsForClient, ServerSettingsService } from "./serverSettings.ts";\n import { TerminalManager } from "./terminal/Services/Manager.ts";\n import { WorkspaceEntries } from "./workspace/Services/WorkspaceEntries.ts";\n import { WorkspaceFileSystem } from "./workspace/Services/WorkspaceFileSystem.ts";\n@@ -512,7 +512,7 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>\n const loadServerConfig = Effect.gen(function* () {\n const keybindingsConfig = yield* keybindings.loadConfigState;\n const providers = yield* providerRegistry.getProviders;\n- const settings = yield* serverSettings.getSettings;\n+ const settings = redactServerSettingsForClient(yield* serverSettings.getSettings);\n const environment = yield* serverEnvironment.getDescriptor;\n const auth = yield* serverAuth.getDescriptor();\n \n@@ -749,10 +749,13 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>\n observeRpcEffect(WS_METHODS.serverGetConfig, loadServerConfig, {\n "rpc.aggregate": "server",\n }),\n- [WS_METHODS.serverRefreshProviders]: (_input) =>\n+ [WS_METHODS.serverRefreshProviders]: (input) =>\n observeRpcEffect(\n WS_METHODS.serverRefreshProviders,\n- providerRegistry.refresh().pipe(Effect.map((providers) => ({ providers }))),\n+ (input.instanceId !== undefined\n+ ? providerRegistry.refreshInstance(input.instanceId)\n+ : providerRegistry.refresh()\n+ ).pipe(Effect.map((providers) => ({ providers }))),\n { "rpc.aggregate": "server" },\n ),\n [WS_METHODS.serverUpsertKeybinding]: (rule) =>\n@@ -765,13 +768,21 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>\n { "rpc.aggregate": "server" },\n ),\n [WS_METHODS.serverGetSettings]: (_input) =>\n- observeRpcEffect(WS_METHODS.serverGetSettings, serverSettings.getSettings, {\n- "rpc.aggregate": "server",\n- }),\n+ observeRpcEffect(\n+ WS_METHODS.serverGetSettings,\n+ serverSettings.getSettings.pipe(Effect.map(redactServerSettingsForClient)),\n+ {\n+ "rpc.aggregate": "server",\n+ },\n+ ),\n [WS_METHODS.serverUpdateSettings]: ({ patch }) =>\n- observeRpcEffect(WS_METHODS.serverUpdateSettings, serverSettings.updateSettings(patch), {\n- "rpc.aggregate": "server",\n- }),\n+ observeRpcEffect(\n+ WS_METHODS.serverUpdateSettings,\n+ serverSettings.updateSettings(patch).pipe(Effect.map(redactServerSettingsForClient)),\n+ {\n+ "rpc.aggregate": "server",\n+ },\n+ ),\n [WS_METHODS.projectsSearchEntries]: (input) =>\n observeRpcEffect(\n WS_METHODS.projectsSearchEntries,\n@@ -976,6 +987,7 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>\n Stream.debounce(Duration.millis(PROVIDER_STATUS_DEBOUNCE_MS)),\n );\n const settingsUpdates = serverSettings.streamChanges.pipe(\n+ Stream.map((settings) => redactServerSettingsForClient(settings)),\n Stream.map((settings) => ({\n version: 1 as const,\n type: "settingsUpdated" as const,\n@@ -983,13 +995,9 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>\n })),\n );\n \n- yield* Effect.all(\n- [providerRegistry.refresh("codex"), providerRegistry.refresh("claudeAgent")],\n- {\n- concurrency: "unbounded",\n- discard: true,\n- },\n- ).pipe(Effect.ignoreCause({ log: true }), Effect.forkScoped);\n+ yield* providerRegistry\n+ .refresh()\n+ .pipe(Effect.ignoreCause({ log: true }), Effect.forkScoped);\n \n const liveUpdates = Stream.merge(\n keybindingsUpdates,\ndiff --git a/apps/web/src/components/ChatView.browser.tsx b/apps/web/src/components/ChatView.browser.tsx\nindex f5cc79b88a..445fe19305 100644\n--- a/apps/web/src/components/ChatView.browser.tsx\n+++ b/apps/web/src/components/ChatView.browser.tsx\n@@ -9,6 +9,8 @@ import {\n type MessageId,\n type OrchestrationReadModel,\n type ProjectId,\n+ ProviderDriverKind,\n+ ProviderInstanceId,\n type ServerConfig,\n type ServerLifecycleWelcomePayload,\n type ThreadId,\n@@ -167,7 +169,8 @@ function createBaseServerConfig(): ServerConfig {\n issues: [],\n providers: [\n {\n- provider: "codex",\n+ driver: ProviderDriverKind.make("codex"),\n+ instanceId: ProviderInstanceId.make("codex"),\n enabled: true,\n installed: true,\n version: "0.116.0",\n@@ -323,7 +326,7 @@ function createSnapshotForTargetUser(options: {\n title: "Project",\n workspaceRoot: "/repo/project",\n defaultModelSelection: {\n- provider: "codex",\n+ instanceId: ProviderInstanceId.make("codex"),\n model: "gpt-5",\n },\n scripts: [],\n@@ -338,7 +341,7 @@ function createSnapshotForTargetUser(options: {\n projectId: PROJECT_ID,\n title: THREAD_TITLE,\n modelSelection: {\n- provider: "codex",\n+ instanceId: ProviderInstanceId.make("codex"),\n model: "gpt-5",\n },\n interactionMode: "default",\n@@ -403,7 +406,7 @@ function addThreadToSnapshot(\n projectId: PROJECT_ID,\n title: "New thread",\n modelSelection: {\n- provider: "codex",\n+ instanceId: ProviderInstanceId.make("codex"),\n model: "gpt-5",\n },\n interactionMode: "default",\n@@ -740,7 +743,7 @@ function createSnapshotWithSecondaryProject(options?: {\n id: "thread-secondary-project" as ThreadId,\n projectId: SECOND_PROJECT_ID,\n title: "Release checklist",\n- modelSelection: { provider: "codex", model: "gpt-5" },\n+ modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5" },\n interactionMode: "default",\n runtimeMode: "full-access",\n branch: "release/docs-portal",\n@@ -772,7 +775,7 @@ function createSnapshotWithSecondaryProject(options?: {\n id: ARCHIVED_SECONDARY_THREAD_ID,\n projectId: SECOND_PROJECT_ID,\n title: "Archived Docs Notes",\n- modelSelection: { provider: "codex", model: "gpt-5" },\n+ modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5" },\n interactionMode: "default",\n runtimeMode: "full-access",\n branch: "release/docs-archive",\n@@ -807,7 +810,7 @@ function createSnapshotWithSecondaryProject(options?: {\n id: SECOND_PROJECT_ID,\n title: "Docs Portal",\n workspaceRoot: "/repo/clients/docs-portal",\n- defaultModelSelection: { provider: "codex", model: "gpt-5" },\n+ defaultModelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5" },\n scripts: [],\n createdAt: NOW_ISO,\n updatedAt: NOW_ISO,\n@@ -884,7 +887,7 @@ function createSnapshotWithPendingUserInput(): OrchestrationReadModel {\n }\n \n function createSnapshotWithPlanFollowUpPrompt(options?: {\n- modelSelection?: { provider: "codex"; model: string };\n+ modelSelection?: { instanceId: ProviderInstanceId; model: string };\n planMarkdown?: string;\n }): OrchestrationReadModel {\n const snapshot = createSnapshotForTargetUser({\n@@ -892,7 +895,7 @@ function createSnapshotWithPlanFollowUpPrompt(options?: {\n targetText: "plan follow-up thread",\n });\n const modelSelection = options?.modelSelection ?? {\n- provider: "codex" as const,\n+ instanceId: ProviderInstanceId.make("codex"),\n model: "gpt-5",\n };\n const planMarkdown =\n@@ -2438,6 +2441,126 @@ describe("ChatView timeline estimator parity (full app)", () => {\n }\n });\n \n+ it("keeps custom provider instance ids when bootstrapping a local draft thread", async () => {\n+ setDraftThreadWithoutWorktree();\n+ const openRouterInstanceId = ProviderInstanceId.make("claude_openrouter");\n+ const openRouterSelection = createModelSelection(openRouterInstanceId, "openai/gpt-5.5");\n+ useComposerDraftStore.getState().setModelSelection(THREAD_REF, openRouterSelection);\n+\n+ const mounted = await mountChatView({\n+ viewport: DEFAULT_VIEWPORT,\n+ snapshot: createDraftOnlySnapshot(),\n+ configureFixture: (nextFixture) => {\n+ nextFixture.serverConfig = {\n+ ...nextFixture.serverConfig,\n+ providers: [\n+ ...nextFixture.serverConfig.providers,\n+ {\n+ driver: ProviderDriverKind.make("claudeAgent"),\n+ instanceId: ProviderInstanceId.make("claudeAgent"),\n+ enabled: true,\n+ installed: true,\n+ version: "2.1.117",\n+ status: "ready",\n+ auth: { status: "authenticated" },\n+ checkedAt: NOW_ISO,\n+ models: [\n+ {\n+ slug: "claude-opus-4-7",\n+ name: "Claude Opus 4.7",\n+ isCustom: false,\n+ capabilities: createModelCapabilities({ optionDescriptors: [] }),\n+ },\n+ ],\n+ slashCommands: [],\n+ skills: [],\n+ },\n+ {\n+ driver: ProviderDriverKind.make("claudeAgent"),\n+ instanceId: openRouterInstanceId,\n+ displayName: "Claude OpenRouter",\n+ enabled: true,\n+ installed: true,\n+ version: "2.1.117",\n+ status: "ready",\n+ auth: { status: "authenticated" },\n+ checkedAt: NOW_ISO,\n+ models: [\n+ {\n+ slug: "claude-opus-4-7",\n+ name: "Claude Opus 4.7",\n+ isCustom: false,\n+ capabilities: createModelCapabilities({ optionDescriptors: [] }),\n+ },\n+ ],\n+ slashCommands: [],\n+ skills: [],\n+ },\n+ ],\n+ settings: {\n+ ...nextFixture.serverConfig.settings,\n+ providerInstances: {\n+ ...nextFixture.serverConfig.settings.providerInstances,\n+ [openRouterInstanceId]: {\n+ driver: ProviderDriverKind.make("claudeAgent"),\n+ displayName: "Claude OpenRouter",\n+ config: { customModels: ["openai/gpt-5.5"] },\n+ },\n+ },\n+ },\n+ };\n+ },\n+ resolveRpc: (body) => {\n+ if (body._tag === ORCHESTRATION_WS_METHODS.dispatchCommand) {\n+ return {\n+ sequence: fixture.snapshot.snapshotSequence + 1,\n+ };\n+ }\n+ return undefined;\n+ },\n+ });\n+\n+ try {\n+ useComposerDraftStore.getState().setPrompt(THREAD_REF, "Hello there");\n+ await waitForLayout();\n+\n+ const sendButton = await waitForSendButton();\n+ expect(sendButton.disabled).toBe(false);\n+ sendButton.click();\n+\n+ await vi.waitFor(\n+ () => {\n+ const turnStartRequest = wsRequests.find(\n+ (request) =>\n+ request._tag === ORCHESTRATION_WS_METHODS.dispatchCommand &&\n+ request.type === "thread.turn.start",\n+ ) as\n+ | {\n+ modelSelection?: { instanceId?: string; model?: string };\n+ bootstrap?: {\n+ createThread?: {\n+ modelSelection?: { instanceId?: string; model?: string };\n+ };\n+ };\n+ }\n+ | undefined;\n+\n+ expect(turnStartRequest?.modelSelection).toMatchObject({\n+ instanceId: openRouterInstanceId,\n+ model: "openai/gpt-5.5",\n+ });\n+ expect(turnStartRequest?.bootstrap?.createThread?.modelSelection).toMatchObject({\n+ instanceId: openRouterInstanceId,\n+ model: "openai/gpt-5.5",\n+ });\n+ },\n+ { timeout: 8_000, interval: 16 },\n+ );\n+ } finally {\n+ await mounted.cleanup();\n+ }\n+ });\n+\n it("keeps new-worktree mode on empty server threads and bootstraps the first send", async () => {\n const snapshot = addThreadToSnapshot(createDraftOnlySnapshot(), THREAD_ID);\n const mounted = await mountChatView({\n@@ -3778,12 +3901,16 @@ describe("ChatView timeline estimator parity (full app)", () => {\n it("snapshots sticky codex settings into a new draft thread", async () => {\n useComposerDraftStore.setState({\n stickyModelSelectionByProvider: {\n- codex: createModelSelection("codex", "gpt-5.3-codex", [\n- { id: "reasoningEffort", value: "medium" },\n- { id: "fastMode", value: true },\n- ]),\n+ [ProviderInstanceId.make("codex")]: createModelSelection(\n+ ProviderInstanceId.make("codex"),\n+ "gpt-5.3-codex",\n+ [\n+ { id: "reasoningEffort", value: "medium" },\n+ { id: "fastMode", value: true },\n+ ],\n+ ),\n },\n- stickyActiveProvider: "codex",\n+ stickyActiveProvider: ProviderInstanceId.make("codex"),\n });\n \n const mounted = await mountChatView({\n@@ -3814,7 +3941,7 @@ describe("ChatView timeline estimator parity (full app)", () => {\n expect(composerDraftFor(newDraftId)).toMatchObject({\n modelSelectionByProvider: {\n codex: {\n- provider: "codex",\n+ instanceId: ProviderInstanceId.make("codex"),\n model: "gpt-5.3-codex",\n options: expect.arrayContaining([{ id: "fastMode", value: true }]),\n },\n@@ -3829,12 +3956,16 @@ describe("ChatView timeline estimator parity (full app)", () => {\n it("hydrates the provider alongside a sticky claude model", async () => {\n useComposerDraftStore.setState({\n stickyModelSelectionByProvider: {\n- claudeAgent: createModelSelection("claudeAgent", "claude-opus-4-6", [\n- { id: "effort", value: "max" },\n- { id: "fastMode", value: true },\n- ]),\n+ [ProviderInstanceId.make("claudeAgent")]: createModelSelection(\n+ ProviderInstanceId.make("claudeAgent"),\n+ "claude-opus-4-6",\n+ [\n+ { id: "effort", value: "max" },\n+ { id: "fastMode", value: true },\n+ ],\n+ ),\n },\n- stickyActiveProvider: "claudeAgent",\n+ stickyActiveProvider: ProviderInstanceId.make("claudeAgent"),\n });\n \n const mounted = await mountChatView({\n@@ -3860,10 +3991,14 @@ describe("ChatView timeline estimator parity (full app)", () => {\n \n expect(composerDraftFor(newDraftId)).toMatchObject({\n modelSelectionByProvider: {\n- claudeAgent: createModelSelection("claudeAgent", "claude-opus-4-6", [\n- { id: "effort", value: "max" },\n- { id: "fastMode", value: true },\n- ]),\n+ claudeAgent: createModelSelection(\n+ ProviderInstanceId.make("claudeAgent"),\n+ "claude-opus-4-6",\n+ [\n+ { id: "effort", value: "max" },\n+ { id: "fastMode", value: true },\n+ ],\n+ ),\n },\n activeProvider: "claudeAgent",\n });\n@@ -3903,12 +4038,16 @@ describe("ChatView timeline estimator parity (full app)", () => {\n it("prefers draft state over sticky composer settings and defaults", async () => {\n useComposerDraftStore.setState({\n stickyModelSelectionByProvider: {\n- codex: createModelSelection("codex", "gpt-5.3-codex", [\n- { id: "reasoningEffort", value: "medium" },\n- { id: "fastMode", value: true },\n- ]),\n+ [ProviderInstanceId.make("codex")]: createModelSelection(\n+ ProviderInstanceId.make("codex"),\n+ "gpt-5.3-codex",\n+ [\n+ { id: "reasoningEffort", value: "medium" },\n+ { id: "fastMode", value: true },\n+ ],\n+ ),\n },\n- stickyActiveProvider: "codex",\n+ stickyActiveProvider: ProviderInstanceId.make("codex"),\n });\n \n const mounted = await mountChatView({\n@@ -3938,7 +4077,7 @@ describe("ChatView timeline estimator parity (full app)", () => {\n expect(composerDraftFor(draftId)).toMatchObject({\n modelSelectionByProvider: {\n codex: {\n- provider: "codex",\n+ instanceId: ProviderInstanceId.make("codex"),\n model: "gpt-5.3-codex",\n options: expect.arrayContaining([{ id: "fastMode", value: true }]),\n },\n@@ -3948,7 +4087,7 @@ describe("ChatView timeline estimator parity (full app)", () => {\n \n useComposerDraftStore.getState().setModelSelection(\n draftId,\n- createModelSelection("codex", "gpt-5.4", [\n+ createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.4", [\n { id: "reasoningEffort", value: "low" },\n { id: "fastMode", value: true },\n ]),\n@@ -3963,7 +4102,7 @@ describe("ChatView timeline estimator parity (full app)", () => {\n );\n expect(composerDraftFor(draftId)).toMatchObject({\n modelSelectionByProvider: {\n- codex: createModelSelection("codex", "gpt-5.4", [\n+ codex: createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.4", [\n { id: "reasoningEffort", value: "low" },\n { id: "fastMode", value: true },\n ]),\n@@ -5435,7 +5574,10 @@ describe("ChatView timeline estimator parity (full app)", () => {\n const mounted = await mountChatView({\n viewport: WIDE_FOOTER_VIEWPORT,\n snapshot: createSnapshotWithPlanFollowUpPrompt({\n- modelSelection: { provider: "codex", model: "gpt-5.3-codex-spark" },\n+ modelSelection: {\n+ instanceId: ProviderInstanceId.make("codex"),\n+ model: "gpt-5.3-codex-spark",\n+ },\n planMarkdown:\n "# Imaginary Long-Range Plan: T3 Code Adaptive Orchestration and Safe-Delay Execution Initiative",\n }),\n@@ -5465,7 +5607,10 @@ describe("ChatView timeline estimator parity (full app)", () => {\n const mounted = await mountChatView({\n viewport: WIDE_FOOTER_VIEWPORT,\n snapshot: createSnapshotWithPlanFollowUpPrompt({\n- modelSelection: { provider: "codex", model: "gpt-5.3-codex-spark" },\n+ modelSelection: {\n+ instanceId: ProviderInstanceId.make("codex"),\n+ model: "gpt-5.3-codex-spark",\n+ },\n planMarkdown:\n "# Imaginary Long-Range Plan: T3 Code Adaptive Orchestration and Safe-Delay Execution Initiative",\n }),\n@@ -5589,14 +5734,17 @@ describe("ChatView timeline estimator parity (full app)", () => {\n projects: snapshot.projects.map((project) =>\n project.id === PROJECT_ID\n ? Object.assign({}, project, {\n- defaultModelSelection: { provider: "codex", model: "gpt-5.4" },\n+ defaultModelSelection: {\n+ instanceId: ProviderInstanceId.make("codex"),\n+ model: "gpt-5.4",\n+ },\n })\n : project,\n ),\n threads: snapshot.threads.map((thread) =>\n thread.id === THREAD_ID\n ? Object.assign({}, thread, {\n- modelSelection: { provider: "codex", model: "gpt-5.4" },\n+ modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },\n })\n : thread,\n ),\n@@ -5647,7 +5795,6 @@ describe("ChatView timeline estimator parity (full app)", () => {\n providers: [\n {\n ...nextFixture.serverConfig.providers[0]!,\n- provider: "codex",\n models: [\n {\n slug: "gpt-5.1-codex-max",\ndiff --git a/apps/web/src/components/ChatView.logic.test.ts b/apps/web/src/components/ChatView.logic.test.ts\nindex ba0a0eddf3..83c90edadd 100644\n--- a/apps/web/src/components/ChatView.logic.test.ts\n+++ b/apps/web/src/components/ChatView.logic.test.ts\n@@ -1,5 +1,12 @@\n import { scopeThreadRef } from "@t3tools/client-runtime";\n-import { EnvironmentId, ProjectId, ThreadId, TurnId } from "@t3tools/contracts";\n+import {\n+ EnvironmentId,\n+ ProjectId,\n+ ProviderDriverKind,\n+ ProviderInstanceId,\n+ ThreadId,\n+ TurnId,\n+} from "@t3tools/contracts";\n import { afterEach, describe, expect, it, vi } from "vitest";\n import { type EnvironmentState, useStore } from "../store";\n import { type Thread } from "../types";\n@@ -220,7 +227,7 @@ const makeThread = (input?: {\n codexThreadId: null,\n projectId: ProjectId.make("project-1"),\n title: "Thread",\n- modelSelection: { provider: "codex" as const, model: "gpt-5.4" },\n+ modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },\n runtimeMode: "full-access" as const,\n interactionMode: "default" as const,\n session: null,\n@@ -253,7 +260,7 @@ function setStoreThreads(threads: ReadonlyArray<ReturnType<typeof makeThread>>)\n name: "Project",\n cwd: "/tmp/project",\n defaultModelSelection: {\n- provider: "codex",\n+ instanceId: ProviderInstanceId.make("codex"),\n model: "gpt-5.4",\n },\n createdAt: "2026-03-29T00:00:00.000Z",\n@@ -452,7 +459,7 @@ describe("hasServerAcknowledgedLocalDispatch", () => {\n };\n \n const previousSession = {\n- provider: "codex" as const,\n+ provider: ProviderDriverKind.make("codex"),\n status: "ready" as const,\n createdAt: "2026-03-29T00:00:00.000Z",\n updatedAt: "2026-03-29T00:00:10.000Z",\n@@ -466,7 +473,7 @@ describe("hasServerAcknowledgedLocalDispatch", () => {\n codexThreadId: null,\n projectId,\n title: "Thread",\n- modelSelection: { provider: "codex", model: "gpt-5.4" },\n+ modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },\n runtimeMode: "full-access",\n interactionMode: "default",\n session: previousSession,\n@@ -503,7 +510,7 @@ describe("hasServerAcknowledgedLocalDispatch", () => {\n codexThreadId: null,\n projectId,\n title: "Thread",\n- modelSelection: { provider: "codex", model: "gpt-5.4" },\n+ modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },\n runtimeMode: "full-access",\n interactionMode: "default",\n session: previousSession,\n@@ -549,7 +556,7 @@ describe("hasServerAcknowledgedLocalDispatch", () => {\n codexThreadId: null,\n projectId,\n title: "Thread",\n- modelSelection: { provider: "codex", model: "gpt-5.4" },\n+ modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },\n runtimeMode: "full-access",\n interactionMode: "default",\n session: previousSession,\n@@ -592,7 +599,7 @@ describe("hasServerAcknowledgedLocalDispatch", () => {\n codexThreadId: null,\n projectId,\n title: "Thread",\n- modelSelection: { provider: "codex", model: "gpt-5.4" },\n+ modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },\n runtimeMode: "full-access",\n interactionMode: "default",\n session: previousSession,\n@@ -635,7 +642,7 @@ describe("hasServerAcknowledgedLocalDispatch", () => {\n codexThreadId: null,\n projectId,\n title: "Thread",\n- modelSelection: { provider: "codex", model: "gpt-5.4" },\n+ modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },\n runtimeMode: "full-access",\n interactionMode: "default",\n session: previousSession,\n@@ -685,7 +692,7 @@ describe("hasServerAcknowledgedLocalDispatch", () => {\n codexThreadId: null,\n projectId,\n title: "Thread",\n- modelSelection: { provider: "codex", model: "gpt-5.4" },\n+ modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },\n runtimeMode: "full-access",\n interactionMode: "default",\n session: previousSession,\ndiff --git a/apps/web/src/components/ChatView.logic.ts b/apps/web/src/components/ChatView.logic.ts\nindex b77cc7b176..417313ef2c 100644\n--- a/apps/web/src/components/ChatView.logic.ts\n+++ b/apps/web/src/components/ChatView.logic.ts\n@@ -1,8 +1,9 @@\n import {\n type EnvironmentId,\n+ isProviderDriverKind,\n ProjectId,\n type ModelSelection,\n- type ProviderKind,\n+ type ProviderDriverKind,\n type ScopedThreadRef,\n type ThreadId,\n type TurnId,\n@@ -226,15 +227,39 @@ export function threadHasStarted(thread: Thread | null | undefined): boolean {\n );\n }\n \n+// `threadProvider` is the open branded driver kind carried by the session.\n+// Unknown driver kinds degrade to `null` (i.e. "unlocked"), which is the safe\n+// rollback / fork behavior — the routing layer is the right place to surface\n+// "driver not installed" errors, not the lock state.\n+//\n+// `selectedProvider` takes the same open-string shape because the composer\n+// now tracks the picker selection as a `ProviderInstanceId` (e.g.\n+// `codex_personal`). Custom instance ids that don\'t directly match a\n+// registered driver resolve to `null` here, which matches the existing\n+// "unknown driver -> unlocked" semantics. Callers that want the lock to track\n+// a custom instance\'s underlying driver kind should resolve the instance id\n+// upstream and pass the correlated kind.\n export function deriveLockedProvider(input: {\n thread: Thread | null | undefined;\n- selectedProvider: ProviderKind | null;\n- threadProvider: ProviderKind | null;\n-}): ProviderKind | null {\n+ selectedProvider: string | null;\n+ threadProvider: string | null;\n+}): ProviderDriverKind | null {\n if (!threadHasStarted(input.thread)) {\n return null;\n }\n- return input.thread?.session?.provider ?? input.threadProvider ?? input.selectedProvider ?? null;\n+ const sessionProvider = input.thread?.session?.provider ?? null;\n+ if (sessionProvider) {\n+ return sessionProvider;\n+ }\n+ const narrowedThreadProvider =\n+ input.threadProvider && isProviderDriverKind(input.threadProvider)\n+ ? input.threadProvider\n+ : null;\n+ const narrowedSelectedProvider =\n+ input.selectedProvider && isProviderDriverKind(input.selectedProvider)\n+ ? input.selectedProvider\n+ : null;\n+ return narrowedThreadProvider ?? narrowedSelectedProvider ?? null;\n }\n \n export async function waitForStartedServerThread(\ndiff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx\nindex c27afda975..765a2d5f9a 100644\n--- a/apps/web/src/components/ChatView.tsx\n+++ b/apps/web/src/components/ChatView.tsx\n@@ -1,13 +1,14 @@\n import {\n type ApprovalRequestId,\n- DEFAULT_MODEL_BY_PROVIDER,\n+ DEFAULT_MODEL,\n+ defaultInstanceIdForDriver,\n type EnvironmentId,\n type MessageId,\n type ModelSelection,\n type ProjectScript,\n- type ProviderKind,\n type ProjectId,\n type ProviderApprovalDecision,\n+ ProviderInstanceId,\n type ServerProvider,\n type ResolvedKeybindingsConfig,\n type ScopedThreadRef,\n@@ -16,6 +17,7 @@ import {\n type KeybindingCommand,\n OrchestrationThreadActivity,\n ProviderInteractionMode,\n+ ProviderDriverKind,\n RuntimeMode,\n TerminalOpenInput,\n } from "@t3tools/contracts";\n@@ -115,7 +117,7 @@ import {\n import { newCommandId, newDraftId, newMessageId, newThreadId } from "~/lib/utils";\n import { getProviderModelCapabilities, resolveSelectableProvider } from "../providerModels";\n import { useSettings } from "../hooks/useSettings";\n-import { resolveAppModelSelection } from "../modelSelection";\n+import { resolveAppModelSelectionForInstance } from "../modelSelection";\n import { isTerminalFocused } from "../lib/terminalFocus";\n import { deriveLogicalProjectKeyFromSettings } from "../logicalProject";\n import {\n@@ -302,7 +304,7 @@ function useThreadPlanCatalog(threadIds: readonly ThreadId[]): ThreadPlanCatalog\n }\n \n function formatOutgoingPrompt(params: {\n- provider: ProviderKind;\n+ provider: ProviderDriverKind;\n model: string | null;\n models: ReadonlyArray<ServerProvider["models"][number]>;\n effort: string | null;\n@@ -777,8 +779,8 @@ export default function ChatView(props: ChatViewProps) {\n threadId,\n draftThread,\n fallbackDraftProject?.defaultModelSelection ?? {\n- provider: "codex",\n- model: DEFAULT_MODEL_BY_PROVIDER.codex,\n+ instanceId: ProviderInstanceId.make("codex"),\n+ model: DEFAULT_MODEL,\n },\n localDraftError,\n )\n@@ -1031,7 +1033,9 @@ export default function ChatView(props: ChatViewProps) {\n \n const selectedProviderByThreadId = composerActiveProvider ?? null;\n const threadProvider =\n- activeThread?.modelSelection.provider ?? activeProject?.defaultModelSelection?.provider ?? null;\n+ activeThread?.modelSelection.instanceId ??\n+ activeProject?.defaultModelSelection?.instanceId ??\n+ null;\n const lockedProvider = deriveLockedProvider({\n thread: activeThread,\n selectedProvider: selectedProviderByThreadId,\n@@ -1051,9 +1055,9 @@ export default function ChatView(props: ChatViewProps) {\n const providerStatuses = serverConfig?.providers ?? EMPTY_PROVIDERS;\n const unlockedSelectedProvider = resolveSelectableProvider(\n providerStatuses,\n- selectedProviderByThreadId ?? threadProvider ?? "codex",\n+ selectedProviderByThreadId ?? threadProvider ?? ProviderDriverKind.make("codex"),\n );\n- const selectedProvider: ProviderKind = lockedProvider ?? unlockedSelectedProvider;\n+ const selectedProvider: ProviderDriverKind = lockedProvider ?? unlockedSelectedProvider;\n const phase = derivePhase(activeThread?.session ?? null);\n const threadActivities = activeThread?.activities ?? EMPTY_ACTIVITIES;\n const workLogEntries = useMemo(\n@@ -1425,10 +1429,24 @@ export default function ChatView(props: ChatViewProps) {\n const gitStatusQuery = useGitStatus({ environmentId, cwd: gitCwd });\n const keybindings = useServerKeybindings();\n const availableEditors = useServerAvailableEditors();\n- const activeProviderStatus = useMemo(\n- () => providerStatuses.find((status) => status.provider === selectedProvider) ?? null,\n- [selectedProvider, providerStatuses],\n- );\n+ // Prefer an instance-id match so a custom Codex instance (e.g.\n+ // `codex_personal`) surfaces its own status/message in the banner rather\n+ // than the default Codex\'s. Falls back to first-match-by-kind when no\n+ // saved instance id is available or the instance no longer exists.\n+ const activeProviderInstanceId =\n+ activeThread?.session?.providerInstanceId ??\n+ activeThread?.modelSelection.instanceId ??\n+ activeProject?.defaultModelSelection?.instanceId ??\n+ null;\n+ const activeProviderStatus = useMemo(() => {\n+ if (activeProviderInstanceId) {\n+ return (\n+ providerStatuses.find((status) => status.instanceId === activeProviderInstanceId) ?? null\n+ );\n+ }\n+ const defaultInstanceId = defaultInstanceIdForDriver(selectedProvider);\n+ return providerStatuses.find((status) => status.instanceId === defaultInstanceId) ?? null;\n+ }, [activeProviderInstanceId, providerStatuses, selectedProvider]);\n const activeProjectCwd = activeProject?.cwd ?? null;\n const activeThreadWorktreePath = activeThread?.worktreePath ?? null;\n const activeWorkspaceRoot = activeThreadWorktreePath ?? activeProjectCwd ?? undefined;\n@@ -1945,7 +1963,7 @@ export default function ChatView(props: ChatViewProps) {\n if (\n input.modelSelection !== undefined &&\n (input.modelSelection.model !== serverThread.modelSelection.model ||\n- input.modelSelection.provider !== serverThread.modelSelection.provider ||\n+ input.modelSelection.instanceId !== serverThread.modelSelection.instanceId ||\n JSON.stringify(input.modelSelection.options ?? null) !==\n JSON.stringify(serverThread.modelSelection.options ?? null))\n ) {\n@@ -2559,10 +2577,8 @@ export default function ChatView(props: ChatViewProps) {\n }\n const title = truncate(titleSeed);\n const threadCreateModelSelection = createModelSelection(\n- ctxSelectedProvider,\n- ctxSelectedModel ||\n- activeProject.defaultModelSelection?.model ||\n- DEFAULT_MODEL_BY_PROVIDER.codex,\n+ ctxSelectedModelSelection.instanceId,\n+ ctxSelectedModel || activeProject.defaultModelSelection?.model || DEFAULT_MODEL,\n ctxSelectedModelSelection.options,\n );\n \n@@ -3128,21 +3144,46 @@ export default function ChatView(props: ChatViewProps) {\n ]);\n \n const onProviderModelSelect = useCallback(\n- (provider: ProviderKind, model: string) => {\n+ (instanceId: ProviderInstanceId, model: string) => {\n if (!activeThread) return;\n- if (lockedProvider !== null && provider !== lockedProvider) {\n+ // Look up the configured instance so model normalization and custom\n+ // model lookup stay scoped to that exact instance. Unknown instance ids\n+ // are rejected by returning early; the server remains authoritative too.\n+ const entry = providerStatuses.find((snapshot) => snapshot.instanceId === instanceId);\n+ const resolvedDriverKind = entry?.driver ?? null;\n+ if (\n+ lockedProvider !== null &&\n+ resolvedDriverKind !== null &&\n+ resolvedDriverKind !== lockedProvider\n+ ) {\n scheduleComposerFocus();\n return;\n }\n- const resolvedProvider = resolveSelectableProvider(providerStatuses, provider);\n- const resolvedModel = resolveAppModelSelection(\n- resolvedProvider,\n+ if (lockedProvider !== null && activeThread.session?.providerInstanceId) {\n+ const currentEntry = providerStatuses.find(\n+ (snapshot) => snapshot.instanceId === activeThread.session?.providerInstanceId,\n+ );\n+ if (\n+ currentEntry?.continuation?.groupKey &&\n+ entry?.continuation?.groupKey &&\n+ currentEntry.continuation.groupKey !== entry.continuation.groupKey\n+ ) {\n+ scheduleComposerFocus();\n+ return;\n+ }\n+ }\n+ const resolvedModel = resolveAppModelSelectionForInstance(\n+ instanceId,\n settings,\n providerStatuses,\n model,\n );\n+ if (!resolvedModel) {\n+ scheduleComposerFocus();\n+ return;\n+ }\n const nextModelSelection: ModelSelection = {\n- provider: resolvedProvider,\n+ instanceId,\n model: resolvedModel,\n };\n setComposerDraftModelSelection(\ndiff --git a/apps/web/src/components/CommandPalette.logic.test.ts b/apps/web/src/components/CommandPalette.logic.test.ts\nindex a49dadc851..38b44f3f6a 100644\n--- a/apps/web/src/components/CommandPalette.logic.test.ts\n+++ b/apps/web/src/components/CommandPalette.logic.test.ts\n@@ -1,5 +1,5 @@\n import { describe, expect, it, vi } from "vitest";\n-import { EnvironmentId, ProjectId, ThreadId } from "@t3tools/contracts";\n+import { EnvironmentId, ProjectId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";\n import type { Thread } from "../types";\n import {\n buildThreadActionItems,\n@@ -17,7 +17,7 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {\n codexThreadId: null,\n projectId: PROJECT_ID,\n title: "Thread",\n- modelSelection: { provider: "codex", model: "gpt-5" },\n+ modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5" },\n runtimeMode: "full-access",\n interactionMode: "default",\n session: null,\ndiff --git a/apps/web/src/components/CommandPalette.tsx b/apps/web/src/components/CommandPalette.tsx\nindex 2b587afc51..050337e438 100644\n--- a/apps/web/src/components/CommandPalette.tsx\n+++ b/apps/web/src/components/CommandPalette.tsx\n@@ -2,10 +2,11 @@\n \n import { scopeProjectRef, scopeThreadRef } from "@t3tools/client-runtime";\n import {\n- DEFAULT_MODEL_BY_PROVIDER,\n+ DEFAULT_MODEL,\n type EnvironmentId,\n type FilesystemBrowseResult,\n type ProjectId,\n+ ProviderInstanceId,\n } from "@t3tools/contracts";\n import { useQuery, useQueryClient } from "@tanstack/react-query";\n import { useNavigate, useParams } from "@tanstack/react-router";\n@@ -786,8 +787,8 @@ function OpenCommandPaletteDialog() {\n workspaceRoot: cwd,\n createWorkspaceRootIfMissing: true,\n defaultModelSelection: {\n- provider: "codex",\n- model: DEFAULT_MODEL_BY_PROVIDER.codex,\n+ instanceId: ProviderInstanceId.make("codex"),\n+ model: DEFAULT_MODEL,\n },\n createdAt: new Date().toISOString(),\n });\ndiff --git a/apps/web/src/components/Icons.tsx b/apps/web/src/components/Icons.tsx\nindex 98bc509a6f..7df7975fb1 100644\n--- a/apps/web/src/components/Icons.tsx\n+++ b/apps/web/src/components/Icons.tsx\n@@ -588,3 +588,26 @@ export const GithubCopilotIcon: Icon = ({ className, ...props }) => (\n <path d="M205.3 31.4c14 14.8 20 35.2 22.5 63.6 6.6 0 12.8 1.5 17 7.2l7.8 10.6c2.2 3 3.4 6.6 3.4 10.4v28.7a12 12 0 0 1-4.8 9.5C215.9 187.2 172.3 208 128 208c-49 0-98.2-28.3-123.2-46.6a12 12 0 0 1-4.8-9.5v-28.7c0-3.8 1.2-7.4 3.4-10.5l7.8-10.5c4.2-5.7 10.4-7.2 17-7.2 2.5-28.4 8.4-48.8 22.5-63.6C77.3 3.2 112.6 0 127.6 0h.4c14.7 0 50.4 2.9 77.3 31.4ZM128 78.7c-3 0-6.5.2-10.3.6a27.1 27.1 0 0 1-6 12.1 45 45 0 0 1-32 13c-6.8 0-13.9-1.5-19.7-5.2-5.5 1.9-10.8 4.5-11.2 11-.5 12.2-.6 24.5-.6 36.8 0 6.1 0 12.3-.2 18.5 0 3.6 2.2 6.9 5.5 8.4C79.9 185.9 105 192 128 192s48-6 74.5-18.1a9.4 9.4 0 0 0 5.5-8.4c.3-18.4 0-37-.8-55.3-.4-6.6-5.7-9.1-11.2-11-5.8 3.7-13 5.1-19.7 5.1a45 45 0 0 1-32-12.9 27.1 27.1 0 0 1-6-12.1c-3.4-.4-6.9-.5-10.3-.6Zm-27 44c5.8 0 10.5 4.6 10.5 10.4v19.2a10.4 10.4 0 0 1-20.8 0V133c0-5.8 4.6-10.4 10.4-10.4Zm53.4 0c5.8 0 10.4 4.6 10.4 10.4v19.2a10.4 10.4 0 0 1-20.8 0V133c0-5.8 4.7-10.4 10.4-10.4Zm-73-94.4c-11.2 1.1-20.6 4.8-25.4 10-10.4 11.3-8.2 40.1-2.2 46.2A31.2 31.2 0 0 0 75 91.7c6.8 0 19.6-1.5 30.1-12.2 4.7-4.5 7.5-15.7 7.2-27-.3-9.1-2.9-16.7-6.7-19.9-4.2-3.6-13.6-5.2-24.2-4.3Zm69 4.3c-3.8 3.2-6.4 10.8-6.7 19.9-.3 11.3 2.5 22.5 7.2 27a41.7 41.7 0 0 0 30 12.2c8.9 0 17-2.9 21.3-7.2 6-6.1 8.2-34.9-2.2-46.3-4.8-5-14.2-8.8-25.4-9.9-10.6-1-20 .7-24.2 4.3ZM128 56c-2.6 0-5.6.2-9 .5.4 1.7.5 3.7.7 5.7 0 1.5 0 3-.2 4.5 3.2-.3 6-.3 8.5-.3 2.6 0 5.3 0 8.5.3-.2-1.6-.2-3-.2-4.5.2-2 .3-4 .7-5.7-3.4-.3-6.4-.5-9-.5Z" />\n </svg>\n );\n+\n+export const ACPRegistryIcon: Icon = ({ className, ...props }) => (\n+ <svg\n+ {...props}\n+ viewBox="0 0 576 220"\n+ fill="none"\n+ className={cn("fill-black dark:fill-white", className)}\n+ >\n+ <path d="M568.003 115.821L517.278 27.9661C507.183 10.4816 489.084 0.0227367 468.894 0.0227367C448.727 0.0227367 430.674 10.4361 420.556 27.8752L343.251 161.749H242.755C236.23 161.749 230.386 158.384 227.135 152.745C223.861 147.106 223.861 140.376 227.135 134.715L277.861 46.8603C281.112 41.2216 286.955 37.8338 293.481 37.8338C300.006 37.8338 305.827 41.1988 309.101 46.8603L312.125 52.0897C313.353 54.2042 315.604 55.5002 318.036 55.5002C320.469 55.5002 322.743 54.1815 323.948 52.067L337.385 28.5118C338.795 26.0335 338.522 22.9413 336.703 20.7586C325.699 7.57131 309.874 0 293.322 0C292.662 0 292.003 0 291.321 0.0454733C272.04 0.75031 254.76 11.1864 245.074 27.9434L200.215 105.657L155.81 29.1484C145.465 11.2092 126.594 0.0227367 106.608 0.0227367C105.949 0.0227367 105.289 0.0227367 104.607 0.06821C85.3265 0.773047 68.0467 11.2092 58.3608 27.9661L7.65806 115.821C-6.25678 139.899 -0.868187 168.82 21.05 187.759C29.8945 195.422 41.6039 199.628 54.0181 199.628H148.648C151.081 199.628 153.332 198.332 154.56 196.217L168.52 172.026C169.748 169.911 169.748 167.319 168.52 165.205C167.292 163.09 165.041 161.794 162.608 161.794H56.0417C49.5163 161.794 43.6729 158.429 40.4216 152.79C37.1475 147.152 37.1475 140.422 40.4216 134.76L91.1471 46.9057C94.3985 41.2671 100.242 37.8793 106.767 37.8793C113.293 37.8793 119.113 41.2443 122.387 46.9057L194.826 172.526C195.031 172.89 195.258 173.208 195.531 173.526C198.76 178.665 202.83 183.485 207.786 187.782C216.631 195.444 228.34 199.651 240.754 199.651H321.424L315.581 209.769C314.353 211.883 314.353 214.475 315.581 216.59C316.809 218.704 319.059 220 321.492 220H349.436C351.868 220 354.119 218.704 355.347 216.59L364.396 200.901L367.17 196.468C367.17 196.468 367.261 196.331 367.284 196.263L453.274 46.9285C456.525 41.2898 462.369 37.902 468.894 37.902C475.42 37.902 481.263 41.2671 484.514 46.9285L535.24 134.783C538.491 140.422 538.514 147.174 535.24 152.813C531.988 158.452 526.145 161.84 519.62 161.84H418.669C416.236 161.84 413.985 163.136 412.757 165.25L398.774 189.442C397.546 191.556 397.546 194.148 398.774 196.263C400.002 198.377 402.253 199.673 404.686 199.673H518.21C539.81 199.673 559.295 188.237 569.026 169.843C578.053 152.79 577.666 132.623 567.981 115.843L568.003 115.821Z" />\n+ </svg>\n+);\n+\n+export const PiAgentIcon: Icon = ({ className, ...props }) => (\n+ <svg {...props} viewBox="0 0 800 800" className={cn("fill-none", className)}>\n+ <rect width="800" height="800" rx="160" fill="#000" />\n+ <path\n+ fill="#fff"\n+ fillRule="evenodd"\n+ d="M165.29 165.29H517.36V400H400V517.36H282.65V634.72H165.29ZM282.65 282.65V400H400V282.65Z"\n+ />\n+ <path fill="#fff" d="M517.36 400H634.72V634.72H517.36Z" />\n+ </svg>\n+);\ndiff --git a/apps/web/src/components/KeybindingsToast.browser.tsx b/apps/web/src/components/KeybindingsToast.browser.tsx\nindex 7eadd4e41b..df1c6ba542 100644\n--- a/apps/web/src/components/KeybindingsToast.browser.tsx\n+++ b/apps/web/src/components/KeybindingsToast.browser.tsx\n@@ -7,6 +7,8 @@ import {\n type MessageId,\n type OrchestrationReadModel,\n type ProjectId,\n+ ProviderDriverKind,\n+ ProviderInstanceId,\n type ServerConfig,\n type ServerLifecycleWelcomePayload,\n type ThreadId,\n@@ -72,7 +74,8 @@ function createBaseServerConfig(): ServerConfig {\n issues: [],\n providers: [\n {\n- provider: "codex",\n+ driver: ProviderDriverKind.make("codex"),\n+ instanceId: ProviderInstanceId.make("codex"),\n enabled: true,\n installed: true,\n version: "0.116.0",\n@@ -95,10 +98,25 @@ function createBaseServerConfig(): ServerConfig {\n ...DEFAULT_SERVER_SETTINGS,\n enableAssistantStreaming: false,\n defaultThreadEnvMode: "local" as const,\n- textGenerationModelSelection: { provider: "codex" as const, model: "gpt-5.4-mini" },\n+ textGenerationModelSelection: {\n+ instanceId: ProviderInstanceId.make("codex"),\n+ model: "gpt-5.4-mini",\n+ },\n providers: {\n- codex: { enabled: true, binaryPath: "", homePath: "", customModels: [] },\n- claudeAgent: { enabled: true, binaryPath: "", customModels: [], launchArgs: "" },\n+ codex: {\n+ enabled: true,\n+ binaryPath: "",\n+ homePath: "",\n+ shadowHomePath: "",\n+ customModels: [],\n+ },\n+ claudeAgent: {\n+ enabled: true,\n+ binaryPath: "",\n+ homePath: "",\n+ customModels: [],\n+ launchArgs: "",\n+ },\n cursor: { enabled: true, binaryPath: "", apiEndpoint: "", customModels: [] },\n opencode: {\n enabled: true,\n@@ -121,7 +139,7 @@ function createMinimalSnapshot(): OrchestrationReadModel {\n title: "Project",\n workspaceRoot: "/repo/project",\n defaultModelSelection: {\n- provider: "codex",\n+ instanceId: ProviderInstanceId.make("codex"),\n model: "gpt-5",\n },\n scripts: [],\n@@ -136,7 +154,7 @@ function createMinimalSnapshot(): OrchestrationReadModel {\n projectId: PROJECT_ID,\n title: "Test thread",\n modelSelection: {\n- provider: "codex",\n+ instanceId: ProviderInstanceId.make("codex"),\n model: "gpt-5",\n },\n interactionMode: "default",\ndiff --git a/apps/web/src/components/Sidebar.logic.test.ts b/apps/web/src/components/Sidebar.logic.test.ts\nindex f92f2f628c..926c117c1c 100644\n--- a/apps/web/src/components/Sidebar.logic.test.ts\n+++ b/apps/web/src/components/Sidebar.logic.test.ts\n@@ -1,4 +1,5 @@\n import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";\n+import { ProviderDriverKind } from "@t3tools/contracts";\n \n import {\n createThreadJumpHintVisibilityController,\n@@ -20,7 +21,13 @@ import {\n sortProjectsForSidebar,\n THREAD_JUMP_HINT_SHOW_DELAY_MS,\n } from "./Sidebar.logic";\n-import { EnvironmentId, OrchestrationLatestTurn, ProjectId, ThreadId } from "@t3tools/contracts";\n+import {\n+ EnvironmentId,\n+ OrchestrationLatestTurn,\n+ ProjectId,\n+ ProviderInstanceId,\n+ ThreadId,\n+} from "@t3tools/contracts";\n import {\n DEFAULT_INTERACTION_MODE,\n DEFAULT_RUNTIME_MODE,\n@@ -474,7 +481,7 @@ describe("resolveThreadStatusPill", () => {\n latestTurn: null,\n lastVisitedAt: undefined,\n session: {\n- provider: "codex" as const,\n+ provider: ProviderDriverKind.make("codex"),\n status: "running" as const,\n createdAt: "2026-03-09T10:00:00.000Z",\n updatedAt: "2026-03-09T10:00:00.000Z",\n@@ -698,7 +705,7 @@ function makeProject(overrides: Partial<Project> = {}): Project {\n name: "Project",\n cwd: "/tmp/project",\n defaultModelSelection: {\n- provider: "codex",\n+ instanceId: ProviderInstanceId.make("codex"),\n model: "gpt-5.4",\n ...defaultModelSelection,\n },\n@@ -717,7 +724,7 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {\n projectId: ProjectId.make("project-1"),\n title: "Thread",\n modelSelection: {\n- provider: "codex",\n+ instanceId: ProviderInstanceId.make("codex"),\n model: "gpt-5.4",\n ...overrides?.modelSelection,\n },\ndiff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx\nindex 3b47b2067c..2b7f62e8af 100644\n--- a/apps/web/src/components/chat/ChatComposer.tsx\n+++ b/apps/web/src/components/chat/ChatComposer.tsx\n@@ -5,7 +5,6 @@ import type {\n ProjectEntry,\n ProviderApprovalDecision,\n ProviderInteractionMode,\n- ProviderKind,\n ResolvedKeybindingsConfig,\n RuntimeMode,\n ScopedThreadRef,\n@@ -14,6 +13,8 @@ import type {\n TurnId,\n } from "@t3tools/contracts";\n import {\n+ ProviderDriverKind,\n+ ProviderInstanceId,\n PROVIDER_SEND_TURN_MAX_ATTACHMENTS,\n PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,\n } from "@t3tools/contracts";\n@@ -95,11 +96,14 @@ import {\n XIcon,\n } from "lucide-react";\n import { proposedPlanTitle } from "../../proposedPlan";\n+import { getProviderInteractionModeToggle } from "../../providerModels";\n import {\n- getProviderInteractionModeToggle,\n- getProviderModels,\n- resolveSelectableProvider,\n-} from "../../providerModels";\n+ deriveProviderInstanceEntries,\n+ resolveProviderDriverKindForInstanceSelection,\n+ sortProviderInstanceEntries,\n+ type ProviderInstanceEntry,\n+} from "../../providerInstances";\n+import { type AppModelOption, getAppModelOptionsForInstance } from "../../modelSelection";\n import type { UnifiedSettings } from "@t3tools/contracts/settings";\n import type { SessionPhase, Thread } from "../../types";\n import type { PendingUserInputDraftAnswer } from "../../pendingUserInput";\n@@ -346,7 +350,7 @@ export interface ChatComposerHandle {\n selectedPromptEffort: string | null;\n selectedModelOptionsForDispatch: unknown;\n selectedModelSelection: ModelSelection;\n- selectedProvider: ProviderKind;\n+ selectedProvider: ProviderDriverKind;\n selectedModel: string;\n selectedProviderModels: ReadonlyArray<ServerProvider["models"][number]>;\n };\n@@ -406,7 +410,7 @@ export interface ChatComposerProps {\n interactionMode: ProviderInteractionMode;\n \n // Provider / model\n- lockedProvider: ProviderKind | null;\n+ lockedProvider: ProviderDriverKind | null;\n providerStatuses: ServerProvider[];\n activeProjectDefaultModelSelection: ModelSelection | null | undefined;\n activeThreadModelSelection: ModelSelection | null | undefined;\n@@ -449,7 +453,7 @@ export interface ChatComposerProps {\n cursorAdjacentToMention: boolean,\n ) => void;\n \n- onProviderModelSelect: (provider: ProviderKind, model: string) => void;\n+ onProviderModelSelect: (instanceId: ProviderInstanceId, model: string) => void;\n toggleInteractionMode: () => void;\n handleRuntimeModeChange: (mode: RuntimeMode) => void;\n handleInteractionModeChange: (mode: ProviderInteractionMode) => void;\n@@ -566,29 +570,134 @@ export const ChatComposer = memo(\n // ------------------------------------------------------------------\n // Model state\n // ------------------------------------------------------------------\n+ // Instance-aware projection of the wire provider list. One entry per\n+ // configured instance (default built-in + any custom `providerInstances.*`),\n+ // sorted default-first per driver kind for a stable picker order.\n+ const providerInstanceEntries = useMemo<ReadonlyArray<ProviderInstanceEntry>>(\n+ () => sortProviderInstanceEntries(deriveProviderInstanceEntries(providerStatuses)),\n+ [providerStatuses],\n+ );\n const selectedProviderByThreadId = composerDraft.activeProvider ?? null;\n const threadProvider =\n- activeThreadModelSelection?.provider ?? activeProjectDefaultModelSelection?.provider ?? null;\n+ activeThread?.session?.providerInstanceId ??\n+ activeThreadModelSelection?.instanceId ??\n+ activeProjectDefaultModelSelection?.instanceId ??\n+ null;\n+ const explicitSelectedInstanceId = selectedProviderByThreadId ?? threadProvider;\n+\n+ const unlockedSelectedProvider =\n+ resolveProviderDriverKindForInstanceSelection(\n+ providerInstanceEntries,\n+ providerStatuses,\n+ explicitSelectedInstanceId,\n+ ) ?? ProviderDriverKind.make("codex");\n+ const selectedProvider: ProviderDriverKind = lockedProvider ?? unlockedSelectedProvider;\n+ const lockedContinuationGroupKey = useMemo((): string | null => {\n+ if (!lockedProvider || !activeThread) return null;\n+ const lockedInstanceId =\n+ activeThread.session?.providerInstanceId ?? activeThreadModelSelection?.instanceId;\n+ if (!lockedInstanceId) return null;\n+ return (\n+ providerInstanceEntries.find((entry) => entry.instanceId === lockedInstanceId)\n+ ?.continuationGroupKey ?? null\n+ );\n+ }, [\n+ activeThread,\n+ activeThreadModelSelection?.instanceId,\n+ lockedProvider,\n+ providerInstanceEntries,\n+ ]);\n \n- const unlockedSelectedProvider = resolveSelectableProvider(\n- providerStatuses,\n- selectedProviderByThreadId ?? threadProvider ?? "codex",\n- );\n- const selectedProvider: ProviderKind = lockedProvider ?? unlockedSelectedProvider;\n+ // Resolve which configured instance the composer is currently targeting.\n+ // Priority:\n+ // 1. The composer draft\'s `activeProvider` — the user\'s unsaved pick\n+ // from the model picker (must win, otherwise the UI appears to\n+ // ignore picker selections).\n+ // 2. Thread\'s persisted instance id (server-side saved selection).\n+ // 3. Project default\'s instance id.\n+ // 4. First enabled entry matching the current driver kind.\n+ // 5. First enabled entry overall / default instance for the kind.\n+ //\n+ const selectedInstanceId = useMemo<ProviderInstanceId>(() => {\n+ const candidates: Array<string | null | undefined> = [\n+ composerDraft.activeProvider,\n+ activeThread?.session?.providerInstanceId,\n+ activeThreadModelSelection?.instanceId,\n+ activeProjectDefaultModelSelection?.instanceId,\n+ ];\n+ for (const candidate of candidates) {\n+ if (!candidate) continue;\n+ const match = providerInstanceEntries.find(\n+ (entry) => entry.instanceId === candidate && entry.enabled,\n+ );\n+ if (match) {\n+ // When locked to a specific driver kind, ignore persisted instance\n+ // ids from a different kind or continuation group.\n+ if (lockedProvider && match.driverKind !== lockedProvider) continue;\n+ if (\n+ lockedContinuationGroupKey &&\n+ match.continuationGroupKey !== lockedContinuationGroupKey\n+ ) {\n+ continue;\n+ }\n+ return match.instanceId;\n+ }\n+ }\n+ if (explicitSelectedInstanceId) {\n+ return ProviderInstanceId.make(explicitSelectedInstanceId);\n+ }\n+ const byKind = providerInstanceEntries.find(\n+ (entry) =>\n+ entry.enabled &&\n+ entry.driverKind === selectedProvider &&\n+ (!lockedContinuationGroupKey ||\n+ entry.continuationGroupKey === lockedContinuationGroupKey),\n+ );\n+ if (byKind) return byKind.instanceId;\n+ const anyEnabled = providerInstanceEntries.find((entry) => entry.enabled);\n+ return (\n+ anyEnabled?.instanceId ??\n+ providerInstanceEntries[0]?.instanceId ??\n+ activeThreadModelSelection?.instanceId ??\n+ activeProjectDefaultModelSelection?.instanceId ??\n+ ProviderInstanceId.make("codex")\n+ );\n+ }, [\n+ activeProjectDefaultModelSelection?.instanceId,\n+ activeThread?.session?.providerInstanceId,\n+ activeThreadModelSelection?.instanceId,\n+ composerDraft.activeProvider,\n+ explicitSelectedInstanceId,\n+ lockedContinuationGroupKey,\n+ lockedProvider,\n+ providerInstanceEntries,\n+ selectedProvider,\n+ ]);\n \n const { modelOptions: composerModelOptions, selectedModel } = useEffectiveComposerModelState({\n threadRef: composerDraftTarget,\n providers: providerStatuses,\n selectedProvider,\n+ selectedInstanceId,\n threadModelSelection: activeThreadModelSelection,\n projectModelSelection: activeProjectDefaultModelSelection,\n settings,\n });\n \n- const selectedProviderModels = getProviderModels(providerStatuses, selectedProvider);\n+ // Resolve the active instance\'s snapshot by `instanceId` so a custom\n+ // instance gets its own slash commands, skills, and model list — not\n+ // the first snapshot for the same driver kind.\n+ const selectedProviderEntry = useMemo(\n+ () => providerInstanceEntries.find((entry) => entry.instanceId === selectedInstanceId),\n+ [providerInstanceEntries, selectedInstanceId],\n+ );\n const selectedProviderStatus = useMemo(\n- () => providerStatuses.find((provider) => provider.provider === selectedProvider),\n- [providerStatuses, selectedProvider],\n+ () => selectedProviderEntry?.snapshot ?? null,\n+ [selectedProviderEntry],\n+ );\n+ const selectedProviderModels = useMemo<ReadonlyArray<ServerProvider["models"][number]>>(\n+ () => selectedProviderEntry?.models ?? [],\n+ [selectedProviderEntry],\n );\n \n const composerProviderState = useMemo(\n@@ -615,29 +724,30 @@ export const ChatComposer = memo(\n [providerStatuses, selectedProvider],\n );\n const selectedModelSelection = useMemo<ModelSelection>(\n- () => createModelSelection(selectedProvider, selectedModel, selectedModelOptionsForDispatch),\n- [selectedModel, selectedModelOptionsForDispatch, selectedProvider],\n+ () =>\n+ createModelSelection(selectedInstanceId, selectedModel, selectedModelOptionsForDispatch),\n+ [selectedInstanceId, selectedModel, selectedModelOptionsForDispatch],\n );\n const selectedModelForPicker = selectedModel;\n- const modelOptionsByProvider = useMemo<\n- Record<ProviderKind, ReadonlyArray<ServerProvider["models"][number]>>\n- >(\n- () => ({\n- codex: providerStatuses.find((provider) => provider.provider === "codex")?.models ?? [],\n- claudeAgent:\n- providerStatuses.find((provider) => provider.provider === "claudeAgent")?.models ?? [],\n- opencode:\n- providerStatuses.find((provider) => provider.provider === "opencode")?.models ?? [],\n- cursor: providerStatuses.find((provider) => provider.provider === "cursor")?.models ?? [],\n- }),\n- [providerStatuses],\n- );\n+ // Instance-keyed option list so the picker can show each configured\n+ // instance (built-in + custom) as a first-class sidebar entry. The\n+ // options are server-reported models plus that exact instance\'s\n+ // configured custom models; selected slugs are not injected into lists.\n+ const modelOptionsByInstance = useMemo<\n+ ReadonlyMap<ProviderInstanceId, ReadonlyArray<AppModelOption>>\n+ >(() => {\n+ const out = new Map<ProviderInstanceId, ReadonlyArray<AppModelOption>>();\n+ for (const entry of providerInstanceEntries) {\n+ out.set(entry.instanceId, getAppModelOptionsForInstance(settings, entry));\n+ }\n+ return out;\n+ }, [providerInstanceEntries, settings]);\n const selectedModelForPickerWithCustomFallback = useMemo(() => {\n- const currentOptions = modelOptionsByProvider[selectedProvider];\n+ const currentOptions = modelOptionsByInstance.get(selectedInstanceId) ?? [];\n return currentOptions.some((option) => option.slug === selectedModelForPicker)\n ? selectedModelForPicker\n : (normalizeModelSlug(selectedModelForPicker, selectedProvider) ?? selectedModelForPicker);\n- }, [modelOptionsByProvider, selectedModelForPicker, selectedProvider]);\n+ }, [modelOptionsByInstance, selectedInstanceId, selectedModelForPicker, selectedProvider]);\n \n // ------------------------------------------------------------------\n // Context window\n@@ -1889,12 +1999,13 @@ export const ChatComposer = memo(\n <div className="-m-1 flex min-w-0 flex-1 items-center gap-1 overflow-x-auto p-1 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">\n <ProviderModelPicker\n compact={isComposerFooterCompact}\n- provider={selectedProvider}\n+ activeInstanceId={selectedInstanceId}\n model={selectedModelForPickerWithCustomFallback}\n lockedProvider={lockedProvider}\n- providers={providerStatuses}\n+ lockedContinuationGroupKey={lockedContinuationGroupKey}\n+ instanceEntries={providerInstanceEntries}\n keybindings={keybindings}\n- modelOptionsByProvider={modelOptionsByProvider}\n+ modelOptionsByInstance={modelOptionsByInstance}\n terminalOpen={terminalOpen}\n open={isComposerModelPickerOpen}\n {...(composerProviderState.modelPickerIconClassName\n@@ -1906,7 +2017,7 @@ export const ChatComposer = memo(\n onOpenChange={(open) => {\n setIsComposerModelPickerOpen(open);\n }}\n- onProviderModelChange={onProviderModelSelect}\n+ onInstanceModelChange={onProviderModelSelect}\n />\n \n {isComposerFooterCompact ? (\ndiff --git a/apps/web/src/components/chat/CompactComposerControlsMenu.browser.tsx b/apps/web/src/components/chat/CompactComposerControlsMenu.browser.tsx\nindex 1808b94033..49eb5fbb94 100644\n--- a/apps/web/src/components/chat/CompactComposerControlsMenu.browser.tsx\n+++ b/apps/web/src/components/chat/CompactComposerControlsMenu.browser.tsx\n@@ -1,7 +1,10 @@\n import {\n+ DEFAULT_MODEL,\n DEFAULT_MODEL_BY_PROVIDER,\n EnvironmentId,\n ModelSelection,\n+ ProviderInstanceId,\n+ ProviderDriverKind,\n ThreadId,\n } from "@t3tools/contracts";\n import { scopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime";\n@@ -50,8 +53,10 @@ async function mountMenu(props?: { modelSelection?: ModelSelection; prompt?: str\n const threadId = ThreadId.make("thread-compact-menu");\n const threadRef = scopeThreadRef(LOCAL_ENVIRONMENT_ID, threadId);\n const threadKey = scopedThreadKey(threadRef);\n- const provider = props?.modelSelection?.provider ?? "claudeAgent";\n- const model = props?.modelSelection?.model ?? DEFAULT_MODEL_BY_PROVIDER[provider];\n+ const provider = ProviderDriverKind.make("claudeAgent");\n+ const instanceId = ProviderInstanceId.make(props?.modelSelection?.instanceId ?? provider);\n+ const model =\n+ props?.modelSelection?.model ?? DEFAULT_MODEL_BY_PROVIDER[provider] ?? DEFAULT_MODEL;\n \n useComposerDraftStore.setState({\n draftsByThreadKey: {\n@@ -62,9 +67,9 @@ async function mountMenu(props?: { modelSelection?: ModelSelection; prompt?: str\n persistedAttachments: [],\n terminalContexts: [],\n modelSelectionByProvider: {\n- [provider]: createModelSelection(provider, model, props?.modelSelection?.options),\n+ [instanceId]: createModelSelection(instanceId, model, props?.modelSelection?.options),\n },\n- activeProvider: provider,\n+ activeProvider: instanceId,\n runtimeMode: null,\n interactionMode: null,\n },\n@@ -178,7 +183,10 @@ describe("CompactComposerControlsMenu", () => {\n \n it("shows fast mode controls for Opus", async () => {\n await using _ = await mountMenu({\n- modelSelection: createModelSelection("claudeAgent", "claude-opus-4-6"),\n+ modelSelection: createModelSelection(\n+ ProviderInstanceId.make("claudeAgent"),\n+ "claude-opus-4-6",\n+ ),\n });\n \n await page.getByLabelText("More composer controls").click();\n@@ -193,7 +201,10 @@ describe("CompactComposerControlsMenu", () => {\n \n it("hides fast mode controls for non-Opus Claude models", async () => {\n await using _ = await mountMenu({\n- modelSelection: createModelSelection("claudeAgent", "claude-sonnet-4-6"),\n+ modelSelection: createModelSelection(\n+ ProviderInstanceId.make("claudeAgent"),\n+ "claude-sonnet-4-6",\n+ ),\n });\n \n await page.getByLabelText("More composer controls").click();\n@@ -205,7 +216,10 @@ describe("CompactComposerControlsMenu", () => {\n \n it("shows only the provided effort options", async () => {\n await using _ = await mountMenu({\n- modelSelection: createModelSelection("claudeAgent", "claude-sonnet-4-6"),\n+ modelSelection: createModelSelection(\n+ ProviderInstanceId.make("claudeAgent"),\n+ "claude-sonnet-4-6",\n+ ),\n });\n \n await page.getByLabelText("More composer controls").click();\n@@ -222,9 +236,11 @@ describe("CompactComposerControlsMenu", () => {\n \n it("shows a Claude thinking on/off section for Haiku", async () => {\n await using _ = await mountMenu({\n- modelSelection: createModelSelection("claudeAgent", "claude-haiku-4-5", [\n- { id: "thinking", value: true },\n- ]),\n+ modelSelection: createModelSelection(\n+ ProviderInstanceId.make("claudeAgent"),\n+ "claude-haiku-4-5",\n+ [{ id: "thinking", value: true }],\n+ ),\n });\n \n await page.getByLabelText("More composer controls").click();\n@@ -239,9 +255,11 @@ describe("CompactComposerControlsMenu", () => {\n \n it("shows prompt-controlled Ultrathink state with selectable effort controls", async () => {\n await using _ = await mountMenu({\n- modelSelection: createModelSelection("claudeAgent", "claude-opus-4-6", [\n- { id: "effort", value: "high" },\n- ]),\n+ modelSelection: createModelSelection(\n+ ProviderInstanceId.make("claudeAgent"),\n+ "claude-opus-4-6",\n+ [{ id: "effort", value: "high" }],\n+ ),\n prompt: "Ultrathink:\\nInvestigate this",\n });\n \n@@ -256,9 +274,11 @@ describe("CompactComposerControlsMenu", () => {\n \n it("warns when ultrathink appears in prompt body text", async () => {\n await using _ = await mountMenu({\n- modelSelection: createModelSelection("claudeAgent", "claude-opus-4-6", [\n- { id: "effort", value: "high" },\n- ]),\n+ modelSelection: createModelSelection(\n+ ProviderInstanceId.make("claudeAgent"),\n+ "claude-opus-4-6",\n+ [{ id: "effort", value: "high" }],\n+ ),\n prompt: "Ultrathink:\\nplease ultrathink about this problem",\n });\n \ndiff --git a/apps/web/src/components/chat/ComposerCommandMenu.tsx b/apps/web/src/components/chat/ComposerCommandMenu.tsx\nindex 5d13e6593b..f687ec7ba2 100644\n--- a/apps/web/src/components/chat/ComposerCommandMenu.tsx\n+++ b/apps/web/src/components/chat/ComposerCommandMenu.tsx\n@@ -1,6 +1,6 @@\n import {\n type ProjectEntry,\n- type ProviderKind,\n+ type ProviderDriverKind,\n type ServerProviderSkill,\n type ServerProviderSlashCommand,\n } from "@t3tools/contracts";\n@@ -39,7 +39,7 @@ export type ComposerCommandItem =\n | {\n id: string;\n type: "provider-slash-command";\n- provider: ProviderKind;\n+ provider: ProviderDriverKind;\n command: ServerProviderSlashCommand;\n label: string;\n description: string;\n@@ -47,7 +47,7 @@ export type ComposerCommandItem =\n | {\n id: string;\n type: "skill";\n- provider: ProviderKind;\n+ provider: ProviderDriverKind;\n skill: ServerProviderSkill;\n label: string;\n description: string;\ndiff --git a/apps/web/src/components/chat/ModelListRow.tsx b/apps/web/src/components/chat/ModelListRow.tsx\nindex 6cd097ad1f..064df338e4 100644\n--- a/apps/web/src/components/chat/ModelListRow.tsx\n+++ b/apps/web/src/components/chat/ModelListRow.tsx\n@@ -1,9 +1,8 @@\n-import { type ProviderKind } from "@t3tools/contracts";\n+import { type ProviderDriverKind, type ProviderInstanceId } from "@t3tools/contracts";\n import { memo } from "react";\n import { StarIcon } from "lucide-react";\n import {\n getDisplayModelName,\n- getProviderLabel,\n getTriggerDisplayModelLabel,\n type ModelEsque,\n PROVIDER_ICON_BY_PROVIDER,\n@@ -16,7 +15,17 @@ import { cn } from "~/lib/utils";\n export const ModelListRow = memo(function ModelListRow(props: {\n index: number;\n model: ModelEsque;\n- provider: ProviderKind;\n+ /** Instance the model belongs to — the routing key used in combobox values. */\n+ instanceId: ProviderInstanceId;\n+ /** Driver kind of the instance — used for the provider icon glyph. */\n+ driverKind: ProviderDriverKind;\n+ /**\n+ * Display name to show in the secondary line (provider footer). Usually\n+ * the instance\'s configured `displayName` so custom instances like\n+ * "Codex Personal" render with their user-authored label.\n+ */\n+ providerDisplayName: string;\n+ providerAccentColor?: string | undefined;\n isFavorite: boolean;\n showProvider: boolean;\n preferShortName?: boolean;\n@@ -25,13 +34,16 @@ export const ModelListRow = memo(function ModelListRow(props: {\n jumpLabel?: string | null;\n onToggleFavorite: () => void;\n }) {\n- const ProviderIcon = PROVIDER_ICON_BY_PROVIDER[props.provider];\n+ const ProviderIcon = PROVIDER_ICON_BY_PROVIDER[props.driverKind] ?? null;\n+ const providerLabel = props.model.subProvider\n+ ? `${props.providerDisplayName} · ${props.model.subProvider}`\n+ : props.providerDisplayName;\n \n return (\n <ComboboxItem\n hideIndicator\n index={props.index}\n- value={`${props.provider}:${props.model.slug}`}\n+ value={`${props.instanceId}:${props.model.slug}`}\n contentClassName="flex w-full items-start gap-2"\n className={cn(\n "w-full cursor-pointer rounded px-3 py-2 transition-colors group",\n@@ -92,9 +104,16 @@ export const ModelListRow = memo(function ModelListRow(props: {\n </div>\n {props.showProvider && (\n <div className="flex items-center gap-1 mt-0.5">\n- <ProviderIcon className="size-3 shrink-0" />\n+ {ProviderIcon ? <ProviderIcon className="size-3 shrink-0" /> : null}\n+ {props.providerAccentColor ? (\n+ <span\n+ className="size-1.5 shrink-0 rounded-full"\n+ style={{ backgroundColor: props.providerAccentColor }}\n+ aria-hidden\n+ />\n+ ) : null}\n <span className="text-xs font-normal leading-snug text-muted-foreground/70 truncate">\n- {getProviderLabel(props.provider, props.model)}\n+ {providerLabel}\n </span>\n </div>\n )}\ndiff --git a/apps/web/src/components/chat/ModelPickerContent.tsx b/apps/web/src/components/chat/ModelPickerContent.tsx\nindex 82720425ef..c3468ef8c6 100644\n--- a/apps/web/src/components/chat/ModelPickerContent.tsx\n+++ b/apps/web/src/components/chat/ModelPickerContent.tsx\n@@ -1,8 +1,7 @@\n import {\n- type ProviderKind,\n- PROVIDER_DISPLAY_NAMES,\n+ type ProviderInstanceId,\n+ type ProviderDriverKind,\n type ResolvedKeybindingsConfig,\n- type ServerProvider,\n } from "@t3tools/contracts";\n import { resolveSelectableModel } from "@t3tools/shared/model";\n import { memo, useMemo, useState, useCallback, useEffect, useLayoutEffect, useRef } from "react";\n@@ -22,40 +21,89 @@ import {\n import { useSettings, useUpdateSettings } from "~/hooks/useSettings";\n import { cn } from "~/lib/utils";\n import { TooltipProvider } from "../ui/tooltip";\n+import type { ProviderInstanceEntry } from "../../providerInstances";\n+import { providerModelKey, sortProviderModelItems } from "../../modelOrdering";\n \n type ModelPickerItem = {\n slug: string;\n name: string;\n shortName?: string;\n subProvider?: string;\n- provider: ProviderKind;\n+ instanceId: ProviderInstanceId;\n+ driverKind: ProviderDriverKind;\n+ instanceDisplayName: string;\n+ instanceAccentColor?: string | undefined;\n+ continuationGroupKey?: string | undefined;\n };\n \n const EMPTY_MODEL_JUMP_LABELS = new Map<string, string>();\n \n+// Split a `${instanceId}:${slug}` combobox key back into its pieces. Slugs\n+// can contain colons (e.g. some vendor model ids), so we only split on the\n+// first colon — anything after that is the slug.\n+function splitInstanceModelKey(key: string): { instanceId: ProviderInstanceId; slug: string } {\n+ const colonIndex = key.indexOf(":");\n+ if (colonIndex === -1) {\n+ return { instanceId: key as ProviderInstanceId, slug: "" };\n+ }\n+ return {\n+ instanceId: key.slice(0, colonIndex) as ProviderInstanceId,\n+ slug: key.slice(colonIndex + 1),\n+ };\n+}\n+\n export const ModelPickerContent = memo(function ModelPickerContent(props: {\n- provider: ProviderKind;\n+ /** The instance currently selected in the composer (combobox "value"). */\n+ activeInstanceId: ProviderInstanceId;\n model: string;\n- lockedProvider: ProviderKind | null;\n- providers?: ReadonlyArray<ServerProvider>;\n+ /**\n+ * When set, the picker is locked to the given driver kind — typically\n+ * because the user is editing a previously-sent message and can\'t change\n+ * which driver served the turn. Multiple instances of the same kind\n+ * remain selectable (e.g. locked to `codex` still lets the user switch\n+ * between the default Codex and a custom Codex Personal).\n+ */\n+ lockedProvider: ProviderDriverKind | null;\n+ lockedContinuationGroupKey?: string | null;\n+ /**\n+ * All configured provider instances in display order. Used to render\n+ * the sidebar (one button per instance) and to resolve display names\n+ * for the locked-mode header.\n+ */\n+ instanceEntries: ReadonlyArray<ProviderInstanceEntry>;\n keybindings?: ResolvedKeybindingsConfig;\n- modelOptionsByProvider: Record<ProviderKind, ReadonlyArray<ModelEsque>>;\n+ /**\n+ * Model options per instance. Keyed by `ProviderInstanceId` so the\n+ * default Codex instance and any custom Codex instances each have their\n+ * own list (custom instances typically start with the same built-in\n+ * model set but are free to diverge via customModels).\n+ */\n+ modelOptionsByInstance: ReadonlyMap<ProviderInstanceId, ReadonlyArray<ModelEsque>>;\n terminalOpen: boolean;\n onRequestClose?: () => void;\n- onProviderModelChange: (provider: ProviderKind, model: string) => void;\n+ onInstanceModelChange: (instanceId: ProviderInstanceId, model: string) => void;\n }) {\n- const { keybindings: providedKeybindings, modelOptionsByProvider, onProviderModelChange } = props;\n+ const {\n+ keybindings: providedKeybindings,\n+ modelOptionsByInstance,\n+ instanceEntries,\n+ onInstanceModelChange,\n+ } = props;\n const [searchQuery, setSearchQuery] = useState("");\n const searchInputRef = useRef<HTMLInputElement>(null);\n const listRegionRef = useRef<HTMLDivElement>(null);\n const highlightedModelKeyRef = useRef<string | null>(null);\n const favorites = useSettings((s) => s.favorites ?? []);\n- const [selectedProvider, setSelectedProvider] = useState<ProviderKind | "favorites">(() => {\n- if (props.lockedProvider !== null) {\n- return props.lockedProvider;\n- }\n- return favorites.length > 0 ? "favorites" : props.provider;\n- });\n+ const [selectedInstanceId, setSelectedInstanceId] = useState<ProviderInstanceId | "favorites">(\n+ () => {\n+ if (props.lockedProvider !== null) {\n+ // When locked, prime the sidebar to the currently-active instance\n+ // so jumping into the picker keeps the focused instance visible.\n+ return props.activeInstanceId;\n+ }\n+ return favorites.length > 0 ? "favorites" : props.activeInstanceId;\n+ },\n+ );\n const keybindings = useMemo<ResolvedKeybindingsConfig>(\n () => providedKeybindings ?? [],\n [providedKeybindings],\n@@ -66,9 +114,9 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {\n searchInputRef.current?.focus({ preventScroll: true });\n }, []);\n \n- const handleSelectProvider = useCallback(\n- (provider: ProviderKind | "favorites") => {\n- setSelectedProvider(provider);\n+ const handleSelectInstance = useCallback(\n+ (instanceId: ProviderInstanceId | "favorites") => {\n+ setSelectedInstanceId(instanceId);\n window.requestAnimationFrame(() => {\n focusSearchInput();\n });\n@@ -90,44 +138,97 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {\n };\n }, [focusSearchInput]);\n \n- // Create a Set for efficient lookup\n+ // Create a Set for efficient lookup. Favorites are keyed by\n+ // `${instanceId}:${slug}`; the storage schema widened from ProviderDriverKind\n+ // to ProviderInstanceId so pre-migration favorites keyed by driver slugs\n+ // (e.g. `"codex:gpt-5"`) still resolve — the default instance id equals\n+ // the driver slug.\n const favoritesSet = useMemo(() => {\n- return new Set(favorites.map((fav) => `${fav.provider}:${fav.model}`));\n- }, [favorites]);\n- const favoriteOrder = useMemo(() => {\n- return new Map(\n- favorites.map((favorite, index) => [`${favorite.provider}:${favorite.model}`, index]),\n- );\n+ return new Set(favorites.map((fav) => providerModelKey(fav.provider, fav.model)));\n }, [favorites]);\n \n- const readyProviderSet = useMemo(() => {\n- if (!props.providers || props.providers.length === 0) {\n- return null;\n+ /**\n+ * Lookup table keyed by `instanceId`. Used for display name + driver\n+ * kind enrichment and for `ready`/enabled filtering before flattening\n+ * models into the search list.\n+ */\n+ const entryByInstanceId = useMemo(\n+ () => new Map(instanceEntries.map((entry) => [entry.instanceId, entry])),\n+ [instanceEntries],\n+ );\n+ const matchesLockedProvider = useCallback(\n+ (entry: Pick<ProviderInstanceEntry, "driverKind" | "continuationGroupKey">): boolean => {\n+ if (props.lockedProvider === null) return true;\n+ if (entry.driverKind !== props.lockedProvider) return false;\n+ if (!props.lockedContinuationGroupKey) return true;\n+ return entry.continuationGroupKey === props.lockedContinuationGroupKey;\n+ },\n+ [props.lockedContinuationGroupKey, props.lockedProvider],\n+ );\n+\n+ const readyInstanceSet = useMemo(() => {\n+ const ready = new Set<ProviderInstanceId>();\n+ for (const entry of instanceEntries) {\n+ if (entry.status === "ready") {\n+ ready.add(entry.instanceId);\n+ }\n }\n- return new Set(\n- props.providers\n- .filter((provider) => provider.status === "ready")\n- .map((provider) => provider.provider),\n- );\n- }, [props.providers]);\n-\n- // Flatten models into a searchable array\n+ return ready;\n+ }, [instanceEntries]);\n+\n+ // Flatten models into a searchable array. One pass over the\n+ // instance-keyed map; each model carries its instance id + driver kind\n+ // so the list row can render the right icon and display name without\n+ // another lookup.\n const flatModels = useMemo(() => {\n- return Object.entries(props.modelOptionsByProvider).flatMap(([providerKind, models]) => {\n- if (readyProviderSet && !readyProviderSet.has(providerKind as ProviderKind)) {\n- return [];\n+ const out: ModelPickerItem[] = [];\n+ for (const [instanceId, models] of modelOptionsByInstance) {\n+ const entry = entryByInstanceId.get(instanceId);\n+ if (!entry) {\n+ // Instance disappeared between renders (configuration change). Skip\n+ // its models — stale options shouldn\'t appear in the picker.\n+ continue;\n }\n- return models.map((m) => ({\n- slug: m.slug,\n- name: m.name,\n- ...(m.shortName ? { shortName: m.shortName } : {}),\n- ...(m.subProvider ? { subProvider: m.subProvider } : {}),\n- provider: providerKind as ProviderKind,\n- })) satisfies Array<ModelPickerItem>;\n- });\n- }, [props.modelOptionsByProvider, readyProviderSet]);\n+ if (!readyInstanceSet.has(instanceId)) {\n+ continue;\n+ }\n+ for (const model of models) {\n+ out.push({\n+ slug: model.slug,\n+ name: model.name,\n+ ...(model.shortName ? { shortName: model.shortName } : {}),\n+ ...(model.subProvider ? { subProvider: model.subProvider } : {}),\n+ instanceId,\n+ driverKind: entry.driverKind,\n+ instanceDisplayName: entry.displayName,\n+ ...(entry.accentColor ? { instanceAccentColor: entry.accentColor } : {}),\n+ ...(entry.continuationGroupKey\n+ ? { continuationGroupKey: entry.continuationGroupKey }\n+ : {}),\n+ });\n+ }\n+ }\n+ return out;\n+ }, [modelOptionsByInstance, entryByInstanceId, readyInstanceSet]);\n+\n+ const isLocked = props.lockedProvider !== null;\n+ const isSearching = searchQuery.trim().length > 0;\n+ const lockedInstanceEntries = useMemo(\n+ () =>\n+ props.lockedProvider ? instanceEntries.filter((entry) => matchesLockedProvider(entry)) : [],\n+ [instanceEntries, matchesLockedProvider, props.lockedProvider],\n+ );\n+ const showLockedInstanceSidebar = isLocked && lockedInstanceEntries.length > 1;\n+ const showSidebar = !isSearching && (!isLocked || showLockedInstanceSidebar);\n+ const sidebarInstanceEntries = showLockedInstanceSidebar\n+ ? lockedInstanceEntries\n+ : instanceEntries;\n+ const instanceOrder = useMemo(\n+ () => instanceEntries.map((entry) => entry.instanceId),\n+ [instanceEntries],\n+ );\n \n- // Filter models based on search query and selected provider\n+ // Filter models based on search query and selected instance\n const filteredModels = useMemo(() => {\n let result = flatModels;\n \n@@ -138,13 +239,23 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {\n model,\n score: scoreModelPickerSearch(\n {\n- ...model,\n- isFavorite: favoritesSet.has(`${model.provider}:${model.slug}`),\n+ name: model.name,\n+ ...(model.shortName ? { shortName: model.shortName } : {}),\n+ ...(model.subProvider ? { subProvider: model.subProvider } : {}),\n+ driverKind: model.driverKind,\n+ providerDisplayName: model.instanceDisplayName,\n+ isFavorite: favoritesSet.has(providerModelKey(model.instanceId, model.slug)),\n },\n searchQuery,\n ),\n- isFavorite: favoritesSet.has(`${model.provider}:${model.slug}`),\n- tieBreaker: buildModelPickerSearchText(model),\n+ isFavorite: favoritesSet.has(providerModelKey(model.instanceId, model.slug)),\n+ tieBreaker: buildModelPickerSearchText({\n+ name: model.name,\n+ ...(model.shortName ? { shortName: model.shortName } : {}),\n+ ...(model.subProvider ? { subProvider: model.subProvider } : {}),\n+ driverKind: model.driverKind,\n+ providerDisplayName: model.instanceDisplayName,\n+ }),\n }))\n .filter(\n (\n@@ -157,10 +268,12 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {\n } => rankedModel.score !== null,\n );\n \n- // When searching, we only respect locked provider, ignoring sidebar selection\n+ // When searching, we only respect locked provider (by driver kind),\n+ // ignoring sidebar selection so account-scoped searches can find a\n+ // model before the user chooses a specific instance rail item.\n if (props.lockedProvider !== null) {\n return rankedMatches\n- .filter((rankedModel) => rankedModel.model.provider === props.lockedProvider)\n+ .filter((rankedModel) => matchesLockedProvider(rankedModel.model))\n .toSorted((a, b) => {\n const scoreDelta = a.score - b.score;\n if (scoreDelta !== 0) {\n@@ -188,72 +301,87 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {\n .map((rankedModel) => rankedModel.model);\n }\n \n- // Locked provider mode always shows that provider\'s models, with favorites first.\n if (props.lockedProvider !== null) {\n- result = result.filter((m) => m.provider === props.lockedProvider);\n- } else if (selectedProvider === "favorites") {\n- result = result.filter((m) => favoritesSet.has(`${m.provider}:${m.slug}`));\n+ result = result.filter((m) => matchesLockedProvider(m));\n+ if (showLockedInstanceSidebar) {\n+ result = result.filter((m) => m.instanceId === selectedInstanceId);\n+ }\n+ } else if (selectedInstanceId === "favorites") {\n+ result = result.filter((m) => favoritesSet.has(providerModelKey(m.instanceId, m.slug)));\n } else {\n- result = result.filter((m) => m.provider === selectedProvider);\n+ result = result.filter((m) => m.instanceId === selectedInstanceId);\n }\n \n- return result.toSorted((a, b) => {\n- const aOrder = favoriteOrder.get(`${a.provider}:${a.slug}`);\n- const bOrder = favoriteOrder.get(`${b.provider}:${b.slug}`);\n-\n- if (aOrder !== undefined && bOrder !== undefined) {\n- return aOrder - bOrder;\n- }\n- if (aOrder !== undefined) {\n- return -1;\n- }\n- if (bOrder !== undefined) {\n- return 1;\n- }\n- return 0;\n+ return sortProviderModelItems(result, {\n+ favoriteModelKeys: favoritesSet,\n+ groupFavorites: selectedInstanceId !== "favorites",\n+ instanceOrder: selectedInstanceId === "favorites" ? instanceOrder : [],\n });\n }, [\n- favoriteOrder,\n favoritesSet,\n flatModels,\n+ instanceOrder,\n+ matchesLockedProvider,\n props.lockedProvider,\n searchQuery,\n- selectedProvider,\n+ showLockedInstanceSidebar,\n+ selectedInstanceId,\n ]);\n \n const handleModelSelect = useCallback(\n- (modelSlug: string, provider: ProviderKind) => {\n- const resolvedModel = resolveSelectableModel(\n- provider,\n- modelSlug,\n- modelOptionsByProvider[provider],\n- );\n+ (modelSlug: string, instanceId: ProviderInstanceId) => {\n+ const options = modelOptionsByInstance.get(instanceId);\n+ if (!options) {\n+ return;\n+ }\n+ const entry = entryByInstanceId.get(instanceId);\n+ if (!entry) {\n+ return;\n+ }\n+ // `resolveSelectableModel` uses the driver kind for normalization\n+ // (slug casing etc.). Custom instances share their driver\'s\n+ // normalization rules, so pass the driver kind here.\n+ const resolvedModel = resolveSelectableModel(entry.driverKind, modelSlug, options);\n if (resolvedModel) {\n- onProviderModelChange(provider, resolvedModel);\n+ onInstanceModelChange(instanceId, resolvedModel);\n }\n },\n- [modelOptionsByProvider, onProviderModelChange],\n+ [entryByInstanceId, modelOptionsByInstance, onInstanceModelChange],\n );\n \n const toggleFavorite = useCallback(\n- (provider: ProviderKind, model: string) => {\n+ (instanceId: ProviderInstanceId, model: string) => {\n const newFavorites = [...favorites];\n- const index = newFavorites.findIndex((f) => f.provider === provider && f.model === model);\n+ const index = newFavorites.findIndex((f) => f.provider === instanceId && f.model === model);\n if (index >= 0) {\n newFavorites.splice(index, 1);\n } else {\n- newFavorites.push({ provider, model });\n+ newFavorites.push({ provider: instanceId, model });\n }\n updateSettings({ favorites: newFavorites });\n },\n [favorites, updateSettings],\n );\n \n- const isLocked = props.lockedProvider !== null;\n- const isSearching = searchQuery.trim().length > 0;\n- const showSidebar = !isLocked && !isSearching;\n const LockedProviderIcon =\n isLocked && props.lockedProvider ? PROVIDER_ICON_BY_PROVIDER[props.lockedProvider] : null;\n+ // Header label for locked mode. Use the active instance\'s displayName\n+ // when the lock narrows to exactly one instance (so "Codex Personal"\n+ // shows instead of the generic driver label); fall back to the first\n+ // matching entry otherwise.\n+ const lockedHeaderLabel = useMemo(() => {\n+ if (!isLocked || !props.lockedProvider) return null;\n+ const matches = instanceEntries.filter((entry) => matchesLockedProvider(entry));\n+ if (matches.length === 0) return null;\n+ const active = matches.find((entry) => entry.instanceId === props.activeInstanceId);\n+ return (active ?? matches[0])?.displayName ?? null;\n+ }, [\n+ isLocked,\n+ matchesLockedProvider,\n+ props.lockedProvider,\n+ props.activeInstanceId,\n+ instanceEntries,\n+ ]);\n const modelJumpCommandByKey = useMemo(() => {\n const mapping = new Map<\n string,\n@@ -264,7 +392,7 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {\n if (!jumpCommand) {\n return mapping;\n }\n- mapping.set(`${model.provider}:${model.slug}`, jumpCommand);\n+ mapping.set(`${model.instanceId}:${model.slug}`, jumpCommand);\n }\n return mapping;\n }, [filteredModels]);\n@@ -273,16 +401,16 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {\n [modelJumpCommandByKey],\n );\n const allModelKeys = useMemo(\n- (): string[] => flatModels.map((model) => `${model.provider}:${model.slug}`),\n+ (): string[] => flatModels.map((model) => `${model.instanceId}:${model.slug}`),\n [flatModels],\n );\n const filteredModelKeys = useMemo(\n- (): string[] => filteredModels.map((model) => `${model.provider}:${model.slug}`),\n+ (): string[] => filteredModels.map((model) => `${model.instanceId}:${model.slug}`),\n [filteredModels],\n );\n const filteredModelByKey = useMemo(\n (): ReadonlyMap<string, ModelPickerItem> =>\n- new Map(filteredModels.map((model) => [`${model.provider}:${model.slug}`, model] as const)),\n+ new Map(filteredModels.map((model) => [`${model.instanceId}:${model.slug}`, model] as const)),\n [filteredModels],\n );\n const modelJumpShortcutContext = useMemo(\n@@ -331,10 +459,10 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {\n if (!targetModelKey) {\n return;\n }\n- const [provider, slug] = targetModelKey.split(":") as [ProviderKind, string];\n+ const { instanceId, slug } = splitInstanceModelKey(targetModelKey);\n event.preventDefault();\n event.stopPropagation();\n- handleModelSelect(slug, provider);\n+ handleModelSelect(slug, instanceId);\n };\n \n window.addEventListener("keydown", onWindowKeyDown, true);\n@@ -392,25 +520,25 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {\n <div\n className={cn(\n "relative flex h-screen max-h-96 w-screen max-w-100 overflow-hidden rounded-lg border bg-popover not-dark:bg-clip-padding text-popover-foreground shadow-lg/5 before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--radius-lg)-1px)] before:shadow-[0_1px_--theme(--color-black/4%)] dark:before:shadow-[0_-1px_--theme(--color-white/6%)]",\n- isLocked ? "flex-col" : "flex-row",\n+ isLocked && !showLockedInstanceSidebar ? "flex-col" : "flex-row",\n )}\n >\n {/* Locked provider header (only shown in locked mode) */}\n- {isLocked && LockedProviderIcon && props.lockedProvider && (\n+ {isLocked && !showLockedInstanceSidebar && LockedProviderIcon && lockedHeaderLabel && (\n <div className="flex items-center gap-2 px-4 py-3 border-b">\n <LockedProviderIcon className="size-5 shrink-0" />\n- <span className="font-medium text-sm">\n- {PROVIDER_DISPLAY_NAMES[props.lockedProvider]}\n- </span>\n+ <span className="font-medium text-sm">{lockedHeaderLabel}</span>\n </div>\n )}\n \n {/* Sidebar (only in unlocked mode) */}\n {showSidebar && (\n <ModelPickerSidebar\n- selectedProvider={selectedProvider}\n- onSelectProvider={handleSelectProvider}\n- {...(props.providers && { providers: props.providers })}\n+ selectedInstanceId={selectedInstanceId}\n+ onSelectInstance={handleSelectInstance}\n+ instanceEntries={sidebarInstanceEntries}\n+ showFavorites={!isLocked}\n+ showComingSoon={!isLocked}\n />\n )}\n \n@@ -422,7 +550,7 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {\n filter={null}\n autoHighlight\n open\n- value={`${props.provider}:${props.model}`}\n+ value={`${props.activeInstanceId}:${props.model}`}\n onItemHighlighted={(modelKey) => {\n highlightedModelKeyRef.current = typeof modelKey === "string" ? modelKey : null;\n }}\n@@ -430,14 +558,14 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {\n if (typeof modelKey !== "string") {\n return;\n }\n- const [provider, slug] = modelKey.split(":") as [ProviderKind, string];\n- handleModelSelect(slug, provider);\n+ const { instanceId, slug } = splitInstanceModelKey(modelKey);\n+ handleModelSelect(slug, instanceId);\n }}\n >\n <div\n className={cn(\n "flex min-h-0 flex-1 flex-col overflow-hidden",\n- isLocked ? "min-w-0" : showSidebar && "border-l",\n+ isLocked && !showLockedInstanceSidebar ? "min-w-0" : showSidebar && "border-l",\n )}\n >\n {/* Search bar */}\n@@ -464,11 +592,10 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {\n ).preventBaseUIHandler?.();\n e.preventDefault();\n e.stopPropagation();\n- const [provider, slug] = highlightedModelKeyRef.current.split(":") as [\n- ProviderKind,\n- string,\n- ];\n- handleModelSelect(slug, provider);\n+ const { instanceId, slug } = splitInstanceModelKey(\n+ highlightedModelKeyRef.current,\n+ );\n+ handleModelSelect(slug, instanceId);\n return;\n }\n e.stopPropagation();\n@@ -495,14 +622,17 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {\n key={modelKey}\n index={index}\n model={model}\n- provider={model.provider}\n+ instanceId={model.instanceId}\n+ driverKind={model.driverKind}\n+ providerDisplayName={model.instanceDisplayName}\n+ providerAccentColor={model.instanceAccentColor}\n isFavorite={favoritesSet.has(modelKey)}\n- showProvider={!isLocked}\n+ showProvider={!isLocked || showLockedInstanceSidebar}\n preferShortName={!isLocked}\n- useTriggerLabel={isLocked}\n- showNewBadge={isModelPickerNewModel(model.provider, model.slug)}\n+ useTriggerLabel={isLocked && !showLockedInstanceSidebar}\n+ showNewBadge={isModelPickerNewModel(model.driverKind, model.slug)}\n jumpLabel={modelJumpLabelByKey.get(modelKey) ?? null}\n- onToggleFavorite={() => toggleFavorite(model.provider, model.slug)}\n+ onToggleFavorite={() => toggleFavorite(model.instanceId, model.slug)}\n />\n );\n })}\ndiff --git a/apps/web/src/components/chat/ModelPickerSidebar.tsx b/apps/web/src/components/chat/ModelPickerSidebar.tsx\nindex b4f23cacdd..121b5267a3 100644\n--- a/apps/web/src/components/chat/ModelPickerSidebar.tsx\n+++ b/apps/web/src/components/chat/ModelPickerSidebar.tsx\n@@ -1,28 +1,32 @@\n-import { type ProviderKind, type ServerProvider } from "@t3tools/contracts";\n-import { memo } from "react";\n+import { type ProviderInstanceId } from "@t3tools/contracts";\n+import { memo, useMemo } from "react";\n import { Clock3Icon, SparklesIcon, StarIcon } from "lucide-react";\n import { Gemini, GithubCopilotIcon } from "../Icons";\n-import { AVAILABLE_PROVIDER_OPTIONS, PROVIDER_ICON_BY_PROVIDER } from "./providerIconUtils";\n+import { ProviderInstanceIcon } from "./ProviderInstanceIcon";\n+import { ScrollArea } from "../ui/scroll-area";\n import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";\n import { cn } from "~/lib/utils";\n-import { getProviderSnapshot } from "../../providerModels";\n+import type { ProviderInstanceEntry } from "../../providerInstances";\n \n-function describeUnavailableProvider(label: string, live: ServerProvider | undefined): string {\n- if (!live) {\n- return `${label} — waiting for provider status…`;\n- }\n- if (live.status === "ready") {\n+/**\n+ * Build the hover tooltip for an instance button. Mirrors the old\n+ * kind-based copy but uses the entry\'s configured `displayName` so custom\n+ * instances get their user-authored name (e.g. "Codex Personal — Unavailable.").\n+ */\n+function describeUnavailableInstance(entry: ProviderInstanceEntry): string {\n+ const label = entry.displayName;\n+ if (entry.status === "ready") {\n return label;\n }\n const kind =\n- live.status === "error"\n+ entry.status === "error"\n ? "Unavailable"\n- : live.status === "warning"\n+ : entry.status === "warning"\n ? "Limited"\n- : live.status === "disabled"\n+ : entry.status === "disabled"\n ? "Disabled in settings"\n : "Not ready";\n- const msg = live.message?.trim();\n+ const msg = entry.snapshot.message?.trim();\n return msg ? `${label} — ${kind}. ${msg}` : `${label} — ${kind}.`;\n }\n \n@@ -39,172 +43,221 @@ const PICKER_TOOLTIP_SIDE = "left" as const;\n const PICKER_TOOLTIP_CLASS = "max-w-64 text-balance font-normal leading-snug";\n \n export const ModelPickerSidebar = memo(function ModelPickerSidebar(props: {\n- selectedProvider: ProviderKind | "favorites";\n- onSelectProvider: (provider: ProviderKind | "favorites") => void;\n- providers?: ReadonlyArray<ServerProvider>;\n+ selectedInstanceId: ProviderInstanceId | "favorites";\n+ onSelectInstance: (instanceId: ProviderInstanceId | "favorites") => void;\n+ /**\n+ * Instance entries to render as rail buttons. Each entry becomes one icon\n+ * keyed by `instanceId`, so the default built-in Codex and a user-authored\n+ * `codex_personal` appear as two distinct rail items, each routing to\n+ * their own model list.\n+ */\n+ instanceEntries: ReadonlyArray<ProviderInstanceEntry>;\n+ /** Render the favorites rail entry. Hidden for locked-provider instance switching. */\n+ showFavorites?: boolean;\n+ /** Render non-configured coming-soon provider entries. Hidden in scoped rails. */\n+ showComingSoon?: boolean;\n+ /**\n+ * Instance id values that should render the "new" sparkle badge. Callers\n+ * pass the subset of default built-in ids they want flagged (custom\n+ * instances are never flagged — the user just made them).\n+ */\n+ newBadgeInstanceIds?: ReadonlySet<ProviderInstanceId>;\n }) {\n- const handleProviderClick = (provider: ProviderKind | "favorites") => {\n- props.onSelectProvider(provider);\n+ const handleSelect = (instanceId: ProviderInstanceId | "favorites") => {\n+ props.onSelectInstance(instanceId);\n };\n+ const showFavorites = props.showFavorites ?? true;\n+ const showComingSoon = props.showComingSoon ?? true;\n+ const duplicateDriverCounts = useMemo(() => {\n+ const counts = new Map<string, number>();\n+ for (const entry of props.instanceEntries) {\n+ counts.set(entry.driverKind, (counts.get(entry.driverKind) ?? 0) + 1);\n+ }\n+ return counts;\n+ }, [props.instanceEntries]);\n \n return (\n- <div className="flex flex-col w-12 border-r bg-muted/30 p-1 overflow-y-auto gap-1">\n- {/* Favorites section */}\n- <div className="pb-1 mb-1 border-b">\n- <div className="relative w-full">\n- {props.selectedProvider === "favorites" && <div className={SELECTED_INDICATOR_CLASS} />}\n- <Tooltip>\n- <TooltipTrigger\n- render={\n- <button\n- className={cn(\n- "relative isolate flex w-full cursor-pointer aspect-square items-center justify-center rounded transition-colors hover:bg-muted",\n- props.selectedProvider === "favorites" && SELECTED_BUTTON_CLASS,\n- )}\n- onClick={() => handleProviderClick("favorites")}\n- type="button"\n- data-model-picker-provider="favorites"\n- aria-label="Favorites"\n+ <ScrollArea\n+ hideScrollbars\n+ scrollFade\n+ className="w-12 shrink-0 border-r bg-muted/30"\n+ data-model-picker-sidebar="true"\n+ >\n+ <div className="flex min-h-full flex-col gap-1 p-1">\n+ {/* Favorites section */}\n+ {showFavorites ? (\n+ <div className="pb-1 mb-1 border-b">\n+ <div className="relative w-full">\n+ {props.selectedInstanceId === "favorites" && (\n+ <div className={SELECTED_INDICATOR_CLASS} />\n+ )}\n+ <Tooltip>\n+ <TooltipTrigger\n+ render={\n+ <button\n+ className={cn(\n+ "relative isolate flex w-full cursor-pointer aspect-square items-center justify-center rounded transition-colors hover:bg-muted",\n+ props.selectedInstanceId === "favorites" && SELECTED_BUTTON_CLASS,\n+ )}\n+ onClick={() => handleSelect("favorites")}\n+ type="button"\n+ data-model-picker-provider="favorites"\n+ aria-label="Favorites"\n+ >\n+ <StarIcon className="size-5 fill-current shrink-0" aria-hidden />\n+ </button>\n+ }\n+ />\n+ <TooltipPopup\n+ side={PICKER_TOOLTIP_SIDE}\n+ align="center"\n+ className={PICKER_TOOLTIP_CLASS}\n >\n- <StarIcon className="size-5 fill-current shrink-0" aria-hidden />\n- </button>\n- }\n- />\n- <TooltipPopup\n- side={PICKER_TOOLTIP_SIDE}\n- align="center"\n- className={PICKER_TOOLTIP_CLASS}\n- >\n- Favorites\n- </TooltipPopup>\n- </Tooltip>\n- </div>\n- </div>\n+ Favorites\n+ </TooltipPopup>\n+ </Tooltip>\n+ </div>\n+ </div>\n+ ) : null}\n \n- {/* Provider buttons */}\n- {AVAILABLE_PROVIDER_OPTIONS.map((option) => {\n- const OptionIcon = PROVIDER_ICON_BY_PROVIDER[option.value];\n- const liveProvider = props.providers\n- ? getProviderSnapshot(props.providers, option.value)\n- : undefined;\n+ {/* Instance buttons (one per configured instance — built-in + custom) */}\n+ {props.instanceEntries.map((entry) => {\n+ const isDisabled = !entry.isAvailable || entry.status !== "ready";\n+ const isSelected = props.selectedInstanceId === entry.instanceId;\n+ const showNewBadge = props.newBadgeInstanceIds?.has(entry.instanceId) ?? false;\n+ const showInstanceBadge =\n+ Boolean(entry.accentColor) || (duplicateDriverCounts.get(entry.driverKind) ?? 0) > 1;\n \n- const isDisabled = !liveProvider || liveProvider.status !== "ready";\n- const isSelected = props.selectedProvider === option.value;\n- const badge = option.pickerSidebarBadge;\n+ const tooltip = isDisabled\n+ ? describeUnavailableInstance(entry)\n+ : showNewBadge\n+ ? `${entry.displayName} — New`\n+ : entry.displayName;\n \n- const providerTooltip = isDisabled\n- ? describeUnavailableProvider(option.label, liveProvider)\n- : badge === "new"\n- ? `${option.label} — New`\n- : option.label;\n+ const button = (\n+ <button\n+ data-model-picker-provider={entry.instanceId}\n+ className={cn(\n+ "relative isolate flex w-full cursor-pointer aspect-square items-center justify-center rounded transition-colors hover:bg-muted",\n+ isSelected && SELECTED_BUTTON_CLASS,\n+ isDisabled && "opacity-50 cursor-not-allowed hover:bg-transparent",\n+ )}\n+ data-provider-accent-color={entry.accentColor}\n+ onClick={() => !isDisabled && handleSelect(entry.instanceId)}\n+ disabled={isDisabled}\n+ type="button"\n+ aria-label={\n+ isDisabled\n+ ? tooltip\n+ : showNewBadge\n+ ? `${entry.displayName}, new`\n+ : entry.displayName\n+ }\n+ >\n+ <ProviderInstanceIcon\n+ driverKind={entry.driverKind}\n+ displayName={entry.displayName}\n+ accentColor={entry.accentColor}\n+ showBadge={showInstanceBadge}\n+ className="size-6"\n+ iconClassName="size-5"\n+ />\n+ {showNewBadge ? (\n+ <span className={NEW_BADGE_CLASS} aria-hidden>\n+ <SparklesIcon className="size-2" />\n+ </span>\n+ ) : null}\n+ </button>\n+ );\n \n- const button = (\n- <button\n- data-model-picker-provider={option.value}\n- className={cn(\n- "relative isolate flex w-full cursor-pointer aspect-square items-center justify-center rounded transition-colors hover:bg-muted",\n- isSelected && SELECTED_BUTTON_CLASS,\n- isDisabled && "opacity-50 cursor-not-allowed hover:bg-transparent",\n- )}\n- onClick={() => !isDisabled && handleProviderClick(option.value)}\n- disabled={isDisabled}\n- type="button"\n- aria-label={\n- isDisabled\n- ? (providerTooltip ?? option.label)\n- : badge === "new"\n- ? `${option.label}, new`\n- : option.label\n- }\n- >\n- <OptionIcon className="size-5 shrink-0" aria-hidden />\n- {badge === "new" ? (\n- <span className={NEW_BADGE_CLASS} aria-hidden>\n- <SparklesIcon className="size-2" />\n- </span>\n- ) : badge === "soon" ? (\n- <span className={SOON_BADGE_CLASS} aria-hidden>\n- <Clock3Icon className="size-2" />\n- </span>\n- ) : null}\n- </button>\n- );\n+ const trigger = isDisabled ? (\n+ <span className="relative block w-full">{button}</span>\n+ ) : (\n+ button\n+ );\n \n- const trigger = isDisabled ? (\n- <span className="relative block w-full">{button}</span>\n- ) : (\n- button\n- );\n+ return (\n+ <div key={entry.instanceId} className="relative w-full">\n+ {isSelected && <div className={SELECTED_INDICATOR_CLASS} />}\n+ <Tooltip>\n+ <TooltipTrigger render={trigger} />\n+ <TooltipPopup\n+ side={PICKER_TOOLTIP_SIDE}\n+ align="center"\n+ className={PICKER_TOOLTIP_CLASS}\n+ >\n+ {tooltip}\n+ </TooltipPopup>\n+ </Tooltip>\n+ </div>\n+ );\n+ })}\n \n- return (\n- <div key={option.value} className="relative w-full">\n- {isSelected && <div className={SELECTED_INDICATOR_CLASS} />}\n+ {showComingSoon ? (\n+ <>\n+ {/* Gemini button (coming soon) */}\n <Tooltip>\n- <TooltipTrigger render={trigger} />\n+ <TooltipTrigger\n+ render={\n+ <span className="relative block w-full">\n+ <button\n+ className={cn(\n+ "relative isolate flex w-full aspect-square items-center justify-center rounded opacity-50 cursor-not-allowed transition-colors hover:bg-transparent",\n+ )}\n+ disabled\n+ type="button"\n+ data-model-picker-provider="gemini-coming-soon"\n+ aria-label="Gemini — coming soon"\n+ >\n+ <Gemini className="size-5 text-muted-foreground/85" aria-hidden />\n+ <span className={SOON_BADGE_CLASS} aria-hidden>\n+ <Clock3Icon className="size-2" />\n+ </span>\n+ </button>\n+ </span>\n+ }\n+ />\n <TooltipPopup\n side={PICKER_TOOLTIP_SIDE}\n align="center"\n className={PICKER_TOOLTIP_CLASS}\n >\n- {providerTooltip}\n+ Gemini — Coming soon\n </TooltipPopup>\n </Tooltip>\n- </div>\n- );\n- })}\n-\n- {/* Gemini button (coming soon) */}\n- <Tooltip>\n- <TooltipTrigger\n- render={\n- <span className="relative block w-full">\n- <button\n- className={cn(\n- "relative isolate flex w-full aspect-square items-center justify-center rounded opacity-50 cursor-not-allowed transition-colors hover:bg-transparent",\n- )}\n- disabled\n- type="button"\n- data-model-picker-provider="gemini-coming-soon"\n- aria-label="Gemini — coming soon"\n- >\n- <Gemini className="size-5 text-muted-foreground/85" aria-hidden />\n- <span className={SOON_BADGE_CLASS} aria-hidden>\n- <Clock3Icon className="size-2" />\n- </span>\n- </button>\n- </span>\n- }\n- />\n- <TooltipPopup side={PICKER_TOOLTIP_SIDE} align="center" className={PICKER_TOOLTIP_CLASS}>\n- Gemini — Coming soon\n- </TooltipPopup>\n- </Tooltip>\n- {/* Github Copilot button (coming soon) */}\n- <Tooltip>\n- <TooltipTrigger\n- render={\n- <span className="relative block w-full">\n- <button\n- className={cn(\n- "relative isolate flex w-full aspect-square items-center justify-center rounded opacity-50 cursor-not-allowed transition-colors hover:bg-transparent",\n- )}\n- disabled\n- type="button"\n- data-model-picker-provider="github-copilot-coming-soon"\n- aria-label="Github Copilot — coming soon"\n+ {/* Github Copilot button (coming soon) */}\n+ <Tooltip>\n+ <TooltipTrigger\n+ render={\n+ <span className="relative block w-full">\n+ <button\n+ className={cn(\n+ "relative isolate flex w-full aspect-square items-center justify-center rounded opacity-50 cursor-not-allowed transition-colors hover:bg-transparent",\n+ )}\n+ disabled\n+ type="button"\n+ data-model-picker-provider="github-copilot-coming-soon"\n+ aria-label="Github Copilot — coming soon"\n+ >\n+ <GithubCopilotIcon className="size-5 text-muted-foreground/85" aria-hidden />\n+ <span className={SOON_BADGE_CLASS} aria-hidden>\n+ <Clock3Icon className="size-2" />\n+ </span>\n+ </button>\n+ </span>\n+ }\n+ />\n+ <TooltipPopup\n+ side={PICKER_TOOLTIP_SIDE}\n+ align="center"\n+ className={PICKER_TOOLTIP_CLASS}\n >\n- <GithubCopilotIcon className="size-5 text-muted-foreground/85" aria-hidden />\n- <span className={SOON_BADGE_CLASS} aria-hidden>\n- <Clock3Icon className="size-2" />\n- </span>\n- </button>\n- </span>\n- }\n- />\n- <TooltipPopup side={PICKER_TOOLTIP_SIDE} align="center" className={PICKER_TOOLTIP_CLASS}>\n- Github Copilot — Coming soon\n- </TooltipPopup>\n- </Tooltip>\n- </div>\n+ Github Copilot — Coming soon\n+ </TooltipPopup>\n+ </Tooltip>\n+ </>\n+ ) : null}\n+ </div>\n+ </ScrollArea>\n );\n });\ndiff --git a/apps/web/src/components/chat/ProviderInstanceIcon.tsx b/apps/web/src/components/chat/ProviderInstanceIcon.tsx\nnew file mode 100644\nindex 0000000000..154cada19a\n--- /dev/null\n+++ b/apps/web/src/components/chat/ProviderInstanceIcon.tsx\n@@ -0,0 +1,73 @@\n+import { type CSSProperties, memo } from "react";\n+import { type ProviderDriverKind } from "@t3tools/contracts";\n+\n+import { PROVIDER_ICON_BY_PROVIDER } from "./providerIconUtils";\n+import { cn } from "~/lib/utils";\n+\n+export function providerInstanceInitials(label: string): string {\n+ const words = label.replace(/[_-]+/g, " ").split(/\\s+/u).filter(Boolean);\n+ if (words.length === 0) return "";\n+ if (words.length === 1) return words[0]!.slice(0, 2).toUpperCase();\n+ return words\n+ .slice(0, 2)\n+ .map((word) => word[0]?.toUpperCase() ?? "")\n+ .join("");\n+}\n+\n+export const ProviderInstanceIcon = memo(function ProviderInstanceIcon(props: {\n+ driverKind: ProviderDriverKind;\n+ displayName: string;\n+ accentColor?: string | undefined;\n+ showBadge?: boolean;\n+ className?: string;\n+ iconClassName?: string;\n+ badgeClassName?: string;\n+ statusDotClassName?: string;\n+}) {\n+ const Icon = PROVIDER_ICON_BY_PROVIDER[props.driverKind] ?? null;\n+ const accentStyle = props.accentColor\n+ ? ({ "--provider-accent": props.accentColor } as CSSProperties)\n+ : undefined;\n+\n+ return (\n+ <span\n+ className={cn(\n+ "relative isolate inline-flex shrink-0 items-center justify-center",\n+ props.className,\n+ )}\n+ style={accentStyle}\n+ data-provider-accent-color={props.accentColor}\n+ >\n+ {Icon ? (\n+ <Icon className={cn("size-5 shrink-0", props.iconClassName)} aria-hidden />\n+ ) : (\n+ <span className={cn("text-[10px] font-semibold leading-none", props.iconClassName)}>\n+ {providerInstanceInitials(props.displayName)}\n+ </span>\n+ )}\n+ {props.statusDotClassName ? (\n+ <span\n+ className={cn(\n+ "pointer-events-none absolute -left-0.5 -top-0.5 size-2 rounded-full ring-2 ring-background",\n+ props.statusDotClassName,\n+ )}\n+ aria-hidden\n+ />\n+ ) : null}\n+ {props.showBadge ? (\n+ <span\n+ className={cn(\n+ "pointer-events-none absolute right-0 bottom-0 flex h-3.5 min-w-3.5 items-center justify-center rounded-full border border-background px-0.5 text-[8px] font-semibold leading-none shadow-sm",\n+ props.accentColor\n+ ? "bg-[var(--provider-accent)] text-white"\n+ : "bg-muted text-muted-foreground",\n+ props.badgeClassName,\n+ )}\n+ aria-hidden\n+ >\n+ {providerInstanceInitials(props.displayName)}\n+ </span>\n+ ) : null}\n+ </span>\n+ );\n+});\ndiff --git a/apps/web/src/components/chat/ProviderModelPicker.browser.tsx b/apps/web/src/components/chat/ProviderModelPicker.browser.tsx\nindex a5f539ae5a..d3b168876a 100644\n--- a/apps/web/src/components/chat/ProviderModelPicker.browser.tsx\n+++ b/apps/web/src/components/chat/ProviderModelPicker.browser.tsx\n@@ -1,4 +1,4 @@\n-import { type ProviderKind, type ServerProvider } from "@t3tools/contracts";\n+import { ProviderDriverKind, ProviderInstanceId, type ServerProvider } from "@t3tools/contracts";\n import { EnvironmentId } from "@t3tools/contracts";\n import { createModelCapabilities } from "@t3tools/shared/model";\n import { page, userEvent } from "vitest/browser";\n@@ -6,8 +6,17 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";\n import { render } from "vitest-browser-react";\n \n import { ProviderModelPicker } from "./ProviderModelPicker";\n-import { getCustomModelOptionsByProvider } from "../../modelSelection";\n-import { DEFAULT_CLIENT_SETTINGS, DEFAULT_UNIFIED_SETTINGS } from "@t3tools/contracts/settings";\n+import { getCustomModelOptionsByInstance } from "../../modelSelection";\n+import {\n+ deriveProviderInstanceEntries,\n+ sortProviderInstanceEntries,\n+} from "../../providerInstances";\n+import type { ModelEsque } from "./providerIconUtils";\n+import {\n+ DEFAULT_CLIENT_SETTINGS,\n+ DEFAULT_UNIFIED_SETTINGS,\n+ type UnifiedSettings,\n+} from "@t3tools/contracts/settings";\n import { __resetLocalApiForTests } from "../../localApi";\n \n // Mock the environments/runtime module to provide a mock primary environment connection\n@@ -93,7 +102,8 @@ function booleanDescriptor(id: string, label: string) {\n \n const TEST_PROVIDERS: ReadonlyArray<ServerProvider> = [\n {\n- provider: "codex",\n+ driver: ProviderDriverKind.make("codex"),\n+ instanceId: ProviderInstanceId.make("codex"),\n displayName: "Codex",\n enabled: true,\n installed: true,\n@@ -137,7 +147,8 @@ const TEST_PROVIDERS: ReadonlyArray<ServerProvider> = [\n ],\n },\n {\n- provider: "claudeAgent",\n+ driver: ProviderDriverKind.make("claudeAgent"),\n+ instanceId: ProviderInstanceId.make("claudeAgent"),\n displayName: "Claude",\n enabled: true,\n installed: true,\n@@ -199,9 +210,14 @@ const TEST_PROVIDERS: ReadonlyArray<ServerProvider> = [\n },\n ];\n \n+const CODEX_INSTANCE_ID = ProviderInstanceId.make("codex");\n+const CLAUDE_INSTANCE_ID = ProviderInstanceId.make("claudeAgent");\n+const OPENCODE_INSTANCE_ID = ProviderInstanceId.make("opencode");\n+\n function buildCodexProvider(models: ServerProvider["models"]): ServerProvider {\n return {\n- provider: "codex",\n+ driver: ProviderDriverKind.make("codex"),\n+ instanceId: ProviderInstanceId.make("codex"),\n displayName: "Codex",\n enabled: true,\n installed: true,\n@@ -217,7 +233,8 @@ function buildCodexProvider(models: ServerProvider["models"]): ServerProvider {\n \n function buildOpenCodeProvider(models: ServerProvider["models"]): ServerProvider {\n return {\n- provider: "opencode",\n+ driver: ProviderDriverKind.make("opencode"),\n+ instanceId: ProviderInstanceId.make("opencode"),\n enabled: true,\n installed: true,\n version: "1.0.0",\n@@ -231,37 +248,47 @@ function buildOpenCodeProvider(models: ServerProvider["models"]): ServerProvider\n }\n \n async function mountPicker(props: {\n- provider: ProviderKind;\n+ activeInstanceId?: ProviderInstanceId;\n model: string;\n- lockedProvider: ProviderKind | null;\n+ lockedProvider: ProviderDriverKind | null;\n+ lockedContinuationGroupKey?: string | null;\n providers?: ReadonlyArray<ServerProvider>;\n+ settings?: UnifiedSettings;\n triggerVariant?: "ghost" | "outline";\n }) {\n const host = document.createElement("div");\n document.body.append(host);\n- const onProviderModelChange = vi.fn();\n+ const onInstanceModelChange = vi.fn();\n const providers = props.providers ?? TEST_PROVIDERS;\n- const modelOptionsByProvider = getCustomModelOptionsByProvider(\n- DEFAULT_UNIFIED_SETTINGS,\n+ const instanceEntries = sortProviderInstanceEntries(deriveProviderInstanceEntries(providers));\n+ const activeInstanceId = props.activeInstanceId ?? CODEX_INSTANCE_ID;\n+ const modelOptionsByInstance = getCustomModelOptionsByInstance(\n+ props.settings ?? DEFAULT_UNIFIED_SETTINGS,\n providers,\n- props.provider,\n+ activeInstanceId,\n props.model,\n );\n const screen = await render(\n <ProviderModelPicker\n- provider={props.provider}\n+ activeInstanceId={activeInstanceId}\n model={props.model}\n lockedProvider={props.lockedProvider}\n- providers={providers}\n- modelOptionsByProvider={modelOptionsByProvider}\n+ lockedContinuationGroupKey={props.lockedContinuationGroupKey ?? null}\n+ instanceEntries={instanceEntries}\n+ modelOptionsByInstance={modelOptionsByInstance}\n triggerVariant={props.triggerVariant}\n- onProviderModelChange={onProviderModelChange}\n+ onInstanceModelChange={onInstanceModelChange}\n />,\n { container: host },\n );\n \n return {\n- onProviderModelChange,\n+ onInstanceModelChange,\n+ // Back-compat alias used by callers that still assert on the old callback\n+ // name. Delegates to the instance-aware mock so existing expectations work.\n+ get onProviderModelChange() {\n+ return onInstanceModelChange;\n+ },\n cleanup: async () => {\n await screen.unmount();\n host.remove();\n@@ -304,7 +331,7 @@ describe("ProviderModelPicker", () => {\n \n it("shows provider sidebar in unlocked mode", async () => {\n const mounted = await mountPicker({\n- provider: "claudeAgent",\n+ activeInstanceId: CLAUDE_INSTANCE_ID,\n model: "claude-opus-4-6",\n lockedProvider: null,\n });\n@@ -325,7 +352,7 @@ describe("ProviderModelPicker", () => {\n \n it("shows favorites first in the provider sidebar", async () => {\n const mounted = await mountPicker({\n- provider: "claudeAgent",\n+ activeInstanceId: CLAUDE_INSTANCE_ID,\n model: "claude-opus-4-6",\n lockedProvider: null,\n });\n@@ -347,7 +374,7 @@ describe("ProviderModelPicker", () => {\n \n it("filters models by selected provider in sidebar", async () => {\n const mounted = await mountPicker({\n- provider: "claudeAgent",\n+ activeInstanceId: CLAUDE_INSTANCE_ID,\n model: "claude-opus-4-6",\n lockedProvider: null,\n });\n@@ -379,9 +406,37 @@ describe("ProviderModelPicker", () => {\n }\n });\n \n+ it("uses client model visibility and ordering preferences", async () => {\n+ const mounted = await mountPicker({\n+ activeInstanceId: CLAUDE_INSTANCE_ID,\n+ model: "claude-opus-4-6",\n+ lockedProvider: null,\n+ settings: {\n+ ...DEFAULT_UNIFIED_SETTINGS,\n+ providerModelPreferences: {\n+ [CLAUDE_INSTANCE_ID]: {\n+ hiddenModels: ["claude-opus-4-6"],\n+ modelOrder: ["claude-haiku-4-5", "claude-sonnet-4-6"],\n+ },\n+ },\n+ },\n+ });\n+\n+ try {\n+ await page.getByRole("button").click();\n+\n+ await vi.waitFor(() => {\n+ expect(getVisibleModelNames()).toEqual(["Claude Haiku 4.5", "Claude Sonnet 4.6"]);\n+ expect(getModelPickerListText()).not.toContain("Claude Opus 4.6");\n+ });\n+ } finally {\n+ await mounted.cleanup();\n+ }\n+ });\n+\n it("focuses the search input after selecting a sidebar provider", async () => {\n const mounted = await mountPicker({\n- provider: "claudeAgent",\n+ activeInstanceId: CLAUDE_INSTANCE_ID,\n model: "claude-opus-4-6",\n lockedProvider: null,\n });\n@@ -419,9 +474,9 @@ describe("ProviderModelPicker", () => {\n );\n \n const mounted = await mountPicker({\n- provider: "claudeAgent",\n+ activeInstanceId: CLAUDE_INSTANCE_ID,\n model: "claude-opus-4-6",\n- lockedProvider: "claudeAgent",\n+ lockedProvider: ProviderDriverKind.make("claudeAgent"),\n });\n \n try {\n@@ -443,27 +498,115 @@ describe("ProviderModelPicker", () => {\n }\n });\n \n+ it("keeps an instance sidebar in locked mode when that provider has multiple instances", async () => {\n+ const defaultCodexModels: ServerProvider["models"] = [\n+ {\n+ slug: "gpt-work",\n+ name: "GPT Work",\n+ isCustom: false,\n+ capabilities: createModelCapabilities({ optionDescriptors: [] }),\n+ },\n+ ];\n+ const personalCodexModels: ServerProvider["models"] = [\n+ {\n+ slug: "gpt-personal",\n+ name: "GPT Personal",\n+ isCustom: false,\n+ capabilities: createModelCapabilities({ optionDescriptors: [] }),\n+ },\n+ ];\n+ const isolatedCodexModels: ServerProvider["models"] = [\n+ {\n+ slug: "gpt-isolated",\n+ name: "GPT Isolated",\n+ isCustom: false,\n+ capabilities: createModelCapabilities({ optionDescriptors: [] }),\n+ },\n+ ];\n+ const providers: ReadonlyArray<ServerProvider> = [\n+ {\n+ ...buildCodexProvider(defaultCodexModels),\n+ instanceId: "codex" as ProviderInstanceId,\n+ displayName: "Codex Work",\n+ accentColor: "#2563eb",\n+ continuation: { groupKey: "codex:home:/Users/julius/.codex" },\n+ },\n+ {\n+ ...buildCodexProvider(personalCodexModels),\n+ instanceId: "codex_personal" as ProviderInstanceId,\n+ displayName: "Codex Personal",\n+ accentColor: "#dc2626",\n+ continuation: { groupKey: "codex:home:/Users/julius/.codex" },\n+ },\n+ {\n+ ...buildCodexProvider(isolatedCodexModels),\n+ instanceId: "codex_isolated" as ProviderInstanceId,\n+ displayName: "Codex Isolated",\n+ accentColor: "#16a34a",\n+ continuation: { groupKey: "codex:home:/Users/julius/.codex_isolated" },\n+ },\n+ TEST_PROVIDERS[1]!,\n+ ];\n+ const mounted = await mountPicker({\n+ activeInstanceId: "codex" as ProviderInstanceId,\n+ model: "gpt-work",\n+ lockedProvider: ProviderDriverKind.make("codex"),\n+ lockedContinuationGroupKey: "codex:home:/Users/julius/.codex",\n+ providers,\n+ });\n+\n+ try {\n+ await page.getByRole("button").click();\n+\n+ await vi.waitFor(() => {\n+ expect(getSidebarProviderOrder()).toEqual(["codex", "codex_personal"]);\n+ expect(getModelPickerListText()).not.toContain("Codex Isolated");\n+ expect(\n+ document.querySelector<HTMLElement>(\'[data-model-picker-provider="codex_personal"]\')\n+ ?.dataset.providerAccentColor,\n+ ).toBe("#dc2626");\n+ expect(getModelPickerListText()).toContain("Codex Work");\n+ expect(getVisibleModelNames()).toEqual(["GPT Work"]);\n+ });\n+\n+ await page.getByRole("button", { name: "Codex Personal" }).click();\n+\n+ await vi.waitFor(() => {\n+ expect(getModelPickerListText()).toContain("Codex Personal");\n+ expect(getVisibleModelNames()).toEqual(["GPT Personal"]);\n+ });\n+ } finally {\n+ await mounted.cleanup();\n+ }\n+ });\n+\n it("falls back to the active provider\'s first model when props.model belongs to another provider (#1982)", async () => {\n const host = document.createElement("div");\n document.body.append(host);\n- const onProviderModelChange = vi.fn();\n- const modelOptionsByProvider = {\n- claudeAgent: [\n- { slug: "claude-opus-4-6", name: "Claude Opus 4.6" },\n- { slug: "claude-sonnet-4-6", name: "Claude Sonnet 4.6" },\n+ const onInstanceModelChange = vi.fn();\n+ const modelOptionsByInstance = new Map<ProviderInstanceId, ReadonlyArray<ModelEsque>>([\n+ [\n+ "claudeAgent" as ProviderInstanceId,\n+ [\n+ { slug: "claude-opus-4-6", name: "Claude Opus 4.6" },\n+ { slug: "claude-sonnet-4-6", name: "Claude Sonnet 4.6" },\n+ ],\n ],\n- codex: [{ slug: "gpt-5-codex", name: "GPT-5 Codex" }],\n- cursor: [],\n- opencode: [],\n- } as const;\n+ ["codex" as ProviderInstanceId, [{ slug: "gpt-5-codex", name: "GPT-5 Codex" }]],\n+ ["cursor" as ProviderInstanceId, []],\n+ ["opencode" as ProviderInstanceId, []],\n+ ]);\n+ const instanceEntries = sortProviderInstanceEntries(\n+ deriveProviderInstanceEntries(TEST_PROVIDERS),\n+ );\n const screen = await render(\n <ProviderModelPicker\n- provider="claudeAgent"\n+ activeInstanceId={"claudeAgent" as ProviderInstanceId}\n model="gpt-5-codex"\n lockedProvider={null}\n- providers={TEST_PROVIDERS}\n- modelOptionsByProvider={modelOptionsByProvider}\n- onProviderModelChange={onProviderModelChange}\n+ instanceEntries={instanceEntries}\n+ modelOptionsByInstance={modelOptionsByInstance}\n+ onInstanceModelChange={onInstanceModelChange}\n />,\n { container: host },\n );\n@@ -504,9 +647,9 @@ describe("ProviderModelPicker", () => {\n ]),\n ];\n const mounted = await mountPicker({\n- provider: "opencode",\n+ activeInstanceId: OPENCODE_INSTANCE_ID,\n model: "github-copilot/claude-opus-4.5",\n- lockedProvider: "opencode",\n+ lockedProvider: ProviderDriverKind.make("opencode"),\n providers,\n });\n \n@@ -531,7 +674,7 @@ describe("ProviderModelPicker", () => {\n \n it("searches models by name in flat list", async () => {\n const mounted = await mountPicker({\n- provider: "claudeAgent",\n+ activeInstanceId: CLAUDE_INSTANCE_ID,\n model: "claude-opus-4-6",\n lockedProvider: null,\n });\n@@ -561,9 +704,9 @@ describe("ProviderModelPicker", () => {\n \n it("supports arrow-key navigation in the model picker", async () => {\n const mounted = await mountPicker({\n- provider: "claudeAgent",\n+ activeInstanceId: CLAUDE_INSTANCE_ID,\n model: "claude-opus-4-6",\n- lockedProvider: "claudeAgent",\n+ lockedProvider: ProviderDriverKind.make("claudeAgent"),\n });\n \n try {\n@@ -600,7 +743,7 @@ describe("ProviderModelPicker", () => {\n \n it("hides the provider sidebar while searching", async () => {\n const mounted = await mountPicker({\n- provider: "claudeAgent",\n+ activeInstanceId: CLAUDE_INSTANCE_ID,\n model: "claude-opus-4-6",\n lockedProvider: null,\n });\n@@ -624,7 +767,7 @@ describe("ProviderModelPicker", () => {\n \n it("closes the picker when escape is pressed in search", async () => {\n const mounted = await mountPicker({\n- provider: "claudeAgent",\n+ activeInstanceId: CLAUDE_INSTANCE_ID,\n model: "claude-opus-4-6",\n lockedProvider: null,\n });\n@@ -652,7 +795,7 @@ describe("ProviderModelPicker", () => {\n \n it("searches models by provider name", async () => {\n const mounted = await mountPicker({\n- provider: "claudeAgent",\n+ activeInstanceId: CLAUDE_INSTANCE_ID,\n model: "claude-opus-4-6",\n lockedProvider: null,\n });\n@@ -718,7 +861,7 @@ describe("ProviderModelPicker", () => {\n ]),\n ];\n const mounted = await mountPicker({\n- provider: "opencode",\n+ activeInstanceId: OPENCODE_INSTANCE_ID,\n model: "github-copilot/claude-opus-4.7",\n lockedProvider: null,\n providers,\n@@ -780,7 +923,7 @@ describe("ProviderModelPicker", () => {\n },\n ];\n const mounted = await mountPicker({\n- provider: "opencode",\n+ activeInstanceId: OPENCODE_INSTANCE_ID,\n model: "github-copilot/claude-opus-4.7",\n lockedProvider: null,\n providers,\n@@ -805,7 +948,7 @@ describe("ProviderModelPicker", () => {\n localStorage.removeItem("t3code:client-settings:v1");\n \n const mounted = await mountPicker({\n- provider: "claudeAgent",\n+ activeInstanceId: CLAUDE_INSTANCE_ID,\n model: "claude-opus-4-6",\n lockedProvider: null,\n });\n@@ -850,7 +993,7 @@ describe("ProviderModelPicker", () => {\n localStorage.removeItem("t3code:client-settings:v1");\n \n const mounted = await mountPicker({\n- provider: "claudeAgent",\n+ activeInstanceId: CLAUDE_INSTANCE_ID,\n model: "claude-opus-4-6",\n lockedProvider: null,\n });\n@@ -890,7 +1033,6 @@ describe("ProviderModelPicker", () => {\n );\n \n const mounted = await mountPicker({\n- provider: "codex",\n model: "gpt-5-codex",\n lockedProvider: null,\n });\n@@ -910,9 +1052,9 @@ describe("ProviderModelPicker", () => {\n \n it("dispatches callback with correct provider and model when selected", async () => {\n const mounted = await mountPicker({\n- provider: "claudeAgent",\n+ activeInstanceId: CLAUDE_INSTANCE_ID,\n model: "claude-opus-4-6",\n- lockedProvider: "claudeAgent",\n+ lockedProvider: ProviderDriverKind.make("claudeAgent"),\n });\n \n try {\n@@ -995,7 +1137,6 @@ describe("ProviderModelPicker", () => {\n ];\n \n const hidden = await mountPicker({\n- provider: "codex",\n model: "gpt-5.3-codex",\n lockedProvider: null,\n providers: providersWithoutSpark,\n@@ -1014,7 +1155,6 @@ describe("ProviderModelPicker", () => {\n }\n \n const visible = await mountPicker({\n- provider: "codex",\n model: "gpt-5.3-codex",\n lockedProvider: null,\n providers: providersWithSpark,\n@@ -1034,7 +1174,7 @@ describe("ProviderModelPicker", () => {\n it("shows disabled providers grayed out in sidebar", async () => {\n const disabledProviders = TEST_PROVIDERS.slice();\n const claudeIndex = disabledProviders.findIndex(\n- (provider) => provider.provider === "claudeAgent",\n+ (provider) => provider.instanceId === ProviderInstanceId.make("claudeAgent"),\n );\n if (claudeIndex >= 0) {\n const claudeProvider = disabledProviders[claudeIndex]!;\n@@ -1046,7 +1186,6 @@ describe("ProviderModelPicker", () => {\n }\n \n const mounted = await mountPicker({\n- provider: "codex",\n model: "gpt-5-codex",\n lockedProvider: null,\n providers: disabledProviders,\n@@ -1068,7 +1207,6 @@ describe("ProviderModelPicker", () => {\n \n it("accepts outline trigger styling", async () => {\n const mounted = await mountPicker({\n- provider: "codex",\n model: "gpt-5-codex",\n lockedProvider: null,\n triggerVariant: "outline",\ndiff --git a/apps/web/src/components/chat/ProviderModelPicker.tsx b/apps/web/src/components/chat/ProviderModelPicker.tsx\nindex 4f4140f834..4a2860ee46 100644\n--- a/apps/web/src/components/chat/ProviderModelPicker.tsx\n+++ b/apps/web/src/components/chat/ProviderModelPicker.tsx\n@@ -1,9 +1,9 @@\n import {\n- type ProviderKind,\n+ type ProviderInstanceId,\n+ type ProviderDriverKind,\n type ResolvedKeybindingsConfig,\n- type ServerProvider,\n } from "@t3tools/contracts";\n-import { memo, useEffect, useState } from "react";\n+import { memo, useEffect, useMemo, useState } from "react";\n import type { VariantProps } from "class-variance-authority";\n import { ChevronDownIcon } from "lucide-react";\n import { Button, buttonVariants } from "../ui/button";\n@@ -11,21 +11,28 @@ import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover";\n import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";\n import { cn } from "~/lib/utils";\n import { ModelPickerContent } from "./ModelPickerContent";\n+import { ProviderInstanceIcon } from "./ProviderInstanceIcon";\n import {\n ModelEsque,\n- PROVIDER_ICON_BY_PROVIDER,\n getTriggerDisplayModelLabel,\n getTriggerDisplayModelName,\n } from "./providerIconUtils";\n import { setModelPickerOpen } from "../../modelPickerOpenState";\n+import type { ProviderInstanceEntry } from "../../providerInstances";\n \n export const ProviderModelPicker = memo(function ProviderModelPicker(props: {\n- provider: ProviderKind;\n+ /**\n+ * The instance currently selected in the composer. Drives the trigger\n+ * icon, label and the default-highlighted combobox row.\n+ */\n+ activeInstanceId: ProviderInstanceId;\n model: string;\n- lockedProvider: ProviderKind | null;\n- providers?: ReadonlyArray<ServerProvider>;\n+ lockedProvider: ProviderDriverKind | null;\n+ lockedContinuationGroupKey?: string | null;\n+ /** Instance entries rendered in the sidebar + used to resolve display name. */\n+ instanceEntries: ReadonlyArray<ProviderInstanceEntry>;\n keybindings?: ResolvedKeybindingsConfig;\n- modelOptionsByProvider: Record<ProviderKind, ReadonlyArray<ModelEsque>>;\n+ modelOptionsByInstance: ReadonlyMap<ProviderInstanceId, ReadonlyArray<ModelEsque>>;\n activeProviderIconClassName?: string;\n compact?: boolean;\n disabled?: boolean;\n@@ -34,22 +41,36 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: {\n triggerVariant?: VariantProps<typeof buttonVariants>["variant"];\n triggerClassName?: string;\n onOpenChange?: (open: boolean) => void;\n- onProviderModelChange: (provider: ProviderKind, model: string) => void;\n+ onInstanceModelChange: (instanceId: ProviderInstanceId, model: string) => void;\n }) {\n const [uncontrolledIsMenuOpen, setUncontrolledIsMenuOpen] = useState(false);\n- const activeProvider = props.lockedProvider ?? props.provider;\n const isMenuOpen = props.open ?? uncontrolledIsMenuOpen;\n- const selectedProviderOptions = props.modelOptionsByProvider[activeProvider];\n- // If the current slug belongs to a different provider (for example after a provider\n- // switch or disable), prefer the active provider\'s first option so the trigger icon\n- // and label stay in sync instead of showing a stale foreign slug.\n+\n+ // Resolve the active instance entry by exact routing key. The composer\n+ // resolves fallbacks before rendering this component; if the selected\n+ // instance disappears, do not infer a replacement from its driver kind.\n+ const activeEntry = useMemo(() => {\n+ return (\n+ props.instanceEntries.find((entry) => entry.instanceId === props.activeInstanceId) ?? null\n+ );\n+ }, [props.activeInstanceId, props.instanceEntries]);\n+\n+ const activeInstanceId = props.activeInstanceId;\n+ const selectedInstanceOptions = props.modelOptionsByInstance.get(activeInstanceId) ?? [];\n+ // If the current slug belongs to a different instance (for example after\n+ // a provider switch or disable), prefer the active instance\'s first\n+ // option so the trigger icon and label stay in sync instead of showing\n+ // a stale foreign slug.\n const selectedModel =\n- selectedProviderOptions.find((option) => option.slug === props.model) ??\n- selectedProviderOptions[0];\n- const ProviderIcon = PROVIDER_ICON_BY_PROVIDER[activeProvider];\n+ selectedInstanceOptions.find((option) => option.slug === props.model) ??\n+ selectedInstanceOptions[0];\n const triggerTitle = selectedModel ? getTriggerDisplayModelName(selectedModel) : props.model;\n const triggerSubtitle = selectedModel?.subProvider;\n const triggerLabel = selectedModel ? getTriggerDisplayModelLabel(selectedModel) : props.model;\n+ const duplicateDriverCount = props.instanceEntries.filter(\n+ (entry) => activeEntry !== null && entry.driverKind === activeEntry.driverKind,\n+ ).length;\n+ const showInstanceBadge = Boolean(activeEntry?.accentColor) || duplicateDriverCount > 1;\n \n const setIsMenuOpen = (open: boolean) => {\n props.onOpenChange?.(open);\n@@ -65,9 +86,9 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: {\n };\n }, [isMenuOpen]);\n \n- const handleProviderModelChange = (provider: ProviderKind, model: string) => {\n+ const handleInstanceModelChange = (instanceId: ProviderInstanceId, model: string) => {\n if (props.disabled) return;\n- props.onProviderModelChange(provider, model);\n+ props.onInstanceModelChange(instanceId, model);\n setIsMenuOpen(false);\n };\n \n@@ -103,10 +124,17 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: {\n props.compact ? "max-w-36 sm:pl-1" : undefined,\n )}\n >\n- <ProviderIcon\n- aria-hidden="true"\n- className={cn("size-4 shrink-0", props.activeProviderIconClassName)}\n- />\n+ {activeEntry ? (\n+ <ProviderInstanceIcon\n+ driverKind={activeEntry.driverKind}\n+ displayName={activeEntry.displayName}\n+ accentColor={activeEntry.accentColor}\n+ showBadge={showInstanceBadge}\n+ className={showInstanceBadge ? "size-5" : "size-4"}\n+ iconClassName={cn("size-4", props.activeProviderIconClassName)}\n+ badgeClassName="right-[-0.125rem] bottom-[-0.125rem] h-3 min-w-3 text-[7px]"\n+ />\n+ ) : null}\n <Tooltip>\n <TooltipTrigger\n render={\n@@ -142,15 +170,16 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: {\n className="border-0 bg-transparent p-0 shadow-none before:hidden [--viewport-inline-padding:0] *:data-[slot=popover-viewport]:p-0"\n >\n <ModelPickerContent\n- provider={props.provider}\n+ activeInstanceId={activeInstanceId}\n model={props.model}\n lockedProvider={props.lockedProvider}\n- {...(props.providers && { providers: props.providers })}\n+ lockedContinuationGroupKey={props.lockedContinuationGroupKey ?? null}\n+ instanceEntries={props.instanceEntries}\n {...(props.keybindings ? { keybindings: props.keybindings } : {})}\n- modelOptionsByProvider={props.modelOptionsByProvider}\n+ modelOptionsByInstance={props.modelOptionsByInstance}\n terminalOpen={props.terminalOpen ?? false}\n onRequestClose={() => setIsMenuOpen(false)}\n- onProviderModelChange={handleProviderModelChange}\n+ onInstanceModelChange={handleInstanceModelChange}\n />\n </PopoverPopup>\n </Popover>\ndiff --git a/apps/web/src/components/chat/ProviderStatusBanner.tsx b/apps/web/src/components/chat/ProviderStatusBanner.tsx\nindex 5eaacafe05..a882942585 100644\n--- a/apps/web/src/components/chat/ProviderStatusBanner.tsx\n+++ b/apps/web/src/components/chat/ProviderStatusBanner.tsx\n@@ -2,7 +2,7 @@ import { type ServerProvider } from "@t3tools/contracts";\n import { memo } from "react";\n import { Alert, AlertDescription, AlertTitle } from "../ui/alert";\n import { CircleAlertIcon } from "lucide-react";\n-import { formatProviderKindLabel } from "../../providerModels";\n+import { formatProviderDriverKindLabel } from "../../providerModels";\n \n export const ProviderStatusBanner = memo(function ProviderStatusBanner({\n status,\n@@ -13,7 +13,7 @@ export const ProviderStatusBanner = memo(function ProviderStatusBanner({\n return null;\n }\n \n- const providerLabel = status.displayName?.trim() || formatProviderKindLabel(status.provider);\n+ const providerLabel = status.displayName?.trim() || formatProviderDriverKindLabel(status.driver);\n const defaultMessage =\n status.status === "error"\n ? `${providerLabel} provider is unavailable.`\ndiff --git a/apps/web/src/components/chat/TraitsPicker.tsx b/apps/web/src/components/chat/TraitsPicker.tsx\nindex 1b54da76da..62caa323fd 100644\n--- a/apps/web/src/components/chat/TraitsPicker.tsx\n+++ b/apps/web/src/components/chat/TraitsPicker.tsx\n@@ -1,5 +1,5 @@\n import {\n- type ProviderKind,\n+ type ProviderDriverKind,\n type ProviderOptionDescriptor,\n type ProviderOptionSelection,\n type ScopedThreadRef,\n@@ -76,7 +76,7 @@ function getDescriptorStringValue(\n }\n \n function getSelectedTraits(\n- provider: ProviderKind,\n+ provider: ProviderDriverKind,\n models: ReadonlyArray<ServerProviderModel>,\n model: string | null | undefined,\n prompt: string,\n@@ -150,7 +150,7 @@ function getSelectedTraits(\n }\n \n function getTraitsSectionVisibility(input: {\n- provider: ProviderKind;\n+ provider: ProviderDriverKind;\n models: ReadonlyArray<ServerProviderModel>;\n model: string | null | undefined;\n prompt: string;\n@@ -184,7 +184,7 @@ function getTraitsSectionVisibility(input: {\n }\n \n export function shouldRenderTraitsControls(input: {\n- provider: ProviderKind;\n+ provider: ProviderDriverKind;\n models: ReadonlyArray<ServerProviderModel>;\n model: string | null | undefined;\n prompt: string;\n@@ -195,7 +195,7 @@ export function shouldRenderTraitsControls(input: {\n }\n \n export interface TraitsMenuContentProps {\n- provider: ProviderKind;\n+ provider: ProviderDriverKind;\n models: ReadonlyArray<ServerProviderModel>;\n model: string | null | undefined;\n prompt: string;\ndiff --git a/apps/web/src/components/chat/composerProviderState.test.tsx b/apps/web/src/components/chat/composerProviderState.test.tsx\nindex cc49cbf5df..d9e35c2bd5 100644\n--- a/apps/web/src/components/chat/composerProviderState.test.tsx\n+++ b/apps/web/src/components/chat/composerProviderState.test.tsx\n@@ -1,9 +1,9 @@\n import { describe, expect, it } from "vitest";\n-import type {\n- ProviderKind,\n- ProviderOptionDescriptor,\n- ProviderOptionSelection,\n- ServerProviderModel,\n+import {\n+ ProviderDriverKind,\n+ type ProviderOptionDescriptor,\n+ type ProviderOptionSelection,\n+ type ServerProviderModel,\n } from "@t3tools/contracts";\n import {\n getComposerProviderState,\n@@ -15,7 +15,7 @@ import {\n // optionDescriptors, so these tests use a single synthetic provider/model and\n // vary only the descriptor shape per scenario.\n \n-const PROVIDER: ProviderKind = "codex";\n+const PROVIDER: ProviderDriverKind = ProviderDriverKind.make("codex");\n const MODEL = "test-model";\n \n function selectDescriptor(\ndiff --git a/apps/web/src/components/chat/composerProviderState.tsx b/apps/web/src/components/chat/composerProviderState.tsx\nindex b817786563..dc61bd1e48 100644\n--- a/apps/web/src/components/chat/composerProviderState.tsx\n+++ b/apps/web/src/components/chat/composerProviderState.tsx\n@@ -1,5 +1,5 @@\n import {\n- type ProviderKind,\n+ type ProviderDriverKind,\n type ProviderOptionSelection,\n type ScopedThreadRef,\n type ServerProviderModel,\n@@ -17,7 +17,7 @@ import { getProviderModelCapabilities } from "../../providerModels";\n import { shouldRenderTraitsControls, TraitsMenuContent, TraitsPicker } from "./TraitsPicker";\n \n export type ComposerProviderStateInput = {\n- provider: ProviderKind;\n+ provider: ProviderDriverKind;\n model: string;\n models: ReadonlyArray<ServerProviderModel>;\n prompt: string;\n@@ -25,7 +25,7 @@ export type ComposerProviderStateInput = {\n };\n \n export type ComposerProviderState = {\n- provider: ProviderKind;\n+ provider: ProviderDriverKind;\n promptEffort: string | null;\n modelOptionsForDispatch: ReadonlyArray<ProviderOptionSelection> | undefined;\n composerFrameClassName?: string;\n@@ -34,7 +34,7 @@ export type ComposerProviderState = {\n };\n \n type TraitsRenderInput = {\n- provider: ProviderKind;\n+ provider: ProviderDriverKind;\n threadRef?: ScopedThreadRef;\n draftId?: DraftId;\n model: string;\ndiff --git a/apps/web/src/components/chat/composerSlashCommandSearch.test.ts b/apps/web/src/components/chat/composerSlashCommandSearch.test.ts\nindex 3da69933d0..ab808f6640 100644\n--- a/apps/web/src/components/chat/composerSlashCommandSearch.test.ts\n+++ b/apps/web/src/components/chat/composerSlashCommandSearch.test.ts\n@@ -1,9 +1,12 @@\n import { describe, expect, it } from "vitest";\n+import { ProviderDriverKind } from "@t3tools/contracts";\n \n import type { ComposerCommandItem } from "./ComposerCommandMenu";\n import { searchSlashCommandItems } from "./composerSlashCommandSearch";\n \n describe("searchSlashCommandItems", () => {\n+ const claudeDriver = ProviderDriverKind.make("claudeAgent");\n+\n it("moves exact provider command matches ahead of broader description matches", () => {\n const items = [\n {\n@@ -16,7 +19,7 @@ describe("searchSlashCommandItems", () => {\n {\n id: "provider-slash-command:claudeAgent:ui",\n type: "provider-slash-command",\n- provider: "claudeAgent",\n+ provider: claudeDriver,\n command: { name: "ui" },\n label: "/ui",\n description: "Explore, build, and refine UI.",\n@@ -24,7 +27,7 @@ describe("searchSlashCommandItems", () => {\n {\n id: "provider-slash-command:claudeAgent:frontend-design",\n type: "provider-slash-command",\n- provider: "claudeAgent",\n+ provider: claudeDriver,\n command: { name: "frontend-design" },\n label: "/frontend-design",\n description: "Create distinctive, production-grade frontend interfaces",\n@@ -44,7 +47,7 @@ describe("searchSlashCommandItems", () => {\n {\n id: "provider-slash-command:claudeAgent:gh-fix-ci",\n type: "provider-slash-command",\n- provider: "claudeAgent",\n+ provider: claudeDriver,\n command: { name: "gh-fix-ci" },\n label: "/gh-fix-ci",\n description: "Fix failing GitHub Actions",\n@@ -52,7 +55,7 @@ describe("searchSlashCommandItems", () => {\n {\n id: "provider-slash-command:claudeAgent:github",\n type: "provider-slash-command",\n- provider: "claudeAgent",\n+ provider: claudeDriver,\n command: { name: "github" },\n label: "/github",\n description: "General GitHub help",\ndiff --git a/apps/web/src/components/chat/modelPickerModelHighlights.ts b/apps/web/src/components/chat/modelPickerModelHighlights.ts\nindex c3661fda2b..2131480a6a 100644\n--- a/apps/web/src/components/chat/modelPickerModelHighlights.ts\n+++ b/apps/web/src/components/chat/modelPickerModelHighlights.ts\n@@ -1,4 +1,4 @@\n-import type { ProviderKind } from "@t3tools/contracts";\n+import type { ProviderDriverKind } from "@t3tools/contracts";\n \n /**\n * Model slugs that show a gold "NEW" chip in the model picker list.\n@@ -8,6 +8,6 @@ const NEW_MODEL_KEYS = new Set<string>([\n // Example: "claudeAgent:claude-opus-4-7",\n ]);\n \n-export function isModelPickerNewModel(provider: ProviderKind, slug: string): boolean {\n+export function isModelPickerNewModel(provider: ProviderDriverKind, slug: string): boolean {\n return NEW_MODEL_KEYS.has(`${provider}:${slug}`);\n }\ndiff --git a/apps/web/src/components/chat/modelPickerSearch.test.ts b/apps/web/src/components/chat/modelPickerSearch.test.ts\nindex 1ce629d8a4..10282dbe3e 100644\n--- a/apps/web/src/components/chat/modelPickerSearch.test.ts\n+++ b/apps/web/src/components/chat/modelPickerSearch.test.ts\n@@ -6,7 +6,8 @@ describe("buildModelPickerSearchText", () => {\n it("builds provider-agnostic search text from generic fields", () => {\n expect(\n buildModelPickerSearchText({\n- provider: "opencode",\n+ driverKind: "opencode",\n+ providerDisplayName: "opencode",\n name: "Claude Opus 4.7",\n subProvider: "GitHub Copilot",\n }),\n@@ -19,7 +20,8 @@ describe("scoreModelPickerSearch", () => {\n expect(\n scoreModelPickerSearch(\n {\n- provider: "opencode",\n+ driverKind: "opencode",\n+ providerDisplayName: "opencode",\n name: "Claude Opus 4.7",\n subProvider: "GitHub Copilot",\n },\n@@ -32,7 +34,8 @@ describe("scoreModelPickerSearch", () => {\n expect(\n scoreModelPickerSearch(\n {\n- provider: "codex",\n+ driverKind: "codex",\n+ providerDisplayName: "codex",\n name: "GPT-5 Codex",\n },\n "coplt op",\n@@ -43,7 +46,8 @@ describe("scoreModelPickerSearch", () => {\n it("ranks exact token matches ahead of fuzzier matches", () => {\n const exactScore = scoreModelPickerSearch(\n {\n- provider: "opencode",\n+ driverKind: "opencode",\n+ providerDisplayName: "opencode",\n name: "Claude Opus 4.7",\n subProvider: "GitHub Copilot",\n },\n@@ -51,7 +55,8 @@ describe("scoreModelPickerSearch", () => {\n );\n const fuzzyScore = scoreModelPickerSearch(\n {\n- provider: "opencode",\n+ driverKind: "opencode",\n+ providerDisplayName: "opencode",\n name: "Claude Opus 4.7",\n subProvider: "GitHub Copilot",\n },\n@@ -66,7 +71,8 @@ describe("scoreModelPickerSearch", () => {\n it("gives favorite models a strong enough ranking boost for partial queries", () => {\n const favoriteScore = scoreModelPickerSearch(\n {\n- provider: "claudeAgent",\n+ driverKind: "claudeAgent",\n+ providerDisplayName: "Claude",\n name: "Claude Opus 4.7",\n isFavorite: true,\n },\n@@ -74,7 +80,8 @@ describe("scoreModelPickerSearch", () => {\n );\n const nonFavoriteScore = scoreModelPickerSearch(\n {\n- provider: "cursor",\n+ driverKind: "cursor",\n+ providerDisplayName: "Cursor",\n name: "Opus 4.5",\n },\n "opu",\n@@ -88,7 +95,8 @@ describe("scoreModelPickerSearch", () => {\n it("does not let the favorite boost outrank clearly better textual matches", () => {\n const favoriteScore = scoreModelPickerSearch(\n {\n- provider: "claudeAgent",\n+ driverKind: "claudeAgent",\n+ providerDisplayName: "Claude",\n name: "Claude Opus 4.7",\n isFavorite: true,\n },\n@@ -96,7 +104,8 @@ describe("scoreModelPickerSearch", () => {\n );\n const nonFavoriteExactScore = scoreModelPickerSearch(\n {\n- provider: "cursor",\n+ driverKind: "cursor",\n+ providerDisplayName: "Cursor",\n name: "Opus 4.7",\n },\n "opus 4.7",\n@@ -106,4 +115,17 @@ describe("scoreModelPickerSearch", () => {\n expect(nonFavoriteExactScore).not.toBeNull();\n expect(nonFavoriteExactScore!).toBeLessThan(favoriteScore!);\n });\n+\n+ it("matches a custom instance\'s display name against its models", () => {\n+ expect(\n+ scoreModelPickerSearch(\n+ {\n+ driverKind: "codex",\n+ providerDisplayName: "Codex Personal",\n+ name: "GPT-5 Codex",\n+ },\n+ "personal",\n+ ),\n+ ).not.toBeNull();\n+ });\n });\ndiff --git a/apps/web/src/components/chat/modelPickerSearch.ts b/apps/web/src/components/chat/modelPickerSearch.ts\nindex a4871fa0f3..d3a954ee4f 100644\n--- a/apps/web/src/components/chat/modelPickerSearch.ts\n+++ b/apps/web/src/components/chat/modelPickerSearch.ts\n@@ -1,8 +1,14 @@\n-import { type ProviderKind, PROVIDER_DISPLAY_NAMES } from "@t3tools/contracts";\n import { normalizeSearchQuery, scoreQueryMatch } from "@t3tools/shared/searchRanking";\n \n type ModelPickerSearchableModel = {\n- provider: ProviderKind;\n+ /** Driver kind — indexed so "codex" still matches a Codex Personal instance. */\n+ driverKind: string;\n+ /**\n+ * Instance display name (e.g. "Codex Personal"). Indexed as a search\n+ * field so typing the custom instance\'s user-authored name matches its\n+ * models directly instead of just the driver kind.\n+ */\n+ providerDisplayName: string;\n name: string;\n shortName?: string;\n subProvider?: string;\n@@ -16,8 +22,8 @@ function getModelPickerSearchFields(model: ModelPickerSearchableModel): string[]\n normalizeSearchQuery(model.name),\n ...(model.shortName ? [normalizeSearchQuery(model.shortName)] : []),\n ...(model.subProvider ? [normalizeSearchQuery(model.subProvider)] : []),\n- normalizeSearchQuery(model.provider),\n- normalizeSearchQuery(PROVIDER_DISPLAY_NAMES[model.provider]),\n+ normalizeSearchQuery(model.driverKind),\n+ normalizeSearchQuery(model.providerDisplayName),\n buildModelPickerSearchText(model),\n ];\n }\n@@ -40,13 +46,7 @@ function scoreModelPickerSearchToken(\n \n export function buildModelPickerSearchText(model: ModelPickerSearchableModel): string {\n return normalizeSearchQuery(\n- [\n- model.name,\n- model.shortName,\n- model.subProvider,\n- model.provider,\n- PROVIDER_DISPLAY_NAMES[model.provider],\n- ]\n+ [model.name, model.shortName, model.subProvider, model.driverKind, model.providerDisplayName]\n .filter((value): value is string => typeof value === "string" && value.length > 0)\n .join(" "),\n );\ndiff --git a/apps/web/src/components/chat/providerIconUtils.ts b/apps/web/src/components/chat/providerIconUtils.ts\nindex 66f5220771..88b56295f3 100644\n--- a/apps/web/src/components/chat/providerIconUtils.ts\n+++ b/apps/web/src/components/chat/providerIconUtils.ts\n@@ -1,16 +1,16 @@\n-import { type ProviderKind, PROVIDER_DISPLAY_NAMES } from "@t3tools/contracts";\n+import { ProviderDriverKind } from "@t3tools/contracts";\n import { ClaudeAI, CursorIcon, Icon, OpenAI, OpenCodeIcon } from "../Icons";\n import { PROVIDER_OPTIONS } from "../../session-logic";\n \n-export const PROVIDER_ICON_BY_PROVIDER: Record<ProviderKind, Icon> = {\n- codex: OpenAI,\n- claudeAgent: ClaudeAI,\n- opencode: OpenCodeIcon,\n- cursor: CursorIcon,\n+export const PROVIDER_ICON_BY_PROVIDER: Partial<Record<ProviderDriverKind, Icon>> = {\n+ [ProviderDriverKind.make("codex")]: OpenAI,\n+ [ProviderDriverKind.make("claudeAgent")]: ClaudeAI,\n+ [ProviderDriverKind.make("opencode")]: OpenCodeIcon,\n+ [ProviderDriverKind.make("cursor")]: CursorIcon,\n };\n \n function isAvailableProviderOption(option: (typeof PROVIDER_OPTIONS)[number]): option is {\n- value: ProviderKind;\n+ value: ProviderDriverKind;\n label: string;\n available: true;\n pickerSidebarBadge?: "new" | "soon";\n@@ -27,11 +27,6 @@ export type ModelEsque = {\n subProvider?: string | undefined;\n };\n \n-export function getProviderLabel(provider: ProviderKind, model: ModelEsque): string {\n- const providerLabel = PROVIDER_DISPLAY_NAMES[provider];\n- return model.subProvider ? `${providerLabel} · ${model.subProvider}` : providerLabel;\n-}\n-\n export function getDisplayModelName(\n model: ModelEsque,\n options?: { preferShortName?: boolean },\ndiff --git a/apps/web/src/components/settings/AddProviderInstanceDialog.tsx b/apps/web/src/components/settings/AddProviderInstanceDialog.tsx\nnew file mode 100644\nindex 0000000000..b8bce8f0cd\n--- /dev/null\n+++ b/apps/web/src/components/settings/AddProviderInstanceDialog.tsx\n@@ -0,0 +1,493 @@\n+"use client";\n+\n+import { CheckIcon } from "lucide-react";\n+import { Radio as RadioPrimitive } from "@base-ui/react/radio";\n+import { useCallback, useEffect, useMemo, useState } from "react";\n+import {\n+ ProviderInstanceId,\n+ ProviderDriverKind,\n+ type ProviderInstanceConfig,\n+} from "@t3tools/contracts";\n+\n+import { useSettings, useUpdateSettings } from "../../hooks/useSettings";\n+import { cn } from "../../lib/utils";\n+import { normalizeProviderAccentColor } from "../../providerInstances";\n+import { Button } from "../ui/button";\n+import { ACPRegistryIcon, Gemini, GithubCopilotIcon, PiAgentIcon } from "../Icons";\n+import {\n+ Dialog,\n+ DialogDescription,\n+ DialogFooter,\n+ DialogHeader,\n+ DialogPopup,\n+ DialogTitle,\n+} from "../ui/dialog";\n+import { Badge } from "../ui/badge";\n+import { Input } from "../ui/input";\n+import { RadioGroup } from "../ui/radio-group";\n+import { toastManager } from "../ui/toast";\n+import { DRIVER_OPTION_BY_VALUE, DRIVER_OPTIONS, type DriverOption } from "./providerDriverMeta";\n+\n+const PROVIDER_ACCENT_SWATCHES = [\n+ "#2563eb",\n+ "#16a34a",\n+ "#ea580c",\n+ "#dc2626",\n+ "#7c3aed",\n+ "#0891b2",\n+] as const;\n+\n+/**\n+ * Normalize a user-provided label into a slug suffix for the instance id.\n+ * The full id is formed by prefixing the driver slug — e.g. label "Work" on\n+ * driver "codex" becomes `codex_work`. Output is trimmed to 48 chars so the\n+ * final composed id stays under the 64-char slug cap enforced by\n+ * `ProviderInstanceId` in `@t3tools/contracts`.\n+ */\n+function slugifyLabel(value: string): string {\n+ return value\n+ .trim()\n+ .toLowerCase()\n+ .replace(/[^a-z0-9]+/g, "_")\n+ .replace(/^_+|_+$/g, "")\n+ .slice(0, 48);\n+}\n+\n+function deriveInstanceId(driver: ProviderDriverKind, label: string): string {\n+ const slug = slugifyLabel(label);\n+ return slug ? `${driver}_${slug}` : "";\n+}\n+\n+const INSTANCE_ID_PATTERN = /^[a-zA-Z][a-zA-Z0-9_-]*$/;\n+const DEFAULT_DRIVER_KIND = ProviderDriverKind.make("codex");\n+const DEFAULT_DRIVER_OPTION = DRIVER_OPTIONS[0]!;\n+const COMING_SOON_DRIVER_OPTIONS: readonly DriverOption[] = [\n+ {\n+ value: ProviderDriverKind.make("githubCopilot"),\n+ label: "Github Copilot",\n+ icon: GithubCopilotIcon,\n+ fields: [],\n+ },\n+ {\n+ value: ProviderDriverKind.make("gemini"),\n+ label: "Gemini",\n+ icon: Gemini,\n+ fields: [],\n+ },\n+ {\n+ value: ProviderDriverKind.make("acpRegistry"),\n+ label: "ACP Registry",\n+ icon: ACPRegistryIcon,\n+ fields: [],\n+ },\n+ {\n+ value: ProviderDriverKind.make("piAgent"),\n+ label: "Pi Agent",\n+ icon: PiAgentIcon,\n+ fields: [],\n+ },\n+];\n+\n+/**\n+ * Validate an instance id against the same slug rules the server applies in\n+ * `ProviderInstanceId` (see `packages/contracts/src/providerInstance.ts`).\n+ * Returns a user-facing error string, or `null` if valid.\n+ */\n+function validateInstanceId(id: string, existing: ReadonlySet<string>): string | null {\n+ if (id.length === 0) return "Instance ID is required.";\n+ if (id.length > 64) return "Instance ID must be 64 characters or fewer.";\n+ if (!INSTANCE_ID_PATTERN.test(id)) {\n+ return "Instance ID must start with a letter and use only letters, digits, \'-\', or \'_\'.";\n+ }\n+ if (existing.has(id)) return `An instance named \'${id}\' already exists.`;\n+ return null;\n+}\n+\n+interface AddProviderInstanceDialogProps {\n+ open: boolean;\n+ onOpenChange: (open: boolean) => void;\n+}\n+\n+export function AddProviderInstanceDialog({ open, onOpenChange }: AddProviderInstanceDialogProps) {\n+ const settings = useSettings();\n+ const { updateSettings } = useUpdateSettings();\n+\n+ const [wizardStep, setWizardStep] = useState(0);\n+ const [driver, setDriver] = useState<ProviderDriverKind>(DEFAULT_DRIVER_KIND);\n+ const [label, setLabel] = useState("");\n+ const [accentColor, setAccentColor] = useState<string>("");\n+ const [instanceId, setInstanceId] = useState("");\n+ const [instanceIdDirty, setInstanceIdDirty] = useState(false);\n+ // Driver-specific field values keyed by `${driver}:${fieldKey}` so toggling\n+ // between drivers during the same dialog session doesn\'t lose in-progress\n+ // input. Only the active driver\'s values are persisted on save.\n+ const [fieldValues, setFieldValues] = useState<Record<string, string>>({});\n+ // Errors are suppressed until the user has tried to submit once. After that\n+ // they update live so fixing the problem clears the message in place.\n+ const [hasAttemptedSubmit, setHasAttemptedSubmit] = useState(false);\n+\n+ const existingIds = useMemo(\n+ () => new Set(Object.keys(settings.providerInstances ?? {})),\n+ [settings.providerInstances],\n+ );\n+\n+ // Reset the form every time the dialog opens so each creation starts\n+ // from a clean slate.\n+ useEffect(() => {\n+ if (!open) return;\n+ setDriver(DEFAULT_DRIVER_KIND);\n+ setLabel("");\n+ setAccentColor("");\n+ setInstanceId("");\n+ setWizardStep(0);\n+ setInstanceIdDirty(false);\n+ setFieldValues({});\n+ setHasAttemptedSubmit(false);\n+ }, [open]);\n+\n+ // Auto-derive the instance id from driver + label until the user types\n+ // in the Instance ID field directly (after which they own its value).\n+ useEffect(() => {\n+ if (instanceIdDirty) return;\n+ setInstanceId(deriveInstanceId(driver, label));\n+ }, [driver, label, instanceIdDirty]);\n+\n+ const driverOption = DRIVER_OPTION_BY_VALUE[driver] ?? DEFAULT_DRIVER_OPTION;\n+ const instanceIdError = validateInstanceId(instanceId, existingIds);\n+ const showInstanceIdError = hasAttemptedSubmit && instanceIdError !== null;\n+ const previewLabel = label.trim() || `${driverOption.label} Workspace`;\n+ const wizardSteps = ["Driver", "Identity", "Config"] as const;\n+ const wizardStepSummaries = [driverOption.label, previewLabel, null] as const;\n+\n+ const getFieldValue = useCallback(\n+ (fieldKey: string) => fieldValues[`${driver}:${fieldKey}`] ?? "",\n+ [driver, fieldValues],\n+ );\n+\n+ const setFieldValue = useCallback(\n+ (fieldKey: string, value: string) => {\n+ setFieldValues((existing) => ({\n+ ...existing,\n+ [`${driver}:${fieldKey}`]: value,\n+ }));\n+ },\n+ [driver],\n+ );\n+\n+ const handleSave = useCallback(() => {\n+ setHasAttemptedSubmit(true);\n+ if (instanceIdError !== null) return;\n+\n+ // Build the config blob from non-empty driver-specific field values.\n+ // Empty strings are dropped so defaults remain in effect on the server.\n+ const config: Record<string, string> = {};\n+ for (const field of driverOption.fields) {\n+ const value = (fieldValues[`${driver}:${field.key}`] ?? "").trim();\n+ if (value.length > 0) config[field.key] = value;\n+ }\n+ const hasConfig = Object.keys(config).length > 0;\n+ const normalizedAccentColor = normalizeProviderAccentColor(accentColor);\n+\n+ const nextInstance: ProviderInstanceConfig = {\n+ driver,\n+ enabled: true,\n+ ...(label.trim().length > 0 ? { displayName: label.trim() } : {}),\n+ ...(normalizedAccentColor ? { accentColor: normalizedAccentColor } : {}),\n+ ...(hasConfig ? { config } : {}),\n+ };\n+ // `ProviderInstanceId.make` revalidates the slug; we\'ve already checked\n+ // it via `validateInstanceId`, but going through the brand constructor\n+ // keeps the type boundary honest and guards against any future drift in\n+ // the slug rules.\n+ const brandedId = ProviderInstanceId.make(instanceId);\n+ const nextMap = {\n+ ...settings.providerInstances,\n+ [brandedId]: nextInstance,\n+ };\n+ try {\n+ updateSettings({ providerInstances: nextMap });\n+ toastManager.add({\n+ type: "success",\n+ title: "Provider instance added",\n+ description: `${driverOption.label} instance \'${instanceId}\' was added.`,\n+ });\n+ onOpenChange(false);\n+ } catch (error) {\n+ toastManager.add({\n+ type: "error",\n+ title: "Could not add provider instance",\n+ description: error instanceof Error ? error.message : "Update failed.",\n+ });\n+ }\n+ }, [\n+ driver,\n+ driverOption,\n+ fieldValues,\n+ instanceId,\n+ instanceIdError,\n+ label,\n+ accentColor,\n+ onOpenChange,\n+ settings.providerInstances,\n+ updateSettings,\n+ ]);\n+\n+ return (\n+ <Dialog open={open} onOpenChange={onOpenChange}>\n+ <DialogPopup className="max-w-xl overflow-hidden">\n+ <div className="flex min-h-0 flex-col overflow-hidden border-foreground/10 bg-background shadow-2xl">\n+ <DialogHeader className="border-b border-border/70 bg-background">\n+ <DialogTitle>Add provider instance</DialogTitle>\n+ <DialogDescription>\n+ Configure an additional provider instance — for example, a second Codex install\n+ pointed at a different workspace.\n+ </DialogDescription>\n+ <div className="grid grid-cols-3 gap-2">\n+ {wizardSteps.map((step, index) => (\n+ <button\n+ key={step}\n+ type="button"\n+ className={cn(\n+ "grid min-w-0 grid-cols-[1rem_minmax(0,1fr)] gap-x-2 rounded-lg border px-3 py-2 text-left transition",\n+ index === wizardStep\n+ ? "border-primary bg-primary/10 ring-1 ring-primary/25"\n+ : index < wizardStep\n+ ? "border-border bg-background"\n+ : "border-border bg-muted/40",\n+ )}\n+ onClick={() => setWizardStep(index)}\n+ >\n+ <span\n+ className={cn(\n+ "row-span-2 mt-0.5 grid size-4 place-items-center rounded-full border",\n+ index < wizardStep\n+ ? "border-primary bg-primary text-primary-foreground"\n+ : index === wizardStep\n+ ? "border-primary bg-background"\n+ : "border-muted-foreground/35 bg-background",\n+ )}\n+ aria-hidden\n+ >\n+ {index < wizardStep ? <CheckIcon className="size-3" /> : null}\n+ </span>\n+ <span className="text-[10px] font-medium uppercase text-muted-foreground">\n+ Step {index + 1}\n+ </span>\n+ <span className="truncate text-xs font-semibold text-foreground">\n+ {step}\n+ {index < wizardStep && wizardStepSummaries[index]\n+ ? `: ${wizardStepSummaries[index]}`\n+ : ""}\n+ </span>\n+ </button>\n+ ))}\n+ </div>\n+ </DialogHeader>\n+\n+ <div\n+ data-slot="dialog-panel"\n+ className="space-y-4 border-b border-border/70 bg-muted/20 px-6 py-5"\n+ >\n+ <div className={cn("grid gap-2", wizardStep !== 0 && "hidden")}>\n+ <span id="add-instance-driver-label" className="text-xs font-medium text-foreground">\n+ Driver\n+ </span>\n+ <RadioGroup\n+ value={driver}\n+ onValueChange={(value) => setDriver(ProviderDriverKind.make(value))}\n+ aria-labelledby="add-instance-driver-label"\n+ className="grid grid-cols-2 gap-2.5"\n+ >\n+ {DRIVER_OPTIONS.map((option) => {\n+ const IconComponent = option.icon;\n+ const isSelected = option.value === driver;\n+ return (\n+ <RadioPrimitive.Root\n+ key={option.value}\n+ value={option.value}\n+ className={cn(\n+ "relative flex cursor-pointer items-center gap-3 rounded-lg border px-3 py-3 text-left outline-none transition-[background-color,border-color,box-shadow]",\n+ "focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background",\n+ isSelected\n+ ? "border-primary bg-background shadow-sm ring-2 ring-primary/35"\n+ : "border-border bg-background hover:border-foreground/20 hover:bg-muted/50",\n+ )}\n+ >\n+ <IconComponent className="size-5 shrink-0" aria-hidden />\n+ <span className="min-w-0 flex-1 truncate text-sm font-medium text-foreground">\n+ {option.label}\n+ </span>\n+ {option.badgeLabel ? (\n+ <Badge variant="warning" size="sm">\n+ {option.badgeLabel}\n+ </Badge>\n+ ) : null}\n+ </RadioPrimitive.Root>\n+ );\n+ })}\n+ {COMING_SOON_DRIVER_OPTIONS.map((option) => {\n+ const IconComponent = option.icon;\n+ return (\n+ <RadioPrimitive.Root\n+ key={option.value}\n+ value={option.value}\n+ disabled\n+ className={cn(\n+ "relative flex cursor-not-allowed items-center gap-3 rounded-lg border border-border bg-background px-3 py-3 text-left opacity-55 outline-none",\n+ )}\n+ >\n+ <IconComponent\n+ className="size-5 shrink-0 text-muted-foreground"\n+ aria-hidden\n+ />\n+ <span className="min-w-0 flex-1 truncate text-sm font-medium text-foreground">\n+ {option.label}\n+ </span>\n+ <Badge variant="warning" size="sm">\n+ Coming Soon\n+ </Badge>\n+ </RadioPrimitive.Root>\n+ );\n+ })}\n+ </RadioGroup>\n+ </div>\n+\n+ <label className={cn("grid gap-2", wizardStep !== 1 && "hidden")}>\n+ <span className="text-xs font-medium text-foreground">Label</span>\n+ <Input\n+ className="bg-background"\n+ placeholder="e.g. Work"\n+ value={label}\n+ onChange={(event) => setLabel(event.target.value)}\n+ />\n+ <span className="text-[11px] text-muted-foreground">\n+ Shown in the provider list. Optional.\n+ </span>\n+ </label>\n+\n+ <label className={cn("grid gap-2", wizardStep !== 1 && "hidden")}>\n+ <span className="text-xs font-medium text-foreground">Instance ID</span>\n+ <Input\n+ className="bg-background"\n+ placeholder={`${driver}_work`}\n+ value={instanceId}\n+ onChange={(event) => {\n+ setInstanceIdDirty(true);\n+ setInstanceId(event.target.value);\n+ }}\n+ aria-invalid={showInstanceIdError}\n+ />\n+ {showInstanceIdError ? (\n+ <span className="text-[11px] text-destructive">{instanceIdError}</span>\n+ ) : (\n+ <span className="text-[11px] text-muted-foreground">\n+ Routing key used by threads and sessions. Letters, digits, \'-\', or \'_\'.\n+ </span>\n+ )}\n+ </label>\n+\n+ <div className={cn("grid gap-2", wizardStep !== 1 && "hidden")}>\n+ <span className="text-xs font-medium text-foreground">Accent color</span>\n+ <div className="flex min-w-0 flex-wrap items-center gap-2">\n+ <input\n+ type="color"\n+ value={normalizeProviderAccentColor(accentColor) ?? PROVIDER_ACCENT_SWATCHES[0]}\n+ onChange={(event) => setAccentColor(event.target.value)}\n+ aria-label="Provider instance accent color"\n+ className="h-8 w-10 cursor-pointer rounded-xl border border-input bg-background p-0.5"\n+ />\n+ <div className="flex flex-wrap gap-1.5">\n+ {PROVIDER_ACCENT_SWATCHES.map((swatch) => {\n+ const selected = accentColor.toLowerCase() === swatch;\n+ return (\n+ <button\n+ key={swatch}\n+ type="button"\n+ className={cn(\n+ "size-6 cursor-pointer rounded-full border transition",\n+ selected\n+ ? "scale-110 border-foreground ring-2 ring-ring ring-offset-1 ring-offset-background"\n+ : "border-black/10 hover:scale-105 dark:border-white/20",\n+ )}\n+ style={{ backgroundColor: swatch }}\n+ onClick={() => setAccentColor(swatch)}\n+ aria-label={`Use ${swatch} accent`}\n+ />\n+ );\n+ })}\n+ </div>\n+ {accentColor ? (\n+ <Button\n+ type="button"\n+ size="sm"\n+ variant="ghost"\n+ className="h-7 px-2 text-xs text-muted-foreground"\n+ onClick={() => setAccentColor("")}\n+ >\n+ Clear\n+ </Button>\n+ ) : null}\n+ </div>\n+ <span className="text-[11px] text-muted-foreground">\n+ Optional marker shown in the picker.\n+ </span>\n+ </div>\n+\n+ {driverOption.fields.length > 0 ? (\n+ <div className={cn("grid gap-4", wizardStep !== 2 && "hidden")}>\n+ {driverOption.fields.map((field) => (\n+ <label key={field.key} className="grid gap-1.5">\n+ <span className="text-xs font-medium text-foreground">{field.label}</span>\n+ <Input\n+ className="bg-background"\n+ type={field.type === "password" ? "password" : undefined}\n+ autoComplete={field.type === "password" ? "off" : undefined}\n+ placeholder={field.placeholder}\n+ value={getFieldValue(field.key)}\n+ onChange={(event) => setFieldValue(field.key, event.target.value)}\n+ spellCheck={false}\n+ />\n+ {field.description ? (\n+ <span className="text-[11px] text-muted-foreground">{field.description}</span>\n+ ) : null}\n+ </label>\n+ ))}\n+ </div>\n+ ) : wizardStep === 2 ? (\n+ <div className="grid gap-2">\n+ <p className="text-sm text-muted-foreground">\n+ This driver has no required configuration. You can add the instance now.\n+ </p>\n+ </div>\n+ ) : null}\n+ </div>\n+\n+ <DialogFooter className="border-t bg-background">\n+ <Button\n+ variant="outline"\n+ size="sm"\n+ onClick={() => {\n+ if (wizardStep === 0) {\n+ onOpenChange(false);\n+ return;\n+ }\n+ setWizardStep((step) => Math.max(0, step - 1));\n+ }}\n+ >\n+ {wizardStep === 0 ? "Cancel" : "Back"}\n+ </Button>\n+ {wizardStep < wizardSteps.length - 1 ? (\n+ <Button size="sm" onClick={() => setWizardStep((step) => Math.min(2, step + 1))}>\n+ Next\n+ </Button>\n+ ) : (\n+ <Button size="sm" onClick={handleSave}>\n+ Add instance\n+ </Button>\n+ )}\n+ </DialogFooter>\n+ </div>\n+ </DialogPopup>\n+ </Dialog>\n+ );\n+}\ndiff --git a/apps/web/src/components/settings/ProviderInstanceCard.test.ts b/apps/web/src/components/settings/ProviderInstanceCard.test.ts\nnew file mode 100644\nindex 0000000000..1aa062c9d6\n--- /dev/null\n+++ b/apps/web/src/components/settings/ProviderInstanceCard.test.ts\n@@ -0,0 +1,36 @@\n+import { describe, expect, it } from "vitest";\n+import type { ServerProviderModel } from "@t3tools/contracts";\n+\n+import { deriveProviderModelsForDisplay } from "./ProviderInstanceCard";\n+\n+describe("deriveProviderModelsForDisplay", () => {\n+ it("uses current config custom models instead of stale live custom rows", () => {\n+ const liveModels: ReadonlyArray<ServerProviderModel> = [\n+ {\n+ slug: "server-model",\n+ name: "Server Model",\n+ isCustom: false,\n+ capabilities: null,\n+ },\n+ {\n+ slug: "removed-custom",\n+ name: "Removed Custom",\n+ isCustom: true,\n+ capabilities: null,\n+ },\n+ {\n+ slug: "kept-custom",\n+ name: "Kept Custom",\n+ isCustom: true,\n+ capabilities: null,\n+ },\n+ ];\n+\n+ expect(\n+ deriveProviderModelsForDisplay({\n+ liveModels,\n+ customModels: ["kept-custom"],\n+ }).map((model) => model.slug),\n+ ).toEqual(["server-model", "kept-custom"]);\n+ });\n+});\ndiff --git a/apps/web/src/components/settings/ProviderInstanceCard.tsx b/apps/web/src/components/settings/ProviderInstanceCard.tsx\nnew file mode 100644\nindex 0000000000..21889412c3\n--- /dev/null\n+++ b/apps/web/src/components/settings/ProviderInstanceCard.tsx\n@@ -0,0 +1,814 @@\n+"use client";\n+\n+import { ChevronDownIcon, PlusIcon, Trash2Icon, XIcon } from "lucide-react";\n+import { useEffect, useMemo, useState } from "react";\n+import {\n+ isProviderDriverKind,\n+ type ProviderInstanceConfig,\n+ type ProviderInstanceEnvironmentVariable,\n+ type ProviderInstanceId,\n+ type ProviderDriverKind,\n+ type ServerProvider,\n+ type ServerProviderModel,\n+} from "@t3tools/contracts";\n+\n+import { cn } from "../../lib/utils";\n+import { normalizeProviderAccentColor } from "../../providerInstances";\n+import { Badge } from "../ui/badge";\n+import { Button } from "../ui/button";\n+import { Collapsible, CollapsibleContent } from "../ui/collapsible";\n+import { DraftInput } from "../ui/draft-input";\n+import { Switch } from "../ui/switch";\n+import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";\n+import type { DriverOption } from "./providerDriverMeta";\n+import { ProviderModelsSection } from "./ProviderModelsSection";\n+import { ProviderInstanceIcon } from "../chat/ProviderInstanceIcon";\n+import {\n+ PROVIDER_STATUS_STYLES,\n+ getProviderSummary,\n+ getProviderVersionLabel,\n+ type ProviderStatusKey,\n+} from "./providerStatus";\n+\n+const PROVIDER_ACCENT_SWATCHES = [\n+ "#2563eb",\n+ "#16a34a",\n+ "#ea580c",\n+ "#dc2626",\n+ "#7c3aed",\n+ "#0891b2",\n+] as const;\n+\n+const ENVIRONMENT_VARIABLE_NAME_PATTERN = /^[a-zA-Z_][a-zA-Z0-9_]*$/;\n+\n+const REDACTED_EMAIL_ALPHABET = "abcdefghijklmnopqrstuvwxyz0123456789";\n+\n+let environmentVariableDraftId = 0;\n+const nextEnvironmentVariableDraftId = () => `provider-env-${environmentVariableDraftId++}`;\n+\n+type EnvironmentDraftRow = {\n+ readonly id: string;\n+ readonly name: string;\n+ readonly value: string;\n+ readonly sensitive: boolean;\n+ readonly valueRedacted?: boolean;\n+};\n+\n+function makeEnvironmentDraftRow(\n+ variable: ProviderInstanceEnvironmentVariable,\n+ index: number,\n+): EnvironmentDraftRow {\n+ return {\n+ id: `${index}:${variable.name}`,\n+ name: variable.name,\n+ value: variable.value,\n+ sensitive: variable.sensitive,\n+ ...(variable.valueRedacted !== undefined ? { valueRedacted: variable.valueRedacted } : {}),\n+ };\n+}\n+\n+function redactedEmailPlaceholder(email: string): string {\n+ let state = 0x811c9dc5;\n+ for (let index = 0; index < email.length; index += 1) {\n+ state ^= email.charCodeAt(index);\n+ state = Math.imul(state, 0x01000193);\n+ }\n+\n+ const nextChar = () => {\n+ state = Math.imul(state ^ (state >>> 13), 0x85ebca6b);\n+ state = Math.imul(state ^ (state >>> 16), 0xc2b2ae35);\n+ return REDACTED_EMAIL_ALPHABET[Math.abs(state) % REDACTED_EMAIL_ALPHABET.length] ?? "x";\n+ };\n+\n+ return Array.from(email, (char) => {\n+ if (char === "@" || char === "." || char === "-" || char === "_") return char;\n+ return nextChar();\n+ }).join("");\n+}\n+\n+/**\n+ * Read a string value at `key` from the opaque per-driver config blob.\n+ * Returns an empty string when the key is missing or the stored value is\n+ * not a string. The permissive shape reflects that `config` is\n+ * `Schema.Unknown` at the contract boundary — forks may populate it with\n+ * non-string values that the built-in UI should round-trip without\n+ * throwing.\n+ */\n+function readConfigString(config: unknown, key: string): string {\n+ if (config === null || typeof config !== "object") return "";\n+ const value = (config as Record<string, unknown>)[key];\n+ return typeof value === "string" ? value : "";\n+}\n+\n+/**\n+ * Read a string[] at `key` from the opaque config blob, filtering out\n+ * non-string entries. Used for `customModels`, which is always typed as\n+ * `string[]` by the concrete driver schemas but arrives here as\n+ * `Schema.Unknown`.\n+ */\n+function readConfigStringArray(config: unknown, key: string): ReadonlyArray<string> {\n+ if (config === null || typeof config !== "object") return [];\n+ const value = (config as Record<string, unknown>)[key];\n+ if (!Array.isArray(value)) return [];\n+ return value.filter((entry): entry is string => typeof entry === "string");\n+}\n+\n+/**\n+ * Produce the next config blob after setting `key` to `value`. Empty\n+ * strings drop the key so server defaults stay in effect, mirroring the\n+ * save-time normalization in `AddProviderInstanceDialog`. Returns\n+ * `undefined` when the resulting blob has no keys, which matches\n+ * `ProviderInstanceConfig.config` being optional.\n+ *\n+ * Non-string values already stored in the blob are carried through\n+ * verbatim so fork-owned fields survive edits made through this UI.\n+ */\n+function nextConfigBlobWithString(\n+ config: unknown,\n+ key: string,\n+ value: string,\n+): Record<string, unknown> | undefined {\n+ const base: Record<string, unknown> =\n+ config !== null && typeof config === "object" ? { ...(config as Record<string, unknown>) } : {};\n+ const trimmed = value.trim();\n+ if (trimmed.length > 0) {\n+ base[key] = value;\n+ } else {\n+ delete base[key];\n+ }\n+ return Object.keys(base).length > 0 ? base : undefined;\n+}\n+\n+/**\n+ * Set `key` to an arbitrary value on the opaque config blob. Unlike\n+ * `nextConfigBlobWithString`, does not drop empty-looking values — the\n+ * caller is responsible for deciding whether an empty array / empty\n+ * object should be stored explicitly (e.g. `customModels: []` is a\n+ * meaningful "user cleared their custom list" state distinct from\n+ * "driver default").\n+ */\n+function nextConfigBlobWithValue(\n+ config: unknown,\n+ key: string,\n+ value: unknown,\n+): Record<string, unknown> {\n+ const base: Record<string, unknown> =\n+ config !== null && typeof config === "object" ? { ...(config as Record<string, unknown>) } : {};\n+ base[key] = value;\n+ return base;\n+}\n+\n+export function deriveProviderModelsForDisplay(input: {\n+ readonly liveModels: ReadonlyArray<ServerProviderModel> | undefined;\n+ readonly customModels: ReadonlyArray<string>;\n+}): ReadonlyArray<ServerProviderModel> {\n+ const liveCustomModelsBySlug = new Map(\n+ (input.liveModels ?? [])\n+ .filter((model) => model.isCustom)\n+ .map((model) => [model.slug, model] as const),\n+ );\n+ const serverModels = input.liveModels?.filter((model) => !model.isCustom) ?? [];\n+ const customModels = input.customModels.map(\n+ (slug) =>\n+ liveCustomModelsBySlug.get(slug) ?? {\n+ slug,\n+ name: slug,\n+ isCustom: true,\n+ capabilities: null,\n+ },\n+ );\n+ return [...serverModels, ...customModels];\n+}\n+\n+function ProviderAuthEmail(props: {\n+ readonly email: string | undefined;\n+ readonly prefix?: string;\n+ readonly separator?: boolean;\n+}) {\n+ const [revealed, setRevealed] = useState(false);\n+ const trimmed = props.email?.trim();\n+ const redacted = useMemo(() => (trimmed ? redactedEmailPlaceholder(trimmed) : ""), [trimmed]);\n+ if (!trimmed) return null;\n+\n+ return (\n+ <span className="inline-flex min-w-0 items-center gap-1.5">\n+ {props.separator ? <span aria-hidden>·</span> : null}\n+ {props.prefix ? <span className="text-muted-foreground/80">{props.prefix}</span> : null}\n+ <Tooltip>\n+ <TooltipTrigger\n+ render={\n+ <button\n+ type="button"\n+ className={cn(\n+ "min-w-0 cursor-pointer rounded-sm font-mono text-[11px] leading-none transition hover:text-foreground",\n+ revealed ? "text-muted-foreground" : "select-none text-muted-foreground blur-[2px]",\n+ )}\n+ onClick={() => setRevealed((value) => !value)}\n+ aria-label={revealed ? "Hide account email" : "Reveal account email"}\n+ >\n+ {revealed ? trimmed : redacted}\n+ </button>\n+ }\n+ />\n+ <TooltipPopup side="top">\n+ {revealed ? "Click to hide email" : "Click to reveal email"}\n+ </TooltipPopup>\n+ </Tooltip>\n+ </span>\n+ );\n+}\n+\n+function ProviderAccentColorPicker(props: {\n+ readonly displayName: string;\n+ readonly value: string | undefined;\n+ readonly onCommit: (value: string) => void;\n+}) {\n+ const [draft, setDraft] = useState(props.value ?? "");\n+ const [isEditing, setIsEditing] = useState(false);\n+ const draftColor = normalizeProviderAccentColor(draft);\n+\n+ useEffect(() => {\n+ if (isEditing) return;\n+ setDraft(props.value ?? "");\n+ }, [isEditing, props.value]);\n+\n+ const commitDraft = () => {\n+ setIsEditing(false);\n+ props.onCommit(draftColor ?? "");\n+ };\n+\n+ const commitSwatch = (swatch: string) => {\n+ setIsEditing(false);\n+ setDraft(swatch);\n+ props.onCommit(swatch);\n+ };\n+\n+ return (\n+ <div className="grid gap-2">\n+ <span className="text-xs font-medium text-foreground">Accent color</span>\n+ <div className="flex min-w-0 flex-wrap items-center gap-2">\n+ <input\n+ type="color"\n+ value={draftColor ?? PROVIDER_ACCENT_SWATCHES[0]}\n+ onFocus={() => setIsEditing(true)}\n+ onInput={(event) => {\n+ setIsEditing(true);\n+ setDraft(event.currentTarget.value);\n+ }}\n+ onChange={(event) => {\n+ setIsEditing(true);\n+ setDraft(event.currentTarget.value);\n+ }}\n+ onBlur={commitDraft}\n+ aria-label={`Accent color for ${props.displayName}`}\n+ className="h-8 w-10 cursor-pointer rounded border border-input bg-background p-0.5"\n+ />\n+ <div className="flex flex-wrap gap-1.5">\n+ {PROVIDER_ACCENT_SWATCHES.map((swatch) => {\n+ const selected = draftColor?.toLowerCase() === swatch;\n+ return (\n+ <button\n+ key={swatch}\n+ type="button"\n+ className={cn(\n+ "size-6 cursor-pointer rounded-full border transition",\n+ selected\n+ ? "border-foreground ring-2 ring-ring ring-offset-1 ring-offset-background"\n+ : "border-black/10 hover:scale-105 dark:border-white/20",\n+ )}\n+ style={{ backgroundColor: swatch }}\n+ onClick={() => commitSwatch(swatch)}\n+ aria-label={`Use ${swatch} accent`}\n+ />\n+ );\n+ })}\n+ </div>\n+ {draftColor ? (\n+ <Button\n+ type="button"\n+ size="sm"\n+ variant="ghost"\n+ className="h-7 px-2 text-xs text-muted-foreground"\n+ onClick={() => {\n+ setIsEditing(false);\n+ setDraft("");\n+ props.onCommit("");\n+ }}\n+ >\n+ Clear\n+ </Button>\n+ ) : null}\n+ </div>\n+ <span className="text-xs text-muted-foreground">\n+ Used to distinguish this instance in picker rails and model lists.\n+ </span>\n+ </div>\n+ );\n+}\n+\n+function ProviderEnvironmentSection(props: {\n+ readonly environment: ReadonlyArray<ProviderInstanceEnvironmentVariable>;\n+ readonly onChange: (environment: ReadonlyArray<ProviderInstanceEnvironmentVariable>) => void;\n+}) {\n+ const [rows, setRows] = useState<ReadonlyArray<EnvironmentDraftRow>>(() =>\n+ props.environment.map(makeEnvironmentDraftRow),\n+ );\n+\n+ useEffect(() => {\n+ setRows(props.environment.map(makeEnvironmentDraftRow));\n+ }, [props.environment]);\n+\n+ const publishRows = (nextRows: ReadonlyArray<EnvironmentDraftRow>) => {\n+ const published: ProviderInstanceEnvironmentVariable[] = [];\n+ for (const row of nextRows) {\n+ const name = row.name.trim();\n+ if (!ENVIRONMENT_VARIABLE_NAME_PATTERN.test(name)) {\n+ if (\n+ name.length > 0 ||\n+ row.value.length > 0 ||\n+ row.sensitive !== true ||\n+ row.valueRedacted !== undefined\n+ ) {\n+ return;\n+ }\n+ continue;\n+ }\n+ const { id: _id, ...rest } = row;\n+ published.push({ ...rest, name });\n+ }\n+ props.onChange(published);\n+ };\n+\n+ const updateVariable = (id: string, patch: Partial<Omit<EnvironmentDraftRow, "id">>) => {\n+ const nextRows = rows.map((row) =>\n+ row.id === id\n+ ? {\n+ ...row,\n+ ...patch,\n+ ...(patch.value !== undefined ? { valueRedacted: false } : {}),\n+ }\n+ : row,\n+ );\n+ setRows(nextRows);\n+ publishRows(nextRows);\n+ };\n+\n+ const removeVariable = (id: string) => {\n+ const nextRows = rows.filter((row) => row.id !== id);\n+ setRows(nextRows);\n+ publishRows(nextRows);\n+ };\n+\n+ return (\n+ <div className="grid gap-2">\n+ <div className="flex items-center justify-between gap-3">\n+ <span className="text-xs font-medium text-foreground">Environment variables</span>\n+ <Button\n+ type="button"\n+ size="sm"\n+ variant="outline"\n+ className="h-7 gap-1.5 px-2 text-xs"\n+ onClick={() =>\n+ setRows([\n+ ...rows,\n+ {\n+ id: nextEnvironmentVariableDraftId(),\n+ name: "",\n+ value: "",\n+ sensitive: true,\n+ },\n+ ])\n+ }\n+ >\n+ <PlusIcon className="size-3" />\n+ Add\n+ </Button>\n+ </div>\n+ {rows.length === 0 ? (\n+ <p className="text-xs text-muted-foreground">\n+ Add variables to pass API keys, base URLs, or other per-instance CLI settings.\n+ </p>\n+ ) : (\n+ <div className="grid gap-2">\n+ {rows.map((variable, index) => (\n+ <div\n+ key={variable.id}\n+ className="grid gap-2 rounded-md border border-border/70 bg-muted/20 p-2 sm:grid-cols-[minmax(0,1fr)_minmax(0,1.4fr)_auto_auto] sm:items-center"\n+ >\n+ <DraftInput\n+ value={variable.name}\n+ onCommit={(name) => updateVariable(variable.id, { name: name.trim() })}\n+ placeholder="VARIABLE_NAME"\n+ spellCheck={false}\n+ aria-label={`Environment variable name ${index + 1}`}\n+ />\n+ <DraftInput\n+ value={variable.valueRedacted ? "" : variable.value}\n+ onCommit={(value) => updateVariable(variable.id, { value })}\n+ type={variable.sensitive ? "password" : undefined}\n+ autoComplete="off"\n+ placeholder={\n+ variable.valueRedacted ? "Stored secret - enter a new value to replace" : "Value"\n+ }\n+ spellCheck={false}\n+ aria-label={`Environment variable value ${index + 1}`}\n+ />\n+ <label className="inline-flex h-8 items-center gap-2 text-xs text-muted-foreground">\n+ <input\n+ type="checkbox"\n+ className="size-3.5"\n+ checked={variable.sensitive}\n+ onChange={(event) => {\n+ const sensitive = event.currentTarget.checked;\n+ updateVariable(variable.id, {\n+ sensitive,\n+ ...(sensitive && variable.valueRedacted === undefined\n+ ? {}\n+ : { valueRedacted: sensitive ? variable.valueRedacted : false }),\n+ });\n+ }}\n+ />\n+ Sensitive\n+ </label>\n+ <Button\n+ type="button"\n+ size="icon-sm"\n+ variant="ghost"\n+ className="size-8 justify-self-start text-muted-foreground hover:text-destructive sm:justify-self-end"\n+ onClick={() => removeVariable(variable.id)}\n+ aria-label={`Remove environment variable ${variable.name || index + 1}`}\n+ >\n+ <XIcon className="size-3.5" />\n+ </Button>\n+ </div>\n+ ))}\n+ </div>\n+ )}\n+ <span className="text-xs text-muted-foreground">\n+ Sensitive values are stored separately and are not returned to the app after saving.\n+ </span>\n+ </div>\n+ );\n+}\n+\n+interface ProviderInstanceCardProps {\n+ readonly instanceId: ProviderInstanceId;\n+ readonly instance: ProviderInstanceConfig;\n+ readonly driverOption: DriverOption | undefined;\n+ readonly liveProvider: ServerProvider | undefined;\n+ readonly isExpanded: boolean;\n+ readonly onExpandedChange: (open: boolean) => void;\n+ readonly onUpdate: (nextInstance: ProviderInstanceConfig) => void;\n+ /**\n+ * Pass `undefined` to hide the delete button entirely. Built-in default\n+ * instance slots use `undefined` — they can\'t be deleted without losing\n+ * the slot, and their "reset to defaults" affordance lives on an outer\n+ * reset button instead. Explicit `| undefined` in the type accommodates\n+ * `exactOptionalPropertyTypes: true`, where an absent key and\n+ * `{ onDelete: undefined }` are treated as distinct shapes.\n+ */\n+ readonly onDelete?: (() => void) | undefined;\n+ /**\n+ * Optional outer reset button rendered next to the driver icon. Built-in\n+ * default slots supply a reset-to-factory control here; custom instances\n+ * omit it.\n+ */\n+ readonly headerAction?: React.ReactNode | undefined;\n+ readonly hiddenModels: ReadonlyArray<string>;\n+ readonly favoriteModels: ReadonlyArray<string>;\n+ readonly modelOrder: ReadonlyArray<string>;\n+ readonly onHiddenModelsChange: (next: ReadonlyArray<string>) => void;\n+ readonly onFavoriteModelsChange: (next: ReadonlyArray<string>) => void;\n+ readonly onModelOrderChange: (next: ReadonlyArray<string>) => void;\n+}\n+\n+/**\n+ * A single configured provider-instance row in the Providers settings\n+ * section. Used for every row — both the built-in default instance for a\n+ * driver (rendered with `onDelete` omitted) and user-authored custom\n+ * instances (`onDelete` supplied). The only UI difference between the two\n+ * is whether the trash button is visible; every other field (display\n+ * name, config fields, models) behaves identically.\n+ *\n+ * Behavior notes:\n+ * - `liveProvider` is matched by the caller via `instanceId`; when no\n+ * match is available (e.g. the server hasn\'t probed yet, or the\n+ * driver is not shipped by the current build) the card still renders\n+ * with a neutral "checking" summary.\n+ * - Unknown drivers (`driverOption === undefined`) get a read-only\n+ * notice instead of editable fields, so fork instances round-trip\n+ * without accidentally destroying their config.\n+ * - The enabled Switch writes to the envelope\'s `instance.enabled`\n+ * field; the server\'s registry consults this at `entry.enabled ?? true`\n+ * before materializing the instance, and the probe also checks its\n+ * driver-specific `config.enabled`. We treat the envelope flag as the\n+ * single source of truth from the UI — built-in cards used to write\n+ * the inner flag, but on the promotion-to-instance path every edit\n+ * flows through the envelope.\n+ */\n+export function ProviderInstanceCard({\n+ instanceId,\n+ instance,\n+ driverOption,\n+ liveProvider,\n+ isExpanded,\n+ onExpandedChange,\n+ onUpdate,\n+ onDelete,\n+ headerAction,\n+ hiddenModels,\n+ favoriteModels,\n+ modelOrder,\n+ onHiddenModelsChange,\n+ onFavoriteModelsChange,\n+ onModelOrderChange,\n+}: ProviderInstanceCardProps) {\n+ const enabled = instance.enabled ?? true;\n+ // The server-reported status wins when present; otherwise fall back to\n+ // "disabled"/"warning" based on the local `enabled` flag so the dot\n+ // reflects the persisted intent even before the first probe completes.\n+ const statusKey: ProviderStatusKey =\n+ (liveProvider?.status as ProviderStatusKey | undefined) ?? (enabled ? "warning" : "disabled");\n+ const statusStyle = PROVIDER_STATUS_STYLES[statusKey];\n+ const rawSummary = getProviderSummary(liveProvider);\n+ const authEmail = liveProvider?.auth.email;\n+ const hasAuthenticatedEmail =\n+ liveProvider?.auth.status === "authenticated" && Boolean(authEmail?.trim());\n+ const authenticatedDetail = hasAuthenticatedEmail\n+ ? (liveProvider?.auth.label ?? liveProvider?.auth.type ?? null)\n+ : null;\n+ const summary = rawSummary;\n+ const versionLabel = getProviderVersionLabel(liveProvider?.version);\n+ const FallbackIconComponent = driverOption?.icon;\n+ const displayName =\n+ instance.displayName?.trim() || driverOption?.label || String(instance.driver);\n+ const accentColor = normalizeProviderAccentColor(instance.accentColor);\n+\n+ // Narrow `instance.driver` for callers that key on the closed\n+ // `ProviderDriverKind` union (e.g. `normalizeModelSlug`\'s alias table). Custom\n+ // fork drivers pass through as `null` and those callers fall back to\n+ // verbatim behaviour.\n+ const driverKind: ProviderDriverKind | null = isProviderDriverKind(instance.driver)\n+ ? instance.driver\n+ : null;\n+\n+ const customModels = readConfigStringArray(instance.config, "customModels");\n+ // Server-returned models may lag behind settings writes. Treat probe\n+ // models as the source for built-ins only; custom rows come directly\n+ // from the current instance config so add/remove reflects immediately.\n+ const modelsForDisplay = deriveProviderModelsForDisplay({\n+ liveModels: liveProvider?.models,\n+ customModels,\n+ });\n+\n+ const updateDisplayName = (value: string) => {\n+ const trimmed = value.trim();\n+ const { displayName: _omit, ...rest } = instance;\n+ onUpdate(\n+ trimmed.length > 0\n+ ? ({ ...rest, displayName: trimmed } as ProviderInstanceConfig)\n+ : (rest as ProviderInstanceConfig),\n+ );\n+ };\n+\n+ const updateEnabled = (value: boolean) => {\n+ onUpdate({ ...instance, enabled: value });\n+ };\n+\n+ const updateAccentColor = (value: string) => {\n+ const normalized = normalizeProviderAccentColor(value);\n+ const { accentColor: _omit, ...rest } = instance;\n+ onUpdate(\n+ normalized\n+ ? ({ ...rest, accentColor: normalized } as ProviderInstanceConfig)\n+ : (rest as ProviderInstanceConfig),\n+ );\n+ };\n+\n+ const updateConfigField = (key: string, value: string) => {\n+ const nextConfig = nextConfigBlobWithString(instance.config, key, value);\n+ const { config: _omit, ...rest } = instance;\n+ onUpdate(\n+ nextConfig !== undefined\n+ ? ({ ...rest, config: nextConfig } as ProviderInstanceConfig)\n+ : (rest as ProviderInstanceConfig),\n+ );\n+ };\n+\n+ const updateCustomModels = (next: ReadonlyArray<string>) => {\n+ const nextConfig = nextConfigBlobWithValue(instance.config, "customModels", [...next]);\n+ const { config: _omit, ...rest } = instance;\n+ onUpdate({ ...rest, config: nextConfig } as ProviderInstanceConfig);\n+ };\n+\n+ const updateEnvironment = (environment: ReadonlyArray<ProviderInstanceEnvironmentVariable>) => {\n+ const cleaned = environment.filter((variable) => variable.name.trim().length > 0);\n+ const { environment: _omit, ...rest } = instance;\n+ onUpdate(\n+ cleaned.length > 0\n+ ? ({ ...rest, environment: cleaned } as ProviderInstanceConfig)\n+ : (rest as ProviderInstanceConfig),\n+ );\n+ };\n+\n+ return (\n+ <div className="border-t border-border first:border-t-0">\n+ <div className="px-4 py-4 sm:px-5">\n+ <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">\n+ <div className="min-w-0 flex-1 space-y-1">\n+ <div className="flex min-h-5 items-center gap-1.5">\n+ {driverKind ? (\n+ <ProviderInstanceIcon\n+ driverKind={driverKind}\n+ displayName={displayName}\n+ accentColor={accentColor}\n+ showBadge={Boolean(accentColor)}\n+ statusDotClassName={statusStyle.dot}\n+ className="size-5"\n+ iconClassName="size-4 text-foreground/80"\n+ badgeClassName="right-[-0.125rem] bottom-[-0.125rem] h-3 min-w-3 text-[7px]"\n+ />\n+ ) : FallbackIconComponent ? (\n+ <span className="relative inline-flex size-5 shrink-0 items-center justify-center">\n+ <FallbackIconComponent className="size-4 text-foreground/80" aria-hidden />\n+ <span\n+ className={cn(\n+ "pointer-events-none absolute -left-0.5 -top-0.5 size-2 rounded-full ring-2 ring-background",\n+ statusStyle.dot,\n+ )}\n+ aria-hidden\n+ />\n+ </span>\n+ ) : (\n+ <span className={cn("size-2 shrink-0 rounded-full", statusStyle.dot)} />\n+ )}\n+ <h3 className="truncate text-sm font-medium text-foreground">{displayName}</h3>\n+ {String(instanceId) !== String(instance.driver) ? (\n+ // Hide the id chip on a default slot whose id === the\n+ // driver slug — it\'s redundant with the driver icon +\n+ // label. Custom instances (and any instance the user has\n+ // since renamed) keep the chip so their slug stays\n+ // visible for copy/paste + disambiguation.\n+ <code className="truncate rounded bg-muted/60 px-1 py-0.5 text-[10px] text-muted-foreground">\n+ {instanceId}\n+ </code>\n+ ) : null}\n+ {driverOption?.badgeLabel ? (\n+ <Badge variant="warning" size="sm" className="shrink-0">\n+ {driverOption.badgeLabel}\n+ </Badge>\n+ ) : null}\n+ {versionLabel ? (\n+ <code className="text-xs text-muted-foreground">{versionLabel}</code>\n+ ) : null}\n+ {headerAction ? (\n+ <span className="inline-flex h-5 w-5 shrink-0 items-center justify-center">\n+ {headerAction}\n+ </span>\n+ ) : null}\n+ {onDelete ? (\n+ <span className="inline-flex h-5 w-5 shrink-0 items-center justify-center">\n+ <Tooltip>\n+ <TooltipTrigger\n+ render={\n+ <Button\n+ size="icon-xs"\n+ variant="ghost"\n+ className="size-5 rounded-sm p-0 text-muted-foreground hover:text-destructive"\n+ onClick={onDelete}\n+ aria-label={`Delete provider instance ${instanceId}`}\n+ >\n+ <Trash2Icon className="size-3" />\n+ </Button>\n+ }\n+ />\n+ <TooltipPopup side="top">Delete instance</TooltipPopup>\n+ </Tooltip>\n+ </span>\n+ ) : null}\n+ </div>\n+ <p className="flex min-w-0 flex-wrap items-center gap-x-1 text-xs text-muted-foreground">\n+ {hasAuthenticatedEmail ? (\n+ <>\n+ <span>Authenticated as</span>\n+ <ProviderAuthEmail email={authEmail} />\n+ {authenticatedDetail ? <span>· {authenticatedDetail}</span> : null}\n+ </>\n+ ) : (\n+ <>\n+ <span>{summary.headline}</span>\n+ <ProviderAuthEmail email={authEmail} separator prefix="Email" />\n+ </>\n+ )}\n+ {summary.detail ? <span>- {summary.detail}</span> : null}\n+ </p>\n+ </div>\n+ <div className="flex w-full shrink-0 items-center gap-2 sm:w-auto sm:justify-end">\n+ <Button\n+ size="sm"\n+ variant="ghost"\n+ className="h-7 px-2 text-xs text-muted-foreground hover:text-foreground"\n+ onClick={() => onExpandedChange(!isExpanded)}\n+ aria-label={`Toggle ${displayName} details`}\n+ >\n+ <ChevronDownIcon\n+ className={cn("size-3.5 transition-transform", isExpanded && "rotate-180")}\n+ />\n+ </Button>\n+ <Switch\n+ checked={enabled}\n+ onCheckedChange={(checked) => updateEnabled(Boolean(checked))}\n+ aria-label={`Enable ${displayName}`}\n+ />\n+ </div>\n+ </div>\n+ </div>\n+\n+ <Collapsible open={isExpanded} onOpenChange={onExpandedChange}>\n+ <CollapsibleContent>\n+ <div className="space-y-0">\n+ <div className="border-t border-border/60 px-4 py-3 sm:px-5">\n+ <label htmlFor={`provider-instance-${instanceId}-display-name`} className="block">\n+ <span className="text-xs font-medium text-foreground">Display name</span>\n+ <DraftInput\n+ id={`provider-instance-${instanceId}-display-name`}\n+ className="mt-1.5"\n+ value={instance.displayName ?? ""}\n+ onCommit={updateDisplayName}\n+ placeholder={driverOption?.label ?? "Instance label"}\n+ spellCheck={false}\n+ />\n+ <span className="mt-1 block text-xs text-muted-foreground">\n+ Optional label shown in the provider list.\n+ </span>\n+ </label>\n+ </div>\n+\n+ <div className="border-t border-border/60 px-4 py-3 sm:px-5">\n+ <ProviderAccentColorPicker\n+ displayName={displayName}\n+ value={accentColor}\n+ onCommit={updateAccentColor}\n+ />\n+ </div>\n+\n+ <div className="border-t border-border/60 px-4 py-3 sm:px-5">\n+ <ProviderEnvironmentSection\n+ environment={instance.environment ?? []}\n+ onChange={updateEnvironment}\n+ />\n+ </div>\n+\n+ {driverOption?.fields.map((field) => (\n+ <div key={field.key} className="border-t border-border/60 px-4 py-3 sm:px-5">\n+ <label htmlFor={`provider-instance-${instanceId}-${field.key}`} className="block">\n+ <span className="text-xs font-medium text-foreground">{field.label}</span>\n+ <DraftInput\n+ id={`provider-instance-${instanceId}-${field.key}`}\n+ className="mt-1.5"\n+ type={field.type === "password" ? "password" : undefined}\n+ autoComplete={field.type === "password" ? "off" : undefined}\n+ value={readConfigString(instance.config, field.key)}\n+ onCommit={(next) => updateConfigField(field.key, next)}\n+ placeholder={field.placeholder}\n+ spellCheck={false}\n+ />\n+ {field.description ? (\n+ <span className="mt-1 block text-xs text-muted-foreground">\n+ {field.description}\n+ </span>\n+ ) : null}\n+ </label>\n+ </div>\n+ ))}\n+\n+ {driverOption !== undefined ? (\n+ <ProviderModelsSection\n+ instanceId={instanceId}\n+ driverKind={driverKind}\n+ models={modelsForDisplay}\n+ customModels={customModels}\n+ hiddenModels={hiddenModels}\n+ favoriteModels={favoriteModels}\n+ modelOrder={modelOrder}\n+ onChange={updateCustomModels}\n+ onHiddenModelsChange={onHiddenModelsChange}\n+ onFavoriteModelsChange={onFavoriteModelsChange}\n+ onModelOrderChange={onModelOrderChange}\n+ />\n+ ) : (\n+ <div className="border-t border-border/60 px-4 py-3 sm:px-5">\n+ <p className="text-xs text-muted-foreground">\n+ This instance uses a driver (\n+ <code className="text-foreground">{String(instance.driver)}</code>) that is not\n+ shipped with the current build. Configuration values are preserved but cannot be\n+ edited from this surface.\n+ </p>\n+ </div>\n+ )}\n+ </div>\n+ </CollapsibleContent>\n+ </Collapsible>\n+ </div>\n+ );\n+}\ndiff --git a/apps/web/src/components/settings/ProviderModelsSection.tsx b/apps/web/src/components/settings/ProviderModelsSection.tsx\nnew file mode 100644\nindex 0000000000..5db713495b\n--- /dev/null\n+++ b/apps/web/src/components/settings/ProviderModelsSection.tsx\n@@ -0,0 +1,411 @@\n+"use client";\n+\n+import {\n+ ArrowDownIcon,\n+ ArrowUpIcon,\n+ EyeIcon,\n+ EyeOffIcon,\n+ InfoIcon,\n+ PlusIcon,\n+ StarIcon,\n+ XIcon,\n+} from "lucide-react";\n+import { useMemo, useRef, useState } from "react";\n+import {\n+ ProviderDriverKind,\n+ type ProviderInstanceId,\n+ type ServerProviderModel,\n+} from "@t3tools/contracts";\n+import { normalizeModelSlug } from "@t3tools/shared/model";\n+\n+import { cn } from "../../lib/utils";\n+import { sortModelsForProviderInstance } from "../../modelOrdering";\n+import { MAX_CUSTOM_MODEL_LENGTH } from "../../modelSelection";\n+import { Button } from "../ui/button";\n+import { Input } from "../ui/input";\n+import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";\n+\n+/**\n+ * Placeholder text for the "add a custom model" input, keyed by driver\n+ * kind. Mirrors the prior hardcoded switch in `SettingsPanels.tsx` so the\n+ * UX is unchanged — only the owning component has moved.\n+ */\n+const CUSTOM_MODEL_PLACEHOLDER_BY_KIND: Partial<Record<ProviderDriverKind, string>> = {\n+ [ProviderDriverKind.make("codex")]: "gpt-6.7-codex-ultra-preview",\n+ [ProviderDriverKind.make("claudeAgent")]: "claude-sonnet-5-0",\n+ [ProviderDriverKind.make("cursor")]: "claude-sonnet-4-6",\n+ [ProviderDriverKind.make("opencode")]: "openai/gpt-5",\n+};\n+\n+interface ProviderModelsSectionProps {\n+ /** Identifier used to namespace input ids within the DOM. */\n+ readonly instanceId: ProviderInstanceId;\n+ /**\n+ * Driver kind for slug normalization + input placeholder. `null` when\n+ * the section is rendered without enough provider metadata.\n+ */\n+ readonly driverKind: ProviderDriverKind | null;\n+ /**\n+ * The live model list to display. Includes both built-in (probe-reported)\n+ * and custom entries, distinguished by `isCustom`.\n+ */\n+ readonly models: ReadonlyArray<ServerProviderModel>;\n+ /**\n+ * The persisted custom-model slug list for this instance. Drives dedup,\n+ * and is the array we hand back verbatim (with the new slug appended /\n+ * removed) via `onChange`.\n+ */\n+ readonly customModels: ReadonlyArray<string>;\n+ /** Server-returned model slugs hidden from the model picker. */\n+ readonly hiddenModels: ReadonlyArray<string>;\n+ /** Model slugs favorited for this provider instance. */\n+ readonly favoriteModels: ReadonlyArray<string>;\n+ /** Explicit user-authored model ordering for this provider instance. */\n+ readonly modelOrder: ReadonlyArray<string>;\n+ /**\n+ * Commit the new custom-model list. Caller is responsible for routing the\n+ * write to the correct storage (legacy `settings.providers[kind]` vs.\n+ * `providerInstances[id].config`).\n+ */\n+ readonly onChange: (next: ReadonlyArray<string>) => void;\n+ readonly onHiddenModelsChange: (next: ReadonlyArray<string>) => void;\n+ readonly onFavoriteModelsChange: (next: ReadonlyArray<string>) => void;\n+ readonly onModelOrderChange: (next: ReadonlyArray<string>) => void;\n+}\n+\n+/**\n+ * Shared "Models" section rendered on both the built-in default and custom\n+ * provider-instance cards. Owns its own input + error local state so two\n+ * cards on screen don\'t fight over the input value.\n+ *\n+ * Validation mirrors the pre-consolidation logic in `SettingsPanels`:\n+ * - empty / whitespace → "Enter a model slug."\n+ * - duplicate of a non-custom (probe-reported) slug → "already built in"\n+ * - exceeds `MAX_CUSTOM_MODEL_LENGTH` → length error\n+ * - duplicate of an already-saved custom slug → already-saved error\n+ */\n+export function ProviderModelsSection({\n+ instanceId,\n+ driverKind,\n+ models,\n+ customModels,\n+ hiddenModels,\n+ favoriteModels,\n+ modelOrder,\n+ onChange,\n+ onHiddenModelsChange,\n+ onFavoriteModelsChange,\n+ onModelOrderChange,\n+}: ProviderModelsSectionProps) {\n+ const [input, setInput] = useState("");\n+ const [error, setError] = useState<string | null>(null);\n+ const listRef = useRef<HTMLDivElement | null>(null);\n+ const hiddenModelSet = useMemo(() => new Set(hiddenModels), [hiddenModels]);\n+ const favoriteModelSet = useMemo(() => new Set(favoriteModels), [favoriteModels]);\n+ const orderedModels = useMemo(() => {\n+ return sortModelsForProviderInstance(models, {\n+ favoriteModels: favoriteModelSet,\n+ groupFavorites: true,\n+ modelOrder,\n+ });\n+ }, [favoriteModelSet, modelOrder, models]);\n+\n+ const handleAdd = () => {\n+ const normalized = driverKind ? normalizeModelSlug(input, driverKind) : input.trim() || null;\n+ if (!normalized) {\n+ setError("Enter a model slug.");\n+ return;\n+ }\n+ if (models.some((model) => !model.isCustom && model.slug === normalized)) {\n+ setError("That model is already built in.");\n+ return;\n+ }\n+ if (normalized.length > MAX_CUSTOM_MODEL_LENGTH) {\n+ setError(`Model slugs must be ${MAX_CUSTOM_MODEL_LENGTH} characters or less.`);\n+ return;\n+ }\n+ if (customModels.includes(normalized)) {\n+ setError("That custom model is already saved.");\n+ return;\n+ }\n+\n+ onChange([...customModels, normalized]);\n+ setInput("");\n+ setError(null);\n+\n+ // Scroll the new row into view once the DOM reflects the commit.\n+ // `MutationObserver` handles the one-frame gap between `onChange` and\n+ // the `models` prop update; the `requestAnimationFrame` covers the\n+ // common case where the parent updates synchronously.\n+ const el = listRef.current;\n+ if (!el) return;\n+ const scrollToEnd = () => el.scrollTo({ top: el.scrollHeight, behavior: "smooth" });\n+ requestAnimationFrame(scrollToEnd);\n+ const observer = new MutationObserver(() => {\n+ scrollToEnd();\n+ observer.disconnect();\n+ });\n+ observer.observe(el, { childList: true, subtree: true });\n+ setTimeout(() => observer.disconnect(), 2_000);\n+ };\n+\n+ const handleRemove = (slug: string) => {\n+ onChange(customModels.filter((model) => model !== slug));\n+ onModelOrderChange(modelOrder.filter((model) => model !== slug));\n+ onFavoriteModelsChange(favoriteModels.filter((model) => model !== slug));\n+ setError(null);\n+ };\n+\n+ const handleToggleHidden = (slug: string) => {\n+ if (hiddenModelSet.has(slug)) {\n+ onHiddenModelsChange(hiddenModels.filter((model) => model !== slug));\n+ return;\n+ }\n+ onHiddenModelsChange([...hiddenModels, slug]);\n+ };\n+\n+ const handleToggleFavorite = (slug: string) => {\n+ if (favoriteModelSet.has(slug)) {\n+ onFavoriteModelsChange(favoriteModels.filter((model) => model !== slug));\n+ return;\n+ }\n+ onFavoriteModelsChange([...favoriteModels, slug]);\n+ };\n+\n+ const handleMove = (slug: string, direction: -1 | 1) => {\n+ const slugs = orderedModels.map((model) => model.slug);\n+ const index = slugs.indexOf(slug);\n+ const nextIndex = index + direction;\n+ if (index < 0 || nextIndex < 0 || nextIndex >= slugs.length) {\n+ return;\n+ }\n+ const next = [...slugs];\n+ [next[index], next[nextIndex]] = [next[nextIndex]!, next[index]!];\n+ onModelOrderChange(next);\n+ };\n+\n+ return (\n+ <div className="border-t border-border/60 px-4 py-3 sm:px-5">\n+ <div className="text-xs font-medium text-foreground">Models</div>\n+ <div className="mt-1 text-xs text-muted-foreground">\n+ {models.length} model{models.length === 1 ? "" : "s"} available.\n+ </div>\n+ <div ref={listRef} className="mt-2 max-h-40 overflow-y-auto pb-1">\n+ {orderedModels.map((model, index) => {\n+ const caps = model.capabilities;\n+ const capLabels: string[] = [];\n+ const isHidden = !model.isCustom && hiddenModelSet.has(model.slug);\n+ const isFavorite = favoriteModelSet.has(model.slug);\n+ const previousModel = orderedModels[index - 1];\n+ const nextModel = orderedModels[index + 1];\n+ const canMoveUp =\n+ previousModel !== undefined && favoriteModelSet.has(previousModel.slug) === isFavorite;\n+ const canMoveDown =\n+ nextModel !== undefined && favoriteModelSet.has(nextModel.slug) === isFavorite;\n+ const descriptors = caps?.optionDescriptors ?? [];\n+ if (descriptors.some((descriptor) => descriptor.id === "fastMode")) {\n+ capLabels.push("Fast mode");\n+ }\n+ if (descriptors.some((descriptor) => descriptor.id === "thinking")) {\n+ capLabels.push("Thinking");\n+ }\n+ if (\n+ descriptors.some(\n+ (descriptor) =>\n+ descriptor.type === "select" &&\n+ (descriptor.id === "reasoningEffort" ||\n+ descriptor.id === "effort" ||\n+ descriptor.id === "reasoning" ||\n+ descriptor.id === "variant"),\n+ )\n+ ) {\n+ capLabels.push("Reasoning");\n+ }\n+ const hasDetails = capLabels.length > 0 || model.name !== model.slug;\n+\n+ return (\n+ <div\n+ key={`${instanceId}:${model.slug}`}\n+ className={cn(\n+ "grid min-h-7 grid-cols-[minmax(0,1fr)_auto] items-center gap-2 py-1",\n+ isHidden && "text-muted-foreground",\n+ )}\n+ >\n+ <div className="flex min-w-0 items-center gap-1">\n+ <span\n+ className={cn(\n+ "min-w-0 truncate text-xs",\n+ isHidden ? "text-muted-foreground line-through" : "text-foreground/90",\n+ )}\n+ >\n+ {model.name}\n+ </span>\n+ {hasDetails ? (\n+ <Tooltip>\n+ <TooltipTrigger\n+ render={\n+ <Button\n+ size="icon-xs"\n+ variant="ghost"\n+ className="size-5 rounded-sm p-0 text-muted-foreground/60 hover:text-muted-foreground"\n+ aria-label={`Details for ${model.name}`}\n+ />\n+ }\n+ >\n+ <InfoIcon className="size-3" />\n+ </TooltipTrigger>\n+ <TooltipPopup side="top" className="max-w-56">\n+ <div className="space-y-1">\n+ <code className="block text-[11px] text-foreground">{model.slug}</code>\n+ {capLabels.length > 0 ? (\n+ <div className="flex flex-wrap gap-x-2 gap-y-0.5">\n+ {capLabels.map((label) => (\n+ <span key={label} className="text-[10px] text-muted-foreground">\n+ {label}\n+ </span>\n+ ))}\n+ </div>\n+ ) : null}\n+ </div>\n+ </TooltipPopup>\n+ </Tooltip>\n+ ) : null}\n+ {isHidden ? (\n+ <span className="text-[10px] text-muted-foreground">hidden</span>\n+ ) : null}\n+ {model.isCustom ? (\n+ <span className="text-[10px] text-muted-foreground">custom</span>\n+ ) : null}\n+ </div>\n+ <div className="flex shrink-0 items-center gap-0.5">\n+ <Tooltip>\n+ <TooltipTrigger\n+ render={\n+ <Button\n+ size="icon-xs"\n+ variant="ghost"\n+ className={cn(\n+ "size-5 rounded-sm p-0 text-muted-foreground hover:text-foreground",\n+ isFavorite && "text-yellow-500 hover:text-yellow-600",\n+ )}\n+ onClick={() => handleToggleFavorite(model.slug)}\n+ aria-label={`${isFavorite ? "Remove" : "Add"} ${model.name} ${\n+ isFavorite ? "from" : "to"\n+ } favorites`}\n+ />\n+ }\n+ >\n+ <StarIcon className={cn("size-3", isFavorite && "fill-current")} />\n+ </TooltipTrigger>\n+ <TooltipPopup side="top">\n+ {isFavorite ? "Remove from favorites" : "Add to favorites"}\n+ </TooltipPopup>\n+ </Tooltip>\n+ <Tooltip>\n+ <TooltipTrigger\n+ render={\n+ <Button\n+ size="icon-xs"\n+ variant="ghost"\n+ className="size-5 rounded-sm p-0 text-muted-foreground hover:text-foreground"\n+ disabled={!canMoveUp}\n+ onClick={() => handleMove(model.slug, -1)}\n+ aria-label={`Move ${model.name} up`}\n+ />\n+ }\n+ >\n+ <ArrowUpIcon className="size-3" />\n+ </TooltipTrigger>\n+ <TooltipPopup side="top">Move up</TooltipPopup>\n+ </Tooltip>\n+ <Tooltip>\n+ <TooltipTrigger\n+ render={\n+ <Button\n+ size="icon-xs"\n+ variant="ghost"\n+ className="size-5 rounded-sm p-0 text-muted-foreground hover:text-foreground"\n+ disabled={!canMoveDown}\n+ onClick={() => handleMove(model.slug, 1)}\n+ aria-label={`Move ${model.name} down`}\n+ />\n+ }\n+ >\n+ <ArrowDownIcon className="size-3" />\n+ </TooltipTrigger>\n+ <TooltipPopup side="top">Move down</TooltipPopup>\n+ </Tooltip>\n+ {!model.isCustom ? (\n+ <Tooltip>\n+ <TooltipTrigger\n+ render={\n+ <Button\n+ size="icon-xs"\n+ variant="ghost"\n+ className="size-5 rounded-sm p-0 text-muted-foreground hover:text-foreground"\n+ onClick={() => handleToggleHidden(model.slug)}\n+ aria-label={`${isHidden ? "Show" : "Hide"} ${model.name}`}\n+ />\n+ }\n+ >\n+ {isHidden ? (\n+ <EyeIcon className="size-3" />\n+ ) : (\n+ <EyeOffIcon className="size-3" />\n+ )}\n+ </TooltipTrigger>\n+ <TooltipPopup side="top">\n+ {isHidden ? "Show in picker" : "Hide from picker"}\n+ </TooltipPopup>\n+ </Tooltip>\n+ ) : null}\n+ {model.isCustom ? (\n+ <Tooltip>\n+ <TooltipTrigger\n+ render={\n+ <Button\n+ size="icon-xs"\n+ variant="ghost"\n+ className="size-5 rounded-sm p-0 text-muted-foreground hover:text-foreground"\n+ aria-label={`Remove ${model.slug}`}\n+ onClick={() => handleRemove(model.slug)}\n+ />\n+ }\n+ >\n+ <XIcon className="size-3" />\n+ </TooltipTrigger>\n+ <TooltipPopup side="top">Remove custom model</TooltipPopup>\n+ </Tooltip>\n+ ) : null}\n+ </div>\n+ </div>\n+ );\n+ })}\n+ </div>\n+\n+ <div className="mt-3 flex flex-col gap-2 sm:flex-row">\n+ <Input\n+ id={`provider-instance-${instanceId}-custom-model`}\n+ value={input}\n+ onChange={(event) => {\n+ setInput(event.target.value);\n+ if (error) setError(null);\n+ }}\n+ onKeyDown={(event) => {\n+ if (event.key !== "Enter") return;\n+ event.preventDefault();\n+ handleAdd();\n+ }}\n+ placeholder={driverKind ? CUSTOM_MODEL_PLACEHOLDER_BY_KIND[driverKind] : "model-slug"}\n+ spellCheck={false}\n+ />\n+ <Button className="shrink-0" variant="outline" onClick={handleAdd}>\n+ <PlusIcon className="size-3.5" />\n+ Add\n+ </Button>\n+ </div>\n+\n+ {error ? <p className="mt-2 text-xs text-destructive">{error}</p> : null}\n+ </div>\n+ );\n+}\ndiff --git a/apps/web/src/components/settings/SettingsPanels.browser.tsx b/apps/web/src/components/settings/SettingsPanels.browser.tsx\nindex b508b29b77..4406d1607c 100644\n--- a/apps/web/src/components/settings/SettingsPanels.browser.tsx\n+++ b/apps/web/src/components/settings/SettingsPanels.browser.tsx\n@@ -713,9 +713,13 @@ describe("GeneralSettingsPanel observability", () => {\n \n await page.getByLabelText("Toggle OpenCode details").click();\n \n- await expect.element(page.getByText("OpenCode server URL")).toBeInTheDocument();\n+ // The unified provider-instance card renders field labels without a\n+ // driver-name prefix (the driver name is already shown in the card\n+ // header), so the labels read "Server URL" / "Server password"\n+ // rather than the old "OpenCode server URL" / "OpenCode server password".\n+ await expect.element(page.getByText("Server URL")).toBeInTheDocument();\n await expect.element(page.getByPlaceholder("http://127.0.0.1:4096")).toBeInTheDocument();\n- await expect.element(page.getByText("OpenCode server password")).toBeInTheDocument();\n- await expect.element(page.getByPlaceholder("Server password")).toBeInTheDocument();\n+ await expect.element(page.getByText("Server password")).toBeInTheDocument();\n+ await expect.element(page.getByPlaceholder("Optional")).toBeInTheDocument();\n });\n });\ndiff --git a/apps/web/src/components/settings/SettingsPanels.logic.test.ts b/apps/web/src/components/settings/SettingsPanels.logic.test.ts\nnew file mode 100644\nindex 0000000000..77206d2484\n--- /dev/null\n+++ b/apps/web/src/components/settings/SettingsPanels.logic.test.ts\n@@ -0,0 +1,63 @@\n+import {\n+ DEFAULT_SERVER_SETTINGS,\n+ ProviderDriverKind,\n+ ProviderInstanceId,\n+ type ProviderInstanceConfig,\n+} from "@t3tools/contracts";\n+import { describe, expect, it } from "vitest";\n+import { buildProviderInstanceUpdatePatch } from "./SettingsPanels.logic";\n+\n+describe("buildProviderInstanceUpdatePatch", () => {\n+ it("promotes an edited default provider into providerInstances and resets the legacy provider", () => {\n+ const instanceId = ProviderInstanceId.make("codex");\n+ const nextInstance = {\n+ driver: ProviderDriverKind.make("codex"),\n+ enabled: true,\n+ config: {\n+ binaryPath: "/opt/t3/codex",\n+ },\n+ } satisfies ProviderInstanceConfig;\n+\n+ const patch = buildProviderInstanceUpdatePatch({\n+ settings: {\n+ ...DEFAULT_SERVER_SETTINGS,\n+ providers: {\n+ ...DEFAULT_SERVER_SETTINGS.providers,\n+ codex: {\n+ ...DEFAULT_SERVER_SETTINGS.providers.codex,\n+ binaryPath: "/legacy/codex",\n+ },\n+ },\n+ },\n+ instanceId,\n+ instance: nextInstance,\n+ driver: ProviderDriverKind.make("codex"),\n+ isDefault: true,\n+ });\n+\n+ expect(patch.providerInstances?.[instanceId]).toEqual(nextInstance);\n+ expect(patch.providers?.codex).toEqual(DEFAULT_SERVER_SETTINGS.providers.codex);\n+ });\n+\n+ it("updates custom instances without touching legacy provider settings", () => {\n+ const instanceId = ProviderInstanceId.make("codex_personal");\n+ const nextInstance = {\n+ driver: ProviderDriverKind.make("codex"),\n+ enabled: true,\n+ config: {\n+ homePath: "/Users/example/.codex-personal",\n+ },\n+ } satisfies ProviderInstanceConfig;\n+\n+ const patch = buildProviderInstanceUpdatePatch({\n+ settings: DEFAULT_SERVER_SETTINGS,\n+ instanceId,\n+ instance: nextInstance,\n+ driver: ProviderDriverKind.make("codex"),\n+ isDefault: false,\n+ });\n+\n+ expect(patch.providerInstances?.[instanceId]).toEqual(nextInstance);\n+ expect(patch.providers).toBeUndefined();\n+ });\n+});\ndiff --git a/apps/web/src/components/settings/SettingsPanels.logic.ts b/apps/web/src/components/settings/SettingsPanels.logic.ts\nnew file mode 100644\nindex 0000000000..57a63b7f2a\n--- /dev/null\n+++ b/apps/web/src/components/settings/SettingsPanels.logic.ts\n@@ -0,0 +1,43 @@\n+import type {\n+ ProviderDriverKind,\n+ ProviderInstanceConfig,\n+ ProviderInstanceId,\n+ ServerSettings,\n+ UnifiedSettings,\n+} from "@t3tools/contracts";\n+import { DEFAULT_UNIFIED_SETTINGS } from "@t3tools/contracts/settings";\n+\n+export function buildProviderInstanceUpdatePatch(input: {\n+ readonly settings: Pick<ServerSettings, "providers" | "providerInstances">;\n+ readonly instanceId: ProviderInstanceId;\n+ readonly instance: ProviderInstanceConfig;\n+ readonly driver: ProviderDriverKind;\n+ readonly isDefault: boolean;\n+ readonly textGenerationModelSelection?:\n+ | ServerSettings["textGenerationModelSelection"]\n+ | undefined;\n+}): Partial<UnifiedSettings> {\n+ type LegacyProviderSettings = ServerSettings["providers"][keyof ServerSettings["providers"]];\n+ const legacyProviderDefaults = DEFAULT_UNIFIED_SETTINGS.providers as Record<\n+ string,\n+ LegacyProviderSettings | undefined\n+ >;\n+ const legacyProviderDefault = input.isDefault ? legacyProviderDefaults[input.driver] : undefined;\n+ return {\n+ ...(legacyProviderDefault !== undefined\n+ ? {\n+ providers: {\n+ ...input.settings.providers,\n+ [input.driver]: legacyProviderDefault,\n+ } as ServerSettings["providers"],\n+ }\n+ : {}),\n+ providerInstances: {\n+ ...input.settings.providerInstances,\n+ [input.instanceId]: input.instance,\n+ },\n+ ...(input.textGenerationModelSelection !== undefined\n+ ? { textGenerationModelSelection: input.textGenerationModelSelection }\n+ : {}),\n+ };\n+}\ndiff --git a/apps/web/src/components/settings/SettingsPanels.tsx b/apps/web/src/components/settings/SettingsPanels.tsx\nindex 29d09a5cdc..ebff744ea4 100644\n--- a/apps/web/src/components/settings/SettingsPanels.tsx\n+++ b/apps/web/src/components/settings/SettingsPanels.tsx\n@@ -1,25 +1,17 @@\n-import {\n- ArchiveIcon,\n- ArchiveX,\n- ChevronDownIcon,\n- InfoIcon,\n- LoaderIcon,\n- PlusIcon,\n- RefreshCwIcon,\n- XIcon,\n-} from "lucide-react";\n+import { ArchiveIcon, ArchiveX, LoaderIcon, PlusIcon, RefreshCwIcon } from "lucide-react";\n import { useQueryClient } from "@tanstack/react-query";\n import { type ReactNode, useCallback, useMemo, useRef, useState } from "react";\n import {\n+ defaultInstanceIdForDriver,\n type DesktopUpdateChannel,\n+ ProviderDriverKind,\n+ type ProviderInstanceConfig,\n+ type ProviderInstanceId,\n type ScopedThreadRef,\n- type ProviderKind,\n- type ServerProvider,\n- type ServerProviderModel,\n } from "@t3tools/contracts";\n import { scopeThreadRef } from "@t3tools/client-runtime";\n import { DEFAULT_UNIFIED_SETTINGS } from "@t3tools/contracts/settings";\n-import { createModelSelection, normalizeModelSlug } from "@t3tools/shared/model";\n+import { createModelSelection } from "@t3tools/shared/model";\n import { Equal } from "effect";\n import { APP_VERSION } from "../../branding";\n import {\n@@ -41,10 +33,13 @@ import {\n useDesktopUpdateState,\n } from "../../lib/desktopUpdateReactQuery";\n import {\n- MAX_CUSTOM_MODEL_LENGTH,\n- getCustomModelOptionsByProvider,\n+ getCustomModelOptionsByInstance,\n resolveAppModelSelectionState,\n } from "../../modelSelection";\n+import {\n+ deriveProviderInstanceEntries,\n+ sortProviderInstanceEntries,\n+} from "../../providerInstances";\n import { ensureLocalApi, readLocalApi } from "../../localApi";\n import { useShallow } from "zustand/react/shallow";\n import {\n@@ -53,16 +48,17 @@ import {\n useStore,\n } from "../../store";\n import { formatRelativeTime, formatRelativeTimeLabel } from "../../timestampFormat";\n-import { cn } from "../../lib/utils";\n-import { Badge } from "../ui/badge";\n import { Button } from "../ui/button";\n-import { Collapsible, CollapsibleContent } from "../ui/collapsible";\n import { Empty, EmptyDescription, EmptyHeader, EmptyMedia, EmptyTitle } from "../ui/empty";\n-import { Input } from "../ui/input";\n+import { DraftInput } from "../ui/draft-input";\n import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";\n import { Switch } from "../ui/switch";\n import { stackedThreadToast, toastManager } from "../ui/toast";\n import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";\n+import { AddProviderInstanceDialog } from "./AddProviderInstanceDialog";\n+import { ProviderInstanceCard } from "./ProviderInstanceCard";\n+import { getDriverOption } from "./providerDriverMeta";\n+import { buildProviderInstanceUpdatePatch } from "./SettingsPanels.logic";\n import {\n SettingResetButton,\n SettingsPageContainer,\n@@ -77,7 +73,6 @@ import {\n useServerObservability,\n useServerProviders,\n } from "../../rpc/serverState";\n-import { formatProviderKindLabel } from "../../providerModels";\n \n const THEME_OPTIONS = [\n {\n@@ -100,8 +95,26 @@ const TIMESTAMP_FORMAT_LABELS = {\n "24-hour": "24-hour",\n } as const;\n \n+const DEFAULT_DRIVER_KIND = ProviderDriverKind.make("codex");\n+\n+function withoutProviderInstanceKey<V>(\n+ record: Readonly<Record<ProviderInstanceId, V>> | undefined,\n+ key: ProviderInstanceId,\n+): Record<ProviderInstanceId, V> {\n+ const next = { ...record } as Record<ProviderInstanceId, V>;\n+ delete next[key];\n+ return next;\n+}\n+\n+function withoutProviderInstanceFavorites(\n+ favorites: ReadonlyArray<{ readonly provider: ProviderInstanceId; readonly model: string }>,\n+ instanceId: ProviderInstanceId,\n+) {\n+ return favorites.filter((favorite) => favorite.provider !== instanceId);\n+}\n+\n type InstallProviderSettings = {\n- provider: ProviderKind;\n+ provider: ProviderDriverKind;\n title: string;\n badgeLabel?: string;\n binaryPlaceholder: string;\n@@ -117,7 +130,7 @@ type InstallProviderSettings = {\n \n const PROVIDER_SETTINGS: readonly InstallProviderSettings[] = [\n {\n- provider: "codex",\n+ provider: ProviderDriverKind.make("codex"),\n title: "Codex",\n binaryPlaceholder: "Codex binary path",\n binaryDescription: "Path to the Codex binary",\n@@ -126,20 +139,20 @@ const PROVIDER_SETTINGS: readonly InstallProviderSettings[] = [\n homeDescription: "Optional custom Codex home and config directory.",\n },\n {\n- provider: "claudeAgent",\n+ provider: ProviderDriverKind.make("claudeAgent"),\n title: "Claude",\n binaryPlaceholder: "Claude binary path",\n binaryDescription: "Path to the Claude binary",\n },\n {\n- provider: "cursor",\n+ provider: ProviderDriverKind.make("cursor"),\n title: "Cursor",\n badgeLabel: "Early Access",\n binaryPlaceholder: "Cursor agent binary path",\n binaryDescription: "Path to the Cursor agent binary",\n },\n {\n- provider: "opencode",\n+ provider: ProviderDriverKind.make("opencode"),\n title: "OpenCode",\n binaryPlaceholder: "OpenCode binary path",\n binaryDescription: "Path to the OpenCode binary",\n@@ -151,78 +164,6 @@ const PROVIDER_SETTINGS: readonly InstallProviderSettings[] = [\n },\n ] as const;\n \n-const PROVIDER_STATUS_STYLES = {\n- disabled: {\n- dot: "bg-amber-400",\n- },\n- error: {\n- dot: "bg-destructive",\n- },\n- ready: {\n- dot: "bg-success",\n- },\n- warning: {\n- dot: "bg-warning",\n- },\n-} as const;\n-\n-function getProviderSummary(provider: ServerProvider | undefined) {\n- if (!provider) {\n- return {\n- headline: "Checking provider status",\n- detail: "Waiting for the server to report installation and authentication details.",\n- };\n- }\n- if (!provider.enabled) {\n- return {\n- headline: "Disabled",\n- detail:\n- provider.message ?? "This provider is installed but disabled for new sessions in T3 Code.",\n- };\n- }\n- if (!provider.installed) {\n- return {\n- headline: "Not found",\n- detail: provider.message ?? "CLI not detected on PATH.",\n- };\n- }\n- if (provider.auth.status === "authenticated") {\n- const authLabel = provider.auth.label ?? provider.auth.type;\n- return {\n- headline: authLabel ? `Authenticated · ${authLabel}` : "Authenticated",\n- detail: provider.message ?? null,\n- };\n- }\n- if (provider.auth.status === "unauthenticated") {\n- return {\n- headline: "Not authenticated",\n- detail: provider.message ?? null,\n- };\n- }\n- if (provider.status === "warning") {\n- return {\n- headline: "Needs attention",\n- detail:\n- provider.message ?? "The provider is installed, but the server could not fully verify it.",\n- };\n- }\n- if (provider.status === "error") {\n- return {\n- headline: "Unavailable",\n- detail: provider.message ?? "The provider failed its startup checks.",\n- };\n- }\n- return {\n- headline: "Available",\n- detail: provider.message ?? "Installed and ready, but authentication could not be verified.",\n- };\n-}\n-\n-function getProviderVersionLabel(version: string | null | undefined) {\n- if (!version) return null;\n- return version.startsWith("v") ? version : `v${version}`;\n-}\n-\n function ProviderLastChecked({ lastCheckedAt }: { lastCheckedAt: string | null }) {\n useRelativeTimeTick();\n const lastCheckedRelative = lastCheckedAt ? formatRelativeTime(lastCheckedAt) : null;\n@@ -457,11 +398,31 @@ export function useSettingsRestore(onRestored?: () => void) {\n settings.textGenerationModelSelection ?? null,\n DEFAULT_UNIFIED_SETTINGS.textGenerationModelSelection ?? null,\n );\n- const areProviderSettingsDirty = PROVIDER_SETTINGS.some((providerSettings) => {\n- const currentSettings = settings.providers[providerSettings.provider];\n- const defaultSettings = DEFAULT_UNIFIED_SETTINGS.providers[providerSettings.provider];\n- return !Equal.equals(currentSettings, defaultSettings);\n- });\n+ // A provider surface is "dirty" if either the legacy per-kind\n+ // `settings.providers[kind]` struct differs from defaults (for users\n+ // on pre-migration data) or the new `settings.providerInstances` map\n+ // has any entries (every edit to a default slot promotes it into an\n+ // explicit entry, so any key in that map represents user intent to\n+ // diverge from factory defaults). Checking both keeps the Restore\n+ // Defaults chip accurate throughout the legacy→instance migration.\n+ const areProviderSettingsDirty =\n+ PROVIDER_SETTINGS.some((providerSettings) => {\n+ type LegacyProviderSettings = (typeof settings.providers)[keyof typeof settings.providers];\n+ const currentProviders = settings.providers as Record<\n+ string,\n+ LegacyProviderSettings | undefined\n+ >;\n+ const defaultProviders = DEFAULT_UNIFIED_SETTINGS.providers as Record<\n+ string,\n+ LegacyProviderSettings | undefined\n+ >;\n+ const currentSettings = currentProviders[providerSettings.provider];\n+ const defaultSettings = defaultProviders[providerSettings.provider];\n+ return !Equal.equals(currentSettings, defaultSettings);\n+ }) ||\n+ Object.keys(settings.providerInstances ?? {}).length > 0 ||\n+ Object.keys(settings.providerModelPreferences ?? {}).length > 0 ||\n+ (settings.favorites ?? []).length > 0;\n \n const changedSettingLabels = useMemo(\n () => [\n@@ -540,47 +501,17 @@ export function GeneralSettingsPanel() {\n const [openPathErrorByTarget, setOpenPathErrorByTarget] = useState<\n Partial<Record<"keybindings" | "logsDirectory", string | null>>\n >({});\n- const [openProviderDetails, setOpenProviderDetails] = useState<Record<ProviderKind, boolean>>({\n- codex: Boolean(\n- settings.providers.codex.binaryPath !== DEFAULT_UNIFIED_SETTINGS.providers.codex.binaryPath ||\n- settings.providers.codex.homePath !== DEFAULT_UNIFIED_SETTINGS.providers.codex.homePath ||\n- settings.providers.codex.customModels.length > 0,\n- ),\n- claudeAgent: Boolean(\n- settings.providers.claudeAgent.binaryPath !==\n- DEFAULT_UNIFIED_SETTINGS.providers.claudeAgent.binaryPath ||\n- settings.providers.claudeAgent.customModels.length > 0 ||\n- settings.providers.claudeAgent.launchArgs !== "",\n- ),\n- cursor: Boolean(\n- settings.providers.cursor.binaryPath !==\n- DEFAULT_UNIFIED_SETTINGS.providers.cursor.binaryPath ||\n- settings.providers.cursor.customModels.length > 0,\n- ),\n- opencode: Boolean(\n- settings.providers.opencode.binaryPath !==\n- DEFAULT_UNIFIED_SETTINGS.providers.opencode.binaryPath ||\n- settings.providers.opencode.serverUrl !==\n- DEFAULT_UNIFIED_SETTINGS.providers.opencode.serverUrl ||\n- settings.providers.opencode.serverPassword !==\n- DEFAULT_UNIFIED_SETTINGS.providers.opencode.serverPassword ||\n- settings.providers.opencode.customModels.length > 0,\n- ),\n- });\n- const [customModelInputByProvider, setCustomModelInputByProvider] = useState<\n- Record<ProviderKind, string>\n- >({\n- codex: "",\n- claudeAgent: "",\n- cursor: "",\n- opencode: "",\n- });\n- const [customModelErrorByProvider, setCustomModelErrorByProvider] = useState<\n- Partial<Record<ProviderKind, string | null>>\n- >({});\n const [isRefreshingProviders, setIsRefreshingProviders] = useState(false);\n+ const [isAddInstanceDialogOpen, setIsAddInstanceDialogOpen] = useState(false);\n+ // Collapsible state per provider-instance card, keyed by the instance id.\n+ // `Record<string, boolean>` so we don\'t need to preseed an entry for every\n+ // configured instance — an absent key reads as collapsed. Default-slot\n+ // rows share this state: their id is the driver slug\n+ // (`defaultInstanceIdForDriver(driver)`), which is also `ProviderDriverKind` at\n+ // runtime, so a pre-existing open key for e.g. "codex" persists across\n+ // the legacy/unified render swap.\n+ const [openInstanceDetails, setOpenInstanceDetails] = useState<Record<string, boolean>>({});\n const refreshingRef = useRef(false);\n- const modelListRefs = useRef<Partial<Record<ProviderKind, HTMLDivElement | null>>>({});\n const refreshProviders = useCallback(() => {\n if (refreshingRef.current) return;\n refreshingRef.current = true;\n@@ -603,9 +534,11 @@ export function GeneralSettingsPanel() {\n const visibleProviderSettings = PROVIDER_SETTINGS.filter(\n (providerSettings) =>\n providerSettings.provider !== "cursor" ||\n- serverProviders.some((provider) => provider.provider === "cursor"),\n+ serverProviders.some(\n+ (provider) =>\n+ provider.instanceId === defaultInstanceIdForDriver(ProviderDriverKind.make("cursor")),\n+ ),\n );\n- const codexHomePath = settings.providers.codex.homePath;\n const logsDirectoryPath = observability?.logsDirectoryPath ?? null;\n const diagnosticsDescription = (() => {\n const exports: string[] = [];\n@@ -620,13 +553,21 @@ export function GeneralSettingsPanel() {\n })();\n \n const textGenerationModelSelection = resolveAppModelSelectionState(settings, serverProviders);\n- const textGenProvider = textGenerationModelSelection.provider;\n+ const textGenInstanceId = textGenerationModelSelection.instanceId;\n const textGenModel = textGenerationModelSelection.model;\n const textGenModelOptions = textGenerationModelSelection.options;\n- const gitModelOptionsByProvider = getCustomModelOptionsByProvider(\n+ const gitModelInstanceEntries = sortProviderInstanceEntries(\n+ deriveProviderInstanceEntries(serverProviders),\n+ );\n+ const textGenInstanceEntry = gitModelInstanceEntries.find(\n+ (entry) => entry.instanceId === textGenInstanceId,\n+ );\n+ const textGenProvider: ProviderDriverKind =\n+ textGenInstanceEntry?.driverKind ?? DEFAULT_DRIVER_KIND;\n+ const gitModelOptionsByInstance = getCustomModelOptionsByInstance(\n settings,\n serverProviders,\n- textGenProvider,\n+ textGenInstanceId,\n textGenModel,\n );\n const isGitWritingModelDirty = !Equal.equals(\n@@ -678,140 +619,6 @@ export function GeneralSettingsPanel() {\n const isOpeningKeybindings = openingPathByTarget.keybindings;\n const isOpeningLogsDirectory = openingPathByTarget.logsDirectory;\n \n- const addCustomModel = useCallback(\n- (provider: ProviderKind) => {\n- const customModelInput = customModelInputByProvider[provider];\n- const customModels = settings.providers[provider].customModels;\n- const normalized = normalizeModelSlug(customModelInput, provider);\n- if (!normalized) {\n- setCustomModelErrorByProvider((existing) => ({\n- ...existing,\n- [provider]: "Enter a model slug.",\n- }));\n- return;\n- }\n- if (\n- serverProviders\n- .find((candidate) => candidate.provider === provider)\n- ?.models.some((option) => !option.isCustom && option.slug === normalized)\n- ) {\n- setCustomModelErrorByProvider((existing) => ({\n- ...existing,\n- [provider]: "That model is already built in.",\n- }));\n- return;\n- }\n- if (normalized.length > MAX_CUSTOM_MODEL_LENGTH) {\n- setCustomModelErrorByProvider((existing) => ({\n- ...existing,\n- [provider]: `Model slugs must be ${MAX_CUSTOM_MODEL_LENGTH} characters or less.`,\n- }));\n- return;\n- }\n- if (customModels.includes(normalized)) {\n- setCustomModelErrorByProvider((existing) => ({\n- ...existing,\n- [provider]: "That custom model is already saved.",\n- }));\n- return;\n- }\n-\n- updateSettings({\n- providers: {\n- ...settings.providers,\n- [provider]: {\n- ...settings.providers[provider],\n- customModels: [...customModels, normalized],\n- },\n- },\n- });\n- setCustomModelInputByProvider((existing) => ({\n- ...existing,\n- [provider]: "",\n- }));\n- setCustomModelErrorByProvider((existing) => ({\n- ...existing,\n- [provider]: null,\n- }));\n-\n- const el = modelListRefs.current[provider];\n- if (!el) return;\n- const scrollToEnd = () => el.scrollTo({ top: el.scrollHeight, behavior: "smooth" });\n- requestAnimationFrame(scrollToEnd);\n- const observer = new MutationObserver(() => {\n- scrollToEnd();\n- observer.disconnect();\n- });\n- observer.observe(el, { childList: true, subtree: true });\n- setTimeout(() => observer.disconnect(), 2_000);\n- },\n- [customModelInputByProvider, serverProviders, settings, updateSettings],\n- );\n-\n- const removeCustomModel = useCallback(\n- (provider: ProviderKind, slug: string) => {\n- updateSettings({\n- providers: {\n- ...settings.providers,\n- [provider]: {\n- ...settings.providers[provider],\n- customModels: settings.providers[provider].customModels.filter(\n- (model) => model !== slug,\n- ),\n- },\n- },\n- });\n- setCustomModelErrorByProvider((existing) => ({\n- ...existing,\n- [provider]: null,\n- }));\n- },\n- [settings, updateSettings],\n- );\n-\n- const providerCards = visibleProviderSettings.map((providerSettings) => {\n- const liveProvider = serverProviders.find(\n- (candidate) => candidate.provider === providerSettings.provider,\n- );\n- const providerConfig = settings.providers[providerSettings.provider];\n- const defaultProviderConfig = DEFAULT_UNIFIED_SETTINGS.providers[providerSettings.provider];\n- const statusKey = liveProvider?.status ?? (providerConfig.enabled ? "warning" : "disabled");\n- const summary = getProviderSummary(liveProvider);\n- const models: ReadonlyArray<ServerProviderModel> =\n- liveProvider?.models ??\n- providerConfig.customModels.map((slug) => ({\n- slug,\n- name: slug,\n- isCustom: true,\n- capabilities: null,\n- }));\n-\n- return {\n- provider: providerSettings.provider,\n- title: providerSettings.title,\n- badgeLabel: providerSettings.badgeLabel,\n- binaryPlaceholder: providerSettings.binaryPlaceholder,\n- binaryDescription: providerSettings.binaryDescription,\n- serverUrlPlaceholder: providerSettings.serverUrlPlaceholder,\n- serverUrlDescription: providerSettings.serverUrlDescription,\n- serverPasswordPlaceholder: providerSettings.serverPasswordPlaceholder,\n- serverPasswordDescription: providerSettings.serverPasswordDescription,\n- homePathKey: providerSettings.homePathKey,\n- homePlaceholder: providerSettings.homePlaceholder,\n- homeDescription: providerSettings.homeDescription,\n- binaryPathValue: providerConfig.binaryPath,\n- serverUrlValue: "serverUrl" in providerConfig ? providerConfig.serverUrl : "",\n- serverPasswordValue: "serverPassword" in providerConfig ? providerConfig.serverPassword : "",\n- isDirty: !Equal.equals(providerConfig, defaultProviderConfig),\n- liveProvider,\n- models,\n- providerConfig,\n- statusStyle: PROVIDER_STATUS_STYLES[statusKey],\n- summary,\n- versionLabel: getProviderVersionLabel(liveProvider?.version),\n- };\n- });\n-\n const lastCheckedAt =\n serverProviders.length > 0\n ? serverProviders.reduce(\n@@ -820,6 +627,213 @@ export function GeneralSettingsPanel() {\n )\n : null;\n \n+ /**\n+ * Build the list of rows to render, one per configured instance. Each\n+ * row carries enough context to drive `ProviderInstanceCard` without\n+ * threading storage concerns: whether it\'s a built-in default slot (in\n+ * which case `isDefault` is true, deletion is gated off, and the\n+ * effective envelope may have been synthesized from legacy just for\n+ * this render), the driver kind narrow for the in-card model-slug\n+ * normalization, and whether a reset-to-factory action is warranted.\n+ *\n+ * Ordering mirrors the prior split: visible built-in default slots\n+ * first (one per visible kind), then user-authored custom instances\n+ * grouped by driver after their default sibling, then orphan instances\n+ * whose driver isn\'t in the visible-defaults set.\n+ */\n+ interface InstanceRow {\n+ readonly instanceId: ProviderInstanceId;\n+ readonly instance: ProviderInstanceConfig;\n+ readonly driver: ProviderDriverKind;\n+ /** True for the slot whose id is `defaultInstanceIdForDriver(driver)`. */\n+ readonly isDefault: boolean;\n+ /**\n+ * True when this default slot differs from the factory defaults —\n+ * either through an explicit `providerInstances[defaultId]` entry,\n+ * or through a non-default legacy `settings.providers[kind]` struct\n+ * that we\'re still bridging. Used to show the reset-to-factory\n+ * affordance. Undefined for custom rows (they have a delete button\n+ * instead; "factory defaults" isn\'t meaningful).\n+ */\n+ readonly isDirty?: boolean;\n+ }\n+\n+ const instancesByDriver = new Map<\n+ ProviderDriverKind,\n+ Array<[ProviderInstanceId, ProviderInstanceConfig]>\n+ >();\n+ for (const [rawId, instance] of Object.entries(settings.providerInstances ?? {})) {\n+ const driver = instance.driver;\n+ const list = instancesByDriver.get(driver) ?? [];\n+ list.push([rawId as ProviderInstanceId, instance]);\n+ instancesByDriver.set(driver, list);\n+ }\n+\n+ const defaultSlotIdsBySource = new Set<string>(\n+ visibleProviderSettings.map((providerSettings) =>\n+ String(defaultInstanceIdForDriver(providerSettings.provider)),\n+ ),\n+ );\n+\n+ const rows: InstanceRow[] = [];\n+ const visibleDriverKinds = new Set<ProviderDriverKind>(\n+ visibleProviderSettings.map((providerSettings) => providerSettings.provider),\n+ );\n+\n+ for (const providerSettings of visibleProviderSettings) {\n+ type LegacyProviderSettings = (typeof settings.providers)[keyof typeof settings.providers];\n+ const legacyProviders = settings.providers as Record<string, LegacyProviderSettings>;\n+ const defaultLegacyProviders = DEFAULT_UNIFIED_SETTINGS.providers as Record<\n+ string,\n+ LegacyProviderSettings\n+ >;\n+ const driver = providerSettings.provider;\n+ const defaultInstanceId = defaultInstanceIdForDriver(driver);\n+ // Prefer an explicit `providerInstances[defaultId]` entry when one\n+ // exists (every edit via this UI promotes the default slot into\n+ // that map); fall back to synthesizing one from the legacy\n+ // `settings.providers[kind]` struct so first-time viewers still see\n+ // their persisted config.\n+ const explicitInstance = settings.providerInstances?.[defaultInstanceId];\n+ const legacyConfig = legacyProviders[providerSettings.provider]!;\n+ const defaultLegacyConfig = defaultLegacyProviders[providerSettings.provider]!;\n+ const effectiveInstance: ProviderInstanceConfig =\n+ explicitInstance ??\n+ ({\n+ driver,\n+ enabled: legacyConfig.enabled,\n+ config: legacyConfig,\n+ } satisfies ProviderInstanceConfig);\n+ const isDirty =\n+ explicitInstance !== undefined || !Equal.equals(legacyConfig, defaultLegacyConfig);\n+ rows.push({\n+ instanceId: defaultInstanceId,\n+ instance: effectiveInstance,\n+ driver,\n+ isDefault: true,\n+ isDirty,\n+ });\n+ // Non-default customs for this driver kind follow their default.\n+ for (const [id, instance] of instancesByDriver.get(providerSettings.provider) ?? []) {\n+ if (id === defaultInstanceId) continue;\n+ rows.push({ instanceId: id, instance, driver: instance.driver, isDefault: false });\n+ }\n+ }\n+ // Orphan instances: drivers the visible-defaults list doesn\'t cover\n+ // (e.g. Cursor when the server hasn\'t reported it but the user has\n+ // authored a Cursor instance anyway, or fork drivers not shipped by\n+ // this build). Preserve insertion order within each driver.\n+ for (const [driver, list] of instancesByDriver) {\n+ if (visibleDriverKinds.has(driver)) continue;\n+ for (const [id, instance] of list) {\n+ const isDefaultSlot = defaultSlotIdsBySource.has(String(id));\n+ rows.push({\n+ instanceId: id,\n+ instance,\n+ driver: instance.driver,\n+ isDefault: isDefaultSlot,\n+ });\n+ }\n+ }\n+\n+ const updateProviderInstance = (\n+ row: InstanceRow,\n+ next: ProviderInstanceConfig,\n+ options?: {\n+ readonly textGenerationModelSelection?: Parameters<\n+ typeof buildProviderInstanceUpdatePatch\n+ >[0]["textGenerationModelSelection"];\n+ },\n+ ) => {\n+ updateSettings(\n+ buildProviderInstanceUpdatePatch({\n+ settings,\n+ instanceId: row.instanceId,\n+ instance: next,\n+ driver: row.driver,\n+ isDefault: row.isDefault,\n+ textGenerationModelSelection: options?.textGenerationModelSelection,\n+ }),\n+ );\n+ };\n+\n+ const deleteProviderInstance = (id: ProviderInstanceId) => {\n+ updateSettings({\n+ providerInstances: withoutProviderInstanceKey(settings.providerInstances, id),\n+ providerModelPreferences: withoutProviderInstanceKey(settings.providerModelPreferences, id),\n+ favorites: withoutProviderInstanceFavorites(settings.favorites ?? [], id),\n+ });\n+ };\n+\n+ const updateProviderModelPreferences = (\n+ instanceId: ProviderInstanceId,\n+ next: {\n+ readonly hiddenModels: ReadonlyArray<string>;\n+ readonly modelOrder: ReadonlyArray<string>;\n+ },\n+ ) => {\n+ const hiddenModels = [...new Set(next.hiddenModels.filter((slug) => slug.trim().length > 0))];\n+ const modelOrder = [...new Set(next.modelOrder.filter((slug) => slug.trim().length > 0))];\n+ const rest = withoutProviderInstanceKey(settings.providerModelPreferences, instanceId);\n+ updateSettings({\n+ providerModelPreferences:\n+ hiddenModels.length === 0 && modelOrder.length === 0\n+ ? rest\n+ : {\n+ ...rest,\n+ [instanceId]: {\n+ hiddenModels,\n+ modelOrder,\n+ },\n+ },\n+ });\n+ };\n+\n+ const updateProviderFavoriteModels = (\n+ instanceId: ProviderInstanceId,\n+ nextFavoriteModels: ReadonlyArray<string>,\n+ ) => {\n+ const favoriteModels = [\n+ ...new Set(nextFavoriteModels.map((slug) => slug.trim()).filter((slug) => slug.length > 0)),\n+ ];\n+ updateSettings({\n+ favorites: [\n+ ...withoutProviderInstanceFavorites(settings.favorites ?? [], instanceId),\n+ ...favoriteModels.map((model) => ({ provider: instanceId, model })),\n+ ],\n+ });\n+ };\n+\n+ /**\n+ * Reset a built-in default slot back to factory defaults. Clears both\n+ * the legacy `settings.providers[kind]` struct and any explicit\n+ * `providerInstances[defaultId]` entry that has promoted legacy into\n+ * the new map, so hydration re-synthesizes a clean envelope on next\n+ * load. Safe to call on drivers that have never been edited.\n+ */\n+ const resetDefaultInstance = (driverKind: ProviderDriverKind) => {\n+ type LegacyProviderSettings = (typeof settings.providers)[keyof typeof settings.providers];\n+ const defaultLegacyProviders = DEFAULT_UNIFIED_SETTINGS.providers as Record<\n+ string,\n+ LegacyProviderSettings | undefined\n+ >;\n+ const defaultInstanceId = defaultInstanceIdForDriver(driverKind);\n+ const defaultLegacyProvider = defaultLegacyProviders[driverKind];\n+ if (defaultLegacyProvider === undefined) return;\n+ updateSettings({\n+ providers: {\n+ ...settings.providers,\n+ [driverKind]: defaultLegacyProvider,\n+ } as typeof settings.providers,\n+ providerInstances: withoutProviderInstanceKey(settings.providerInstances, defaultInstanceId),\n+ providerModelPreferences: withoutProviderInstanceKey(\n+ settings.providerModelPreferences,\n+ defaultInstanceId,\n+ ),\n+ favorites: withoutProviderInstanceFavorites(settings.favorites ?? [], defaultInstanceId),\n+ });\n+ };\n+\n return (\n <SettingsPageContainer>\n <SettingsSection title="General">\n@@ -1033,10 +1047,10 @@ export function GeneralSettingsPanel() {\n ) : null\n }\n control={\n- <Input\n+ <DraftInput\n className="w-full sm:w-72"\n value={settings.addProjectBaseDirectory}\n- onChange={(event) => updateSettings({ addProjectBaseDirectory: event.target.value })}\n+ onCommit={(next) => updateSettings({ addProjectBaseDirectory: next })}\n placeholder="~/"\n spellCheck={false}\n aria-label="Add project base directory"\n@@ -1115,19 +1129,19 @@ export function GeneralSettingsPanel() {\n control={\n <div className="flex flex-wrap items-center justify-end gap-1.5">\n <ProviderModelPicker\n- provider={textGenProvider}\n+ activeInstanceId={textGenInstanceId}\n model={textGenModel}\n lockedProvider={null}\n- providers={serverProviders}\n- modelOptionsByProvider={gitModelOptionsByProvider}\n+ instanceEntries={gitModelInstanceEntries}\n+ modelOptionsByInstance={gitModelOptionsByInstance}\n triggerVariant="outline"\n triggerClassName="min-w-0 max-w-none shrink-0 text-foreground/90 hover:text-foreground"\n- onProviderModelChange={(provider, model) => {\n+ onInstanceModelChange={(instanceId, model) => {\n updateSettings({\n textGenerationModelSelection: resolveAppModelSelectionState(\n {\n ...settings,\n- textGenerationModelSelection: createModelSelection(provider, model),\n+ textGenerationModelSelection: createModelSelection(instanceId, model),\n },\n serverProviders,\n ),\n@@ -1137,8 +1151,11 @@ export function GeneralSettingsPanel() {\n <TraitsPicker\n provider={textGenProvider}\n models={\n- serverProviders.find((provider) => provider.provider === textGenProvider)\n- ?.models ?? []\n+ // Use the exact instance\'s models (rather than the\n+ // first-kind-match) so a custom text-gen instance like\n+ // `codex_personal` gets its own model list, not the\n+ // default Codex one.\n+ textGenInstanceEntry?.models ?? []\n }\n model={textGenModel}\n prompt=""\n@@ -1153,7 +1170,7 @@ export function GeneralSettingsPanel() {\n {\n ...settings,\n textGenerationModelSelection: createModelSelection(\n- textGenProvider,\n+ textGenInstanceId,\n textGenModel,\n nextOptions,\n ),\n@@ -1173,6 +1190,22 @@ export function GeneralSettingsPanel() {\n headerAction={\n <div className="flex items-center gap-1.5">\n <ProviderLastChecked lastCheckedAt={lastCheckedAt} />\n+ <Tooltip>\n+ <TooltipTrigger\n+ render={\n+ <Button\n+ size="icon-xs"\n+ variant="ghost"\n+ className="size-5 rounded-sm p-0 text-muted-foreground hover:text-foreground"\n+ onClick={() => setIsAddInstanceDialogOpen(true)}\n+ aria-label="Add provider instance"\n+ >\n+ <PlusIcon className="size-3" />\n+ </Button>\n+ }\n+ />\n+ <TooltipPopup side="top">Add provider instance</TooltipPopup>\n+ </Tooltip>\n <Tooltip>\n <TooltipTrigger\n render={\n@@ -1197,447 +1230,90 @@ export function GeneralSettingsPanel() {\n </div>\n }\n >\n- {providerCards.map((providerCard) => {\n- const customModelInput = customModelInputByProvider[providerCard.provider];\n- const customModelError = customModelErrorByProvider[providerCard.provider] ?? null;\n- const providerDisplayName =\n- providerCard.liveProvider?.displayName?.trim() ||\n- providerCard.title ||\n- formatProviderKindLabel(providerCard.provider);\n-\n+ {rows.map((row) => {\n+ const driverOption = getDriverOption(row.driver);\n+ const liveProvider = serverProviders.find(\n+ (candidate) => candidate.instanceId === row.instanceId,\n+ );\n+ const modelPreferences = settings.providerModelPreferences?.[row.instanceId] ?? {\n+ hiddenModels: [],\n+ modelOrder: [],\n+ };\n+ const favoriteModels = (settings.favorites ?? [])\n+ .filter((favorite) => favorite.provider === row.instanceId)\n+ .map((favorite) => favorite.model);\n+ const resetLabel = driverOption?.label ?? String(row.driver);\n+ const headerAction =\n+ row.isDefault && row.isDirty ? (\n+ <SettingResetButton\n+ label={`${resetLabel} provider settings`}\n+ onClick={() => resetDefaultInstance(row.driver)}\n+ />\n+ ) : null;\n return (\n- <div key={providerCard.provider} className="border-t border-border first:border-t-0">\n- <div className="px-4 py-4 sm:px-5">\n- <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">\n- <div className="min-w-0 flex-1 space-y-1">\n- <div className="flex min-h-5 items-center gap-1.5">\n- <span\n- className={cn("size-2 shrink-0 rounded-full", providerCard.statusStyle.dot)}\n- />\n- <h3 className="text-sm font-medium text-foreground">{providerDisplayName}</h3>\n- {providerCard.badgeLabel ? (\n- <Badge variant="warning" size="sm" className="shrink-0">\n- {providerCard.badgeLabel}\n- </Badge>\n- ) : null}\n- {providerCard.versionLabel ? (\n- <code className="text-xs text-muted-foreground">\n- {providerCard.versionLabel}\n- </code>\n- ) : null}\n- <span className="inline-flex h-5 w-5 shrink-0 items-center justify-center">\n- {providerCard.isDirty ? (\n- <SettingResetButton\n- label={`${providerDisplayName} provider settings`}\n- onClick={() => {\n- updateSettings({\n- providers: {\n- ...settings.providers,\n- [providerCard.provider]:\n- DEFAULT_UNIFIED_SETTINGS.providers[providerCard.provider],\n- },\n- });\n- setCustomModelErrorByProvider((existing) => ({\n- ...existing,\n- [providerCard.provider]: null,\n- }));\n- }}\n- />\n- ) : null}\n- </span>\n- </div>\n- <p className="text-xs text-muted-foreground">\n- {providerCard.summary.headline}\n- {providerCard.summary.detail ? ` - ${providerCard.summary.detail}` : null}\n- </p>\n- </div>\n- <div className="flex w-full shrink-0 items-center gap-2 sm:w-auto sm:justify-end">\n- <Button\n- size="sm"\n- variant="ghost"\n- className="h-7 px-2 text-xs text-muted-foreground hover:text-foreground"\n- onClick={() =>\n- setOpenProviderDetails((existing) => ({\n- ...existing,\n- [providerCard.provider]: !existing[providerCard.provider],\n- }))\n- }\n- aria-label={`Toggle ${providerDisplayName} details`}\n- >\n- <ChevronDownIcon\n- className={cn(\n- "size-3.5 transition-transform",\n- openProviderDetails[providerCard.provider] && "rotate-180",\n- )}\n- />\n- </Button>\n- <Switch\n- checked={providerCard.providerConfig.enabled}\n- onCheckedChange={(checked) => {\n- const isDisabling = !checked;\n- const shouldClearModelSelection =\n- isDisabling && textGenProvider === providerCard.provider;\n- updateSettings({\n- providers: {\n- ...settings.providers,\n- [providerCard.provider]: {\n- ...settings.providers[providerCard.provider],\n- enabled: Boolean(checked),\n- },\n- },\n- ...(shouldClearModelSelection\n- ? {\n- textGenerationModelSelection:\n- DEFAULT_UNIFIED_SETTINGS.textGenerationModelSelection,\n- }\n- : {}),\n- });\n- }}\n- aria-label={`Enable ${providerDisplayName}`}\n- />\n- </div>\n- </div>\n- </div>\n-\n- <Collapsible\n- open={openProviderDetails[providerCard.provider]}\n- onOpenChange={(open) =>\n- setOpenProviderDetails((existing) => ({\n- ...existing,\n- [providerCard.provider]: open,\n- }))\n+ <ProviderInstanceCard\n+ key={row.instanceId}\n+ instanceId={row.instanceId}\n+ instance={row.instance}\n+ driverOption={driverOption}\n+ liveProvider={liveProvider}\n+ isExpanded={openInstanceDetails[row.instanceId] ?? false}\n+ onExpandedChange={(open) =>\n+ setOpenInstanceDetails((existing) => ({\n+ ...existing,\n+ [row.instanceId]: open,\n+ }))\n+ }\n+ onUpdate={(next) => {\n+ // When the user disables the exact instance the text-gen\n+ // selection points at, fall back to the global default so we\n+ // don\'t leave the selection dangling on a disabled instance.\n+ // Prior kind-level behavior cleared on any kind-matching\n+ // disable; instance-level addressing makes this narrower and\n+ // more accurate (other instances of the same kind stay\n+ // untouched).\n+ const wasEnabled = row.instance.enabled ?? true;\n+ const isDisabling = next.enabled === false && wasEnabled;\n+ const shouldClearTextGen = isDisabling && textGenInstanceId === row.instanceId;\n+ if (shouldClearTextGen) {\n+ updateProviderInstance(row, next, {\n+ textGenerationModelSelection:\n+ DEFAULT_UNIFIED_SETTINGS.textGenerationModelSelection,\n+ });\n+ } else {\n+ updateProviderInstance(row, next);\n }\n- >\n- <CollapsibleContent>\n- <div className="space-y-0">\n- <div className="border-t border-border/60 px-4 py-3 sm:px-5">\n- <label\n- htmlFor={`provider-install-${providerCard.provider}-binary-path`}\n- className="block"\n- >\n- <span className="text-xs font-medium text-foreground">\n- {providerDisplayName} binary path\n- </span>\n- <Input\n- id={`provider-install-${providerCard.provider}-binary-path`}\n- className="mt-1.5"\n- value={providerCard.binaryPathValue}\n- onChange={(event) =>\n- updateSettings({\n- providers: {\n- ...settings.providers,\n- [providerCard.provider]: {\n- ...settings.providers[providerCard.provider],\n- binaryPath: event.target.value,\n- },\n- },\n- })\n- }\n- placeholder={providerCard.binaryPlaceholder}\n- spellCheck={false}\n- />\n- <span className="mt-1 block text-xs text-muted-foreground">\n- {providerCard.binaryDescription}\n- </span>\n- </label>\n- </div>\n-\n- {providerCard.serverUrlPlaceholder ? (\n- <div className="border-t border-border/60 px-4 py-3 sm:px-5">\n- <label\n- htmlFor={`provider-install-${providerCard.provider}-server-url`}\n- className="block"\n- >\n- <span className="text-xs font-medium text-foreground">\n- {providerDisplayName} server URL\n- </span>\n- <Input\n- id={`provider-install-${providerCard.provider}-server-url`}\n- className="mt-1.5"\n- value={providerCard.serverUrlValue}\n- onChange={(event) =>\n- updateSettings({\n- providers: {\n- ...settings.providers,\n- [providerCard.provider]: {\n- ...settings.providers[providerCard.provider],\n- ...(providerCard.provider === "opencode"\n- ? { serverUrl: event.target.value }\n- : {}),\n- },\n- },\n- })\n- }\n- placeholder={providerCard.serverUrlPlaceholder}\n- spellCheck={false}\n- />\n- {providerCard.serverUrlDescription ? (\n- <span className="mt-1 block text-xs text-muted-foreground">\n- {providerCard.serverUrlDescription}\n- </span>\n- ) : null}\n- </label>\n- </div>\n- ) : null}\n-\n- {providerCard.serverPasswordPlaceholder ? (\n- <div className="border-t border-border/60 px-4 py-3 sm:px-5">\n- <label\n- htmlFor={`provider-install-${providerCard.provider}-server-password`}\n- className="block"\n- >\n- <span className="text-xs font-medium text-foreground">\n- {providerDisplayName} server password\n- </span>\n- <Input\n- id={`provider-install-${providerCard.provider}-server-password`}\n- className="mt-1.5"\n- type="password"\n- autoComplete="off"\n- value={providerCard.serverPasswordValue}\n- onChange={(event) =>\n- updateSettings({\n- providers: {\n- ...settings.providers,\n- [providerCard.provider]: {\n- ...settings.providers[providerCard.provider],\n- ...(providerCard.provider === "opencode"\n- ? { serverPassword: event.target.value }\n- : {}),\n- },\n- },\n- })\n- }\n- placeholder={providerCard.serverPasswordPlaceholder}\n- spellCheck={false}\n- />\n- {providerCard.serverPasswordDescription ? (\n- <span className="mt-1 block text-xs text-muted-foreground">\n- {providerCard.serverPasswordDescription}\n- </span>\n- ) : null}\n- </label>\n- </div>\n- ) : null}\n-\n- {providerCard.homePathKey ? (\n- <div className="border-t border-border/60 px-4 py-3 sm:px-5">\n- <label\n- htmlFor={`provider-install-${providerCard.homePathKey}`}\n- className="block"\n- >\n- <span className="text-xs font-medium text-foreground">\n- CODEX_HOME path\n- </span>\n- <Input\n- id={`provider-install-${providerCard.homePathKey}`}\n- className="mt-1.5"\n- value={codexHomePath}\n- onChange={(event) =>\n- updateSettings({\n- providers: {\n- ...settings.providers,\n- codex: {\n- ...settings.providers.codex,\n- homePath: event.target.value,\n- },\n- },\n- })\n- }\n- placeholder={providerCard.homePlaceholder}\n- spellCheck={false}\n- />\n- {providerCard.homeDescription ? (\n- <span className="mt-1 block text-xs text-muted-foreground">\n- {providerCard.homeDescription}\n- </span>\n- ) : null}\n- </label>\n- </div>\n- ) : null}\n-\n- {providerCard.provider === "claudeAgent" ? (\n- <div className="border-t border-border/60 px-4 py-3 sm:px-5">\n- <label htmlFor="provider-install-claudeAgent-launch-args" className="block">\n- <span className="text-xs font-medium text-foreground">\n- Launch arguments\n- </span>\n- <Input\n- id="provider-install-claudeAgent-launch-args"\n- className="mt-1.5"\n- value={settings.providers.claudeAgent.launchArgs}\n- onChange={(event) =>\n- updateSettings({\n- providers: {\n- ...settings.providers,\n- claudeAgent: {\n- ...settings.providers.claudeAgent,\n- launchArgs: event.target.value,\n- },\n- },\n- })\n- }\n- placeholder="e.g. --chrome"\n- spellCheck={false}\n- />\n- <span className="mt-1 block text-xs text-muted-foreground">\n- Additional CLI arguments passed to Claude Code on session start.\n- </span>\n- </label>\n- </div>\n- ) : null}\n-\n- <div className="border-t border-border/60 px-4 py-3 sm:px-5">\n- <div className="text-xs font-medium text-foreground">Models</div>\n- <div className="mt-1 text-xs text-muted-foreground">\n- {providerCard.models.length} model\n- {providerCard.models.length === 1 ? "" : "s"} available.\n- </div>\n- <div\n- ref={(el) => {\n- modelListRefs.current[providerCard.provider] = el;\n- }}\n- className="mt-2 max-h-40 overflow-y-auto pb-1"\n- >\n- {providerCard.models.map((model) => {\n- const caps = model.capabilities;\n- const capLabels: string[] = [];\n- const descriptors = caps?.optionDescriptors ?? [];\n- if (descriptors.some((descriptor) => descriptor.id === "fastMode")) {\n- capLabels.push("Fast mode");\n- }\n- if (descriptors.some((descriptor) => descriptor.id === "thinking")) {\n- capLabels.push("Thinking");\n- }\n- if (\n- descriptors.some(\n- (descriptor) =>\n- descriptor.type === "select" &&\n- (descriptor.id === "reasoningEffort" ||\n- descriptor.id === "effort" ||\n- descriptor.id === "reasoning" ||\n- descriptor.id === "variant"),\n- )\n- ) {\n- capLabels.push("Reasoning");\n- }\n- const hasDetails = capLabels.length > 0 || model.name !== model.slug;\n-\n- return (\n- <div\n- key={`${providerCard.provider}:${model.slug}`}\n- className="flex items-center gap-2 py-1"\n- >\n- <span className="min-w-0 truncate text-xs text-foreground/90">\n- {model.name}\n- </span>\n- {hasDetails ? (\n- <Tooltip>\n- <TooltipTrigger\n- render={\n- <button\n- type="button"\n- className="shrink-0 text-muted-foreground/40 transition-colors hover:text-muted-foreground"\n- aria-label={`Details for ${model.name}`}\n- />\n- }\n- >\n- <InfoIcon className="size-3" />\n- </TooltipTrigger>\n- <TooltipPopup side="top" className="max-w-56">\n- <div className="space-y-1">\n- <code className="block text-[11px] text-foreground">\n- {model.slug}\n- </code>\n- {capLabels.length > 0 ? (\n- <div className="flex flex-wrap gap-x-2 gap-y-0.5">\n- {capLabels.map((label) => (\n- <span\n- key={label}\n- className="text-[10px] text-muted-foreground"\n- >\n- {label}\n- </span>\n- ))}\n- </div>\n- ) : null}\n- </div>\n- </TooltipPopup>\n- </Tooltip>\n- ) : null}\n- {model.isCustom ? (\n- <div className="ml-auto flex shrink-0 items-center gap-1.5">\n- <span className="text-[10px] text-muted-foreground">custom</span>\n- <button\n- type="button"\n- className="text-muted-foreground transition-colors hover:text-foreground"\n- aria-label={`Remove ${model.slug}`}\n- onClick={() =>\n- removeCustomModel(providerCard.provider, model.slug)\n- }\n- >\n- <XIcon className="size-3" />\n- </button>\n- </div>\n- ) : null}\n- </div>\n- );\n- })}\n- </div>\n-\n- <div className="mt-3 flex flex-col gap-2 sm:flex-row">\n- <Input\n- id={`custom-model-${providerCard.provider}`}\n- value={customModelInput}\n- onChange={(event) => {\n- const value = event.target.value;\n- setCustomModelInputByProvider((existing) => ({\n- ...existing,\n- [providerCard.provider]: value,\n- }));\n- if (customModelError) {\n- setCustomModelErrorByProvider((existing) => ({\n- ...existing,\n- [providerCard.provider]: null,\n- }));\n- }\n- }}\n- onKeyDown={(event) => {\n- if (event.key !== "Enter") return;\n- event.preventDefault();\n- addCustomModel(providerCard.provider);\n- }}\n- placeholder={\n- providerCard.provider === "codex"\n- ? "gpt-6.7-codex-ultra-preview"\n- : providerCard.provider === "opencode"\n- ? "openai/gpt-5"\n- : "claude-sonnet-5-0"\n- }\n- spellCheck={false}\n- />\n- <Button\n- className="shrink-0"\n- variant="outline"\n- onClick={() => addCustomModel(providerCard.provider)}\n- >\n- <PlusIcon className="size-3.5" />\n- Add\n- </Button>\n- </div>\n-\n- {customModelError ? (\n- <p className="mt-2 text-xs text-destructive">{customModelError}</p>\n- ) : null}\n- </div>\n- </div>\n- </CollapsibleContent>\n- </Collapsible>\n- </div>\n+ }}\n+ onDelete={row.isDefault ? undefined : () => deleteProviderInstance(row.instanceId)}\n+ headerAction={headerAction}\n+ hiddenModels={modelPreferences.hiddenModels}\n+ favoriteModels={favoriteModels}\n+ modelOrder={modelPreferences.modelOrder}\n+ onHiddenModelsChange={(hiddenModels) =>\n+ updateProviderModelPreferences(row.instanceId, {\n+ ...modelPreferences,\n+ hiddenModels,\n+ })\n+ }\n+ onFavoriteModelsChange={(favoriteModels) =>\n+ updateProviderFavoriteModels(row.instanceId, favoriteModels)\n+ }\n+ onModelOrderChange={(modelOrder) =>\n+ updateProviderModelPreferences(row.instanceId, {\n+ ...modelPreferences,\n+ modelOrder,\n+ })\n+ }\n+ />\n );\n })}\n </SettingsSection>\n \n+ <AddProviderInstanceDialog\n+ open={isAddInstanceDialogOpen}\n+ onOpenChange={setIsAddInstanceDialogOpen}\n+ />\n+\n <SettingsSection title="Advanced">\n <SettingsRow\n title="Keybindings"\ndiff --git a/apps/web/src/components/settings/providerDriverMeta.ts b/apps/web/src/components/settings/providerDriverMeta.ts\nnew file mode 100644\nindex 0000000000..38f8039647\n--- /dev/null\n+++ b/apps/web/src/components/settings/providerDriverMeta.ts\n@@ -0,0 +1,151 @@\n+import { ProviderDriverKind } from "@t3tools/contracts";\n+import { ClaudeAI, CursorIcon, type Icon, OpenAI, OpenCodeIcon } from "../Icons";\n+\n+/**\n+ * A single editable field exposed on a provider instance. `key` must match\n+ * the corresponding driver config schema in\n+ * `packages/contracts/src/settings.ts` — values are merged into the saved\n+ * `ProviderInstanceConfig.config` blob (or the legacy\n+ * `ServerSettings.providers[kind]` struct) under this key verbatim.\n+ */\n+export interface DriverFieldDef {\n+ readonly key: string;\n+ readonly label: string;\n+ readonly placeholder?: string;\n+ readonly description?: string;\n+ readonly type?: "text" | "password";\n+}\n+\n+/**\n+ * Presentation + editable-field metadata for a registered driver. Shared\n+ * between the Add-Instance dialog and the per-instance settings card so\n+ * both surfaces offer the same keys for the same driver.\n+ */\n+export interface DriverOption {\n+ readonly value: ProviderDriverKind;\n+ readonly label: string;\n+ readonly icon: Icon;\n+ readonly fields: readonly DriverFieldDef[];\n+ /**\n+ * Optional short label rendered as a `variant="warning"` badge next to\n+ * the instance title. Used to flag drivers that still ship under an\n+ * early-access or preview gate — the flag is a property of the driver\n+ * kind (not a specific instance), so every instance of that driver —\n+ * built-in default or custom — advertises the same marker.\n+ */\n+ readonly badgeLabel?: string;\n+}\n+\n+export const DRIVER_OPTIONS: readonly DriverOption[] = [\n+ {\n+ value: ProviderDriverKind.make("codex"),\n+ label: "Codex",\n+ icon: OpenAI,\n+ fields: [\n+ {\n+ key: "binaryPath",\n+ label: "Binary path",\n+ placeholder: "codex",\n+ description: "Path to the Codex binary used by this instance.",\n+ },\n+ {\n+ key: "homePath",\n+ label: "CODEX_HOME path",\n+ placeholder: "~/.codex",\n+ description: "Custom Codex home and config directory.",\n+ },\n+ {\n+ key: "shadowHomePath",\n+ label: "Shadow home path",\n+ placeholder: "~/.codex-t3/personal",\n+ description:\n+ "Account-specific Codex home. Keeps auth.json separate while sharing state from CODEX_HOME.",\n+ },\n+ ],\n+ },\n+ {\n+ value: ProviderDriverKind.make("claudeAgent"),\n+ label: "Claude",\n+ icon: ClaudeAI,\n+ fields: [\n+ {\n+ key: "binaryPath",\n+ label: "Binary path",\n+ placeholder: "claude",\n+ description: "Path to the Claude binary used by this instance.",\n+ },\n+ {\n+ key: "homePath",\n+ label: "Claude HOME path",\n+ placeholder: "~",\n+ description:\n+ "Custom HOME used when running this Claude instance. Keeps .claude.json and .claude separate.",\n+ },\n+ {\n+ key: "launchArgs",\n+ label: "Launch arguments",\n+ placeholder: "e.g. --chrome",\n+ description: "Additional CLI arguments passed on session start.",\n+ },\n+ ],\n+ },\n+ {\n+ value: ProviderDriverKind.make("cursor"),\n+ label: "Cursor",\n+ icon: CursorIcon,\n+ badgeLabel: "Early Access",\n+ fields: [\n+ {\n+ key: "binaryPath",\n+ label: "Binary path",\n+ placeholder: "agent",\n+ description: "Path to the Cursor agent binary.",\n+ },\n+ {\n+ key: "apiEndpoint",\n+ label: "API endpoint",\n+ placeholder: "https://…",\n+ description: "Override the Cursor API endpoint for this instance.",\n+ },\n+ ],\n+ },\n+ {\n+ value: ProviderDriverKind.make("opencode"),\n+ label: "OpenCode",\n+ icon: OpenCodeIcon,\n+ fields: [\n+ {\n+ key: "binaryPath",\n+ label: "Binary path",\n+ placeholder: "opencode",\n+ description: "Path to the OpenCode binary.",\n+ },\n+ {\n+ key: "serverUrl",\n+ label: "Server URL",\n+ placeholder: "http://127.0.0.1:4096",\n+ description: "Leave blank to let T3 Code spawn the server when needed.",\n+ },\n+ {\n+ key: "serverPassword",\n+ label: "Server password",\n+ placeholder: "Optional",\n+ type: "password",\n+ description: "Stored in plain text on disk.",\n+ },\n+ ],\n+ },\n+];\n+\n+export const DRIVER_OPTION_BY_VALUE: Partial<Record<ProviderDriverKind, DriverOption>> =\n+ Object.fromEntries(DRIVER_OPTIONS.map((option) => [option.value, option]));\n+\n+/**\n+ * Look up the driver metadata for an instance\'s `driver` field. Accepts\n+ * Returns `undefined` for fork / unknown drivers so callers can decide how\n+ * to render them — typically by falling back to a generic card.\n+ */\n+export function getDriverOption(driver: ProviderDriverKind | undefined): DriverOption | undefined {\n+ if (driver === undefined) return undefined;\n+ return DRIVER_OPTION_BY_VALUE[driver];\n+}\ndiff --git a/apps/web/src/components/settings/providerStatus.ts b/apps/web/src/components/settings/providerStatus.ts\nnew file mode 100644\nindex 0000000000..d437399da2\n--- /dev/null\n+++ b/apps/web/src/components/settings/providerStatus.ts\n@@ -0,0 +1,91 @@\n+import type { ServerProvider } from "@t3tools/contracts";\n+\n+/**\n+ * Visual treatment for each server-reported provider status. Centralized so\n+ * the default-driver card and per-instance cards share the same language.\n+ */\n+export const PROVIDER_STATUS_STYLES = {\n+ disabled: {\n+ dot: "bg-amber-400",\n+ },\n+ error: {\n+ dot: "bg-destructive",\n+ },\n+ ready: {\n+ dot: "bg-success",\n+ },\n+ warning: {\n+ dot: "bg-warning",\n+ },\n+} as const;\n+\n+export type ProviderStatusKey = keyof typeof PROVIDER_STATUS_STYLES;\n+\n+/**\n+ * Derive the headline + detail copy shown under a provider\'s name in the\n+ * settings page. Prefers `provider.message` for server-supplied detail and\n+ * falls back to generic phrasing when the server has not yet reported any\n+ * state — which happens before the first probe or when an instance names a\n+ * driver this build does not ship.\n+ */\n+export function getProviderSummary(provider: ServerProvider | undefined) {\n+ if (!provider) {\n+ return {\n+ headline: "Checking provider status",\n+ detail: "Waiting for the server to report installation and authentication details.",\n+ };\n+ }\n+ if (!provider.enabled) {\n+ return {\n+ headline: "Disabled",\n+ detail:\n+ provider.message ?? "This provider is installed but disabled for new sessions in T3 Code.",\n+ };\n+ }\n+ if (!provider.installed) {\n+ return {\n+ headline: "Not found",\n+ detail: provider.message ?? "CLI not detected on PATH.",\n+ };\n+ }\n+ if (provider.auth.status === "authenticated") {\n+ const authLabel = provider.auth.label ?? provider.auth.type;\n+ return {\n+ headline: authLabel ? `Authenticated · ${authLabel}` : "Authenticated",\n+ detail: provider.message ?? null,\n+ };\n+ }\n+ if (provider.auth.status === "unauthenticated") {\n+ return {\n+ headline: "Not authenticated",\n+ detail: provider.message ?? null,\n+ };\n+ }\n+ if (provider.status === "warning") {\n+ return {\n+ headline: "Needs attention",\n+ detail:\n+ provider.message ?? "The provider is installed, but the server could not fully verify it.",\n+ };\n+ }\n+ if (provider.status === "error") {\n+ return {\n+ headline: "Unavailable",\n+ detail: provider.message ?? "The provider failed its startup checks.",\n+ };\n+ }\n+ return {\n+ headline: "Available",\n+ detail: provider.message ?? "Installed and ready, but authentication could not be verified.",\n+ };\n+}\n+\n+/**\n+ * Normalize a version string for display. Adds the `v` prefix when the\n+ * driver reported a bare version (e.g. `1.2.3`) so cards render\n+ * consistently regardless of driver.\n+ */\n+export function getProviderVersionLabel(version: string | null | undefined) {\n+ if (!version) return null;\n+ return version.startsWith("v") ? version : `v${version}`;\n+}\ndiff --git a/apps/web/src/components/ui/draft-input.tsx b/apps/web/src/components/ui/draft-input.tsx\nnew file mode 100644\nindex 0000000000..a81d5d9baf\n--- /dev/null\n+++ b/apps/web/src/components/ui/draft-input.tsx\n@@ -0,0 +1,21 @@\n+"use client";\n+\n+import { useCommitOnBlur } from "~/hooks/useCommitOnBlur";\n+import { Input, type InputProps } from "./input";\n+\n+export type DraftInputProps = Omit<InputProps, "value" | "onChange" | "defaultValue"> & {\n+ readonly value: string;\n+ readonly onCommit: (next: string) => void;\n+};\n+\n+/**\n+ * Text `<Input>` that buffers keystrokes locally and invokes `onCommit`\n+ * only when the user finishes editing (blur or Enter). Prevents each\n+ * keystroke from triggering a settings-wide re-render or a server RPC\n+ * round-trip, which otherwise makes fields backed by a server-hydrated\n+ * value feel laggy.\n+ */\n+export function DraftInput({ value, onCommit, ...rest }: DraftInputProps) {\n+ const bag = useCommitOnBlur(value, onCommit);\n+ return <Input {...rest} {...bag} />;\n+}\ndiff --git a/apps/web/src/composerDraftStore.test.ts b/apps/web/src/composerDraftStore.test.ts\nindex 9416b42ff9..67f754bd71 100644\n--- a/apps/web/src/composerDraftStore.test.ts\n+++ b/apps/web/src/composerDraftStore.test.ts\n@@ -6,17 +6,29 @@ import {\n } from "@t3tools/client-runtime";\n import * as Schema from "effect/Schema";\n import {\n+ defaultInstanceIdForDriver,\n EnvironmentId,\n ProjectId,\n+ ProviderDriverKind,\n+ ProviderInstanceId,\n ThreadId,\n type ModelSelection,\n- type ProviderKind,\n type ProviderOptionSelection,\n } from "@t3tools/contracts";\n import { createModelSelection } from "@t3tools/shared/model";\n \n+// The composer draft\'s `modelSelectionByProvider` and\n+// `stickyModelSelectionByProvider` maps are keyed by `ProviderInstanceId`\n+// in production; these aliases keep the legacy-key migration tests concise.\n+const CODEX_INSTANCE = ProviderInstanceId.make("codex");\n+const CLAUDE_AGENT_INSTANCE = ProviderInstanceId.make("claudeAgent");\n+const CURSOR_INSTANCE = ProviderInstanceId.make("cursor");\n+const CODEX_DRIVER = ProviderDriverKind.make("codex");\n+const CLAUDE_AGENT_DRIVER = ProviderDriverKind.make("claudeAgent");\n+const CURSOR_DRIVER = ProviderDriverKind.make("cursor");\n+\n type ProviderOptionSelectionBag = ReadonlyArray<ProviderOptionSelection>;\n-type ProviderOptionSelectionsByProvider = Partial<Record<ProviderKind, ProviderOptionSelectionBag>>;\n+type ProviderOptionSelectionsByProvider = Partial<Record<string, ProviderOptionSelectionBag>>;\n \n function toSelections(\n options: Record<string, string | boolean | undefined> | undefined,\n@@ -32,11 +44,11 @@ function toSelections(\n }\n \n function selectionsByProvider(\n- options: Partial<Record<ProviderKind, Record<string, string | boolean | undefined>>>,\n+ options: Partial<Record<ProviderDriverKind, Record<string, string | boolean | undefined>>>,\n ): ProviderOptionSelectionsByProvider {\n const result: ProviderOptionSelectionsByProvider = {};\n for (const [provider, bag] of Object.entries(options) as Array<\n- [ProviderKind, Record<string, string | boolean | undefined>]\n+ [ProviderDriverKind, Record<string, string | boolean | undefined>]\n >) {\n result[provider] = toSelections(bag);\n }\n@@ -121,15 +133,15 @@ function resetComposerDraftStore() {\n }\n \n function modelSelection(\n- provider: "codex" | "claudeAgent" | "cursor",\n+ provider: ProviderDriverKind,\n model: string,\n options?: Record<string, string | boolean | undefined>,\n ): ModelSelection {\n- return createModelSelection(provider, model, toSelections(options));\n+ return createModelSelection(defaultInstanceIdForDriver(provider), model, toSelections(options));\n }\n \n function providerModelOptions(\n- options: Partial<Record<ProviderKind, Record<string, string | boolean | undefined>>>,\n+ options: Partial<Record<string, Record<string, string | boolean | undefined>>>,\n ): ProviderOptionSelectionsByProvider {\n return selectionsByProvider(options);\n }\n@@ -929,14 +941,16 @@ describe("composerDraftStore modelSelection", () => {\n const store = useComposerDraftStore.getState();\n store.setModelSelection(\n threadRef,\n- modelSelection("codex", "gpt-5.3-codex", {\n+ modelSelection(CODEX_DRIVER, "gpt-5.3-codex", {\n reasoningEffort: "xhigh",\n fastMode: true,\n }),\n );\n \n- expect(draftFor(threadId, TEST_ENVIRONMENT_ID)?.modelSelectionByProvider.codex).toEqual(\n- modelSelection("codex", "gpt-5.3-codex", {\n+ expect(\n+ draftFor(threadId, TEST_ENVIRONMENT_ID)?.modelSelectionByProvider[CODEX_INSTANCE],\n+ ).toEqual(\n+ modelSelection(CODEX_DRIVER, "gpt-5.3-codex", {\n reasoningEffort: "xhigh",\n fastMode: true,\n }),\n@@ -945,11 +959,11 @@ describe("composerDraftStore modelSelection", () => {\n \n it("keeps default-only model selections on the draft", () => {\n const store = useComposerDraftStore.getState();\n- store.setModelSelection(threadRef, modelSelection("codex", "gpt-5.4"));\n+ store.setModelSelection(threadRef, modelSelection(CODEX_DRIVER, "gpt-5.4"));\n \n- expect(draftFor(threadId, TEST_ENVIRONMENT_ID)?.modelSelectionByProvider.codex).toEqual(\n- modelSelection("codex", "gpt-5.4"),\n- );\n+ expect(\n+ draftFor(threadId, TEST_ENVIRONMENT_ID)?.modelSelectionByProvider[CODEX_INSTANCE],\n+ ).toEqual(modelSelection(CODEX_DRIVER, "gpt-5.4"));\n });\n \n it("replaces only the targeted provider options on the current model selection", () => {\n@@ -957,29 +971,38 @@ describe("composerDraftStore modelSelection", () => {\n \n store.setModelSelection(\n threadRef,\n- modelSelection("claudeAgent", "claude-opus-4-6", {\n+ modelSelection(CLAUDE_AGENT_DRIVER, "claude-opus-4-6", {\n effort: "max",\n fastMode: true,\n }),\n );\n store.setStickyModelSelection(\n- modelSelection("claudeAgent", "claude-opus-4-6", {\n+ modelSelection(CLAUDE_AGENT_DRIVER, "claude-opus-4-6", {\n effort: "max",\n fastMode: true,\n }),\n );\n \n- store.setProviderModelOptions(threadRef, "claudeAgent", toSelections({ thinking: false }), {\n- persistSticky: true,\n- });\n+ store.setProviderModelOptions(\n+ threadRef,\n+ CLAUDE_AGENT_DRIVER,\n+ toSelections({ thinking: false }),\n+ {\n+ persistSticky: true,\n+ },\n+ );\n \n- expect(draftFor(threadId, TEST_ENVIRONMENT_ID)?.modelSelectionByProvider.claudeAgent).toEqual(\n- modelSelection("claudeAgent", "claude-opus-4-6", {\n+ expect(\n+ draftFor(threadId, TEST_ENVIRONMENT_ID)?.modelSelectionByProvider[CLAUDE_AGENT_INSTANCE],\n+ ).toEqual(\n+ modelSelection(CLAUDE_AGENT_DRIVER, "claude-opus-4-6", {\n thinking: false,\n }),\n );\n- expect(useComposerDraftStore.getState().stickyModelSelectionByProvider.claudeAgent).toEqual(\n- modelSelection("claudeAgent", "claude-opus-4-6", {\n+ expect(\n+ useComposerDraftStore.getState().stickyModelSelectionByProvider[CLAUDE_AGENT_INSTANCE],\n+ ).toEqual(\n+ modelSelection(CLAUDE_AGENT_DRIVER, "claude-opus-4-6", {\n thinking: false,\n }),\n );\n@@ -990,15 +1013,17 @@ describe("composerDraftStore modelSelection", () => {\n \n store.setModelSelection(\n threadRef,\n- modelSelection("claudeAgent", "claude-opus-4-6", {\n+ modelSelection(CLAUDE_AGENT_DRIVER, "claude-opus-4-6", {\n effort: "max",\n }),\n );\n \n- store.setProviderModelOptions(threadRef, "claudeAgent", toSelections({ thinking: true }));\n+ store.setProviderModelOptions(threadRef, CLAUDE_AGENT_DRIVER, toSelections({ thinking: true }));\n \n- expect(draftFor(threadId, TEST_ENVIRONMENT_ID)?.modelSelectionByProvider.claudeAgent).toEqual(\n- modelSelection("claudeAgent", "claude-opus-4-6", {\n+ expect(\n+ draftFor(threadId, TEST_ENVIRONMENT_ID)?.modelSelectionByProvider[CLAUDE_AGENT_INSTANCE],\n+ ).toEqual(\n+ modelSelection(CLAUDE_AGENT_DRIVER, "claude-opus-4-6", {\n thinking: true,\n }),\n );\n@@ -1008,16 +1033,18 @@ describe("composerDraftStore modelSelection", () => {\n it("keeps explicit off/default codex overrides on the selection", () => {\n const store = useComposerDraftStore.getState();\n \n- store.setModelSelection(threadRef, modelSelection("codex", "gpt-5.4", { fastMode: true }));\n+ store.setModelSelection(threadRef, modelSelection(CODEX_DRIVER, "gpt-5.4", { fastMode: true }));\n \n store.setProviderModelOptions(\n threadRef,\n- "codex",\n+ CODEX_DRIVER,\n toSelections({ reasoningEffort: "high", fastMode: false }),\n );\n \n- expect(draftFor(threadId, TEST_ENVIRONMENT_ID)?.modelSelectionByProvider.codex).toEqual(\n- modelSelection("codex", "gpt-5.4", {\n+ expect(\n+ draftFor(threadId, TEST_ENVIRONMENT_ID)?.modelSelectionByProvider[CODEX_INSTANCE],\n+ ).toEqual(\n+ modelSelection(CODEX_DRIVER, "gpt-5.4", {\n reasoningEffort: "high",\n fastMode: false,\n }),\n@@ -1029,7 +1056,7 @@ describe("composerDraftStore modelSelection", () => {\n \n store.setModelSelection(\n threadRef,\n- modelSelection("cursor", "claude-opus-4-6", {\n+ modelSelection(CURSOR_DRIVER, "claude-opus-4-6", {\n reasoning: "xhigh",\n fastMode: true,\n thinking: false,\n@@ -1038,12 +1065,14 @@ describe("composerDraftStore modelSelection", () => {\n \n store.setProviderModelOptions(\n threadRef,\n- "cursor",\n+ CURSOR_DRIVER,\n toSelections({ reasoning: "medium", fastMode: false, thinking: true }),\n );\n \n- expect(draftFor(threadId, TEST_ENVIRONMENT_ID)?.modelSelectionByProvider.cursor).toEqual(\n- modelSelection("cursor", "claude-opus-4-6", {\n+ expect(\n+ draftFor(threadId, TEST_ENVIRONMENT_ID)?.modelSelectionByProvider[CURSOR_INSTANCE],\n+ ).toEqual(\n+ modelSelection(CURSOR_DRIVER, "claude-opus-4-6", {\n reasoning: "medium",\n fastMode: false,\n thinking: true,\n@@ -1054,18 +1083,22 @@ describe("composerDraftStore modelSelection", () => {\n it("preserves the selected Cursor model when only traits change", () => {\n const store = useComposerDraftStore.getState();\n \n- store.setProviderModelOptions(threadRef, "cursor", toSelections({ reasoning: "high" }), {\n+ store.setProviderModelOptions(threadRef, CURSOR_DRIVER, toSelections({ reasoning: "high" }), {\n model: "gpt-5.4",\n persistSticky: true,\n });\n \n- expect(draftFor(threadId, TEST_ENVIRONMENT_ID)?.modelSelectionByProvider.cursor).toEqual(\n- modelSelection("cursor", "gpt-5.4", {\n+ expect(\n+ draftFor(threadId, TEST_ENVIRONMENT_ID)?.modelSelectionByProvider[CURSOR_INSTANCE],\n+ ).toEqual(\n+ modelSelection(CURSOR_DRIVER, "gpt-5.4", {\n reasoning: "high",\n }),\n );\n- expect(useComposerDraftStore.getState().stickyModelSelectionByProvider.cursor).toEqual(\n- modelSelection("cursor", "gpt-5.4", {\n+ expect(\n+ useComposerDraftStore.getState().stickyModelSelectionByProvider[CURSOR_INSTANCE],\n+ ).toEqual(\n+ modelSelection(CURSOR_DRIVER, "gpt-5.4", {\n reasoning: "high",\n }),\n );\n@@ -1075,23 +1108,29 @@ describe("composerDraftStore modelSelection", () => {\n const store = useComposerDraftStore.getState();\n \n store.setStickyModelSelection(\n- modelSelection("claudeAgent", "claude-opus-4-6", { effort: "max" }),\n+ modelSelection(CLAUDE_AGENT_DRIVER, "claude-opus-4-6", { effort: "max" }),\n );\n store.setModelSelection(\n threadRef,\n- modelSelection("claudeAgent", "claude-opus-4-6", { effort: "max" }),\n+ modelSelection(CLAUDE_AGENT_DRIVER, "claude-opus-4-6", { effort: "max" }),\n );\n \n- store.setProviderModelOptions(threadRef, "claudeAgent", toSelections({ thinking: false }));\n+ store.setProviderModelOptions(\n+ threadRef,\n+ CLAUDE_AGENT_DRIVER,\n+ toSelections({ thinking: false }),\n+ );\n \n- expect(draftFor(threadId, TEST_ENVIRONMENT_ID)?.modelSelectionByProvider.claudeAgent).toEqual(\n- modelSelection("claudeAgent", "claude-opus-4-6", {\n+ expect(\n+ draftFor(threadId, TEST_ENVIRONMENT_ID)?.modelSelectionByProvider[CLAUDE_AGENT_INSTANCE],\n+ ).toEqual(\n+ modelSelection(CLAUDE_AGENT_DRIVER, "claude-opus-4-6", {\n thinking: false,\n }),\n );\n- expect(useComposerDraftStore.getState().stickyModelSelectionByProvider.claudeAgent).toEqual(\n- modelSelection("claudeAgent", "claude-opus-4-6", { effort: "max" }),\n- );\n+ expect(\n+ useComposerDraftStore.getState().stickyModelSelectionByProvider[CLAUDE_AGENT_INSTANCE],\n+ ).toEqual(modelSelection(CLAUDE_AGENT_DRIVER, "claude-opus-4-6", { effort: "max" }));\n });\n \n it("does not clear other provider options when setting options for a single provider", () => {\n@@ -1110,13 +1149,17 @@ describe("composerDraftStore modelSelection", () => {\n store.setModelOptions(threadRef, providerModelOptions({ codex: { reasoningEffort: "xhigh" } }));\n \n const draft = draftFor(threadId, TEST_ENVIRONMENT_ID);\n- expect(draft?.modelSelectionByProvider.codex?.options).toEqual(\n- createModelSelection("codex", "gpt-5.4", toSelections({ reasoningEffort: "xhigh" })).options,\n- );\n- expect(draft?.modelSelectionByProvider.claudeAgent?.options).toEqual(\n- createModelSelection("claudeAgent", "claude-opus-4-6", toSelections({ effort: "max" }))\n+ expect(draft?.modelSelectionByProvider[CODEX_INSTANCE]?.options).toEqual(\n+ createModelSelection(CODEX_INSTANCE, "gpt-5.4", toSelections({ reasoningEffort: "xhigh" }))\n .options,\n );\n+ expect(draft?.modelSelectionByProvider[CLAUDE_AGENT_INSTANCE]?.options).toEqual(\n+ createModelSelection(\n+ CLAUDE_AGENT_INSTANCE,\n+ "claude-opus-4-6",\n+ toSelections({ effort: "max" }),\n+ ).options,\n+ );\n });\n \n it("preserves other provider options when switching the active model selection", () => {\n@@ -1130,14 +1173,14 @@ describe("composerDraftStore modelSelection", () => {\n }),\n );\n \n- store.setModelSelection(threadRef, modelSelection("claudeAgent", "claude-opus-4-6"));\n+ store.setModelSelection(threadRef, modelSelection(CLAUDE_AGENT_DRIVER, "claude-opus-4-6"));\n \n const draft = draftFor(threadId, TEST_ENVIRONMENT_ID);\n- expect(draft?.modelSelectionByProvider.claudeAgent).toEqual(\n- modelSelection("claudeAgent", "claude-opus-4-6", { effort: "max" }),\n+ expect(draft?.modelSelectionByProvider[CLAUDE_AGENT_INSTANCE]).toEqual(\n+ modelSelection(CLAUDE_AGENT_DRIVER, "claude-opus-4-6", { effort: "max" }),\n );\n- expect(draft?.modelSelectionByProvider.codex?.options).toEqual(\n- createModelSelection("codex", "gpt-5.4", toSelections({ fastMode: true })).options,\n+ expect(draft?.modelSelectionByProvider[CODEX_INSTANCE]?.options).toEqual(\n+ createModelSelection(CODEX_INSTANCE, "gpt-5.4", toSelections({ fastMode: true })).options,\n );\n expect(draft?.activeProvider).toBe("claudeAgent");\n });\n@@ -1145,14 +1188,14 @@ describe("composerDraftStore modelSelection", () => {\n it("creates the first sticky snapshot from provider option changes", () => {\n const store = useComposerDraftStore.getState();\n \n- store.setModelSelection(threadRef, modelSelection("codex", "gpt-5.4"));\n+ store.setModelSelection(threadRef, modelSelection(CODEX_DRIVER, "gpt-5.4"));\n \n- store.setProviderModelOptions(threadRef, "codex", toSelections({ fastMode: true }), {\n+ store.setProviderModelOptions(threadRef, CODEX_DRIVER, toSelections({ fastMode: true }), {\n persistSticky: true,\n });\n \n- expect(useComposerDraftStore.getState().stickyModelSelectionByProvider.codex).toEqual(\n- modelSelection("codex", "gpt-5.4", {\n+ expect(useComposerDraftStore.getState().stickyModelSelectionByProvider[CODEX_INSTANCE]).toEqual(\n+ modelSelection(CODEX_DRIVER, "gpt-5.4", {\n fastMode: true,\n }),\n );\n@@ -1162,25 +1205,32 @@ describe("composerDraftStore modelSelection", () => {\n const store = useComposerDraftStore.getState();\n \n store.setStickyModelSelection(\n- modelSelection("claudeAgent", "claude-opus-4-6", { effort: "max" }),\n+ modelSelection(CLAUDE_AGENT_DRIVER, "claude-opus-4-6", { effort: "max" }),\n );\n store.setModelSelection(\n threadRef,\n- modelSelection("claudeAgent", "claude-opus-4-6", { effort: "max" }),\n+ modelSelection(CLAUDE_AGENT_DRIVER, "claude-opus-4-6", { effort: "max" }),\n );\n \n- store.setProviderModelOptions(threadRef, "claudeAgent", toSelections({ thinking: false }), {\n- persistSticky: false,\n- });\n+ store.setProviderModelOptions(\n+ threadRef,\n+ CLAUDE_AGENT_DRIVER,\n+ toSelections({ thinking: false }),\n+ {\n+ persistSticky: false,\n+ },\n+ );\n \n- expect(draftFor(threadId, TEST_ENVIRONMENT_ID)?.modelSelectionByProvider.claudeAgent).toEqual(\n- modelSelection("claudeAgent", "claude-opus-4-6", {\n+ expect(\n+ draftFor(threadId, TEST_ENVIRONMENT_ID)?.modelSelectionByProvider[CLAUDE_AGENT_INSTANCE],\n+ ).toEqual(\n+ modelSelection(CLAUDE_AGENT_DRIVER, "claude-opus-4-6", {\n thinking: false,\n }),\n );\n- expect(useComposerDraftStore.getState().stickyModelSelectionByProvider.claudeAgent).toEqual(\n- modelSelection("claudeAgent", "claude-opus-4-6", { effort: "max" }),\n- );\n+ expect(\n+ useComposerDraftStore.getState().stickyModelSelectionByProvider[CLAUDE_AGENT_INSTANCE],\n+ ).toEqual(modelSelection(CLAUDE_AGENT_DRIVER, "claude-opus-4-6", { effort: "max" }));\n });\n });\n \n@@ -1195,11 +1245,11 @@ describe("composerDraftStore setModelSelection", () => {\n it("keeps explicit model overrides instead of coercing to null", () => {\n const store = useComposerDraftStore.getState();\n \n- store.setModelSelection(threadRef, modelSelection("codex", "gpt-5.3-codex"));\n+ store.setModelSelection(threadRef, modelSelection(CODEX_DRIVER, "gpt-5.3-codex"));\n \n- expect(draftFor(threadId, TEST_ENVIRONMENT_ID)?.modelSelectionByProvider.codex).toEqual(\n- modelSelection("codex", "gpt-5.3-codex"),\n- );\n+ expect(\n+ draftFor(threadId, TEST_ENVIRONMENT_ID)?.modelSelectionByProvider[CODEX_INSTANCE],\n+ ).toEqual(modelSelection(CODEX_DRIVER, "gpt-5.3-codex"));\n });\n });\n \n@@ -1212,14 +1262,14 @@ describe("composerDraftStore sticky composer settings", () => {\n const store = useComposerDraftStore.getState();\n \n store.setStickyModelSelection(\n- modelSelection("codex", "gpt-5.3-codex", {\n+ modelSelection(CODEX_DRIVER, "gpt-5.3-codex", {\n reasoningEffort: "medium",\n fastMode: true,\n }),\n );\n \n- expect(useComposerDraftStore.getState().stickyModelSelectionByProvider.codex).toEqual(\n- modelSelection("codex", "gpt-5.3-codex", {\n+ expect(useComposerDraftStore.getState().stickyModelSelectionByProvider[CODEX_INSTANCE]).toEqual(\n+ modelSelection(CODEX_DRIVER, "gpt-5.3-codex", {\n reasoningEffort: "medium",\n fastMode: true,\n }),\n@@ -1230,10 +1280,10 @@ describe("composerDraftStore sticky composer settings", () => {\n it("normalizes empty sticky model options by dropping selection options", () => {\n const store = useComposerDraftStore.getState();\n \n- store.setStickyModelSelection(modelSelection("codex", "gpt-5.4"));\n+ store.setStickyModelSelection(modelSelection(CODEX_DRIVER, "gpt-5.4"));\n \n- expect(useComposerDraftStore.getState().stickyModelSelectionByProvider.codex).toEqual(\n- modelSelection("codex", "gpt-5.4"),\n+ expect(useComposerDraftStore.getState().stickyModelSelectionByProvider[CODEX_INSTANCE]).toEqual(\n+ modelSelection(CODEX_DRIVER, "gpt-5.4"),\n );\n expect(useComposerDraftStore.getState().stickyActiveProvider).toBe("codex");\n });\n@@ -1242,7 +1292,7 @@ describe("composerDraftStore sticky composer settings", () => {\n const store = useComposerDraftStore.getState();\n \n store.setStickyModelSelection(\n- modelSelection("cursor", "gpt-5.4", {\n+ modelSelection(CURSOR_DRIVER, "gpt-5.4", {\n reasoning: undefined,\n fastMode: undefined,\n thinking: undefined,\n@@ -1250,9 +1300,9 @@ describe("composerDraftStore sticky composer settings", () => {\n }),\n );\n \n- expect(useComposerDraftStore.getState().stickyModelSelectionByProvider.cursor).toEqual(\n- modelSelection("cursor", "gpt-5.4"),\n- );\n+ expect(\n+ useComposerDraftStore.getState().stickyModelSelectionByProvider[CURSOR_INSTANCE],\n+ ).toEqual(modelSelection(CURSOR_DRIVER, "gpt-5.4"));\n expect(useComposerDraftStore.getState().stickyActiveProvider).toBe("cursor");\n });\n \n@@ -1261,12 +1311,12 @@ describe("composerDraftStore sticky composer settings", () => {\n const threadId = ThreadId.make("thread-sticky-active-provider");\n const threadRef = scopeThreadRef(TEST_ENVIRONMENT_ID, threadId);\n \n- store.setStickyModelSelection(modelSelection("claudeAgent", "claude-opus-4-6"));\n+ store.setStickyModelSelection(modelSelection(CLAUDE_AGENT_DRIVER, "claude-opus-4-6"));\n store.applyStickyState(threadRef);\n \n expect(draftFor(threadId, TEST_ENVIRONMENT_ID)).toMatchObject({\n modelSelectionByProvider: {\n- claudeAgent: modelSelection("claudeAgent", "claude-opus-4-6"),\n+ claudeAgent: modelSelection(CLAUDE_AGENT_DRIVER, "claude-opus-4-6"),\n },\n activeProvider: "claudeAgent",\n });\n@@ -1285,18 +1335,21 @@ describe("composerDraftStore provider-scoped option updates", () => {\n const store = useComposerDraftStore.getState();\n store.setModelSelection(\n threadRef,\n- modelSelection("codex", "gpt-5.3-codex", {\n+ modelSelection(CODEX_DRIVER, "gpt-5.3-codex", {\n reasoningEffort: "medium",\n }),\n );\n- store.setProviderModelOptions(threadRef, "claudeAgent", toSelections({ effort: "max" }));\n+ store.setProviderModelOptions(threadRef, CLAUDE_AGENT_DRIVER, toSelections({ effort: "max" }));\n const draft = draftFor(threadId, TEST_ENVIRONMENT_ID);\n- expect(draft?.modelSelectionByProvider.codex).toEqual(\n- modelSelection("codex", "gpt-5.3-codex", { reasoningEffort: "medium" }),\n+ expect(draft?.modelSelectionByProvider[CODEX_INSTANCE]).toEqual(\n+ modelSelection(CODEX_DRIVER, "gpt-5.3-codex", { reasoningEffort: "medium" }),\n );\n- expect(draft?.modelSelectionByProvider.claudeAgent?.options).toEqual(\n- createModelSelection("claudeAgent", "claude-opus-4-6", toSelections({ effort: "max" }))\n- .options,\n+ expect(draft?.modelSelectionByProvider[CLAUDE_AGENT_INSTANCE]?.options).toEqual(\n+ createModelSelection(\n+ CLAUDE_AGENT_INSTANCE,\n+ "claude-opus-4-6",\n+ toSelections({ effort: "max" }),\n+ ).options,\n );\n expect(draft?.activeProvider).toBe("codex");\n });\ndiff --git a/apps/web/src/composerDraftStore.ts b/apps/web/src/composerDraftStore.ts\nindex cdd11a77b1..9533ea0b90 100644\n--- a/apps/web/src/composerDraftStore.ts\n+++ b/apps/web/src/composerDraftStore.ts\n@@ -1,10 +1,13 @@\n import {\n+ DEFAULT_MODEL,\n DEFAULT_MODEL_BY_PROVIDER,\n+ defaultInstanceIdForDriver,\n type EnvironmentId,\n ModelSelection,\n ProjectId,\n+ ProviderInstanceId,\n ProviderInteractionMode,\n- ProviderKind,\n+ ProviderDriverKind,\n ProviderOptionSelection,\n RuntimeMode,\n type ServerProvider,\n@@ -26,7 +29,7 @@ import { DeepMutable } from "effect/Types";\n import { createModelSelection, normalizeModelSlug } from "@t3tools/shared/model";\n import { useMemo } from "react";\n import { getLocalStorageItem } from "./hooks/useLocalStorage";\n-import { resolveAppModelSelection } from "./modelSelection";\n+import { resolveAppModelSelection, resolveAppModelSelectionForInstance } from "./modelSelection";\n import { DEFAULT_INTERACTION_MODE, DEFAULT_RUNTIME_MODE, type ChatImageAttachment } from "./types";\n import {\n type TerminalContextDraft,\n@@ -92,10 +95,19 @@ const PersistedComposerThreadDraftState = Schema.Struct({\n prompt: Schema.String,\n attachments: Schema.Array(PersistedComposerImageAttachment),\n terminalContexts: Schema.optionalKey(Schema.Array(PersistedTerminalContextDraft)),\n- modelSelectionByProvider: Schema.optionalKey(\n- Schema.Record(ProviderKind, Schema.optionalKey(ModelSelection)),\n- ),\n- activeProvider: Schema.optionalKey(Schema.NullOr(ProviderKind)),\n+ // Keyed by `ProviderInstanceId` (open branded slug) so custom provider\n+ // instances (e.g. `codex_personal`) round-trip alongside the built-in\n+ // `codex` / `claudeAgent` / ... entries. Every prior `ProviderDriverKind`\n+ // literal satisfies the `ProviderInstanceId` slug pattern, so existing\n+ // persisted drafts decode unchanged.\n+ //\n+ // The record\'s value schema is NOT wrapped in `Schema.optionalKey`:\n+ // that helper is only meaningful on property signatures with a known\n+ // key set, and `Schema.Record(<branded string>, …)` produces an index\n+ // signature at runtime (Schema rejects the combination). Absence of\n+ // an entry already encodes "no selection for this instance".\n+ modelSelectionByProvider: Schema.optionalKey(Schema.Record(ProviderInstanceId, ModelSelection)),\n+ activeProvider: Schema.optionalKey(Schema.NullOr(ProviderInstanceId)),\n runtimeMode: Schema.optionalKey(RuntimeMode),\n interactionMode: Schema.optionalKey(ProviderInteractionMode),\n });\n@@ -107,7 +119,7 @@ type PersistedComposerThreadDraftState = typeof PersistedComposerThreadDraftStat\n * deriving per-provider option bundles for downstream consumers.\n */\n type ProviderOptionSelectionsByProvider = Partial<\n- Record<ProviderKind, ReadonlyArray<ProviderOptionSelection>>\n+ Record<string, ReadonlyArray<ProviderOptionSelection>>\n >;\n \n type LegacyCodexFields = {\n@@ -182,9 +194,9 @@ const PersistedComposerDraftStoreState = Schema.Struct({\n draftThreadsByThreadKey: Schema.Record(Schema.String, PersistedDraftThreadState),\n logicalProjectDraftThreadKeyByLogicalProjectKey: Schema.Record(Schema.String, Schema.String),\n stickyModelSelectionByProvider: Schema.optionalKey(\n- Schema.Record(ProviderKind, Schema.optionalKey(ModelSelection)),\n+ Schema.Record(ProviderInstanceId, ModelSelection),\n ),\n- stickyActiveProvider: Schema.optionalKey(Schema.NullOr(ProviderKind)),\n+ stickyActiveProvider: Schema.optionalKey(Schema.NullOr(ProviderInstanceId)),\n });\n type PersistedComposerDraftStoreState = typeof PersistedComposerDraftStoreState.Type;\n \n@@ -203,8 +215,17 @@ export interface ComposerThreadDraftState {\n nonPersistedImageIds: string[];\n persistedAttachments: PersistedComposerImageAttachment[];\n terminalContexts: TerminalContextDraft[];\n- modelSelectionByProvider: Partial<Record<ProviderKind, ModelSelection>>;\n- activeProvider: ProviderKind | null;\n+ /**\n+ * Per-instance model selection. Keyed by `ProviderInstanceId` (open\n+ * branded slug) so a default `codex` instance and a user-authored\n+ * `codex_personal` instance each persist their own selected model. Every\n+ * historical `ProviderDriverKind` literal (`codex` / `claudeAgent` / `cursor` /\n+ * `opencode`) also satisfies the `ProviderInstanceId` slug pattern, so\n+ * legacy kind-keyed drafts round-trip unchanged.\n+ */\n+ modelSelectionByProvider: Partial<Record<ProviderInstanceId, ModelSelection>>;\n+ /** Routing key of the last picked instance (see `modelSelectionByProvider`). */\n+ activeProvider: ProviderInstanceId | null;\n runtimeMode: RuntimeMode | null;\n interactionMode: ProviderInteractionMode | null;\n }\n@@ -259,8 +280,8 @@ interface ComposerDraftStoreState {\n draftsByThreadKey: Record<string, ComposerThreadDraftState>;\n draftThreadsByThreadKey: Record<string, DraftThreadState>;\n logicalProjectDraftThreadKeyByLogicalProjectKey: Record<string, string>;\n- stickyModelSelectionByProvider: Partial<Record<ProviderKind, ModelSelection>>;\n- stickyActiveProvider: ProviderKind | null;\n+ stickyModelSelectionByProvider: Partial<Record<ProviderInstanceId, ModelSelection>>;\n+ stickyActiveProvider: ProviderInstanceId | null;\n /** Returns the editable composer content for a draft session or server thread. */\n getComposerDraft: (target: ComposerThreadTarget) => ComposerThreadDraftState | null;\n /** Looks up the active draft session for a logical project identity. */\n@@ -339,14 +360,14 @@ interface ComposerDraftStoreState {\n setModelOptions: (\n threadRef: ComposerThreadTarget,\n modelOptions:\n- | Partial<Record<ProviderKind, ReadonlyArray<ProviderOptionSelection>>>\n+ | Partial<Record<string, ReadonlyArray<ProviderOptionSelection>>>\n | null\n | undefined,\n ) => void;\n applyStickyState: (threadRef: ComposerThreadTarget) => void;\n setProviderModelOptions: (\n threadRef: ComposerThreadTarget,\n- provider: ProviderKind,\n+ provider: ProviderDriverKind,\n nextProviderOptions: ReadonlyArray<ProviderOptionSelection> | null | undefined,\n options?: {\n model?: string | null | undefined;\n@@ -388,8 +409,8 @@ export interface EffectiveComposerModelState {\n }\n \n interface ComposerDraftModelState {\n- activeProvider: ProviderKind | null;\n- modelSelectionByProvider: Partial<Record<ProviderKind, ModelSelection>>;\n+ activeProvider: ProviderInstanceId | null;\n+ modelSelectionByProvider: Partial<Record<ProviderInstanceId, ModelSelection>>;\n }\n \n function providerSelectionsFromModelSelection(\n@@ -402,17 +423,17 @@ function providerSelectionsFromModelSelection(\n if (!options || options.length === 0) {\n return null;\n }\n- return { [modelSelection.provider]: options } as ProviderOptionSelectionsByProvider;\n+ return { [modelSelection.instanceId]: options };\n }\n \n function modelSelectionByProviderToOptions(\n- map: Partial<Record<ProviderKind, ModelSelection>> | null | undefined,\n+ map: Partial<Record<string, ModelSelection>> | null | undefined,\n ): ProviderOptionSelectionsByProvider | null {\n if (!map) return null;\n- const result: Partial<Record<ProviderKind, ReadonlyArray<ProviderOptionSelection>>> = {};\n+ const result: ProviderOptionSelectionsByProvider = {};\n for (const [provider, selection] of Object.entries(map)) {\n if (selection?.options && selection.options.length > 0) {\n- result[provider as ProviderKind] = selection.options;\n+ result[provider] = selection.options;\n }\n }\n return Object.keys(result).length > 0 ? result : null;\n@@ -425,15 +446,14 @@ function cloneModelSelection(selection: ModelSelection): DeepMutable<ModelSelect\n } as DeepMutable<ModelSelection>;\n }\n \n-function cloneModelSelectionByProvider(\n- selections: Partial<Record<ProviderKind, ModelSelection>>,\n-): DeepMutable<Partial<Record<ProviderKind, ModelSelection>>> {\n+function compactModelSelectionByProvider(\n+ selections: Partial<Record<ProviderInstanceId, ModelSelection>>,\n+): DeepMutable<Record<ProviderInstanceId, ModelSelection>> {\n return Object.fromEntries(\n- Object.entries(selections).map(([provider, selection]) => [\n- provider,\n- selection ? cloneModelSelection(selection) : selection,\n- ]),\n- ) as DeepMutable<Partial<Record<ProviderKind, ModelSelection>>>;\n+ Object.entries(selections)\n+ .filter((entry): entry is [string, ModelSelection] => entry[1] !== undefined)\n+ .map(([provider, selection]) => [provider, cloneModelSelection(selection)]),\n+ ) as DeepMutable<Record<ProviderInstanceId, ModelSelection>>;\n }\n \n const EMPTY_PERSISTED_DRAFT_STORE_STATE = Object.freeze<PersistedComposerDraftStoreState>({\n@@ -451,7 +471,7 @@ const EMPTY_TERMINAL_CONTEXTS: TerminalContextDraft[] = [];\n Object.freeze(EMPTY_IMAGES);\n Object.freeze(EMPTY_IDS);\n Object.freeze(EMPTY_PERSISTED_ATTACHMENTS);\n-const EMPTY_MODEL_SELECTION_BY_PROVIDER: Partial<Record<ProviderKind, ModelSelection>> =\n+const EMPTY_MODEL_SELECTION_BY_PROVIDER: Partial<Record<ProviderDriverKind, ModelSelection>> =\n Object.freeze({});\n const EMPTY_COMPOSER_DRAFT_MODEL_STATE = Object.freeze<ComposerDraftModelState>({\n activeProvider: null,\n@@ -554,10 +574,28 @@ function shouldRemoveDraft(draft: ComposerThreadDraftState): boolean {\n );\n }\n \n-function normalizeProviderKind(value: unknown): ProviderKind | null {\n- return value === "codex" || value === "claudeAgent" || value === "cursor" || value === "opencode"\n- ? value\n- : null;\n+function normalizeProviderDriverKind(value: unknown): ProviderDriverKind | null {\n+ return Schema.is(ProviderDriverKind)(value) ? value : null;\n+}\n+\n+/**\n+ * Match the `ProviderInstanceId` slug pattern (letter followed by\n+ * letters/digits/`-`/`_`, 1..64 chars). Permissive validator — the schema\n+ * layer owns authoritative validation; this is used inline to gate typed\n+ * writes to the draft\'s instance-keyed maps without pulling the full\n+ * Effect Schema runtime into the hot path.\n+ */\n+const PROVIDER_INSTANCE_ID_PATTERN = /^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/;\n+\n+/**\n+ * Coerce an arbitrary persisted value into a valid `ProviderInstanceId`. Used\n+ * wherever we need to accept both legacy driver-kind keys and custom instance\n+ * slugs (e.g. `codex_personal`) as routing keys.\n+ */\n+function normalizeProviderInstanceId(value: unknown): ProviderInstanceId | null {\n+ if (typeof value !== "string") return null;\n+ if (!PROVIDER_INSTANCE_ID_PATTERN.test(value)) return null;\n+ return value as ProviderInstanceId;\n }\n \n /**\n@@ -610,11 +648,11 @@ function coerceProviderOptionSelections(\n */\n function normalizeProviderModelOptions(\n value: unknown,\n- provider?: ProviderKind | null,\n+ provider?: ProviderDriverKind | null,\n legacy?: LegacyCodexFields,\n ): ProviderOptionSelectionsByProvider | null {\n const candidate = value && typeof value === "object" ? (value as Record<string, unknown>) : null;\n- const result: Partial<Record<ProviderKind, ReadonlyArray<ProviderOptionSelection>>> = {};\n+ const result: ProviderOptionSelectionsByProvider = {};\n for (const providerKey of ["codex", "claudeAgent", "cursor", "opencode"] as const) {\n const selections = coerceProviderOptionSelections(candidate?.[providerKey]);\n if (selections) {\n@@ -648,6 +686,13 @@ function normalizeProviderModelOptions(\n return Object.keys(result).length > 0 ? result : null;\n }\n \n+// Returns a model selection whose `instanceId` is a valid\n+// `ProviderInstanceId` slug. Legacy `provider` fields are promoted verbatim\n+// because default instance ids used the same slug as the driver kind.\n+//\n+// Selections whose instance id doesn\'t match the slug pattern collapse to\n+// `null` — caller is responsible for deciding whether that\'s a dropped\n+// write or a routed error.\n function normalizeModelSelection(\n value: unknown,\n legacy?: {\n@@ -656,63 +701,98 @@ function normalizeModelSelection(\n modelOptions?: unknown;\n legacyCodex?: LegacyCodexFields;\n },\n-): ModelSelection | null {\n+): NormalizedModelSelection | null {\n const candidate = value && typeof value === "object" ? (value as Record<string, unknown>) : null;\n- const provider = normalizeProviderKind(candidate?.provider ?? legacy?.provider);\n- if (provider === null) {\n+ // Post-migration ModelSelection carries `instanceId`; pre-migration (v2\n+ // storage, legacy wire shapes) carries `provider`. Accept either so both\n+ // normalized stores and legacy drafts round-trip through this helper.\n+ const instanceId = normalizeProviderInstanceId(\n+ candidate?.instanceId ?? candidate?.provider ?? legacy?.provider,\n+ );\n+ if (instanceId === null) {\n return null;\n }\n const rawModel = candidate?.model ?? legacy?.model;\n if (typeof rawModel !== "string") {\n return null;\n }\n- const model = normalizeModelSlug(rawModel, provider);\n+ // Slug normalization can use provider-kind-specific rules when a legacy\n+ // driver key is present. Instance-only selections are not reverse-inferred\n+ // into a driver kind here; they get generic default normalization.\n+ const driverKindHint =\n+ normalizeProviderDriverKind(candidate?.provider ?? legacy?.provider) ??\n+ ProviderDriverKind.make("codex");\n+ const model = normalizeModelSlug(rawModel, driverKindHint);\n if (!model) {\n return null;\n }\n if (Array.isArray(candidate?.options)) {\n const selections = coerceProviderOptionSelections(candidate.options);\n- return createModelSelection(provider, model, selections);\n+ return createModelSelection(instanceId, model, selections) as NormalizedModelSelection;\n }\n- const modelOptions = normalizeProviderModelOptions(\n- candidate?.options ? { [provider]: candidate.options } : legacy?.modelOptions,\n- provider,\n- provider === "codex" ? legacy?.legacyCodex : undefined,\n- );\n- const options = modelOptions?.[provider];\n- return createModelSelection(provider, model, options);\n+ // Per-kind options were a pre-migration concern; only recover them for a\n+ // built-in-kind instance. Custom instances don\'t have a legacy options\n+ // store to thread through here.\n+ const kindForLegacyOptions = normalizeProviderDriverKind(instanceId);\n+ const modelOptions = kindForLegacyOptions\n+ ? normalizeProviderModelOptions(\n+ candidate?.options ? { [kindForLegacyOptions]: candidate.options } : legacy?.modelOptions,\n+ kindForLegacyOptions,\n+ kindForLegacyOptions === "codex" ? legacy?.legacyCodex : undefined,\n+ )\n+ : null;\n+ const options = kindForLegacyOptions ? modelOptions?.[kindForLegacyOptions] : undefined;\n+ return createModelSelection(instanceId, model, options) as NormalizedModelSelection;\n }\n \n+type NormalizedModelSelection = Omit<ModelSelection, "instanceId"> & {\n+ readonly instanceId: ProviderInstanceId;\n+};\n+\n // ── Legacy sync helpers (used only during migration from v2 storage) ──\n+//\n+// These operate against the legacy kind-keyed `modelOptions` map. The\n+// normalized selection now carries an open `ProviderInstanceId`; legacy\n+// migration only recovers options for keys that existed before custom\n+// provider instances.\n \n function legacySyncModelSelectionOptions(\n- modelSelection: ModelSelection | null,\n+ modelSelection: NormalizedModelSelection | null,\n modelOptions: ProviderOptionSelectionsByProvider | null | undefined,\n-): ModelSelection | null {\n+): NormalizedModelSelection | null {\n if (modelSelection === null) {\n return null;\n }\n- const options = modelOptions?.[modelSelection.provider];\n- return createModelSelection(modelSelection.provider, modelSelection.model, options);\n+ const kind = normalizeProviderDriverKind(modelSelection.instanceId);\n+ const options = kind ? modelOptions?.[kind] : undefined;\n+ return createModelSelection(\n+ modelSelection.instanceId,\n+ modelSelection.model,\n+ options,\n+ ) as NormalizedModelSelection;\n }\n \n function legacyMergeModelSelectionIntoProviderModelOptions(\n- modelSelection: ModelSelection | null,\n+ modelSelection: NormalizedModelSelection | null,\n currentModelOptions: ProviderOptionSelectionsByProvider | null | undefined,\n ): ProviderOptionSelectionsByProvider | null {\n if (!modelSelection?.options || modelSelection.options.length === 0) {\n return normalizeProviderModelOptions(currentModelOptions);\n }\n+ const kind = normalizeProviderDriverKind(modelSelection.instanceId);\n+ if (!kind) {\n+ return normalizeProviderModelOptions(currentModelOptions);\n+ }\n return legacyReplaceProviderModelOptions(\n normalizeProviderModelOptions(currentModelOptions),\n- modelSelection.provider,\n+ kind,\n modelSelection.options,\n );\n }\n \n function legacyReplaceProviderModelOptions(\n currentModelOptions: ProviderOptionSelectionsByProvider | null | undefined,\n- provider: ProviderKind,\n+ provider: ProviderDriverKind,\n nextProviderOptions: ReadonlyArray<ProviderOptionSelection> | null | undefined,\n ): ProviderOptionSelectionsByProvider | null {\n const { [provider]: _discardedProviderModelOptions, ...otherProviderModelOptions } =\n@@ -727,26 +807,28 @@ function legacyReplaceProviderModelOptions(\n // ── New helpers for the consolidated representation ────────────────────\n \n function legacyToModelSelectionByProvider(\n- modelSelection: ModelSelection | null,\n+ modelSelection: NormalizedModelSelection | null,\n modelOptions: ProviderOptionSelectionsByProvider | null | undefined,\n-): Partial<Record<ProviderKind, ModelSelection>> {\n- const result: Partial<Record<ProviderKind, ModelSelection>> = {};\n+): Partial<Record<ProviderInstanceId, ModelSelection>> {\n+ const result: Partial<Record<ProviderInstanceId, ModelSelection>> = {};\n if (modelOptions) {\n for (const provider of ["codex", "claudeAgent", "cursor", "opencode"] as const) {\n const options = modelOptions[provider];\n if (options && options.length > 0) {\n- result[provider] = createModelSelection(\n- provider,\n- modelSelection?.provider === provider\n+ const driverKind = ProviderDriverKind.make(provider);\n+ const instanceKey = defaultInstanceIdForDriver(driverKind);\n+ result[instanceKey] = createModelSelection(\n+ instanceKey,\n+ modelSelection?.instanceId === instanceKey\n ? modelSelection.model\n- : DEFAULT_MODEL_BY_PROVIDER[provider],\n+ : (DEFAULT_MODEL_BY_PROVIDER[driverKind] ?? DEFAULT_MODEL),\n options,\n );\n }\n }\n }\n if (modelSelection) {\n- result[modelSelection.provider] = modelSelection;\n+ result[modelSelection.instanceId] = modelSelection as ModelSelection;\n }\n return result;\n }\n@@ -757,24 +839,64 @@ export function deriveEffectiveComposerModelState(input: {\n | null\n | undefined;\n providers: ReadonlyArray<ServerProvider>;\n- selectedProvider: ProviderKind;\n+ selectedProvider: ProviderDriverKind;\n+ /**\n+ * Optional routing key of the instance whose selection should override\n+ * the driver-level lookup. When present, the draft is queried by\n+ * `modelSelectionByProvider[selectedInstanceId]` so a custom Codex\n+ * instance (e.g. `codex_personal`) reads its own saved model instead of\n+ * collapsing to the default Codex bucket.\n+ */\n+ selectedInstanceId?: ProviderInstanceId | null | undefined;\n threadModelSelection: ModelSelection | null | undefined;\n projectModelSelection: ModelSelection | null | undefined;\n settings: UnifiedSettings;\n }): EffectiveComposerModelState {\n+ const baseModelCandidate =\n+ input.threadModelSelection?.model ?? input.projectModelSelection?.model ?? null;\n const baseModel =\n- normalizeModelSlug(\n- input.threadModelSelection?.model ?? input.projectModelSelection?.model,\n+ (input.selectedInstanceId\n+ ? resolveAppModelSelectionForInstance(\n+ input.selectedInstanceId,\n+ input.settings,\n+ input.providers,\n+ baseModelCandidate,\n+ )\n+ : null) ??\n+ resolveAppModelSelection(\n input.selectedProvider,\n- ) ?? getDefaultServerModel(input.providers, input.selectedProvider);\n- const activeSelection = input.draft?.modelSelectionByProvider?.[input.selectedProvider];\n+ input.settings,\n+ input.providers,\n+ baseModelCandidate,\n+ ) ??\n+ normalizeModelSlug(baseModelCandidate, input.selectedProvider) ??\n+ getDefaultServerModel(input.providers, input.selectedProvider);\n+ // Look up the instance\'s saved selection first; fall back to the\n+ // driver-kind bucket so legacy kind-keyed drafts still resolve. Every\n+ // `ProviderDriverKind` literal is a valid `ProviderInstanceId` slug, so the\n+ // cast to the branded type is safe.\n+ const instanceSelection = input.selectedInstanceId\n+ ? input.draft?.modelSelectionByProvider?.[input.selectedInstanceId]\n+ : undefined;\n+ const legacySelection =\n+ input.draft?.modelSelectionByProvider?.[ProviderInstanceId.make(input.selectedProvider)];\n+ const activeSelection = instanceSelection ?? legacySelection;\n+ const activeSelectionInstanceId = instanceSelection\n+ ? (input.selectedInstanceId ?? ProviderInstanceId.make(input.selectedProvider))\n+ : ProviderInstanceId.make(input.selectedProvider);\n const selectedModel = activeSelection?.model\n- ? resolveAppModelSelection(\n+ ? (resolveAppModelSelectionForInstance(\n+ activeSelectionInstanceId,\n+ input.settings,\n+ input.providers,\n+ activeSelection.model,\n+ ) ??\n+ resolveAppModelSelection(\n input.selectedProvider,\n input.settings,\n input.providers,\n activeSelection.model,\n- )\n+ ))\n : baseModel;\n const modelOptions =\n modelSelectionByProviderToOptions(input.draft?.modelSelectionByProvider) ??\n@@ -1365,8 +1487,8 @@ function normalizePersistedDraftsByThreadId(\n );\n // If the draft already has the v3 shape, use it directly\n const legacyDraftCandidate = draftValue as LegacyPersistedComposerThreadDraftState;\n- let modelSelectionByProvider: Partial<Record<ProviderKind, ModelSelection>> = {};\n- let activeProvider: ProviderKind | null = null;\n+ let modelSelectionByProvider: Partial<Record<ProviderInstanceId, ModelSelection>> = {};\n+ let activeProvider: ProviderInstanceId | null = null;\n \n if (\n draftCandidate.modelSelectionByProvider &&\n@@ -1374,9 +1496,9 @@ function normalizePersistedDraftsByThreadId(\n ) {\n // v3 format\n modelSelectionByProvider = draftCandidate.modelSelectionByProvider as Partial<\n- Record<ProviderKind, ModelSelection>\n+ Record<ProviderInstanceId, ModelSelection>\n >;\n- activeProvider = normalizeProviderKind(draftCandidate.activeProvider);\n+ activeProvider = normalizeProviderInstanceId(draftCandidate.activeProvider);\n } else {\n // v2 or legacy format: migrate\n const normalizedModelOptions =\n@@ -1406,7 +1528,7 @@ function normalizePersistedDraftsByThreadId(\n modelSelection,\n mergedModelOptions,\n );\n- activeProvider = modelSelection?.provider ?? null;\n+ activeProvider = modelSelection?.instanceId ?? null;\n }\n \n const hasModelData =\n@@ -1439,7 +1561,7 @@ function normalizePersistedDraftsByThreadId(\n ...(terminalContexts.length > 0 ? { terminalContexts } : {}),\n ...(hasModelData\n ? {\n- modelSelectionByProvider: cloneModelSelectionByProvider(modelSelectionByProvider),\n+ modelSelectionByProvider: compactModelSelectionByProvider(modelSelectionByProvider),\n activeProvider,\n }\n : {}),\n@@ -1486,7 +1608,7 @@ function migratePersistedComposerDraftStoreState(\n stickyModelSelection,\n nextStickyModelOptions,\n );\n- const stickyActiveProvider = normalizeProviderKind(candidate.stickyProvider) ?? null;\n+ const stickyActiveProvider = normalizeProviderInstanceId(candidate.stickyProvider) ?? null;\n \n const { draftThreadsByThreadKey, logicalProjectDraftThreadKeyByLogicalProjectKey } =\n normalizePersistedDraftThreads(rawDraftThreadsByThreadId, rawProjectDraftThreadIdByProjectKey);\n@@ -1498,7 +1620,7 @@ function migratePersistedComposerDraftStoreState(\n draftsByThreadKey,\n draftThreadsByThreadKey,\n logicalProjectDraftThreadKeyByLogicalProjectKey,\n- stickyModelSelectionByProvider,\n+ stickyModelSelectionByProvider: compactModelSelectionByProvider(stickyModelSelectionByProvider),\n stickyActiveProvider,\n };\n }\n@@ -1543,7 +1665,9 @@ function partializeComposerDraftStoreState(\n : {}),\n ...(hasModelData\n ? {\n- modelSelectionByProvider: cloneModelSelectionByProvider(draft.modelSelectionByProvider),\n+ modelSelectionByProvider: compactModelSelectionByProvider(\n+ draft.modelSelectionByProvider,\n+ ),\n activeProvider: draft.activeProvider,\n }\n : {}),\n@@ -1557,7 +1681,9 @@ function partializeComposerDraftStoreState(\n draftThreadsByThreadKey: state.draftThreadsByThreadKey,\n logicalProjectDraftThreadKeyByLogicalProjectKey:\n state.logicalProjectDraftThreadKeyByLogicalProjectKey,\n- stickyModelSelectionByProvider: state.stickyModelSelectionByProvider,\n+ stickyModelSelectionByProvider: compactModelSelectionByProvider(\n+ state.stickyModelSelectionByProvider,\n+ ),\n stickyActiveProvider: state.stickyActiveProvider,\n };\n }\n@@ -1580,17 +1706,19 @@ function normalizeCurrentPersistedComposerDraftStoreState(\n );\n \n // Handle both v3 (modelSelectionByProvider) and v2/legacy formats\n- let stickyModelSelectionByProvider: Partial<Record<ProviderKind, ModelSelection>> = {};\n- let stickyActiveProvider: ProviderKind | null = null;\n+ let stickyModelSelectionByProvider: Partial<Record<ProviderInstanceId, ModelSelection>> = {};\n+ let stickyActiveProvider: ProviderInstanceId | null = null;\n if (\n normalizedPersistedState.stickyModelSelectionByProvider &&\n typeof normalizedPersistedState.stickyModelSelectionByProvider === "object"\n ) {\n stickyModelSelectionByProvider =\n normalizedPersistedState.stickyModelSelectionByProvider as Partial<\n- Record<ProviderKind, ModelSelection>\n+ Record<ProviderInstanceId, ModelSelection>\n >;\n- stickyActiveProvider = normalizeProviderKind(normalizedPersistedState.stickyActiveProvider);\n+ stickyActiveProvider = normalizeProviderInstanceId(\n+ normalizedPersistedState.stickyActiveProvider,\n+ );\n } else {\n // Legacy migration path\n const stickyModelOptions =\n@@ -1615,7 +1743,7 @@ function normalizeCurrentPersistedComposerDraftStoreState(\n stickyModelSelection,\n nextStickyModelOptions,\n );\n- stickyActiveProvider = normalizeProviderKind(normalizedPersistedState.stickyProvider);\n+ stickyActiveProvider = normalizeProviderInstanceId(normalizedPersistedState.stickyProvider);\n }\n \n return {\n@@ -1625,7 +1753,7 @@ function normalizeCurrentPersistedComposerDraftStoreState(\n ),\n draftThreadsByThreadKey,\n logicalProjectDraftThreadKeyByLogicalProjectKey,\n- stickyModelSelectionByProvider,\n+ stickyModelSelectionByProvider: compactModelSelectionByProvider(stickyModelSelectionByProvider),\n stickyActiveProvider,\n };\n }\n@@ -1754,9 +1882,9 @@ function toHydratedThreadDraft(\n persistedDraft: PersistedComposerThreadDraftState,\n ): ComposerThreadDraftState {\n // The persisted draft is already in v3 shape (migration handles older formats)\n- const modelSelectionByProvider: Partial<Record<ProviderKind, ModelSelection>> =\n+ const modelSelectionByProvider: Partial<Record<ProviderInstanceId, ModelSelection>> =\n persistedDraft.modelSelectionByProvider ?? {};\n- const activeProvider = normalizeProviderKind(persistedDraft.activeProvider) ?? null;\n+ const activeProvider = normalizeProviderInstanceId(persistedDraft.activeProvider) ?? null;\n \n return {\n prompt: persistedDraft.prompt,\n@@ -2117,18 +2245,18 @@ const composerDraftStore = create<ComposerDraftStoreState>()(\n if (!normalized) {\n return state;\n }\n- const nextMap: Partial<Record<ProviderKind, ModelSelection>> = {\n+ const nextMap: Partial<Record<ProviderInstanceId, ModelSelection>> = {\n ...state.stickyModelSelectionByProvider,\n- [normalized.provider]: normalized,\n+ [normalized.instanceId]: normalized,\n };\n if (Equal.equals(state.stickyModelSelectionByProvider, nextMap)) {\n- return state.stickyActiveProvider === normalized.provider\n+ return state.stickyActiveProvider === normalized.instanceId\n ? state\n- : { stickyActiveProvider: normalized.provider };\n+ : { stickyActiveProvider: normalized.instanceId };\n }\n return {\n stickyModelSelectionByProvider: nextMap,\n- stickyActiveProvider: normalized.provider,\n+ stickyActiveProvider: normalized.instanceId,\n };\n });\n },\n@@ -2148,8 +2276,12 @@ const composerDraftStore = create<ComposerDraftStoreState>()(\n const nextMap = { ...base.modelSelectionByProvider };\n for (const [provider, selection] of Object.entries(stickyMap)) {\n if (selection) {\n- const current = nextMap[provider as ProviderKind];\n- nextMap[provider as ProviderKind] = {\n+ // Iteration key comes from the instance-keyed sticky map,\n+ // so coerce the string back to `ProviderInstanceId` for\n+ // the typed lookup.\n+ const instanceKey = provider as ProviderInstanceId;\n+ const current = nextMap[instanceKey];\n+ nextMap[instanceKey] = {\n ...selection,\n model: current?.model ?? selection.model,\n };\n@@ -2235,20 +2367,20 @@ const composerDraftStore = create<ComposerDraftStoreState>()(\n const base = existing ?? createEmptyThreadDraft();\n const nextMap = { ...base.modelSelectionByProvider };\n if (normalized) {\n- const current = nextMap[normalized.provider];\n+ const current = nextMap[normalized.instanceId];\n if (normalized.options !== undefined) {\n // Explicit options provided → use them\n- nextMap[normalized.provider] = normalized;\n+ nextMap[normalized.instanceId] = normalized as ModelSelection;\n } else {\n // No options in selection → preserve existing options, update provider+model\n- nextMap[normalized.provider] = createModelSelection(\n- normalized.provider,\n+ nextMap[normalized.instanceId] = createModelSelection(\n+ normalized.instanceId,\n normalized.model,\n current?.options,\n );\n }\n }\n- const nextActiveProvider = normalized?.provider ?? base.activeProvider;\n+ const nextActiveProvider = normalized?.instanceId ?? base.activeProvider;\n if (\n Equal.equals(base.modelSelectionByProvider, nextMap) &&\n base.activeProvider === nextActiveProvider\n@@ -2284,16 +2416,18 @@ const composerDraftStore = create<ComposerDraftStoreState>()(\n for (const provider of ["codex", "claudeAgent", "cursor", "opencode"] as const) {\n if (!modelOptions || !(provider in modelOptions)) continue;\n const opts = modelOptions[provider];\n- const current = nextMap[provider];\n+ const driverKind = ProviderDriverKind.make(provider);\n+ const instanceKey = defaultInstanceIdForDriver(driverKind);\n+ const current = nextMap[instanceKey];\n if (opts && opts.length > 0) {\n- nextMap[provider] = createModelSelection(\n- provider,\n- current?.model ?? DEFAULT_MODEL_BY_PROVIDER[provider],\n+ nextMap[instanceKey] = createModelSelection(\n+ instanceKey,\n+ current?.model ?? DEFAULT_MODEL_BY_PROVIDER[driverKind] ?? DEFAULT_MODEL,\n opts,\n );\n } else if (current?.options) {\n const { options: _, ...rest } = current;\n- nextMap[provider] = rest as ModelSelection;\n+ nextMap[instanceKey] = rest as ModelSelection;\n }\n }\n if (Equal.equals(base.modelSelectionByProvider, nextMap)) {\n@@ -2317,13 +2451,15 @@ const composerDraftStore = create<ComposerDraftStoreState>()(\n if (threadKey.length === 0) {\n return;\n }\n- const normalizedProvider = normalizeProviderKind(provider);\n+ const normalizedProvider = normalizeProviderDriverKind(provider);\n if (normalizedProvider === null) {\n return;\n }\n+ const instanceKey = defaultInstanceIdForDriver(normalizedProvider);\n const fallbackModel =\n normalizeModelSlug(options?.model, normalizedProvider) ??\n- DEFAULT_MODEL_BY_PROVIDER[normalizedProvider];\n+ DEFAULT_MODEL_BY_PROVIDER[normalizedProvider] ??\n+ DEFAULT_MODEL;\n const providerOpts =\n nextProviderOptions && nextProviderOptions.length > 0 ? nextProviderOptions : undefined;\n \n@@ -2333,16 +2469,16 @@ const composerDraftStore = create<ComposerDraftStoreState>()(\n \n // Update the map entry for this provider\n const nextMap = { ...base.modelSelectionByProvider };\n- const currentForProvider = nextMap[normalizedProvider];\n+ const currentForProvider = nextMap[instanceKey];\n if (providerOpts) {\n- nextMap[normalizedProvider] = createModelSelection(\n- normalizedProvider,\n+ nextMap[instanceKey] = createModelSelection(\n+ instanceKey,\n currentForProvider?.model ?? fallbackModel,\n providerOpts,\n );\n } else if (currentForProvider && (currentForProvider.options?.length ?? 0) > 0) {\n const { options: _, ...rest } = currentForProvider;\n- nextMap[normalizedProvider] = rest as ModelSelection;\n+ nextMap[instanceKey] = rest as ModelSelection;\n }\n \n // Handle sticky persistence\n@@ -2351,20 +2487,20 @@ const composerDraftStore = create<ComposerDraftStoreState>()(\n if (options?.persistSticky === true) {\n nextStickyMap = { ...state.stickyModelSelectionByProvider };\n const stickyBase =\n- nextStickyMap[normalizedProvider] ??\n- base.modelSelectionByProvider[normalizedProvider] ??\n- createModelSelection(normalizedProvider, fallbackModel);\n+ nextStickyMap[instanceKey] ??\n+ base.modelSelectionByProvider[instanceKey] ??\n+ createModelSelection(instanceKey, fallbackModel);\n if (providerOpts) {\n- nextStickyMap[normalizedProvider] = createModelSelection(\n- normalizedProvider,\n+ nextStickyMap[instanceKey] = createModelSelection(\n+ instanceKey,\n stickyBase.model,\n providerOpts,\n );\n } else if ((stickyBase.options?.length ?? 0) > 0) {\n const { options: _, ...rest } = stickyBase;\n- nextStickyMap[normalizedProvider] = rest as ModelSelection;\n+ nextStickyMap[instanceKey] = rest as ModelSelection;\n }\n- nextStickyActiveProvider = base.activeProvider ?? normalizedProvider;\n+ nextStickyActiveProvider = base.activeProvider ?? instanceKey;\n }\n \n if (\n@@ -2815,7 +2951,13 @@ export function useEffectiveComposerModelState(input: {\n threadRef?: ComposerThreadTarget;\n draftId?: DraftId;\n providers: ReadonlyArray<ServerProvider>;\n- selectedProvider: ProviderKind;\n+ selectedProvider: ProviderDriverKind;\n+ /**\n+ * When supplied, the draft\'s saved selection for this instance takes\n+ * precedence over the driver-kind bucket — so a custom `codex_personal`\n+ * instance reads its own model, not the default Codex\'s.\n+ */\n+ selectedInstanceId?: ProviderInstanceId | null | undefined;\n threadModelSelection: ModelSelection | null | undefined;\n projectModelSelection: ModelSelection | null | undefined;\n settings: UnifiedSettings;\n@@ -2828,6 +2970,7 @@ export function useEffectiveComposerModelState(input: {\n draft,\n providers: input.providers,\n selectedProvider: input.selectedProvider,\n+ selectedInstanceId: input.selectedInstanceId,\n threadModelSelection: input.threadModelSelection,\n projectModelSelection: input.projectModelSelection,\n settings: input.settings,\n@@ -2837,6 +2980,7 @@ export function useEffectiveComposerModelState(input: {\n input.providers,\n input.settings,\n input.projectModelSelection,\n+ input.selectedInstanceId,\n input.selectedProvider,\n input.threadModelSelection,\n ],\ndiff --git a/apps/web/src/environmentGrouping.test.ts b/apps/web/src/environmentGrouping.test.ts\nindex 9ae26fe8b4..8dd5eb89a0 100644\n--- a/apps/web/src/environmentGrouping.test.ts\n+++ b/apps/web/src/environmentGrouping.test.ts\n@@ -1,4 +1,4 @@\n-import { EnvironmentId, ProjectId, ThreadId } from "@t3tools/contracts";\n+import { EnvironmentId, ProjectId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";\n import { scopeProjectRef } from "@t3tools/client-runtime";\n import { describe, expect, it } from "vitest";\n \n@@ -48,7 +48,7 @@ function makeProject(\n ): Project {\n return {\n cwd: `/tmp/${overrides.name}`,\n- defaultModelSelection: { provider: "codex" as const, model: "gpt-5-codex" },\n+ defaultModelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5-codex" },\n createdAt: "2026-01-01T00:00:00.000Z",\n updatedAt: "2026-01-01T00:00:00.000Z",\n scripts: [],\ndiff --git a/apps/web/src/environments/runtime/service.threadSubscriptions.test.ts b/apps/web/src/environments/runtime/service.threadSubscriptions.test.ts\nindex 5f169adc9b..efecfdca8e 100644\n--- a/apps/web/src/environments/runtime/service.threadSubscriptions.test.ts\n+++ b/apps/web/src/environments/runtime/service.threadSubscriptions.test.ts\n@@ -2,6 +2,7 @@ import { QueryClient } from "@tanstack/react-query";\n import {\n EnvironmentId,\n ProjectId,\n+ ProviderInstanceId,\n ThreadId,\n TurnId,\n type OrchestrationShellSnapshot,\n@@ -98,7 +99,7 @@ function makeThreadShellSnapshot(params: {\n projectId,\n title: "Thread",\n modelSelection: {\n- provider: "codex",\n+ instanceId: ProviderInstanceId.make("codex"),\n model: "gpt-5-codex",\n },\n runtimeMode: "full-access",\ndiff --git a/apps/web/src/hooks/useCommitOnBlur.ts b/apps/web/src/hooks/useCommitOnBlur.ts\nnew file mode 100644\nindex 0000000000..43244762aa\n--- /dev/null\n+++ b/apps/web/src/hooks/useCommitOnBlur.ts\n@@ -0,0 +1,49 @@\n+import { type ChangeEvent, type KeyboardEvent, useEffect, useRef, useState } from "react";\n+\n+/**\n+ * Buffer text input locally so keystrokes don\'t cause a settings-wide\n+ * re-render (and optionally a server RPC round-trip) on every character.\n+ * `onCommit` fires on blur and on Enter.\n+ *\n+ * The draft resynchronizes from the upstream `value` only when the input\n+ * is not focused, so an external push (e.g. an optimistic settings\n+ * update from the user\'s own commit, or a reset to defaults) doesn\'t\n+ * clobber an in-progress edit.\n+ *\n+ * Returns a bag of props that should be spread onto an `<Input>`:\n+ *\n+ * const bag = useCommitOnBlur(instance.displayName ?? "", (next) => {...});\n+ * <Input {...bag} placeholder="e.g. Work" />\n+ */\n+export function useCommitOnBlur(value: string, onCommit: (next: string) => void) {\n+ const [draft, setDraft] = useState(value);\n+ const focusedRef = useRef(false);\n+\n+ useEffect(() => {\n+ if (!focusedRef.current) {\n+ setDraft(value);\n+ }\n+ }, [value]);\n+\n+ return {\n+ value: draft,\n+ onChange: (event: ChangeEvent<HTMLInputElement>) => {\n+ setDraft(event.target.value);\n+ },\n+ onFocus: () => {\n+ focusedRef.current = true;\n+ },\n+ onBlur: () => {\n+ focusedRef.current = false;\n+ if (draft !== value) {\n+ onCommit(draft);\n+ }\n+ },\n+ onKeyDown: (event: KeyboardEvent<HTMLInputElement>) => {\n+ if (event.key === "Enter") {\n+ event.preventDefault();\n+ (event.target as HTMLInputElement).blur();\n+ }\n+ },\n+ };\n+}\ndiff --git a/apps/web/src/lib/threadSort.test.ts b/apps/web/src/lib/threadSort.test.ts\nindex f80260a69d..2a69357c49 100644\n--- a/apps/web/src/lib/threadSort.test.ts\n+++ b/apps/web/src/lib/threadSort.test.ts\n@@ -1,5 +1,11 @@\n import { describe, expect, it } from "vitest";\n-import { DEFAULT_RUNTIME_MODE, EnvironmentId, ProjectId, ThreadId } from "@t3tools/contracts";\n+import {\n+ DEFAULT_RUNTIME_MODE,\n+ EnvironmentId,\n+ ProjectId,\n+ ProviderInstanceId,\n+ ThreadId,\n+} from "@t3tools/contracts";\n import type { Thread } from "../types";\n import { getLatestThreadForProject, sortThreads } from "./threadSort";\n \n@@ -13,7 +19,7 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {\n codexThreadId: null,\n projectId: PROJECT_ID,\n title: "Thread",\n- modelSelection: { provider: "codex", model: "gpt-5.4" },\n+ modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },\n runtimeMode: DEFAULT_RUNTIME_MODE,\n interactionMode: "default",\n session: null,\ndiff --git a/apps/web/src/localApi.test.ts b/apps/web/src/localApi.test.ts\nindex c361cbd787..fbdd203e99 100644\n--- a/apps/web/src/localApi.test.ts\n+++ b/apps/web/src/localApi.test.ts\n@@ -6,6 +6,8 @@ import {\n type GitStatusResult,\n ProjectId,\n type OrchestrationShellStreamItem,\n+ ProviderDriverKind,\n+ ProviderInstanceId,\n type ServerConfig,\n type ServerProvider,\n type TerminalEvent,\n@@ -207,7 +209,8 @@ function makeDesktopBridge(overrides: Partial<DesktopBridge> = {}): DesktopBridg\n \n const defaultProviders: ReadonlyArray<ServerProvider> = [\n {\n- provider: "codex",\n+ instanceId: ProviderInstanceId.make("codex"),\n+ driver: ProviderDriverKind.make("codex"),\n enabled: true,\n installed: true,\n version: "0.116.0",\n@@ -328,7 +331,7 @@ describe("wsApi", () => {\n title: "Project",\n workspaceRoot: "/tmp/workspace",\n defaultModelSelection: {\n- provider: "codex",\n+ instanceId: ProviderInstanceId.make("codex"),\n model: "gpt-5-codex",\n },\n scripts: [],\n@@ -394,7 +397,7 @@ describe("wsApi", () => {\n title: "Project",\n workspaceRoot: "/tmp/project",\n defaultModelSelection: {\n- provider: "codex",\n+ instanceId: ProviderInstanceId.make("codex"),\n model: "gpt-5-codex",\n },\n createdAt: "2026-02-24T00:00:00.000Z",\n@@ -534,6 +537,7 @@ describe("wsApi", () => {\n confirmThreadDelete: false,\n diffWordWrap: true,\n favorites: [],\n+ providerModelPreferences: {},\n sidebarProjectGroupingMode: "repository_path" as const,\n sidebarProjectGroupingOverrides: {\n "environment-local:/tmp/project": "separate" as const,\n@@ -593,6 +597,7 @@ describe("wsApi", () => {\n confirmThreadDelete: false,\n diffWordWrap: true,\n favorites: [],\n+ providerModelPreferences: {},\n sidebarProjectGroupingMode: "repository_path" as const,\n sidebarProjectGroupingOverrides: {\n "environment-local:/tmp/project": "separate" as const,\ndiff --git a/apps/web/src/modelOrdering.test.ts b/apps/web/src/modelOrdering.test.ts\nnew file mode 100644\nindex 0000000000..82a9d8f9af\n--- /dev/null\n+++ b/apps/web/src/modelOrdering.test.ts\n@@ -0,0 +1,52 @@\n+import { describe, expect, it } from "vitest";\n+import { ProviderInstanceId } from "@t3tools/contracts";\n+\n+import {\n+ providerModelKey,\n+ sortModelsForProviderInstance,\n+ sortProviderModelItems,\n+} from "./modelOrdering";\n+\n+const CODEX_WORK_ID = ProviderInstanceId.make("codex_work");\n+const CLAUDE_ID = ProviderInstanceId.make("claudeAgent");\n+\n+describe("model ordering", () => {\n+ it("groups favorites first while preserving provider model order inside each group", () => {\n+ const models = [\n+ { slug: "gpt-5.5" },\n+ { slug: "gpt-5.4-mini" },\n+ { slug: "crest-alpha" },\n+ { slug: "gpt-5.3-codex" },\n+ ];\n+\n+ expect(\n+ sortModelsForProviderInstance(models, {\n+ favoriteModels: ["gpt-5.5", "gpt-5.4-mini", "crest-alpha"],\n+ groupFavorites: true,\n+ modelOrder: ["gpt-5.4-mini", "gpt-5.5", "crest-alpha", "gpt-5.3-codex"],\n+ }).map((model) => model.slug),\n+ ).toEqual(["gpt-5.4-mini", "gpt-5.5", "crest-alpha", "gpt-5.3-codex"]);\n+ });\n+\n+ it("sorts the favorites view by provider order, then provider model order", () => {\n+ const items = [\n+ { instanceId: CODEX_WORK_ID, slug: "gpt-5.4-mini" },\n+ { instanceId: CODEX_WORK_ID, slug: "gpt-5.5" },\n+ { instanceId: CODEX_WORK_ID, slug: "crest-alpha" },\n+ { instanceId: CLAUDE_ID, slug: "claude-opus-4-6" },\n+ ];\n+ const favoriteKeys = [\n+ providerModelKey(CODEX_WORK_ID, "gpt-5.5"),\n+ providerModelKey(CLAUDE_ID, "claude-opus-4-6"),\n+ providerModelKey(CODEX_WORK_ID, "gpt-5.4-mini"),\n+ providerModelKey(CODEX_WORK_ID, "crest-alpha"),\n+ ];\n+\n+ expect(\n+ sortProviderModelItems(items, {\n+ favoriteModelKeys: favoriteKeys,\n+ instanceOrder: [CODEX_WORK_ID, CLAUDE_ID],\n+ }).map((item) => item.slug),\n+ ).toEqual(["gpt-5.4-mini", "gpt-5.5", "crest-alpha", "claude-opus-4-6"]);\n+ });\n+});\ndiff --git a/apps/web/src/modelOrdering.ts b/apps/web/src/modelOrdering.ts\nnew file mode 100644\nindex 0000000000..c8b5d9cec6\n--- /dev/null\n+++ b/apps/web/src/modelOrdering.ts\n@@ -0,0 +1,86 @@\n+import type { ProviderInstanceId } from "@t3tools/contracts";\n+import * as Arr from "effect/Array";\n+import * as Order from "effect/Order";\n+\n+export interface ModelSlugItem {\n+ readonly slug: string;\n+}\n+\n+export interface ProviderModelItem extends ModelSlugItem {\n+ readonly instanceId: ProviderInstanceId;\n+}\n+\n+export function providerModelKey(instanceId: ProviderInstanceId, slug: string): string {\n+ return `${instanceId}:${slug}`;\n+}\n+\n+function rankByValue(values: ReadonlyArray<string>): ReadonlyMap<string, number> {\n+ return new Map(Arr.map(values, (value, index) => [value, index] as const));\n+}\n+\n+function toSet(\n+ values: ReadonlySet<string> | ReadonlyArray<string> | undefined,\n+): ReadonlySet<string> {\n+ return values instanceof Set ? values : new Set(values ?? []);\n+}\n+\n+function byOptionalRank<T>(rank: (item: T) => number | undefined): Order.Order<T> {\n+ return Order.mapInput(Order.Number, (item: T) => rank(item) ?? Number.POSITIVE_INFINITY);\n+}\n+\n+function byTrueFirst<T>(predicate: (item: T) => boolean): Order.Order<T> {\n+ return Order.mapInput(Order.flip(Order.Boolean), predicate);\n+}\n+\n+export function sortModelsForProviderInstance<T extends ModelSlugItem>(\n+ models: ReadonlyArray<T>,\n+ options?: {\n+ readonly modelOrder?: ReadonlyArray<string>;\n+ readonly favoriteModels?: ReadonlySet<string> | ReadonlyArray<string>;\n+ readonly groupFavorites?: boolean;\n+ },\n+): T[] {\n+ const modelOrder = options?.modelOrder ?? [];\n+ const favoriteModels = toSet(options?.favoriteModels);\n+ const orderBySlug = rankByValue(modelOrder);\n+ const originalOrder = rankByValue(Arr.map(models, (model) => model.slug));\n+ const orders: Array<Order.Order<T>> = [\n+ ...(options?.groupFavorites === true\n+ ? [byTrueFirst<T>((model) => favoriteModels.has(model.slug))]\n+ : []),\n+ byOptionalRank((model) => orderBySlug.get(model.slug)),\n+ byOptionalRank((model) => originalOrder.get(model.slug)),\n+ ];\n+\n+ return Arr.sort(models, Order.combineAll(orders));\n+}\n+\n+export function sortProviderModelItems<T extends ProviderModelItem>(\n+ items: ReadonlyArray<T>,\n+ options?: {\n+ readonly favoriteModelKeys?: ReadonlySet<string> | ReadonlyArray<string>;\n+ readonly groupFavorites?: boolean;\n+ readonly instanceOrder?: ReadonlyArray<ProviderInstanceId>;\n+ },\n+): T[] {\n+ const favoriteModelKeys = toSet(options?.favoriteModelKeys);\n+ const instanceOrder = new Map(\n+ Arr.map(options?.instanceOrder ?? [], (instanceId, index) => [instanceId, index] as const),\n+ );\n+ const originalOrder = rankByValue(\n+ Arr.map(items, (item) => providerModelKey(item.instanceId, item.slug)),\n+ );\n+ const orders: Array<Order.Order<T>> = [\n+ ...(options?.groupFavorites === true\n+ ? [\n+ byTrueFirst<T>((item) =>\n+ favoriteModelKeys.has(providerModelKey(item.instanceId, item.slug)),\n+ ),\n+ ]\n+ : []),\n+ byOptionalRank((item) => instanceOrder.get(item.instanceId)),\n+ byOptionalRank((item) => originalOrder.get(providerModelKey(item.instanceId, item.slug))),\n+ ];\n+\n+ return Arr.sort(items, Order.combineAll(orders));\n+}\ndiff --git a/apps/web/src/modelSelection.test.ts b/apps/web/src/modelSelection.test.ts\nnew file mode 100644\nindex 0000000000..67758cac5d\n--- /dev/null\n+++ b/apps/web/src/modelSelection.test.ts\n@@ -0,0 +1,251 @@\n+import { ProviderDriverKind, ProviderInstanceId, type ServerProvider } from "@t3tools/contracts";\n+import { DEFAULT_UNIFIED_SETTINGS, type UnifiedSettings } from "@t3tools/contracts/settings";\n+import { describe, expect, it } from "vitest";\n+import { deriveProviderInstanceEntries } from "./providerInstances";\n+import {\n+ getAppModelOptionsForInstance,\n+ resolveAppModelSelectionForInstance,\n+ resolveAppModelSelectionState,\n+} from "./modelSelection";\n+\n+function provider(input: {\n+ provider?: ProviderDriverKind;\n+ instanceId: string;\n+ models?: ReadonlyArray<string>;\n+}): ServerProvider {\n+ const driver =\n+ input.provider ??\n+ (input.instanceId.startsWith("claude_")\n+ ? ProviderDriverKind.make("claudeAgent")\n+ : ProviderDriverKind.make("codex"));\n+ return {\n+ instanceId: ProviderInstanceId.make(input.instanceId),\n+ driver,\n+ enabled: true,\n+ installed: true,\n+ version: null,\n+ status: "ready",\n+ auth: { status: "authenticated" },\n+ checkedAt: "2026-01-01T00:00:00.000Z",\n+ models: (input.models ?? []).map((slug) => ({\n+ slug,\n+ name: slug,\n+ isCustom: false,\n+ capabilities: {},\n+ })),\n+ slashCommands: [],\n+ skills: [],\n+ };\n+}\n+\n+function settingsWithProviderInstances(): UnifiedSettings {\n+ return {\n+ ...DEFAULT_UNIFIED_SETTINGS,\n+ providerInstances: {\n+ [ProviderInstanceId.make("claudeAgent")]: {\n+ driver: ProviderDriverKind.make("claudeAgent"),\n+ config: { customModels: [] },\n+ },\n+ [ProviderInstanceId.make("claude_openrouter")]: {\n+ driver: ProviderDriverKind.make("claudeAgent"),\n+ config: { customModels: ["openai/gpt-5.5"] },\n+ },\n+ },\n+ };\n+}\n+\n+describe("instance-scoped model selection", () => {\n+ it("keeps custom models on the provider instance that declared them", () => {\n+ const providers = [\n+ provider({\n+ instanceId: "claudeAgent",\n+ models: ["claude-sonnet-4-6"],\n+ }),\n+ provider({\n+ instanceId: "claude_openrouter",\n+ models: ["claude-sonnet-4-6"],\n+ }),\n+ ];\n+ const entries = deriveProviderInstanceEntries(providers);\n+ const stock = entries.find((entry) => entry.instanceId === "claudeAgent")!;\n+ const openrouter = entries.find((entry) => entry.instanceId === "claude_openrouter")!;\n+\n+ expect(\n+ getAppModelOptionsForInstance(settingsWithProviderInstances(), stock).map(\n+ (option) => option.slug,\n+ ),\n+ ).not.toContain("openai/gpt-5.5");\n+ expect(\n+ getAppModelOptionsForInstance(settingsWithProviderInstances(), openrouter).map(\n+ (option) => option.slug,\n+ ),\n+ ).toContain("openai/gpt-5.5");\n+ });\n+\n+ it("resolves a custom slug against the selected custom instance", () => {\n+ const providers = [\n+ provider({ provider: ProviderDriverKind.make("claudeAgent"), instanceId: "claudeAgent" }),\n+ provider({\n+ provider: ProviderDriverKind.make("claudeAgent"),\n+ instanceId: "claude_openrouter",\n+ }),\n+ ];\n+\n+ expect(\n+ resolveAppModelSelectionForInstance(\n+ ProviderInstanceId.make("claude_openrouter"),\n+ settingsWithProviderInstances(),\n+ providers,\n+ "openai/gpt-5.5",\n+ ),\n+ ).toBe("openai/gpt-5.5");\n+ });\n+\n+ it("does not inject an unknown selected slug into the stock instance list", () => {\n+ const providers = [\n+ provider({\n+ instanceId: "claudeAgent",\n+ models: ["claude-sonnet-4-6"],\n+ }),\n+ provider({\n+ instanceId: "claude_openrouter",\n+ models: ["claude-sonnet-4-6"],\n+ }),\n+ ];\n+ const stock = deriveProviderInstanceEntries(providers).find(\n+ (entry) => entry.instanceId === "claudeAgent",\n+ )!;\n+\n+ expect(\n+ getAppModelOptionsForInstance(settingsWithProviderInstances(), stock).map(\n+ (option) => option.slug,\n+ ),\n+ ).not.toContain("openai/gpt-5.5");\n+ });\n+\n+ it("hides server models from the instance option list", () => {\n+ const providers = [\n+ provider({\n+ instanceId: "claudeAgent",\n+ models: ["claude-opus-4-6", "claude-sonnet-4-6"],\n+ }),\n+ ];\n+ const settings: UnifiedSettings = {\n+ ...settingsWithProviderInstances(),\n+ providerModelPreferences: {\n+ [ProviderInstanceId.make("claudeAgent")]: {\n+ hiddenModels: ["claude-opus-4-6"],\n+ modelOrder: [],\n+ },\n+ },\n+ };\n+ const stock = deriveProviderInstanceEntries(providers).find(\n+ (entry) => entry.instanceId === "claudeAgent",\n+ )!;\n+\n+ expect(getAppModelOptionsForInstance(settings, stock).map((option) => option.slug)).toEqual([\n+ "claude-sonnet-4-6",\n+ ]);\n+ });\n+\n+ it("applies persisted per-instance model ordering", () => {\n+ const providers = [\n+ provider({\n+ instanceId: "claudeAgent",\n+ models: ["claude-opus-4-6", "claude-sonnet-4-6", "claude-haiku-4-5"],\n+ }),\n+ ];\n+ const settings: UnifiedSettings = {\n+ ...settingsWithProviderInstances(),\n+ providerModelPreferences: {\n+ [ProviderInstanceId.make("claudeAgent")]: {\n+ hiddenModels: [],\n+ modelOrder: ["claude-haiku-4-5", "claude-opus-4-6"],\n+ },\n+ },\n+ };\n+ const stock = deriveProviderInstanceEntries(providers).find(\n+ (entry) => entry.instanceId === "claudeAgent",\n+ )!;\n+\n+ expect(getAppModelOptionsForInstance(settings, stock).map((option) => option.slug)).toEqual([\n+ "claude-haiku-4-5",\n+ "claude-opus-4-6",\n+ "claude-sonnet-4-6",\n+ ]);\n+ });\n+\n+ it("falls back when the selected model is hidden", () => {\n+ const providers = [\n+ provider({\n+ instanceId: "claudeAgent",\n+ models: ["claude-opus-4-6", "claude-sonnet-4-6"],\n+ }),\n+ ];\n+ const settings: UnifiedSettings = {\n+ ...settingsWithProviderInstances(),\n+ providerModelPreferences: {\n+ [ProviderInstanceId.make("claudeAgent")]: {\n+ hiddenModels: ["claude-opus-4-6"],\n+ modelOrder: [],\n+ },\n+ },\n+ };\n+\n+ expect(\n+ resolveAppModelSelectionForInstance(\n+ ProviderInstanceId.make("claudeAgent"),\n+ settings,\n+ providers,\n+ "claude-opus-4-6",\n+ ),\n+ ).toBe("claude-sonnet-4-6");\n+ });\n+\n+ it("falls back instead of resolving a custom slug against the wrong instance", () => {\n+ const providers = [\n+ provider({\n+ instanceId: "claudeAgent",\n+ models: ["claude-sonnet-4-6"],\n+ }),\n+ provider({\n+ instanceId: "claude_openrouter",\n+ models: ["claude-sonnet-4-6"],\n+ }),\n+ ];\n+\n+ expect(\n+ resolveAppModelSelectionForInstance(\n+ ProviderInstanceId.make("claudeAgent"),\n+ settingsWithProviderInstances(),\n+ providers,\n+ "openai/gpt-5.5",\n+ ),\n+ ).toBe("claude-sonnet-4-6");\n+ });\n+\n+ it("preserves custom provider instances in settings model selection", () => {\n+ const providers = [\n+ provider({\n+ instanceId: "claudeAgent",\n+ models: ["claude-sonnet-4-6"],\n+ }),\n+ provider({\n+ instanceId: "claude_openrouter",\n+ models: ["claude-sonnet-4-6"],\n+ }),\n+ ];\n+ const settings: UnifiedSettings = {\n+ ...settingsWithProviderInstances(),\n+ textGenerationModelSelection: {\n+ instanceId: ProviderInstanceId.make("claude_openrouter"),\n+ model: "openai/gpt-5.5",\n+ },\n+ };\n+\n+ expect(resolveAppModelSelectionState(settings, providers)).toEqual({\n+ instanceId: ProviderInstanceId.make("claude_openrouter"),\n+ model: "openai/gpt-5.5",\n+ });\n+ });\n+});\ndiff --git a/apps/web/src/modelSelection.ts b/apps/web/src/modelSelection.ts\nindex 80e9e241e7..8ba0c8fa5d 100644\n--- a/apps/web/src/modelSelection.ts\n+++ b/apps/web/src/modelSelection.ts\n@@ -1,7 +1,10 @@\n import {\n+ DEFAULT_GIT_TEXT_GENERATION_MODEL,\n DEFAULT_GIT_TEXT_GENERATION_MODEL_BY_PROVIDER,\n+ defaultInstanceIdForDriver,\n type ModelSelection,\n- type ProviderKind,\n+ ProviderDriverKind,\n+ ProviderInstanceId,\n type ServerProvider,\n } from "@t3tools/contracts";\n import {\n@@ -17,9 +20,52 @@ import {\n resolveSelectableProvider,\n } from "./providerModels";\n import { ModelEsque } from "./components/chat/providerIconUtils";\n+import { type ProviderInstanceEntry, deriveProviderInstanceEntries } from "./providerInstances";\n+import { sortModelsForProviderInstance } from "./modelOrdering";\n \n const MAX_CUSTOM_MODEL_COUNT = 32;\n export const MAX_CUSTOM_MODEL_LENGTH = 256;\n+const DEFAULT_TEXT_GENERATION_INSTANCE_ID = ProviderInstanceId.make("codex");\n+\n+/**\n+ * Resolve the custom-model list for a given instance, preferring the\n+ * instance\'s own `providerInstances[id].config.customModels` blob when\n+ * present and falling back to the legacy per-kind\n+ * `settings.providers[kind].customModels` bucket for default instances only.\n+ *\n+ * The Settings UI promotes the legacy bucket into an explicit\n+ * `providerInstances[defaultId]` entry on every edit (the "migrate on\n+ * first write" scheme documented in\n+ * `ProviderInstanceRegistryHydration`), so this helper exists primarily\n+ * so readers pick up that promotion immediately — and so first-time\n+ * viewers on pre-migration settings still see their legacy list on\n+ * default slots. Custom instances intentionally do not read the legacy\n+ * per-driver bucket; otherwise one custom model added to `claude_openrouter`\n+ * can appear on the stock `claudeAgent` instance.\n+ */\n+function readInstanceCustomModels(\n+ settings: UnifiedSettings,\n+ instanceId: ProviderInstanceId,\n+ driverKind: ProviderDriverKind,\n+): ReadonlyArray<string> {\n+ const instance = settings.providerInstances?.[instanceId];\n+ const config = instance?.config;\n+ if (config !== null && typeof config === "object") {\n+ const value = (config as Record<string, unknown>).customModels;\n+ if (Array.isArray(value)) {\n+ return value.filter((entry): entry is string => typeof entry === "string");\n+ }\n+ }\n+ const defaultInstanceId = defaultInstanceIdForDriver(driverKind);\n+ if (instanceId !== defaultInstanceId) {\n+ return [];\n+ }\n+ const legacyProviders = settings.providers as Record<\n+ string,\n+ { readonly customModels: ReadonlyArray<string> } | undefined\n+ >;\n+ return legacyProviders[driverKind]?.customModels ?? [];\n+}\n \n export interface AppModelOption {\n slug: string;\n@@ -29,10 +75,47 @@ export interface AppModelOption {\n isCustom: boolean;\n }\n \n+function toAppModelOption(model: ServerProvider["models"][number]): AppModelOption {\n+ const option: AppModelOption = {\n+ slug: model.slug,\n+ name: model.name,\n+ isCustom: model.isCustom,\n+ };\n+ if (model.shortName) option.shortName = model.shortName;\n+ if (model.subProvider) option.subProvider = model.subProvider;\n+ return option;\n+}\n+\n+function readInstanceModelPreferences(\n+ settings: UnifiedSettings,\n+ instanceId: ProviderInstanceId,\n+): { readonly hiddenModels: ReadonlyArray<string>; readonly modelOrder: ReadonlyArray<string> } {\n+ return (\n+ settings.providerModelPreferences?.[instanceId] ?? {\n+ hiddenModels: [],\n+ modelOrder: [],\n+ }\n+ );\n+}\n+\n+function applyInstanceModelPreferences(\n+ options: ReadonlyArray<AppModelOption>,\n+ preferences: {\n+ readonly hiddenModels: ReadonlyArray<string>;\n+ readonly modelOrder: ReadonlyArray<string>;\n+ },\n+): AppModelOption[] {\n+ const hiddenModels = new Set(preferences.hiddenModels);\n+ return sortModelsForProviderInstance(\n+ options.filter((option) => option.isCustom || !hiddenModels.has(option.slug)),\n+ { modelOrder: preferences.modelOrder },\n+ );\n+}\n+\n export function normalizeCustomModelSlugs(\n models: Iterable<string | null | undefined>,\n builtInModelSlugs: ReadonlySet<string>,\n- provider: ProviderKind = "codex",\n+ provider: ProviderDriverKind = ProviderDriverKind.make("codex"),\n ): string[] {\n const normalizedModels: string[] = [];\n const seen = new Set<string>();\n@@ -61,27 +144,23 @@ export function normalizeCustomModelSlugs(\n export function getAppModelOptions(\n settings: UnifiedSettings,\n providers: ReadonlyArray<ServerProvider>,\n- provider: ProviderKind,\n- selectedModel?: string | null,\n+ provider: ProviderDriverKind,\n+ _selectedModel?: string | null,\n ): AppModelOption[] {\n- const options: AppModelOption[] = getProviderModels(providers, provider).map(\n- ({ slug, name, shortName, subProvider, isCustom }) => ({\n- slug,\n- name,\n- ...(shortName ? { shortName } : {}),\n- ...(subProvider ? { subProvider } : {}),\n- isCustom,\n- }),\n- );\n+ const options: AppModelOption[] = getProviderModels(providers, provider).map(toAppModelOption);\n const seen = new Set(options.map((option) => option.slug));\n- const trimmedSelectedModel = selectedModel?.trim().toLowerCase();\n const builtInModelSlugs = new Set(\n getProviderModels(providers, provider)\n .filter((model) => !model.isCustom)\n .map((model) => model.slug),\n );\n \n- const customModels = settings.providers[provider].customModels;\n+ // Read from the default instance\'s config first (that\'s where edits\n+ // now land), falling back to the legacy per-kind bucket so unmigrated\n+ // settings and the initial render before the first write both still\n+ // see the user\'s authored custom models.\n+ const defaultInstanceId = defaultInstanceIdForDriver(provider);\n+ const customModels = readInstanceCustomModels(settings, defaultInstanceId, provider);\n for (const slug of normalizeCustomModelSlugs(customModels, builtInModelSlugs, provider)) {\n if (seen.has(slug)) {\n continue;\n@@ -95,27 +174,52 @@ export function getAppModelOptions(\n });\n }\n \n- const normalizedSelectedModel = normalizeModelSlug(selectedModel, provider);\n- const selectedModelMatchesExistingName =\n- typeof trimmedSelectedModel === "string" &&\n- options.some((option) => option.name.toLowerCase() === trimmedSelectedModel);\n- if (\n- normalizedSelectedModel &&\n- !seen.has(normalizedSelectedModel) &&\n- !selectedModelMatchesExistingName\n- ) {\n- options.push({\n- slug: normalizedSelectedModel,\n- name: normalizedSelectedModel,\n- isCustom: true,\n- });\n+ return applyInstanceModelPreferences(\n+ options,\n+ readInstanceModelPreferences(settings, defaultInstanceId),\n+ );\n+}\n+\n+/**\n+ * Instance-scoped variant of {@link getAppModelOptions}. Built-in models\n+ * come from the instance\'s own `entry.models` snapshot (rather than the\n+ * first-matching-kind fallback in `getProviderModels`), so each custom\n+ * instance gets the precise model list its driver reported. Custom model\n+ * slugs come from the instance\'s own `providerInstances[id].config.customModels`\n+ * when present, falling back to the legacy per-kind\n+ * `settings.providers[driverKind].customModels` bucket for default\n+ * instances only. This keeps two instances of the same kind from leaking\n+ * custom slugs into each other.\n+ */\n+export function getAppModelOptionsForInstance(\n+ settings: UnifiedSettings,\n+ entry: ProviderInstanceEntry,\n+): AppModelOption[] {\n+ const options: AppModelOption[] = entry.models.map(toAppModelOption);\n+ const seen = new Set(options.map((option) => option.slug));\n+ const builtInModelSlugs = new Set(\n+ entry.models.filter((model) => !model.isCustom).map((model) => model.slug),\n+ );\n+\n+ const customModels = readInstanceCustomModels(settings, entry.instanceId, entry.driverKind);\n+ const normalizer = entry.driverKind;\n+ for (const slug of normalizeCustomModelSlugs(customModels, builtInModelSlugs, normalizer)) {\n+ if (seen.has(slug)) {\n+ continue;\n+ }\n+\n+ seen.add(slug);\n+ options.push({ slug, name: slug, isCustom: true });\n }\n \n- return options;\n+ return applyInstanceModelPreferences(\n+ options,\n+ readInstanceModelPreferences(settings, entry.instanceId),\n+ );\n }\n \n export function resolveAppModelSelection(\n- provider: ProviderKind,\n+ provider: ProviderDriverKind,\n settings: UnifiedSettings,\n providers: ReadonlyArray<ServerProvider>,\n selectedModel: string | null | undefined,\n@@ -128,38 +232,41 @@ export function resolveAppModelSelection(\n );\n }\n \n-export function getCustomModelOptionsByProvider(\n+export function resolveAppModelSelectionForInstance(\n+ instanceId: ProviderInstanceId,\n settings: UnifiedSettings,\n providers: ReadonlyArray<ServerProvider>,\n- selectedProvider?: ProviderKind | null,\n- selectedModel?: string | null,\n-): Record<ProviderKind, ReadonlyArray<ModelEsque>> {\n- return {\n- codex: getAppModelOptions(\n- settings,\n- providers,\n- "codex",\n- selectedProvider === "codex" ? selectedModel : undefined,\n- ),\n- claudeAgent: getAppModelOptions(\n- settings,\n- providers,\n- "claudeAgent",\n- selectedProvider === "claudeAgent" ? selectedModel : undefined,\n- ),\n- cursor: getAppModelOptions(\n- settings,\n- providers,\n- "cursor",\n- selectedProvider === "cursor" ? selectedModel : undefined,\n- ),\n- opencode: getAppModelOptions(\n- settings,\n- providers,\n- "opencode",\n- selectedProvider === "opencode" ? selectedModel : undefined,\n- ),\n- };\n+ selectedModel: string | null | undefined,\n+): string | null {\n+ const entry = deriveProviderInstanceEntries(providers).find(\n+ (candidate) => candidate.instanceId === instanceId,\n+ );\n+ if (!entry) return null;\n+ const options = getAppModelOptionsForInstance(settings, entry);\n+ return (\n+ resolveSelectableModel(entry.driverKind, selectedModel, options) ??\n+ options[0]?.slug ??\n+ entry.models[0]?.slug ??\n+ null\n+ );\n+}\n+\n+/**\n+ * Instance-keyed model options map. Each configured instance gets its own\n+ * option list so the model picker can show the same driver\'s built-in and\n+ * custom instances side by side without collapsing them.\n+ */\n+export function getCustomModelOptionsByInstance(\n+ settings: UnifiedSettings,\n+ providers: ReadonlyArray<ServerProvider>,\n+ _selectedInstanceId?: ProviderInstanceId | null,\n+ _selectedModel?: string | null,\n+): ReadonlyMap<ProviderInstanceId, ReadonlyArray<ModelEsque>> {\n+ const out = new Map<ProviderInstanceId, ReadonlyArray<ModelEsque>>();\n+ for (const entry of deriveProviderInstanceEntries(providers)) {\n+ out.set(entry.instanceId, getAppModelOptionsForInstance(settings, entry));\n+ }\n+ return out;\n }\n \n export function resolveAppModelSelectionState(\n@@ -167,22 +274,52 @@ export function resolveAppModelSelectionState(\n providers: ReadonlyArray<ServerProvider>,\n ): ModelSelection {\n const selection = settings.textGenerationModelSelection ?? {\n- provider: "codex" as const,\n- model: DEFAULT_GIT_TEXT_GENERATION_MODEL_BY_PROVIDER.codex,\n+ instanceId: DEFAULT_TEXT_GENERATION_INSTANCE_ID,\n+ model: DEFAULT_GIT_TEXT_GENERATION_MODEL,\n };\n- const provider = resolveSelectableProvider(providers, selection.provider);\n+ const entries = deriveProviderInstanceEntries(providers);\n+ const selectedEntry = entries.find(\n+ (entry) => entry.instanceId === selection.instanceId && entry.enabled && entry.isAvailable,\n+ );\n+ const entry =\n+ selectedEntry ?? entries.find((candidate) => candidate.enabled && candidate.isAvailable);\n+ if (entry) {\n+ // When the instance changed due to fallback (e.g. selected instance was disabled),\n+ // don\'t carry over the old instance\'s model — use the fallback instance\'s default.\n+ const selectedModel = selectedEntry ? selection.model : null;\n+ const model =\n+ resolveAppModelSelectionForInstance(entry.instanceId, settings, providers, selectedModel) ??\n+ entry.models[0]?.slug ??\n+ DEFAULT_GIT_TEXT_GENERATION_MODEL_BY_PROVIDER[entry.driverKind];\n+ if (!model) {\n+ return createModelSelection(entry.instanceId, "", []);\n+ }\n+ const provider = entry.driverKind;\n+ const { modelOptionsForDispatch } = getComposerProviderState({\n+ provider,\n+ model,\n+ models: entry.models,\n+ prompt: "",\n+ modelOptions: selectedEntry ? selection.options : undefined,\n+ });\n+\n+ return createModelSelection(entry.instanceId, model, modelOptionsForDispatch);\n+ }\n+\n+ const provider = resolveSelectableProvider(providers, null);\n+ const keptSelectedProvider = false;\n \n // When the provider changed due to fallback (e.g. selected provider was disabled),\n // don\'t carry over the old provider\'s model — use the fallback provider\'s default.\n- const selectedModel = provider === selection.provider ? selection.model : null;\n+ const selectedModel = keptSelectedProvider ? selection.model : null;\n const model = resolveAppModelSelection(provider, settings, providers, selectedModel);\n const { modelOptionsForDispatch } = getComposerProviderState({\n provider,\n model,\n models: getProviderModels(providers, provider),\n prompt: "",\n- modelOptions: provider === selection.provider ? selection.options : undefined,\n+ modelOptions: keptSelectedProvider ? selection.options : undefined,\n });\n \n- return createModelSelection(provider, model, modelOptionsForDispatch);\n+ return createModelSelection(defaultInstanceIdForDriver(provider), model, modelOptionsForDispatch);\n }\ndiff --git a/apps/web/src/orchestrationEventEffects.test.ts b/apps/web/src/orchestrationEventEffects.test.ts\nindex d35dc9e260..a20e64e253 100644\n--- a/apps/web/src/orchestrationEventEffects.test.ts\n+++ b/apps/web/src/orchestrationEventEffects.test.ts\n@@ -3,6 +3,7 @@ import {\n EventId,\n MessageId,\n ProjectId,\n+ ProviderInstanceId,\n ThreadId,\n TurnId,\n type OrchestrationEvent,\n@@ -49,7 +50,7 @@ describe("deriveOrchestrationBatchEffects", () => {\n threadId: createdThreadId,\n projectId: ProjectId.make("project-1"),\n title: "Created thread",\n- modelSelection: { provider: "codex", model: "gpt-5-codex" },\n+ modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5-codex" },\n runtimeMode: "full-access",\n interactionMode: "default",\n branch: null,\n@@ -86,7 +87,7 @@ describe("deriveOrchestrationBatchEffects", () => {\n threadId,\n projectId: ProjectId.make("project-1"),\n title: "Recreated thread",\n- modelSelection: { provider: "codex", model: "gpt-5-codex" },\n+ modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5-codex" },\n runtimeMode: "full-access",\n interactionMode: "default",\n branch: null,\ndiff --git a/apps/web/src/providerInstances.test.ts b/apps/web/src/providerInstances.test.ts\nnew file mode 100644\nindex 0000000000..7104f365eb\n--- /dev/null\n+++ b/apps/web/src/providerInstances.test.ts\n@@ -0,0 +1,132 @@\n+import { ProviderDriverKind, ProviderInstanceId, type ServerProvider } from "@t3tools/contracts";\n+import { describe, expect, it } from "vitest";\n+import {\n+ deriveProviderInstanceEntries,\n+ resolveSelectableProviderInstance,\n+ resolveProviderDriverKindForInstanceSelection,\n+} from "./providerInstances";\n+\n+function provider(input: {\n+ provider: ProviderDriverKind;\n+ instanceId: string;\n+ enabled?: boolean;\n+ availability?: ServerProvider["availability"];\n+ displayName?: string;\n+}): ServerProvider {\n+ return {\n+ instanceId: ProviderInstanceId.make(input.instanceId),\n+ driver: input.provider,\n+ ...(input.displayName ? { displayName: input.displayName } : {}),\n+ enabled: input.enabled ?? true,\n+ installed: true,\n+ version: null,\n+ status: "ready",\n+ ...(input.availability ? { availability: input.availability } : {}),\n+ auth: { status: "authenticated" },\n+ checkedAt: "2026-01-01T00:00:00.000Z",\n+ models: [],\n+ slashCommands: [],\n+ skills: [],\n+ };\n+}\n+\n+describe("deriveProviderInstanceEntries", () => {\n+ it("uses explicit instance id and driver kind from the snapshot", () => {\n+ const snapshot = provider({\n+ provider: ProviderDriverKind.make("codex"),\n+ instanceId: "codex_personal",\n+ });\n+ const [entry] = deriveProviderInstanceEntries([snapshot]);\n+\n+ expect(entry?.instanceId).toBe("codex_personal");\n+ expect(entry?.driverKind).toBe("codex");\n+ expect(entry?.isDefault).toBe(false);\n+ });\n+});\n+\n+describe("resolveSelectableProviderInstance", () => {\n+ it("returns the requested instance when it is enabled and available", () => {\n+ const requested = ProviderInstanceId.make("claude_work");\n+ const providers = [\n+ provider({ provider: ProviderDriverKind.make("codex"), instanceId: "codex" }),\n+ provider({ provider: ProviderDriverKind.make("claudeAgent"), instanceId: requested }),\n+ ];\n+\n+ expect(resolveSelectableProviderInstance(providers, requested)).toBe(requested);\n+ });\n+\n+ it("falls back to the first enabled and available instance", () => {\n+ const disabled = ProviderInstanceId.make("codex");\n+ const fallback = ProviderInstanceId.make("claudeAgent");\n+ const providers = [\n+ provider({\n+ provider: ProviderDriverKind.make("codex"),\n+ instanceId: disabled,\n+ enabled: false,\n+ }),\n+ provider({ provider: ProviderDriverKind.make("claudeAgent"), instanceId: fallback }),\n+ ];\n+\n+ expect(resolveSelectableProviderInstance(providers, disabled)).toBe(fallback);\n+ });\n+\n+ it("does not return disabled, unavailable, or unknown instances when none are sendable", () => {\n+ const disabled = ProviderInstanceId.make("codex");\n+ const unavailable = ProviderInstanceId.make("claudeAgent");\n+ const unknown = ProviderInstanceId.make("removed_instance");\n+ const providers = [\n+ provider({\n+ provider: ProviderDriverKind.make("codex"),\n+ instanceId: disabled,\n+ enabled: false,\n+ }),\n+ provider({\n+ provider: ProviderDriverKind.make("claudeAgent"),\n+ instanceId: unavailable,\n+ availability: "unavailable",\n+ }),\n+ ];\n+\n+ expect(resolveSelectableProviderInstance(providers, disabled)).toBeUndefined();\n+ expect(resolveSelectableProviderInstance(providers, unavailable)).toBeUndefined();\n+ expect(resolveSelectableProviderInstance(providers, unknown)).toBeUndefined();\n+ });\n+});\n+\n+describe("resolveProviderDriverKindForInstanceSelection", () => {\n+ it("maps custom provider instance ids back to their driver kind", () => {\n+ const providers = [\n+ provider({ provider: ProviderDriverKind.make("codex"), instanceId: "codex" }),\n+ provider({\n+ provider: ProviderDriverKind.make("claudeAgent"),\n+ instanceId: "claude_openrouter",\n+ displayName: "Claude OpenRouter",\n+ }),\n+ ];\n+ const entries = deriveProviderInstanceEntries(providers);\n+\n+ expect(\n+ resolveProviderDriverKindForInstanceSelection(\n+ entries,\n+ providers,\n+ ProviderInstanceId.make("claude_openrouter"),\n+ ),\n+ ).toBe("claudeAgent");\n+ });\n+\n+ it("does not guess a provider kind when the instance selection is unknown", () => {\n+ const providers = [\n+ provider({ provider: ProviderDriverKind.make("codex"), instanceId: "codex", enabled: false }),\n+ provider({ provider: ProviderDriverKind.make("claudeAgent"), instanceId: "claudeAgent" }),\n+ ];\n+ const entries = deriveProviderInstanceEntries(providers);\n+\n+ expect(\n+ resolveProviderDriverKindForInstanceSelection(\n+ entries,\n+ providers,\n+ ProviderInstanceId.make("removed_instance"),\n+ ),\n+ ).toBeUndefined();\n+ });\n+});\ndiff --git a/apps/web/src/providerInstances.ts b/apps/web/src/providerInstances.ts\nnew file mode 100644\nindex 0000000000..6ff0bd1ab9\n--- /dev/null\n+++ b/apps/web/src/providerInstances.ts\n@@ -0,0 +1,248 @@\n+/**\n+ * Instance-aware view over the wire `ServerProvider[]`.\n+ *\n+ * The wire carries one `ServerProvider` per *configured instance* — the\n+ * default built-in codex instance, a user-authored `codex_personal`, an\n+ * unavailable shadow for a fork driver, etc. Legacy UI code collapsed these\n+ * into a single bucket per built-in driver via `.find((p) => p.driver === kind)`,\n+ * which silently dropped every custom instance after the first. This module\n+ * replaces that pattern with `ProviderInstanceEntry[]`, keyed on\n+ * `ProviderInstanceId`, so the model picker, settings list, and composer\n+ * can treat built-in and custom instances uniformly.\n+ *\n+ * @module providerInstances\n+ */\n+import {\n+ defaultInstanceIdForDriver,\n+ PROVIDER_DISPLAY_NAMES,\n+ type ProviderDriverKind,\n+ type ProviderInstanceId,\n+ type ServerProvider,\n+ type ServerProviderModel,\n+ type ServerProviderState,\n+} from "@t3tools/contracts";\n+\n+import { formatProviderDriverKindLabel } from "./providerModels";\n+\n+/**\n+ * UI-facing projection of one configured provider instance. Carries the\n+ * snapshot verbatim for callers that need server-side fields we don\'t\n+ * hoist here, plus the precomputed `instanceId` / `driverKind` /\n+ * `displayName` used by every picker and settings view.\n+ */\n+export interface ProviderInstanceEntry {\n+ readonly instanceId: ProviderInstanceId;\n+ readonly driverKind: ProviderDriverKind;\n+ readonly displayName: string;\n+ readonly accentColor?: string | undefined;\n+ readonly continuationGroupKey?: string | undefined;\n+ readonly enabled: boolean;\n+ readonly installed: boolean;\n+ readonly status: ServerProviderState;\n+ /**\n+ * True when this entry is the default instance for its driver kind —\n+ * i.e. its instance id equals `defaultInstanceIdForDriver(driverKind)`.\n+ * The settings panel and picker sort defaults before customs.\n+ */\n+ readonly isDefault: boolean;\n+ /** True when `availability === "unavailable"` is absent or "available". */\n+ readonly isAvailable: boolean;\n+ readonly snapshot: ServerProvider;\n+ readonly models: ReadonlyArray<ServerProviderModel>;\n+}\n+\n+/**\n+ * Turn an instance id slug into a human-readable label. Splits on `_` / `-`\n+ * and camelCase boundaries and title-cases each token, so `codex_personal`\n+ * becomes "Codex Personal" and `myCustomInstance` becomes "My Custom\n+ * Instance".\n+ *\n+ * This is a fallback used only when the wire snapshot\'s `displayName`\n+ * doesn\'t disambiguate a non-default instance from the default one of the\n+ * same driver (today every built-in driver hard-codes a single presentation\n+ * label per kind, so two instances of the same kind arrive with identical\n+ * display names). When a server/driver later plumbs the user\'s configured\n+ * `ProviderInstanceConfig.displayName` through to the snapshot, that value\n+ * will take precedence over this fallback.\n+ */\n+function humanizeInstanceId(instanceId: ProviderInstanceId): string {\n+ return instanceId\n+ .replace(/[_-]+/g, " ")\n+ .replace(/([a-z])([A-Z])/g, "$1 $2")\n+ .split(" ")\n+ .filter((token) => token.length > 0)\n+ .map((token) => token.charAt(0).toUpperCase() + token.slice(1))\n+ .join(" ");\n+}\n+\n+function driverKindLabel(driverKind: ProviderDriverKind): string {\n+ return PROVIDER_DISPLAY_NAMES[driverKind] ?? formatProviderDriverKindLabel(driverKind);\n+}\n+\n+export function normalizeProviderAccentColor(value: string | undefined): string | undefined {\n+ const trimmed = value?.trim();\n+ if (!trimmed) return undefined;\n+ return /^#[0-9a-fA-F]{6}$/u.test(trimmed) ? trimmed : undefined;\n+}\n+\n+/**\n+ * Resolve an entry\'s displayName with a tiered priority:\n+ *\n+ * 1. A snapshot `displayName` that differs from the driver-kind label —\n+ * the server has explicitly named this instance, trust it.\n+ * 2. For non-default instances, a humanized `instanceId` — the server\n+ * fell back to the driver-level presentation constant (which is the\n+ * same for every instance of that kind), so we differentiate at the\n+ * UI layer by slug. This is what keeps "Codex" + "Codex Personal"\n+ * distinguishable in tooltips and list labels today.\n+ * 3. The snapshot\'s `displayName` (if any) — default instance, trust\n+ * whatever label the driver stamped.\n+ * 4. `driverKindLabel(driverKind)` — nothing else on hand, so use the\n+ * canonical brand label from contracts (falling back to a generic\n+ * title-case of the kind slug).\n+ */\n+function resolveInstanceDisplayName(\n+ snapshot: ServerProvider,\n+ instanceId: ProviderInstanceId,\n+ driverKind: ProviderDriverKind,\n+ isDefault: boolean,\n+): string {\n+ const trimmedSnapshotName = snapshot.displayName?.trim();\n+ const kindLabel = driverKindLabel(driverKind);\n+ if (trimmedSnapshotName && trimmedSnapshotName !== kindLabel) {\n+ return trimmedSnapshotName;\n+ }\n+ if (!isDefault) {\n+ const humanized = humanizeInstanceId(instanceId);\n+ if (humanized.length > 0) return humanized;\n+ }\n+ return trimmedSnapshotName || kindLabel;\n+}\n+\n+/**\n+ * Project the wire `ServerProvider[]` into instance entries, one per\n+ * configured instance. Preserves the server\'s ordering (which sources\n+ * from `deriveProviderInstanceConfigMap` — explicit `providerInstances.*`\n+ * first, synthesized defaults after) so callers that want "default first"\n+ * should sort with `sortProviderInstanceEntries` below.\n+ */\n+export function deriveProviderInstanceEntries(\n+ providers: ReadonlyArray<ServerProvider>,\n+): ReadonlyArray<ProviderInstanceEntry> {\n+ return providers.map((snapshot) => {\n+ const instanceId = snapshot.instanceId;\n+ const driverKind = snapshot.driver;\n+ const defaultId = defaultInstanceIdForDriver(driverKind);\n+ const isDefault = instanceId === defaultId;\n+ const displayName = resolveInstanceDisplayName(snapshot, instanceId, driverKind, isDefault);\n+ return {\n+ instanceId,\n+ driverKind,\n+ displayName,\n+ accentColor: normalizeProviderAccentColor(snapshot.accentColor),\n+ continuationGroupKey: snapshot.continuation?.groupKey,\n+ enabled: snapshot.enabled,\n+ installed: snapshot.installed,\n+ status: snapshot.status,\n+ isDefault,\n+ isAvailable: snapshot.availability !== "unavailable",\n+ snapshot,\n+ models: snapshot.models,\n+ } satisfies ProviderInstanceEntry;\n+ });\n+}\n+\n+/**\n+ * Sort instance entries so the default instance of each driver kind appears\n+ * before any custom instances of the same kind. Within a kind, custom\n+ * instances keep their settings-author order (which is how the server\n+ * emits them). Stable across kinds: entries retain the server\'s\n+ * cross-driver ordering.\n+ */\n+export function sortProviderInstanceEntries(\n+ entries: ReadonlyArray<ProviderInstanceEntry>,\n+): ReadonlyArray<ProviderInstanceEntry> {\n+ // Group by driver kind preserving first-appearance order, then emit\n+ // default-first within each kind. Using a Map keeps the "first-seen"\n+ // semantics for kinds whose default instance is absent (unusual but\n+ // possible during the migration).\n+ const byKind = new Map<ProviderDriverKind, ProviderInstanceEntry[]>();\n+ for (const entry of entries) {\n+ const bucket = byKind.get(entry.driverKind);\n+ if (bucket) {\n+ bucket.push(entry);\n+ } else {\n+ byKind.set(entry.driverKind, [entry]);\n+ }\n+ }\n+ const sorted: ProviderInstanceEntry[] = [];\n+ for (const bucket of byKind.values()) {\n+ const defaults = bucket.filter((entry) => entry.isDefault);\n+ const customs = bucket.filter((entry) => !entry.isDefault);\n+ sorted.push(...defaults, ...customs);\n+ }\n+ return sorted;\n+}\n+\n+/**\n+ * Look up a single instance entry by exact `instanceId`. Missing snapshots\n+ * are not inferred from driver kind in UI routing code.\n+ */\n+export function getProviderInstanceEntry(\n+ providers: ReadonlyArray<ServerProvider>,\n+ instanceId: ProviderInstanceId,\n+): ProviderInstanceEntry | undefined {\n+ return deriveProviderInstanceEntries(providers).find((entry) => entry.instanceId === instanceId);\n+}\n+\n+/**\n+ * Model list for a specific instance. Returns `[]` when the instance isn\'t\n+ * present so callers don\'t have to thread optionality through render code.\n+ */\n+export function getProviderInstanceModels(\n+ providers: ReadonlyArray<ServerProvider>,\n+ instanceId: ProviderInstanceId,\n+): ReadonlyArray<ServerProviderModel> {\n+ return getProviderInstanceEntry(providers, instanceId)?.models ?? [];\n+}\n+\n+/**\n+ * Resolve the routing key for a selection that may reference an instance\n+ * id that no longer exists (e.g. a persisted thread selection after the\n+ * user deleted the custom instance). Returns the first enabled instance\n+ * as a fallback so downstream code can still send a turn.\n+ */\n+export function resolveSelectableProviderInstance(\n+ providers: ReadonlyArray<ServerProvider>,\n+ instanceId: ProviderInstanceId | undefined,\n+): ProviderInstanceId | undefined {\n+ if (instanceId === undefined) {\n+ return deriveProviderInstanceEntries(providers).find(\n+ (entry) => entry.enabled && entry.isAvailable,\n+ )?.instanceId;\n+ }\n+ const entries = deriveProviderInstanceEntries(providers);\n+ const requested = entries.find((entry) => entry.instanceId === instanceId);\n+ if (requested && requested.enabled && requested.isAvailable) {\n+ return instanceId;\n+ }\n+ return entries.find((entry) => entry.enabled && entry.isAvailable)?.instanceId;\n+}\n+\n+/**\n+ * Resolve an open model-selection routing key back to a driver kind.\n+ * Custom instance ids such as `claude_openrouter` are not themselves\n+ * driver-kind slugs, but the composer still needs the owning driver kind\n+ * for capabilities, options, icons, and turn dispatch metadata.\n+ */\n+export function resolveProviderDriverKindForInstanceSelection(\n+ entries: ReadonlyArray<ProviderInstanceEntry>,\n+ providers: ReadonlyArray<ServerProvider>,\n+ selection: ProviderInstanceId | ProviderDriverKind | null | undefined,\n+): ProviderDriverKind | undefined {\n+ const matchedEntry = entries.find((entry) => entry.instanceId === selection);\n+ if (matchedEntry) {\n+ return matchedEntry.driverKind;\n+ }\n+ return undefined;\n+}\ndiff --git a/apps/web/src/providerModels.ts b/apps/web/src/providerModels.ts\nindex 229d61ca56..aa9afcf31e 100644\n--- a/apps/web/src/providerModels.ts\n+++ b/apps/web/src/providerModels.ts\n@@ -1,7 +1,10 @@\n import {\n+ DEFAULT_MODEL,\n DEFAULT_MODEL_BY_PROVIDER,\n+ defaultInstanceIdForDriver,\n+ ProviderDriverKind,\n type ModelCapabilities,\n- type ProviderKind,\n+ type ProviderInstanceId,\n type ServerProvider,\n type ServerProviderModel,\n } from "@t3tools/contracts";\n@@ -10,8 +13,9 @@ import { createModelCapabilities, normalizeModelSlug } from "@t3tools/shared/mod\n const EMPTY_CAPABILITIES: ModelCapabilities = createModelCapabilities({\n optionDescriptors: [],\n });\n+const DEFAULT_DRIVER_KIND = ProviderDriverKind.make("codex");\n \n-export function formatProviderKindLabel(provider: ProviderKind): string {\n+export function formatProviderDriverKindLabel(provider: ProviderDriverKind): string {\n return provider\n .replace(/([a-z])([A-Z])/g, "$1 $2")\n .replace(/[_-]+/g, " ")\n@@ -21,36 +25,37 @@ export function formatProviderKindLabel(provider: ProviderKind): string {\n \n export function getProviderModels(\n providers: ReadonlyArray<ServerProvider>,\n- provider: ProviderKind,\n+ provider: ProviderDriverKind,\n ): ReadonlyArray<ServerProviderModel> {\n- return providers.find((candidate) => candidate.provider === provider)?.models ?? [];\n+ return getProviderSnapshot(providers, provider)?.models ?? [];\n }\n \n export function getProviderSnapshot(\n providers: ReadonlyArray<ServerProvider>,\n- provider: ProviderKind,\n+ provider: ProviderDriverKind,\n ): ServerProvider | undefined {\n- return providers.find((candidate) => candidate.provider === provider);\n+ const defaultInstanceId = defaultInstanceIdForDriver(provider);\n+ return providers.find((candidate) => candidate.instanceId === defaultInstanceId);\n }\n \n export function getProviderDisplayName(\n providers: ReadonlyArray<ServerProvider>,\n- provider: ProviderKind,\n+ provider: ProviderDriverKind,\n ): string {\n const snapshot = getProviderSnapshot(providers, provider);\n- return snapshot?.displayName?.trim() || formatProviderKindLabel(provider);\n+ return snapshot?.displayName?.trim() || formatProviderDriverKindLabel(provider);\n }\n \n export function getProviderInteractionModeToggle(\n providers: ReadonlyArray<ServerProvider>,\n- provider: ProviderKind,\n+ provider: ProviderDriverKind,\n ): boolean {\n return getProviderSnapshot(providers, provider)?.showInteractionModeToggle ?? true;\n }\n \n export function isProviderEnabled(\n providers: ReadonlyArray<ServerProvider>,\n- provider: ProviderKind,\n+ provider: ProviderDriverKind,\n ): boolean {\n if (providers.length === 0) {\n return true;\n@@ -58,21 +63,24 @@ export function isProviderEnabled(\n return getProviderSnapshot(providers, provider)?.enabled ?? false;\n }\n \n+// Resolve an instance selection to the correlated live driver. If the\n+// instance is absent, fall back to a live enabled provider instead of\n+// inferring a driver from the missing instance id.\n export function resolveSelectableProvider(\n providers: ReadonlyArray<ServerProvider>,\n- provider: ProviderKind | null | undefined,\n-): ProviderKind {\n- const requested = provider ?? "codex";\n- if (isProviderEnabled(providers, requested)) {\n- return requested;\n+ provider: ProviderDriverKind | ProviderInstanceId | null | undefined,\n+): ProviderDriverKind {\n+ const requestedEntry = providers.find((candidate) => candidate.instanceId === provider);\n+ if (requestedEntry?.enabled) {\n+ return requestedEntry.driver;\n }\n- return providers.find((candidate) => candidate.enabled)?.provider ?? requested;\n+ return providers.find((candidate) => candidate.enabled)?.driver ?? DEFAULT_DRIVER_KIND;\n }\n \n export function getProviderModelCapabilities(\n models: ReadonlyArray<ServerProviderModel>,\n model: string | null | undefined,\n- provider: ProviderKind,\n+ provider: ProviderDriverKind,\n ): ModelCapabilities {\n const slug = normalizeModelSlug(model, provider);\n return models.find((candidate) => candidate.slug === slug)?.capabilities ?? EMPTY_CAPABILITIES;\n@@ -80,12 +88,13 @@ export function getProviderModelCapabilities(\n \n export function getDefaultServerModel(\n providers: ReadonlyArray<ServerProvider>,\n- provider: ProviderKind,\n+ provider: ProviderDriverKind,\n ): string {\n const models = getProviderModels(providers, provider);\n return (\n models.find((model) => !model.isCustom)?.slug ??\n models[0]?.slug ??\n- DEFAULT_MODEL_BY_PROVIDER[provider]\n+ DEFAULT_MODEL_BY_PROVIDER[provider] ??\n+ DEFAULT_MODEL\n );\n }\ndiff --git a/apps/web/src/rpc/serverState.test.ts b/apps/web/src/rpc/serverState.test.ts\nindex a587fcd9f1..04c9c9e8f1 100644\n--- a/apps/web/src/rpc/serverState.test.ts\n+++ b/apps/web/src/rpc/serverState.test.ts\n@@ -1,6 +1,8 @@\n import {\n DEFAULT_SERVER_SETTINGS,\n EnvironmentId,\n+ ProviderDriverKind,\n+ ProviderInstanceId,\n ProjectId,\n ThreadId,\n type ServerConfig,\n@@ -40,7 +42,8 @@ const configListeners = new Set<(event: ServerConfigStreamEvent) => void>();\n \n const defaultProviders: ReadonlyArray<ServerProvider> = [\n {\n- provider: "codex",\n+ instanceId: ProviderInstanceId.make("codex"),\n+ driver: ProviderDriverKind.make("codex"),\n enabled: true,\n installed: true,\n version: "0.116.0",\ndiff --git a/apps/web/src/rpc/wsRpcClient.ts b/apps/web/src/rpc/wsRpcClient.ts\nindex b67be32dc7..f1183c1e9c 100644\n--- a/apps/web/src/rpc/wsRpcClient.ts\n+++ b/apps/web/src/rpc/wsRpcClient.ts\n@@ -102,7 +102,13 @@ export interface WsRpcClient {\n };\n readonly server: {\n readonly getConfig: RpcUnaryNoArgMethod<typeof WS_METHODS.serverGetConfig>;\n- readonly refreshProviders: RpcUnaryNoArgMethod<typeof WS_METHODS.serverRefreshProviders>;\n+ /**\n+ * Refresh provider snapshots. Pass `{ instanceId }` to refresh a single\n+ * configured instance; pass no argument (or `{}`) to refresh all.\n+ */\n+ readonly refreshProviders: (\n+ input?: RpcInput<typeof WS_METHODS.serverRefreshProviders>,\n+ ) => ReturnType<RpcUnaryMethod<typeof WS_METHODS.serverRefreshProviders>>;\n readonly upsertKeybinding: RpcUnaryMethod<typeof WS_METHODS.serverUpsertKeybinding>;\n readonly getSettings: RpcUnaryNoArgMethod<typeof WS_METHODS.serverGetSettings>;\n readonly updateSettings: (\n@@ -206,8 +212,8 @@ export function createWsRpcClient(transport: WsTransport): WsRpcClient {\n },\n server: {\n getConfig: () => transport.request((client) => client[WS_METHODS.serverGetConfig]({})),\n- refreshProviders: () =>\n- transport.request((client) => client[WS_METHODS.serverRefreshProviders]({})),\n+ refreshProviders: (input) =>\n+ transport.request((client) => client[WS_METHODS.serverRefreshProviders](input ?? {})),\n upsertKeybinding: (input) =>\n transport.request((client) => client[WS_METHODS.serverUpsertKeybinding](input)),\n getSettings: () => transport.request((client) => client[WS_METHODS.serverGetSettings]({})),\ndiff --git a/apps/web/src/session-logic.ts b/apps/web/src/session-logic.ts\nindex fc009f9393..a7767672fa 100644\n--- a/apps/web/src/session-logic.ts\n+++ b/apps/web/src/session-logic.ts\n@@ -6,7 +6,7 @@ import {\n type OrchestrationLatestTurn,\n type OrchestrationThreadActivity,\n type OrchestrationProposedPlanId,\n- type ProviderKind,\n+ ProviderDriverKind,\n type ToolLifecycleItemType,\n type UserInputQuestion,\n type ThreadId,\n@@ -22,7 +22,7 @@ import type {\n TurnDiffSummary,\n } from "./types";\n \n-export type ProviderPickerKind = ProviderKind;\n+export type ProviderPickerKind = ProviderDriverKind;\n \n export const PROVIDER_OPTIONS: Array<{\n value: ProviderPickerKind;\n@@ -31,10 +31,20 @@ export const PROVIDER_OPTIONS: Array<{\n /** Shown on the model picker sidebar when relevant */\n pickerSidebarBadge?: "new" | "soon";\n }> = [\n- { value: "codex", label: "Codex", available: true },\n- { value: "claudeAgent", label: "Claude", available: true },\n- { value: "opencode", label: "OpenCode", available: true, pickerSidebarBadge: "new" },\n- { value: "cursor", label: "Cursor", available: true, pickerSidebarBadge: "new" },\n+ { value: ProviderDriverKind.make("codex"), label: "Codex", available: true },\n+ { value: ProviderDriverKind.make("claudeAgent"), label: "Claude", available: true },\n+ {\n+ value: ProviderDriverKind.make("opencode"),\n+ label: "OpenCode",\n+ available: true,\n+ pickerSidebarBadge: "new",\n+ },\n+ {\n+ value: ProviderDriverKind.make("cursor"),\n+ label: "Cursor",\n+ available: true,\n+ pickerSidebarBadge: "new",\n+ },\n ];\n \n export interface WorkLogEntry {\ndiff --git a/apps/web/src/store.test.ts b/apps/web/src/store.test.ts\nindex 9bb01ba0be..99ddf4ca09 100644\n--- a/apps/web/src/store.test.ts\n+++ b/apps/web/src/store.test.ts\n@@ -1,11 +1,12 @@\n import { scopeThreadRef } from "@t3tools/client-runtime";\n import {\n CheckpointRef,\n- DEFAULT_MODEL_BY_PROVIDER,\n+ DEFAULT_MODEL,\n EnvironmentId,\n EventId,\n MessageId,\n ProjectId,\n+ ProviderInstanceId,\n ThreadId,\n TurnId,\n type OrchestrationEvent,\n@@ -65,7 +66,7 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {\n projectId: ProjectId.make("project-1"),\n title: "Thread",\n modelSelection: {\n- provider: "codex",\n+ instanceId: ProviderInstanceId.make("codex"),\n model: "gpt-5-codex",\n },\n runtimeMode: DEFAULT_RUNTIME_MODE,\n@@ -93,7 +94,7 @@ function makeState(thread: Thread): AppState {\n name: "Project",\n cwd: "/tmp/project",\n defaultModelSelection: {\n- provider: "codex" as const,\n+ instanceId: ProviderInstanceId.make("codex"),\n model: "gpt-5-codex",\n },\n createdAt: "2026-02-13T00:00:00.000Z",\n@@ -463,8 +464,8 @@ describe("incremental orchestration updates", () => {\n name: "Project",\n cwd: "/tmp/project",\n defaultModelSelection: {\n- provider: "codex",\n- model: DEFAULT_MODEL_BY_PROVIDER.codex,\n+ instanceId: ProviderInstanceId.make("codex"),\n+ model: DEFAULT_MODEL,\n },\n createdAt: "2026-02-27T00:00:00.000Z",\n updatedAt: "2026-02-27T00:00:00.000Z",\n@@ -480,8 +481,8 @@ describe("incremental orchestration updates", () => {\n title: "Project Recreated",\n workspaceRoot: "/tmp/project",\n defaultModelSelection: {\n- provider: "codex",\n- model: DEFAULT_MODEL_BY_PROVIDER.codex,\n+ instanceId: ProviderInstanceId.make("codex"),\n+ model: DEFAULT_MODEL,\n },\n scripts: [],\n createdAt: "2026-02-27T00:00:01.000Z",\n@@ -518,8 +519,8 @@ describe("incremental orchestration updates", () => {\n name: "Project 1",\n cwd: "/tmp/project-1",\n defaultModelSelection: {\n- provider: "codex",\n- model: DEFAULT_MODEL_BY_PROVIDER.codex,\n+ instanceId: ProviderInstanceId.make("codex"),\n+ model: DEFAULT_MODEL,\n },\n createdAt: "2026-02-27T00:00:00.000Z",\n updatedAt: "2026-02-27T00:00:00.000Z",\n@@ -531,8 +532,8 @@ describe("incremental orchestration updates", () => {\n name: "Project 2",\n cwd: "/tmp/project-2",\n defaultModelSelection: {\n- provider: "codex",\n- model: DEFAULT_MODEL_BY_PROVIDER.codex,\n+ instanceId: ProviderInstanceId.make("codex"),\n+ model: DEFAULT_MODEL,\n },\n createdAt: "2026-02-27T00:00:00.000Z",\n updatedAt: "2026-02-27T00:00:00.000Z",\n@@ -548,8 +549,8 @@ describe("incremental orchestration updates", () => {\n projectId: recreatedProjectId,\n title: "Recovered thread",\n modelSelection: {\n- provider: "codex",\n- model: DEFAULT_MODEL_BY_PROVIDER.codex,\n+ instanceId: ProviderInstanceId.make("codex"),\n+ model: DEFAULT_MODEL,\n },\n runtimeMode: DEFAULT_RUNTIME_MODE,\n interactionMode: DEFAULT_INTERACTION_MODE,\ndiff --git a/apps/web/src/store.ts b/apps/web/src/store.ts\nindex 3b1976bf9a..e3012a8c8b 100644\n--- a/apps/web/src/store.ts\n+++ b/apps/web/src/store.ts\n@@ -18,7 +18,7 @@ import type {\n ScopedProjectRef,\n ScopedThreadRef,\n } from "@t3tools/contracts";\n-import { ProviderKind } from "@t3tools/contracts";\n+import { isProviderDriverKind, ProviderDriverKind } from "@t3tools/contracts";\n import type { ThreadId, TurnId } from "@t3tools/contracts";\n import { Schema } from "effect";\n import { resolveModelSlugForProvider } from "@t3tools/shared/model";\n@@ -129,12 +129,16 @@ function arraysEqual<T>(left: readonly T[], right: readonly T[]): boolean {\n return left.length === right.length && left.every((value, index) => value === right[index]);\n }\n \n-function normalizeModelSelection<T extends { provider: ProviderKind; model: string }>(\n- selection: T,\n-): T {\n+// Accepts the open `instanceId` string carried on `ModelSelection`; malformed\n+// values pass through unchanged, while valid slugs use any registered alias\n+// table for model normalization.\n+function normalizeModelSelection<T extends { instanceId: string; model: string }>(selection: T): T {\n+ if (!isProviderDriverKind(selection.instanceId)) {\n+ return selection;\n+ }\n return {\n ...selection,\n- model: resolveModelSlugForProvider(selection.provider, selection.model),\n+ model: resolveModelSlugForProvider(selection.instanceId, selection.model),\n };\n }\n \n@@ -145,6 +149,7 @@ function mapProjectScripts(scripts: ReadonlyArray<Project["scripts"][number]>):\n function mapSession(session: OrchestrationSession): ThreadSession {\n return {\n provider: toLegacyProvider(session.providerName),\n+ providerInstanceId: session.providerInstanceId ?? undefined,\n status: toLegacySessionStatus(session.status),\n orchestrationStatus: session.status,\n activeTurnId: session.activeTurnId ?? undefined,\n@@ -1000,11 +1005,11 @@ function toLegacySessionStatus(\n }\n }\n \n-function toLegacyProvider(providerName: string | null): ProviderKind {\n- if (Schema.is(ProviderKind)(providerName)) {\n+function toLegacyProvider(providerName: string | null): ProviderDriverKind {\n+ if (Schema.is(ProviderDriverKind)(providerName)) {\n return providerName;\n }\n- return "codex";\n+ return ProviderDriverKind.make("codex");\n }\n \n function attachmentPreviewRoutePath(attachmentId: string): string {\ndiff --git a/apps/web/src/types.ts b/apps/web/src/types.ts\nindex a544975731..7c9fd41bba 100644\n--- a/apps/web/src/types.ts\n+++ b/apps/web/src/types.ts\n@@ -11,7 +11,8 @@ import type {\n ProjectId,\n TurnId,\n MessageId,\n- ProviderKind,\n+ ProviderDriverKind,\n+ ProviderInstanceId,\n CheckpointRef,\n ProviderInteractionMode,\n RuntimeMode,\n@@ -158,7 +159,8 @@ export interface SidebarThreadSummary {\n }\n \n export interface ThreadSession {\n- provider: ProviderKind;\n+ provider: ProviderDriverKind;\n+ providerInstanceId?: ProviderInstanceId | undefined;\n status: SessionPhase | "error" | "closed";\n activeTurnId?: TurnId | undefined;\n createdAt: string;\ndiff --git a/apps/web/src/worktreeCleanup.test.ts b/apps/web/src/worktreeCleanup.test.ts\nindex bdd5bb12a0..9c833c03c7 100644\n--- a/apps/web/src/worktreeCleanup.test.ts\n+++ b/apps/web/src/worktreeCleanup.test.ts\n@@ -1,4 +1,4 @@\n-import { EnvironmentId, ProjectId, ThreadId } from "@t3tools/contracts";\n+import { EnvironmentId, ProjectId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";\n import { describe, expect, it } from "vitest";\n \n import { DEFAULT_INTERACTION_MODE, DEFAULT_RUNTIME_MODE, type Thread } from "./types";\n@@ -14,7 +14,7 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {\n projectId: ProjectId.make("project-1"),\n title: "Thread",\n modelSelection: {\n- provider: "codex",\n+ instanceId: ProviderInstanceId.make("codex"),\n model: "gpt-5.3-codex",\n },\n runtimeMode: DEFAULT_RUNTIME_MODE,\ndiff --git a/apps/web/vite.config.ts b/apps/web/vite.config.ts\nindex 01b5076695..d4042c2e88 100644\n--- a/apps/web/vite.config.ts\n+++ b/apps/web/vite.config.ts\n@@ -56,7 +56,13 @@ export default defineConfig({\n tailwindcss(),\n ],\n optimizeDeps: {\n- include: ["@pierre/diffs", "@pierre/diffs/react", "@pierre/diffs/worker/worker.js"],\n+ include: [\n+ "@pierre/diffs",\n+ "@pierre/diffs/react",\n+ "@pierre/diffs/worker/worker.js",\n+ "effect/Array",\n+ "effect/Order",\n+ ],\n },\n define: {\n "import.meta.env.VITE_HTTP_URL": JSON.stringify(configuredHttpUrl ?? ""),\ndiff --git a/docs/providers/claude.md b/docs/providers/claude.md\nnew file mode 100644\nindex 0000000000..bbf72722cf\n--- /dev/null\n+++ b/docs/providers/claude.md\n@@ -0,0 +1,224 @@\n+# Claude\n+\n+This guide is for people who want to use more than one Claude setup in T3 Code.\n+\n+Common reasons:\n+\n+- use separate work and personal Claude accounts\n+- try a different Claude Code configuration without disturbing your main setup\n+- run Claude through a router such as Claude Code Router\n+- use external providers exposed through a Claude-compatible workflow\n+\n+## I Only Use One Claude Account\n+\n+Use the default provider.\n+\n+Log in with Claude Code normally:\n+\n+```bash\n+claude auth login\n+```\n+\n+In T3 Code Settings, your Claude provider can stay like this:\n+\n+```text\n+Display name: Claude\n+Binary path: claude\n+Claude HOME path: empty\n+```\n+\n+An empty `Claude HOME path` means T3 Code uses your normal home directory.\n+\n+## I Want Work And Personal Claude Accounts\n+\n+Use a different Claude home for each account.\n+\n+Example:\n+\n+```text\n+default home work account\n+~/.claude_personal_home personal account\n+```\n+\n+### Set Up The First Account\n+\n+Log in normally:\n+\n+```bash\n+claude auth login\n+```\n+\n+In T3 Code Settings:\n+\n+```text\n+Display name: Claude Work\n+Binary path: claude\n+Claude HOME path: empty\n+```\n+\n+### Set Up The Second Account\n+\n+Log in with a separate home:\n+\n+```bash\n+mkdir -p ~/.claude_personal_home\n+HOME=~/.claude_personal_home claude auth login\n+```\n+\n+Then add another Claude provider in T3 Code:\n+\n+```text\n+Display name: Claude Personal\n+Binary path: claude\n+Claude HOME path: ~/.claude_personal_home\n+```\n+\n+Use the email shown in Settings to confirm each provider is using the intended account. Emails are\n+blurred by default; click the blurred email to reveal it.\n+\n+## Can I Switch Claude Accounts In An Existing Thread?\n+\n+Usually, no.\n+\n+T3 Code only offers Claude providers that use the same Claude home for an existing thread. A\n+different Claude home is treated as a different Claude environment.\n+\n+This is different from the recommended Codex setup. Claude Code keeps account and local state across\n+multiple files under its home directory, so T3 Code keeps separate Claude homes isolated instead of\n+trying to share part of the state.\n+\n+## I Want To Use OpenRouter\n+\n+Use this when you want Claude Code to talk to OpenRouter directly, without running a local router.\n+This is the simplest external-provider setup.\n+\n+OpenRouter provides a Claude Code integration through Claude\'s Anthropic-compatible environment\n+variables.\n+\n+### Configure A Claude OpenRouter Provider\n+\n+Add or edit a Claude provider in T3 Code Settings:\n+\n+```text\n+Display name: Claude OpenRouter\n+Binary path: claude\n+Claude HOME path: ~/.claude_openrouter_home\n+```\n+\n+In that provider\'s Environment variables section, add:\n+\n+```text\n+ANTHROPIC_BASE_URL https://openrouter.ai/api\n+ANTHROPIC_AUTH_TOKEN sk-or-... Sensitive\n+ANTHROPIC_API_KEY Empty value\n+```\n+\n+Mark `ANTHROPIC_AUTH_TOKEN` as sensitive. T3 Code stores the value as a server secret and does not\n+send it back to the app after saving.\n+\n+If you want this setup isolated from your normal Claude account, create that home first:\n+\n+```bash\n+mkdir -p ~/.claude_openrouter_home\n+```\n+\n+If you previously used the same Claude home with a normal Anthropic login, run `/logout` in a Claude\n+Code session for that home before using OpenRouter. Otherwise Claude Code may keep using cached\n+Anthropic credentials instead of the OpenRouter token.\n+\n+### Pick OpenRouter Models\n+\n+OpenRouter can route Claude Code\'s default model roles to OpenRouter model IDs.\n+\n+Example:\n+\n+```text\n+ANTHROPIC_DEFAULT_OPUS_MODEL anthropic/claude-opus-4.6\n+ANTHROPIC_DEFAULT_SONNET_MODEL anthropic/claude-sonnet-4.6\n+ANTHROPIC_DEFAULT_HAIKU_MODEL anthropic/claude-haiku-4.5\n+CLAUDE_CODE_SUBAGENT_MODEL anthropic/claude-sonnet-4.6\n+```\n+\n+Add those to the same provider\'s Environment variables section if you want stable model choices.\n+\n+### Verify OpenRouter Is Being Used\n+\n+Open a Claude session and run:\n+\n+```text\n+/status\n+```\n+\n+You should see the Anthropic base URL set to:\n+\n+```text\n+https://openrouter.ai/api\n+```\n+\n+You can also check the OpenRouter activity dashboard for requests from your API key.\n+\n+### Common OpenRouter Mistakes\n+\n+- Use `https://openrouter.ai/api`, not `https://openrouter.ai/api/v1`, for Claude Code.\n+- Set `ANTHROPIC_AUTH_TOKEN` to your OpenRouter API key.\n+- Set `ANTHROPIC_API_KEY` to an empty string so Claude Code does not try to use an Anthropic login.\n+- Put these variables on the Claude provider instance, not in global shell startup files.\n+\n+OpenRouter\'s setup can change over time. Use its upstream Claude Code guide for the current details:\n+<https://openrouter.ai/docs/guides/guides/claude-code-integration>.\n+\n+## I Want To Use Claude Code Router\n+\n+Claude Code Router is useful when you want a local routing layer with more control than a direct\n+OpenRouter setup.\n+\n+T3 Code does not need a special Claude Code Router provider. Treat the router as a Claude\n+environment.\n+\n+Use this when you want Claude Code Router to decide which upstream model or provider handles Claude\n+requests.\n+\n+High-level flow:\n+\n+1. Start Claude Code Router.\n+2. Add or configure a Claude provider in T3 Code.\n+3. Put the router\'s required variables on that provider instance.\n+\n+Configure a Claude provider:\n+\n+```text\n+Display name: Claude Router\n+Binary path: claude\n+Claude HOME path: ~/.claude_router_home\n+```\n+\n+Then copy the variables that `ccr activate` would export into the provider\'s Environment variables\n+section. Mark tokens and API keys as sensitive.\n+\n+If you want the router-backed setup to stay separate from your normal Claude account, create and log\n+in with a dedicated home first:\n+\n+```bash\n+mkdir -p ~/.claude_router_home\n+ccr start\n+ccr activate\n+HOME=~/.claude_router_home claude auth login\n+```\n+\n+Claude Code Router\'s setup can change over time. Use its upstream README for the current install and\n+configuration steps: <https://github.com/musistudio/claude-code-router>.\n+\n+## I Want Different Claude Settings, Not A Different Account\n+\n+Create another Claude provider with the same account if you want a named preset.\n+\n+Examples:\n+\n+- "Claude Default"\n+- "Claude Router"\n+- "Claude Experimental"\n+\n+If the preset needs different Claude files, give it a different `Claude HOME path`. If it needs\n+different API keys, base URLs, or router settings, use Environment variables.\n+\n+Do not put environment variable assignments in `Launch arguments`.\ndiff --git a/docs/providers/codex.md b/docs/providers/codex.md\nnew file mode 100644\nindex 0000000000..cc9e84e484\n--- /dev/null\n+++ b/docs/providers/codex.md\n@@ -0,0 +1,140 @@\n+# Codex\n+\n+This guide is for people who want to use more than one Codex account in T3 Code.\n+\n+Common reasons:\n+\n+- use a work account for work projects\n+- use a personal account for personal projects\n+- switch to another account when one account hits limits\n+- keep one shared Codex history instead of maintaining two separate Codex setups\n+\n+## I Only Use One Codex Account\n+\n+Use the default provider.\n+\n+In Settings, your Codex provider can stay like this:\n+\n+```text\n+Display name: Codex\n+CODEX_HOME path: ~/.codex\n+Shadow home path: empty\n+```\n+\n+Log in with Codex normally:\n+\n+```bash\n+codex login\n+```\n+\n+## I Want Work And Personal Codex Accounts\n+\n+Use one real Codex home and one shadow home.\n+\n+Recommended setup:\n+\n+```text\n+~/.codex shared Codex home\n+~/.codex_p second account auth\n+```\n+\n+The idea is:\n+\n+- both accounts can see the same T3/Codex sessions\n+- each account keeps its own login\n+- existing threads can continue with either account\n+\n+### Set Up The First Account\n+\n+Log in normally:\n+\n+```bash\n+codex login\n+```\n+\n+This is the account used by `~/.codex`.\n+\n+In T3 Code Settings, name it something obvious:\n+\n+```text\n+Display name: Codex Work\n+CODEX_HOME path: ~/.codex\n+Shadow home path: empty\n+```\n+\n+### Set Up The Second Account\n+\n+Log in with a separate Codex home:\n+\n+```bash\n+mkdir -p ~/.codex_p\n+CODEX_HOME=~/.codex_p codex login\n+```\n+\n+In T3 Code Settings, add another Codex provider:\n+\n+```text\n+Display name: Codex Personal\n+CODEX_HOME path: ~/.codex\n+Shadow home path: ~/.codex_p\n+```\n+\n+The important part is that both providers use the same `CODEX_HOME path`, but only the second one\n+has a `Shadow home path`.\n+\n+## Which Account Am I Using?\n+\n+Open Settings and look at the provider row.\n+\n+T3 Code shows the authenticated email for providers that report one. Emails are blurred by default;\n+click the blurred email to reveal it.\n+\n+Use display names and accent colors to make accounts easy to tell apart in the model picker.\n+\n+## I Need A Different API Key Or Endpoint\n+\n+Use the provider\'s Environment variables section in Settings.\n+\n+This is useful when a Codex-compatible setup needs account-specific variables. Add the variables to\n+the provider instance that should receive them, and mark API keys or tokens as sensitive. Sensitive\n+values are stored as server secrets and are not sent back to the app after saving.\n+\n+## Can I Switch Accounts In An Existing Thread?\n+\n+Yes, when both Codex providers share the same `CODEX_HOME path`.\n+\n+For example:\n+\n+```text\n+Codex Work CODEX_HOME path: ~/.codex\n+Codex Personal CODEX_HOME path: ~/.codex, Shadow home path: ~/.codex_p\n+```\n+\n+Those two providers are considered compatible for continuation, so the locked model picker can show\n+both.\n+\n+If you add a third Codex provider with a completely different `CODEX_HOME path`, T3 Code treats it\n+as a different workspace. It will not be offered for existing threads created under `~/.codex`.\n+\n+## If Both Accounts Look The Same\n+\n+If two Codex providers show the same account or the same unexpected model list:\n+\n+1. Check the email in Settings.\n+2. Refresh provider status.\n+3. Confirm the second provider has `Shadow home path` set.\n+4. Confirm the shadow directory has its own `auth.json`.\n+5. If you copied `~/.codex` into the shadow directory, remove everything except `auth.json`.\n+\n+Example cleanup:\n+\n+```bash\n+find ~/.codex_p -mindepth 1 ! -name auth.json -exec rm -rf {} +\n+```\n+\n+## When To Use A Separate CODEX_HOME\n+\n+Use a totally separate `CODEX_HOME path` only when you want a separate Codex workspace.\n+\n+That means separate sessions and less account switching inside old threads. Most dual-account users\n+should use the shared-home plus shadow-home setup instead.\ndiff --git a/packages/contracts/src/index.ts b/packages/contracts/src/index.ts\nindex 47081d8df1..ad90571740 100644\n--- a/packages/contracts/src/index.ts\n+++ b/packages/contracts/src/index.ts\n@@ -4,6 +4,7 @@ export * from "./environment.ts";\n export * from "./ipc.ts";\n export * from "./terminal.ts";\n export * from "./provider.ts";\n+export * from "./providerInstance.ts";\n export * from "./providerRuntime.ts";\n export * from "./model.ts";\n export * from "./keybindings.ts";\ndiff --git a/packages/contracts/src/ipc.ts b/packages/contracts/src/ipc.ts\nindex a1abc0fa4a..a63c6de962 100644\n--- a/packages/contracts/src/ipc.ts\n+++ b/packages/contracts/src/ipc.ts\n@@ -25,6 +25,7 @@ import type {\n ProjectWriteFileInput,\n ProjectWriteFileResult,\n } from "./project.ts";\n+import type { ProviderInstanceId } from "./providerInstance.ts";\n import type {\n ServerConfig,\n ServerProviderUpdatedPayload,\n@@ -215,7 +216,14 @@ export interface LocalApi {\n };\n server: {\n getConfig: () => Promise<ServerConfig>;\n- refreshProviders: () => Promise<ServerProviderUpdatedPayload>;\n+ /**\n+ * Refresh provider snapshots. When `input.instanceId` is supplied only that\n+ * configured instance is probed; otherwise every configured instance is\n+ * refreshed (legacy untargeted refresh).\n+ */\n+ refreshProviders: (input?: {\n+ readonly instanceId?: ProviderInstanceId;\n+ }) => Promise<ServerProviderUpdatedPayload>;\n upsertKeybinding: (input: ServerUpsertKeybindingInput) => Promise<ServerUpsertKeybindingResult>;\n getSettings: () => Promise<ServerSettings>;\n updateSettings: (patch: ServerSettingsPatch) => Promise<ServerSettings>;\ndiff --git a/packages/contracts/src/model.ts b/packages/contracts/src/model.ts\nindex 92de00bea3..cd8ab45a4b 100644\n--- a/packages/contracts/src/model.ts\n+++ b/packages/contracts/src/model.ts\n@@ -1,6 +1,6 @@\n import { Effect, Schema, SchemaTransformation } from "effect";\n import { TrimmedNonEmptyString } from "./baseSchemas.ts";\n-import type { ProviderKind } from "./orchestration.ts";\n+import { ProviderDriverKind } from "./providerInstance.ts";\n \n export const ProviderOptionDescriptorType = Schema.Literals(["select", "boolean"]);\n export type ProviderOptionDescriptorType = typeof ProviderOptionDescriptorType.Type;\n@@ -125,25 +125,35 @@ export const ModelCapabilities = Schema.Struct({\n });\n export type ModelCapabilities = typeof ModelCapabilities.Type;\n \n-export const DEFAULT_MODEL_BY_PROVIDER: Record<ProviderKind, string> = {\n- codex: "gpt-5.4",\n- claudeAgent: "claude-sonnet-4-6",\n- cursor: "auto",\n- opencode: "openai/gpt-5",\n-};\n+const CODEX_DRIVER_KIND = ProviderDriverKind.make("codex");\n+const CLAUDE_DRIVER_KIND = ProviderDriverKind.make("claudeAgent");\n+const CURSOR_DRIVER_KIND = ProviderDriverKind.make("cursor");\n+const OPENCODE_DRIVER_KIND = ProviderDriverKind.make("opencode");\n+\n+export const DEFAULT_MODEL = "gpt-5.4";\n+export const DEFAULT_GIT_TEXT_GENERATION_MODEL = "gpt-5.4-mini";\n \n-export const DEFAULT_MODEL = DEFAULT_MODEL_BY_PROVIDER.codex;\n+export const DEFAULT_MODEL_BY_PROVIDER: Partial<Record<ProviderDriverKind, string>> = {\n+ [CODEX_DRIVER_KIND]: DEFAULT_MODEL,\n+ [CLAUDE_DRIVER_KIND]: "claude-sonnet-4-6",\n+ [CURSOR_DRIVER_KIND]: "auto",\n+ [OPENCODE_DRIVER_KIND]: "openai/gpt-5",\n+};\n \n /** Per-provider text generation model defaults. */\n-export const DEFAULT_GIT_TEXT_GENERATION_MODEL_BY_PROVIDER: Record<ProviderKind, string> = {\n- codex: "gpt-5.4-mini",\n- claudeAgent: "claude-haiku-4-5",\n- cursor: "composer-2",\n- opencode: "openai/gpt-5",\n+export const DEFAULT_GIT_TEXT_GENERATION_MODEL_BY_PROVIDER: Partial<\n+ Record<ProviderDriverKind, string>\n+> = {\n+ [CODEX_DRIVER_KIND]: DEFAULT_GIT_TEXT_GENERATION_MODEL,\n+ [CLAUDE_DRIVER_KIND]: "claude-haiku-4-5",\n+ [CURSOR_DRIVER_KIND]: "composer-2",\n+ [OPENCODE_DRIVER_KIND]: "openai/gpt-5",\n };\n \n-export const MODEL_SLUG_ALIASES_BY_PROVIDER: Record<ProviderKind, Record<string, string>> = {\n- codex: {\n+export const MODEL_SLUG_ALIASES_BY_PROVIDER: Partial<\n+ Record<ProviderDriverKind, Record<string, string>>\n+> = {\n+ [CODEX_DRIVER_KIND]: {\n "gpt-5-codex": "gpt-5.4",\n "5.4": "gpt-5.4",\n "5.3": "gpt-5.3-codex",\n@@ -151,7 +161,7 @@ export const MODEL_SLUG_ALIASES_BY_PROVIDER: Record<ProviderKind, Record<string,\n "5.3-spark": "gpt-5.3-codex-spark",\n "gpt-5.3-spark": "gpt-5.3-codex-spark",\n },\n- claudeAgent: {\n+ [CLAUDE_DRIVER_KIND]: {\n opus: "claude-opus-4-7",\n "opus-4.7": "claude-opus-4-7",\n "claude-opus-4.7": "claude-opus-4-7",\n@@ -167,7 +177,7 @@ export const MODEL_SLUG_ALIASES_BY_PROVIDER: Record<ProviderKind, Record<string,\n "claude-haiku-4.5": "claude-haiku-4-5",\n "claude-haiku-4-5-20251001": "claude-haiku-4-5",\n },\n- cursor: {\n+ [CURSOR_DRIVER_KIND]: {\n composer: "composer-2",\n "composer-1.5": "composer-1.5",\n "composer-1": "composer-1.5",\n@@ -178,14 +188,14 @@ export const MODEL_SLUG_ALIASES_BY_PROVIDER: Record<ProviderKind, Record<string,\n "opus-4.5-thinking": "claude-opus-4-5",\n "opus-4.5": "claude-opus-4-5",\n },\n- opencode: {},\n+ [OPENCODE_DRIVER_KIND]: {},\n };\n \n // ── Provider display names ────────────────────────────────────────────\n \n-export const PROVIDER_DISPLAY_NAMES: Record<ProviderKind, string> = {\n- codex: "Codex",\n- claudeAgent: "Claude",\n- cursor: "Cursor",\n- opencode: "OpenCode",\n+export const PROVIDER_DISPLAY_NAMES: Partial<Record<ProviderDriverKind, string>> = {\n+ [CODEX_DRIVER_KIND]: "Codex",\n+ [CLAUDE_DRIVER_KIND]: "Claude",\n+ [CURSOR_DRIVER_KIND]: "Cursor",\n+ [OPENCODE_DRIVER_KIND]: "OpenCode",\n };\ndiff --git a/packages/contracts/src/orchestration.test.ts b/packages/contracts/src/orchestration.test.ts\nindex 190e09aa63..559f3016e0 100644\n--- a/packages/contracts/src/orchestration.test.ts\n+++ b/packages/contracts/src/orchestration.test.ts\n@@ -5,6 +5,7 @@ import { Effect, Schema } from "effect";\n import {\n DEFAULT_PROVIDER_INTERACTION_MODE,\n DEFAULT_RUNTIME_MODE,\n+ ModelSelection,\n OrchestrationCommand,\n OrchestrationEvent,\n OrchestrationGetTurnDiffInput,\n@@ -20,6 +21,7 @@ import {\n ThreadTurnDiff,\n ThreadTurnStartRequestedPayload,\n } from "./orchestration.ts";\n+import { ProviderInstanceId } from "./providerInstance.ts";\n \n const decodeTurnDiffInput = Schema.decodeUnknownEffect(OrchestrationGetTurnDiffInput);\n const decodeThreadTurnDiff = Schema.decodeUnknownEffect(ThreadTurnDiff);\n@@ -104,7 +106,7 @@ it.effect("trims branded ids and command string fields at decode boundaries", ()\n assert.strictEqual(parsed.workspaceRoot, "/tmp/workspace");\n assert.strictEqual(parsed.createWorkspaceRootIfMissing, undefined);\n assert.deepStrictEqual(parsed.defaultModelSelection, {\n- provider: "codex",\n+ instanceId: ProviderInstanceId.make("codex"),\n model: "gpt-5.2",\n });\n }),\n@@ -140,7 +142,7 @@ it.effect("decodes historical project.created payloads with a default provider",\n createdAt: "2026-01-01T00:00:00.000Z",\n updatedAt: "2026-01-01T00:00:00.000Z",\n });\n- assert.strictEqual(parsed.defaultModelSelection?.provider, "codex");\n+ assert.strictEqual(parsed.defaultModelSelection?.instanceId, "codex");\n }),\n );\n \n@@ -154,7 +156,7 @@ it.effect("decodes project.meta-updated payloads with explicit default provider"\n },\n updatedAt: "2026-01-01T00:00:00.000Z",\n });\n- assert.strictEqual(parsed.defaultModelSelection?.provider, "claudeAgent");\n+ assert.strictEqual(parsed.defaultModelSelection?.instanceId, "claudeAgent");\n }),\n );\n \n@@ -213,7 +215,7 @@ it.effect("preserves explicit provider and runtime mode in thread.turn.start", (\n runtimeMode: "full-access",\n createdAt: "2026-01-01T00:00:00.000Z",\n });\n- assert.strictEqual(parsed.modelSelection?.provider, "codex");\n+ assert.strictEqual(parsed.modelSelection?.instanceId, "codex");\n assert.strictEqual(parsed.runtimeMode, "full-access");\n assert.strictEqual(parsed.interactionMode, DEFAULT_PROVIDER_INTERACTION_MODE);\n }),\n@@ -278,7 +280,7 @@ it.effect("decodes thread.created runtime mode for historical events", () =>\n });\n \n assert.strictEqual(parsed.runtimeMode, DEFAULT_RUNTIME_MODE);\n- assert.strictEqual(parsed.modelSelection.provider, "codex");\n+ assert.strictEqual(parsed.modelSelection.instanceId, "codex");\n }),\n );\n \n@@ -292,7 +294,7 @@ it.effect("decodes thread.meta-updated payloads with explicit provider", () =>\n },\n updatedAt: "2026-01-01T00:00:00.000Z",\n });\n- assert.strictEqual(parsed.modelSelection?.provider, "claudeAgent");\n+ assert.strictEqual(parsed.modelSelection?.instanceId, "claudeAgent");\n }),\n );\n \n@@ -378,7 +380,7 @@ it.effect("accepts provider-scoped model options in thread.turn.start", () =>\n },\n createdAt: "2026-01-01T00:00:00.000Z",\n });\n- assert.strictEqual(parsed.modelSelection?.provider, "codex");\n+ assert.strictEqual(parsed.modelSelection?.instanceId, "codex");\n assert.strictEqual(getOptionValue(parsed.modelSelection?.options, "reasoningEffort"), "high");\n assert.strictEqual(getOptionValue(parsed.modelSelection?.options, "fastMode"), true);\n }),\n@@ -408,7 +410,7 @@ it.effect("normalizes legacy object-shaped modelSelection.options on decode", ()\n updatedAt: "2026-01-01T00:00:00.000Z",\n });\n \n- assert.strictEqual(parsed.modelSelection.provider, "claudeAgent");\n+ assert.strictEqual(parsed.modelSelection.instanceId, ProviderInstanceId.make("claudeAgent"));\n assert.deepStrictEqual(parsed.modelSelection.options, [\n { id: "effort", value: "max" },\n { id: "fastMode", value: true },\n@@ -618,3 +620,96 @@ it.effect("preserves proposed plan implementation metadata when present", () =>\n assert.strictEqual(parsed.implementationThreadId, "thread-2");\n }),\n );\n+\n+// ── ModelSelection: instance-keyed wire shape + legacy decoder ────────\n+//\n+// `ModelSelection` is routing-keyed on `instanceId` — never a driver kind.\n+// Persisted and in-flight payloads from pre-instance builds carry a\n+// `provider` field whose value was a driver kind; those payloads are migrated\n+// at the wire boundary by\n+// promoting `provider` to the default instance id for that driver\n+// (built-in drivers use the driver kind slug as their default instance id, so\n+// the migration is a 1:1 rename).\n+//\n+// These tests pin the rollback/fork tolerance invariant: legacy payloads\n+// decode cleanly for fork-provided drivers, and the decoded form uses\n+// `instanceId` uniformly regardless of origin.\n+\n+const decodeModelSelection = Schema.decodeUnknownEffect(ModelSelection);\n+const encodeModelSelection = Schema.encodeUnknownEffect(ModelSelection);\n+\n+it.effect("ModelSelection migrates legacy `provider` field to `instanceId`", () =>\n+ Effect.gen(function* () {\n+ const parsed = yield* decodeModelSelection({\n+ provider: "codex",\n+ model: "gpt-5-codex",\n+ options: [{ id: "reasoningEffort", value: "high" }],\n+ });\n+ assert.strictEqual(parsed.instanceId, ProviderInstanceId.make("codex"));\n+ assert.strictEqual(parsed.model, "gpt-5-codex");\n+ assert.deepStrictEqual(parsed.options, [{ id: "reasoningEffort", value: "high" }]);\n+ }),\n+);\n+\n+it.effect("ModelSelection accepts an explicit instanceId routing key", () =>\n+ Effect.gen(function* () {\n+ const parsed = yield* decodeModelSelection({\n+ instanceId: "codex_personal",\n+ model: "gpt-5-codex",\n+ });\n+ assert.strictEqual(parsed.instanceId, ProviderInstanceId.make("codex_personal"));\n+ }),\n+);\n+\n+it.effect("ModelSelection prefers explicit instanceId over legacy provider", () =>\n+ Effect.gen(function* () {\n+ const parsed = yield* decodeModelSelection({\n+ provider: "codex",\n+ instanceId: "codex_personal",\n+ model: "gpt-5-codex",\n+ });\n+ assert.strictEqual(parsed.instanceId, ProviderInstanceId.make("codex_personal"));\n+ }),\n+);\n+\n+it.effect(\n+ "ModelSelection decodes unknown driver kinds via legacy provider (rollback / fork invariant)",\n+ () =>\n+ Effect.gen(function* () {\n+ const parsed = yield* decodeModelSelection({\n+ provider: "ollama",\n+ model: "llama3:70b",\n+ options: [{ id: "temperature", value: "0.4" }],\n+ });\n+ assert.strictEqual(parsed.instanceId, ProviderInstanceId.make("ollama"));\n+ assert.strictEqual(parsed.model, "llama3:70b");\n+ }),\n+);\n+\n+it.effect("ModelSelection encodes to the canonical instanceId wire form", () =>\n+ Effect.gen(function* () {\n+ const decoded = yield* decodeModelSelection({\n+ provider: "ollama",\n+ model: "llama3:70b",\n+ options: [{ id: "temperature", value: "0.4" }],\n+ });\n+ const encoded = yield* encodeModelSelection(decoded);\n+ assert.deepStrictEqual(encoded, {\n+ instanceId: "ollama",\n+ model: "llama3:70b",\n+ options: [{ id: "temperature", value: "0.4" }],\n+ });\n+ }),\n+);\n+\n+it.effect("ModelSelection rejects malformed instance ids", () =>\n+ Effect.gen(function* () {\n+ const result = yield* Effect.exit(\n+ decodeModelSelection({\n+ instanceId: "1invalid", // must start with a letter\n+ model: "x",\n+ }),\n+ );\n+ assert.strictEqual(result._tag, "Failure");\n+ }),\n+);\ndiff --git a/packages/contracts/src/orchestration.ts b/packages/contracts/src/orchestration.ts\nindex c201d6c82a..19160c0b60 100644\n--- a/packages/contracts/src/orchestration.ts\n+++ b/packages/contracts/src/orchestration.ts\n@@ -1,4 +1,4 @@\n-import { Effect, Option, Schema, SchemaIssue, Struct } from "effect";\n+import { Effect, Option, Schema, SchemaIssue, SchemaTransformation, Struct } from "effect";\n import { ProviderOptionSelections } from "./model.ts";\n import { RepositoryIdentity } from "./environment.ts";\n import {\n@@ -15,6 +15,7 @@ import {\n TrimmedNonEmptyString,\n TurnId,\n } from "./baseSchemas.ts";\n+import { ProviderInstanceId } from "./providerInstance.ts";\n \n export const ORCHESTRATION_WS_METHODS = {\n dispatchCommand: "orchestration.dispatchCommand",\n@@ -25,8 +26,6 @@ export const ORCHESTRATION_WS_METHODS = {\n subscribeThread: "orchestration.subscribeThread",\n } as const;\n \n-export const ProviderKind = Schema.Literals(["codex", "claudeAgent", "cursor", "opencode"]);\n-export type ProviderKind = typeof ProviderKind.Type;\n export const ProviderApprovalPolicy = Schema.Literals([\n "untrusted",\n "on-failure",\n@@ -41,41 +40,72 @@ export const ProviderSandboxMode = Schema.Literals([\n ]);\n export type ProviderSandboxMode = typeof ProviderSandboxMode.Type;\n \n-export const DEFAULT_PROVIDER_KIND: ProviderKind = "codex";\n-\n-export const CodexModelSelection = Schema.Struct({\n- provider: Schema.Literal("codex"),\n- model: TrimmedNonEmptyString,\n- options: Schema.optionalKey(ProviderOptionSelections),\n-});\n-export type CodexModelSelection = typeof CodexModelSelection.Type;\n-\n-export const ClaudeModelSelection = Schema.Struct({\n- provider: Schema.Literal("claudeAgent"),\n+/**\n+ * `ModelSelection` — selection of a model on a configured provider instance.\n+ *\n+ * The routing key is `instanceId` (a user-defined slug identifying one\n+ * configured provider instance). Drivers, credentials, working-directory\n+ * bindings, and any other per-instance state are recovered from the\n+ * runtime registry via the instance id.\n+ *\n+ * Wire legacy: persisted selections produced before the driver/instance\n+ * split carried a `provider: <driver-id>` field instead. The schema absorbs\n+ * that shape via a pre-decoding transform — `{provider, model}` is promoted\n+ * to `{instanceId: defaultInstanceIdForDriver(provider), model}`. No\n+ * post-decode compatibility code lives in the runtime; the transform is the\n+ * only compat surface.\n+ */\n+const ModelSelectionWire = Schema.Struct({\n+ instanceId: ProviderInstanceId,\n model: TrimmedNonEmptyString,\n options: Schema.optionalKey(ProviderOptionSelections),\n });\n-export type ClaudeModelSelection = typeof ClaudeModelSelection.Type;\n \n-export const CursorModelSelection = Schema.Struct({\n- provider: Schema.Literal("cursor"),\n- model: TrimmedNonEmptyString,\n- options: Schema.optionalKey(ProviderOptionSelections),\n-});\n-export type CursorModelSelection = typeof CursorModelSelection.Type;\n-export const OpenCodeModelSelection = Schema.Struct({\n- provider: Schema.Literal("opencode"),\n- model: TrimmedNonEmptyString,\n- options: Schema.optionalKey(ProviderOptionSelections),\n-});\n-export type OpenCodeModelSelection = typeof OpenCodeModelSelection.Type;\n-\n-export const ModelSelection = Schema.Union([\n- CodexModelSelection,\n- ClaudeModelSelection,\n- CursorModelSelection,\n- OpenCodeModelSelection,\n-]);\n+// Source shape for persisted legacy payloads. Fields are typed as\n+// `Schema.Unknown` so malformed drafts still make it into the transform and\n+// fail validation through the target schema (with proper error messages)\n+// rather than at the source-struct layer where the error is less actionable.\n+const ModelSelectionSource = Schema.Struct({\n+ provider: Schema.optional(Schema.Unknown),\n+ instanceId: Schema.optional(Schema.Unknown),\n+ model: Schema.Unknown,\n+ options: Schema.optional(Schema.Unknown),\n+});\n+\n+export const ModelSelection = ModelSelectionSource.pipe(\n+ Schema.decodeTo(\n+ ModelSelectionWire,\n+ SchemaTransformation.transformOrFail({\n+ decode: (raw) => {\n+ // Resolve the routing key: prefer an explicit `instanceId`; fall\n+ // back to promoting the legacy `provider` slug (the canonical\n+ // `defaultInstanceIdForDriver` mapping) so persisted rollout-era\n+ // payloads decode without data loss. The target schema brands the\n+ // string as `ProviderInstanceId`.\n+ const instanceIdSource =\n+ raw.instanceId !== undefined\n+ ? raw.instanceId\n+ : typeof raw.provider === "string"\n+ ? raw.provider\n+ : undefined;\n+ const base: Record<string, unknown> = {\n+ instanceId: instanceIdSource,\n+ model: raw.model,\n+ };\n+ if (raw.options !== undefined) base.options = raw.options;\n+ return Effect.succeed(base as typeof ModelSelectionWire.Encoded);\n+ },\n+ encode: (value) => {\n+ const base: Record<string, unknown> = {\n+ model: value.model,\n+ instanceId: value.instanceId,\n+ };\n+ if (value.options !== undefined) base.options = value.options;\n+ return Effect.succeed(base as typeof ModelSelectionSource.Encoded);\n+ },\n+ }),\n+ ),\n+);\n export type ModelSelection = typeof ModelSelection.Type;\n \n export const RuntimeMode = Schema.Literals([\n@@ -225,6 +255,7 @@ export const OrchestrationSession = Schema.Struct({\n threadId: ThreadId,\n status: OrchestrationSessionStatus,\n providerName: Schema.NullOr(TrimmedNonEmptyString),\n+ providerInstanceId: Schema.optional(ProviderInstanceId),\n runtimeMode: RuntimeMode.pipe(Schema.withDecodingDefault(Effect.succeed(DEFAULT_RUNTIME_MODE))),\n activeTurnId: Schema.NullOr(TurnId),\n lastError: Schema.NullOr(TrimmedNonEmptyString),\ndiff --git a/packages/contracts/src/provider.test.ts b/packages/contracts/src/provider.test.ts\nindex 9bbc3ff10b..67318d0e33 100644\n--- a/packages/contracts/src/provider.test.ts\n+++ b/packages/contracts/src/provider.test.ts\n@@ -1,10 +1,17 @@\n import { describe, expect, it } from "vitest";\n import { Schema } from "effect";\n \n-import { ProviderSendTurnInput, ProviderSessionStartInput } from "./provider.ts";\n+import {\n+ ProviderEvent,\n+ ProviderSendTurnInput,\n+ ProviderSession,\n+ ProviderSessionStartInput,\n+} from "./provider.ts";\n \n const decodeProviderSessionStartInput = Schema.decodeUnknownSync(ProviderSessionStartInput);\n const decodeProviderSendTurnInput = Schema.decodeUnknownSync(ProviderSendTurnInput);\n+const decodeProviderSession = Schema.decodeUnknownSync(ProviderSession);\n+const decodeProviderEvent = Schema.decodeUnknownSync(ProviderEvent);\n \n function getOptionValue(\n options: ReadonlyArray<{ id: string; value: unknown }> | undefined,\n@@ -30,13 +37,10 @@ describe("ProviderSessionStartInput", () => {\n runtimeMode: "full-access",\n });\n expect(parsed.runtimeMode).toBe("full-access");\n- expect(parsed.modelSelection?.provider).toBe("codex");\n+ expect(parsed.modelSelection?.instanceId).toBe("codex");\n expect(parsed.modelSelection?.model).toBe("gpt-5.3-codex");\n- if (parsed.modelSelection?.provider !== "codex") {\n- throw new Error("Expected codex modelSelection");\n- }\n- expect(getOptionValue(parsed.modelSelection.options, "reasoningEffort")).toBe("high");\n- expect(getOptionValue(parsed.modelSelection.options, "fastMode")).toBe(true);\n+ expect(getOptionValue(parsed.modelSelection?.options, "reasoningEffort")).toBe("high");\n+ expect(getOptionValue(parsed.modelSelection?.options, "fastMode")).toBe(true);\n });\n \n it("rejects payloads without runtime mode", () => {\n@@ -65,14 +69,11 @@ describe("ProviderSessionStartInput", () => {\n runtimeMode: "full-access",\n });\n expect(parsed.provider).toBe("claudeAgent");\n- expect(parsed.modelSelection?.provider).toBe("claudeAgent");\n+ expect(parsed.modelSelection?.instanceId).toBe("claudeAgent");\n expect(parsed.modelSelection?.model).toBe("claude-sonnet-4-6");\n- if (parsed.modelSelection?.provider !== "claudeAgent") {\n- throw new Error("Expected claude modelSelection");\n- }\n- expect(getOptionValue(parsed.modelSelection.options, "thinking")).toBe(true);\n- expect(getOptionValue(parsed.modelSelection.options, "effort")).toBe("max");\n- expect(getOptionValue(parsed.modelSelection.options, "fastMode")).toBe(true);\n+ expect(getOptionValue(parsed.modelSelection?.options, "thinking")).toBe(true);\n+ expect(getOptionValue(parsed.modelSelection?.options, "effort")).toBe("max");\n+ expect(getOptionValue(parsed.modelSelection?.options, "fastMode")).toBe(true);\n expect(parsed.runtimeMode).toBe("full-access");\n });\n \n@@ -89,11 +90,27 @@ describe("ProviderSessionStartInput", () => {\n },\n });\n expect(parsed.provider).toBe("cursor");\n- expect(parsed.modelSelection?.provider).toBe("cursor");\n+ expect(parsed.modelSelection?.instanceId).toBe("cursor");\n expect(parsed.modelSelection?.model).toBe("composer-2");\n- if (parsed.modelSelection?.provider === "cursor") {\n- expect(getOptionValue(parsed.modelSelection.options, "fastMode")).toBe(true);\n- }\n+ expect(getOptionValue(parsed.modelSelection?.options, "fastMode")).toBe(true);\n+ });\n+\n+ it("accepts fork-provided driver kinds as branded slugs", () => {\n+ const parsed = decodeProviderSessionStartInput({\n+ threadId: "thread-1",\n+ provider: "ollama",\n+ providerInstanceId: "ollama_local",\n+ cwd: "/tmp/workspace",\n+ runtimeMode: "full-access",\n+ modelSelection: {\n+ instanceId: "ollama_local",\n+ model: "llama3.3",\n+ },\n+ });\n+\n+ expect(parsed.provider).toBe("ollama");\n+ expect(parsed.providerInstanceId).toBe("ollama_local");\n+ expect(parsed.modelSelection?.instanceId).toBe("ollama_local");\n });\n });\n \n@@ -111,13 +128,10 @@ describe("ProviderSendTurnInput", () => {\n },\n });\n \n- expect(parsed.modelSelection?.provider).toBe("codex");\n+ expect(parsed.modelSelection?.instanceId).toBe("codex");\n expect(parsed.modelSelection?.model).toBe("gpt-5.3-codex");\n- if (parsed.modelSelection?.provider !== "codex") {\n- throw new Error("Expected codex modelSelection");\n- }\n- expect(getOptionValue(parsed.modelSelection.options, "reasoningEffort")).toBe("xhigh");\n- expect(getOptionValue(parsed.modelSelection.options, "fastMode")).toBe(true);\n+ expect(getOptionValue(parsed.modelSelection?.options, "reasoningEffort")).toBe("xhigh");\n+ expect(getOptionValue(parsed.modelSelection?.options, "fastMode")).toBe(true);\n });\n \n it("accepts claude modelSelection including ultrathink", () => {\n@@ -133,11 +147,82 @@ describe("ProviderSendTurnInput", () => {\n },\n });\n \n- expect(parsed.modelSelection?.provider).toBe("claudeAgent");\n- if (parsed.modelSelection?.provider !== "claudeAgent") {\n- throw new Error("Expected claude modelSelection");\n- }\n- expect(getOptionValue(parsed.modelSelection.options, "effort")).toBe("ultrathink");\n- expect(getOptionValue(parsed.modelSelection.options, "fastMode")).toBe(true);\n+ expect(parsed.modelSelection?.instanceId).toBe("claudeAgent");\n+ expect(getOptionValue(parsed.modelSelection?.options, "effort")).toBe("ultrathink");\n+ expect(getOptionValue(parsed.modelSelection?.options, "fastMode")).toBe(true);\n+ });\n+});\n+\n+describe("providerInstanceId routing key (slice-2 invariant)", () => {\n+ it("decodes a ProviderSessionStartInput without providerInstanceId (legacy producer)", () => {\n+ const parsed = decodeProviderSessionStartInput({\n+ threadId: "thread-1",\n+ provider: "codex",\n+ runtimeMode: "full-access",\n+ });\n+ expect(parsed.providerInstanceId).toBeUndefined();\n+ });\n+\n+ it("decodes a ProviderSessionStartInput with providerInstanceId (post-migration producer)", () => {\n+ const parsed = decodeProviderSessionStartInput({\n+ threadId: "thread-1",\n+ provider: "codex",\n+ providerInstanceId: "codex_personal",\n+ runtimeMode: "full-access",\n+ });\n+ expect(parsed.providerInstanceId).toBe("codex_personal");\n+ });\n+\n+ it("propagates providerInstanceId through ProviderSession decode", () => {\n+ const session = decodeProviderSession({\n+ provider: "codex",\n+ providerInstanceId: "codex_work",\n+ status: "ready",\n+ runtimeMode: "full-access",\n+ threadId: "thread-1",\n+ createdAt: "2024-01-01T00:00:00Z",\n+ updatedAt: "2024-01-01T00:00:00Z",\n+ });\n+ expect(session.providerInstanceId).toBe("codex_work");\n+ });\n+\n+ it("decodes ProviderSession for fork-provided driver kinds", () => {\n+ const session = decodeProviderSession({\n+ provider: "ollama",\n+ providerInstanceId: "ollama_local",\n+ status: "ready",\n+ runtimeMode: "full-access",\n+ threadId: "thread-1",\n+ createdAt: "2024-01-01T00:00:00Z",\n+ updatedAt: "2024-01-01T00:00:00Z",\n+ });\n+\n+ expect(session.provider).toBe("ollama");\n+ expect(session.providerInstanceId).toBe("ollama_local");\n+ });\n+\n+ it("decodes a ProviderEvent carrying both legacy provider and new instance routing", () => {\n+ const event = decodeProviderEvent({\n+ id: "event-1",\n+ kind: "notification",\n+ provider: "codex",\n+ providerInstanceId: "codex_personal",\n+ threadId: "thread-1",\n+ createdAt: "2024-01-01T00:00:00Z",\n+ method: "session.created",\n+ });\n+ expect(event.provider).toBe("codex");\n+ expect(event.providerInstanceId).toBe("codex_personal");\n+ });\n+\n+ it("rejects providerInstanceId values that fail the slug pattern (defense in depth)", () => {\n+ expect(() =>\n+ decodeProviderSessionStartInput({\n+ threadId: "thread-1",\n+ provider: "codex",\n+ providerInstanceId: "1bad",\n+ runtimeMode: "full-access",\n+ }),\n+ ).toThrow();\n });\n });\ndiff --git a/packages/contracts/src/provider.ts b/packages/contracts/src/provider.ts\nindex e27e3aa7ef..e8ad017d7b 100644\n--- a/packages/contracts/src/provider.ts\n+++ b/packages/contracts/src/provider.ts\n@@ -16,12 +16,12 @@ import {\n ProviderApprovalDecision,\n ProviderApprovalPolicy,\n ProviderInteractionMode,\n- ProviderKind,\n ProviderRequestKind,\n ProviderSandboxMode,\n ProviderUserInputAnswers,\n RuntimeMode,\n } from "./orchestration.ts";\n+import { ProviderInstanceId, ProviderDriverKind } from "./providerInstance.ts";\n \n const ProviderSessionStatus = Schema.Literals([\n "connecting",\n@@ -32,7 +32,11 @@ const ProviderSessionStatus = Schema.Literals([\n ]);\n \n export const ProviderSession = Schema.Struct({\n- provider: ProviderKind,\n+ provider: ProviderDriverKind,\n+ // Optional during the driver/instance migration. Once every producer\n+ // populates it (post-slice-4), routing flips to instance-id-only and the\n+ // legacy `provider` field is removed.\n+ providerInstanceId: Schema.optional(ProviderInstanceId),\n status: ProviderSessionStatus,\n runtimeMode: RuntimeMode,\n cwd: Schema.optional(TrimmedNonEmptyString),\n@@ -48,7 +52,9 @@ export type ProviderSession = typeof ProviderSession.Type;\n \n export const ProviderSessionStartInput = Schema.Struct({\n threadId: ThreadId,\n- provider: Schema.optional(ProviderKind),\n+ provider: Schema.optional(ProviderDriverKind),\n+ // See ProviderSession for the migration story.\n+ providerInstanceId: Schema.optional(ProviderInstanceId),\n cwd: Schema.optional(TrimmedNonEmptyString),\n modelSelection: Schema.optional(ModelSelection),\n resumeCursor: Schema.optional(Schema.Unknown),\n@@ -108,7 +114,9 @@ const ProviderEventKind = Schema.Literals(["session", "notification", "request",\n export const ProviderEvent = Schema.Struct({\n id: EventId,\n kind: ProviderEventKind,\n- provider: ProviderKind,\n+ provider: ProviderDriverKind,\n+ // See ProviderSession for the migration story.\n+ providerInstanceId: Schema.optional(ProviderInstanceId),\n threadId: ThreadId,\n createdAt: IsoDateTime,\n method: TrimmedNonEmptyString,\ndiff --git a/packages/contracts/src/providerInstance.test.ts b/packages/contracts/src/providerInstance.test.ts\nnew file mode 100644\nindex 0000000000..9139001cf3\n--- /dev/null\n+++ b/packages/contracts/src/providerInstance.test.ts\n@@ -0,0 +1,192 @@\n+import { describe, expect, it } from "vitest";\n+import { Schema } from "effect";\n+\n+import {\n+ ProviderDriverKind,\n+ ProviderInstanceConfig,\n+ ProviderInstanceConfigMap,\n+ ProviderInstanceId,\n+ ProviderInstanceRef,\n+} from "./providerInstance.ts";\n+\n+const decodeProviderDriverKind = Schema.decodeUnknownSync(ProviderDriverKind);\n+const decodeProviderInstanceId = Schema.decodeUnknownSync(ProviderInstanceId);\n+const decodeProviderInstanceRef = Schema.decodeUnknownSync(ProviderInstanceRef);\n+const decodeProviderInstanceConfig = Schema.decodeUnknownSync(ProviderInstanceConfig);\n+const decodeProviderInstanceConfigMap = Schema.decodeUnknownSync(ProviderInstanceConfigMap);\n+\n+describe("provider slug validation (shared by driver + instance ids)", () => {\n+ const cases = [\n+ { schemaName: "ProviderInstanceId", decode: decodeProviderInstanceId },\n+ { schemaName: "ProviderDriverKind", decode: decodeProviderDriverKind },\n+ ] as const;\n+\n+ for (const { schemaName, decode } of cases) {\n+ describe(schemaName, () => {\n+ it.each(["codex", "codex_personal", "codex-work", "claudeAgent", "x", "abc123", "ollama"])(\n+ "accepts %s",\n+ (id) => {\n+ expect(decode(id)).toBe(id);\n+ },\n+ );\n+\n+ it.each([\n+ ["empty string", ""],\n+ ["leading digit", "1codex"],\n+ ["leading dash", "-codex"],\n+ ["leading underscore", "_codex"],\n+ ["whitespace inside", "codex personal"],\n+ ["dot inside", "codex.personal"],\n+ ["slash inside", "codex/personal"],\n+ ])("rejects %s", (_label, value) => {\n+ expect(() => decode(value)).toThrow();\n+ });\n+\n+ it("trims surrounding whitespace before validating", () => {\n+ expect(decode(" codex_work ")).toBe("codex_work");\n+ });\n+\n+ it("rejects ids longer than 64 characters", () => {\n+ const tooLong = "a".repeat(65);\n+ expect(() => decode(tooLong)).toThrow();\n+ const justRight = "a".repeat(64);\n+ expect(decode(justRight)).toBe(justRight);\n+ });\n+ });\n+ }\n+});\n+\n+describe("ProviderInstanceRef", () => {\n+ it("decodes a driver ref", () => {\n+ const ref = decodeProviderInstanceRef({\n+ instanceId: "codex_work",\n+ driver: "codex",\n+ });\n+ expect(ref.instanceId).toBe("codex_work");\n+ expect(ref.driver).toBe("codex");\n+ });\n+\n+ it("decodes a fork-defined driver ref without complaint", () => {\n+ const ref = decodeProviderInstanceRef({\n+ instanceId: "ollama_local",\n+ driver: "ollama",\n+ });\n+ expect(ref.instanceId).toBe("ollama_local");\n+ expect(ref.driver).toBe("ollama");\n+ });\n+\n+ it("rejects refs whose driver field is not a valid slug", () => {\n+ expect(() =>\n+ decodeProviderInstanceRef({\n+ instanceId: "codex",\n+ driver: "1nope",\n+ }),\n+ ).toThrow();\n+ });\n+});\n+\n+describe("ProviderInstanceConfig", () => {\n+ it("accepts a minimal config envelope for a driver", () => {\n+ const decoded = decodeProviderInstanceConfig({ driver: "codex" });\n+ expect(decoded.driver).toBe("codex");\n+ expect(decoded.displayName).toBeUndefined();\n+ expect(decoded.enabled).toBeUndefined();\n+ expect(decoded.config).toBeUndefined();\n+ });\n+\n+ it("preserves driver-opaque config payloads verbatim", () => {\n+ const opaqueConfig = { homePath: "~/.codex_personal", binaryPath: "codex" };\n+ const decoded = decodeProviderInstanceConfig({\n+ driver: "codex",\n+ displayName: "Codex (personal)",\n+ accentColor: "#dc2626",\n+ enabled: true,\n+ config: opaqueConfig,\n+ });\n+ expect(decoded.displayName).toBe("Codex (personal)");\n+ expect(decoded.accentColor).toBe("#dc2626");\n+ expect(decoded.enabled).toBe(true);\n+ expect(decoded.config).toEqual(opaqueConfig);\n+ });\n+\n+ it("decodes generic environment variables on the instance envelope", () => {\n+ const decoded = decodeProviderInstanceConfig({\n+ driver: "claudeAgent",\n+ environment: [\n+ { name: "ANTHROPIC_BASE_URL", value: "https://openrouter.ai/api", sensitive: false },\n+ { name: "OPENROUTER_API_KEY", value: "sk-or-test", sensitive: true },\n+ { name: "ANTHROPIC_API_KEY", value: "", sensitive: false },\n+ ],\n+ });\n+\n+ expect(decoded.environment).toEqual([\n+ { name: "ANTHROPIC_BASE_URL", value: "https://openrouter.ai/api", sensitive: false },\n+ { name: "OPENROUTER_API_KEY", value: "sk-or-test", sensitive: true },\n+ { name: "ANTHROPIC_API_KEY", value: "", sensitive: false },\n+ ]);\n+ });\n+\n+ it("rejects invalid environment variable names", () => {\n+ expect(() =>\n+ decodeProviderInstanceConfig({\n+ driver: "codex",\n+ environment: [{ name: "HAS-DASH", value: "x", sensitive: false }],\n+ }),\n+ ).toThrow();\n+ });\n+\n+ it("decodes envelopes that name an unknown driver and preserves their config opaquely", () => {\n+ const opaqueConfig = { someUnknownKnob: 42, model: "llama3" };\n+ const decoded = decodeProviderInstanceConfig({\n+ driver: "ollama",\n+ displayName: "Ollama",\n+ enabled: true,\n+ config: opaqueConfig,\n+ });\n+ expect(decoded.driver).toBe("ollama");\n+ expect(decoded.config).toEqual(opaqueConfig);\n+ });\n+\n+ it("rejects a blank displayName (must be trimmed non-empty)", () => {\n+ expect(() => decodeProviderInstanceConfig({ driver: "codex", displayName: " " })).toThrow();\n+ });\n+\n+ it("rejects driver values that do not satisfy the slug pattern", () => {\n+ expect(() => decodeProviderInstanceConfig({ driver: "" })).toThrow();\n+ expect(() => decodeProviderInstanceConfig({ driver: "has spaces" })).toThrow();\n+ });\n+});\n+\n+describe("ProviderInstanceConfigMap", () => {\n+ it("decodes a multi-instance map mixing first-party and fork drivers", () => {\n+ const decoded = decodeProviderInstanceConfigMap({\n+ codex_personal: {\n+ driver: "codex",\n+ displayName: "Codex (personal)",\n+ config: { homePath: "~/.codex_personal" },\n+ },\n+ codex_work: {\n+ driver: "codex",\n+ config: { homePath: "~/.codex_work" },\n+ },\n+ claudeAgent: { driver: "claudeAgent" },\n+ ollama_local: { driver: "ollama", config: { endpoint: "http://localhost:11434" } },\n+ });\n+ expect(new Set(Object.keys(decoded))).toEqual(\n+ new Set(["claudeAgent", "codex_personal", "codex_work", "ollama_local"]),\n+ );\n+ expect(decoded[ProviderInstanceId.make("codex_personal")]?.driver).toBe("codex");\n+ expect(decoded[ProviderInstanceId.make("codex_work")]?.config).toEqual({\n+ homePath: "~/.codex_work",\n+ });\n+ expect(decoded[ProviderInstanceId.make("ollama_local")]?.driver).toBe("ollama");\n+ });\n+\n+ it("rejects keys that fail the instance-id pattern", () => {\n+ expect(() =>\n+ decodeProviderInstanceConfigMap({\n+ "1codex": { driver: "codex" },\n+ }),\n+ ).toThrow();\n+ });\n+});\ndiff --git a/packages/contracts/src/providerInstance.ts b/packages/contracts/src/providerInstance.ts\nnew file mode 100644\nindex 0000000000..d5bb25f772\n--- /dev/null\n+++ b/packages/contracts/src/providerInstance.ts\n@@ -0,0 +1,148 @@\n+/**\n+ * Provider-instance contracts.\n+ *\n+ * Splits the historical "provider kind" concept into two:\n+ *\n+ * - `ProviderDriverKind` is the implementation kind selector (e.g. codex,\n+ * claudeAgent, a fork\'s `ollama`, …). It picks which driver package\n+ * handles the protocol, the probe, the adapter, and text generation.\n+ *\n+ * - `ProviderInstanceId` is the routing key (a user-defined slug).\n+ * Threads, sessions, runtime events, and persisted bindings reference\n+ * instance ids — never driver kinds — so a user can configure multiple\n+ * instances of the same driver (e.g. `codex_personal` + `codex_work`),\n+ * each with independent driver-specific configuration.\n+ *\n+ * Forward/backward compatibility invariant\n+ * ----------------------------------------\n+ * `ProviderDriverKind` is intentionally an **open** branded slug, not a closed\n+ * literal union. The server hosts forks, ships in PRs that add drivers, and\n+ * users frequently roll between branches and forks. Any of those paths can\n+ * leave `ServerSettings`, persisted thread state, or session bindings\n+ * referencing a driver that the currently-running build does not know about.\n+ *\n+ * The rule: parsing any of those payloads must always succeed, and the\n+ * runtime is responsible for marking the unknown driver/instance as\n+ * "unavailable" rather than crashing. Built-in drivers shipped by the core\n+ * product happens to register in a given build is not part of the contract\n+ * layer. Driver availability is discovered through the runtime registry.\n+ *\n+ * Driver-specific configuration is similarly opaque at the contracts layer:\n+ * drivers live in (or will be extracted to) their own packages and own their\n+ * config schemas. The contracts package only knows the envelope.\n+ *\n+ * @module providerInstance\n+ */\n+import { Effect, Schema } from "effect";\n+import { TrimmedNonEmptyString } from "./baseSchemas.ts";\n+\n+const PROVIDER_SLUG_MAX_CHARS = 64;\n+/**\n+ * Slug pattern shared by driver kinds and instance ids — letters, digits,\n+ * dashes, underscores. The first character must be a letter so slugs remain\n+ * JS-identifier friendly when used as object keys, log fields, or telemetry\n+ * attributes. Mixed case is permitted so historical driver kinds (e.g.\n+ * `claudeAgent`) can be used verbatim during the migration and so external\n+ * fork authors retain reasonable freedom.\n+ */\n+const PROVIDER_SLUG_PATTERN = /^[a-zA-Z][a-zA-Z0-9_-]*$/;\n+const ENVIRONMENT_VARIABLE_NAME_MAX_CHARS = 128;\n+const ENVIRONMENT_VARIABLE_NAME_PATTERN = /^[a-zA-Z_][a-zA-Z0-9_]*$/;\n+\n+const slugSchema = TrimmedNonEmptyString.check(\n+ Schema.isMaxLength(PROVIDER_SLUG_MAX_CHARS),\n+ Schema.isPattern(PROVIDER_SLUG_PATTERN),\n+);\n+\n+/**\n+ * `ProviderDriverKind` — open branded slug naming a driver implementation.\n+ *\n+ * Constraints (validated at the schema layer):\n+ * - starts with a letter\n+ * - only letters, digits, `-`, `_` after the first char\n+ * - 1..64 characters\n+ *\n+ * Notably **not** validated: that the driver is one we know how to load.\n+ * That check belongs to the runtime registry, which downgrades unknown\n+ * drivers gracefully (see module docs).\n+ */\n+export const ProviderDriverKind = slugSchema.pipe(Schema.brand("ProviderDriverKind"));\n+export type ProviderDriverKind = typeof ProviderDriverKind.Type;\n+\n+const isProviderDriverKindValue = Schema.is(ProviderDriverKind);\n+export const isProviderDriverKind = (value: unknown): value is ProviderDriverKind =>\n+ isProviderDriverKindValue(value);\n+\n+/**\n+ * `ProviderInstanceId` — user-defined routing key for a configured provider\n+ * instance. Same slug rules as `ProviderDriverKind`; branded separately so the\n+ * type system cannot confuse the two.\n+ */\n+export const ProviderInstanceId = slugSchema.pipe(Schema.brand("ProviderInstanceId"));\n+export type ProviderInstanceId = typeof ProviderInstanceId.Type;\n+\n+/**\n+ * Lightweight reference identifying which driver implements an instance.\n+ * Carried alongside `ProviderInstanceId` on wire shapes so consumers can\n+ * branch on driver behavior (icons, capabilities, presentation) without\n+ * having to look up the instance in the registry.\n+ */\n+export const ProviderInstanceRef = Schema.Struct({\n+ instanceId: ProviderInstanceId,\n+ driver: ProviderDriverKind,\n+});\n+export type ProviderInstanceRef = typeof ProviderInstanceRef.Type;\n+\n+export const ProviderInstanceEnvironmentVariableName = TrimmedNonEmptyString.check(\n+ Schema.isMaxLength(ENVIRONMENT_VARIABLE_NAME_MAX_CHARS),\n+ Schema.isPattern(ENVIRONMENT_VARIABLE_NAME_PATTERN),\n+);\n+export type ProviderInstanceEnvironmentVariableName =\n+ typeof ProviderInstanceEnvironmentVariableName.Type;\n+\n+export const ProviderInstanceEnvironmentVariable = Schema.Struct({\n+ name: ProviderInstanceEnvironmentVariableName,\n+ value: Schema.String.pipe(Schema.withDecodingDefault(Effect.succeed(""))),\n+ sensitive: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),\n+ valueRedacted: Schema.optionalKey(Schema.Boolean),\n+});\n+export type ProviderInstanceEnvironmentVariable = typeof ProviderInstanceEnvironmentVariable.Type;\n+\n+export const ProviderInstanceEnvironment = Schema.Array(ProviderInstanceEnvironmentVariable);\n+export type ProviderInstanceEnvironment = typeof ProviderInstanceEnvironment.Type;\n+\n+/**\n+ * Envelope shape for a provider instance configuration in `ServerSettings`.\n+ *\n+ * `driver` is intentionally accepted as any well-formed slug (see module\n+ * docs). The driver-specific config payload is left as `Schema.Unknown`;\n+ * each driver registers its own decoder with the runtime registry, and\n+ * envelopes for unknown drivers are preserved verbatim so they round-trip\n+ * across version changes without data loss.\n+ */\n+export const ProviderInstanceConfig = Schema.Struct({\n+ driver: ProviderDriverKind,\n+ displayName: Schema.optional(TrimmedNonEmptyString),\n+ accentColor: Schema.optional(TrimmedNonEmptyString),\n+ environment: Schema.optionalKey(ProviderInstanceEnvironment),\n+ enabled: Schema.optionalKey(Schema.Boolean),\n+ config: Schema.optionalKey(Schema.Unknown),\n+});\n+export type ProviderInstanceConfig = typeof ProviderInstanceConfig.Type;\n+\n+/**\n+ * Map shape for `ServerSettings.providerInstances`. Keyed by\n+ * `ProviderInstanceId`, values are envelopes the registry feeds to drivers.\n+ */\n+export const ProviderInstanceConfigMap = Schema.Record(ProviderInstanceId, ProviderInstanceConfig);\n+export type ProviderInstanceConfigMap = typeof ProviderInstanceConfigMap.Type;\n+\n+/**\n+ * Construct the canonical `ProviderInstanceId` used as a back-compat default\n+ * for a built-in driver. The legacy single-instance-per-driver world used\n+ * the driver kind itself as the instance id; preserving that mapping keeps\n+ * existing persisted threads, bindings, and cache files routable across the\n+ * migration without rewriting their stored selection payloads.\n+ */\n+export const defaultInstanceIdForDriver = (driver: ProviderDriverKind): ProviderInstanceId =>\n+ ProviderInstanceId.make(driver);\ndiff --git a/packages/contracts/src/providerRuntime.test.ts b/packages/contracts/src/providerRuntime.test.ts\nindex 7b822a2860..42c0117935 100644\n--- a/packages/contracts/src/providerRuntime.test.ts\n+++ b/packages/contracts/src/providerRuntime.test.ts\n@@ -6,6 +6,23 @@ import { ProviderRuntimeEvent } from "./providerRuntime.ts";\n const decodeRuntimeEvent = Schema.decodeUnknownSync(ProviderRuntimeEvent);\n \n describe("ProviderRuntimeEvent", () => {\n+ it("accepts fork-provided driver kinds as branded slugs", () => {\n+ const parsed = decodeRuntimeEvent({\n+ type: "session.started",\n+ eventId: "event-ollama-session",\n+ provider: "ollama",\n+ providerInstanceId: "ollama_local",\n+ createdAt: "2026-02-28T00:00:00.000Z",\n+ threadId: "thread-1",\n+ payload: {\n+ message: "started",\n+ },\n+ });\n+\n+ expect(parsed.provider).toBe("ollama");\n+ expect(parsed.providerInstanceId).toBe("ollama_local");\n+ });\n+\n it("decodes turn.plan.updated for plan rendering", () => {\n const parsed = decodeRuntimeEvent({\n type: "turn.plan.updated",\ndiff --git a/packages/contracts/src/providerRuntime.ts b/packages/contracts/src/providerRuntime.ts\nindex 8387880ea3..f5e4e7452a 100644\n--- a/packages/contracts/src/providerRuntime.ts\n+++ b/packages/contracts/src/providerRuntime.ts\n@@ -12,7 +12,7 @@ import {\n TrimmedNonEmptyString,\n TurnId,\n } from "./baseSchemas.ts";\n-import { ProviderKind } from "./orchestration.ts";\n+import { ProviderInstanceId, ProviderDriverKind } from "./providerInstance.ts";\n \n const TrimmedNonEmptyStringSchema = TrimmedNonEmptyString;\n const UnknownRecordSchema = Schema.Record(Schema.String, Schema.Unknown);\n@@ -245,7 +245,11 @@ const RuntimeErrorType = Schema.Literal("runtime.error");\n \n const ProviderRuntimeEventBase = Schema.Struct({\n eventId: EventId,\n- provider: ProviderKind,\n+ provider: ProviderDriverKind,\n+ // Optional during the driver/instance migration. See providerInstance.ts\n+ // for the routing-key-vs-driver-id distinction. Once every emitter\n+ // populates it (post-slice-4), routing flips to instance-id-only.\n+ providerInstanceId: Schema.optional(ProviderInstanceId),\n threadId: ThreadId,\n createdAt: IsoDateTime,\n turnId: Schema.optional(TurnId),\ndiff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.ts\nindex 5dec716a72..ca68d5cfe4 100644\n--- a/packages/contracts/src/rpc.ts\n+++ b/packages/contracts/src/rpc.ts\n@@ -48,6 +48,7 @@ import {\n OrchestrationReplayEventsInput,\n OrchestrationRpcSchemas,\n } from "./orchestration.ts";\n+import { ProviderInstanceId } from "./providerInstance.ts";\n import {\n ProjectSearchEntriesError,\n ProjectSearchEntriesInput,\n@@ -140,7 +141,15 @@ export const WsServerGetConfigRpc = Rpc.make(WS_METHODS.serverGetConfig, {\n });\n \n export const WsServerRefreshProvidersRpc = Rpc.make(WS_METHODS.serverRefreshProviders, {\n- payload: Schema.Struct({}),\n+ payload: Schema.Struct({\n+ /**\n+ * When supplied, only refresh this specific provider instance. When\n+ * omitted, refresh all configured instances — the legacy `refresh()`\n+ * behaviour retained for transports that still dispatch untargeted\n+ * refreshes.\n+ */\n+ instanceId: Schema.optional(ProviderInstanceId),\n+ }),\n success: ServerProviderUpdatedPayload,\n });\n \ndiff --git a/packages/contracts/src/server.test.ts b/packages/contracts/src/server.test.ts\nindex 2603d51d6a..149b0db201 100644\n--- a/packages/contracts/src/server.test.ts\n+++ b/packages/contracts/src/server.test.ts\n@@ -6,9 +6,10 @@ import { ServerProvider } from "./server.ts";\n const decodeServerProvider = Schema.decodeUnknownSync(ServerProvider);\n \n describe("ServerProvider", () => {\n- it("defaults capability arrays when decoding legacy snapshots", () => {\n+ it("defaults capability arrays when decoding provider snapshots", () => {\n const parsed = decodeServerProvider({\n- provider: "codex",\n+ instanceId: "codex",\n+ driver: "codex",\n enabled: true,\n installed: true,\n version: "1.0.0",\n@@ -23,4 +24,23 @@ describe("ServerProvider", () => {\n expect(parsed.slashCommands).toEqual([]);\n expect(parsed.skills).toEqual([]);\n });\n+\n+ it("decodes continuation group metadata", () => {\n+ const parsed = decodeServerProvider({\n+ instanceId: "codex_personal",\n+ driver: "codex",\n+ continuation: { groupKey: "codex:home:/Users/julius/.codex" },\n+ enabled: true,\n+ installed: true,\n+ version: "1.0.0",\n+ status: "ready",\n+ auth: {\n+ status: "authenticated",\n+ },\n+ checkedAt: "2026-04-10T00:00:00.000Z",\n+ models: [],\n+ });\n+\n+ expect(parsed.continuation?.groupKey).toBe("codex:home:/Users/julius/.codex");\n+ });\n });\ndiff --git a/packages/contracts/src/server.ts b/packages/contracts/src/server.ts\nindex 1f048c1340..1381faf5df 100644\n--- a/packages/contracts/src/server.ts\n+++ b/packages/contracts/src/server.ts\n@@ -11,7 +11,7 @@ import {\n import { KeybindingRule, ResolvedKeybindingsConfig } from "./keybindings.ts";\n import { EditorId } from "./editor.ts";\n import { ModelCapabilities } from "./model.ts";\n-import { ProviderKind } from "./orchestration.ts";\n+import { ProviderDriverKind, ProviderInstanceId } from "./providerInstance.ts";\n import { ServerSettings } from "./settings.ts";\n \n const KeybindingsMalformedConfigIssue = Schema.Struct({\n@@ -47,6 +47,7 @@ export const ServerProviderAuth = Schema.Struct({\n status: ServerProviderAuthStatus,\n type: Schema.optional(TrimmedNonEmptyString),\n label: Schema.optional(TrimmedNonEmptyString),\n+ email: Schema.optional(TrimmedNonEmptyString),\n });\n export type ServerProviderAuth = typeof ServerProviderAuth.Type;\n \n@@ -83,10 +84,42 @@ export const ServerProviderSkill = Schema.Struct({\n });\n export type ServerProviderSkill = typeof ServerProviderSkill.Type;\n \n+/**\n+ * Availability of a configured provider instance from the runtime\'s POV.\n+ *\n+ * - `available` — the build ships this driver and an instance is wired\n+ * up. Default for legacy snapshots produced from the closed\n+ * `ServerSettings.providers` map.\n+ * - `unavailable` — the user\'s `ServerSettings.providerInstances` (or a\n+ * persisted thread / session binding) references a driver this build\n+ * doesn\'t ship. Common after rolling back from a fork or PR branch\n+ * that introduced a new driver. The snapshot is preserved so the UI\n+ * can render "missing driver" affordances and so the data round-trips\n+ * when the user moves back to the fork.\n+ *\n+ * Snapshots with `availability: "unavailable"` MUST set\n+ * `installed: false` and `enabled: false`; the runtime refuses turn\n+ * starts against them with a structured error.\n+ */\n+export const ServerProviderAvailability = Schema.Literals(["available", "unavailable"]);\n+export type ServerProviderAvailability = typeof ServerProviderAvailability.Type;\n+\n+export const ServerProviderContinuation = Schema.Struct({\n+ groupKey: TrimmedNonEmptyString,\n+});\n+export type ServerProviderContinuation = typeof ServerProviderContinuation.Type;\n+\n export const ServerProvider = Schema.Struct({\n- provider: ProviderKind,\n+ // Routing key for the configured instance this snapshot represents. This\n+ // is the only stable identity consumers may use for provider routing.\n+ instanceId: ProviderInstanceId,\n+ // Open driver kind slug that selects the implementation handling this\n+ // instance. It is metadata/capability context, not a routing key.\n+ driver: ProviderDriverKind,\n displayName: Schema.optional(TrimmedNonEmptyString),\n+ accentColor: Schema.optional(TrimmedNonEmptyString),\n badgeLabel: Schema.optional(TrimmedNonEmptyString),\n+ continuation: Schema.optional(ServerProviderContinuation),\n showInteractionModeToggle: Schema.optional(Schema.Boolean),\n enabled: Schema.Boolean,\n installed: Schema.Boolean,\n@@ -95,6 +128,15 @@ export const ServerProvider = Schema.Struct({\n auth: ServerProviderAuth,\n checkedAt: IsoDateTime,\n message: Schema.optional(TrimmedNonEmptyString),\n+ // Optional for back-compat: every legacy producer omits this field and\n+ // an absent value is interpreted as `"available"` by consumers (see\n+ // `isProviderAvailable`). New `ProviderInstanceRegistry` outputs set it\n+ // explicitly so the UI can render unavailable shadows from\n+ // `ServerSettings.providerInstances`.\n+ availability: Schema.optional(ServerProviderAvailability),\n+ // Human-readable reason populated when `availability === "unavailable"`.\n+ // Surfaces in the UI alongside the missing-driver affordance.\n+ unavailableReason: Schema.optional(TrimmedNonEmptyString),\n models: Schema.Array(ServerProviderModel),\n slashCommands: Schema.Array(ServerProviderSlashCommand).pipe(\n Schema.withDecodingDefault(Effect.succeed([])),\n@@ -106,6 +148,15 @@ export type ServerProvider = typeof ServerProvider.Type;\n export const ServerProviders = Schema.Array(ServerProvider);\n export type ServerProviders = typeof ServerProviders.Type;\n \n+/**\n+ * Treat the optional `availability` as "available" when absent. This is\n+ * the rule legacy producers (which omit the field) and new producers\n+ * (which set it explicitly) agree on so consumers never have to thread\n+ * `?? "available"` defaults through their code paths.\n+ */\n+export const isProviderAvailable = (snapshot: ServerProvider): boolean =>\n+ snapshot.availability !== "unavailable";\n+\n export const ServerObservability = Schema.Struct({\n logsDirectoryPath: TrimmedNonEmptyString,\n localTracingEnabled: Schema.Boolean,\ndiff --git a/packages/contracts/src/settings.test.ts b/packages/contracts/src/settings.test.ts\nnew file mode 100644\nindex 0000000000..d2b73f567a\n--- /dev/null\n+++ b/packages/contracts/src/settings.test.ts\n@@ -0,0 +1,94 @@\n+import { describe, expect, it } from "vitest";\n+import { Schema } from "effect";\n+\n+import { ProviderInstanceId } from "./providerInstance.ts";\n+import { DEFAULT_SERVER_SETTINGS, ServerSettings, ServerSettingsPatch } from "./settings.ts";\n+\n+const decodeServerSettings = Schema.decodeUnknownSync(ServerSettings);\n+const decodeServerSettingsPatch = Schema.decodeUnknownSync(ServerSettingsPatch);\n+\n+describe("ServerSettings.providerInstances (slice-2 invariant)", () => {\n+ it("defaults to an empty record so legacy configs without the key still decode", () => {\n+ expect(DEFAULT_SERVER_SETTINGS.providerInstances).toEqual({});\n+ });\n+\n+ it("decodes a fully empty config (legacy on-disk shape) without complaint", () => {\n+ const decoded = decodeServerSettings({});\n+ expect(decoded.providerInstances).toEqual({});\n+ // Legacy `providers` struct is still hydrated with its per-driver defaults\n+ // so existing call sites keep working through the migration.\n+ expect(decoded.providers.codex.enabled).toBe(true);\n+ });\n+\n+ it("decodes a multi-instance map mixing first-party and fork drivers", () => {\n+ const decoded = decodeServerSettings({\n+ providerInstances: {\n+ codex_personal: {\n+ driver: "codex",\n+ displayName: "Codex (personal)",\n+ config: { homePath: "~/.codex_personal" },\n+ },\n+ codex_work: {\n+ driver: "codex",\n+ config: { homePath: "~/.codex_work" },\n+ },\n+ ollama_local: {\n+ driver: "ollama",\n+ displayName: "Ollama (local)",\n+ config: { endpoint: "http://localhost:11434" },\n+ },\n+ },\n+ });\n+ const personalId = ProviderInstanceId.make("codex_personal");\n+ const workId = ProviderInstanceId.make("codex_work");\n+ const ollamaId = ProviderInstanceId.make("ollama_local");\n+\n+ expect(decoded.providerInstances[personalId]?.driver).toBe("codex");\n+ expect(decoded.providerInstances[workId]?.config).toEqual({ homePath: "~/.codex_work" });\n+ // Critical: a config naming a driver this build does not know about\n+ // (`ollama` is not in `ProviderDriverKind`) must round-trip without loss.\n+ // The runtime handles "driver not installed" — the schema must not.\n+ expect(decoded.providerInstances[ollamaId]?.driver).toBe("ollama");\n+ expect(decoded.providerInstances[ollamaId]?.config).toEqual({\n+ endpoint: "http://localhost:11434",\n+ });\n+ });\n+\n+ it("rejects instance keys that violate the slug pattern", () => {\n+ expect(() =>\n+ decodeServerSettings({\n+ providerInstances: { "1bad": { driver: "codex" } },\n+ }),\n+ ).toThrow();\n+ });\n+});\n+\n+describe("ServerSettingsPatch.providerInstances", () => {\n+ it("treats providerInstances as an optional whole-map replacement", () => {\n+ const patch = decodeServerSettingsPatch({});\n+ expect(patch.providerInstances).toBeUndefined();\n+\n+ const replacement = decodeServerSettingsPatch({\n+ providerInstances: {\n+ codex_personal: { driver: "codex", config: { homePath: "~/.codex" } },\n+ },\n+ });\n+ expect(replacement.providerInstances).toBeDefined();\n+ expect(replacement.providerInstances?.[ProviderInstanceId.make("codex_personal")]?.driver).toBe(\n+ "codex",\n+ );\n+ });\n+\n+ it("preserves a fork-defined driver entry through patch decoding", () => {\n+ const patch = decodeServerSettingsPatch({\n+ providerInstances: {\n+ ollama_local: {\n+ driver: "ollama",\n+ config: { endpoint: "http://localhost:11434" },\n+ },\n+ },\n+ });\n+ const ollamaId = ProviderInstanceId.make("ollama_local");\n+ expect(patch.providerInstances?.[ollamaId]?.driver).toBe("ollama");\n+ });\n+});\ndiff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts\nindex 2b50957a79..4a10c4cc6c 100644\n--- a/packages/contracts/src/settings.ts\n+++ b/packages/contracts/src/settings.ts\n@@ -2,11 +2,9 @@ import { Effect } from "effect";\n import * as Schema from "effect/Schema";\n import * as SchemaTransformation from "effect/SchemaTransformation";\n import { TrimmedNonEmptyString, TrimmedString } from "./baseSchemas.ts";\n-import {\n- DEFAULT_GIT_TEXT_GENERATION_MODEL_BY_PROVIDER,\n- ProviderOptionSelections,\n-} from "./model.ts";\n-import { ModelSelection, ProviderKind } from "./orchestration.ts";\n+import { DEFAULT_GIT_TEXT_GENERATION_MODEL, ProviderOptionSelections } from "./model.ts";\n+import { ModelSelection } from "./orchestration.ts";\n+import { ProviderInstanceConfig, ProviderInstanceId } from "./providerInstance.ts";\n \n // ── Client Settings (local-only) ───────────────────────────────\n \n@@ -35,12 +33,31 @@ export const ClientSettingsSchema = Schema.Struct({\n confirmThreadArchive: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),\n confirmThreadDelete: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),\n diffWordWrap: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),\n+ // Model favorites. Historically keyed by provider kind, now\n+ // widened to `ProviderInstanceId` so users can favorite a specific model\n+ // on a custom provider instance (e.g. "Codex Personal · gpt-5") without\n+ // the UI collapsing it into the same bucket as the default Codex. The\n+ // widening is backward-compatible by construction: prior provider-kind\n+ // strings satisfy the `ProviderInstanceId` slug schema, so previously\n+ // persisted favorites decode unchanged and continue to point at the\n+ // default instance for their kind (because `defaultInstanceIdForDriver(kind)`\n+ // uses the same slug). The field name is kept as `provider` for storage\n+ // stability; new call sites should treat the value as an instance id.\n favorites: Schema.Array(\n Schema.Struct({\n- provider: ProviderKind,\n+ provider: ProviderInstanceId,\n model: TrimmedNonEmptyString,\n }),\n ).pipe(Schema.withDecodingDefault(Effect.succeed([]))),\n+ providerModelPreferences: Schema.Record(\n+ ProviderInstanceId,\n+ Schema.Struct({\n+ hiddenModels: Schema.Array(Schema.String).pipe(\n+ Schema.withDecodingDefault(Effect.succeed([])),\n+ ),\n+ modelOrder: Schema.Array(Schema.String).pipe(Schema.withDecodingDefault(Effect.succeed([]))),\n+ }),\n+ ).pipe(Schema.withDecodingDefault(Effect.succeed({}))),\n sidebarProjectGroupingMode: SidebarProjectGroupingMode.pipe(\n Schema.withDecodingDefault(Effect.succeed(DEFAULT_SIDEBAR_PROJECT_GROUPING_MODE)),\n ),\n@@ -83,6 +100,7 @@ export const CodexSettings = Schema.Struct({\n enabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),\n binaryPath: makeBinaryPathSetting("codex"),\n homePath: TrimmedString.pipe(Schema.withDecodingDefault(Effect.succeed(""))),\n+ shadowHomePath: TrimmedString.pipe(Schema.withDecodingDefault(Effect.succeed(""))),\n customModels: Schema.Array(Schema.String).pipe(Schema.withDecodingDefault(Effect.succeed([]))),\n });\n export type CodexSettings = typeof CodexSettings.Type;\n@@ -90,6 +108,7 @@ export type CodexSettings = typeof CodexSettings.Type;\n export const ClaudeSettings = Schema.Struct({\n enabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),\n binaryPath: makeBinaryPathSetting("claude"),\n+ homePath: TrimmedString.pipe(Schema.withDecodingDefault(Effect.succeed(""))),\n customModels: Schema.Array(Schema.String).pipe(Schema.withDecodingDefault(Effect.succeed([]))),\n launchArgs: Schema.String.pipe(Schema.withDecodingDefault(Effect.succeed(""))),\n });\n@@ -126,19 +145,32 @@ export const ServerSettings = Schema.Struct({\n textGenerationModelSelection: ModelSelection.pipe(\n Schema.withDecodingDefault(\n Effect.succeed({\n- provider: "codex" as const,\n- model: DEFAULT_GIT_TEXT_GENERATION_MODEL_BY_PROVIDER.codex,\n+ instanceId: ProviderInstanceId.make("codex"),\n+ model: DEFAULT_GIT_TEXT_GENERATION_MODEL,\n }),\n ),\n ),\n \n- // Provider specific settings\n+ // Legacy single-instance-per-driver settings. Continues to be the source\n+ // of truth until `providerInstances` (below) lands per-driver migration\n+ // shims and the server starts hydrating instances from it. Driver-specific\n+ // schemas live here for the duration of the migration; once each driver\n+ // owns its config in its own package, this struct shrinks to nothing and\n+ // is removed entirely.\n providers: Schema.Struct({\n codex: CodexSettings.pipe(Schema.withDecodingDefault(Effect.succeed({}))),\n claudeAgent: ClaudeSettings.pipe(Schema.withDecodingDefault(Effect.succeed({}))),\n cursor: CursorSettings.pipe(Schema.withDecodingDefault(Effect.succeed({}))),\n opencode: OpenCodeSettings.pipe(Schema.withDecodingDefault(Effect.succeed({}))),\n }).pipe(Schema.withDecodingDefault(Effect.succeed({}))),\n+ // New driver-agnostic instance map. Keyed by `ProviderInstanceId`; values\n+ // are `ProviderInstanceConfig` envelopes. The driver-specific config blob\n+ // is `Schema.Unknown` at this layer so envelopes with unknown drivers\n+ // (forks, downgrades, in-flight PR branches) round-trip without loss.\n+ // See providerInstance.ts for the forward/backward compatibility invariant.\n+ providerInstances: Schema.Record(ProviderInstanceId, ProviderInstanceConfig).pipe(\n+ Schema.withDecodingDefault(Effect.succeed({})),\n+ ),\n observability: ObservabilitySettings.pipe(Schema.withDecodingDefault(Effect.succeed({}))),\n });\n export type ServerSettings = typeof ServerSettings.Type;\n@@ -168,39 +200,24 @@ export const DEFAULT_UNIFIED_SETTINGS: UnifiedSettings = {\n \n // ── Server Settings Patch (replace with a Schema.deepPartial if available) ──────────────────────────────────────────\n \n-const ModelSelectionPatch = Schema.Union([\n- Schema.Struct({\n- provider: Schema.optionalKey(Schema.Literal("codex")),\n- model: Schema.optionalKey(TrimmedNonEmptyString),\n- options: Schema.optionalKey(ProviderOptionSelections),\n- }),\n- Schema.Struct({\n- provider: Schema.optionalKey(Schema.Literal("claudeAgent")),\n- model: Schema.optionalKey(TrimmedNonEmptyString),\n- options: Schema.optionalKey(ProviderOptionSelections),\n- }),\n- Schema.Struct({\n- provider: Schema.optionalKey(Schema.Literal("cursor")),\n- model: Schema.optionalKey(TrimmedNonEmptyString),\n- options: Schema.optionalKey(ProviderOptionSelections),\n- }),\n- Schema.Struct({\n- provider: Schema.optionalKey(Schema.Literal("opencode")),\n- model: Schema.optionalKey(TrimmedNonEmptyString),\n- options: Schema.optionalKey(ProviderOptionSelections),\n- }),\n-]);\n+const ModelSelectionPatch = Schema.Struct({\n+ instanceId: Schema.optionalKey(ProviderInstanceId),\n+ model: Schema.optionalKey(TrimmedNonEmptyString),\n+ options: Schema.optionalKey(ProviderOptionSelections),\n+});\n \n const CodexSettingsPatch = Schema.Struct({\n enabled: Schema.optionalKey(Schema.Boolean),\n binaryPath: Schema.optionalKey(Schema.String),\n homePath: Schema.optionalKey(Schema.String),\n+ shadowHomePath: Schema.optionalKey(Schema.String),\n customModels: Schema.optionalKey(Schema.Array(Schema.String)),\n });\n \n const ClaudeSettingsPatch = Schema.Struct({\n enabled: Schema.optionalKey(Schema.Boolean),\n binaryPath: Schema.optionalKey(Schema.String),\n+ homePath: Schema.optionalKey(Schema.String),\n customModels: Schema.optionalKey(Schema.Array(Schema.String)),\n launchArgs: Schema.optionalKey(Schema.String),\n });\n@@ -240,6 +257,11 @@ export const ServerSettingsPatch = Schema.Struct({\n opencode: Schema.optionalKey(OpenCodeSettingsPatch),\n }),\n ),\n+ // Whole-map replacement for the new instance config. Patching individual\n+ // entries is intentionally out of scope: the map is small, and partial\n+ // patches risk leaving driver-specific config in a half-merged state.\n+ // The web UI sends a fully-formed map every time it edits this field.\n+ providerInstances: Schema.optionalKey(Schema.Record(ProviderInstanceId, ProviderInstanceConfig)),\n });\n export type ServerSettingsPatch = typeof ServerSettingsPatch.Type;\n \n@@ -251,11 +273,24 @@ export const ClientSettingsPatch = Schema.Struct({\n favorites: Schema.optionalKey(\n Schema.Array(\n Schema.Struct({\n- provider: ProviderKind,\n+ provider: ProviderInstanceId,\n model: TrimmedNonEmptyString,\n }),\n ),\n ),\n+ providerModelPreferences: Schema.optionalKey(\n+ Schema.Record(\n+ ProviderInstanceId,\n+ Schema.Struct({\n+ hiddenModels: Schema.Array(Schema.String).pipe(\n+ Schema.withDecodingDefault(Effect.succeed([])),\n+ ),\n+ modelOrder: Schema.Array(Schema.String).pipe(\n+ Schema.withDecodingDefault(Effect.succeed([])),\n+ ),\n+ }),\n+ ),\n+ ),\n sidebarProjectGroupingMode: Schema.optionalKey(SidebarProjectGroupingMode),\n sidebarProjectGroupingOverrides: Schema.optionalKey(\n Schema.Record(TrimmedNonEmptyString, SidebarProjectGroupingMode),\ndiff --git a/packages/shared/src/model.test.ts b/packages/shared/src/model.test.ts\nindex 242e798223..61cc8d181f 100644\n--- a/packages/shared/src/model.test.ts\n+++ b/packages/shared/src/model.test.ts\n@@ -1,5 +1,10 @@\n import { describe, expect, it } from "vitest";\n-import { DEFAULT_MODEL_BY_PROVIDER, type ModelCapabilities } from "@t3tools/contracts";\n+import {\n+ DEFAULT_MODEL,\n+ ProviderDriverKind,\n+ ProviderInstanceId,\n+ type ModelCapabilities,\n+} from "@t3tools/contracts";\n \n import {\n applyClaudePromptEffortPrefix,\n@@ -67,9 +72,10 @@ const claudeCaps: ModelCapabilities = createModelCapabilities({\n \n describe("normalizeModelSlug", () => {\n it("maps known aliases to canonical slugs", () => {\n+ const claude = ProviderDriverKind.make("claudeAgent");\n expect(normalizeModelSlug("gpt-5-codex")).toBe("gpt-5.4");\n expect(normalizeModelSlug("5.3")).toBe("gpt-5.3-codex");\n- expect(normalizeModelSlug("sonnet", "claudeAgent")).toBe("claude-sonnet-4-6");\n+ expect(normalizeModelSlug("sonnet", claude)).toBe("claude-sonnet-4-6");\n });\n \n it("returns null for empty or missing values", () => {\n@@ -82,16 +88,18 @@ describe("normalizeModelSlug", () => {\n \n describe("resolveModelSlugForProvider", () => {\n it("returns defaults when the model is missing", () => {\n- expect(resolveModelSlugForProvider("codex", undefined)).toBe(DEFAULT_MODEL_BY_PROVIDER.codex);\n- expect(resolveModelSlugForProvider("claudeAgent", undefined)).toBe(\n- DEFAULT_MODEL_BY_PROVIDER.claudeAgent,\n+ expect(resolveModelSlugForProvider(ProviderDriverKind.make("codex"), undefined)).toBe(\n+ DEFAULT_MODEL,\n+ );\n+ expect(resolveModelSlugForProvider(ProviderDriverKind.make("ollama"), undefined)).toBe(\n+ DEFAULT_MODEL,\n );\n });\n \n it("preserves normalized unknown models", () => {\n- expect(resolveModelSlugForProvider("codex", "custom/internal-model")).toBe(\n- "custom/internal-model",\n- );\n+ expect(\n+ resolveModelSlugForProvider(ProviderDriverKind.make("codex"), "custom/internal-model"),\n+ ).toBe("custom/internal-model");\n });\n });\n \n@@ -101,9 +109,15 @@ describe("resolveSelectableModel", () => {\n { slug: "gpt-5.3-codex", name: "GPT-5.3 Codex" },\n { slug: "claude-sonnet-4-6", name: "Claude Sonnet 4.6" },\n ];\n- expect(resolveSelectableModel("codex", "gpt-5.3-codex", options)).toBe("gpt-5.3-codex");\n- expect(resolveSelectableModel("codex", "gpt-5.3 codex", options)).toBe("gpt-5.3-codex");\n- expect(resolveSelectableModel("claudeAgent", "sonnet", options)).toBe("claude-sonnet-4-6");\n+ expect(resolveSelectableModel(ProviderDriverKind.make("codex"), "gpt-5.3-codex", options)).toBe(\n+ "gpt-5.3-codex",\n+ );\n+ expect(resolveSelectableModel(ProviderDriverKind.make("codex"), "gpt-5.3 codex", options)).toBe(\n+ "gpt-5.3-codex",\n+ );\n+ expect(resolveSelectableModel(ProviderDriverKind.make("claudeAgent"), "sonnet", options)).toBe(\n+ "claude-sonnet-4-6",\n+ );\n });\n });\n \n@@ -182,12 +196,12 @@ describe("descriptor helpers", () => {\n \n it("stores option selection arrays in model selections", () => {\n expect(\n- createModelSelection("codex", "gpt-5.4", [\n+ createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.4", [\n { id: "reasoningEffort", value: "high" },\n { id: "fastMode", value: true },\n ]),\n ).toEqual({\n- provider: "codex",\n+ instanceId: "codex",\n model: "gpt-5.4",\n options: [\n { id: "reasoningEffort", value: "high" },\n@@ -197,7 +211,7 @@ describe("descriptor helpers", () => {\n });\n \n it("reads typed option selection values", () => {\n- const selection = createModelSelection("codex", "gpt-5.4", [\n+ const selection = createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.4", [\n { id: "reasoningEffort", value: "high" },\n { id: "fastMode", value: true },\n ]);\ndiff --git a/packages/shared/src/model.ts b/packages/shared/src/model.ts\nindex 4f61fc33e8..9fdbd6c044 100644\n--- a/packages/shared/src/model.ts\n+++ b/packages/shared/src/model.ts\n@@ -1,13 +1,17 @@\n import {\n+ DEFAULT_MODEL,\n DEFAULT_MODEL_BY_PROVIDER,\n MODEL_SLUG_ALIASES_BY_PROVIDER,\n type ModelCapabilities,\n type ModelSelection,\n+ ProviderDriverKind,\n+ ProviderInstanceId,\n type ProviderOptionDescriptor,\n type ProviderOptionSelection,\n- type ProviderKind,\n } from "@t3tools/contracts";\n \n+const DEFAULT_PROVIDER_DRIVER_KIND = ProviderDriverKind.make("codex");\n+\n export interface SelectableModelOption {\n slug: string;\n name: string;\n@@ -230,7 +234,7 @@ export function isClaudeUltrathinkPrompt(text: string | null | undefined): boole\n \n export function normalizeModelSlug(\n model: string | null | undefined,\n- provider: ProviderKind = "codex",\n+ provider: ProviderDriverKind = DEFAULT_PROVIDER_DRIVER_KIND,\n ): string | null {\n if (typeof model !== "string") {\n return null;\n@@ -241,7 +245,7 @@ export function normalizeModelSlug(\n return null;\n }\n \n- const aliases = MODEL_SLUG_ALIASES_BY_PROVIDER[provider] as Record<string, string>;\n+ const aliases = MODEL_SLUG_ALIASES_BY_PROVIDER[provider] ?? {};\n const aliased = Object.prototype.hasOwnProperty.call(aliases, trimmed)\n ? aliases[trimmed]\n : undefined;\n@@ -249,7 +253,7 @@ export function normalizeModelSlug(\n }\n \n export function resolveSelectableModel(\n- provider: ProviderKind,\n+ provider: ProviderDriverKind,\n value: string | null | undefined,\n options: ReadonlyArray<SelectableModelOption>,\n ): string | null {\n@@ -281,16 +285,16 @@ export function resolveSelectableModel(\n return resolved ? resolved.slug : null;\n }\n \n-function resolveModelSlug(model: string | null | undefined, provider: ProviderKind): string {\n+function resolveModelSlug(model: string | null | undefined, provider: ProviderDriverKind): string {\n const normalized = normalizeModelSlug(model, provider);\n if (!normalized) {\n- return DEFAULT_MODEL_BY_PROVIDER[provider];\n+ return DEFAULT_MODEL_BY_PROVIDER[provider] ?? DEFAULT_MODEL;\n }\n return normalized;\n }\n \n export function resolveModelSlugForProvider(\n- provider: ProviderKind,\n+ provider: ProviderDriverKind,\n model: string | null | undefined,\n ): string {\n return resolveModelSlug(model, provider);\n@@ -310,16 +314,16 @@ function cloneSelections(\n }\n \n export function createModelSelection(\n- provider: ProviderKind,\n+ instanceId: ProviderInstanceId,\n model: string,\n options?: ReadonlyArray<ProviderOptionSelection> | null,\n ): ModelSelection {\n const selections = options ? cloneSelections(options) : [];\n- return {\n- provider,\n+ const base: ModelSelection = {\n+ instanceId,\n model,\n- ...(selections.length > 0 ? { options: selections } : {}),\n- } as ModelSelection;\n+ };\n+ return selections.length > 0 ? { ...base, options: selections } : base;\n }\n \n /**\ndiff --git a/packages/shared/src/serverSettings.test.ts b/packages/shared/src/serverSettings.test.ts\nindex ccae816cf5..3e8114f0dc 100644\n--- a/packages/shared/src/serverSettings.test.ts\n+++ b/packages/shared/src/serverSettings.test.ts\n@@ -1,4 +1,8 @@\n-import { DEFAULT_SERVER_SETTINGS } from "@t3tools/contracts";\n+import {\n+ DEFAULT_SERVER_SETTINGS,\n+ ProviderDriverKind,\n+ ProviderInstanceId,\n+} from "@t3tools/contracts";\n import { describe, expect, it } from "vitest";\n import { createModelSelection } from "./model.ts";\n import {\n@@ -57,21 +61,25 @@ describe("serverSettings helpers", () => {\n it("replaces text generation selection when provider/model are provided", () => {\n const current = {\n ...DEFAULT_SERVER_SETTINGS,\n- textGenerationModelSelection: createModelSelection("codex", "gpt-5.4-mini", [\n- { id: "reasoningEffort", value: "high" },\n- { id: "fastMode", value: true },\n- ]),\n+ textGenerationModelSelection: createModelSelection(\n+ ProviderInstanceId.make("codex"),\n+ "gpt-5.4-mini",\n+ [\n+ { id: "reasoningEffort", value: "high" },\n+ { id: "fastMode", value: true },\n+ ],\n+ ),\n };\n \n expect(\n applyServerSettingsPatch(current, {\n textGenerationModelSelection: {\n- provider: "codex",\n+ instanceId: ProviderInstanceId.make("codex"),\n model: "gpt-5.4-mini",\n },\n }).textGenerationModelSelection,\n ).toEqual({\n- provider: "codex",\n+ instanceId: "codex",\n model: "gpt-5.4-mini",\n });\n });\n@@ -79,10 +87,14 @@ describe("serverSettings helpers", () => {\n it("still deep merges text generation selection when only options are provided", () => {\n const current = {\n ...DEFAULT_SERVER_SETTINGS,\n- textGenerationModelSelection: createModelSelection("codex", "gpt-5.4-mini", [\n- { id: "reasoningEffort", value: "high" },\n- { id: "fastMode", value: true },\n- ]),\n+ textGenerationModelSelection: createModelSelection(\n+ ProviderInstanceId.make("codex"),\n+ "gpt-5.4-mini",\n+ [\n+ { id: "reasoningEffort", value: "high" },\n+ { id: "fastMode", value: true },\n+ ],\n+ ),\n };\n \n expect(\n@@ -92,7 +104,7 @@ describe("serverSettings helpers", () => {\n },\n }).textGenerationModelSelection,\n ).toEqual({\n- provider: "codex",\n+ instanceId: "codex",\n model: "gpt-5.4-mini",\n options: [\n { id: "reasoningEffort", value: "high" },\n@@ -104,21 +116,25 @@ describe("serverSettings helpers", () => {\n it("replaces text generation selection across providers without leaking stale options", () => {\n const current = {\n ...DEFAULT_SERVER_SETTINGS,\n- textGenerationModelSelection: createModelSelection("codex", "gpt-5.4-mini", [\n- { id: "reasoningEffort", value: "high" },\n- { id: "fastMode", value: true },\n- ]),\n+ textGenerationModelSelection: createModelSelection(\n+ ProviderInstanceId.make("codex"),\n+ "gpt-5.4-mini",\n+ [\n+ { id: "reasoningEffort", value: "high" },\n+ { id: "fastMode", value: true },\n+ ],\n+ ),\n };\n \n expect(\n applyServerSettingsPatch(current, {\n textGenerationModelSelection: {\n- provider: "opencode",\n+ instanceId: ProviderInstanceId.make("opencode"),\n model: "openai/gpt-5",\n },\n }).textGenerationModelSelection,\n ).toEqual({\n- provider: "opencode",\n+ instanceId: "opencode",\n model: "openai/gpt-5",\n });\n });\n@@ -127,7 +143,7 @@ describe("serverSettings helpers", () => {\n expect(\n applyServerSettingsPatch(DEFAULT_SERVER_SETTINGS, {\n textGenerationModelSelection: {\n- provider: "opencode",\n+ instanceId: ProviderInstanceId.make("opencode"),\n model: "openai/gpt-5",\n options: [\n { id: "variant", value: "prod" },\n@@ -136,7 +152,7 @@ describe("serverSettings helpers", () => {\n },\n }).textGenerationModelSelection,\n ).toEqual({\n- provider: "opencode",\n+ instanceId: "opencode",\n model: "openai/gpt-5",\n options: [\n { id: "variant", value: "prod" },\n@@ -144,4 +160,38 @@ describe("serverSettings helpers", () => {\n ],\n });\n });\n+\n+ it("replaces providerInstances maps so omitted instance fields are cleared", () => {\n+ const codexId = ProviderInstanceId.make("codex");\n+ const current = {\n+ ...DEFAULT_SERVER_SETTINGS,\n+ providerInstances: {\n+ [codexId]: {\n+ driver: ProviderDriverKind.make("codex"),\n+ displayName: "Codex Work",\n+ accentColor: "#7c3aed",\n+ enabled: true,\n+ config: { homePath: "~/.codex" },\n+ },\n+ },\n+ };\n+\n+ expect(\n+ applyServerSettingsPatch(current, {\n+ providerInstances: {\n+ [codexId]: {\n+ driver: ProviderDriverKind.make("codex"),\n+ displayName: "Codex Work",\n+ enabled: true,\n+ config: { homePath: "~/.codex" },\n+ },\n+ },\n+ }).providerInstances[codexId],\n+ ).toEqual({\n+ driver: ProviderDriverKind.make("codex"),\n+ displayName: "Codex Work",\n+ enabled: true,\n+ config: { homePath: "~/.codex" },\n+ });\n+ });\n });\ndiff --git a/packages/shared/src/serverSettings.ts b/packages/shared/src/serverSettings.ts\nindex 2488f60293..655de4d92a 100644\n--- a/packages/shared/src/serverSettings.ts\n+++ b/packages/shared/src/serverSettings.ts\n@@ -44,7 +44,7 @@ export function parsePersistedServerObservabilitySettings(\n function shouldReplaceTextGenerationModelSelection(\n patch: ServerSettingsPatch["textGenerationModelSelection"] | undefined,\n ): boolean {\n- return Boolean(patch && (patch.provider !== undefined || patch.model !== undefined));\n+ return Boolean(patch && (patch.instanceId !== undefined || patch.model !== undefined));\n }\n \n function mergeModelSelectionOptionsById(input: {\n@@ -76,11 +76,18 @@ export function applyServerSettingsPatch(\n ): ServerSettings {\n const selectionPatch = patch.textGenerationModelSelection;\n const next = deepMerge(current, patch);\n+ const nextWithReplacements =\n+ patch.providerInstances !== undefined\n+ ? {\n+ ...next,\n+ providerInstances: patch.providerInstances,\n+ }\n+ : next;\n if (!selectionPatch) {\n- return next;\n+ return nextWithReplacements;\n }\n \n- const provider = selectionPatch.provider ?? current.textGenerationModelSelection.provider;\n+ const instanceId = selectionPatch.instanceId ?? current.textGenerationModelSelection.instanceId;\n const model = selectionPatch.model ?? current.textGenerationModelSelection.model;\n const options = shouldReplaceTextGenerationModelSelection(selectionPatch)\n ? selectionPatch.options\n@@ -90,7 +97,7 @@ export function applyServerSettingsPatch(\n });\n \n return {\n- ...next,\n- textGenerationModelSelection: createModelSelection(provider, model, options),\n+ ...nextWithReplacements,\n+ textGenerationModelSelection: createModelSelection(instanceId, model, options),\n };\n }\n';
apps/mobile/src/features/debug/native-review-diff/nativeReviewDiffParser.test.ts+0−156
@@ -1,156 +0,0 @@
1import { describe, expect, it } from "vitest";
2
3import { parseNativeReviewDiffFixture } from "./nativeReviewDiffParser";
4
5describe("parseNativeReviewDiffFixture", () => {
6 it("adds word diff ranges to paired changed lines", () => {
7 const parsed = parseNativeReviewDiffFixture({
8 id: "states",
9 label: "States",
10 filename: "states.diff",
11 lineCount: 9,
12 diff: [
13 "diff --git a/main.ts b/main.ts",
14 "index 1111111..2222222 100644",
15 "--- a/main.ts",
16 "+++ b/main.ts",
17 "@@ -1,3 +1,3 @@",
18 " const stable = true;",
19 '-const label = "Before value";',
20 '+const label = "After value";',
21 " const done = true;",
22 ].join("\n"),
23 });
24
25 const deletion = parsed.rows.find((row) => row.change === "delete");
26 const addition = parsed.rows.find((row) => row.change === "add");
27
28 expect(deletion?.wordDiffRanges).toEqual([{ start: 15, end: 21 }]);
29 expect(addition?.wordDiffRanges).toEqual([{ start: 15, end: 20 }]);
30 });
31
32 it("does not add word diff ranges to unpaired created lines", () => {
33 const parsed = parseNativeReviewDiffFixture({
34 id: "states",
35 label: "States",
36 filename: "states.diff",
37 lineCount: 9,
38 diff: [
39 "diff --git a/new.ts b/new.ts",
40 "new file mode 100644",
41 "index 0000000..2222222",
42 "--- /dev/null",
43 "+++ b/new.ts",
44 "@@ -0,0 +1,2 @@",
45 '+const label = "After value";',
46 "+export default label;",
47 ].join("\n"),
48 });
49
50 expect(parsed.rows.filter((row) => row.kind === "line")).toHaveLength(2);
51 expect(parsed.rows.every((row) => row.wordDiffRanges === undefined)).toBe(true);
52 });
53
54 it("trims whitespace from word diff range edges", () => {
55 const parsed = parseNativeReviewDiffFixture({
56 id: "states",
57 label: "States",
58 filename: "states.diff",
59 lineCount: 8,
60 diff: [
61 "diff --git a/main.tsx b/main.tsx",
62 "index 1111111..2222222 100644",
63 "--- a/main.tsx",
64 "+++ b/main.tsx",
65 "@@ -1,2 +1,2 @@",
66 "- const status = disabled;",
67 "+ const status = enabled;",
68 ].join("\n"),
69 });
70
71 const deletion = parsed.rows.find((row) => row.change === "delete");
72 const addition = parsed.rows.find((row) => row.change === "add");
73
74 expect(deletion?.wordDiffRanges?.[0]?.start).toBeGreaterThanOrEqual(4);
75 expect(addition?.wordDiffRanges?.[0]?.start).toBeGreaterThanOrEqual(4);
76 });
77
78 it("keeps word diff ranges aligned to exact replacement columns", () => {
79 const parsed = parseNativeReviewDiffFixture({
80 id: "states",
81 label: "States",
82 filename: "states.diff",
83 lineCount: 12,
84 diff: [
85 "diff --git a/main.ts b/main.ts",
86 "index 1111111..2222222 100644",
87 "--- a/main.ts",
88 "+++ b/main.ts",
89 "@@ -1,5 +1,5 @@",
90 "-const retryLimit = 2;",
91 "+const retryLimit = 4;",
92 '-const greeting = greeting.replace("{name}", "reviewer");',
93 '+const greeting = greeting.replace("{name}", "native reviewer");',
94 ].join("\n"),
95 });
96
97 const changedRows = parsed.rows.filter((row) => row.kind === "line");
98
99 expect(changedRows[0]?.wordDiffRanges).toEqual([{ start: 19, end: 20 }]);
100 expect(changedRows[1]?.wordDiffRanges).toEqual([{ start: 19, end: 20 }]);
101 expect(changedRows[2]?.wordDiffRanges).toBeUndefined();
102 expect(changedRows[3]?.wordDiffRanges).toEqual([{ start: 45, end: 51 }]);
103 });
104
105 it("suppresses noisy word diff ranges for unrelated replacement lines", () => {
106 const parsed = parseNativeReviewDiffFixture({
107 id: "states",
108 label: "States",
109 filename: "states.diff",
110 lineCount: 8,
111 diff: [
112 "diff --git a/main.tsx b/main.tsx",
113 "index 1111111..2222222 100644",
114 "--- a/main.tsx",
115 "+++ b/main.tsx",
116 "@@ -1,2 +1,2 @@",
117 '- case "file-header":',
118 "+ const status = enabled;",
119 ].join("\n"),
120 });
121
122 expect(parsed.rows.every((row) => row.wordDiffRanges === undefined)).toBe(true);
123 });
124
125 it("adds notice rows for pure renames and metadata-only changes", () => {
126 const parsed = parseNativeReviewDiffFixture({
127 id: "states",
128 label: "States",
129 filename: "states.diff",
130 lineCount: 16,
131 diff: [
132 "diff --git a/src/oldName.ts b/src/newName.ts",
133 "similarity index 100%",
134 "rename from src/oldName.ts",
135 "rename to src/newName.ts",
136 "diff --git a/scripts/run.sh b/scripts/run.sh",
137 "old mode 100644",
138 "new mode 100755",
139 "diff --git a/assets/logo.png b/assets/logo.png",
140 "new file mode 100644",
141 "index 000000000..4628f44da",
142 "--- /dev/null",
143 "+++ b/assets/logo.png",
144 "Binary files /dev/null and b/assets/logo.png differ",
145 ].join("\n"),
146 });
147
148 const noticeTexts = parsed.rows.filter((row) => row.kind === "notice").map((row) => row.text);
149
150 expect(noticeTexts).toEqual([
151 "This file was renamed without modifications.",
152 "File mode changed from 100644 to 100755.",
153 "Unsupported binary format. Diff contents are not available.",
154 ]);
155 });
156});
apps/mobile/src/features/debug/native-review-diff/nativeReviewDiffParser.ts+0−549
@@ -1,549 +0,0 @@
1import {
2 debugReviewDiffFixtures,
3 type DebugReviewDiffFixture,
4 type DebugReviewDiffFixtureId,
5} from "../fixtures/reviewDiffFixtures";
6import { computeWordAltDiffRanges } from "../../review/reviewWordDiffs";
7import type { NativeReviewDiffRow } from "./nativeReviewDiffModule";
8
9const NATIVE_REVIEW_MAX_WORD_DIFF_RANGE_COUNT = 4;
10const NATIVE_REVIEW_MAX_WORD_DIFF_COVERAGE = 0.45;
11
12export type NativeReviewDiffLanguage =
13 | "bash"
14 | "diff"
15 | "javascript"
16 | "json"
17 | "jsx"
18 | "tsx"
19 | "typescript"
20 | "yaml";
21
22export interface NativeReviewDiffFile {
23 readonly id: string;
24 readonly path: string;
25 readonly language: NativeReviewDiffLanguage;
26 readonly additions: number;
27 readonly deletions: number;
28}
29
30export interface NativeReviewDiffParsedFixture {
31 readonly fixtureId: DebugReviewDiffFixtureId;
32 readonly rows: ReadonlyArray<NativeReviewDiffRow>;
33 readonly files: ReadonlyArray<NativeReviewDiffFile>;
34 readonly additions: number;
35 readonly deletions: number;
36}
37
38interface NativeReviewDiffFileParseState {
39 readonly path: string;
40 readonly language: NativeReviewDiffLanguage;
41 readonly additions: number;
42 readonly deletions: number;
43 readonly hasRenderableRows: boolean;
44 readonly isBinary: boolean;
45 readonly oldMode: string | null;
46 readonly newMode: string | null;
47}
48
49function getDiffPathFromHeader(line: string): string {
50 const match = line.match(/^diff --git a\/(.+) b\/(.+)$/);
51 return match?.[2] ?? line.replace(/^diff --git /, "");
52}
53
54function getDiffPreviousPathFromHeader(line: string): string | null {
55 const match = line.match(/^diff --git a\/(.+) b\/(.+)$/);
56 return match?.[1] ?? null;
57}
58
59function parseDiffPath(line: string, prefix: "--- " | "+++ "): string | null {
60 if (!line.startsWith(prefix)) {
61 return null;
62 }
63
64 const rawPath = line.slice(prefix.length).trim();
65 if (rawPath === "/dev/null") {
66 return null;
67 }
68
69 return rawPath.replace(/^[ab]\//, "");
70}
71
72function resolveChangeType(input: {
73 readonly previousPath: string | null;
74 readonly nextPath: string | null;
75}): NativeReviewDiffRow["changeType"] {
76 if (!input.previousPath && input.nextPath) {
77 return "new";
78 }
79 if (input.previousPath && !input.nextPath) {
80 return "deleted";
81 }
82 if (input.previousPath && input.nextPath && input.previousPath !== input.nextPath) {
83 return "renamed";
84 }
85 return "modified";
86}
87
88function resolveFileHeaderChangeType(input: {
89 readonly previousPath: string | null | undefined;
90 readonly nextPath: string | null | undefined;
91 readonly currentChangeType: NativeReviewDiffRow["changeType"];
92 readonly additions: number;
93 readonly deletions: number;
94}): NativeReviewDiffRow["changeType"] {
95 if (input.currentChangeType === "new" || input.currentChangeType === "deleted") {
96 return input.currentChangeType;
97 }
98
99 if (input.previousPath && input.nextPath && input.previousPath !== input.nextPath) {
100 return input.additions + input.deletions === 0 ? "rename-pure" : "rename-changed";
101 }
102
103 return resolveChangeType({
104 nextPath: input.nextPath ?? null,
105 previousPath: input.previousPath ?? null,
106 });
107}
108
109function getLanguageForPath(filePath: string): NativeReviewDiffLanguage {
110 const normalizedPath = filePath.toLowerCase();
111 if (normalizedPath.endsWith(".tsx")) return "tsx";
112 if (normalizedPath.endsWith(".ts")) return "typescript";
113 if (normalizedPath.endsWith(".jsx")) return "jsx";
114 if (normalizedPath.endsWith(".js") || normalizedPath.endsWith(".cjs")) return "javascript";
115 if (normalizedPath.endsWith(".json") || normalizedPath.endsWith(".jsonc")) return "json";
116 if (normalizedPath.endsWith(".yml") || normalizedPath.endsWith(".yaml")) return "yaml";
117 if (
118 normalizedPath.endsWith(".sh") ||
119 normalizedPath.includes("/bin/") ||
120 normalizedPath.includes("shell")
121 ) {
122 return "bash";
123 }
124 return "diff";
125}
126
127function parseHunkLineNumbers(line: string): { oldLine: number; newLine: number } | null {
128 const match = line.match(/^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/);
129 if (!match) {
130 return null;
131 }
132 return {
133 oldLine: Number(match[1]),
134 newLine: Number(match[2]),
135 };
136}
137
138function parseFileModeLine(line: string, prefix: "old mode " | "new mode "): string | null {
139 if (!line.startsWith(prefix)) {
140 return null;
141 }
142
143 return line.slice(prefix.length).trim() || null;
144}
145
146function createNoticeRow(input: {
147 readonly fileId: string;
148 readonly message: string;
149 readonly suffix: string;
150}): NativeReviewDiffRow {
151 return {
152 kind: "notice",
153 id: `${input.fileId}:notice:${input.suffix}`,
154 fileId: input.fileId,
155 text: input.message,
156 };
157}
158
159function getNoticeRowForFile(input: {
160 readonly row: NativeReviewDiffRow;
161 readonly file: NativeReviewDiffFileParseState | undefined;
162}): NativeReviewDiffRow | null {
163 const { file, row } = input;
164 if (!file || row.kind !== "file" || !row.fileId) {
165 return null;
166 }
167
168 if (file.isBinary) {
169 return createNoticeRow({
170 fileId: row.fileId,
171 message: "Unsupported binary format. Diff contents are not available.",
172 suffix: "binary",
173 });
174 }
175
176 if (file.oldMode && file.newMode && file.oldMode !== file.newMode && !file.hasRenderableRows) {
177 return createNoticeRow({
178 fileId: row.fileId,
179 message: `File mode changed from ${file.oldMode} to ${file.newMode}.`,
180 suffix: "mode",
181 });
182 }
183
184 if (row.changeType === "rename-pure" && !file.hasRenderableRows) {
185 return createNoticeRow({
186 fileId: row.fileId,
187 message: "This file was renamed without modifications.",
188 suffix: "rename",
189 });
190 }
191
192 return null;
193}
194
195function isChangedLine(row: NativeReviewDiffRow | undefined, change: "add" | "delete") {
196 return row?.kind === "line" && row.change === change && typeof row.content === "string";
197}
198
199function trimWordDiffRanges(
200 content: string,
201 ranges: NonNullable<NativeReviewDiffRow["wordDiffRanges"]>,
202): NonNullable<NativeReviewDiffRow["wordDiffRanges"]> {
203 return ranges.flatMap((range) => {
204 let start = Math.max(0, range.start);
205 let end = Math.min(content.length, range.end);
206
207 while (start < end && /\s/.test(content[start] ?? "")) {
208 start += 1;
209 }
210
211 while (end > start && /\s/.test(content[end - 1] ?? "")) {
212 end -= 1;
213 }
214
215 return end > start ? [{ start, end }] : [];
216 });
217}
218
219function nonWhitespaceLength(value: string) {
220 return value.replace(/\s/g, "").length;
221}
222
223function getRangeCoverage(
224 content: string,
225 ranges: NonNullable<NativeReviewDiffRow["wordDiffRanges"]>,
226) {
227 const meaningfulLength = nonWhitespaceLength(content);
228 if (meaningfulLength === 0) {
229 return 1;
230 }
231
232 const highlightedLength = ranges.reduce(
233 (total, range) => total + nonWhitespaceLength(content.slice(range.start, range.end)),
234 0,
235 );
236 return highlightedLength / meaningfulLength;
237}
238
239function shouldUseWordDiffRanges(
240 content: string,
241 ranges: NonNullable<NativeReviewDiffRow["wordDiffRanges"]>,
242) {
243 if (ranges.length === 0 || ranges.length > NATIVE_REVIEW_MAX_WORD_DIFF_RANGE_COUNT) {
244 return false;
245 }
246
247 return getRangeCoverage(content, ranges) <= NATIVE_REVIEW_MAX_WORD_DIFF_COVERAGE;
248}
249
250function addNativeWordDiffRanges(rows: ReadonlyArray<NativeReviewDiffRow>) {
251 const nextRows = [...rows];
252 let index = 0;
253
254 while (index < nextRows.length) {
255 const deletedRowIndexes: number[] = [];
256 const addedRowIndexes: number[] = [];
257 const fileId = nextRows[index]?.fileId;
258
259 while (isChangedLine(nextRows[index], "delete") && nextRows[index]?.fileId === fileId) {
260 deletedRowIndexes.push(index);
261 index += 1;
262 }
263
264 if (deletedRowIndexes.length === 0) {
265 index += 1;
266 continue;
267 }
268
269 while (isChangedLine(nextRows[index], "add") && nextRows[index]?.fileId === fileId) {
270 addedRowIndexes.push(index);
271 index += 1;
272 }
273
274 if (addedRowIndexes.length === 0) {
275 continue;
276 }
277
278 const pairCount = Math.min(deletedRowIndexes.length, addedRowIndexes.length);
279 for (let pairIndex = 0; pairIndex < pairCount; pairIndex += 1) {
280 const deletedRowIndex = deletedRowIndexes[pairIndex];
281 const addedRowIndex = addedRowIndexes[pairIndex];
282 const deletedRow = nextRows[deletedRowIndex];
283 const addedRow = nextRows[addedRowIndex];
284 if (!deletedRow?.content || !addedRow?.content) {
285 continue;
286 }
287
288 const ranges = computeWordAltDiffRanges({
289 deletionLine: deletedRow.content,
290 additionLine: addedRow.content,
291 });
292
293 const deletionRanges = trimWordDiffRanges(deletedRow.content, ranges.deletion);
294 const additionRanges = trimWordDiffRanges(addedRow.content, ranges.addition);
295
296 if (shouldUseWordDiffRanges(deletedRow.content, deletionRanges)) {
297 nextRows[deletedRowIndex] = { ...deletedRow, wordDiffRanges: deletionRanges };
298 }
299
300 if (shouldUseWordDiffRanges(addedRow.content, additionRanges)) {
301 nextRows[addedRowIndex] = { ...addedRow, wordDiffRanges: additionRanges };
302 }
303 }
304 }
305
306 return nextRows;
307}
308
309export function parseNativeReviewDiffFixture(
310 fixture: DebugReviewDiffFixture,
311): NativeReviewDiffParsedFixture {
312 const startedAt = performance.now();
313 let rows: NativeReviewDiffRow[] = [];
314 const files = new Map<string, NativeReviewDiffFileParseState>();
315 const rawLines = fixture.diff.split(/\r?\n/);
316
317 let currentFileId: string | null = null;
318 let currentOldLine: number | null = null;
319 let currentNewLine: number | null = null;
320
321 function ensureCurrentFile(filePath: string, previousPath: string | null): string {
322 const fileId = `file:${files.size}:${filePath}`;
323 const language = getLanguageForPath(filePath);
324 files.set(fileId, {
325 path: filePath,
326 language,
327 additions: 0,
328 deletions: 0,
329 hasRenderableRows: false,
330 isBinary: false,
331 oldMode: null,
332 newMode: null,
333 });
334 rows.push({
335 kind: "file",
336 id: `${fileId}:header`,
337 fileId,
338 filePath,
339 previousPath,
340 changeType: resolveChangeType({ nextPath: filePath, previousPath }),
341 additions: 0,
342 deletions: 0,
343 });
344 return fileId;
345 }
346
347 for (let index = 0; index < rawLines.length; index += 1) {
348 const rawLine = rawLines[index] ?? "";
349
350 if (rawLine.startsWith("diff --git ")) {
351 currentFileId = ensureCurrentFile(
352 getDiffPathFromHeader(rawLine),
353 getDiffPreviousPathFromHeader(rawLine),
354 );
355 currentOldLine = null;
356 currentNewLine = null;
357 continue;
358 }
359
360 if (!currentFileId) {
361 continue;
362 }
363
364 const previousPath = parseDiffPath(rawLine, "--- ");
365 if (previousPath !== null || rawLine === "--- /dev/null") {
366 rows = rows.map((row) =>
367 row.id === `${currentFileId}:header`
368 ? {
369 ...row,
370 previousPath,
371 changeType: resolveChangeType({
372 nextPath: row.filePath ?? null,
373 previousPath,
374 }),
375 }
376 : row,
377 );
378 continue;
379 }
380
381 const nextPath = parseDiffPath(rawLine, "+++ ");
382 if (nextPath !== null || rawLine === "+++ /dev/null") {
383 rows = rows.map((row) =>
384 row.id === `${currentFileId}:header`
385 ? {
386 ...row,
387 filePath: nextPath ?? row.filePath,
388 changeType: resolveChangeType({
389 nextPath,
390 previousPath: row.previousPath ?? null,
391 }),
392 }
393 : row,
394 );
395 continue;
396 }
397
398 const oldMode = parseFileModeLine(rawLine, "old mode ");
399 if (oldMode !== null) {
400 const file = files.get(currentFileId);
401 if (file) {
402 files.set(currentFileId, { ...file, oldMode });
403 }
404 continue;
405 }
406
407 const newMode = parseFileModeLine(rawLine, "new mode ");
408 if (newMode !== null) {
409 const file = files.get(currentFileId);
410 if (file) {
411 files.set(currentFileId, { ...file, newMode });
412 }
413 continue;
414 }
415
416 if (rawLine.startsWith("Binary files ")) {
417 const file = files.get(currentFileId);
418 if (file) {
419 files.set(currentFileId, { ...file, isBinary: true });
420 }
421 continue;
422 }
423
424 if (rawLine.startsWith("@@ ")) {
425 const file = files.get(currentFileId);
426 if (file) {
427 files.set(currentFileId, { ...file, hasRenderableRows: true });
428 }
429 const parsedLineNumbers = parseHunkLineNumbers(rawLine);
430 currentOldLine = parsedLineNumbers?.oldLine ?? null;
431 currentNewLine = parsedLineNumbers?.newLine ?? null;
432 rows.push({
433 kind: "hunk",
434 id: `${currentFileId}:hunk:${index}`,
435 fileId: currentFileId,
436 text: rawLine,
437 });
438 continue;
439 }
440
441 const marker = rawLine[0];
442 if (marker !== " " && marker !== "+" && marker !== "-") {
443 continue;
444 }
445
446 const file = files.get(currentFileId);
447 if (!file) {
448 continue;
449 }
450
451 const change = marker === "+" ? "add" : marker === "-" ? "delete" : "context";
452 rows.push({
453 kind: "line",
454 id: `${currentFileId}:line:${index}`,
455 fileId: currentFileId,
456 change,
457 oldLineNumber: change === "add" ? null : currentOldLine,
458 newLineNumber: change === "delete" ? null : currentNewLine,
459 content: rawLine.slice(1),
460 });
461
462 if (change === "add") {
463 files.set(currentFileId, { ...file, additions: file.additions + 1 });
464 currentNewLine = currentNewLine === null ? null : currentNewLine + 1;
465 continue;
466 }
467
468 if (change === "delete") {
469 files.set(currentFileId, { ...file, deletions: file.deletions + 1 });
470 currentOldLine = currentOldLine === null ? null : currentOldLine + 1;
471 continue;
472 }
473
474 currentOldLine = currentOldLine === null ? null : currentOldLine + 1;
475 currentNewLine = currentNewLine === null ? null : currentNewLine + 1;
476 }
477
478 rows = addNativeWordDiffRanges(rows);
479
480 const fileSummaries = Array.from(files, ([id, file]) => ({
481 id,
482 path: file.path,
483 language: file.language,
484 additions: file.additions,
485 deletions: file.deletions,
486 }));
487 const fileSummaryByPath = new Map(fileSummaries.map((file) => [file.path, file]));
488 const rowsWithFileStats = rows.map((row): NativeReviewDiffRow => {
489 if (row.kind !== "file" || !row.filePath) {
490 return row;
491 }
492 const file = fileSummaryByPath.get(row.filePath);
493 const additions = file?.additions ?? row.additions ?? 0;
494 const deletions = file?.deletions ?? row.deletions ?? 0;
495 return {
496 kind: row.kind,
497 id: row.id,
498 fileId: row.fileId,
499 filePath: row.filePath,
500 previousPath: row.previousPath,
501 changeType: resolveFileHeaderChangeType({
502 previousPath: row.previousPath,
503 nextPath: row.filePath,
504 currentChangeType: row.changeType ?? "modified",
505 additions,
506 deletions,
507 }),
508 additions,
509 deletions,
510 text: row.text,
511 content: row.content,
512 change: row.change,
513 oldLineNumber: row.oldLineNumber,
514 newLineNumber: row.newLineNumber,
515 wordDiffRanges: row.wordDiffRanges,
516 };
517 });
518 const rowsWithFileNotices = rowsWithFileStats.flatMap((row): NativeReviewDiffRow[] => {
519 const noticeRow = getNoticeRowForFile({
520 row,
521 file: row.fileId ? files.get(row.fileId) : undefined,
522 });
523 return noticeRow ? [row, noticeRow] : [row];
524 });
525
526 const parsed = {
527 fixtureId: fixture.id,
528 rows: rowsWithFileNotices,
529 files: fileSummaries,
530 additions: fileSummaries.reduce((total, file) => total + file.additions, 0),
531 deletions: fileSummaries.reduce((total, file) => total + file.deletions, 0),
532 };
533
534 console.log("[debug-native-diff] parse", {
535 durationMs: Math.round(performance.now() - startedAt),
536 files: parsed.files.length,
537 fixture: fixture.id,
538 rows: parsed.rows.length,
539 });
540
541 return parsed;
542}
543
544export function getNativeReviewDiffFixture(fixtureId: DebugReviewDiffFixtureId) {
545 return (
546 debugReviewDiffFixtures.find((fixture) => fixture.id === fixtureId) ??
547 debugReviewDiffFixtures[0]
548 );
549}
apps/mobile/src/features/diffs/nativeReviewDiffHighlighter.tsrenamed from apps/mobile/src/features/debug/native-review-diff/nativeReviewDiffHighlighter.ts+2−2
@@ -9,8 +9,8 @@ import tsxLanguage from "@shikijs/langs/tsx"; · 8 unmodified lines
9import typescriptLanguage from "@shikijs/langs/typescript";9import typescriptLanguage from "@shikijs/langs/typescript";
10import yamlLanguage from "@shikijs/langs/yaml";10import yamlLanguage from "@shikijs/langs/yaml";
11 11
12import type { NativeReviewDiffRow, NativeReviewDiffToken } from "./nativeReviewDiffModule";12import type { NativeReviewDiffFile, NativeReviewDiffLanguage } from "./nativeReviewDiffTypes";
13import type { NativeReviewDiffFile, NativeReviewDiffLanguage } from "./nativeReviewDiffParser";13import type { NativeReviewDiffRow, NativeReviewDiffToken } from "./nativeReviewDiffSurface";
14 14
15export type NativeReviewDiffHighlightScheme = "light" | "dark";15export type NativeReviewDiffHighlightScheme = "light" | "dark";
16export type NativeReviewDiffHighlightEngine = "native" | "javascript";16export type NativeReviewDiffHighlightEngine = "native" | "javascript";
apps/mobile/src/features/diffs/nativeReviewDiffSurface.test.tsrenamed from apps/mobile/src/features/debug/native-review-diff/nativeReviewDiffModule.test.ts+4−4
@@ -28,7 +28,7 @@ describe("resolveNativeReviewDiffView", () => { · 27 unmodified lines
28 });28 });
29 29
30 it("returns null when the native review diff view config is unavailable", async () => {30 it("returns null when the native review diff view config is unavailable", async () => {
31 const { resolveNativeReviewDiffView } = await import("./nativeReviewDiffModule");31 const { resolveNativeReviewDiffView } = await import("./nativeReviewDiffSurface");
32 expect(resolveNativeReviewDiffView()).toBeNull();32 expect(resolveNativeReviewDiffView()).toBeNull();
33 expect(expoModulesCoreMocks.requireNativeViewManager).not.toHaveBeenCalled();33 expect(expoModulesCoreMocks.requireNativeViewManager).not.toHaveBeenCalled();
34 });34 });
@@ -36,7 +36,7 @@ describe("resolveNativeReviewDiffView", () => { · 1 unmodified line
36 it("returns the native review diff view when the view config is installed", async () => {36 it("returns the native review diff view when the view config is installed", async () => {
37 setExpoViewConfigAvailable();37 setExpoViewConfigAvailable();
38 expoModulesCoreMocks.requireNativeViewManager.mockReturnValue(nativeView);38 expoModulesCoreMocks.requireNativeViewManager.mockReturnValue(nativeView);
39 const { resolveNativeReviewDiffView } = await import("./nativeReviewDiffModule");39 const { resolveNativeReviewDiffView } = await import("./nativeReviewDiffSurface");
40 expect(resolveNativeReviewDiffView()).toBe(nativeView);40 expect(resolveNativeReviewDiffView()).toBe(nativeView);
41 expect(expoModulesCoreMocks.requireNativeViewManager).toHaveBeenCalledWith(41 expect(expoModulesCoreMocks.requireNativeViewManager).toHaveBeenCalledWith(
42 "T3ReviewDiffSurface",42 "T3ReviewDiffSurface",
@@ -53,7 +53,7 @@ describe("resolveNativeReviewDiffView", () => { · 10 unmodified lines
53 }),53 }),
54 } as unknown as typeof globalThis.expo;54 } as unknown as typeof globalThis.expo;
55 expoModulesCoreMocks.requireNativeViewManager.mockReturnValue(nativeView);55 expoModulesCoreMocks.requireNativeViewManager.mockReturnValue(nativeView);
56 const { resolveNativeReviewDiffView } = await import("./nativeReviewDiffModule");56 const { resolveNativeReviewDiffView } = await import("./nativeReviewDiffSurface");
57 expect(resolveNativeReviewDiffView()).toBeNull();57 expect(resolveNativeReviewDiffView()).toBeNull();
58 expect(expoModulesCoreMocks.requireNativeViewManager).not.toHaveBeenCalled();58 expect(expoModulesCoreMocks.requireNativeViewManager).not.toHaveBeenCalled();
59 });59 });
@@ -63,7 +63,7 @@ describe("resolveNativeReviewDiffView", () => { · 3 unmodified lines
63 expoModulesCoreMocks.requireNativeViewManager.mockImplementation(() => {63 expoModulesCoreMocks.requireNativeViewManager.mockImplementation(() => {
64 throw new Error("boom");64 throw new Error("boom");
65 });65 });
66 const { resolveNativeReviewDiffView } = await import("./nativeReviewDiffModule");66 const { resolveNativeReviewDiffView } = await import("./nativeReviewDiffSurface");
67 expect(resolveNativeReviewDiffView()).toBeNull();67 expect(resolveNativeReviewDiffView()).toBeNull();
68 });68 });
69});69});
apps/mobile/src/features/diffs/nativeReviewDiffSurface.tsrenamed from apps/mobile/src/features/debug/native-review-diff/nativeReviewDiffModule.ts+0−6
@@ -127,7 +127,6 @@ export interface NativeReviewDiffViewProps extends ViewProps { · 126 unmodified lines
127}127}
128 128
129let cachedNativeReviewDiffView: ComponentType<NativeReviewDiffViewProps> | undefined;129let cachedNativeReviewDiffView: ComponentType<NativeReviewDiffViewProps> | undefined;
130let cachedNativeReviewDiffModuleName: typeof NATIVE_REVIEW_DIFF_MODULE_NAME | undefined;
131 130
132function getExpoViewConfig(moduleName: string) {131function getExpoViewConfig(moduleName: string) {
133 return (globalThis as typeof globalThis & ExpoGlobalWithViewConfig).expo?.getViewConfig?.(132 return (globalThis as typeof globalThis & ExpoGlobalWithViewConfig).expo?.getViewConfig?.(
@@ -152,10 +151,5 @@ export function resolveNativeReviewDiffView(): ComponentType<NativeReviewDiffVie · 18 unmodified lines
152 return null;151 return null;
153 }152 }
154 153
155 cachedNativeReviewDiffModuleName = NATIVE_REVIEW_DIFF_MODULE_NAME;
156 return cachedNativeReviewDiffView ?? null;154 return cachedNativeReviewDiffView ?? null;
157}155}
158
159export function getResolvedNativeReviewDiffModuleName() {
160 return cachedNativeReviewDiffModuleName ?? null;
161}
apps/mobile/src/features/diffs/nativeReviewDiffTypes.ts+17−0
@@ -0,0 +1,17 @@
1export type NativeReviewDiffLanguage =
2 | "bash"
3 | "diff"
4 | "javascript"
5 | "json"
6 | "jsx"
7 | "tsx"
8 | "typescript"
9 | "yaml";
10
11export interface NativeReviewDiffFile {
12 readonly id: string;
13 readonly path: string;
14 readonly language: NativeReviewDiffLanguage;
15 readonly additions: number;
16 readonly deletions: number;
17}
apps/mobile/src/features/review/ReviewSheet.tsx+4−4
@@ -52,8 +52,8 @@ import { markReviewEvent, measureReviewWork } from "./reviewPerf"; · 51 unmodified lines
52import {52import {
53 highlightNativeReviewDiffVisibleRows,53 highlightNativeReviewDiffVisibleRows,
54 type NativeReviewDiffHighlightEngine,54 type NativeReviewDiffHighlightEngine,
55} from "../debug/native-review-diff/nativeReviewDiffHighlighter";55} from "../diffs/nativeReviewDiffHighlighter";
56import { resolveNativeReviewDiffView } from "../debug/native-review-diff/nativeReviewDiffModule";56import { resolveNativeReviewDiffView } from "../diffs/nativeReviewDiffSurface";
57import {57import {
58 buildNativeReviewDiffData,58 buildNativeReviewDiffData,
59 createNativeReviewDiffTheme,59 createNativeReviewDiffTheme,
@@ -507,9 +507,9 @@ export function ReviewSheet() { · 447 unmodified lines
507 setLoadingGitDiffs(true);507 setLoadingGitDiffs(true);
508 setError(null);508 setError(null);
509 try {509 try {
510 const result = await client.git.getReviewDiffs({ cwd });510 const result = await client.review.getDiffPreview({ cwd });
511 if (reviewCache.threadKey) {511 if (reviewCache.threadKey) {
512 setReviewGitSections(reviewCache.threadKey, result.sections);512 setReviewGitSections(reviewCache.threadKey, result.sources);
513 }513 }
514 } catch (cause) {514 } catch (cause) {
515 setError(cause instanceof Error ? cause.message : "Failed to load review diffs.");515 setError(cause instanceof Error ? cause.message : "Failed to load review diffs.");
apps/mobile/src/features/review/nativeReviewDiffAdapter.test.ts+1−0
@@ -39,6 +39,7 @@ describe("buildNativeReviewDiffData", () => { · 38 unmodified lines
39 endIndex: 1,39 endIndex: 1,
40 rangeLabel: "+2",40 rangeLabel: "+2",
41 text: "Please keep this configurable.",41 text: "Please keep this configurable.",
42 diff: "",
42 },43 },
43 ],44 ],
44 });45 });
apps/mobile/src/features/review/nativeReviewDiffAdapter.ts+2−5
@@ -1,11 +1,8 @@
1import type {1import type { NativeReviewDiffRow, NativeReviewDiffTheme } from "../diffs/nativeReviewDiffSurface";
2 NativeReviewDiffRow,
3 NativeReviewDiffTheme,
4} from "../debug/native-review-diff/nativeReviewDiffModule";
5import type {2import type {
6 NativeReviewDiffFile,3 NativeReviewDiffFile,
7 NativeReviewDiffLanguage,4 NativeReviewDiffLanguage,
8} from "../debug/native-review-diff/nativeReviewDiffParser";5} from "../diffs/nativeReviewDiffTypes";
9import { getPierreTerminalTheme, type TerminalAppearanceScheme } from "../terminal/terminalTheme";6import { getPierreTerminalTheme, type TerminalAppearanceScheme } from "../terminal/terminalTheme";
10import { computeWordAltDiffRanges } from "./reviewWordDiffs";7import { computeWordAltDiffRanges } from "./reviewWordDiffs";
11import {8import {
apps/mobile/src/features/review/reviewCommentSelection.test.ts+21−0
@@ -3,6 +3,7 @@ import { describe, expect, it } from "vitest"; · 2 unmodified lines
3import {3import {
4 countReviewCommentContexts,4 countReviewCommentContexts,
5 formatReviewCommentContext,5 formatReviewCommentContext,
6 parseReviewCommentMessageSegments,
6 parseReviewInlineComments,7 parseReviewInlineComments,
7 type ReviewCommentTarget,8 type ReviewCommentTarget,
8} from "./reviewCommentSelection";9} from "./reviewCommentSelection";
@@ -54,7 +55,27 @@ describe("review comment serialization", () => { · 45 unmodified lines
54 startIndex: 0,55 startIndex: 0,
55 endIndex: 1,56 endIndex: 1,
56 text: "Please keep this configurable.",57 text: "Please keep this configurable.",
58 diff: expect.stringContaining("-const retryLimit = 2;"),
57 }),59 }),
58 ]);60 ]);
59 });61 });
62
63 it("splits chat text into review comment segments", () => {
64 const serialized = `Before\n${formatReviewCommentContext(makeTarget(), "Please keep this configurable.")}\nAfter`;
65 const segments = parseReviewCommentMessageSegments(serialized);
66
67 expect(segments).toHaveLength(3);
68 expect(segments[0]).toEqual(expect.objectContaining({ kind: "text", text: "Before\n" }));
69 expect(segments[1]).toEqual(
70 expect.objectContaining({
71 kind: "review-comment",
72 comment: expect.objectContaining({
73 filePath: "apps/demo/src/main.ts",
74 text: "Please keep this configurable.",
75 diff: expect.stringContaining("+const retryLimit = 4;"),
76 }),
77 }),
78 );
79 expect(segments[2]).toEqual(expect.objectContaining({ kind: "text", text: "\nAfter" }));
80 });
60});81});
apps/mobile/src/features/review/reviewCommentSelection.ts+92−16
@@ -20,8 +20,20 @@ export interface ReviewInlineComment { · 19 unmodified lines
20 readonly endIndex: number;20 readonly endIndex: number;
21 readonly rangeLabel: string;21 readonly rangeLabel: string;
22 readonly text: string;22 readonly text: string;
23 readonly diff: string;
23}24}
24 25
26export type ReviewCommentMessageSegment =
27 | {
28 readonly kind: "text";
29 readonly id: string;
30 readonly text: string;
31 }
32 | {
33 readonly kind: "review-comment";
34 readonly comment: ReviewInlineComment;
35 };
36
25let currentTarget: ReviewCommentTarget | null = null;37let currentTarget: ReviewCommentTarget | null = null;
26const listeners = new Set<() => void>();38const listeners = new Set<() => void>();
27const REVIEW_COMMENT_BLOCK_PATTERN = /<review_comment\b([^>]*)>\s*([\s\S]*?)<\/review_comment>/g;39const REVIEW_COMMENT_BLOCK_PATTERN = /<review_comment\b([^>]*)>\s*([\s\S]*?)<\/review_comment>/g;
@@ -189,6 +201,38 @@ function extractReviewCommentText(rawBody: string): string { · 161 unmodified lines
189 return commentBody.trim();201 return commentBody.trim();
190}202}
191 203
204function extractReviewCommentDiff(rawBody: string): string {
205 const match = rawBody.match(/```diff\s*\n([\s\S]*?)\n```/);
206 return match?.[1]?.trim() ?? "";
207}
208
209function parseReviewInlineComment(
210 rawAttributes: string,
211 rawBody: string,
212 index: number,
213): ReviewInlineComment | null {
214 const attributes = readReviewCommentAttributes(rawAttributes);
215 const startIndex = readNonNegativeInteger(attributes.startIndex);
216 const endIndex = readNonNegativeInteger(attributes.endIndex);
217 const filePath = attributes.filePath?.trim();
218 const sectionId = attributes.sectionId?.trim();
219 if (!filePath || !sectionId || startIndex === null || endIndex === null) {
220 return null;
221 }
222
223 return {
224 id: `review-comment:${index}:${sectionId}:${filePath}:${startIndex}:${endIndex}`,
225 sectionId,
226 sectionTitle: attributes.sectionTitle?.trim() || "Review",
227 filePath,
228 startIndex: Math.min(startIndex, endIndex),
229 endIndex: Math.max(startIndex, endIndex),
230 rangeLabel: attributes.rangeLabel?.trim() || "line",
231 text: extractReviewCommentText(rawBody),
232 diff: extractReviewCommentDiff(rawBody),
233 };
234}
235
192export function formatReviewCommentContext(target: ReviewCommentTarget, comment: string): string {236export function formatReviewCommentContext(target: ReviewCommentTarget, comment: string): string {
193 const rangeLabel = formatReviewSelectedRangeLabel(target);237 const rangeLabel = formatReviewSelectedRangeLabel(target);
194 return [238 return [
@@ -217,25 +261,57 @@ export function countReviewCommentContexts(value: string): number { · 22 unmodified lines
217export function parseReviewInlineComments(value: string): ReadonlyArray<ReviewInlineComment> {261export function parseReviewInlineComments(value: string): ReadonlyArray<ReviewInlineComment> {
218 const comments: ReviewInlineComment[] = [];262 const comments: ReviewInlineComment[] = [];
219 for (const [index, match] of Array.from(value.matchAll(REVIEW_COMMENT_BLOCK_PATTERN)).entries()) {263 for (const [index, match] of Array.from(value.matchAll(REVIEW_COMMENT_BLOCK_PATTERN)).entries()) {
220 const attributes = readReviewCommentAttributes(match[1] ?? "");264 const comment = parseReviewInlineComment(match[1] ?? "", match[2] ?? "", index);
221 const startIndex = readNonNegativeInteger(attributes.startIndex);265 if (!comment) {
222 const endIndex = readNonNegativeInteger(attributes.endIndex);
223 const filePath = attributes.filePath?.trim();
224 const sectionId = attributes.sectionId?.trim();
225 if (!filePath || !sectionId || startIndex === null || endIndex === null) {
226 continue;266 continue;
227 }267 }
228 268
229 comments.push({269 comments.push(comment);
230 id: `review-comment:${index}:${sectionId}:${filePath}:${startIndex}:${endIndex}`,
231 sectionId,
232 sectionTitle: attributes.sectionTitle?.trim() || "Review",
233 filePath,
234 startIndex: Math.min(startIndex, endIndex),
235 endIndex: Math.max(startIndex, endIndex),
236 rangeLabel: attributes.rangeLabel?.trim() || "line",
237 text: extractReviewCommentText(match[2] ?? ""),
238 });
239 }270 }
240 return comments;271 return comments;
241}272}
273
274export function parseReviewCommentMessageSegments(
275 value: string,
276): ReadonlyArray<ReviewCommentMessageSegment> {
277 const segments: ReviewCommentMessageSegment[] = [];
278 let cursor = 0;
279 let parsedCommentIndex = 0;
280
281 for (const match of value.matchAll(REVIEW_COMMENT_BLOCK_PATTERN)) {
282 const matchIndex = match.index ?? 0;
283 const beforeText = value.slice(cursor, matchIndex);
284 if (beforeText.length > 0) {
285 segments.push({
286 kind: "text",
287 id: `review-comment-text:${cursor}`,
288 text: beforeText,
289 });
290 }
291
292 const comment = parseReviewInlineComment(match[1] ?? "", match[2] ?? "", parsedCommentIndex);
293 if (comment) {
294 segments.push({ kind: "review-comment", comment });
295 parsedCommentIndex += 1;
296 } else {
297 segments.push({
298 kind: "text",
299 id: `review-comment-invalid:${matchIndex}`,
300 text: match[0],
301 });
302 }
303
304 cursor = matchIndex + match[0].length;
305 }
306
307 const rest = value.slice(cursor);
308 if (rest.length > 0) {
309 segments.push({
310 kind: "text",
311 id: `review-comment-text:${cursor}`,
312 text: rest,
313 });
314 }
315
316 return segments;
317}
apps/mobile/src/features/review/reviewModel.test.ts+16−5
@@ -3,8 +3,8 @@ import { describe, expect, it } from "vitest"; · 2 unmodified lines
3import {3import {
4 MessageId,4 MessageId,
5 TurnId,5 TurnId,
6 type GitReviewDiffSection,
7 type OrchestrationCheckpointSummary,6 type OrchestrationCheckpointSummary,
7 type ReviewDiffPreviewSource,
8} from "@t3tools/contracts";8} from "@t3tools/contracts";
9 9
10import {10import {
@@ -62,20 +62,26 @@ describe("buildReviewSectionItems", () => { · 51 unmodified lines
62 completedAt: "2026-04-02T00:00:00.000Z",62 completedAt: "2026-04-02T00:00:00.000Z",
63 }),63 }),
64 ];64 ];
65 const gitSections: GitReviewDiffSection[] = [65 const gitSections: ReviewDiffPreviewSource[] = [
66 {66 {
67 kind: "dirty",67 id: "working-tree",
68 kind: "working-tree",
68 title: "Dirty worktree",69 title: "Dirty worktree",
69 baseRef: "HEAD",70 baseRef: "HEAD",
70 headRef: null,71 headRef: null,
71 diff: "diff --git a/a.ts b/a.ts",72 diff: "diff --git a/a.ts b/a.ts",
73 diffHash: "hash-dirty",
74 truncated: false,
72 },75 },
73 {76 {
74 kind: "base",77 id: "branch-range",
78 kind: "branch-range",
75 title: "Against main",79 title: "Against main",
76 baseRef: "main",80 baseRef: "main",
77 headRef: "feature",81 headRef: "feature",
78 diff: "diff --git a/a.ts b/a.ts",82 diff: "diff --git a/a.ts b/a.ts",
83 diffHash: "hash-base",
84 truncated: false,
79 },85 },
80 ];86 ];
81 87
@@ -91,7 +97,12 @@ describe("buildReviewSectionItems", () => { · 9 unmodified lines
91 },97 },
92 });98 });
93 99
94 expect(items.map((item) => item.id)).toEqual(["turn:2", "turn:1", "git:dirty", "git:base"]);100 expect(items.map((item) => item.id)).toEqual([
101 "turn:2",
102 "turn:1",
103 "git:working-tree",
104 "git:branch-range",
105 ]);
95 expect(items[0]).toMatchObject({ isLoading: true, diff: null });106 expect(items[0]).toMatchObject({ isLoading: true, diff: null });
96 expect(items[1]).toMatchObject({107 expect(items[1]).toMatchObject({
97 isLoading: false,108 isLoading: false,
apps/mobile/src/features/review/reviewModel.ts+5−5
@@ -1,9 +1,9 @@
1import { parsePatchFiles, type ChangeTypes, type FileDiffMetadata } from "@pierre/diffs/utils";1import { parsePatchFiles, type ChangeTypes, type FileDiffMetadata } from "@pierre/diffs/utils";
2import type { GitReviewDiffSection, OrchestrationCheckpointSummary } from "@t3tools/contracts";2import type { OrchestrationCheckpointSummary, ReviewDiffPreviewSource } from "@t3tools/contracts";
3import * as Arr from "effect/Array";3import * as Arr from "effect/Array";
4import * as Order from "effect/Order";4import * as Order from "effect/Order";
5 5
6export type ReviewSectionKind = "turn" | "dirty" | "base";6export type ReviewSectionKind = "turn" | "working-tree" | "branch-range";
7 7
8export interface ReviewSectionItem {8export interface ReviewSectionItem {
9 readonly id: string;9 readonly id: string;
@@ -149,8 +149,8 @@ const readyCheckpointOrder = Order.make<OrchestrationCheckpointSummary>( · 139 unmodified lines
149 compareCheckpointTurnCountDescending,149 compareCheckpointTurnCountDescending,
150);150);
151 151
152function gitSubtitle(section: GitReviewDiffSection): string | null {152function gitSubtitle(section: ReviewDiffPreviewSource): string | null {
153 if (section.kind === "dirty") {153 if (section.kind === "working-tree") {
154 return "Tracked, staged, and untracked worktree changes";154 return "Tracked, staged, and untracked worktree changes";
155 }155 }
156 if (section.baseRef) {156 if (section.baseRef) {
@@ -520,7 +520,7 @@ export function getReadyReviewCheckpoints( · 363 unmodified lines
520 520
521export function buildReviewSectionItems(input: {521export function buildReviewSectionItems(input: {
522 readonly checkpoints: ReadonlyArray<OrchestrationCheckpointSummary>;522 readonly checkpoints: ReadonlyArray<OrchestrationCheckpointSummary>;
523 readonly gitSections: ReadonlyArray<GitReviewDiffSection>;523 readonly gitSections: ReadonlyArray<ReviewDiffPreviewSource>;
524 readonly turnDiffById: Readonly<Record<string, string | undefined>>;524 readonly turnDiffById: Readonly<Record<string, string | undefined>>;
525 readonly loadingTurnIds: Readonly<Record<string, boolean | undefined>>;525 readonly loadingTurnIds: Readonly<Record<string, boolean | undefined>>;
526}): ReadonlyArray<ReviewSectionItem> {526}): ReadonlyArray<ReviewSectionItem> {
apps/mobile/src/features/review/reviewState.ts+3−3
@@ -1,13 +1,13 @@
1import { useAtomValue } from "@effect/atom-react";1import { useAtomValue } from "@effect/atom-react";
2 2
3import type { EnvironmentId, GitReviewDiffSection, ThreadId } from "@t3tools/contracts";3import type { EnvironmentId, ReviewDiffPreviewSource, ThreadId } from "@t3tools/contracts";
4import { Atom } from "effect/unstable/reactivity";4import { Atom } from "effect/unstable/reactivity";
5 5
6import { scopedThreadKey } from "../../lib/scopedEntities";6import { scopedThreadKey } from "../../lib/scopedEntities";
7import { appAtomRegistry } from "../../state/atom-registry";7import { appAtomRegistry } from "../../state/atom-registry";
8import { buildReviewParsedDiff, type ReviewParsedDiff } from "./reviewModel";8import { buildReviewParsedDiff, type ReviewParsedDiff } from "./reviewModel";
9 9
10const EMPTY_GIT_REVIEW_SECTIONS = Object.freeze<ReadonlyArray<GitReviewDiffSection>>([]);10const EMPTY_GIT_REVIEW_SECTIONS = Object.freeze<ReadonlyArray<ReviewDiffPreviewSource>>([]);
11const EMPTY_REVIEW_TURN_DIFFS = Object.freeze<Readonly<Record<string, string>>>({});11const EMPTY_REVIEW_TURN_DIFFS = Object.freeze<Readonly<Record<string, string>>>({});
12const EMPTY_REVIEW_SECTION_FILE_IDS = Object.freeze<12const EMPTY_REVIEW_SECTION_FILE_IDS = Object.freeze<
13 Readonly<Record<string, ReadonlyArray<string> | undefined>>13 Readonly<Record<string, ReadonlyArray<string> | undefined>>
@@ -134,7 +134,7 @@ export function useReviewCacheForThread(input: { · 120 unmodified lines
134 134
135export function setReviewGitSections(135export function setReviewGitSections(
136 threadKey: string,136 threadKey: string,
137 sections: ReadonlyArray<GitReviewDiffSection>,137 sections: ReadonlyArray<ReviewDiffPreviewSource>,
138): void {138): void {
139 appAtomRegistry.set(reviewGitSectionsByThreadKeyAtom(threadKey), sections);139 appAtomRegistry.set(reviewGitSectionsByThreadKeyAtom(threadKey), sections);
140}140}
apps/mobile/src/features/threads/ThreadComposer.tsx+7−0
@@ -62,6 +62,13 @@ export const COMPOSER_COLLAPSED_CHROME = 68; · 61 unmodified lines
62 */62 */
63export const COMPOSER_EXPANDED_CHROME = 174;63export const COMPOSER_EXPANDED_CHROME = 174;
64 64
65/**
66 * Height of the expanded-only toolbar below the text surface.
67 * Used by the feed inset because KeyboardAvoidingLegendList only accounts for
68 * keyboard height; the floating toolbar remains an additional overlay.
69 */
70export const COMPOSER_EXPANDED_TOOLBAR_CHROME = 54;
71
65function withModelSelectionOption(72function withModelSelectionOption(
66 selection: ModelSelection,73 selection: ModelSelection,
67 id: string,74 id: string,
apps/mobile/src/features/threads/ThreadDetailScreen.tsx+4−1
@@ -33,6 +33,7 @@ import { PendingUserInputCard } from "./PendingUserInputCard"; · 32 unmodified lines
33import {33import {
34 COMPOSER_COLLAPSED_CHROME,34 COMPOSER_COLLAPSED_CHROME,
35 COMPOSER_EXPANDED_CHROME,35 COMPOSER_EXPANDED_CHROME,
36 COMPOSER_EXPANDED_TOOLBAR_CHROME,
36 ThreadComposer,37 ThreadComposer,
37} from "./ThreadComposer";38} from "./ThreadComposer";
38import { ThreadFeed } from "./ThreadFeed";39import { ThreadFeed } from "./ThreadFeed";
@@ -220,7 +221,9 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread · 181 unmodified lines
220 const layoutVariant = props.layoutVariant ?? "compact";221 const layoutVariant = props.layoutVariant ?? "compact";
221 const isSplitLayout = layoutVariant === "split";222 const isSplitLayout = layoutVariant === "split";
222 useStreamingHaptics(props.selectedThread.id, props.selectedThreadFeed);223 useStreamingHaptics(props.selectedThread.id, props.selectedThreadFeed);
223 const feedBottomInset = Math.max(estimatedOverlayHeight, measuredOverlayHeight) + 8;224 const expandedToolbarInset = composerExpanded ? COMPOSER_EXPANDED_TOOLBAR_CHROME : 0;
225 const feedBottomInset =
226 Math.max(estimatedOverlayHeight, measuredOverlayHeight) + expandedToolbarInset + 8;
224 227
225 const completeDrawerGesture = useCallback(() => {228 const completeDrawerGesture = useCallback(() => {
226 void Haptics.selectionAsync();229 void Haptics.selectionAsync();
apps/mobile/src/features/threads/ThreadFeed.tsx+298−34
@@ -15,8 +15,11 @@ import { · 14 unmodified lines
15 Image,15 Image,
16 Pressable,16 Pressable,
17 ScrollView,17 ScrollView,
18 StyleSheet,
18 Text as NativeText,19 Text as NativeText,
19 type ColorValue,20 type ColorValue,
21 useColorScheme,
22 useWindowDimensions,
20 View,23 View,
21} from "react-native";24} from "react-native";
22import { TouchableOpacity } from "react-native-gesture-handler";25import { TouchableOpacity } from "react-native-gesture-handler";
@@ -26,6 +29,19 @@ import { useThemeColor } from "../../lib/useThemeColor"; · 3 unmodified lines
26 29
27import { AppText as Text } from "../../components/AppText";30import { AppText as Text } from "../../components/AppText";
28import { EmptyState } from "../../components/EmptyState";31import { EmptyState } from "../../components/EmptyState";
32import {
33 parseReviewCommentMessageSegments,
34 type ReviewInlineComment,
35} from "../review/reviewCommentSelection";
36import { resolveNativeReviewDiffView } from "../diffs/nativeReviewDiffSurface";
37import {
38 buildNativeReviewDiffData,
39 createNativeReviewDiffTheme,
40 NATIVE_REVIEW_DIFF_CONTENT_WIDTH,
41 NATIVE_REVIEW_DIFF_ROW_HEIGHT,
42 NATIVE_REVIEW_DIFF_STYLE,
43} from "../review/nativeReviewDiffAdapter";
44import { buildReviewParsedDiff } from "../review/reviewModel";
29import { cn } from "../../lib/cn";45import { cn } from "../../lib/cn";
30import type { MobileLayoutVariant } from "../../lib/mobileLayout";46import type { MobileLayoutVariant } from "../../lib/mobileLayout";
31import type { ThreadFeedEntry } from "../../lib/threadActivity";47import type { ThreadFeedEntry } from "../../lib/threadActivity";
@@ -101,6 +117,38 @@ interface MarkdownStyleSet { · 69 unmodified lines
101 readonly renderers: CustomRenderers;117 readonly renderers: CustomRenderers;
102}118}
103 119
120interface ReviewCommentColors {
121 readonly background: ColorValue;
122 readonly border: ColorValue;
123 readonly mutedBackground: ColorValue;
124 readonly text: ColorValue;
125 readonly mutedText: ColorValue;
126 readonly codeBackground: ColorValue;
127}
128
129function useReviewCommentColors(): ReviewCommentColors {
130 const colorScheme = useColorScheme();
131 const isDark = colorScheme === "dark";
132 const background = isDark ? "#151515" : "#ffffff";
133 const border = isDark ? "#2a2a2a" : "#d7d7d7";
134 const mutedBackground = isDark ? "#242424" : "#f2f2f2";
135 const text = isDark ? "#f3f3f3" : "#111111";
136 const mutedText = isDark ? "#8f8f8f" : "#666666";
137 const codeBackground = isDark ? "#0f0f0f" : "#ffffff";
138
139 return useMemo(
140 () => ({
141 background,
142 border,
143 mutedBackground,
144 text,
145 mutedText,
146 codeBackground,
147 }),
148 [background, border, codeBackground, mutedBackground, mutedText, text],
149 );
150}
151
104function useMarkdownStyles(): MarkdownStyleSets {152function useMarkdownStyles(): MarkdownStyleSets {
105 const bodyColor = useThemeColor("--color-md-body");153 const bodyColor = useThemeColor("--color-md-body");
106 const strongColor = useThemeColor("--color-md-strong");154 const strongColor = useThemeColor("--color-md-strong");
@@ -357,6 +405,8 @@ function renderFeedEntry( · 250 unmodified lines
357 readonly iconSubtleColor: string | import("react-native").ColorValue;405 readonly iconSubtleColor: string | import("react-native").ColorValue;
358 readonly userBubbleColor: string | import("react-native").ColorValue;406 readonly userBubbleColor: string | import("react-native").ColorValue;
359 readonly markdownStyles: MarkdownStyleSets;407 readonly markdownStyles: MarkdownStyleSets;
408 readonly reviewCommentColors: ReviewCommentColors;
409 readonly reviewCommentBubbleWidth: number;
360 },410 },
361) {411) {
362 const entry = info.item;412 const entry = info.item;
@@ -368,23 +418,24 @@ function renderFeedEntry( · 5 unmodified lines
368 const styles = isUser ? markdownStyles.user : markdownStyles.assistant;418 const styles = isUser ? markdownStyles.user : markdownStyles.assistant;
369 const timestampLabel = `${relativeTime(message.createdAt)}${message.streaming ? " • live" : ""}`;419 const timestampLabel = `${relativeTime(message.createdAt)}${message.streaming ? " • live" : ""}`;
370 const attachments = message.attachments ?? [];420 const attachments = message.attachments ?? [];
421 const hasReviewCommentContext = message.text.includes("<review_comment");
371 422
372 if (isUser) {423 if (isUser) {
373 return (424 return (
374 <View className="mb-3.5 items-end gap-1.5">425 <View className="mb-5 items-end">
375 <View426 <View
376 className="max-w-[85%] gap-2 rounded-[22px] rounded-br-[6px] px-3.5 py-2.5"427 className="max-w-[85%] gap-2 rounded-[22px] rounded-br-[6px] px-3.5 py-2.5"
377 style={{ backgroundColor: userBubbleColor }}428 style={{
429 backgroundColor: userBubbleColor,
430 ...(hasReviewCommentContext ? { width: props.reviewCommentBubbleWidth } : null),
431 }}
378 >432 >
379 {message.text.trim().length > 0 ? (433 {message.text.trim().length > 0 ? (
380 <Markdown434 <UserMessageContent
381 options={{ gfm: true }}435 text={message.text}
382 renderers={styles.renderers}436 markdownStyles={styles}
383 styles={styles.styles}437 reviewCommentColors={props.reviewCommentColors}
384 theme={styles.theme}438 />
385 >
386 {message.text}
387 </Markdown>
388 ) : null}439 ) : null}
389 {attachments.map((attachment) => {440 {attachments.map((attachment) => {
390 const uri = messageImageUrl(props.httpBaseUrl, attachment.id);441 const uri = messageImageUrl(props.httpBaseUrl, attachment.id);
@@ -410,7 +461,7 @@ function renderFeedEntry( · 19 unmodified lines
410 );461 );
411 })}462 })}
412 </View>463 </View>
413 <Text className="px-1 text-right font-t3-medium text-xs text-neutral-600 dark:text-neutral-400">464 <Text className="mt-1.5 px-1 text-right font-t3-medium text-xs text-neutral-600 dark:text-neutral-400">
414 {timestampLabel}465 {timestampLabel}
415 </Text>466 </Text>
416 </View>467 </View>
@@ -424,7 +475,7 @@ function renderFeedEntry( · 7 unmodified lines
424 }475 }
425 476
426 return (477 return (
427 <View className="mb-3.5 gap-1.5 px-1">478 <View className="mb-5 px-1">
428 {message.text.trim().length > 0 ? (479 {message.text.trim().length > 0 ? (
429 <Markdown480 <Markdown
430 options={{ gfm: true }}481 options={{ gfm: true }}
@@ -448,6 +499,7 @@ function renderFeedEntry( · 17 unmodified lines
448 <TouchableOpacity499 <TouchableOpacity
449 key={attachment.id}500 key={attachment.id}
450 activeOpacity={0.7}501 activeOpacity={0.7}
502 className="mt-1.5"
451 onPress={() => props.onPressImage(uri, headers)}503 onPress={() => props.onPressImage(uri, headers)}
452 >504 >
453 <Image505 <Image
@@ -458,7 +510,7 @@ function renderFeedEntry( · 4 unmodified lines
458 </TouchableOpacity>510 </TouchableOpacity>
459 );511 );
460 })}512 })}
461 <Text className="font-t3-medium text-xs text-neutral-600 dark:text-neutral-400">513 <Text className="mt-1.5 font-t3-medium text-xs text-neutral-600 dark:text-neutral-400">
462 {timestampLabel}514 {timestampLabel}
463 </Text>515 </Text>
464 </View>516 </View>
@@ -467,7 +519,7 @@ function renderFeedEntry( · 2 unmodified lines
467 519
468 if (entry.type === "queued-message") {520 if (entry.type === "queued-message") {
469 return (521 return (
470 <View className="mb-3.5 gap-1.5 items-end">522 <View className="mb-5 items-end">
471 <View523 <View
472 className="max-w-[85%] gap-2 rounded-[22px] rounded-br-[6px] px-3.5 py-2.5 opacity-60"524 className="max-w-[85%] gap-2 rounded-[22px] rounded-br-[6px] px-3.5 py-2.5 opacity-60"
473 style={{ backgroundColor: userBubbleColor }}525 style={{ backgroundColor: userBubbleColor }}
@@ -482,7 +534,7 @@ function renderFeedEntry( · 8 unmodified lines
482 </Text>534 </Text>
483 ) : null}535 ) : null}
484 </View>536 </View>
485 <Text className="px-1 text-right font-t3-medium text-xs text-neutral-600 dark:text-neutral-400">537 <Text className="mt-1.5 px-1 text-right font-t3-medium text-xs text-neutral-600 dark:text-neutral-400">
486 {entry.sending ? "dispatching" : `${relativeTime(entry.createdAt)} • pending`}538 {entry.sending ? "dispatching" : `${relativeTime(entry.createdAt)} • pending`}
487 </Text>539 </Text>
488 </View>540 </View>
@@ -555,11 +607,226 @@ function renderFeedEntry( · 66 unmodified lines
555 );607 );
556}608}
557 609
610function UserMessageContent(props: {
611 readonly text: string;
612 readonly markdownStyles: MarkdownStyleSet;
613 readonly reviewCommentColors: ReviewCommentColors;
614}) {
615 const segments = parseReviewCommentMessageSegments(props.text);
616 const hasReviewComment = segments.some((segment) => segment.kind === "review-comment");
617 if (!hasReviewComment) {
618 return (
619 <Markdown
620 options={{ gfm: true }}
621 renderers={props.markdownStyles.renderers}
622 styles={props.markdownStyles.styles}
623 theme={props.markdownStyles.theme}
624 >
625 {props.text}
626 </Markdown>
627 );
628 }
629
630 return (
631 <View className="w-full gap-2">
632 {segments.map((segment) => {
633 if (segment.kind === "review-comment") {
634 return (
635 <ReviewCommentCard
636 key={segment.comment.id}
637 comment={segment.comment}
638 colors={props.reviewCommentColors}
639 />
640 );
641 }
642
643 const text = segment.text.trim();
644 if (text.length === 0) {
645 return null;
646 }
647
648 return (
649 <Markdown
650 key={segment.id}
651 options={{ gfm: true }}
652 renderers={props.markdownStyles.renderers}
653 styles={props.markdownStyles.styles}
654 theme={props.markdownStyles.theme}
655 >
656 {text}
657 </Markdown>
658 );
659 })}
660 </View>
661 );
662}
663
664const ReviewCommentCard = memo(function ReviewCommentCard(props: {
665 readonly comment: ReviewInlineComment;
666 readonly colors: ReviewCommentColors;
667}) {
668 const colorScheme = useColorScheme();
669 const appearanceScheme = colorScheme === "light" ? "light" : "dark";
670 const NativeReviewDiffView = resolveNativeReviewDiffView();
671 const patch = useMemo(() => buildReviewCommentPatch(props.comment), [props.comment]);
672 const parsedDiff = useMemo(
673 () => buildReviewParsedDiff(patch, `thread-review-comment:${props.comment.id}`),
674 [patch, props.comment.id],
675 );
676 const nativeReviewDiffData = useMemo(() => buildNativeReviewDiffData(parsedDiff), [parsedDiff]);
677 const compactNativeRows = useMemo(
678 () => nativeReviewDiffData.rows.filter((row) => row.kind !== "file"),
679 [nativeReviewDiffData.rows],
680 );
681 const nativeReviewDiffTheme = useMemo(
682 () => createNativeReviewDiffTheme(appearanceScheme),
683 [appearanceScheme],
684 );
685 const nativeRowsJson = useMemo(() => JSON.stringify(compactNativeRows), [compactNativeRows]);
686 const nativeThemeJson = useMemo(
687 () => JSON.stringify(nativeReviewDiffTheme),
688 [nativeReviewDiffTheme],
689 );
690 const nativeStyleJson = useMemo(() => JSON.stringify(NATIVE_REVIEW_DIFF_STYLE), []);
691 const nativeDiffHeight = useMemo(
692 () =>
693 Math.min(
694 360,
695 Math.max(
696 112,
697 compactNativeRows.length * NATIVE_REVIEW_DIFF_ROW_HEIGHT +
698 NATIVE_REVIEW_DIFF_STYLE.fileHeaderVerticalMargin,
699 ),
700 ),
701 [compactNativeRows.length],
702 );
703 const shouldRenderNativeDiff = NativeReviewDiffView != null && compactNativeRows.length > 0;
704
705 return (
706 <View
707 className="w-full overflow-hidden rounded-[16px] border"
708 style={{
709 backgroundColor: props.colors.background,
710 borderColor: props.colors.border,
711 borderCurve: "continuous",
712 }}
713 >
714 <View
715 className="flex-row items-center gap-2 border-b px-3 py-2"
716 style={{ borderColor: props.colors.border }}
717 >
718 <View
719 className="size-6 items-center justify-center rounded-[7px]"
720 style={{ backgroundColor: props.colors.mutedBackground, borderCurve: "continuous" }}
721 >
722 <SymbolView
723 name="doc.text"
724 size={13}
725 tintColor={props.colors.mutedText}
726 type="monochrome"
727 />
728 </View>
729 <View className="min-w-0 flex-1">
730 <Text
731 className="font-mono text-[12px] leading-[16px]"
732 numberOfLines={1}
733 style={{ color: props.colors.text }}
734 >
735 {compactFileName(props.comment.filePath)}
736 </Text>
737 </View>
738 </View>
739 {shouldRenderNativeDiff ? (
740 <View
741 className="border-t"
742 collapsable={false}
743 style={{
744 backgroundColor: nativeReviewDiffTheme.background,
745 borderColor: props.colors.border,
746 height: nativeDiffHeight,
747 }}
748 >
749 <NativeReviewDiffView
750 collapsable={false}
751 style={StyleSheet.absoluteFillObject}
752 appearanceScheme={appearanceScheme}
753 contentWidth={NATIVE_REVIEW_DIFF_CONTENT_WIDTH}
754 rowHeight={NATIVE_REVIEW_DIFF_ROW_HEIGHT}
755 rowsJson={nativeRowsJson}
756 styleJson={nativeStyleJson}
757 themeJson={nativeThemeJson}
758 />
759 </View>
760 ) : props.comment.diff.trim().length > 0 ? (
761 <ScrollView
762 horizontal
763 nestedScrollEnabled
764 directionalLockEnabled
765 showsHorizontalScrollIndicator={false}
766 bounces={false}
767 className="border-t"
768 style={{ backgroundColor: props.colors.codeBackground, borderColor: props.colors.border }}
769 contentContainerStyle={{ padding: 10 }}
770 >
771 <NativeText
772 selectable
773 style={{
774 color: props.colors.text,
775 fontFamily: "ui-monospace",
776 fontSize: 12,
777 lineHeight: 18,
778 }}
779 >
780 {props.comment.diff.trim()}
781 </NativeText>
782 </ScrollView>
783 ) : null}
784 {props.comment.text.length > 0 ? (
785 <View className="border-t px-3 py-3" style={{ borderColor: props.colors.border }}>
786 <Text
787 selectable
788 className="text-[15px] leading-[21px]"
789 style={{ color: props.colors.text }}
790 >
791 {props.comment.text}
792 </Text>
793 </View>
794 ) : null}
795 </View>
796 );
797});
798
799function buildReviewCommentPatch(comment: ReviewInlineComment): string {
800 const diff = comment.diff.trim();
801 if (!diff) {
802 return "";
803 }
804
805 if (diff.startsWith("diff --git ")) {
806 return diff;
807 }
808
809 const normalizedPath = comment.filePath.replaceAll("\\", "/");
810 return [
811 `diff --git a/${normalizedPath} b/${normalizedPath}`,
812 `--- a/${normalizedPath}`,
813 `+++ b/${normalizedPath}`,
814 diff,
815 ].join("\n");
816}
817
818function compactFileName(filePath: string): string {
819 const normalized = filePath.replaceAll("\\", "/");
820 const lastSlashIndex = normalized.lastIndexOf("/");
821 return lastSlashIndex >= 0 ? normalized.slice(lastSlashIndex + 1) : normalized;
822}
823
558const IOS_NAV_BAR_HEIGHT = 44;824const IOS_NAV_BAR_HEIGHT = 44;
559 825
560export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {826export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
561 const listRef = useRef<LegendListRef>(null);827 const listRef = useRef<LegendListRef>(null);
562 const copyFeedbackTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);828 const copyFeedbackTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
829 const { width: viewportWidth } = useWindowDimensions();
563 const [copiedRowId, setCopiedRowId] = useState<string | null>(null);830 const [copiedRowId, setCopiedRowId] = useState<string | null>(null);
564 const [expandedWorkGroups, setExpandedWorkGroups] = useState<Record<string, boolean>>({});831 const [expandedWorkGroups, setExpandedWorkGroups] = useState<Record<string, boolean>>({});
565 const [expandedImage, setExpandedImage] = useState<{832 const [expandedImage, setExpandedImage] = useState<{
@@ -567,30 +834,22 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { · 1 unmodified line
567 headers?: Record<string, string>;834 headers?: Record<string, string>;
568 } | null>(null);835 } | null>(null);
569 const horizontalPadding = props.layoutVariant === "split" ? 20 : 16;836 const horizontalPadding = props.layoutVariant === "split" ? 20 : 16;
837 const contentWidth = Math.max(0, viewportWidth - horizontalPadding * 2);
838 const reviewCommentBubbleWidth = Math.min(Math.max(280, contentWidth * 0.85), contentWidth);
570 const insets = useSafeAreaInsets();839 const insets = useSafeAreaInsets();
571 const topContentInset = insets.top + IOS_NAV_BAR_HEIGHT;840 const topContentInset = insets.top + IOS_NAV_BAR_HEIGHT;
841 const bottomContentInset = props.contentBottomInset ?? 18;
572 842
573 const iconSubtleColor = useThemeColor("--color-icon-subtle");843 const iconSubtleColor = useThemeColor("--color-icon-subtle");
574 const userBubbleColor = useThemeColor("--color-user-bubble");844 const userBubbleColor = useThemeColor("--color-user-bubble");
575 const markdownStyles = useMarkdownStyles();845 const markdownStyles = useMarkdownStyles();
846 const reviewCommentColors = useReviewCommentColors();
576 847
577 useEffect(() => {848 useEffect(() => {
578 setCopiedRowId(null);849 setCopiedRowId(null);
579 setExpandedWorkGroups({});850 setExpandedWorkGroups({});
580 }, [props.threadId]);851 }, [props.threadId]);
581 852
582 // Scroll to end when the composer expands (keyboard opens) so the latest
583 // message stays visible above the taller composer + keyboard.
584 useEffect(() => {
585 if (props.composerExpanded && props.feed.length > 0) {
586 // Small delay to let KAV + layout settle before scrolling
587 const timer = setTimeout(() => {
588 void listRef.current?.scrollToEnd({ animated: true });
589 }, 100);
590 return () => clearTimeout(timer);
591 }
592 }, [props.composerExpanded, props.feed.length]);
593
594 useEffect(() => {853 useEffect(() => {
595 return () => {854 return () => {
596 if (copyFeedbackTimeoutRef.current) {855 if (copyFeedbackTimeoutRef.current) {
@@ -636,6 +895,8 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { · 39 unmodified lines
636 iconSubtleColor,895 iconSubtleColor,
637 userBubbleColor,896 userBubbleColor,
638 markdownStyles,897 markdownStyles,
898 reviewCommentColors,
899 reviewCommentBubbleWidth,
639 }),900 }),
640 [901 [
641 copiedRowId,902 copiedRowId,
@@ -643,6 +904,8 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { · 1 unmodified line
643 iconSubtleColor,904 iconSubtleColor,
644 userBubbleColor,905 userBubbleColor,
645 markdownStyles,906 markdownStyles,
907 reviewCommentColors,
908 reviewCommentBubbleWidth,
646 onCopyWorkRow,909 onCopyWorkRow,
647 onPressImage,910 onPressImage,
648 onToggleWorkGroup,911 onToggleWorkGroup,
@@ -656,13 +919,12 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { · 7 unmodified lines
656 <ScrollView919 <ScrollView
657 style={{ flex: 1 }}920 style={{ flex: 1 }}
658 contentInsetAdjustmentBehavior="never"921 contentInsetAdjustmentBehavior="never"
659 contentInset={{ top: topContentInset }}922 contentInset={{ top: topContentInset, bottom: bottomContentInset }}
660 contentOffset={{ x: 0, y: -topContentInset }}923 contentOffset={{ x: 0, y: -topContentInset }}
661 scrollIndicatorInsets={{ top: topContentInset }}924 scrollIndicatorInsets={{ top: topContentInset, bottom: bottomContentInset }}
662 contentContainerStyle={{925 contentContainerStyle={{
663 flexGrow: 1,926 flexGrow: 1,
664 paddingHorizontal: horizontalPadding,927 paddingHorizontal: horizontalPadding,
665 paddingBottom: props.contentBottomInset ?? 18,
666 }}928 }}
667 >929 >
668 <EmptyState930 <EmptyState
@@ -681,13 +943,16 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { · 12 unmodified lines
681 style={{ flex: 1 }}943 style={{ flex: 1 }}
682 alignItemsAtEnd944 alignItemsAtEnd
683 contentInsetAdjustmentBehavior="never"945 contentInsetAdjustmentBehavior="never"
684 contentInset={{ top: topContentInset }}946 contentInset={{ top: topContentInset, bottom: bottomContentInset }}
685 scrollIndicatorInsets={{ top: topContentInset }}947 scrollIndicatorInsets={{ top: topContentInset, bottom: bottomContentInset }}
686 data={props.feed as ThreadFeedEntry[]}948 data={props.feed as ThreadFeedEntry[]}
687 renderItem={renderItem}949 renderItem={renderItem}
688 keyExtractor={(entry) => `${entry.type}:${entry.id}`}950 keyExtractor={(entry) => `${entry.type}:${entry.id}`}
951 getItemType={(entry) =>
952 entry.type === "message" ? `message:${entry.message.role}` : entry.type
953 }
689 keyboardShouldPersistTaps="handled"954 keyboardShouldPersistTaps="handled"
690 estimatedItemSize={80}955 estimatedItemSize={180}
691 initialScrollAtEnd956 initialScrollAtEnd
692 maintainScrollAtEnd={{957 maintainScrollAtEnd={{
693 on: { layout: true, itemLayout: true, dataChange: true },958 on: { layout: true, itemLayout: true, dataChange: true },
@@ -699,7 +964,6 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { · 5 unmodified lines
699 contentContainerStyle={{964 contentContainerStyle={{
700 paddingTop: 12,965 paddingTop: 12,
701 paddingHorizontal: horizontalPadding,966 paddingHorizontal: horizontalPadding,
702 paddingBottom: props.contentBottomInset ?? 18,
703 }}967 }}
704 />968 />
705 969
apps/server/src/git/GitWorkflowService.ts+0−9
@@ -15,8 +15,6 @@ import { · 14 unmodified lines
15 type GitPreparePullRequestThreadInput,15 type GitPreparePullRequestThreadInput,
16 type GitPreparePullRequestThreadResult,16 type GitPreparePullRequestThreadResult,
17 type GitPullRequestRefInput,17 type GitPullRequestRefInput,
18 type GitReviewDiffsInput,
19 type GitReviewDiffsResult,
20 type VcsPullResult,18 type VcsPullResult,
21 type VcsRemoveWorktreeInput,19 type VcsRemoveWorktreeInput,
22 type GitResolvePullRequestResult,20 type GitResolvePullRequestResult,
@@ -56,9 +54,6 @@ export interface GitWorkflowServiceShape { · 33 unmodified lines
56 readonly preparePullRequestThread: (54 readonly preparePullRequestThread: (
57 input: GitPreparePullRequestThreadInput,55 input: GitPreparePullRequestThreadInput,
58 ) => Effect.Effect<GitPreparePullRequestThreadResult, GitManagerServiceError>;56 ) => Effect.Effect<GitPreparePullRequestThreadResult, GitManagerServiceError>;
59 readonly getReviewDiffs: (
60 input: GitReviewDiffsInput,
61 ) => Effect.Effect<GitReviewDiffsResult, GitCommandError>;
62 readonly listRefs: (input: VcsListRefsInput) => Effect.Effect<VcsListRefsResult, GitCommandError>;57 readonly listRefs: (input: VcsListRefsInput) => Effect.Effect<VcsListRefsResult, GitCommandError>;
63 readonly createWorktree: (58 readonly createWorktree: (
64 input: VcsCreateWorktreeInput,59 input: VcsCreateWorktreeInput,
@@ -287,10 +282,6 @@ export const make = Effect.fn("makeGitWorkflowService")(function* () { · 222 unmodified lines
287 "GitWorkflowService.preparePullRequestThread",282 "GitWorkflowService.preparePullRequestThread",
288 gitManager.preparePullRequestThread,283 gitManager.preparePullRequestThread,
289 ),284 ),
290 getReviewDiffs: (input) =>
291 ensureGitCommand("GitWorkflowService.getReviewDiffs", input.cwd).pipe(
292 Effect.andThen(git.getReviewDiffs(input)),
293 ),
294 listRefs: (input) =>285 listRefs: (input) =>
295 detectGitRepositoryForCommand("GitWorkflowService.listRefs", input.cwd).pipe(286 detectGitRepositoryForCommand("GitWorkflowService.listRefs", input.cwd).pipe(
296 Effect.flatMap((isGitRepository) =>287 Effect.flatMap((isGitRepository) =>
apps/server/src/review/ReviewService.ts+63−0
@@ -0,0 +1,63 @@
1import { Context, Effect, Layer } from "effect";
2
3import {
4 VcsUnsupportedOperationError,
5 type ReviewDiffPreviewError,
6 type ReviewDiffPreviewInput,
7 type ReviewDiffPreviewResult,
8} from "@t3tools/contracts";
9
10import { GitVcsDriver } from "../vcs/GitVcsDriver.ts";
11import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";
12
13export interface ReviewServiceShape {
14 readonly getDiffPreview: (
15 input: ReviewDiffPreviewInput,
16 ) => Effect.Effect<ReviewDiffPreviewResult, ReviewDiffPreviewError>;
17}
18
19export class ReviewService extends Context.Service<ReviewService, ReviewServiceShape>()(
20 "t3/review/ReviewService",
21) {}
22
23function emptyDiffPreview(input: ReviewDiffPreviewInput): ReviewDiffPreviewResult {
24 return {
25 cwd: input.cwd,
26 generatedAt: new Date().toISOString(),
27 sources: [],
28 };
29}
30
31export const make = Effect.fn("makeReviewService")(function* () {
32 const vcsRegistry = yield* VcsDriverRegistry.VcsDriverRegistry;
33 const git = yield* GitVcsDriver;
34
35 const getDiffPreview: ReviewServiceShape["getDiffPreview"] = Effect.fn(
36 "ReviewService.getDiffPreview",
37 )(function* (input) {
38 const handle = yield* vcsRegistry.detect({ cwd: input.cwd, requestedKind: "auto" });
39 if (!handle) {
40 return emptyDiffPreview(input);
41 }
42
43 const getDriverDiffPreview = handle.driver.getDiffPreview;
44 if (!getDriverDiffPreview) {
45 if (handle.kind === "git") {
46 return yield* git.getReviewDiffPreview(input);
47 }
48 return yield* new VcsUnsupportedOperationError({
49 operation: "ReviewService.getDiffPreview",
50 kind: handle.kind,
51 detail: `The ${handle.kind} VCS driver does not support review diff previews.`,
52 });
53 }
54
55 return yield* getDriverDiffPreview(input);
56 });
57
58 return ReviewService.of({
59 getDiffPreview,
60 });
61});
62
63export const layer = Layer.effect(ReviewService, make());
apps/server/src/server.test.ts+27−10
@@ -110,6 +110,7 @@ import * as VcsStatusBroadcaster from "./vcs/VcsStatusBroadcaster.ts"; · 109 unmodified lines
110import * as VcsDriverRegistry from "./vcs/VcsDriverRegistry.ts";110import * as VcsDriverRegistry from "./vcs/VcsDriverRegistry.ts";
111import * as VcsProvisioningService from "./vcs/VcsProvisioningService.ts";111import * as VcsProvisioningService from "./vcs/VcsProvisioningService.ts";
112import * as GitWorkflowService from "./git/GitWorkflowService.ts";112import * as GitWorkflowService from "./git/GitWorkflowService.ts";
113import * as ReviewService from "./review/ReviewService.ts";
113import * as SourceControlRepositoryService from "./sourceControl/SourceControlRepositoryService.ts";114import * as SourceControlRepositoryService from "./sourceControl/SourceControlRepositoryService.ts";
114import { ServerSecretStoreLive } from "./auth/Layers/ServerSecretStore.ts";115import { ServerSecretStoreLive } from "./auth/Layers/ServerSecretStore.ts";
115import { ServerAuthLive } from "./auth/Layers/ServerAuth.ts";116import { ServerAuthLive } from "./auth/Layers/ServerAuth.ts";
@@ -323,6 +324,7 @@ const buildAppUnderTest = (options?: { · 207 unmodified lines
323 gitVcsDriver?: Partial<GitVcsDriver.GitVcsDriverShape>;324 gitVcsDriver?: Partial<GitVcsDriver.GitVcsDriverShape>;
324 gitManager?: Partial<GitManagerShape>;325 gitManager?: Partial<GitManagerShape>;
325 sourceControlRepositoryService?: Partial<SourceControlRepositoryService.SourceControlRepositoryServiceShape>;326 sourceControlRepositoryService?: Partial<SourceControlRepositoryService.SourceControlRepositoryServiceShape>;
327 reviewService?: Partial<ReviewService.ReviewServiceShape>;
326 vcsStatusBroadcaster?: Partial<VcsStatusBroadcaster.VcsStatusBroadcasterShape>;328 vcsStatusBroadcaster?: Partial<VcsStatusBroadcaster.VcsStatusBroadcasterShape>;
327 projectSetupScriptRunner?: Partial<ProjectSetupScriptRunnerShape>;329 projectSetupScriptRunner?: Partial<ProjectSetupScriptRunnerShape>;
328 terminalManager?: Partial<TerminalManagerShape>;330 terminalManager?: Partial<TerminalManagerShape>;
@@ -493,6 +495,14 @@ const buildAppUnderTest = (options?: { · 164 unmodified lines
493 const vcsProvisioningLayer = VcsProvisioningService.layer.pipe(495 const vcsProvisioningLayer = VcsProvisioningService.layer.pipe(
494 Layer.provide(vcsDriverRegistryLayer),496 Layer.provide(vcsDriverRegistryLayer),
495 );497 );
498 const reviewLayer = options?.layers?.reviewService
499 ? Layer.mock(ReviewService.ReviewService)({
500 ...options.layers.reviewService,
501 })
502 : ReviewService.layer.pipe(
503 Layer.provideMerge(gitVcsDriverLayer),
504 Layer.provide(vcsDriverRegistryLayer),
505 );
496 const vcsStatusBroadcasterLayer = options?.layers?.vcsStatusBroadcaster506 const vcsStatusBroadcasterLayer = options?.layers?.vcsStatusBroadcaster
497 ? Layer.mock(VcsStatusBroadcaster.VcsStatusBroadcaster)({507 ? Layer.mock(VcsStatusBroadcaster.VcsStatusBroadcaster)({
498 ...options.layers.vcsStatusBroadcaster,508 ...options.layers.vcsStatusBroadcaster,
@@ -539,6 +549,7 @@ const buildAppUnderTest = (options?: { · 40 unmodified lines
539 Layer.provide(gitManagerLayer),549 Layer.provide(gitManagerLayer),
540 Layer.provide(gitVcsDriverLayer),550 Layer.provide(gitVcsDriverLayer),
541 Layer.provide(gitWorkflowLayer),551 Layer.provide(gitWorkflowLayer),
552 Layer.provide(reviewLayer),
542 Layer.provide(vcsProvisioningLayer),553 Layer.provide(vcsProvisioningLayer),
543 Layer.provide(554 Layer.provide(
544 Layer.mock(SourceControlRepositoryService.SourceControlRepositoryService)({555 Layer.mock(SourceControlRepositoryService.SourceControlRepositoryService)({
@@ -2509,31 +2520,37 @@ it.layer(NodeServices.layer)("server router seam", (it) => { · 1964 unmodified lines
2509 removeWorktree: () => Effect.void,2520 removeWorktree: () => Effect.void,
2510 createRef: (input) => Effect.succeed({ refName: input.refName }),2521 createRef: (input) => Effect.succeed({ refName: input.refName }),
2511 switchRef: (input) => Effect.succeed({ refName: input.refName }),2522 switchRef: (input) => Effect.succeed({ refName: input.refName }),
2512 getReviewDiffs: (input) =>2523 },
2524 vcsDriver: {
2525 isInsideWorkTree: () => Effect.succeed(true),
2526 getDiffPreview: (input) =>
2513 Effect.succeed({2527 Effect.succeed({
2514 cwd: input.cwd,2528 cwd: input.cwd,
2515 generatedAt: new Date(0).toISOString(),2529 generatedAt: new Date(0).toISOString(),
2516 sections: [2530 sources: [
2517 {2531 {
2518 kind: "dirty",2532 id: "working-tree",
2533 kind: "working-tree",
2519 title: "Dirty worktree",2534 title: "Dirty worktree",
2520 baseRef: "HEAD",2535 baseRef: "HEAD",
2521 headRef: null,2536 headRef: null,
2522 diff: "dirty-diff",2537 diff: "dirty-diff",
2538 diffHash: "hash-dirty",
2539 truncated: false,
2523 },2540 },
2524 {2541 {
2525 kind: "base",2542 id: "branch-range",
2543 kind: "branch-range",
2526 title: "Against main",2544 title: "Against main",
2527 baseRef: "main",2545 baseRef: "main",
2528 headRef: "feature/demo",2546 headRef: "feature/demo",
2529 diff: "base-diff",2547 diff: "base-diff",
2548 diffHash: "hash-base",
2549 truncated: false,
2530 },2550 },
2531 ],2551 ],
2532 }),2552 }),
2533 },2553 },
2534 vcsDriver: {
2535 isInsideWorkTree: () => Effect.succeed(true),
2536 },
2537 },2554 },
2538 });2555 });
2539 2556
@@ -2641,12 +2658,12 @@ it.layer(NodeServices.layer)("server router seam", (it) => { · 101 unmodified lines
2641 ),2658 ),
2642 );2659 );
2643 2660
2644 const reviewDiffs = yield* Effect.scoped(2661 const diffPreview = yield* Effect.scoped(
2645 withWsRpcClient(wsUrl, (client) =>2662 withWsRpcClient(wsUrl, (client) =>
2646 client[WS_METHODS.gitGetReviewDiffs]({ cwd: "/tmp/repo" }),2663 client[WS_METHODS.reviewGetDiffPreview]({ cwd: "/tmp/repo" }),
2647 ),2664 ),
2648 );2665 );
2649 assert.equal(reviewDiffs.sections[0]?.diff, "dirty-diff");2666 assert.equal(diffPreview.sources[0]?.diff, "dirty-diff");
2650 }).pipe(Effect.provide(NodeHttpServer.layerTest)),2667 }).pipe(Effect.provide(NodeHttpServer.layerTest)),
2651 );2668 );
2652 2669
apps/server/src/server.ts+7−0
@@ -55,6 +55,7 @@ import * as VcsProcess from "./vcs/VcsProcess.ts"; · 54 unmodified lines
55import * as VcsProvisioningService from "./vcs/VcsProvisioningService.ts";55import * as VcsProvisioningService from "./vcs/VcsProvisioningService.ts";
56import * as VcsStatusBroadcaster from "./vcs/VcsStatusBroadcaster.ts";56import * as VcsStatusBroadcaster from "./vcs/VcsStatusBroadcaster.ts";
57import * as GitWorkflowService from "./git/GitWorkflowService.ts";57import * as GitWorkflowService from "./git/GitWorkflowService.ts";
58import * as ReviewService from "./review/ReviewService.ts";
58import * as SourceControlProviderRegistry from "./sourceControl/SourceControlProviderRegistry.ts";59import * as SourceControlProviderRegistry from "./sourceControl/SourceControlProviderRegistry.ts";
59import * as SourceControlRepositoryService from "./sourceControl/SourceControlRepositoryService.ts";60import * as SourceControlRepositoryService from "./sourceControl/SourceControlRepositoryService.ts";
60import { ProjectSetupScriptRunnerLive } from "./project/Layers/ProjectSetupScriptRunner.ts";61import { ProjectSetupScriptRunnerLive } from "./project/Layers/ProjectSetupScriptRunner.ts";
@@ -195,11 +196,17 @@ const SourceControlRepositoryServiceLayerLive = SourceControlRepositoryService.l · 134 unmodified lines
195 Layer.provideMerge(SourceControlProviderRegistryLayerLive),196 Layer.provideMerge(SourceControlProviderRegistryLayerLive),
196);197);
197 198
199const ReviewLayerLive = ReviewService.layer.pipe(
200 Layer.provideMerge(GitVcsDriver.layer),
201 Layer.provideMerge(VcsDriverRegistryLayerLive),
202);
203
198const VcsLayerLive = Layer.empty.pipe(204const VcsLayerLive = Layer.empty.pipe(
199 Layer.provideMerge(VcsProjectConfig.layer),205 Layer.provideMerge(VcsProjectConfig.layer),
200 Layer.provideMerge(VcsDriverRegistryLayerLive),206 Layer.provideMerge(VcsDriverRegistryLayerLive),
201 Layer.provideMerge(VcsProvisioningService.layer.pipe(Layer.provide(VcsDriverRegistryLayerLive))),207 Layer.provideMerge(VcsProvisioningService.layer.pipe(Layer.provide(VcsDriverRegistryLayerLive))),
202 Layer.provideMerge(GitWorkflowLayerLive),208 Layer.provideMerge(GitWorkflowLayerLive),
209 Layer.provideMerge(ReviewLayerLive),
203 Layer.provideMerge(SourceControlRepositoryServiceLayerLive),210 Layer.provideMerge(SourceControlRepositoryServiceLayerLive),
204 Layer.provideMerge(VcsStatusBroadcaster.layer.pipe(Layer.provide(GitWorkflowLayerLive))),211 Layer.provideMerge(VcsStatusBroadcaster.layer.pipe(Layer.provide(GitWorkflowLayerLive))),
205);212);
apps/server/src/vcs/GitVcsDriver.ts+5−5
@@ -10,8 +10,8 @@ import { · 9 unmodified lines
10 type VcsCreateRefResult,10 type VcsCreateRefResult,
11 type VcsCreateWorktreeInput,11 type VcsCreateWorktreeInput,
12 type VcsCreateWorktreeResult,12 type VcsCreateWorktreeResult,
13 type GitReviewDiffsInput,13 type ReviewDiffPreviewInput,
14 type GitReviewDiffsResult,14 type ReviewDiffPreviewResult,
15 type VcsInitInput,15 type VcsInitInput,
16 type VcsListRefsInput,16 type VcsListRefsInput,
17 type VcsListRefsResult,17 type VcsListRefsResult,
@@ -173,9 +173,9 @@ export interface GitVcsDriverShape { · 155 unmodified lines
173 cwd: string,173 cwd: string,
174 baseRef: string,174 baseRef: string,
175 ) => Effect.Effect<GitRangeContext, GitCommandError>;175 ) => Effect.Effect<GitRangeContext, GitCommandError>;
176 readonly getReviewDiffs: (176 readonly getReviewDiffPreview: (
177 input: GitReviewDiffsInput,177 input: ReviewDiffPreviewInput,
178 ) => Effect.Effect<GitReviewDiffsResult, GitCommandError>;178 ) => Effect.Effect<ReviewDiffPreviewResult, GitCommandError>;
179 readonly readConfigValue: (179 readonly readConfigValue: (
180 cwd: string,180 cwd: string,
181 key: string,181 key: string,
apps/server/src/vcs/GitVcsDriverCore.ts+73−32
@@ -16,9 +16,15 @@ import { · 15 unmodified lines
16 Semaphore,16 Semaphore,
17 Stream,17 Stream,
18} from "effect";18} from "effect";
19import { createHash } from "node:crypto";
19import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";20import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
20 21
21import { GitCommandError, type GitReviewDiffSection, type VcsRef } from "@t3tools/contracts";22import {
23 GitCommandError,
24 type ReviewDiffPreviewInput,
25 type ReviewDiffPreviewSource,
26 type VcsRef,
27} from "@t3tools/contracts";
22import { dedupeRemoteBranchesWithLocalMatches } from "@t3tools/shared/git";28import { dedupeRemoteBranchesWithLocalMatches } from "@t3tools/shared/git";
23import { compactTraceAttributes } from "../observability/Attributes.ts";29import { compactTraceAttributes } from "../observability/Attributes.ts";
24import { gitCommandDuration, gitCommandsTotal, withMetrics } from "../observability/Metrics.ts";30import { gitCommandDuration, gitCommandsTotal, withMetrics } from "../observability/Metrics.ts";
@@ -43,6 +49,10 @@ const REVIEW_UNTRACKED_DIFF_MAX_OUTPUT_BYTES = 40_000; · 18 unmodified lines
43const WORKSPACE_FILES_MAX_OUTPUT_BYTES = 16 * 1024 * 1024;49const WORKSPACE_FILES_MAX_OUTPUT_BYTES = 16 * 1024 * 1024;
44const STATUS_UPSTREAM_REFRESH_INTERVAL = Duration.seconds(15);50const STATUS_UPSTREAM_REFRESH_INTERVAL = Duration.seconds(15);
45const STATUS_UPSTREAM_REFRESH_TIMEOUT = Duration.seconds(5);51const STATUS_UPSTREAM_REFRESH_TIMEOUT = Duration.seconds(5);
52
53function reviewDiffHash(diff: string): string {
54 return createHash("sha256").update(diff).digest("hex");
55}
46const STATUS_UPSTREAM_REFRESH_FAILURE_COOLDOWN = Duration.seconds(5);56const STATUS_UPSTREAM_REFRESH_FAILURE_COOLDOWN = Duration.seconds(5);
47const STATUS_UPSTREAM_REFRESH_CACHE_CAPACITY = 2_048;57const STATUS_UPSTREAM_REFRESH_CACHE_CAPACITY = 2_048;
48const DEFAULT_BASE_BRANCH_CANDIDATES = ["main", "master"] as const;58const DEFAULT_BASE_BRANCH_CANDIDATES = ["main", "master"] as const;
@@ -1657,7 +1667,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* · 1608 unmodified lines
1657 );1667 );
1658 const untrackedPaths = splitNullSeparatedPaths(untrackedOutput, false);1668 const untrackedPaths = splitNullSeparatedPaths(untrackedOutput, false);
1659 if (untrackedPaths.length === 0) {1669 if (untrackedPaths.length === 0) {
1660 return "";1670 return { diff: "", truncated: false };
1661 }1671 }
1662 1672
1663 const diffs = yield* Effect.forEach(1673 const diffs = yield* Effect.forEach(
@@ -1672,86 +1682,117 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* · 8 unmodified lines
1672 maxOutputBytes: REVIEW_UNTRACKED_DIFF_MAX_OUTPUT_BYTES,1682 maxOutputBytes: REVIEW_UNTRACKED_DIFF_MAX_OUTPUT_BYTES,
1673 truncateOutputAtMaxBytes: true,1683 truncateOutputAtMaxBytes: true,
1674 },1684 },
1675 ).pipe(
1676 Effect.map((result) =>
1677 result.stdoutTruncated ? `${result.stdout}${OUTPUT_TRUNCATED_MARKER}` : result.stdout,
1678 ),
1679 ),1685 ),
1680 { concurrency: 4 },1686 { concurrency: 4 },
1681 );1687 );
1682 1688
1683 return diffs.filter((diff) => diff.trim().length > 0).join("\n");1689 return {
1690 diff: diffs
1691 .map((result) => result.stdout)
1692 .filter((diff) => diff.trim().length > 0)
1693 .join("\n"),
1694 truncated: diffs.some((result) => result.stdoutTruncated),
1695 };
1684 });1696 });
1685 1697
1686 const getReviewDiffs: GitVcsDriver.GitVcsDriverShape["getReviewDiffs"] = Effect.fn(1698 const getReviewDiffPreview = Effect.fn("getReviewDiffPreview")(function* (
1687 "getReviewDiffs",1699 input: ReviewDiffPreviewInput,
1688 )(function* (input) {1700 ) {
1689 const details = yield* statusDetailsLocal(input.cwd);1701 const details = yield* statusDetailsLocal(input.cwd);
1690 if (!details.isRepo) {1702 if (!details.isRepo) {
1691 return {1703 return {
1692 cwd: input.cwd,1704 cwd: input.cwd,
1693 generatedAt: new Date().toISOString(),1705 generatedAt: new Date().toISOString(),
1694 sections: [],1706 sources: [],
1695 };1707 };
1696 }1708 }
1697 1709
1698 const branch = details.branch;1710 const branch = details.branch;
1699 const baseRef = branch1711 const baseRef =
1700 ? yield* resolveBaseBranchForNoUpstream(input.cwd, branch).pipe(1712 input.baseRef ??
1701 Effect.catch(() => Effect.succeed(null)),1713 (branch
1702 )1714 ? yield* resolveBaseBranchForNoUpstream(input.cwd, branch).pipe(
1703 : null;1715 Effect.catch(() => Effect.succeed(null)),
1716 )
1717 : null);
1704 1718
1705 const dirtyTrackedDiff = yield* runGitStdoutWithOptions(1719 const dirtyTrackedResult = yield* executeGit(
1706 "GitVcsDriver.getReviewDiffs.dirtyTracked",1720 "GitVcsDriver.getReviewDiffPreview.dirtyTracked",
1707 input.cwd,1721 input.cwd,
1708 ["diff", "--patch", "--minimal", "HEAD", "--"],1722 ["diff", "--patch", "--minimal", "HEAD", "--"],
1709 {1723 {
1710 maxOutputBytes: REVIEW_DIFF_PATCH_MAX_OUTPUT_BYTES,1724 maxOutputBytes: REVIEW_DIFF_PATCH_MAX_OUTPUT_BYTES,
1711 truncateOutputAtMaxBytes: true,1725 truncateOutputAtMaxBytes: true,
1712 },1726 },
1713 ).pipe(Effect.catch(() => Effect.succeed("")));1727 ).pipe(
1714 const dirtyUntrackedDiff = yield* readUntrackedReviewDiffs(input.cwd).pipe(1728 Effect.catch(() =>
1715 Effect.catch(() => Effect.succeed("")),1729 Effect.succeed({
1730 exitCode: 0,
1731 stdout: "",
1732 stderr: "",
1733 stdoutTruncated: false,
1734 stderrTruncated: false,
1735 }),
1736 ),
1716 );1737 );
1717 const dirtyDiff = [dirtyTrackedDiff.trimEnd(), dirtyUntrackedDiff.trimEnd()]1738 const dirtyUntracked = yield* readUntrackedReviewDiffs(input.cwd).pipe(
1739 Effect.catch(() => Effect.succeed({ diff: "", truncated: false })),
1740 );
1741 const dirtyDiff = [dirtyTrackedResult.stdout.trimEnd(), dirtyUntracked.diff.trimEnd()]
1718 .filter((diff) => diff.length > 0)1742 .filter((diff) => diff.length > 0)
1719 .join("\n");1743 .join("\n");
1720 1744
1721 const baseDiff =1745 const baseResult =
1722 baseRef && branch1746 baseRef && branch
1723 ? yield* runGitStdoutWithOptions(1747 ? yield* executeGit(
1724 "GitVcsDriver.getReviewDiffs.base",1748 "GitVcsDriver.getReviewDiffPreview.base",
1725 input.cwd,1749 input.cwd,
1726 ["diff", "--patch", "--minimal", `${baseRef}...HEAD`],1750 ["diff", "--patch", "--minimal", `${baseRef}...HEAD`],
1727 {1751 {
1728 maxOutputBytes: REVIEW_DIFF_PATCH_MAX_OUTPUT_BYTES,1752 maxOutputBytes: REVIEW_DIFF_PATCH_MAX_OUTPUT_BYTES,
1729 truncateOutputAtMaxBytes: true,1753 truncateOutputAtMaxBytes: true,
1730 },1754 },
1731 ).pipe(Effect.catch(() => Effect.succeed("")))1755 ).pipe(
1732 : "";1756 Effect.catch(() =>
1757 Effect.succeed({
1758 exitCode: 0,
1759 stdout: "",
1760 stderr: "",
1761 stdoutTruncated: false,
1762 stderrTruncated: false,
1763 }),
1764 ),
1765 )
1766 : null;
1767 const baseDiff = baseResult?.stdout ?? "";
1733 1768
1734 const sections: GitReviewDiffSection[] = [1769 const sources: ReviewDiffPreviewSource[] = [
1735 {1770 {
1736 kind: "dirty",1771 id: "working-tree",
1772 kind: "working-tree",
1737 title: "Dirty worktree",1773 title: "Dirty worktree",
1738 baseRef: "HEAD",1774 baseRef: "HEAD",
1739 headRef: null,1775 headRef: null,
1740 diff: dirtyDiff,1776 diff: dirtyDiff,
1777 diffHash: reviewDiffHash(dirtyDiff),
1778 truncated: dirtyTrackedResult.stdoutTruncated || dirtyUntracked.truncated,
1741 },1779 },
1742 {1780 {
1743 kind: "base",1781 id: "branch-range",
1782 kind: "branch-range",
1744 title: baseRef ? `Against ${baseRef}` : "Against base branch",1783 title: baseRef ? `Against ${baseRef}` : "Against base branch",
1745 baseRef,1784 baseRef,
1746 headRef: branch ?? "HEAD",1785 headRef: branch ?? "HEAD",
1747 diff: baseDiff,1786 diff: baseDiff,
1787 diffHash: reviewDiffHash(baseDiff),
1788 truncated: baseResult?.stdoutTruncated ?? false,
1748 },1789 },
1749 ];1790 ];
1750 1791
1751 return {1792 return {
1752 cwd: input.cwd,1793 cwd: input.cwd,
1753 generatedAt: new Date().toISOString(),1794 generatedAt: new Date().toISOString(),
1754 sections,1795 sources,
1755 };1796 };
1756 });1797 });
1757 1798
@@ -2249,7 +2290,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* · 491 unmodified lines
2249 pushCurrentBranch,2290 pushCurrentBranch,
2250 pullCurrentBranch,2291 pullCurrentBranch,
2251 readRangeContext,2292 readRangeContext,
2252 getReviewDiffs,2293 getReviewDiffPreview,
2253 readConfigValue,2294 readConfigValue,
2254 listRefs,2295 listRefs,
2255 createWorktree,2296 createWorktree,
apps/server/src/vcs/VcsDriver.ts+5−0
@@ -6,6 +6,8 @@ import type { · 5 unmodified lines
6 VcsInitInput,6 VcsInitInput,
7 VcsListRemotesResult,7 VcsListRemotesResult,
8 VcsListWorkspaceFilesResult,8 VcsListWorkspaceFilesResult,
9 ReviewDiffPreviewInput,
10 ReviewDiffPreviewResult,
9 VcsRepositoryIdentity,11 VcsRepositoryIdentity,
10} from "@t3tools/contracts";12} from "@t3tools/contracts";
11import * as VcsProcess from "./VcsProcess.ts";13import * as VcsProcess from "./VcsProcess.ts";
@@ -26,6 +28,9 @@ export interface VcsDriverShape { · 14 unmodified lines
26 relativePaths: ReadonlyArray<string>,28 relativePaths: ReadonlyArray<string>,
27 ) => Effect.Effect<ReadonlyArray<string>, VcsError>;29 ) => Effect.Effect<ReadonlyArray<string>, VcsError>;
28 readonly initRepository: (input: VcsInitInput) => Effect.Effect<void, VcsError>;30 readonly initRepository: (input: VcsInitInput) => Effect.Effect<void, VcsError>;
31 readonly getDiffPreview?: (
32 input: ReviewDiffPreviewInput,
33 ) => Effect.Effect<ReviewDiffPreviewResult, VcsError>;
29}34}
30 35
31export class VcsDriver extends Context.Service<VcsDriver, VcsDriverShape>()("t3/vcs/VcsDriver") {}36export class VcsDriver extends Context.Service<VcsDriver, VcsDriverShape>()("t3/vcs/VcsDriver") {}
apps/server/src/ws.ts+5−3
@@ -53,6 +53,7 @@ import { WorkspacePathOutsideRootError } from "./workspace/Services/WorkspacePat · 52 unmodified lines
53import { VcsStatusBroadcaster } from "./vcs/VcsStatusBroadcaster.ts";53import { VcsStatusBroadcaster } from "./vcs/VcsStatusBroadcaster.ts";
54import { VcsProvisioningService } from "./vcs/VcsProvisioningService.ts";54import { VcsProvisioningService } from "./vcs/VcsProvisioningService.ts";
55import { GitWorkflowService } from "./git/GitWorkflowService.ts";55import { GitWorkflowService } from "./git/GitWorkflowService.ts";
56import { ReviewService } from "./review/ReviewService.ts";
56import { ProjectSetupScriptRunner } from "./project/Services/ProjectSetupScriptRunner.ts";57import { ProjectSetupScriptRunner } from "./project/Services/ProjectSetupScriptRunner.ts";
57import { RepositoryIdentityResolver } from "./project/Services/RepositoryIdentityResolver.ts";58import { RepositoryIdentityResolver } from "./project/Services/RepositoryIdentityResolver.ts";
58import { ServerEnvironment } from "./environment/Services/ServerEnvironment.ts";59import { ServerEnvironment } from "./environment/Services/ServerEnvironment.ts";
@@ -151,6 +152,7 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) => · 92 unmodified lines
151 const keybindings = yield* Keybindings;152 const keybindings = yield* Keybindings;
152 const open = yield* Open;153 const open = yield* Open;
153 const gitWorkflow = yield* GitWorkflowService;154 const gitWorkflow = yield* GitWorkflowService;
155 const review = yield* ReviewService;
154 const vcsProvisioning = yield* VcsProvisioningService;156 const vcsProvisioning = yield* VcsProvisioningService;
155 const vcsStatusBroadcaster = yield* VcsStatusBroadcaster;157 const vcsStatusBroadcaster = yield* VcsStatusBroadcaster;
156 const terminalManager = yield* TerminalManager;158 const terminalManager = yield* TerminalManager;
@@ -998,9 +1000,9 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) => · 841 unmodified lines
998 .pipe(Effect.tap(() => refreshGitStatus(input.cwd))),1000 .pipe(Effect.tap(() => refreshGitStatus(input.cwd))),
999 { "rpc.aggregate": "vcs" },1001 { "rpc.aggregate": "vcs" },
1000 ),1002 ),
1001 [WS_METHODS.gitGetReviewDiffs]: (input) =>1003 [WS_METHODS.reviewGetDiffPreview]: (input) =>
1002 observeRpcEffect(WS_METHODS.gitGetReviewDiffs, gitWorkflow.getReviewDiffs(input), {1004 observeRpcEffect(WS_METHODS.reviewGetDiffPreview, review.getDiffPreview(input), {
1003 "rpc.aggregate": "git",1005 "rpc.aggregate": "review",
1004 }),1006 }),
1005 [WS_METHODS.terminalOpen]: (input) =>1007 [WS_METHODS.terminalOpen]: (input) =>
1006 observeRpcEffect(WS_METHODS.terminalOpen, terminalManager.open(input), {1008 observeRpcEffect(WS_METHODS.terminalOpen, terminalManager.open(input), {
apps/web/src/components/ChatView.browser.tsx+1−0
@@ -214,6 +214,7 @@ function createMockEnvironmentApi(input: { · 213 unmodified lines
214 sourceControl: {} as EnvironmentApi["sourceControl"],214 sourceControl: {} as EnvironmentApi["sourceControl"],
215 vcs: {} as EnvironmentApi["vcs"],215 vcs: {} as EnvironmentApi["vcs"],
216 git: {} as EnvironmentApi["git"],216 git: {} as EnvironmentApi["git"],
217 review: {} as EnvironmentApi["review"],
217 orchestration: {218 orchestration: {
218 dispatchCommand: input.dispatchCommand,219 dispatchCommand: input.dispatchCommand,
219 getTurnDiff: (() => {220 getTurnDiff: (() => {
apps/web/src/components/DiffPanel.tsx+8−74
@@ -1,5 +1,4 @@
1import { parsePatchFiles } from "@pierre/diffs";1import { FileDiff, Virtualizer } from "@pierre/diffs/react";
2import { FileDiff, type FileDiffMetadata, Virtualizer } from "@pierre/diffs/react";
3import { useQuery } from "@tanstack/react-query";2import { useQuery } from "@tanstack/react-query";
4import { useNavigate, useParams, useSearch } from "@tanstack/react-router";3import { useNavigate, useParams, useSearch } from "@tanstack/react-router";
5import { scopeThreadRef } from "@t3tools/client-runtime";4import { scopeThreadRef } from "@t3tools/client-runtime";
@@ -29,8 +28,13 @@ import { readLocalApi } from "../localApi"; · 23 unmodified lines
29import { resolvePathLinkTarget } from "../terminal-links";28import { resolvePathLinkTarget } from "../terminal-links";
30import { parseDiffRouteSearch, stripDiffSearchParams } from "../diffRouteSearch";29import { parseDiffRouteSearch, stripDiffSearchParams } from "../diffRouteSearch";
31import { useTheme } from "../hooks/useTheme";30import { useTheme } from "../hooks/useTheme";
32import { buildPatchCacheKey } from "../lib/diffRendering";31import {
33import { resolveDiffThemeName } from "../lib/diffRendering";32 buildFileDiffRenderKey,
33 getDiffCollapseIconClassName,
34 getRenderablePatch,
35 resolveDiffThemeName,
36 resolveFileDiffPath,
37} from "../lib/diffRendering";
34import { useTurnDiffSummaries } from "../hooks/useTurnDiffSummaries";38import { useTurnDiffSummaries } from "../hooks/useTurnDiffSummaries";
35import { selectProjectByRef, useStore } from "../store";39import { selectProjectByRef, useStore } from "../store";
36import { createThreadSelectorByRef } from "../storeSelectors";40import { createThreadSelectorByRef } from "../storeSelectors";
@@ -107,76 +111,6 @@ const DIFF_PANEL_UNSAFE_CSS = ` · 70 unmodified lines
107}111}
108`;112`;
109 113
110type RenderablePatch =
111 | {
112 kind: "files";
113 files: FileDiffMetadata[];
114 }
115 | {
116 kind: "raw";
117 text: string;
118 reason: string;
119 };
120
121function getRenderablePatch(
122 patch: string | undefined,
123 cacheScope = "diff-panel",
124): RenderablePatch | null {
125 if (!patch) return null;
126 const normalizedPatch = patch.trim();
127 if (normalizedPatch.length === 0) return null;
128
129 try {
130 const parsedPatches = parsePatchFiles(
131 normalizedPatch,
132 buildPatchCacheKey(normalizedPatch, cacheScope),
133 );
134 const files = parsedPatches.flatMap((parsedPatch) => parsedPatch.files);
135 if (files.length > 0) {
136 return { kind: "files", files };
137 }
138
139 return {
140 kind: "raw",
141 text: normalizedPatch,
142 reason: "Unsupported diff format. Showing raw patch.",
143 };
144 } catch {
145 return {
146 kind: "raw",
147 text: normalizedPatch,
148 reason: "Failed to parse patch. Showing raw patch.",
149 };
150 }
151}
152
153function resolveFileDiffPath(fileDiff: FileDiffMetadata): string {
154 const raw = fileDiff.name ?? fileDiff.prevName ?? "";
155 if (raw.startsWith("a/") || raw.startsWith("b/")) {
156 return raw.slice(2);
157 }
158 return raw;
159}
160
161function buildFileDiffRenderKey(fileDiff: FileDiffMetadata): string {
162 return fileDiff.cacheKey ?? `${fileDiff.prevName ?? "none"}:${fileDiff.name}`;
163}
164
165function getDiffCollapseIconClassName(fileDiff: FileDiffMetadata): string {
166 switch (fileDiff.type) {
167 case "new":
168 return "text-[var(--diffs-addition-base)]";
169 case "deleted":
170 return "text-[var(--diffs-deletion-base)]";
171 case "change":
172 case "rename-pure":
173 case "rename-changed":
174 return "text-[var(--diffs-modified-base)]";
175 default:
176 return "text-muted-foreground/80";
177 }
178}
179
180interface DiffPanelProps {114interface DiffPanelProps {
181 mode?: DiffPanelMode;115 mode?: DiffPanelMode;
182}116}
apps/web/src/components/chat/MessagesTimeline.test.tsx+58−0
@@ -31,6 +31,25 @@ vi.mock("@legendapp/list/react", async () => { · 30 unmodified lines
31 return { LegendList };31 return { LegendList };
32});32});
33 33
34function MockFileDiff(props: {
35 fileDiff: { name?: string | null; prevName?: string | null };
36 renderCustomHeader?: (fileDiff: {
37 name?: string | null;
38 prevName?: string | null;
39 }) => React.ReactNode;
40}) {
41 return (
42 <div data-testid="file-diff">
43 {props.renderCustomHeader?.(props.fileDiff)}
44 {props.fileDiff.name ?? props.fileDiff.prevName ?? "diff"}
45 </div>
46 );
47}
48
49vi.mock("@pierre/diffs/react", () => {
50 return { FileDiff: MockFileDiff };
51});
52
34function matchMedia() {53function matchMedia() {
35 return {54 return {
36 matches: false,55 matches: false,
@@ -186,4 +205,43 @@ describe("MessagesTimeline", () => { · 149 unmodified lines
186 expect(markup).toContain("t3code/apps/web/src/session-logic.ts");205 expect(markup).toContain("t3code/apps/web/src/session-logic.ts");
187 expect(markup).not.toContain("C:/Users/mike/dev-stuff/t3code/apps/web/src/session-logic.ts");206 expect(markup).not.toContain("C:/Users/mike/dev-stuff/t3code/apps/web/src/session-logic.ts");
188 });207 });
208
209 it("renders review comment contexts as structured cards instead of raw tags", async () => {
210 const { MessagesTimeline } = await import("./MessagesTimeline");
211 const markup = renderToStaticMarkup(
212 <MessagesTimeline
213 {...buildProps()}
214 timelineEntries={[
215 {
216 id: "entry-1",
217 kind: "message",
218 createdAt: "2026-03-17T19:12:28.000Z",
219 message: {
220 id: MessageId.make("message-2"),
221 role: "user",
222 text: [
223 '<review_comment sectionId="turn:2" sectionTitle="Turn 2" filePath="apps/web/src/lib/contextWindow.test.ts" startIndex="3" endIndex="14" rangeLabel="+47 to +58">',
224 "Wadduo",
225 "```diff",
226 "@@ -0,0 +47,2 @@",
227 '+ it("keeps valid zero-usage snapshots", () => {',
228 "+ expect(snapshot).not.toBeNull();",
229 "```",
230 "</review_comment>",
231 ].join("\n"),
232 createdAt: "2026-03-17T19:12:28.000Z",
233 streaming: false,
234 },
235 },
236 ]}
237 />,
238 );
239
240 expect(markup).toContain("contextWindow.test.ts");
241 expect(markup).toContain("Wadduo");
242 expect(markup).toContain('data-testid="file-diff"');
243 expect(markup).not.toContain(">Review comment<");
244 expect(markup).not.toContain("&lt;review_comment");
245 expect(markup).not.toContain("&lt;/review_comment&gt;");
246 });
189});247});
apps/web/src/components/chat/MessagesTimeline.tsx+182−1
@@ -20,6 +20,7 @@ import { · 19 unmodified lines
20 CheckIcon,20 CheckIcon,
21 CircleAlertIcon,21 CircleAlertIcon,
22 EyeIcon,22 EyeIcon,
23 FileTextIcon,
23 GlobeIcon,24 GlobeIcon,
24 HammerIcon,25 HammerIcon,
25 type LucideIcon,26 type LucideIcon,
@@ -61,6 +62,18 @@ import { · 35 unmodified lines
61 textContainsInlineTerminalContextLabels,62 textContainsInlineTerminalContextLabels,
62} from "./userMessageTerminalContexts";63} from "./userMessageTerminalContexts";
63import { formatWorkspaceRelativePath } from "../../filePathDisplay";64import { formatWorkspaceRelativePath } from "../../filePathDisplay";
65import {
66 buildFileDiffRenderKey,
67 getRenderablePatch,
68 resolveDiffThemeName,
69 resolveFileDiffPath,
70} from "../../lib/diffRendering";
71import {
72 buildReviewCommentRenderablePatch,
73 parseReviewCommentMessageSegments,
74 type ReviewCommentContext,
75} from "../../reviewCommentContext";
76import { FileDiff } from "@pierre/diffs/react";
64 77
65// ---------------------------------------------------------------------------78// ---------------------------------------------------------------------------
66// Context — shared state consumed by every row component via useContext.79// Context — shared state consumed by every row component via useContext.
@@ -89,6 +102,28 @@ interface TimelineRowSharedState { · 22 unmodified lines
89const TimelineRowCtx = createContext<TimelineRowSharedState>(null!);102const TimelineRowCtx = createContext<TimelineRowSharedState>(null!);
90const TIMELINE_LIST_HEADER = <div className="h-3 sm:h-4" />;103const TIMELINE_LIST_HEADER = <div className="h-3 sm:h-4" />;
91const TIMELINE_LIST_FOOTER = <div className="h-3 sm:h-4" />;104const TIMELINE_LIST_FOOTER = <div className="h-3 sm:h-4" />;
105const REVIEW_COMMENT_DIFF_UNSAFE_CSS = `
106[data-diffs-header],
107[data-diff],
108[data-file],
109[data-error-wrapper] {
110 --diffs-bg: color-mix(in srgb, var(--background) 94%, var(--card)) !important;
111 --diffs-light-bg: color-mix(in srgb, var(--background) 94%, var(--card)) !important;
112 --diffs-dark-bg: color-mix(in srgb, var(--background) 94%, var(--card)) !important;
113 --diffs-token-light-bg: transparent;
114 --diffs-token-dark-bg: transparent;
115 --diffs-bg-addition-override: color-mix(in srgb, var(--background) 90%, var(--success));
116 --diffs-bg-deletion-override: color-mix(in srgb, var(--background) 90%, var(--destructive));
117 background-color: var(--diffs-bg) !important;
118}
119
120[data-file-info],
121[data-diffs-header] {
122 background-color: color-mix(in srgb, var(--card) 96%, var(--foreground)) !important;
123 border-block-color: var(--border) !important;
124 color: var(--foreground) !important;
125}
126`;
92 127
93// ---------------------------------------------------------------------------128// ---------------------------------------------------------------------------
94// Props (public API)129// Props (public API)
@@ -305,10 +340,17 @@ function TimelineRowContent({ row }: { row: TimelineRow }) { · 210 unmodified lines
305 const userImages = row.message.attachments ?? [];340 const userImages = row.message.attachments ?? [];
306 const displayedUserMessage = deriveDisplayedUserMessageState(row.message.text);341 const displayedUserMessage = deriveDisplayedUserMessageState(row.message.text);
307 const terminalContexts = displayedUserMessage.contexts;342 const terminalContexts = displayedUserMessage.contexts;
343 const hasReviewCommentContext =
344 displayedUserMessage.visibleText.includes("<review_comment");
308 const canRevertAgentWork = typeof row.revertTurnCount === "number";345 const canRevertAgentWork = typeof row.revertTurnCount === "number";
309 return (346 return (
310 <div className="flex justify-end">347 <div className="flex justify-end">
311 <div className="group relative max-w-[80%] rounded-2xl rounded-br-sm border border-border bg-secondary px-4 py-3">348 <div
349 className={cn(
350 "group relative rounded-2xl rounded-br-sm border border-border bg-secondary px-4 py-3",
351 hasReviewCommentContext ? "w-full max-w-[min(56rem,100%)]" : "max-w-[80%]",
352 )}
353 >
312 {userImages.length > 0 && (354 {userImages.length > 0 && (
313 <div className="mb-2 grid max-w-[420px] grid-cols-2 gap-2">355 <div className="mb-2 grid max-w-[420px] grid-cols-2 gap-2">
314 {userImages.map(356 {userImages.map(
@@ -349,6 +391,7 @@ function TimelineRowContent({ row }: { row: TimelineRow }) { · 34 unmodified lines
349 <UserMessageBody391 <UserMessageBody
350 text={displayedUserMessage.visibleText}392 text={displayedUserMessage.visibleText}
351 terminalContexts={terminalContexts}393 terminalContexts={terminalContexts}
394 resolvedTheme={ctx.resolvedTheme}
352 />395 />
353 )}396 )}
354 <div className="mt-1.5 flex items-center justify-end gap-2">397 <div className="mt-1.5 flex items-center justify-end gap-2">
@@ -686,7 +729,53 @@ const UserMessageTerminalContextInlineLabel = memo( · 331 unmodified lines
686const UserMessageBody = memo(function UserMessageBody(props: {729const UserMessageBody = memo(function UserMessageBody(props: {
687 text: string;730 text: string;
688 terminalContexts: ParsedTerminalContextEntry[];731 terminalContexts: ParsedTerminalContextEntry[];
732 resolvedTheme: "light" | "dark";
689}) {733}) {
734 const reviewCommentSegments = parseReviewCommentMessageSegments(props.text);
735 const hasReviewCommentSegments = reviewCommentSegments.some(
736 (segment) => segment.kind === "review-comment",
737 );
738 if (hasReviewCommentSegments) {
739 return (
740 <div className="space-y-2">
741 {props.terminalContexts.length > 0 && (
742 <div className="whitespace-pre-wrap wrap-break-word text-sm leading-relaxed text-foreground">
743 {props.terminalContexts.map((context) => (
744 <UserMessageTerminalContextInlineLabel
745 key={`user-terminal-context-inline:${context.header}`}
746 context={context}
747 />
748 ))}
749 </div>
750 )}
751 {reviewCommentSegments.map((segment) => {
752 if (segment.kind === "review-comment") {
753 return (
754 <UserReviewCommentCard
755 key={segment.comment.id}
756 comment={segment.comment}
757 resolvedTheme={props.resolvedTheme}
758 />
759 );
760 }
761
762 const text = segment.text.trim();
763 if (text.length === 0) {
764 return null;
765 }
766 return (
767 <div
768 key={segment.id}
769 className="whitespace-pre-wrap wrap-break-word text-sm leading-relaxed text-foreground"
770 >
771 {text}
772 </div>
773 );
774 })}
775 </div>
776 );
777 }
778
690 if (props.terminalContexts.length > 0) {779 if (props.terminalContexts.length > 0) {
691 const hasEmbeddedInlineLabels = textContainsInlineTerminalContextLabels(780 const hasEmbeddedInlineLabels = textContainsInlineTerminalContextLabels(
692 props.text,781 props.text,
@@ -776,6 +865,98 @@ const UserMessageBody = memo(function UserMessageBody(props: { · 83 unmodified lines
776 );865 );
777});866});
778 867
868const UserReviewCommentCard = memo(function UserReviewCommentCard(props: {
869 comment: ReviewCommentContext;
870 resolvedTheme: "light" | "dark";
871}) {
872 const patch = useMemo(() => buildReviewCommentRenderablePatch(props.comment), [props.comment]);
873 const renderablePatch = useMemo(
874 () => getRenderablePatch(patch, `review-comment:${props.resolvedTheme}:${props.comment.id}`),
875 [patch, props.comment.id, props.resolvedTheme],
876 );
877 const renderableFiles = useMemo(() => {
878 if (!renderablePatch || renderablePatch.kind !== "files") {
879 return [];
880 }
881 return renderablePatch.files.toSorted((left, right) =>
882 resolveFileDiffPath(left).localeCompare(resolveFileDiffPath(right), undefined, {
883 numeric: true,
884 sensitivity: "base",
885 }),
886 );
887 }, [renderablePatch]);
888
889 return (
890 <div className="w-full overflow-hidden rounded-xl border border-border bg-background text-foreground shadow-sm">
891 {renderablePatch ? (
892 renderablePatch.kind === "files" ? (
893 <div className="w-full max-h-[360px] overflow-auto bg-background">
894 {renderableFiles.map((fileDiff) => {
895 const fileKey = `${buildFileDiffRenderKey(fileDiff)}:${props.resolvedTheme}`;
896 return (
897 <div
898 key={fileKey}
899 className="diff-render-file review-comment-diff-file w-full border-b border-border/60 last:border-b-0"
900 >
901 <FileDiff
902 className="w-full"
903 fileDiff={fileDiff}
904 renderCustomHeader={(headerFileDiff) => (
905 <ReviewCommentDiffHeader filePath={resolveFileDiffPath(headerFileDiff)} />
906 )}
907 options={{
908 diffStyle: "unified",
909 lineDiffType: "none",
910 overflow: "wrap",
911 theme: resolveDiffThemeName(props.resolvedTheme),
912 themeType: props.resolvedTheme,
913 unsafeCSS: REVIEW_COMMENT_DIFF_UNSAFE_CSS,
914 }}
915 />
916 </div>
917 );
918 })}
919 </div>
920 ) : (
921 <div className="bg-background">
922 <ReviewCommentDiffHeader filePath={props.comment.filePath} />
923 <pre className="max-h-[320px] overflow-auto border-b border-border/60 bg-muted/30 p-3 font-mono text-[11px] leading-relaxed text-muted-foreground">
924 {renderablePatch.text}
925 </pre>
926 </div>
927 )
928 ) : null}
929 {props.comment.text.length > 0 && (
930 <div className="whitespace-pre-wrap wrap-break-word border-t border-border px-3 py-2.5 text-sm leading-relaxed text-foreground">
931 {props.comment.text}
932 </div>
933 )}
934 </div>
935 );
936});
937
938const ReviewCommentDiffHeader = memo(function ReviewCommentDiffHeader(props: { filePath: string }) {
939 return (
940 <div className="flex w-full min-w-0 items-center gap-2 border-b border-border bg-card/70 px-3 py-2">
941 <span className="flex size-6 shrink-0 items-center justify-center rounded-md border border-border/60 bg-muted/70 text-muted-foreground">
942 <FileTextIcon className="size-3.5" />
943 </span>
944 <p
945 className="min-w-0 flex-1 truncate font-mono text-xs font-medium text-foreground"
946 title={props.filePath}
947 >
948 {compactFileName(props.filePath)}
949 </p>
950 </div>
951 );
952});
953
954function compactFileName(filePath: string): string {
955 const normalized = filePath.replaceAll("\\", "/");
956 const lastSlashIndex = normalized.lastIndexOf("/");
957 return lastSlashIndex >= 0 ? normalized.slice(lastSlashIndex + 1) : normalized;
958}
959
779// ---------------------------------------------------------------------------960// ---------------------------------------------------------------------------
780// Structural sharing — reuse old row references when data hasn't changed961// Structural sharing — reuse old row references when data hasn't changed
781// so LegendList (and React) can skip re-rendering unchanged items.962// so LegendList (and React) can skip re-rendering unchanged items.
apps/web/src/environmentApi.ts+3−1
@@ -44,7 +44,9 @@ export function createEnvironmentApi(rpcClient: WsRpcClient): EnvironmentApi { · 43 unmodified lines
44 git: {44 git: {
45 resolvePullRequest: rpcClient.git.resolvePullRequest,45 resolvePullRequest: rpcClient.git.resolvePullRequest,
46 preparePullRequestThread: rpcClient.git.preparePullRequestThread,46 preparePullRequestThread: rpcClient.git.preparePullRequestThread,
47 getReviewDiffs: rpcClient.git.getReviewDiffs,47 },
48 review: {
49 getDiffPreview: rpcClient.review.getDiffPreview,
48 },50 },
49 orchestration: {51 orchestration: {
50 dispatchCommand: rpcClient.orchestration.dispatchCommand,52 dispatchCommand: rpcClient.orchestration.dispatchCommand,
apps/web/src/environments/runtime/connection.test.ts+3−1
@@ -85,7 +85,9 @@ function createTestClient() { · 84 unmodified lines
85 runStackedAction: vi.fn(async () => ({}) as any),85 runStackedAction: vi.fn(async () => ({}) as any),
86 resolvePullRequest: vi.fn(async () => undefined),86 resolvePullRequest: vi.fn(async () => undefined),
87 preparePullRequestThread: vi.fn(async () => undefined),87 preparePullRequestThread: vi.fn(async () => undefined),
88 getReviewDiffs: vi.fn(async () => undefined),88 },
89 review: {
90 getDiffPreview: vi.fn(async () => undefined),
89 },91 },
90 } as unknown as WsRpcClient;92 } as unknown as WsRpcClient;
91 93
apps/web/src/environments/runtime/service.threadSubscriptions.test.ts+3−1
@@ -127,7 +127,9 @@ vi.mock("@t3tools/client-runtime", async (importOriginal) => { · 126 unmodified lines
127 runStackedAction: vi.fn(),127 runStackedAction: vi.fn(),
128 resolvePullRequest: vi.fn(),128 resolvePullRequest: vi.fn(),
129 preparePullRequestThread: vi.fn(),129 preparePullRequestThread: vi.fn(),
130 getReviewDiffs: vi.fn(),130 },
131 review: {
132 getDiffPreview: vi.fn(),
131 },133 },
132 server: {134 server: {
133 getConfig: vi.fn(),135 getConfig: vi.fn(),
apps/web/src/lib/diffRendering.ts+73−0
@@ -1,3 +1,6 @@
1import { parsePatchFiles } from "@pierre/diffs";
2import type { FileDiffMetadata } from "@pierre/diffs/react";
3
1export const DIFF_THEME_NAMES = {4export const DIFF_THEME_NAMES = {
2 light: "pierre-light",5 light: "pierre-light",
3 dark: "pierre-dark",6 dark: "pierre-dark",
@@ -37,3 +40,73 @@ export function buildPatchCacheKey(patch: string, scope = "diff-panel"): string · 33 unmodified lines
37 ).toString(36);40 ).toString(36);
38 return `${scope}:${normalizedPatch.length}:${primary}:${secondary}`;41 return `${scope}:${normalizedPatch.length}:${primary}:${secondary}`;
39}42}
43
44export type RenderablePatch =
45 | {
46 kind: "files";
47 files: FileDiffMetadata[];
48 }
49 | {
50 kind: "raw";
51 text: string;
52 reason: string;
53 };
54
55export function getRenderablePatch(
56 patch: string | undefined,
57 cacheScope = "diff-panel",
58): RenderablePatch | null {
59 if (!patch) return null;
60 const normalizedPatch = patch.trim();
61 if (normalizedPatch.length === 0) return null;
62
63 try {
64 const parsedPatches = parsePatchFiles(
65 normalizedPatch,
66 buildPatchCacheKey(normalizedPatch, cacheScope),
67 );
68 const files = parsedPatches.flatMap((parsedPatch) => parsedPatch.files);
69 if (files.length > 0) {
70 return { kind: "files", files };
71 }
72
73 return {
74 kind: "raw",
75 text: normalizedPatch,
76 reason: "Unsupported diff format. Showing raw patch.",
77 };
78 } catch {
79 return {
80 kind: "raw",
81 text: normalizedPatch,
82 reason: "Failed to parse patch. Showing raw patch.",
83 };
84 }
85}
86
87export function resolveFileDiffPath(fileDiff: FileDiffMetadata): string {
88 const raw = fileDiff.name ?? fileDiff.prevName ?? "";
89 if (raw.startsWith("a/") || raw.startsWith("b/")) {
90 return raw.slice(2);
91 }
92 return raw;
93}
94
95export function buildFileDiffRenderKey(fileDiff: FileDiffMetadata): string {
96 return fileDiff.cacheKey ?? `${fileDiff.prevName ?? "none"}:${fileDiff.name}`;
97}
98
99export function getDiffCollapseIconClassName(fileDiff: FileDiffMetadata): string {
100 switch (fileDiff.type) {
101 case "new":
102 return "text-[var(--diffs-addition-base)]";
103 case "deleted":
104 return "text-[var(--diffs-deletion-base)]";
105 case "change":
106 case "rename-pure":
107 case "rename-changed":
108 return "text-[var(--diffs-modified-base)]";
109 default:
110 return "text-muted-foreground/80";
111 }
112}
apps/web/src/localApi.test.ts+3−1
@@ -86,7 +86,9 @@ const rpcClientMock = { · 85 unmodified lines
86 runStackedAction: vi.fn(),86 runStackedAction: vi.fn(),
87 resolvePullRequest: vi.fn(),87 resolvePullRequest: vi.fn(),
88 preparePullRequestThread: vi.fn(),88 preparePullRequestThread: vi.fn(),
89 getReviewDiffs: vi.fn(),89 },
90 review: {
91 getDiffPreview: vi.fn(),
90 },92 },
91 server: {93 server: {
92 getConfig: vi.fn(),94 getConfig: vi.fn(),
apps/web/src/reviewCommentContext.test.ts+77−0
@@ -0,0 +1,77 @@
1import { describe, expect, it } from "vitest";
2
3import {
4 buildReviewCommentRenderablePatch,
5 parseReviewCommentMessageSegments,
6} from "./reviewCommentContext";
7
8describe("review comment context parsing", () => {
9 it("extracts comment metadata, user text, and fenced diff without raw wrapper text", () => {
10 const segments = parseReviewCommentMessageSegments(
11 [
12 'Before <review_comment sectionId="turn:2" sectionTitle="Turn 2" filePath="apps/web/src/lib/contextWindow.test.ts" startIndex="3" endIndex="14" rangeLabel="+47 to +58">',
13 "Wadduo",
14 "```diff",
15 "@@ -0,0 +47,2 @@",
16 '+ it("keeps valid zero-usage snapshots", () => {',
17 "+ expect(snapshot).not.toBeNull();",
18 "```",
19 "</review_comment> after",
20 ].join("\n"),
21 );
22
23 expect(segments).toHaveLength(3);
24 expect(segments[0]).toEqual(
25 expect.objectContaining({
26 kind: "text",
27 text: expect.stringContaining("Before"),
28 }),
29 );
30 expect(segments[1]).toEqual(
31 expect.objectContaining({
32 kind: "review-comment",
33 comment: expect.objectContaining({
34 filePath: "apps/web/src/lib/contextWindow.test.ts",
35 rangeLabel: "+47 to +58",
36 text: "Wadduo",
37 diff: expect.stringContaining('it("keeps valid zero-usage snapshots"'),
38 }),
39 }),
40 );
41 expect(segments[2]).toEqual(
42 expect.objectContaining({
43 kind: "text",
44 text: " after",
45 }),
46 );
47 });
48
49 it("wraps hunk-only review diffs in a renderable file patch", () => {
50 const [segment] = parseReviewCommentMessageSegments(
51 [
52 '<review_comment sectionId="s" filePath="src/app.ts" startIndex="0" endIndex="0">',
53 "Please check this.",
54 "```diff",
55 "@@ -1,1 +1,1 @@",
56 "-old",
57 "+new",
58 "```",
59 "</review_comment>",
60 ].join("\n"),
61 );
62
63 expect(segment?.kind).toBe("review-comment");
64 if (segment?.kind !== "review-comment") return;
65
66 expect(buildReviewCommentRenderablePatch(segment.comment)).toBe(
67 [
68 "diff --git a/src/app.ts b/src/app.ts",
69 "--- a/src/app.ts",
70 "+++ b/src/app.ts",
71 "@@ -1,1 +1,1 @@",
72 "-old",
73 "+new",
74 ].join("\n"),
75 );
76 });
77});
apps/web/src/reviewCommentContext.ts+154−0
@@ -0,0 +1,154 @@
1export interface ReviewCommentContext {
2 readonly id: string;
3 readonly sectionId: string;
4 readonly sectionTitle: string;
5 readonly filePath: string;
6 readonly startIndex: number;
7 readonly endIndex: number;
8 readonly rangeLabel: string;
9 readonly text: string;
10 readonly diff: string;
11}
12
13export type ReviewCommentMessageSegment =
14 | {
15 readonly kind: "text";
16 readonly id: string;
17 readonly text: string;
18 }
19 | {
20 readonly kind: "review-comment";
21 readonly comment: ReviewCommentContext;
22 };
23
24const REVIEW_COMMENT_BLOCK_PATTERN = /<review_comment\b([^>]*)>\s*([\s\S]*?)<\/review_comment>/g;
25const REVIEW_COMMENT_ATTRIBUTE_PATTERN = /([a-zA-Z][a-zA-Z0-9_-]*)="([^"]*)"/g;
26const REVIEW_COMMENT_DIFF_FENCE_PATTERN = /```diff\s*\n([\s\S]*?)\n```/;
27
28function unescapeReviewCommentAttribute(value: string): string {
29 return value
30 .replace(/&lt;/g, "<")
31 .replace(/&quot;/g, '"')
32 .replace(/&amp;/g, "&");
33}
34
35function readReviewCommentAttributes(rawAttributes: string): Record<string, string> {
36 const attributes: Record<string, string> = {};
37 for (const match of rawAttributes.matchAll(REVIEW_COMMENT_ATTRIBUTE_PATTERN)) {
38 attributes[match[1]!] = unescapeReviewCommentAttribute(match[2] ?? "");
39 }
40 return attributes;
41}
42
43function readNonNegativeInteger(value: string | undefined): number | null {
44 if (value === undefined || !/^\d+$/.test(value)) {
45 return null;
46 }
47 return Number(value);
48}
49
50function extractReviewCommentText(rawBody: string): string {
51 const fenceIndex = rawBody.indexOf("```diff");
52 const commentBody = fenceIndex >= 0 ? rawBody.slice(0, fenceIndex) : rawBody;
53 return commentBody.trim();
54}
55
56function extractReviewCommentDiff(rawBody: string): string {
57 return rawBody.match(REVIEW_COMMENT_DIFF_FENCE_PATTERN)?.[1]?.trim() ?? "";
58}
59
60function parseReviewCommentContext(
61 rawAttributes: string,
62 rawBody: string,
63 index: number,
64): ReviewCommentContext | null {
65 const attributes = readReviewCommentAttributes(rawAttributes);
66 const startIndex = readNonNegativeInteger(attributes.startIndex);
67 const endIndex = readNonNegativeInteger(attributes.endIndex);
68 const filePath = attributes.filePath?.trim();
69 const sectionId = attributes.sectionId?.trim();
70 if (!filePath || !sectionId || startIndex === null || endIndex === null) {
71 return null;
72 }
73
74 return {
75 id: `review-comment:${index}:${sectionId}:${filePath}:${startIndex}:${endIndex}`,
76 sectionId,
77 sectionTitle: attributes.sectionTitle?.trim() || "Review",
78 filePath,
79 startIndex: Math.min(startIndex, endIndex),
80 endIndex: Math.max(startIndex, endIndex),
81 rangeLabel: attributes.rangeLabel?.trim() || "line",
82 text: extractReviewCommentText(rawBody),
83 diff: extractReviewCommentDiff(rawBody),
84 };
85}
86
87export function parseReviewCommentMessageSegments(
88 value: string,
89): ReadonlyArray<ReviewCommentMessageSegment> {
90 const segments: ReviewCommentMessageSegment[] = [];
91 let cursor = 0;
92 let parsedCommentIndex = 0;
93
94 for (const match of value.matchAll(REVIEW_COMMENT_BLOCK_PATTERN)) {
95 const matchIndex = match.index ?? 0;
96 const beforeText = value.slice(cursor, matchIndex);
97 if (beforeText.length > 0) {
98 segments.push({
99 kind: "text",
100 id: `review-comment-text:${cursor}`,
101 text: beforeText,
102 });
103 }
104
105 const comment = parseReviewCommentContext(match[1] ?? "", match[2] ?? "", parsedCommentIndex);
106 if (comment) {
107 segments.push({ kind: "review-comment", comment });
108 parsedCommentIndex += 1;
109 } else {
110 segments.push({
111 kind: "text",
112 id: `review-comment-invalid:${matchIndex}`,
113 text: match[0],
114 });
115 }
116
117 cursor = matchIndex + match[0].length;
118 }
119
120 const rest = value.slice(cursor);
121 if (rest.length > 0) {
122 segments.push({
123 kind: "text",
124 id: `review-comment-text:${cursor}`,
125 text: rest,
126 });
127 }
128
129 return segments;
130}
131
132export function hasReviewCommentMessageSegments(value: string): boolean {
133 return parseReviewCommentMessageSegments(value).some(
134 (segment) => segment.kind === "review-comment",
135 );
136}
137
138export function buildReviewCommentRenderablePatch(comment: ReviewCommentContext): string {
139 const diff = comment.diff.trim();
140 if (diff.length === 0) {
141 return "";
142 }
143 if (diff.startsWith("diff --git ")) {
144 return diff;
145 }
146
147 const normalizedPath = comment.filePath.replaceAll("\\", "/");
148 return [
149 `diff --git a/${normalizedPath} b/${normalizedPath}`,
150 `--- a/${normalizedPath}`,
151 `+++ b/${normalizedPath}`,
152 diff,
153 ].join("\n");
154}
bun.lock+5−5
@@ -16,7 +16,7 @@ · 15 unmodified lines
16 },16 },
17 "apps/desktop": {17 "apps/desktop": {
18 "name": "@t3tools/desktop",18 "name": "@t3tools/desktop",
19 "version": "0.0.21",19 "version": "0.0.22",
20 "dependencies": {20 "dependencies": {
21 "@effect/platform-node": "catalog:",21 "@effect/platform-node": "catalog:",
22 "effect": "catalog:",22 "effect": "catalog:",
@@ -55,7 +55,7 @@ · 32 unmodified lines
55 "@effect/atom-react": "catalog:",55 "@effect/atom-react": "catalog:",
56 "@expo-google-fonts/dm-sans": "^0.4.2",56 "@expo-google-fonts/dm-sans": "^0.4.2",
57 "@legendapp/list": "3.0.0-beta.44",57 "@legendapp/list": "3.0.0-beta.44",
58 "@pierre/diffs": "^1.1.0-beta.16",58 "@pierre/diffs": "catalog:",
59 "@react-native-menu/menu": "^2.0.0",59 "@react-native-menu/menu": "^2.0.0",
60 "@shikijs/core": "3.23.0",60 "@shikijs/core": "3.23.0",
61 "@shikijs/engine-javascript": "3.23.0",61 "@shikijs/engine-javascript": "3.23.0",
@@ -116,7 +116,7 @@ · 54 unmodified lines
116 },116 },
117 "apps/server": {117 "apps/server": {
118 "name": "t3",118 "name": "t3",
119 "version": "0.0.21",119 "version": "0.0.22",
120 "bin": {120 "bin": {
121 "t3": "./dist/bin.mjs",121 "t3": "./dist/bin.mjs",
122 },122 },
@@ -149,7 +149,7 @@ · 26 unmodified lines
149 },149 },
150 "apps/web": {150 "apps/web": {
151 "name": "@t3tools/web",151 "name": "@t3tools/web",
152 "version": "0.0.21",152 "version": "0.0.22",
153 "dependencies": {153 "dependencies": {
154 "@base-ui/react": "^1.2.0",154 "@base-ui/react": "^1.2.0",
155 "@dnd-kit/core": "^6.3.1",155 "@dnd-kit/core": "^6.3.1",
@@ -216,7 +216,7 @@ · 60 unmodified lines
216 },216 },
217 "packages/contracts": {217 "packages/contracts": {
218 "name": "@t3tools/contracts",218 "name": "@t3tools/contracts",
219 "version": "0.0.21",219 "version": "0.0.22",
220 "dependencies": {220 "dependencies": {
221 "effect": "catalog:",221 "effect": "catalog:",
222 },222 },
packages/client-runtime/src/wsRpcClient.ts+7−3
@@ -109,7 +109,9 @@ export interface WsRpcClient { · 108 unmodified lines
109 readonly preparePullRequestThread: RpcUnaryMethod<109 readonly preparePullRequestThread: RpcUnaryMethod<
110 typeof WS_METHODS.gitPreparePullRequestThread110 typeof WS_METHODS.gitPreparePullRequestThread
111 >;111 >;
112 readonly getReviewDiffs: RpcUnaryMethod<typeof WS_METHODS.gitGetReviewDiffs>;112 };
113 readonly review: {
114 readonly getDiffPreview: RpcUnaryMethod<typeof WS_METHODS.reviewGetDiffPreview>;
113 };115 };
114 readonly server: {116 readonly server: {
115 readonly getConfig: RpcUnaryNoArgMethod<typeof WS_METHODS.serverGetConfig>;117 readonly getConfig: RpcUnaryNoArgMethod<typeof WS_METHODS.serverGetConfig>;
@@ -245,8 +247,10 @@ export function createWsRpcClient( · 129 unmodified lines
245 transport.request((client) => client[WS_METHODS.gitResolvePullRequest](input)),247 transport.request((client) => client[WS_METHODS.gitResolvePullRequest](input)),
246 preparePullRequestThread: (input) =>248 preparePullRequestThread: (input) =>
247 transport.request((client) => client[WS_METHODS.gitPreparePullRequestThread](input)),249 transport.request((client) => client[WS_METHODS.gitPreparePullRequestThread](input)),
248 getReviewDiffs: (input) =>250 },
249 transport.request((client) => client[WS_METHODS.gitGetReviewDiffs](input)),251 review: {
252 getDiffPreview: (input) =>
253 transport.request((client) => client[WS_METHODS.reviewGetDiffPreview](input)),
250 },254 },
251 server: {255 server: {
252 getConfig: () => transport.request((client) => client[WS_METHODS.serverGetConfig]({})),256 getConfig: () => transport.request((client) => client[WS_METHODS.serverGetConfig]({})),
packages/contracts/src/git.ts+0−24
@@ -184,11 +184,6 @@ export const VcsInitInput = Schema.Struct({ · 183 unmodified lines
184});184});
185export type VcsInitInput = typeof VcsInitInput.Type;185export type VcsInitInput = typeof VcsInitInput.Type;
186 186
187export const GitReviewDiffsInput = Schema.Struct({
188 cwd: TrimmedNonEmptyStringSchema,
189});
190export type GitReviewDiffsInput = typeof GitReviewDiffsInput.Type;
191
192// RPC Results187// RPC Results
193 188
194const VcsStatusChangeRequest = Schema.Struct({189const VcsStatusChangeRequest = Schema.Struct({
@@ -285,25 +280,6 @@ export const VcsSwitchRefResult = Schema.Struct({ · 90 unmodified lines
285});280});
286export type VcsSwitchRefResult = typeof VcsSwitchRefResult.Type;281export type VcsSwitchRefResult = typeof VcsSwitchRefResult.Type;
287 282
288export const GitReviewDiffKind = Schema.Literals(["dirty", "base"]);
289export type GitReviewDiffKind = typeof GitReviewDiffKind.Type;
290
291export const GitReviewDiffSection = Schema.Struct({
292 kind: GitReviewDiffKind,
293 title: TrimmedNonEmptyStringSchema,
294 baseRef: Schema.NullOr(TrimmedNonEmptyStringSchema),
295 headRef: Schema.NullOr(TrimmedNonEmptyStringSchema),
296 diff: Schema.String,
297});
298export type GitReviewDiffSection = typeof GitReviewDiffSection.Type;
299
300export const GitReviewDiffsResult = Schema.Struct({
301 cwd: TrimmedNonEmptyStringSchema,
302 generatedAt: Schema.String,
303 sections: Schema.Array(GitReviewDiffSection),
304});
305export type GitReviewDiffsResult = typeof GitReviewDiffsResult.Type;
306
307export const GitRunStackedActionResult = Schema.Struct({283export const GitRunStackedActionResult = Schema.Struct({
308 action: GitStackedAction,284 action: GitStackedAction,
309 branch: Schema.Struct({285 branch: Schema.Struct({
packages/contracts/src/index.ts+1−0
@@ -18,4 +18,5 @@ export * from "./orchestration.ts"; · 17 unmodified lines
18export * from "./editor.ts";18export * from "./editor.ts";
19export * from "./project.ts";19export * from "./project.ts";
20export * from "./filesystem.ts";20export * from "./filesystem.ts";
21export * from "./review.ts";
21export * from "./rpc.ts";22export * from "./rpc.ts";
packages/contracts/src/ipc.ts+4−3
@@ -5,8 +5,6 @@ import type { · 4 unmodified lines
5 GitPreparePullRequestThreadInput,5 GitPreparePullRequestThreadInput,
6 GitPreparePullRequestThreadResult,6 GitPreparePullRequestThreadResult,
7 GitPullRequestRefInput,7 GitPullRequestRefInput,
8 GitReviewDiffsInput,
9 GitReviewDiffsResult,
10 VcsCreateWorktreeInput,8 VcsCreateWorktreeInput,
11 VcsCreateWorktreeResult,9 VcsCreateWorktreeResult,
12 VcsInitInput,10 VcsInitInput,
@@ -20,6 +18,7 @@ import type { · 7 unmodified lines
20 VcsStatusResult,18 VcsStatusResult,
21 VcsCreateRefResult,19 VcsCreateRefResult,
22} from "./git.ts";20} from "./git.ts";
21import type { ReviewDiffPreviewInput, ReviewDiffPreviewResult } from "./review.ts";
23import type { FilesystemBrowseInput, FilesystemBrowseResult } from "./filesystem.ts";22import type { FilesystemBrowseInput, FilesystemBrowseResult } from "./filesystem.ts";
24import type {23import type {
25 ProjectSearchEntriesInput,24 ProjectSearchEntriesInput,
@@ -378,7 +377,9 @@ export interface EnvironmentApi { · 352 unmodified lines
378 preparePullRequestThread: (377 preparePullRequestThread: (
379 input: GitPreparePullRequestThreadInput,378 input: GitPreparePullRequestThreadInput,
380 ) => Promise<GitPreparePullRequestThreadResult>;379 ) => Promise<GitPreparePullRequestThreadResult>;
381 getReviewDiffs: (input: GitReviewDiffsInput) => Promise<GitReviewDiffsResult>;380 };
381 review: {
382 getDiffPreview: (input: ReviewDiffPreviewInput) => Promise<ReviewDiffPreviewResult>;
382 };383 };
383 orchestration: {384 orchestration: {
384 dispatchCommand: (command: ClientOrchestrationCommand) => Promise<{ sequence: number }>;385 dispatchCommand: (command: ClientOrchestrationCommand) => Promise<{ sequence: number }>;
packages/contracts/src/review.ts+35−0
@@ -0,0 +1,35 @@
1import { Schema } from "effect";
2import { TrimmedNonEmptyString } from "./baseSchemas.ts";
3import { GitCommandError } from "./git.ts";
4import { VcsError } from "./vcs.ts";
5
6export const ReviewDiffPreviewInput = Schema.Struct({
7 cwd: TrimmedNonEmptyString,
8 baseRef: Schema.optional(TrimmedNonEmptyString),
9});
10export type ReviewDiffPreviewInput = typeof ReviewDiffPreviewInput.Type;
11
12export const ReviewDiffPreviewSourceKind = Schema.Literals(["working-tree", "branch-range"]);
13export type ReviewDiffPreviewSourceKind = typeof ReviewDiffPreviewSourceKind.Type;
14
15export const ReviewDiffPreviewSource = Schema.Struct({
16 id: TrimmedNonEmptyString,
17 kind: ReviewDiffPreviewSourceKind,
18 title: TrimmedNonEmptyString,
19 baseRef: Schema.NullOr(TrimmedNonEmptyString),
20 headRef: Schema.NullOr(TrimmedNonEmptyString),
21 diff: Schema.String,
22 diffHash: TrimmedNonEmptyString,
23 truncated: Schema.Boolean,
24});
25export type ReviewDiffPreviewSource = typeof ReviewDiffPreviewSource.Type;
26
27export const ReviewDiffPreviewResult = Schema.Struct({
28 cwd: TrimmedNonEmptyString,
29 generatedAt: Schema.String,
30 sources: Schema.Array(ReviewDiffPreviewSource),
31});
32export type ReviewDiffPreviewResult = typeof ReviewDiffPreviewResult.Type;
33
34export const ReviewDiffPreviewError = Schema.Union([VcsError, GitCommandError]);
35export type ReviewDiffPreviewError = typeof ReviewDiffPreviewError.Type;
packages/contracts/src/rpc.ts+18−8
@@ -26,8 +26,6 @@ import { · 25 unmodified lines
26 GitPreparePullRequestThreadResult,26 GitPreparePullRequestThreadResult,
27 VcsPullInput,27 VcsPullInput,
28 GitPullRequestRefInput,28 GitPullRequestRefInput,
29 GitReviewDiffsInput,
30 GitReviewDiffsResult,
31 VcsPullResult,29 VcsPullResult,
32 VcsRemoveWorktreeInput,30 VcsRemoveWorktreeInput,
33 GitResolvePullRequestResult,31 GitResolvePullRequestResult,
@@ -36,6 +34,11 @@ import { · 2 unmodified lines
36 VcsStatusResult,34 VcsStatusResult,
37 VcsStatusStreamEvent,35 VcsStatusStreamEvent,
38} from "./git.ts";36} from "./git.ts";
37import {
38 ReviewDiffPreviewError,
39 ReviewDiffPreviewInput,
40 ReviewDiffPreviewResult,
41} from "./review.ts";
39import { KeybindingsConfigError } from "./keybindings.ts";42import { KeybindingsConfigError } from "./keybindings.ts";
40import {43import {
41 ClientOrchestrationCommand,44 ClientOrchestrationCommand,
@@ -122,7 +125,9 @@ export const WS_METHODS = { · 80 unmodified lines
122 gitRunStackedAction: "git.runStackedAction",125 gitRunStackedAction: "git.runStackedAction",
123 gitResolvePullRequest: "git.resolvePullRequest",126 gitResolvePullRequest: "git.resolvePullRequest",
124 gitPreparePullRequestThread: "git.preparePullRequestThread",127 gitPreparePullRequestThread: "git.preparePullRequestThread",
125 gitGetReviewDiffs: "git.getReviewDiffs",128
129 // Review methods
130 reviewGetDiffPreview: "review.getDiffPreview",
126 131
127 // Terminal methods132 // Terminal methods
128 terminalOpen: "terminal.open",133 terminalOpen: "terminal.open",
@@ -316,10 +321,15 @@ export const WsVcsInitRpc = Rpc.make(WS_METHODS.vcsInit, { · 187 unmodified lines
316 error: VcsError,321 error: VcsError,
317});322});
318 323
319export const WsGitGetReviewDiffsRpc = Rpc.make(WS_METHODS.gitGetReviewDiffs, {324/**
320 payload: GitReviewDiffsInput,325 * Ephemeral live diff preview for compact/mobile surfaces.
321 success: GitReviewDiffsResult,326 * Not the persisted T3 Review model. Future review sessions should use
322 error: GitCommandError,327 * review.open* + review.getSnapshot.
328 */
329export const WsReviewGetDiffPreviewRpc = Rpc.make(WS_METHODS.reviewGetDiffPreview, {
330 payload: ReviewDiffPreviewInput,
331 success: ReviewDiffPreviewResult,
332 error: ReviewDiffPreviewError,
323});333});
324 334
325export const WsTerminalOpenRpc = Rpc.make(WS_METHODS.terminalOpen, {335export const WsTerminalOpenRpc = Rpc.make(WS_METHODS.terminalOpen, {
@@ -465,7 +475,7 @@ export const WsRpcGroup = RpcGroup.make( · 139 unmodified lines
465 WsVcsCreateRefRpc,475 WsVcsCreateRefRpc,
466 WsVcsSwitchRefRpc,476 WsVcsSwitchRefRpc,
467 WsVcsInitRpc,477 WsVcsInitRpc,
468 WsGitGetReviewDiffsRpc,478 WsReviewGetDiffPreviewRpc,
469 WsTerminalOpenRpc,479 WsTerminalOpenRpc,
470 WsTerminalAttachRpc,480 WsTerminalAttachRpc,
471 WsTerminalWriteRpc,481 WsTerminalWriteRpc,

Keyboard shortcuts

General

Show keyboard shortcuts
?
Focus the current search
/

Issues and pull requests

Open filters
f

Issues, pull requests and Inbox

Select next item
j↓
Select previous item
k↑
Open selected item
Enter
Dismiss filters or clear selection
Esc

Repository code

Go to file
t