From c8625cafce8dd0195f024efbbed66f7d803a1bf5 Mon Sep 17 00:00:00 2001 From: "Timo S." <18382402+sti0@users.noreply.github.com> Date: Thu, 19 Nov 2026 20:24:40 +0100 Subject: [PATCH 01/97] fix(web): Ctrl+B reaches a focused terminal again (#34588) Co-authored-by: Julius Marminge --- apps/web/src/components/AppSidebarLayout.tsx | 21 ++++++++------- apps/web/src/keybindings.test.ts | 28 ++++++++++++++++++++ apps/web/src/keybindings.ts | 10 +++++++ docs/user/keybindings.md | 2 ++ 4 files changed, 52 insertions(+), 9 deletions(-) diff --git a/apps/web/src/components/AppSidebarLayout.tsx b/apps/web/src/components/AppSidebarLayout.tsx index 4b7a6d36a98cd..c7515485662ac 100644 --- a/apps/web/src/components/AppSidebarLayout.tsx +++ b/apps/web/src/components/AppSidebarLayout.tsx @@ -21,6 +21,7 @@ import { import { getLocalStorageItem, removeLocalStorageItem } from "../hooks/useLocalStorage"; import { isRichTextBoldShortcut, + isSidebarToggleShortcut, resolveShortcutCommand, shortcutLabelForCommand, } from "../keybindings"; @@ -348,15 +349,17 @@ function SidebarControl({ showSidebar }: { readonly showSidebar: boolean }) { // the toggle stays available everywhere else. return; } - const command = resolveShortcutCommand(event, keybindings, { - context: { - terminalFocus: isTerminalFocused(), - previewFocus: isPreviewFocused(), - ...readRoutePanelsOpen(router), - usagePageOpen, - }, - }); - if (command !== "sidebar.toggle") return; + if ( + !isSidebarToggleShortcut(event, keybindings, { + context: { + terminalFocus: isTerminalFocused(), + previewFocus: isPreviewFocused(), + ...readRoutePanelsOpen(router), + usagePageOpen, + }, + }) + ) + return; event.preventDefault(); event.stopPropagation(); diff --git a/apps/web/src/keybindings.test.ts b/apps/web/src/keybindings.test.ts index 3b596f838fa0d..fb6f719bb2346 100644 --- a/apps/web/src/keybindings.test.ts +++ b/apps/web/src/keybindings.test.ts @@ -15,6 +15,7 @@ import { effectiveShortcutsForCommand, formatShortcutLabel, isRichTextBoldShortcut, + isSidebarToggleShortcut, isTerminalNewShortcut, isTerminalSplitShortcut, resolveChatShortcutCommand, @@ -813,6 +814,33 @@ describe("isRichTextBoldShortcut", () => { }); }); +describe("isSidebarToggleShortcut", () => { + it("leaves Ctrl+B to a focused terminal, where it is the tmux prefix", () => { + const ctrlB = event({ key: "b", ctrlKey: true }); + assert.isFalse( + isSidebarToggleShortcut(ctrlB, DEFAULT_BINDINGS, { + platform: "Linux", + context: { terminalFocus: true }, + }), + ); + assert.isTrue( + isSidebarToggleShortcut(ctrlB, DEFAULT_BINDINGS, { + platform: "Linux", + context: { terminalFocus: false }, + }), + ); + }); + + it("keeps Cmd+B toggling the sidebar from a focused terminal on macOS", () => { + assert.isTrue( + isSidebarToggleShortcut(event({ key: "b", metaKey: true }), DEFAULT_BINDINGS, { + platform: "MacIntel", + context: { terminalFocus: true }, + }), + ); + }); +}); + describe("composer and pull request shortcuts", () => { it("uses the dictation chord outside the terminal and preserves terminal split", () => { const chord = event({ key: "d", ctrlKey: true, shiftKey: true }); diff --git a/apps/web/src/keybindings.ts b/apps/web/src/keybindings.ts index 75f617d3cca86..88a30f76b675d 100644 --- a/apps/web/src/keybindings.ts +++ b/apps/web/src/keybindings.ts @@ -379,6 +379,16 @@ export function isDiffToggleShortcut( return matchesCommandShortcut(event, keybindings, "diff.toggle", options); } +export function isSidebarToggleShortcut( + event: ShortcutEventLike, + keybindings: ResolvedKeybindingsConfig, + options?: ShortcutMatchOptions, +): boolean { + // A focused terminal owns Ctrl chords, such as tmux's Ctrl+B prefix; Cmd never reaches it. + if (event.ctrlKey && options?.context?.terminalFocus) return false; + return matchesCommandShortcut(event, keybindings, "sidebar.toggle", options); +} + export function isOpenFavoriteEditorShortcut( event: ShortcutEventLike, keybindings: ResolvedKeybindingsConfig, diff --git a/docs/user/keybindings.md b/docs/user/keybindings.md index 308d7d934c1f8..22c50349cb1c7 100644 --- a/docs/user/keybindings.md +++ b/docs/user/keybindings.md @@ -209,6 +209,8 @@ if the browser takes it first. Many defaults include `!terminalFocus` so they do not intercept terminal input. Keep that condition when remapping them if you want the same behavior. +`sidebar.toggle` never takes a Ctrl chord from a focused terminal, so tmux's `Ctrl+B` +prefix reaches it. On macOS, `Cmd+B` still toggles the sidebar there. ## Desktop quit shortcut From ff4197c480525e228d4c0058b0d7b5f88bb5627e Mon Sep 17 00:00:00 2001 From: Alex Southwell Date: Fri, 20 Nov 2026 06:28:10 +1100 Subject: [PATCH 02/97] perf(client-runtime): skip history scans when no runs are queued (#25519) Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> Co-authored-by: SAPHID Co-authored-by: maria-rcks Co-authored-by: Julius Marminge --- .../src/state/threadWorkflows.test.ts | 19 +++++++++++++++++++ .../src/state/threadWorkflows.ts | 2 ++ 2 files changed, 21 insertions(+) diff --git a/packages/client-runtime/src/state/threadWorkflows.test.ts b/packages/client-runtime/src/state/threadWorkflows.test.ts index 3fe571e84b5bf..a4049c7169163 100644 --- a/packages/client-runtime/src/state/threadWorkflows.test.ts +++ b/packages/client-runtime/src/state/threadWorkflows.test.ts @@ -4,6 +4,7 @@ import type { OrchestrationV2ThreadProjection } from "@t3tools/contracts"; import { canForkProjectedAssistantItem, deriveThreadQueueWorkflowState, + getUserQueuedThreadRuns, resolveLatestMergeBackRun, threadSupportsProviderHandoff, } from "./threadWorkflows.ts"; @@ -30,6 +31,24 @@ const capabilities = (input?: { }) as never; describe("thread workflows", () => { + it("skips message history classification when no runs are queued", () => { + let metadataReads = 0; + const message = { + id: "message", + get delegatedCompletion() { + metadataReads++; + return undefined; + }, + }; + const projection = { + runs: [{ id: "active", status: "running", userMessageId: "message", ordinal: 1 }], + messages: [message], + } as never; + + expect(getUserQueuedThreadRuns(projection)).toEqual([]); + expect(metadataReads).toBe(0); + }); + it("allows a completed thread to switch providers after its session detaches", () => { const projection = { thread: { diff --git a/packages/client-runtime/src/state/threadWorkflows.ts b/packages/client-runtime/src/state/threadWorkflows.ts index ef39233707a7b..7dbbcf1e80c57 100644 --- a/packages/client-runtime/src/state/threadWorkflows.ts +++ b/packages/client-runtime/src/state/threadWorkflows.ts @@ -125,6 +125,8 @@ export function threadSupportsProviderHandoff(projection: Projection | null | un export function getUserQueuedThreadRuns( projection: Pick, ): ReadonlyArray { + if (!projection.runs.some((run) => run.status === "queued")) return []; + const automaticCompletionMessageIds = new Set( projection.messages .filter( From 42d2387285eea2e4cb34bab29e64f78f65a8b3b2 Mon Sep 17 00:00:00 2001 From: Nawfal Ahmed <111358247+NawfalAhmed@users.noreply.github.com> Date: Fri, 20 Nov 2026 00:29:44 +0500 Subject: [PATCH 03/97] fix(web): right-clicking a sidebar search result now opens its thread actions (#31545) Co-authored-by: maria-rcks Co-authored-by: Julius Marminge --- .../components/Sidebar.drag.browser.test.tsx | 1 + apps/web/src/components/Sidebar.tsx | 25 ++++++++++++++++--- .../components/sidebar/SidebarThreadRow.tsx | 13 ++++++++++ .../components/threadActionMenu.logic.test.ts | 5 ++++ .../src/components/threadActionMenu.logic.ts | 10 +++++++- 5 files changed, 50 insertions(+), 4 deletions(-) diff --git a/apps/web/src/components/Sidebar.drag.browser.test.tsx b/apps/web/src/components/Sidebar.drag.browser.test.tsx index f3402f20a4bc7..2a5acdd3b1b70 100644 --- a/apps/web/src/components/Sidebar.drag.browser.test.tsx +++ b/apps/web/src/components/Sidebar.drag.browser.test.tsx @@ -128,6 +128,7 @@ it("keeps focus in the search box when a click picks a search result", async () searchQuery="invoice" onHighlight={() => {}} onSelect={onSelect} + onContextMenu={() => {}} onFileDropThreads={() => {}} /> diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index 7157e7aaa75b9..86a2d04c53eef 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -2607,17 +2607,30 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve ); const handleThreadContextMenu = useStableCallback( - (threadRef: ScopedThreadRef, position: { x: number; y: number }, source: ContextMenuSource) => { + ( + threadRef: ScopedThreadRef, + position: { x: number; y: number }, + source: ContextMenuSource, + fromSearch = false, + ) => { void (async () => { const api = readLocalApi(); if (!api) return; const threadKey = scopedThreadKey(threadRef); const selectionState = useThreadSelectionStore.getState(); - if (selectionState.hasSelection() && selectionState.selectedThreadKeys.has(threadKey)) { + // Search results are not selectable rows, so they always act on their own thread. + if ( + !fromSearch && + selectionState.hasSelection() && + selectionState.selectedThreadKeys.has(threadKey) + ) { await handleMultiSelectContextMenu(position, source); return; } - const thread = threadByKeyRef.current.get(threadKey); + // Search results also reach threads in collapsed shelves, which are not rendered rows. + const thread = + threadByKeyRef.current.get(threadKey) ?? + searchableThreads.find((candidate) => threadShellKey(candidate) === threadKey); if (!thread) return; const threadWorkspacePath = thread.worktreePath ?? @@ -2671,6 +2684,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve canShareWithGuestAtom(threadRef.environmentId), ), canTurnIntoProject: canTurnThreadIntoProject(threadRef), + canRename: !fromSearch, supports: { settlement: configLoaded, autoSettleOptOut: supportsAutoSettleOptOut, @@ -2897,6 +2911,10 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve })(); }, ); + const handleSearchResultContextMenu = useStableCallback( + (threadRef: ScopedThreadRef, position: { x: number; y: number }, source: ContextMenuSource) => + handleThreadContextMenu(threadRef, position, source, true), + ); // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- subscribes to window keydown for thread navigation shortcuts using the current thread list useEffect(() => { @@ -3284,6 +3302,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve searchMatchQuery={threadSearch.query} onHighlight={() => setActiveSearchResultIndex(index)} onSelect={() => selectThreadSearchResult(thread)} + onContextMenu={handleSearchResultContextMenu} onFileDropThreads={handleThreadFileDrop} /> ); diff --git a/apps/web/src/components/sidebar/SidebarThreadRow.tsx b/apps/web/src/components/sidebar/SidebarThreadRow.tsx index f3505bd2c66bf..3e1695e63f0a7 100644 --- a/apps/web/src/components/sidebar/SidebarThreadRow.tsx +++ b/apps/web/src/components/sidebar/SidebarThreadRow.tsx @@ -1777,6 +1777,11 @@ export const SidebarSearchResultRow = memo(function SidebarSearchResultRow(props searchMatchQuery?: string; onHighlight: () => void; onSelect: () => void; + onContextMenu: ( + threadRef: ScopedThreadRef, + position: { x: number; y: number }, + source: ContextMenuSource, + ) => void; onFileDropThreads: (threadRef: ScopedThreadRef, files: File[]) => void; }) { const messages = useMessages(); @@ -1881,6 +1886,14 @@ export const SidebarSearchResultRow = memo(function SidebarSearchResultRow(props event.preventDefault(); }} onClick={props.onSelect} + onContextMenu={(event) => { + event.preventDefault(); + props.onContextMenu( + threadRef, + { x: event.clientX, y: event.clientY }, + contextMenuSourceOf(event), + ); + }} className={cn( "group/sidebar-row group/v2-row flex min-h-9 w-full cursor-pointer items-center gap-2.5 rounded-md px-2.5 py-1 text-left text-sm outline-none", props.isHighlighted || props.isRouteActive diff --git a/apps/web/src/components/threadActionMenu.logic.test.ts b/apps/web/src/components/threadActionMenu.logic.test.ts index bd9dfdcdcc4b6..0c13e765131cc 100644 --- a/apps/web/src/components/threadActionMenu.logic.test.ts +++ b/apps/web/src/components/threadActionMenu.logic.test.ts @@ -74,4 +74,9 @@ describe("buildThreadActionMenuItems", () => { expect(items.find((item) => item.id === "archive")?.disabled).toBe(true); expect(items.find((item) => item.id === "turn-into-project")?.disabled).toBe(true); }); + + it("disables only rename where no inline title editor exists", () => { + const items = buildThreadActionMenuItems({ ...baseState, canRename: false }); + expect(items.filter((item) => item.disabled).map((item) => item.id)).toEqual(["rename"]); + }); }); diff --git a/apps/web/src/components/threadActionMenu.logic.ts b/apps/web/src/components/threadActionMenu.logic.ts index 0f95a9a4bbd16..dc2d7687a2be6 100644 --- a/apps/web/src/components/threadActionMenu.logic.ts +++ b/apps/web/src/components/threadActionMenu.logic.ts @@ -96,6 +96,8 @@ export function buildDraftActionMenuItems( export interface ThreadActionMenuState { readonly canOperate: boolean; readonly canFind?: boolean; + /** False where no inline title editor is rendered, such as sidebar search results. */ + readonly canRename?: boolean; readonly branch: string | null; readonly projectFilter: { readonly label: string; @@ -198,7 +200,13 @@ export function buildThreadActionMenuItems( }, ] : []), - { id: "rename", label: resolve(msg("Rename thread")), icon: "pencil", separatorBefore: true }, + { + id: "rename", + label: resolve(msg("Rename thread")), + icon: "pencil", + disabled: state.canRename === false, + separatorBefore: true, + }, ...(state.supports.titleRegeneration ? [ { From 910c1a8df90c0d85e2a418d1693da9e1f9647492 Mon Sep 17 00:00:00 2001 From: Suhail <63963181+BreadGenie@users.noreply.github.com> Date: Fri, 20 Nov 2026 01:04:57 +0530 Subject: [PATCH 04/97] fix(mobile): long user messages collapse like on web (#34319) Co-authored-by: maria-rcks Co-authored-by: Julius Marminge --- .../threads/CollapsibleUserMessageBody.tsx | 76 +++++++++++++++++++ .../src/features/threads/ThreadFeed.tsx | 46 ++++++++--- apps/mobile/src/i18n/translations/de.json | 2 + apps/mobile/src/i18n/translations/en.json | 2 + apps/mobile/src/i18n/translations/es.json | 2 + apps/mobile/src/i18n/translations/fr.json | 2 + apps/mobile/src/i18n/translations/ja.json | 2 + apps/mobile/src/i18n/translations/ko.json | 2 + apps/mobile/src/i18n/translations/pt-BR.json | 2 + apps/mobile/src/i18n/translations/ru.json | 2 + apps/mobile/src/i18n/translations/sv.json | 2 + apps/mobile/src/i18n/translations/zh.json | 2 + apps/mobile/src/lib/filePreview.test.ts | 3 + 13 files changed, 135 insertions(+), 10 deletions(-) create mode 100644 apps/mobile/src/features/threads/CollapsibleUserMessageBody.tsx diff --git a/apps/mobile/src/features/threads/CollapsibleUserMessageBody.tsx b/apps/mobile/src/features/threads/CollapsibleUserMessageBody.tsx new file mode 100644 index 0000000000000..986656827927f --- /dev/null +++ b/apps/mobile/src/features/threads/CollapsibleUserMessageBody.tsx @@ -0,0 +1,76 @@ +import { T } from "gt-react-native"; +import { useId, useLayoutEffect, useRef, useState, type ReactNode } from "react"; +import { + Pressable, + View, + type ColorValue, + type LayoutChangeEvent, + type ViewInstance, +} from "react-native"; +import Svg, { Defs, LinearGradient, Rect, Stop } from "react-native-svg"; +import { AppText as Text } from "../../components/ui/AppText"; + +const FOLDED_HEIGHT = 176; + +// Fold only when opening at least doubles what is on screen, matching web's useTallEnoughToFold. +const isTallEnoughToFold = (height: number) => height >= FOLDED_HEIGHT * 2; + +export function CollapsibleUserMessageBody(props: { + readonly collapsible: boolean; + readonly expanded: boolean; + readonly onToggle: () => void; + readonly bubbleColor: ColorValue; + readonly children: ReactNode; +}) { + const gradientId = `user-message-fade-${useId().replaceAll(":", "")}`; + const contentRef = useRef(null); + const [tallEnough, setTallEnough] = useState(false); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- the fold depends on the rendered height; measuring before paint avoids one unfolded frame + useLayoutEffect(() => { + const height = contentRef.current?.getBoundingClientRect().height; + if (height !== undefined) setTallEnough(isTallEnoughToFold(height)); + }, []); + const canCollapse = props.collapsible && tallEnough; + const collapsed = canCollapse && !props.expanded; + + return ( + + + { + // Folded, Yoga reports the clipped height, which would read as short and unfold it in a loop. + if (!collapsed) setTallEnough(isTallEnoughToFold(event.nativeEvent.layout.height)); + }} + > + {props.children} + + {collapsed ? ( + + + + + + + + + + + + ) : null} + + {canCollapse ? ( + + + {props.expanded ? Show less : Show full message} + + + ) : null} + + ); +} diff --git a/apps/mobile/src/features/threads/ThreadFeed.tsx b/apps/mobile/src/features/threads/ThreadFeed.tsx index b81aa7aec59aa..6165ac6f2fff3 100644 --- a/apps/mobile/src/features/threads/ThreadFeed.tsx +++ b/apps/mobile/src/features/threads/ThreadFeed.tsx @@ -1,3 +1,4 @@ +import { CollapsibleUserMessageBody } from "./CollapsibleUserMessageBody"; import { msg, T, useGT, useLocale, useMessages } from "gt-react-native"; import { m } from "../../i18n/messages"; import { errorDisplayMessage } from "@t3tools/client-runtime/errors"; @@ -1991,6 +1992,7 @@ function renderFeedEntry( readonly onCopyWorkRow: (rowId: string, value: string) => void; readonly onToggleWorkGroup: (groupId: string, anchorKey?: string) => void; readonly onToggleWorkRow: (rowId: string, anchorKey?: string, groupId?: string) => void; + readonly onToggleUserMessage: (rowId: string, anchorKey: string) => void; readonly onToggleTurnFold: (runId: RunId) => void; readonly onOpenTurnDiff: (checkpoint: ThreadCheckpointSummary) => void; readonly onPressPreview: (source: FilePreviewSource) => void; @@ -2551,16 +2553,25 @@ function renderFeedEntry( - + + props.onToggleUserMessage(`message:${message.id}`, entry.id) + } + bubbleColor={userBubbleColor} + > + + ) : null} @@ -4121,6 +4132,20 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { }); }; + const onToggleUserMessage = (rowId: string, anchorKey: string) => { + const list = listRef.current; + if (expandedWorkRows[rowId] && list) { + const anchor = list.anchorVisibleContent({ key: anchorKey, hold: false }); + const nextKey = groupedFeed[groupedFeed.findIndex((item) => item.id === anchorKey) + 1]?.id; + // Once the message top is scrolled away, collapse toward it like the web: what follows stays put. + if (anchor && anchor.offset > 0 && nextKey) { + onToggleWorkRow(rowId, nextKey); + return; + } + } + onToggleWorkRow(rowId, anchorKey); + }; + const onToggleTurnFold = (runId: RunId) => { preserveDisclosurePosition(`run-fold:${runId}`); setInteractionState((current) => { @@ -4260,6 +4285,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { onCopyWorkRow, onToggleWorkGroup, onToggleWorkRow, + onToggleUserMessage, onToggleTurnFold, onOpenTurnDiff, onPressPreview, diff --git a/apps/mobile/src/i18n/translations/de.json b/apps/mobile/src/i18n/translations/de.json index 2b33c6db04ae1..f5a0b37879c52 100644 --- a/apps/mobile/src/i18n/translations/de.json +++ b/apps/mobile/src/i18n/translations/de.json @@ -3992,6 +3992,8 @@ "v": "v" } ], + "43c5fbd02c6f330a": "Weniger anzeigen", + "918cd5477d0c0e9b": "Vollständige Nachricht anzeigen", "74fed222a72f86bc": "Fotomediathek", "f47273372ba4ed5c": "Dateien auswählen", "584c3539b9524b9a": "Anhang hinzufügen", diff --git a/apps/mobile/src/i18n/translations/en.json b/apps/mobile/src/i18n/translations/en.json index fa572328fc871..43344b92f04ec 100644 --- a/apps/mobile/src/i18n/translations/en.json +++ b/apps/mobile/src/i18n/translations/en.json @@ -3993,6 +3993,8 @@ "v": "v" } ], + "43c5fbd02c6f330a": "Show less", + "918cd5477d0c0e9b": "Show full message", "74fed222a72f86bc": "Photo Library", "f47273372ba4ed5c": "Choose Files", "584c3539b9524b9a": "Add attachment", diff --git a/apps/mobile/src/i18n/translations/es.json b/apps/mobile/src/i18n/translations/es.json index 3a4bc17fd3ada..ffa0249acb7c5 100644 --- a/apps/mobile/src/i18n/translations/es.json +++ b/apps/mobile/src/i18n/translations/es.json @@ -3987,6 +3987,8 @@ "v": "v" } ], + "43c5fbd02c6f330a": "Mostrar menos", + "918cd5477d0c0e9b": "Mostrar el mensaje completo", "74fed222a72f86bc": "Fototeca", "f47273372ba4ed5c": "Elegir archivos", "584c3539b9524b9a": "Añadir adjunto", diff --git a/apps/mobile/src/i18n/translations/fr.json b/apps/mobile/src/i18n/translations/fr.json index 4e094c01b5bce..76b6c1fee0d68 100644 --- a/apps/mobile/src/i18n/translations/fr.json +++ b/apps/mobile/src/i18n/translations/fr.json @@ -3987,6 +3987,8 @@ "v": "v" } ], + "43c5fbd02c6f330a": "Afficher moins", + "918cd5477d0c0e9b": "Afficher le message complet", "74fed222a72f86bc": "Photothèque", "f47273372ba4ed5c": "Choisir des fichiers", "584c3539b9524b9a": "Ajouter une pièce jointe", diff --git a/apps/mobile/src/i18n/translations/ja.json b/apps/mobile/src/i18n/translations/ja.json index 261f141b613ef..274edf167b42e 100644 --- a/apps/mobile/src/i18n/translations/ja.json +++ b/apps/mobile/src/i18n/translations/ja.json @@ -3984,6 +3984,8 @@ }, " からの承認" ], + "43c5fbd02c6f330a": "表示を減らす", + "918cd5477d0c0e9b": "メッセージ全体を表示", "74fed222a72f86bc": "写真ライブラリ", "f47273372ba4ed5c": "ファイルを選択", "584c3539b9524b9a": "添付ファイルを追加", diff --git a/apps/mobile/src/i18n/translations/ko.json b/apps/mobile/src/i18n/translations/ko.json index e21d3b00822af..d0d37ca80f4e9 100644 --- a/apps/mobile/src/i18n/translations/ko.json +++ b/apps/mobile/src/i18n/translations/ko.json @@ -3988,6 +3988,8 @@ }, "의 승인" ], + "43c5fbd02c6f330a": "간략히 보기", + "918cd5477d0c0e9b": "전체 메시지 표시", "74fed222a72f86bc": "사진 보관함", "f47273372ba4ed5c": "파일 선택", "584c3539b9524b9a": "첨부 파일 추가", diff --git a/apps/mobile/src/i18n/translations/pt-BR.json b/apps/mobile/src/i18n/translations/pt-BR.json index 6c7cdf3098bd4..ec401f9fa194a 100644 --- a/apps/mobile/src/i18n/translations/pt-BR.json +++ b/apps/mobile/src/i18n/translations/pt-BR.json @@ -3987,6 +3987,8 @@ "v": "v" } ], + "43c5fbd02c6f330a": "Mostrar menos", + "918cd5477d0c0e9b": "Mostrar mensagem completa", "74fed222a72f86bc": "Biblioteca de Fotos", "f47273372ba4ed5c": "Escolher arquivos", "584c3539b9524b9a": "Adicionar anexo", diff --git a/apps/mobile/src/i18n/translations/ru.json b/apps/mobile/src/i18n/translations/ru.json index 3c74c7fe4be49..44db80a8f6808 100644 --- a/apps/mobile/src/i18n/translations/ru.json +++ b/apps/mobile/src/i18n/translations/ru.json @@ -4041,6 +4041,8 @@ "v": "v" } ], + "43c5fbd02c6f330a": "Показать меньше", + "918cd5477d0c0e9b": "Показать сообщение полностью", "74fed222a72f86bc": "Медиатека", "f47273372ba4ed5c": "Выбрать файлы", "584c3539b9524b9a": "Добавить вложение", diff --git a/apps/mobile/src/i18n/translations/sv.json b/apps/mobile/src/i18n/translations/sv.json index e393eb249899f..e62b0c05509d9 100644 --- a/apps/mobile/src/i18n/translations/sv.json +++ b/apps/mobile/src/i18n/translations/sv.json @@ -3993,6 +3993,8 @@ "v": "v" } ], + "43c5fbd02c6f330a": "Visa mindre", + "918cd5477d0c0e9b": "Visa hela meddelandet", "74fed222a72f86bc": "Bildbibliotek", "f47273372ba4ed5c": "Välj filer", "584c3539b9524b9a": "Lägg till bilaga", diff --git a/apps/mobile/src/i18n/translations/zh.json b/apps/mobile/src/i18n/translations/zh.json index be595b718cbac..9a358e7b617fc 100644 --- a/apps/mobile/src/i18n/translations/zh.json +++ b/apps/mobile/src/i18n/translations/zh.json @@ -3990,6 +3990,8 @@ }, " 的批准" ], + "43c5fbd02c6f330a": "收起", + "918cd5477d0c0e9b": "显示完整消息", "74fed222a72f86bc": "照片图库", "f47273372ba4ed5c": "选择文件", "584c3539b9524b9a": "添加附件", diff --git a/apps/mobile/src/lib/filePreview.test.ts b/apps/mobile/src/lib/filePreview.test.ts index 43322f8ad148e..b93913c00da55 100644 --- a/apps/mobile/src/lib/filePreview.test.ts +++ b/apps/mobile/src/lib/filePreview.test.ts @@ -300,6 +300,9 @@ vi.mock("../features/threads/LinkRequestCard", () => ({ LinkRequestCard: () => n vi.mock("../features/threads/worktree-setup-card", () => ({})); vi.mock("../features/threads/CopyTextButton", () => ({ CopyTextButton: () => null })); vi.mock("../features/threads/thread-work-log", () => ({ THREAD_DISCLOSURE_TRANSITION_MS: 100 })); +vi.mock("../features/threads/CollapsibleUserMessageBody", () => ({ + CollapsibleUserMessageBody: (props: { children: ReactNode }) => props.children, +})); vi.mock("../features/threads/HtmlRenderWebView", () => ({})); vi.mock("../features/threads/McpAppWebView", () => ({})); vi.mock("../features/layout/AdaptiveWorkspaceLayout", () => ({ From 3c08684f1deb7aa19e2a6440161d2e600ae215f8 Mon Sep 17 00:00:00 2001 From: Eightsheet <148897140+Eightsheet@users.noreply.github.com> Date: Thu, 19 Nov 2026 20:35:10 +0100 Subject: [PATCH 05/97] fix(client-runtime): CamelCase account names get distinct badge initials (#35343) Co-authored-by: Julius Marminge --- .../src/state/providerInstanceDisplay.test.ts | 7 ++++++- .../src/state/providerInstanceDisplay.ts | 15 +++++++++------ 2 files changed, 15 insertions(+), 7 deletions(-) diff --git a/packages/client-runtime/src/state/providerInstanceDisplay.test.ts b/packages/client-runtime/src/state/providerInstanceDisplay.test.ts index 4ac36acedf761..161e6113c03bd 100644 --- a/packages/client-runtime/src/state/providerInstanceDisplay.test.ts +++ b/packages/client-runtime/src/state/providerInstanceDisplay.test.ts @@ -12,13 +12,18 @@ const codex = ProviderDriverKind.make("codex"); const acpRegistry = ProviderDriverKind.make("acpRegistry"); describe("providerInstanceInitials", () => { - it("treats punctuation as a word break but keeps apostrophes between letters", () => { + it("treats punctuation and camel-case humps as word breaks but keeps apostrophes between letters", () => { expect(providerInstanceInitials("Codex (hub)")).toBe("CH"); expect(providerInstanceInitials("work_codex")).toBe("WC"); expect(providerInstanceInitials("Theo's Codex")).toBe("TC"); expect(providerInstanceInitials("Codex 'hub'")).toBe("CH"); expect(providerInstanceInitials("‘hub’")).toBe("HU"); expect(providerInstanceInitials("(hub)")).toBe("HU"); + expect(providerInstanceInitials("ClaudeProx")).toBe("CP"); + expect(providerInstanceInitials("ClaudeAPI")).toBe("CA"); + expect(providerInstanceInitials("API")).toBe("AP"); + expect(providerInstanceInitials("ClaudeProx Work")).toBe("CW"); + expect(providerInstanceInitials("(ClaudeProx)")).toBe("CP"); }); it("keeps an emoji whole instead of splitting its surrogate pair", () => { diff --git a/packages/client-runtime/src/state/providerInstanceDisplay.ts b/packages/client-runtime/src/state/providerInstanceDisplay.ts index ad69b7275342b..ba090beb3fd36 100644 --- a/packages/client-runtime/src/state/providerInstanceDisplay.ts +++ b/packages/client-runtime/src/state/providerInstanceDisplay.ts @@ -29,12 +29,15 @@ export function resolveProviderInstanceDisplayName( export function providerInstanceInitials(label: string): string { // Punctuation separates words so "Codex (hub)" reads CH, not C(. An apostrophe // inside a word stays ("Theo's Codex" is TC); a quoting one does not - // ("Codex 'hub'" is CH). - const words = label - .replace(/[^\P{P}'’]+/gu, " ") - .split(/\s+/u) - .map((word) => word.replace(/^['’]+|['’]+$/gu, "")) - .filter(Boolean); + // ("Codex 'hub'" is CH). A single camel-case word splits at its humps, so + // "ClaudeProx" is CP, but "ClaudeProx Work" keeps its own words and is CW. + const toWords = (text: string) => + text + .split(/\s+/u) + .map((word) => word.replace(/^['’]+|['’]+$/gu, "")) + .filter(Boolean); + let words = toWords(label.replace(/[^\P{P}'’]+/gu, " ")); + if (words.length === 1) words = toWords(words[0]!.replace(/(\p{Ll})(\p{Lu})/gu, "$1 $2")); if (words.length === 0) return ""; if (words.length === 1) return Array.from(words[0]!).slice(0, 2).join("").toUpperCase(); return words From 5533151d779ca3969a5615381a5526712f0ebb14 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 19 Nov 2026 11:37:27 -0800 Subject: [PATCH 06/97] fix(server): delegated completion wakes name the child thread (#39297) --- .../DelegatedCompletionDelivery.test.ts | 11 +++++++++-- apps/server/src/orchestration-v2/Orchestrator.ts | 4 +++- 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts b/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts index 23b3deb1184c4..fd677a079d1d3 100644 --- a/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts +++ b/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts @@ -872,7 +872,14 @@ it.layer(layerTest)("delegated completion delivery repairs", (it) => { runId, nodeId: id, occurredAt: now, - payload: { ...task, id, result, status, title: "Inspect regression" }, + payload: { + ...task, + id, + result, + status, + title: "Inspect regression", + childThreadId: ThreadId.make(`thread:inline-budget-child:${id}`), + }, })), }); yield* orchestrator.dispatch({ @@ -898,7 +905,7 @@ it.layer(layerTest)("delegated completion delivery repairs", (it) => { const deferredTaskId = testCase.inlineFirst ? secondTaskId : firstTaskId; assert.include( message.text, - `Delegated task ${deferredTaskId} (Inspect regression) [${testCase.inlineFirst ? "cancelled" : "failed"}]`, + `Delegated task ${deferredTaskId} (Inspect regression) in child thread thread:inline-budget-child:${deferredTaskId} [${testCase.inlineFirst ? "cancelled" : "failed"}]`, ); assert.include(message.text, `Use task_status with taskId ${deferredTaskId}`); assert.deepEqual(message.delegatedCompletion?.taskIds, [firstTaskId, secondTaskId]); diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 6a72d8a6a7f58..b8e6a869dd17d 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -953,7 +953,9 @@ function delegatedCompletionWakeDetail( return taskIds .map((taskId) => { const task = tasks.find((candidate) => candidate.id === taskId); - const label = `Delegated task ${taskId}${task?.title == null ? "" : ` (${task.title})`}${task === undefined ? " reached a terminal state" : ` [${task.status}]`}`; + // A follow-up gets a fresh task id; the child thread links it to the task delegate_task returned. + const thread = task?.childThreadId == null ? "" : ` in child thread ${task.childThreadId}`; + const label = `Delegated task ${taskId}${task?.title == null ? "" : ` (${task.title})`}${thread}${task === undefined ? " reached a terminal state" : ` [${task.status}]`}`; if (task?.result != null) { const detail = `${label}:\n${task.result}`; const bytes = Buffer.byteLength(detail); From 4e3966424802d5c8bc97fc94ceb631adac5d0e05 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 19 Nov 2026 11:38:48 -0800 Subject: [PATCH 07/97] fix(server): preview_resize sizes hidden desktop tabs without a snapshot (#39269) --- apps/server/src/preview/ServerBrowser.test.ts | 5 +++++ apps/server/src/preview/ServerBrowser.ts | 21 ++++++++++++++++++- 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/apps/server/src/preview/ServerBrowser.test.ts b/apps/server/src/preview/ServerBrowser.test.ts index f345bf6f150e6..3bc4eba2f240c 100644 --- a/apps/server/src/preview/ServerBrowser.test.ts +++ b/apps/server/src/preview/ServerBrowser.test.ts @@ -3047,6 +3047,11 @@ it.effect("a desktop tab reports the size the desktop draws after a resize", () expect( yield* resize({ mode: "freeform", width: 900, height: 600 }, 900, 600), ).toBeUndefined(); + // A hidden guest takes the new size only while the desktop paints it, which a capture asks for. + expect(cdp.send).toHaveBeenCalledWith( + "Page.captureScreenshot", + expect.objectContaining({ clip: expect.anything() }), + ); desktopSizeAnswer = null; expect(yield* resize({ mode: "freeform", width: 1280, height: 760 }, 1280, 760)).toEqual({ width: 1280, diff --git a/apps/server/src/preview/ServerBrowser.ts b/apps/server/src/preview/ServerBrowser.ts index 0960faa3a30bf..0a0dad06fb50d 100644 --- a/apps/server/src/preview/ServerBrowser.ts +++ b/apps/server/src/preview/ServerBrowser.ts @@ -126,6 +126,12 @@ const AGENT_CURSOR_CLICK_LEAD_MS = 40; const DESKTOP_VIEWPORT_READ_TIMEOUT = "1 second"; /** A desktop page that keeps its size draws nothing on a resize, so the wait gives up. */ const DESKTOP_RESIZE_WAIT_MS = 1000; +/** Answered only once the guest paints a frame; one pixel keeps it cheap. */ +const DESKTOP_PAINT_CAPTURE = { + format: "jpeg", + quality: 1, + clip: { x: 0, y: 0, width: 1, height: 1, scale: 1 }, +} as const; // A revealed tab's client opens the panel and attaches its stream a few round trips later, remote ones included. const REVEAL_VIEWER_WAIT_MS = 1000; // A desktop panel's shown report waits on the renderer's layout, which a busy machine can push past a second. @@ -2827,7 +2833,20 @@ const make = Effect.gen(function* () { // The desktop draws the new size after the session update; its page resize says it has. // Half the time left keeps room for the read, which runs even if nothing was drawn, // because a page can keep another size than the one asked for. - if (changed) await within(drawn, Math.min(DESKTOP_RESIZE_WAIT_MS, remainingMs() / 2)); + if (changed) { + // Electron resizes no hidden guest it does not paint; a pending capture makes the desktop paint it. + let waiting = true; + void (async () => { + while (waiting && !tab.closing) { + await tab.cdp.send("Page.captureScreenshot", DESKTOP_PAINT_CAPTURE); + } + })().catch(constVoid); + try { + await within(drawn, Math.min(DESKTOP_RESIZE_WAIT_MS, remainingMs() / 2)); + } finally { + waiting = false; + } + } const changes = tab.desktopViewportChanges; const measured = await within(measureDesktopViewport(tab), remainingMs()); // Only a read after the draw, with no page resize or load during it, measures this resize. From 7922611cee5dcffaeaf37f60ea5ce99d2f2df696 Mon Sep 17 00:00:00 2001 From: loosekite Date: Fri, 20 Nov 2026 03:42:39 +0800 Subject: [PATCH 08/97] fix(i18n): correct wrong and ambiguous Simplified Chinese strings (#37978) Co-authored-by: T3 Code Co-authored-by: maria-rcks Co-authored-by: Julius Marminge --- apps/marketing/src/i18n/zh.ts | 4 ++-- apps/mobile/src/i18n/translations/zh.json | 2 +- apps/web/src/i18n/translations/zh.json | 4 ++-- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/apps/marketing/src/i18n/zh.ts b/apps/marketing/src/i18n/zh.ts index dd57a9414be7b..09abf6efd0a8e 100644 --- a/apps/marketing/src/i18n/zh.ts +++ b/apps/marketing/src/i18n/zh.ts @@ -11,7 +11,7 @@ export const zh: Messages = { starsLabel: "在 GitHub 上为 T3 Code 加星标,已有 {stars} 个星标", githubStars: "{stars} GitHub 星标", language: "语言", - mitLicensed: "MIT 许可", + mitLicensed: "MIT 许可证", iosApp: "iOS 应用", androidApp: "Android 应用", terms: "条款", @@ -29,7 +29,7 @@ export const zh: Messages = { downloadForLinux: "下载 Linux 版", downloadForIos: "下载 iOS 版", downloadForAndroid: "下载 Android 版", - sourceLink: "来偷我们的代码(合法的)", + sourceLink: "来偷我们的代码(合法地)", alsoOnPhone: "手机上也能用:", screenshotAlt: "T3 Code 在同一个线程中运行 Claude、Codex、Muse 和 Gemini 子智能体", endorsementsTitle: "超过 {users} 名开发者觉得还行", diff --git a/apps/mobile/src/i18n/translations/zh.json b/apps/mobile/src/i18n/translations/zh.json index 9a358e7b617fc..f70973a639e22 100644 --- a/apps/mobile/src/i18n/translations/zh.json +++ b/apps/mobile/src/i18n/translations/zh.json @@ -3441,7 +3441,7 @@ "bd7ace2d408d814b": "T3 账户", "1a07e4d043f5df4e": "连接", "1be65659f947b808": "没有与“{query}”匹配的设置。", - "1cf216566c1ee064": "项目不可用", + "1cf216566c1ee064": "不可用的项目", "2632f324dc2d9c48": "智能体", "58058320796d28f6": "代码", "2a546119bf3879ee": "归档", diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index 4a7cd89260f3f..beea2b7210a2a 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -5747,7 +5747,7 @@ "b6a29fff7c7c0808": "无", "54420465784bb1bd": "加载较早的评论", "9d82ebf35bfb4043": "这里还没有任何动态。", - "1cf216566c1ee064": "项目不可用", + "1cf216566c1ee064": "不可用的项目", "b5ddadeb0810688c": "状态", "93c1fc19d9bf1db0": "参与方式", "2160067266a61dd8": "任意", @@ -9700,7 +9700,7 @@ "62d8f823deedf316": "并排", "7e8c995646a967d3": "直接退出", "51497bd401292062": "长按", - "9d6cc6ac23312071": "按两次", + "9d6cc6ac23312071": "连按两次", "f001fa7b329c8fbf": "隐藏成功的调用", "ad208e3e32c85029": "全部隐藏", "c80e4bb3201efd71": "专注模式", From 0240eac9dad58b5e922e96a3093874332d38d707 Mon Sep 17 00:00:00 2001 From: cosier <86030128+matthewcosier@users.noreply.github.com> Date: Fri, 20 Nov 2026 06:44:40 +1100 Subject: [PATCH 09/97] fix(server): images that ACP agents read show a preview (#37468) Co-authored-by: Julius Marminge --- apps/server/scripts/acp-mock-agent.ts | 10 +++++++ .../Adapters/AcpAdapterV2.test.ts | 26 +++++++++++++++---- packages/provider-acp/src/server/adapter.ts | 7 +++++ 3 files changed, 38 insertions(+), 5 deletions(-) diff --git a/apps/server/scripts/acp-mock-agent.ts b/apps/server/scripts/acp-mock-agent.ts index 762df4227b28e..fe97d392b5d3e 100644 --- a/apps/server/scripts/acp-mock-agent.ts +++ b/apps/server/scripts/acp-mock-agent.ts @@ -1322,6 +1322,16 @@ const program = Effect.gen(function* () { rawInput: { path: "src/env.ts" }, locations: [{ path: "src/env.ts" }], }, + // Antigravity reports an image read with only a text result, never the image bytes. + { + sessionUpdate: "tool_call_update", + toolCallId: "structured-image-read", + title: "Read `mockup.png`", + kind: "read", + status: "completed", + rawInput: { file_path: "/workspace/mockup.png", start_line: 0, end_line: 799 }, + rawOutput: "View mockup.png", + }, { sessionUpdate: "tool_call_update", toolCallId: "structured-search", diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts index e869b2f6ebbb5..cc56b4c29abdf 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts @@ -4645,11 +4645,27 @@ describe("AcpAdapterV2", () => { item.changes[0]?.oldPath === "/workspace/old.ts", ), ); - const read = items.find((item) => item.type === "dynamic_tool" && item.toolName === "Read"); - assert.deepEqual( - read?.type === "dynamic_tool" ? { title: read.title, input: read.input } : null, - { title: "Read src/env.ts", input: { path: "src/env.ts" } }, - ); + const readItem = (nativeId: string) => { + const item = items.findLast( + (candidate) => + candidate.type === "dynamic_tool" && + candidate.toolName === "Read" && + candidate.nativeItemRef?.nativeId?.endsWith(nativeId) === true, + ); + return item?.type === "dynamic_tool" + ? { title: item.title, input: item.input, viewedImagePath: item.viewedImagePath } + : null; + }; + assert.deepEqual(readItem("structured-read"), { + title: "Read src/env.ts", + input: { path: "src/env.ts" }, + viewedImagePath: undefined, + }); + assert.deepEqual(readItem("structured-image-read"), { + title: "Read /workspace/mockup.png", + input: { file_path: "/workspace/mockup.png", start_line: 0, end_line: 799 }, + viewedImagePath: "/workspace/mockup.png", + }); const search = items.find((item) => item.type === "file_search"); assert.deepEqual( search?.type === "file_search" ? { title: search.title, pattern: search.pattern } : null, diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index 108156b8e0a66..3e0864054c32f 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -70,6 +70,7 @@ import type * as EffectAcpProtocol from "effect-acp/protocol"; import type * as EffectAcpSchema from "effect-acp/compat"; import { formatReadToolLabel, formatSearchToolLabel } from "@t3tools/shared/toolActivity"; +import { isWorkspaceImagePreviewPath } from "@t3tools/shared/mediaPreview"; import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost"; import { makeAcpMcpOverAcpBridge, type AcpMcpOverAcpBridge } from "./mcpOverAcpBridge.ts"; import { mcpToolPresentation } from "@t3tools/provider-core/server/mcpToolPresentation"; @@ -4724,6 +4725,12 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( title: path ? formatReadToolLabel(path) : (title ?? "Read file"), type: "dynamic_tool", toolName: "Read", + ...(path !== undefined && + path.length <= 4096 && + !/[\r\n]/.test(path) && + isWorkspaceImagePreviewPath(path) + ? { viewedImagePath: path } + : {}), input: path === undefined || ["path", "filePath", "file_path"].some((key) => rawInputRecord?.[key] === path) From cdf5a6c0fc9f0ad68bc2bd462a5f7ce626fdd622 Mon Sep 17 00:00:00 2001 From: YouJiaXing <287009007@qq.com> Date: Fri, 20 Nov 2026 03:45:25 +0800 Subject: [PATCH 10/97] fix(antigravity): allow compaction when the runtime advertises it (#37020) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: 尤嘉兴 Co-authored-by: Julius Marminge --- .../Adapters/AntigravityAdapterV2.test.ts | 81 ++++++++++++++++--- .../Adapters/AntigravityAdapterV2.ts | 3 +- docs/user/providers-antigravity.md | 5 +- 3 files changed, 72 insertions(+), 17 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts index 32d6b8172abf2..5aed140fde08c 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts @@ -317,16 +317,23 @@ describe("AntigravityAdapterV2 harness recovery", () => { }); describe("AntigravityAdapterV2 compaction", () => { - it.live.each([false, true])( - "negotiates native goals (%s) without enabling manual compaction", - (nativeGoals) => + it.live.each([ + { nativeGoals: false, compact: false }, + { nativeGoals: true, compact: false }, + { nativeGoals: false, compact: true }, + ])( + "negotiates native goals ($nativeGoals) and advertised compaction ($compact)", + ({ nativeGoals, compact }) => Effect.gen(function* () { const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; const crypto = yield* SecureRandom.SecureRandom; const mockAgentPath = yield* path.fromFileUrl( new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), ); + const logs = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-ag-compact-" }); + const requestLog = path.join(logs, "requests.ndjson"); const instanceId = ProviderInstanceId.make("antigravity-compaction-test"); const goalSupport = yield* Ref.make(false); const startupMilestone = yield* Deferred.make(); @@ -346,7 +353,11 @@ describe("AntigravityAdapterV2 compaction", () => { command: process.execPath, args: [mockAgentPath], cwd: input.cwd, - env: { T3_ACP_ANTIGRAVITY: "1" }, + env: { + T3_ACP_ANTIGRAVITY: "1", + T3_ACP_AVAILABLE_COMMANDS: compact ? "compact" : "", + T3_ACP_REQUEST_LOG_PATH: requestLog, + }, }, }).pipe( Effect.provideService(SecureRandom.SecureRandom, crypto), @@ -375,28 +386,72 @@ describe("AntigravityAdapterV2 compaction", () => { ) : Effect.void, }); + const threadId = ThreadId.make("thread-antigravity-compaction"); + const modelSelection = { instanceId, model: "gemini-test-low" } as const; + const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd: process.cwd(), + }); const opening = yield* adapter .openSession({ - threadId: ThreadId.make("thread-antigravity-compaction"), + threadId, providerSessionId: ProviderSessionId.make("provider-session-antigravity-compaction"), - modelSelection: { instanceId, model: "gemini-test-low" }, - runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ - runtimeMode: "full-access", - interactionMode: "default", - cwd: process.cwd(), - }), + modelSelection, + runtimePolicy, }) .pipe(Effect.forkScoped); yield* Deferred.await(startupMilestone); yield* Deferred.succeed(consumeStartupCommands, undefined); const session = yield* Fiber.join(opening); assert.deepEqual(yield* Ref.get(workspaceCommands), { - names: ["plan", "logout"], + names: compact ? ["compact"] : ["plan", "logout"], cwd: process.cwd(), }); - assert.isUndefined(session.compactThread); + const compactThread = session.compactThread; + assert.isDefined(compactThread); assert.equal(session.providerSession.capabilities.turns.supportsNativeGoals, nativeGoals); assert.equal((yield* adapter.getCapabilities()).turns.supportsNativeGoals, nativeGoals); + const providerThread = yield* session.ensureThread({ + threadId, + modelSelection, + runtimePolicy, + }); + const turnInput = makeTurnInput({ + threadId, + providerThread, + instanceId, + modelSelection, + runtimePolicy, + now: yield* DateTime.now, + messageText: "Compact the conversation.", + }); + if (compact) { + yield* compactThread!(turnInput); + const events = yield* session.events.pipe( + Stream.takeUntil((event) => event.type === "turn.terminal"), + Stream.runCollect, + ); + assert.isTrue( + events.some( + (event) => + event.type === "turn_item.updated" && + event.turnItem.type === "compaction" && + event.turnItem.status === "completed", + ), + ); + } else { + const error = yield* compactThread!(turnInput).pipe(Effect.flip); + assert.instanceOf(error, ProviderAdapter.ProviderAdapterTurnStartError); + assert.instanceOf(error.cause, ProviderAdapter.ProviderCompactionUnsupportedError); + } + const prompts = (yield* fileSystem.readFileString(requestLog)) + .trim() + .split("\n") + .map((line) => JSON.parse(line) as { method?: string; params?: { prompt?: unknown } }) + .filter((request) => request.method === "session/prompt") + .map((request) => request.params?.prompt); + assert.deepEqual(prompts, compact ? [[{ type: "text", text: "/compact" }]] : []); }).pipe(Effect.provide(layerSession)), ); }); diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts index 21dcd613b55e9..6f25f207fcc33 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts @@ -294,8 +294,7 @@ export function makeAntigravityAcpAdapterFlavor( normalizeToolCall: normalizeAntigravityToolCall, extractSubagentUpdate: extractAntigravitySubagentUpdate, supportsImagePrompts: true, - // ACP 1.3.0 treats /compact as ordinary model input. - supportsCompaction: false, + compactViaAdvertisedCommand: true, requiresSignIn: isAntigravitySignInRequiredError, // Antigravity can leave a prompt open without updates; long tools and approvals pause this. promptInactivityTimeout: "15 minutes", diff --git a/docs/user/providers-antigravity.md b/docs/user/providers-antigravity.md index c22a20a2ca540..8935439c0a63d 100644 --- a/docs/user/providers-antigravity.md +++ b/docs/user/providers-antigravity.md @@ -98,8 +98,9 @@ Antigravity. Antigravity cannot rewind its own conversation, so the next turn starts a fresh Antigravity session and T3 Code sends it the kept conversation, without the turns you removed. -Manual context compaction is unavailable through Antigravity's ACP runtime, even -though its CLI has `/compact`. Send `/clear` when you need a fresh context. +Use `/compact` to summarize a long conversation when your Antigravity runtime +offers that command. If it is unavailable, update Antigravity in provider settings +or send `/clear` when you need a fresh context. ### Skills and attachments From 031dd1a818c348353ff96dc42b81b6697701ecc7 Mon Sep 17 00:00:00 2001 From: Your Open Source Tooling Specialist <121191527+bettercallcaleb@users.noreply.github.com> Date: Thu, 19 Nov 2026 14:49:33 -0500 Subject: [PATCH 11/97] fix(ssh): report missing tar or gzip before downloading remote runtime (#35307) Signed-off-by: bettercallcaleb <121191527+bettercallcaleb@users.noreply.github.com> Co-authored-by: maria-rcks Co-authored-by: Julius Marminge --- packages/ssh/src/tunnel.test.ts | 39 +++++++++++++++++++++++++++++++++ packages/ssh/src/tunnel.ts | 4 ++++ 2 files changed, 43 insertions(+) diff --git a/packages/ssh/src/tunnel.test.ts b/packages/ssh/src/tunnel.test.ts index 6047f4d1b3125..ca7b4ce85ac51 100644 --- a/packages/ssh/src/tunnel.test.ts +++ b/packages/ssh/src/tunnel.test.ts @@ -448,6 +448,45 @@ describe("ssh tunnel scripts", () => { } }); + it("names missing tar before downloading the release archive", () => { + const root = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-ssh-runner-")); + try { + const bin = NodePath.join(root, "bin"); + const home = NodePath.join(root, "home"); + NodeFS.mkdirSync(bin); + NodeFS.mkdirSync(home); + for (const tool of ["sh", "mkdir", "mktemp", "cat", "rm"]) { + NodeFS.symlinkSync( + NodeChildProcess.execFileSync("sh", ["-c", `command -v ${tool}`], { + encoding: "utf8", + }).trim(), + NodePath.join(bin, tool), + ); + } + NodeFS.writeFileSync( + NodePath.join(bin, "uname"), + '#!/bin/sh\ncase "$1" in -s) echo Linux ;; -m) echo x86_64 ;; esac\n', + { mode: 0o755 }, + ); + NodeFS.writeFileSync( + NodePath.join(bin, "curl"), + '#!/bin/sh\necho "download attempt" >&2\nexit 1\n', + { mode: 0o755 }, + ); + const runner = NodePath.join(root, "run-t3.sh"); + NodeFS.writeFileSync(runner, SshTunnel.buildRemoteT3RunnerScript(ARCHIVE)); + const result = NodeChildProcess.spawnSync(NodePath.join(bin, "sh"), [runner, "--version"], { + encoding: "utf8", + env: { HOME: home, PATH: bin }, + }); + assert.notEqual(result.status, 0); + assert.include(result.stderr, "needs tar"); + assert.notInclude(result.stderr, "download attempt"); + } finally { + NodeFS.rmSync(root, { recursive: true, force: true }); + } + }); + it.effect("accepts launch JSON after remote shell startup noise", () => { const target = { alias: "devbox", diff --git a/packages/ssh/src/tunnel.ts b/packages/ssh/src/tunnel.ts index cd0593f04f6b6..522fb23625286 100644 --- a/packages/ssh/src/tunnel.ts +++ b/packages/ssh/src/tunnel.ts @@ -533,6 +533,10 @@ if ! t3_runtime_ready; then *) printf 'Remote host %s has no t3 release archive.\\n' "$(uname -s) $(uname -m)" >&2; exit 1 ;; esac T3_ARCHIVE="t3-$T3_ARCHIVE_VERSION-$T3_PLATFORM_KEY.tar.gz" + if ! command -v tar >/dev/null 2>&1; then + printf 'Remote host needs tar to unpack %s. Install tar on it and try again.\\n' "$T3_ARCHIVE" >&2 + exit 1 + fi T3_STAGING="$(mktemp -d "$HOME/.t3/runtime/versions/.staging-XXXXXX")" trap 'rm -rf "$T3_STAGING" "$T3_LOCK"' EXIT t3_fetch() { From 44e3f42e6915806275539871c10f2c18c6543f80 Mon Sep 17 00:00:00 2001 From: Martin Bergo Date: Thu, 19 Nov 2026 20:53:53 +0100 Subject: [PATCH 12/97] fix(server): starting a native subagent no longer records a failed projection read span (#39284) Co-authored-by: mInrOz <14320143+mInrOz@users.noreply.github.com> Co-authored-by: Julius Marminge --- .../ProviderEventIngestor.test.ts | 33 ++++++++++++++----- .../orchestration-v2/ProviderEventIngestor.ts | 6 +--- 2 files changed, 26 insertions(+), 13 deletions(-) diff --git a/apps/server/src/orchestration-v2/ProviderEventIngestor.test.ts b/apps/server/src/orchestration-v2/ProviderEventIngestor.test.ts index 7aa18f0956e39..938ad7e81eec5 100644 --- a/apps/server/src/orchestration-v2/ProviderEventIngestor.test.ts +++ b/apps/server/src/orchestration-v2/ProviderEventIngestor.test.ts @@ -37,6 +37,7 @@ import * as Schema from "effect/Schema"; import * as SqlClient from "effect/sql/SqlClient"; import * as SqlError from "effect/sql/SqlError"; import * as Stream from "effect/Stream"; +import * as Tracer from "effect/Tracer"; import { toolOutputImages } from "@t3tools/shared/toolOutput"; import * as SqlitePersistence from "../persistence/Sqlite.ts"; @@ -1920,16 +1921,32 @@ layer("ProviderEventIngestorV2", (it) => { threadId: rootEvent.threadId, }); - const threadEvents = yield* ingestor.normalize({ - providerSessionId, - providerInstanceId: modelSelection.instanceId, - threadId: rootEvent.threadId, - event: { - type: "app_thread.created", - driver: CODEX_DRIVER, - appThread: childThread, + const failedSpans: Array = []; + const tracer = Tracer.make({ + span(options) { + const span = new Tracer.NativeSpan(options); + const end = span.end.bind(span); + span.end = (time, exit) => { + end(time, exit); + if (Exit.isFailure(exit)) failedSpans.push(span.name); + }; + return span; }, }); + const threadEvents = yield* ingestor + .normalize({ + providerSessionId, + providerInstanceId: modelSelection.instanceId, + threadId: rootEvent.threadId, + event: { + type: "app_thread.created", + driver: CODEX_DRIVER, + appThread: childThread, + }, + }) + .pipe(Effect.withTracer(tracer)); + // A new child's existence check expects a miss; a failed span there reads as an error in Tempo. + assert.deepEqual(failedSpans, []); const messageEvents = yield* ingestor.normalize({ providerSessionId, providerInstanceId: modelSelection.instanceId, diff --git a/apps/server/src/orchestration-v2/ProviderEventIngestor.ts b/apps/server/src/orchestration-v2/ProviderEventIngestor.ts index 45ed0d1c78180..e036bbe8994c1 100644 --- a/apps/server/src/orchestration-v2/ProviderEventIngestor.ts +++ b/apps/server/src/orchestration-v2/ProviderEventIngestor.ts @@ -471,11 +471,7 @@ export const layer: Layer.Layer< switch (input.event.type) { case "app_thread.created": { const offered = input.event.appThread; - const existing = yield* projections.getThread(offered.id).pipe( - Effect.catchTags({ - ProjectionStoreThreadNotFoundError: () => Effect.succeed(null), - }), - ); + const existing = yield* projections.findThread(offered.id); if ( existing !== null && (input.event.createOnly === true || From a4d015170024ea4fa9c8e06ddf0a32e04972c9b9 Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Thu, 19 Nov 2026 20:56:23 +0100 Subject: [PATCH 13/97] fix: match dotted capital I in Find in Thread (#39290) Co-authored-by: Julius Marminge --- packages/shared/src/threadSearch.test.ts | 7 ++++ packages/shared/src/threadSearch.ts | 3 +- ...hread-find-matches-dotted-capital-i.e2e.ts | 34 +++++++++++++++++++ 3 files changed, 43 insertions(+), 1 deletion(-) create mode 100644 scripts/scenarios/thread-find-matches-dotted-capital-i.e2e.ts diff --git a/packages/shared/src/threadSearch.test.ts b/packages/shared/src/threadSearch.test.ts index fb52b2ec16a29..6f45724a412a7 100644 --- a/packages/shared/src/threadSearch.test.ts +++ b/packages/shared/src/threadSearch.test.ts @@ -17,3 +17,10 @@ it("matches straight and curly apostrophes without changing source offsets", () expect(findThreadSearchOccurrences("don't don’t", "don’t")).toEqual([0, 6]); expect(findThreadSearchOccurrences("İ don‘t", "don't")).toEqual([2]); }); + +it("matches dotted capital I without changing source offsets", () => { + expect(findThreadSearchOccurrences("📍 İstanbul ıstanbul i\u0307stanbul", "istanbul")).toEqual([ + 3, + ]); + expect(findThreadSearchOccurrences("Istanbul istanbul", "İSTANBUL")).toEqual([0, 9]); +}); diff --git a/packages/shared/src/threadSearch.ts b/packages/shared/src/threadSearch.ts index 6ffa12fcc1523..e690cd7dd7ac0 100644 --- a/packages/shared/src/threadSearch.ts +++ b/packages/shared/src/threadSearch.ts @@ -7,7 +7,8 @@ function foldThreadSearchCase(text: string): string { let folded = ""; for (const character of text) { - const loweredCharacter = foldCharacters(character.toLowerCase()); + // Lowercasing İ adds a combining dot. Drop that expansion to preserve source offsets. + const loweredCharacter = foldCharacters(character.toLowerCase()).replace("i\u0307", "i"); folded += loweredCharacter.length === character.length ? loweredCharacter : character; } return folded; diff --git a/scripts/scenarios/thread-find-matches-dotted-capital-i.e2e.ts b/scripts/scenarios/thread-find-matches-dotted-capital-i.e2e.ts new file mode 100644 index 0000000000000..1bdf366646288 --- /dev/null +++ b/scripts/scenarios/thread-find-matches-dotted-capital-i.e2e.ts @@ -0,0 +1,34 @@ +import { expect } from "e2e"; + +import { test, WEB } from "./t3.ts"; + +test("Find in thread matches İstanbul with istanbul", WEB, async ({ t3, app, screen, browser }) => { + const project = await t3.project("demo"); + const thread = await t3.thread({ + project, + title: "Travel notes", + messages: ["Travel notes for İstanbul"], + }); + await t3.open(thread); + await screen.getByRole("button", /^Agent Travel notes for İstanbul/).tap(); + await browser + .locator("[data-user-message-body]") + .getByText("Travel notes for İstanbul", { exact: true }) + .waitFor(); + + await browser.keyboard.press("Control+f"); + await screen.getByRole("searchbox", "Find in thread").fill("istanbul"); + try { + await expect + .poll( + () => + browser.evaluate( + 'document.querySelector("[data-thread-find-bar] span[aria-hidden]")?.textContent ?? ""', + ), + { message: "Find in thread counts İstanbul as a match for istanbul" }, + ) + .toBe("1/1"); + } finally { + await app.screenshot("istanbul-find-result"); + } +}); From 55e379bb96d8cb1223d9faa453e9ed6f04f2c2f7 Mon Sep 17 00:00:00 2001 From: Martin Bergo Date: Thu, 19 Nov 2026 20:57:27 +0100 Subject: [PATCH 14/97] fix(server): the HEAD watch no longer spawns Git in a removed worktree (#39294) Co-authored-by: Martin Bergo <14320143+mInrOz@users.noreply.github.com> Co-authored-by: Julius Marminge --- .../server/src/git/GitWorkflowService.test.ts | 23 +++++++++++++++++++ apps/server/src/git/GitWorkflowService.ts | 6 +++-- 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/apps/server/src/git/GitWorkflowService.test.ts b/apps/server/src/git/GitWorkflowService.test.ts index a90c43daed72a..43b8a32d13e14 100644 --- a/apps/server/src/git/GitWorkflowService.test.ts +++ b/apps/server/src/git/GitWorkflowService.test.ts @@ -56,4 +56,27 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("GitWorkflowServi ), ), ); + + it.effect("reads no HEAD path from a removed worktree without spawning Git", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const parent = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-removed-wt-" }); + const removed = `${parent}/removed`; + const workflow = yield* GitWorkflowService.GitWorkflowService; + assert.strictEqual(yield* workflow.headPath(removed), null); + }).pipe( + Effect.scoped, + Effect.provide( + GitWorkflowService.layer.pipe( + Layer.provide(Layer.mock(VcsDriverRegistry.VcsDriverRegistry)({})), + Layer.provide(Layer.mock(GitManager.GitManager)({})), + Layer.provide( + Layer.mock(GitVcsDriver.GitVcsDriver)({ + execute: (input) => Effect.die(`spawned Git in ${input.cwd}`), + }), + ), + ), + ), + ), + ); }); diff --git a/apps/server/src/git/GitWorkflowService.ts b/apps/server/src/git/GitWorkflowService.ts index 287207840ad6a..f012a65bb0692 100644 --- a/apps/server/src/git/GitWorkflowService.ts +++ b/apps/server/src/git/GitWorkflowService.ts @@ -398,8 +398,10 @@ export const make = Effect.gen(function* () { invalidateRemoteStatus: gitManager.invalidateRemoteStatus, readRefSnapshot: git.readRefSnapshot, invalidateStatus: gitManager.invalidateStatus, - headPath: Effect.fn("GitWorkflowService.headPath")(function (cwd) { - return git + headPath: Effect.fn("GitWorkflowService.headPath")(function* (cwd) { + // Clients keep watching threads whose worktree was removed; spawning there fails noisily. + if (!(yield* fileSystem.exists(cwd).pipe(Effect.orElseSucceed(() => true)))) return null; + return yield* git .execute({ operation: "GitWorkflowService.headPath", cwd, From 9f4d25495d72c1768c000273f2fcca89b91b538f Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 19 Nov 2026 11:59:58 -0800 Subject: [PATCH 15/97] fix(server): whole-word content searches no longer miss matching files (#39285) --- .../workspace/WorkspaceSearchIndex.test.ts | 43 +++++++++++++++++++ .../src/workspace/WorkspaceSearchIndex.ts | 36 ++++++++++++++-- 2 files changed, 75 insertions(+), 4 deletions(-) diff --git a/apps/server/src/workspace/WorkspaceSearchIndex.test.ts b/apps/server/src/workspace/WorkspaceSearchIndex.test.ts index 265a72a98a4aa..421f36df73f68 100644 --- a/apps/server/src/workspace/WorkspaceSearchIndex.test.ts +++ b/apps/server/src/workspace/WorkspaceSearchIndex.test.ts @@ -290,6 +290,8 @@ it.effect("continues whole-word searches after a filtered grep page", () => truncated: false, }); expect(grep).toHaveBeenCalledTimes(2); + expect(grep.mock.calls[0]?.[0]).toBe(String.raw`(?-u)\bneedle\b`); + expect(grep.mock.calls[0]?.[1]?.mode).toBe("regex"); expect(grep.mock.calls[1]?.[1]?.cursor).toBe(nextCursor); }), ).pipe(Effect.provide(testLayer)), @@ -772,3 +774,44 @@ it.live("finds Git-ignored files that a root .ignore re-includes", () => expect(result.entries).toEqual([{ kind: "file", path: "notes/daily/standup.md" }]); }).pipe(Effect.scoped, Effect.provide(testLayer)), ); + +// Real fff: the native whole-word pattern must return what the plain search and the JS word check did. +it.live.each([ + { query: "needle", caseSensitive: true, expected: ["notes.md:1:0-6", "words.ts:2:0-6,8-14"] }, + { query: "NEEDLE", caseSensitive: false, expected: ["notes.md:1:0-6", "words.ts:2:0-6,8-14"] }, + // fff reads `*.ts` as a file constraint, which a regex built around the whole query would lose. + { query: "*.ts needle", caseSensitive: true, expected: ["words.ts:2:0-6,8-14"] }, + // Plain search folds ASCII case only: `ſ` is not an `s`, and the Kelvin sign is not a `k`. + { query: "s", caseSensitive: false, expected: ["fold.txt:2:0-1"] }, + { query: "k", caseSensitive: false, expected: ["fold.txt:4:0-1"] }, +])("matches whole words in a real workspace for $query", ({ query, caseSensitive, expected }) => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-search-whole-word-" }); + yield* fileSystem.writeFileString( + path.join(cwd, "words.ts"), + "needleSuffix\nneedle, needle.\n\u00e9needle\n", + ); + yield* fileSystem.writeFileString(path.join(cwd, "notes.md"), "needle *.ts\n"); + yield* fileSystem.writeFileString(path.join(cwd, "fold.txt"), "\u017f\ns\n\u212a\nk\n"); + + const searchIndex = yield* WorkspaceSearchIndex.make(cwd, "content"); + const result = yield* searchIndex.searchContents({ + query, + limit: 500, + caseSensitive, + wholeWord: true, + useRegex: false, + }); + + expect( + result.matches + .map( + (match) => + `${match.path}:${match.lineNumber}:${match.matchRanges.map((range) => `${range.start}-${range.end}`).join(",")}`, + ) + .toSorted(), + ).toEqual(expected); + }).pipe(Effect.scoped, Effect.provide(testLayer)), +); diff --git a/apps/server/src/workspace/WorkspaceSearchIndex.ts b/apps/server/src/workspace/WorkspaceSearchIndex.ts index 13a54f27e40d6..a5503a50f55b8 100644 --- a/apps/server/src/workspace/WorkspaceSearchIndex.ts +++ b/apps/server/src/workspace/WorkspaceSearchIndex.ts @@ -285,6 +285,28 @@ function buildContentSearchQuery(input: Omit) : { searchQuery: input.query.toLowerCase(), regexMode: false }; } +const ASCII_WORD = /^\w+$/; + +// A whole-word search for an ASCII word asks fff for the word itself, so substring hits are dropped +// natively instead of filling pages with lines the JS check then discards. `-u` keeps `\b` and `i` +// to ASCII: plain search does not fold `ſ` or `K`, and any non-ASCII neighbour stays a candidate. +function buildWholeWordPattern(query: string, caseSensitive: boolean): string { + return `(?${caseSensitive ? "" : "i"}-u)\\b${query}\\b`; +} + +// fff's ranges for that pattern are not used: the JS word check decides, on every hit in the line. +function findWordRanges( + line: string, + word: string, + caseSensitive: boolean, +): Array<{ readonly start: number; readonly end: number }> { + // No `u` flag: with it, `i` would fold `ſ` and `K` onto ASCII letters. + return Array.from(line.matchAll(new RegExp(word, caseSensitive ? "g" : "gi")), (match) => ({ + start: match.index, + end: match.index + match[0].length, + })); +} + function mapContentMatchRanges( line: string, byteRanges: ReadonlyArray, @@ -1318,7 +1340,11 @@ export const make = Effect.fn("WorkspaceSearchIndex.make")(function* ( ); contentIndexPending = false; } - let { searchQuery, regexMode } = buildContentSearchQuery(input); + // fff reads glob and path syntax out of a query even in regex mode, so only a bare word qualifies. + const wholeWordPrefilter = input.wholeWord && !input.useRegex && ASCII_WORD.test(input.query); + let { searchQuery, regexMode } = wholeWordPrefilter + ? { searchQuery: buildWholeWordPattern(input.query, input.caseSensitive), regexMode: true } + : buildContentSearchQuery(input); const deadline = performance.now() + CONTENT_SEARCH_TIME_BUDGET_MS; // Grep cursors advance per file; whole-word filtering needs enough raw candidates before advancing. const rawPageSize = input.wholeWord @@ -1351,9 +1377,11 @@ export const make = Effect.fn("WorkspaceSearchIndex.make")(function* ( for (const match of result.items) { if (isIgnoredPath(ignoredPaths, match.relativePath, hostIsWindows)) continue; - const matchRanges = mapContentMatchRanges(match.lineContent, match.matchRanges).filter( - (range) => !input.wholeWord || isWholeWordRange(match.lineContent, range), - ); + const matchRanges = ( + wholeWordPrefilter + ? findWordRanges(match.lineContent, input.query, input.caseSensitive) + : mapContentMatchRanges(match.lineContent, match.matchRanges) + ).filter((range) => !input.wholeWord || isWholeWordRange(match.lineContent, range)); // fff reports hits past its 512-char lineContent cap with no ranges, so whole words can't be verified there. if (input.wholeWord && matchRanges.length === 0) continue; matches.push({ From 5bc2d512e470ed8f3ea6b5876118d9f3b39c4474 Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Thu, 19 Nov 2026 21:00:48 +0100 Subject: [PATCH 16/97] fix(web): scroll wide tables to the selected Find match (#39295) Co-authored-by: Julius Marminge --- .../chat/MessagesTimeline.browser.test.tsx | 93 +++++++++++++++++++ .../chat/useThreadFindNavigation.ts | 19 +++- .../find-reveals-clipped-table-cell.e2e.ts | 57 ++++++++++++ 3 files changed, 164 insertions(+), 5 deletions(-) create mode 100644 scripts/scenarios/find-reveals-clipped-table-cell.e2e.ts diff --git a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx index 013d478127b47..7dc87ff67cfc7 100644 --- a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx @@ -1841,6 +1841,99 @@ describe("MessagesTimeline thread find", () => { } const released = { source: "command", releasesFollow: true }; + it("reveals the previous match in a table without scrolling a sibling table", async () => { + setup(); + const columns = Array.from({ length: 12 }, (_, index) => `DiagnosticsColumn${index}`); + const cells = ["needle", ...columns.slice(1, -1), "needle"]; + const table = [columns, columns.map(() => "---"), cells] + .map((row) => `| ${row.join(" | ")} |`) + .join("\n"); + const entry = message(`${table}\n\n${table}`); + const props = { + ...baseProps(), + timelineEntries: [entry], + liveFollowEnabled: false, + findOpen: true, + findExpanded: true, + findQuery: "needle", + }; + const element = (occurrence: number, navigationId: number) => ( + + ); + await using screen = await renderElement(element(1, 1)); + const [viewport, sibling] = await vi.waitFor(() => { + const tables = screen.container.querySelectorAll( + '.chat-markdown-table-container [data-slot="scroll-area-viewport"]', + ); + expect(tables).toHaveLength(2); + return [tables[0]!, tables[1]!] as const; + }); + viewport.scrollLeft = viewport.scrollWidth; + sibling.scrollLeft = sibling.scrollWidth; + const siblingOffset = sibling.scrollLeft; + const clip = viewport.getBoundingClientRect(); + expect(viewport.querySelector("td")!.getBoundingClientRect().right).toBeLessThan(clip.left); + expect(siblingOffset).toBeGreaterThan(0); + + await screen.rerender(element(0, 2)); + await vi.waitFor(() => { + const [match] = CSS.highlights.get("t3-thread-find-active") ?? []; + if (!(match instanceof Range)) throw new Error("Missing active match range"); + expect(match.startContainer.parentElement?.closest("td")).toBe(viewport.querySelector("td")); + expect(match.getBoundingClientRect().left).toBeGreaterThanOrEqual(clip.left - 1); + }); + expect(sibling.scrollLeft).toBe(siblingOffset); + }); + + it("reveals a match in a nested table clipped by the outer table", async () => { + setup(); + const columns = Array.from({ length: 12 }, (_, index) => `DiagnosticsColumn${index}`); + const entry = message( + `${columns.join("")}
needle
`, + { role: "assistant" }, + ); + const props = { + ...baseProps(), + timelineEntries: [entry], + liveFollowEnabled: false, + findOpen: true, + findExpanded: true, + findQuery: "needle", + }; + await using screen = await renderElement(); + const outerViewport = await vi.waitFor(() => { + const viewport = screen.container.querySelector( + '.chat-markdown-table-container [data-slot="scroll-area-viewport"]', + ); + const nestedCell = viewport?.querySelector("table table td"); + expect(nestedCell?.textContent).toBe("needle"); + expect(nestedCell!.getBoundingClientRect().left).toBeGreaterThan( + viewport!.getBoundingClientRect().right, + ); + return viewport!; + }); + + await screen.rerender( + , + ); + await vi.waitFor(() => { + const [match] = CSS.highlights.get("t3-thread-find-active") ?? []; + if (!(match instanceof Range)) throw new Error("Missing active match range"); + const bounds = match.getBoundingClientRect(); + const clip = outerViewport.getBoundingClientRect(); + expect(bounds.left).toBeGreaterThanOrEqual(clip.left - 1); + expect(bounds.right).toBeLessThanOrEqual(clip.right + 1); + }); + }); + it("releases follow once when it starts showing a thread whose find is open", async () => { setup(); const { navigations, element } = renderObserved(); diff --git a/apps/web/src/components/chat/useThreadFindNavigation.ts b/apps/web/src/components/chat/useThreadFindNavigation.ts index 054faa23201e0..b4cd75a8036ab 100644 --- a/apps/web/src/components/chat/useThreadFindNavigation.ts +++ b/apps/web/src/components/chat/useThreadFindNavigation.ts @@ -4,6 +4,8 @@ import type { ThreadFindMatch } from "./threadFind"; import { useThreadFindHighlights } from "./threadFindHighlights"; const FIND_MATCH_VIEW_MARGIN = 96; +const FIND_SCROLL_VIEWPORT_SELECTOR = + 'pre, .chat-markdown-table-container [data-slot="scroll-area-viewport"]'; type FindEntries = readonly { readonly id: string }[]; @@ -124,13 +126,20 @@ function revealThreadFindMatch( return; } - const codeScroller = range.startContainer.parentElement?.closest("pre"); - if (codeScroller) { + for ( + let horizontalViewport = range.startContainer.parentElement?.closest( + FIND_SCROLL_VIEWPORT_SELECTOR, + ); + horizontalViewport; + horizontalViewport = horizontalViewport.parentElement?.closest( + FIND_SCROLL_VIEWPORT_SELECTOR, + ) + ) { const rect = range.getBoundingClientRect(); - const viewport = codeScroller.getBoundingClientRect(); - if (rect.left < viewport.left) codeScroller.scrollLeft += rect.left - viewport.left - 16; + const viewport = horizontalViewport.getBoundingClientRect(); + if (rect.left < viewport.left) horizontalViewport.scrollLeft += rect.left - viewport.left - 16; else if (rect.right > viewport.right) - codeScroller.scrollLeft += rect.right - viewport.right + 16; + horizontalViewport.scrollLeft += rect.right - viewport.right + 16; } const rect = range.getBoundingClientRect(); const viewport = container?.getBoundingClientRect(); diff --git a/scripts/scenarios/find-reveals-clipped-table-cell.e2e.ts b/scripts/scenarios/find-reveals-clipped-table-cell.e2e.ts new file mode 100644 index 0000000000000..f08966c98f75f --- /dev/null +++ b/scripts/scenarios/find-reveals-clipped-table-cell.e2e.ts @@ -0,0 +1,57 @@ +/// +import { expect } from "e2e"; + +import { test, WEB } from "./t3.ts"; + +const MATCH = "quartzneedle"; +const columns = Array.from({ length: 16 }, (_, index) => `DiagnosticsColumn${index + 1}`); +const row = (cells: string[]) => `| ${cells.join(" | ")} |`; +const TABLE = [ + row(columns), + row(columns.map(() => "---")), + row([...columns.slice(0, -1).map(() => "pending"), MATCH]), +].join("\n"); + +test( + "Find reveals a match in the last column of a wide table", + WEB, + async ({ t3, app, screen, browser }) => { + const project = await t3.project("wide-table"); + const thread = await t3.thread({ project, title: "Diagnostics table", messages: [TABLE] }); + await t3.open(thread); + await screen.getByText("first fixture turn complete", { exact: false }).waitFor({ + timeout: 120_000, + }); + + await browser.keyboard.press("Control+f"); + const find = screen.getByRole("searchbox", "Find in thread"); + await find.fill(MATCH); + + try { + await expect + .poll( + () => + browser.evaluate((query) => { + const active = CSS.highlights.get("t3-thread-find-active"); + const match = + active && + [...active].find((range) => range instanceof Range && range.toString() === query); + const viewport = match?.startContainer.parentElement?.closest( + '.chat-markdown-table-container [data-slot="scroll-area-viewport"]', + ); + if (!(match instanceof Range) || !viewport) + return "Table match has no active highlight"; + const rect = match.getBoundingClientRect(); + const clip = viewport.getBoundingClientRect(); + return rect.height > 0 && rect.left >= clip.left - 1 && rect.right <= clip.right + 1 + ? "Selected table match is inside the horizontal viewport" + : "Selected table match is clipped horizontally"; + }, MATCH), + { timeout: 20_000 }, + ) + .toBe("Selected table match is inside the horizontal viewport"); + } finally { + await app.screenshot("selected-table-match"); + } + }, +); From cb2a488c67bf577c58750a0d1335e82c7322288a Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 19 Nov 2026 12:01:28 -0800 Subject: [PATCH 17/97] fix(web): an off-track desktop build no longer says "Up to date" (#39302) --- .../src/components/desktopUpdate.logic.test.ts | 15 +++++++++++++++ apps/web/src/components/desktopUpdate.logic.ts | 15 +++++++++++++++ apps/web/src/i18n/translations/de.json | 1 + apps/web/src/i18n/translations/en.json | 1 + apps/web/src/i18n/translations/es.json | 1 + apps/web/src/i18n/translations/fr.json | 1 + apps/web/src/i18n/translations/ja.json | 1 + apps/web/src/i18n/translations/ko.json | 1 + apps/web/src/i18n/translations/pt-BR.json | 1 + apps/web/src/i18n/translations/ru.json | 1 + apps/web/src/i18n/translations/sv.json | 1 + apps/web/src/i18n/translations/zh.json | 1 + 12 files changed, 40 insertions(+) diff --git a/apps/web/src/components/desktopUpdate.logic.test.ts b/apps/web/src/components/desktopUpdate.logic.test.ts index eb5bacd37f828..29494789b6cff 100644 --- a/apps/web/src/components/desktopUpdate.logic.test.ts +++ b/apps/web/src/components/desktopUpdate.logic.test.ts @@ -58,6 +58,21 @@ describe("desktop update button state", () => { ); }); + it("never calls a build on the other track up to date", () => { + // A Stable build whose switch to Nightly did not finish; the updater discards every release. + const state: DesktopUpdateState = { + ...baseState, + status: "up-to-date", + channel: "nightly", + currentVersion: "0.1.5", + checkedAt: "2026-11-18T00:00:00.000Z", + }; + expect(getDesktopUpdateButtonTooltip(state)).not.toBe("Up to date"); + expect( + getDesktopUpdateButtonTooltip({ ...state, currentVersion: "0.1.6-nightly.20261118.1" }), + ).toBe("Up to date"); + }); + it("prefers a newly available release over a stale downloaded version", () => { const state: DesktopUpdateState = { ...baseState, diff --git a/apps/web/src/components/desktopUpdate.logic.ts b/apps/web/src/components/desktopUpdate.logic.ts index b6018a592c0ff..b853c448a10bb 100644 --- a/apps/web/src/components/desktopUpdate.logic.ts +++ b/apps/web/src/components/desktopUpdate.logic.ts @@ -1,7 +1,9 @@ import type { DesktopUpdateActionResult, DesktopUpdateState } from "@t3tools/contracts"; +import { desktopUpdateChannelOf } from "@t3tools/shared/cliRelease"; import { msg } from "gt-react"; import { m, type MessageResolver } from "../i18n/messages"; +import { channelSwitchLabel } from "./sidebar/updateEverything.logic"; export type DesktopUpdateButtonAction = "download" | "install" | "none"; @@ -159,6 +161,19 @@ export function getDesktopUpdateButtonTooltip( } return state.message ?? resolve(msg("Update failed")); } + // The updater discards every release of the other track, so "up to date" would be false here. + const buildChannel = desktopUpdateChannelOf(state.currentVersion); + if (state.status === "up-to-date" && buildChannel !== state.channel) { + return resolve( + msg( + "This {build} build ignores {track} releases. Review the update track in Settings to finish the switch.", + { + build: channelSwitchLabel(buildChannel, resolve), + track: channelSwitchLabel(state.channel, resolve), + }, + ), + ); + } return resolve(msg("Up to date")); } diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index 7b125c6298aa4..e6ea47432d43e 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -2607,6 +2607,7 @@ "d62631cab06d2b80": "Update {version} heruntergeladen. Klicke zum Neustarten und Installieren.", "52e1d4a487c0cf4b": "Installation von {version} fehlgeschlagen. Klicke, um es erneut zu versuchen.", "78a04e0e625c0990": "Update fehlgeschlagen", + "c24de5eb69373a55": "Dieser {build}-Build ignoriert {track}-Releases. Prüfe den Update-Kanal in den Einstellungen, um den Wechsel abzuschließen.", "b02ae45a6109c93b": "Auf dem neuesten Stand", "edcda9e8ee4ccad8": "Update {version} installieren und T3 Code neu starten?\n\nLaufende Aufgaben werden unterbrochen. Stelle sicher, dass du bereit bist, bevor du fortfährst.", "02eba0f7cc90f759": "Update installieren und T3 Code neu starten?\n\nLaufende Aufgaben werden unterbrochen. Stelle sicher, dass du bereit bist, bevor du fortfährst.", diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index fc971dba6e051..195984c8bc9c6 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -2606,6 +2606,7 @@ "d62631cab06d2b80": "Update {version} downloaded. Click to restart and install.", "52e1d4a487c0cf4b": "Install failed for {version}. Click to retry.", "78a04e0e625c0990": "Update failed", + "c24de5eb69373a55": "This {build} build ignores {track} releases. Review the update track in Settings to finish the switch.", "b02ae45a6109c93b": "Up to date", "edcda9e8ee4ccad8": "Install update {version} and restart T3 Code?\n\nAny running tasks will be interrupted. Make sure you're ready before continuing.", "02eba0f7cc90f759": "Install update and restart T3 Code?\n\nAny running tasks will be interrupted. Make sure you're ready before continuing.", diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index 2bf075b8cde09..1c0ecfca61eb4 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -2606,6 +2606,7 @@ "d62631cab06d2b80": "Actualización {version} descargada. Haz clic para reiniciar e instalar.", "52e1d4a487c0cf4b": "Falló la instalación de {version}. Haz clic para reintentarlo.", "78a04e0e625c0990": "Falló la actualización", + "c24de5eb69373a55": "Esta compilación {build} ignora las versiones {track}. Revisa el canal de actualizaciones en Ajustes para terminar el cambio.", "b02ae45a6109c93b": "Actualizado", "edcda9e8ee4ccad8": "¿Instalar la actualización {version} y reiniciar T3 Code?\n\nSe interrumpirán las tareas en curso. Asegúrate de estar listo antes de continuar.", "02eba0f7cc90f759": "¿Instalar la actualización y reiniciar T3 Code?\n\nSe interrumpirán las tareas en curso. Asegúrate de estar listo antes de continuar.", diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index 57f3b582c471c..5d9f5bce153c5 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -2606,6 +2606,7 @@ "d62631cab06d2b80": "Mise à jour {version} téléchargée. Cliquez pour redémarrer et l’installer.", "52e1d4a487c0cf4b": "Échec de l’installation de {version}. Cliquez pour réessayer.", "78a04e0e625c0990": "Échec de la mise à jour", + "c24de5eb69373a55": "Cette version {build} ignore les versions {track}. Vérifiez le canal de mise à jour dans les Réglages pour terminer le changement.", "b02ae45a6109c93b": "À jour", "edcda9e8ee4ccad8": "Installer la mise à jour {version} et redémarrer T3 Code ?\n\nToutes les tâches en cours seront interrompues. Assurez-vous d’être prêt avant de continuer.", "02eba0f7cc90f759": "Installer la mise à jour et redémarrer T3 Code ?\n\nToutes les tâches en cours seront interrompues. Assurez-vous d’être prêt avant de continuer.", diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index 1032927325af6..70a5135906665 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -2604,6 +2604,7 @@ "d62631cab06d2b80": "更新 {version} をダウンロードしました。クリックすると再起動してインストールします。", "52e1d4a487c0cf4b": "{version} のインストールに失敗しました。クリックして再試行してください。", "78a04e0e625c0990": "更新に失敗しました", + "c24de5eb69373a55": "この {build} ビルドは {track} のリリースを無視します。切り替えを完了するには、設定で更新トラックを確認してください。", "b02ae45a6109c93b": "最新の状態です", "edcda9e8ee4ccad8": "更新 {version} をインストールして T3 Code を再起動しますか?\n\n実行中のタスクはすべて中断されます。準備ができていることを確認してから続行してください。", "02eba0f7cc90f759": "更新をインストールして T3 Code を再起動しますか?\n\n実行中のタスクはすべて中断されます。準備ができていることを確認してから続行してください。", diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index d918ed423daef..2690d7cd556ca 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -2605,6 +2605,7 @@ "d62631cab06d2b80": "업데이트 {version}이(가) 다운로드되었습니다. 클릭하여 다시 시작하고 설치하세요.", "52e1d4a487c0cf4b": "{version} 설치에 실패했습니다. 클릭하여 다시 시도하세요.", "78a04e0e625c0990": "업데이트 실패", + "c24de5eb69373a55": "이 {build} 빌드는 {track} 릴리스를 무시합니다. 전환을 완료하려면 설정에서 업데이트 트랙을 확인하세요.", "b02ae45a6109c93b": "최신 상태", "edcda9e8ee4ccad8": "업데이트 {version}을(를) 설치하고 T3 Code를 다시 시작할까요?\n\n실행 중인 작업은 모두 중단됩니다. 계속하기 전에 준비가 되었는지 확인하세요.", "02eba0f7cc90f759": "업데이트를 설치하고 T3 Code를 다시 시작할까요?\n\n실행 중인 작업은 모두 중단됩니다. 계속하기 전에 준비가 되었는지 확인하세요.", diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index f2a498937efd8..3b57bb68c1b11 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -2606,6 +2606,7 @@ "d62631cab06d2b80": "Atualização {version} baixada. Clique para reiniciar e instalar.", "52e1d4a487c0cf4b": "Falha ao instalar {version}. Clique para tentar novamente.", "78a04e0e625c0990": "Falha na atualização", + "c24de5eb69373a55": "Esta build {build} ignora as versões {track}. Revise o canal de atualização em Configurações para concluir a troca.", "b02ae45a6109c93b": "Atualizado", "edcda9e8ee4ccad8": "Instalar a atualização {version} e reiniciar o T3 Code?\n\nAs tarefas em execução serão interrompidas. Verifique se está tudo pronto antes de continuar.", "02eba0f7cc90f759": "Instalar a atualização e reiniciar o T3 Code?\n\nAs tarefas em execução serão interrompidas. Verifique se está tudo pronto antes de continuar.", diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index 5823e9e268e26..64ac787207b45 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -2606,6 +2606,7 @@ "d62631cab06d2b80": "Обновление {version} скачано. Нажмите, чтобы перезапустить и установить.", "52e1d4a487c0cf4b": "Не удалось установить {version}. Нажмите, чтобы повторить.", "78a04e0e625c0990": "Ошибка обновления", + "c24de5eb69373a55": "Эта сборка {build} игнорирует выпуски {track}. Проверьте канал обновлений в настройках, чтобы завершить переключение.", "b02ae45a6109c93b": "Последняя версия", "edcda9e8ee4ccad8": "Установить обновление {version} и перезапустить T3 Code?\n\nВсе выполняющиеся задачи будут прерваны. Убедитесь, что вы готовы.", "02eba0f7cc90f759": "Установить обновление и перезапустить T3 Code?\n\nВсе выполняющиеся задачи будут прерваны. Убедитесь, что вы готовы.", diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index c42afb6d94fbc..0767578a42c58 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -2606,6 +2606,7 @@ "d62631cab06d2b80": "Uppdateringen {version} har laddats ned. Klicka för att starta om och installera.", "52e1d4a487c0cf4b": "Installationen av {version} misslyckades. Klicka för att försöka igen.", "78a04e0e625c0990": "Uppdateringen misslyckades", + "c24de5eb69373a55": "Den här {build}-versionen ignorerar {track}-versioner. Granska uppdateringsspåret i Inställningar för att slutföra bytet.", "b02ae45a6109c93b": "Uppdaterad", "edcda9e8ee4ccad8": "Installera uppdateringen {version} och starta om T3 Code?\n\nPågående uppgifter avbryts. Se till att du är redo innan du fortsätter.", "02eba0f7cc90f759": "Installera uppdateringen och starta om T3 Code?\n\nPågående uppgifter avbryts. Se till att du är redo innan du fortsätter.", diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index beea2b7210a2a..277b7fe77da0f 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -2610,6 +2610,7 @@ "d62631cab06d2b80": "更新 {version} 已下载。点击重启并安装。", "52e1d4a487c0cf4b": "安装 {version} 失败。点击重试。", "78a04e0e625c0990": "更新失败", + "c24de5eb69373a55": "此 {build} 版本会忽略 {track} 版本。请在设置中检查更新通道以完成切换。", "b02ae45a6109c93b": "已是最新版本", "edcda9e8ee4ccad8": "安装更新 {version} 并重启 T3 Code?\n\n正在运行的任务会被中断。请确认已准备好再继续。", "02eba0f7cc90f759": "安装更新并重启 T3 Code?\n\n正在运行的任务会被中断。请确认已准备好再继续。", From d32df2d34c0927c12b05409ab05eae804366ae15 Mon Sep 17 00:00:00 2001 From: TinBane Date: Fri, 20 Nov 2026 07:02:27 +1100 Subject: [PATCH 18/97] fix(server): native session replacement fails honestly when the provider reuses its session (#27517) Co-authored-by: TinBane <363069+TinBane@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 Co-authored-by: maria-rcks --- .../src/orchestration-v2/EffectWorker.test.ts | 1 + .../ProviderSessionManager.ts | 27 ++ .../ProviderTurnControlService.test.ts | 1 + .../ProviderTurnStartService.ts | 36 +- .../ProviderSwitch.integration.test.ts | 345 ++++++++++++++++++ 5 files changed, 407 insertions(+), 3 deletions(-) diff --git a/apps/server/src/orchestration-v2/EffectWorker.test.ts b/apps/server/src/orchestration-v2/EffectWorker.test.ts index 428d7d47066aa..60c6fdd94784f 100644 --- a/apps/server/src/orchestration-v2/EffectWorker.test.ts +++ b/apps/server/src/orchestration-v2/EffectWorker.test.ts @@ -124,6 +124,7 @@ function layerExecutorFor(input: { detach: () => record("detach"), otherWorkingThreads: () => Effect.succeed([]), releaseUnlessBusy: () => Effect.succeed(true), + forgetLoadedProviderThread: () => Effect.void, subscribePromptSuggestion: () => Stream.empty, }), ), diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.ts index 4df9d60b545d7..162136a1e0f93 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.ts @@ -280,6 +280,17 @@ export interface ProviderSessionManagerV2Shape { readonly providerSessionId: ProviderSessionId; readonly threadId: ThreadId; }) => Effect.Effect>; + /** + * Forgets that the thread has this provider thread loaded, so its next resume reaches the + * adapter. Leaves the attachment, idle unload and MCP credential alone, unlike detach. + */ + readonly forgetLoadedProviderThread: (input: { + readonly providerSessionId: ProviderSessionId; + readonly threadId: ThreadId; + readonly providerThread: OrchestrationV2ProviderThread; + readonly modelSelection: ModelSelection; + readonly runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy; + }) => Effect.Effect; /** The thread's latest predicted next prompt, then each replacement. */ readonly subscribePromptSuggestion: ( threadId: ThreadId, @@ -3446,6 +3457,22 @@ export const layerWithOptions = ( ), ), ), + forgetLoadedProviderThread: (input) => + Ref.update(sessions, (current) => { + const key = sessionKey(input.providerSessionId); + const entry = current.get(key); + // Only the matching load: a different key belongs to a later load of this thread. + if ( + entry === undefined || + entry.loadedProviderThreadKeyByThread.get(input.threadId) !== + providerThreadLoadKey({ ...input, runtime: entry.runtime }) + ) { + return current; + } + const loadedProviderThreadKeyByThread = new Map(entry.loadedProviderThreadKeyByThread); + loadedProviderThreadKeyByThread.delete(input.threadId); + return new Map(current).set(key, { ...entry, loadedProviderThreadKeyByThread }); + }), // Stored suggestions can outlive a deleted thread, so check the thread before serving one. subscribePromptSuggestion: (threadId) => SubscriptionRef.changes(promptSuggestionStore).pipe( diff --git a/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts b/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts index cb9550efe5799..10cc4b10b7130 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts @@ -218,6 +218,7 @@ function layerSessions( detach: () => Effect.void, otherWorkingThreads: () => Effect.succeed([]), releaseUnlessBusy: () => Effect.succeed(true), + forgetLoadedProviderThread: () => Effect.void, subscribePromptSuggestion: () => Stream.empty, }), ); diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts index 2b4967ce5b619..3a9313ac45475 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts @@ -1632,9 +1632,32 @@ export const layer: Layer.Layer< }), ); if (replacement === undefined) return undefined; + if ( + replacement.nativeThreadRef?.nativeId != null && + replacement.nativeThreadRef.driver === providerThread.nativeThreadRef?.driver && + replacement.nativeThreadRef.nativeId === providerThread.nativeThreadRef.nativeId + ) { + // Never retried. Forget the load first, or the next turn would skip resume and start on + // the reused session without this error or the recovery handoff. + yield* providerSessions.forgetLoadedProviderThread({ + providerSessionId: session.providerSessionId, + threadId: projection.thread.id, + providerThread: replacement, + modelSelection: run.modelSelection, + runtimePolicy: resolvedRuntimePolicy, + }); + yield* settleStartFailure({ + signal: "provider-thread-load-failure", + title: "Provider turn failed to start", + error: new ProviderAdapter.ProviderAdapterProtocolError({ + driver: session.driver, + detail: + "the provider returned its existing session when asked for a fresh one, so the conversation context could not be moved to a new session", + }), + }); + return undefined; + } const { handoff, transferId, createdAt } = yield* recoveryHandoff; - effectiveHandoffs = withRecoveryHandoff(handoff); - resumeFellBack = true; const previousRun = projection.runs.findLast( (candidate) => candidate.providerThreadId === providerThread.id && @@ -1679,7 +1702,11 @@ export const layer: Layer.Layer< strategy: handoff.strategy, summary: handoff.summaryText, }; - yield* eventSink.write({ + const replacementWrite = yield* eventSink.writeIfRunCurrent({ + threadId: projection.thread.id, + runId: run.id, + activeAttemptId: attempt.id, + expectedStatus: "starting", events: [ { id: yield* idAllocator.allocate.event({ threadId: projection.thread.id }), @@ -1718,6 +1745,9 @@ export const layer: Layer.Layer< }, ], }); + if (!replacementWrite.committed) return undefined; + effectiveHandoffs = withRecoveryHandoff(handoff); + resumeFellBack = true; recoveryTurnItem = handoffTurnItem; return replacement; }); diff --git a/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts b/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts index e1b92b61cb5a1..c2826eb6a1aae 100644 --- a/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts +++ b/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts @@ -138,6 +138,7 @@ function makeTestAdapter(input: { readonly runtimeStarts?: Ref.Ref>; // ACP cannot truncate, so its rollback answers with a fresh, empty native session. readonly rollback?: "truncates" | "replaces_native_thread"; + readonly beforeForcedNativeThread?: Effect.Effect; }): ProviderAdapter.ProviderAdapterV2["Service"] { return { instanceId: input.instanceId, @@ -210,6 +211,8 @@ function makeTestAdapter(input: { if (threadInput.forceNewNativeThread && input.runtimeStarts !== undefined) { yield* Ref.update(input.runtimeStarts, (starts) => [...starts, "replacement"]); } + if (threadInput.forceNewNativeThread && input.beforeForcedNativeThread !== undefined) + yield* input.beforeForcedNativeThread; const createdAt = yield* DateTime.now; const generation = input.nativeThreadGeneration === undefined @@ -1772,6 +1775,348 @@ describe("orchestration v2 provider switching", () => { }), ); + const unverifiedReplacementHarness = ( + name: string, + adapters: ReadonlyArray, + body: (helpers: { + readonly orchestrator: Orchestrator.OrchestratorV2["Service"]; + readonly worker: EffectWorker.OrchestrationEffectWorkerV2["Service"]; + readonly dispatchRequest: ( + ordinal: number, + selection: ModelSelection, + ) => ReturnType; + readonly awaitSettled: ( + ordinal: number, + ) => Effect.Effect< + number, + Orchestrator.OrchestratorV2Error | EffectWorker.OrchestrationEffectWorkerError + >; + }) => Effect.Effect, + ) => + Effect.scoped( + Effect.gen(function* () { + const cwd = yield* checkpointWorkspace(name); + return yield* Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; + yield* orchestrator.dispatch({ + type: "thread.create", + commandId: CommandId.make("unverified-replacement:create"), + threadId, + projectId, + createdBy: "user", + creationSource: "web", + title: "Unverified replacement", + modelSelection: CLAUDE_MODEL_SELECTION, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + }); + return yield* body({ + orchestrator, + worker, + dispatchRequest: (ordinal, selection) => + orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make(`unverified-replacement:${ordinal}`), + threadId, + messageId: MessageId.make(`unverified-replacement:${ordinal}`), + createdBy: "user", + creationSource: "web", + text: `Request ${ordinal}`, + attachments: [], + modelSelection: selection, + dispatchMode: { type: "start_immediately" }, + }), + awaitSettled: (ordinal) => + orchestrator.streamStoredEvents.pipe( + Stream.filter( + ({ event }) => + event.type === "run.updated" && + event.payload.ordinal === ordinal && + (event.payload.status === "completed" || + event.payload.status === "failed" || + event.payload.status === "interrupted"), + ), + Stream.runHead, + Effect.andThen(worker.drain()), + ), + }); + }).pipe( + Effect.provide( + ProviderReplayHarness.layerWithRegistry( + { + name, + runtimePolicyOverride: { + cwd, + approvalPolicy: "never", + sandboxPolicy: { type: "readOnly" }, + }, + }, + ProviderAdapterRegistry.layerFromAdapters(adapters), + ), + ), + ); + }), + ); + // Replacement bookkeeping is a full-thread summary handoff plus a resume-fallback transfer. + const replacementRecordsFor = (projection: OrchestrationV2ThreadProjection, runId: string) => [ + ...projection.contextHandoffs.filter( + (handoff) => handoff.targetRunId === runId && handoff.strategy === "full_thread_summary", + ), + ...projection.contextTransfers.filter( + (transfer) => + transfer.targetRunId === runId && transfer.id.includes("provider_resume_fallback"), + ), + ]; + + it.live("fails honestly when the provider reuses its session for a context handoff", () => + Effect.gen(function* () { + const capturedTurns = yield* Ref.make>([]); + yield* unverifiedReplacementHarness( + "unverified-replacement-reused", + [ + makeTestAdapter({ + instanceId: CODEX_MODEL_SELECTION.instanceId, + driver: CODEX_DRIVER, + capabilities: CodexProviderCapabilitiesV2, + modelSelection: CODEX_MODEL_SELECTION, + responseByRunOrdinal: { 2: `Source work ${"s".repeat(12_000)}` }, + capturedTurns, + }), + // Without a generation every ensureThread returns the same native id, like Muse. + makeTestAdapter({ + instanceId: CLAUDE_MODEL_SELECTION.instanceId, + driver: CLAUDE_DRIVER, + capabilities: ClaudeProviderCapabilitiesV2, + modelSelection: CLAUDE_MODEL_SELECTION, + responseByRunOrdinal: {}, + capturedTurns, + getModelContextWindow: () => 32_000, + }), + ], + ({ orchestrator, dispatchRequest, awaitSettled }) => + Effect.gen(function* () { + yield* dispatchRequest(1, CLAUDE_MODEL_SELECTION); + yield* awaitSettled(1); + const target = (yield* orchestrator.getThreadProjection(threadId)).providerThreads[0]!; + // The native session has no room left for the returning handoff. + yield* (yield* EventSink.EventSinkV2).write({ + events: [ + { + id: EventId.make("unverified-replacement-usage"), + type: "provider-thread.updated", + threadId, + occurredAt: yield* DateTime.now, + payload: { ...target, contextUsage: { usedTokens: 31_000, maxTokens: 32_000 } }, + }, + ], + }); + yield* dispatchRequest(2, CODEX_MODEL_SELECTION); + yield* awaitSettled(2); + yield* dispatchRequest(3, CLAUDE_MODEL_SELECTION); + yield* awaitSettled(3); + + const projection = yield* orchestrator.getThreadProjection(threadId); + const run3 = projection.runs.at(-1)!; + assert.equal(run3.status, "failed"); + assert.deepEqual(replacementRecordsFor(projection, run3.id), []); + const failure = projection.turnItems.findLast((item) => item.type === "error"); + assert.equal( + failure?.type === "error" ? failure.failure.message : null, + "claudeAgent provider protocol error: the provider returned its existing session when asked for a fresh one, so the conversation context could not be moved to a new session.", + ); + assert.deepEqual( + (yield* Ref.get(capturedTurns)).map((turn) => turn.driver), + [CLAUDE_DRIVER, CODEX_DRIVER], + ); + }), + ); + }), + ); + + it.live("fails without retrying when a failed resume's replacement reuses the session", () => + Effect.gen(function* () { + const capturedTurns = yield* Ref.make>([]); + const failResumeOnce = yield* Ref.make(false); + yield* unverifiedReplacementHarness( + "unverified-replacement-reused-resume", + [ + // Without a generation every ensureThread returns the same native id, like Muse. + makeTestAdapter({ + instanceId: CLAUDE_MODEL_SELECTION.instanceId, + driver: CLAUDE_DRIVER, + capabilities: ClaudeProviderCapabilitiesV2, + modelSelection: CLAUDE_MODEL_SELECTION, + responseByRunOrdinal: {}, + capturedTurns, + failResumeOnce, + }), + ], + ({ orchestrator, worker, dispatchRequest, awaitSettled }) => + Effect.gen(function* () { + yield* dispatchRequest(1, CLAUDE_MODEL_SELECTION); + yield* awaitSettled(1); + const original = (yield* orchestrator.getThreadProjection(threadId)) + .providerThreads[0]!; + yield* orchestrator.dispatch({ + type: "provider-session.detach", + commandId: CommandId.make("unverified-replacement:detach"), + threadId, + providerSessionId: original.providerSessionId!, + }); + yield* worker.drain(); + // Only the first attempt fails to resume; a retry would find the session loaded. + yield* Ref.set(failResumeOnce, true); + yield* dispatchRequest(2, CLAUDE_MODEL_SELECTION); + yield* awaitSettled(2); + + const projection = yield* orchestrator.getThreadProjection(threadId); + const run2 = projection.runs.at(-1)!; + assert.equal(run2.status, "failed"); + assert.deepEqual(replacementRecordsFor(projection, run2.id), []); + const failure = projection.turnItems.findLast((item) => item.type === "error"); + assert.equal( + failure?.type === "error" ? failure.failure.message : null, + "claudeAgent provider protocol error: the provider returned its existing session when asked for a fresh one, so the conversation context could not be moved to a new session.", + ); + assert.equal((yield* Ref.get(capturedTurns)).length, 1); + }), + ); + }), + ); + + it.live("keeps failing honestly on the next turn after rejecting a reused session", () => + Effect.gen(function* () { + const capturedTurns = yield* Ref.make>([]); + yield* unverifiedReplacementHarness( + "unverified-replacement-reused-next-turn", + [ + // Resume always fails and every ensureThread returns the same native id. + makeTestAdapter({ + instanceId: CLAUDE_MODEL_SELECTION.instanceId, + driver: CLAUDE_DRIVER, + capabilities: ClaudeProviderCapabilitiesV2, + modelSelection: CLAUDE_MODEL_SELECTION, + responseByRunOrdinal: {}, + capturedTurns, + failResume: true, + }), + ], + ({ orchestrator, worker, dispatchRequest, awaitSettled }) => + Effect.gen(function* () { + yield* dispatchRequest(1, CLAUDE_MODEL_SELECTION); + yield* awaitSettled(1); + const original = (yield* orchestrator.getThreadProjection(threadId)) + .providerThreads[0]!; + yield* orchestrator.dispatch({ + type: "provider-session.detach", + commandId: CommandId.make("unverified-replacement:detach"), + threadId, + providerSessionId: original.providerSessionId!, + }); + yield* worker.drain(); + yield* dispatchRequest(2, CLAUDE_MODEL_SELECTION); + yield* awaitSettled(2); + // The rejected session must not count as loaded, or this turn would skip resume and + // run on it without the recovery history. + yield* dispatchRequest(3, CLAUDE_MODEL_SELECTION); + yield* awaitSettled(3); + + const projection = yield* orchestrator.getThreadProjection(threadId); + assert.deepEqual( + projection.runs.map((run) => run.status), + ["completed", "failed", "failed"], + ); + assert.deepEqual(replacementRecordsFor(projection, projection.runs[2]!.id), []); + assert.equal((yield* Ref.get(capturedTurns)).length, 1); + }), + ); + }), + ); + + it.live("drops replacement bookkeeping when the run stops during replacement", () => + Effect.gen(function* () { + const capturedTurns = yield* Ref.make>([]); + const failResumeOnce = yield* Ref.make(false); + const replacementRequested = yield* Deferred.make(); + const releaseReplacement = yield* Deferred.make(); + yield* unverifiedReplacementHarness( + "unverified-replacement-interrupted", + [ + makeTestAdapter({ + instanceId: CLAUDE_MODEL_SELECTION.instanceId, + driver: CLAUDE_DRIVER, + capabilities: ClaudeProviderCapabilitiesV2, + modelSelection: CLAUDE_MODEL_SELECTION, + responseByRunOrdinal: {}, + capturedTurns, + failResumeOnce, + nativeThreadGeneration: yield* Ref.make(0), + beforeForcedNativeThread: Deferred.succeed(replacementRequested, undefined).pipe( + Effect.andThen(Deferred.await(releaseReplacement)), + ), + }), + ], + ({ orchestrator, worker, dispatchRequest, awaitSettled }) => + Effect.gen(function* () { + yield* dispatchRequest(1, CLAUDE_MODEL_SELECTION); + yield* awaitSettled(1); + const original = (yield* orchestrator.getThreadProjection(threadId)) + .providerThreads[0]!; + yield* orchestrator.dispatch({ + type: "provider-session.detach", + commandId: CommandId.make("unverified-replacement:detach"), + threadId, + providerSessionId: original.providerSessionId!, + }); + yield* worker.drain(); + yield* Ref.set(failResumeOnce, true); + yield* dispatchRequest(2, CLAUDE_MODEL_SELECTION); + yield* Deferred.await(replacementRequested); + const run2 = (yield* orchestrator.getThreadProjection(threadId)).runs.at(-1)!; + assert.equal(run2.status, "starting"); + // run.interrupt would also cancel the start effect, so move the run on directly to + // reach the window where the replacement session exists but is not yet recorded. + const settledAt = yield* DateTime.now; + yield* (yield* EventSink.EventSinkV2).write({ + events: [ + { + id: EventId.make("unverified-replacement-interrupted"), + type: "run.updated", + threadId, + runId: run2.id, + occurredAt: settledAt, + payload: { ...run2, status: "interrupted", completedAt: settledAt }, + }, + ], + }); + yield* Deferred.succeed(releaseReplacement, undefined); + + // Effects run one at a time per thread, so run 3 settles after run 2's start finishes. + // The next turn resumes the original native session with no abandoned replacement. + yield* dispatchRequest(3, CLAUDE_MODEL_SELECTION); + yield* awaitSettled(3); + const final = yield* orchestrator.getThreadProjection(threadId); + const run3 = final.runs.at(-1)!; + assert.equal(final.runs[1]?.status, "interrupted"); + assert.deepEqual(replacementRecordsFor(final, run2.id), []); + assert.equal(run3.status, "completed"); + assert.deepEqual(replacementRecordsFor(final, run3.id), []); + assert.equal( + final.providerThreads[0]?.nativeThreadRef?.nativeId, + original.nativeThreadRef?.nativeId, + ); + const turns = yield* Ref.get(capturedTurns); + assert.equal(turns.length, 2); + assert.equal(turns[1]?.nativeThreadId, original.nativeThreadRef?.nativeId); + assert.include(turns[1]!.text, "Request 3"); + }), + ); + }), + ); + it.live.each(["an older handoff", "a missed request"] as const)( "keeps the latest turn when a resume fallback also delivers %s", (older) => From 61085457d76ea246b5955c092ffba2452a825aff Mon Sep 17 00:00:00 2001 From: Lakshmi Tanmay Date: Fri, 20 Nov 2026 01:32:45 +0530 Subject: [PATCH 19/97] fix(server): repeated capture timeouts no longer delay turn starts (#29196) Co-authored-by: maria-rcks --- .../CheckpointService.test.ts | 130 +++++++++++++++++- .../src/orchestration-v2/CheckpointService.ts | 82 +++++++---- 2 files changed, 179 insertions(+), 33 deletions(-) diff --git a/apps/server/src/orchestration-v2/CheckpointService.test.ts b/apps/server/src/orchestration-v2/CheckpointService.test.ts index 62fa68c4c53af..fec015b5a1b63 100644 --- a/apps/server/src/orchestration-v2/CheckpointService.test.ts +++ b/apps/server/src/orchestration-v2/CheckpointService.test.ts @@ -11,6 +11,7 @@ import { VcsProcessTimeoutError, VcsUnsupportedOperationError, } from "@t3tools/contracts"; +import * as Cause from "effect/Cause"; import * as DateTime from "effect/DateTime"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; @@ -164,12 +165,23 @@ it.effect( assert.strictEqual((yield* Fiber.join(postTurn)).status, "ready"); assert.strictEqual((yield* Fiber.join(waitingBaseline))._tag, "Success"); - const slowBaseline = yield* checkpoints - .captureBaseline({ scope, ordinalWithinScope: 2 }) + for (const ordinalWithinScope of [2, 3]) { + const slowBaseline = yield* checkpoints + .captureBaseline({ scope, ordinalWithinScope }) + .pipe(Effect.result, Effect.forkChild); + yield* TestClock.adjust("5 seconds"); + const result = yield* Fiber.join(slowBaseline); + assert.strictEqual(result._tag, "Failure"); + if (result._tag === "Failure") { + assert.isTrue(Cause.isTimeoutError(result.failure.cause)); + } + } + const backedOffBaseline = yield* checkpoints + .captureBaseline({ scope, ordinalWithinScope: 4 }) .pipe(Effect.result, Effect.forkChild); yield* TestClock.adjust("5 seconds"); - assert.strictEqual((yield* Fiber.join(slowBaseline))._tag, "Failure"); - assert.strictEqual(yield* Ref.get(snapshots), 2); + assert.strictEqual((yield* Fiber.join(backedOffBaseline))._tag, "Success"); + assert.strictEqual(yield* Ref.get(snapshots), 3); assert.strictEqual((yield* Ref.get(refs)).size, 1); }).pipe(Effect.provide(layerTest)); }), @@ -233,3 +245,113 @@ it.effect("records a repository probe failure as an error checkpoint, not a miss assert.deepEqual(statuses, { baseline: "error", turn: "error" }); }), ); + +it.effect("backs off only baseline retries after repeated workspace capture timeouts", () => + Effect.gen(function* () { + const scope: OrchestrationV2CheckpointScope = { + id: CheckpointScopeId.make("checkpoint-scope:slow-capture"), + threadId: ThreadId.make("thread:slow-capture"), + runId: RunId.make("run:slow-capture:1"), + nodeId: NodeId.make("node:slow-capture:1"), + parentScopeId: null, + providerThreadId: ProviderThreadId.make("provider-thread:slow-capture"), + kind: "root_run", + ordinalWithinParent: 0, + advancesAppRunCount: true, + cwd: "/repo/slow", + createdAt: DateTime.makeUnsafe("2026-07-28T00:00:00.000Z"), + }; + const timeout = new VcsProcessTimeoutError({ + operation: "GitVcsDriver.checkpoints.captureCheckpoint", + command: "git", + cwd: scope.cwd, + timeoutMs: 30_000, + }); + let attempts = 0; + let healthy = false; + let nonTimeoutFailure = false; + const failure = new VcsProcessExitError({ + operation: "test.capture", + command: "git", + cwd: scope.cwd, + exitCode: 128, + detail: "capture failed", + }); + const layerTest = CheckpointService.layer.pipe( + Layer.provide( + Layer.mergeAll( + IdAllocator.layer, + Layer.mock(CheckpointStore.CheckpointStore)({ + isGitRepository: () => Effect.succeed(true), + hasCheckpointRef: () => Effect.succeed(false), + captureCheckpoint: () => + Effect.suspend(() => { + attempts++; + return healthy ? Effect.void : Effect.fail(nonTimeoutFailure ? failure : timeout); + }), + }), + ), + ), + Layer.provideMerge(NodeCrypto.layer), + ); + yield* Effect.gen(function* () { + const checkpoints = yield* CheckpointService.CheckpointServiceV2; + const baseline = { scope, ordinalWithinScope: 0 }; + const turn = { + scope, + ordinalWithinScope: 1, + runId: scope.runId, + nodeId: scope.nodeId, + appRunOrdinal: 1, + capturedAt: scope.createdAt, + }; + yield* Effect.result(checkpoints.captureBaseline(baseline)); + assert.strictEqual((yield* checkpoints.capture(turn)).status, "error"); + assert.strictEqual(attempts, 2); + + const otherThread = { ...scope, id: CheckpointScopeId.make("checkpoint-scope:other") }; + const skipped = yield* Effect.result( + checkpoints.captureBaseline({ scope: otherThread, ordinalWithinScope: 0 }), + ); + assert.strictEqual(attempts, 2, "baseline retried a repeatedly timing-out workspace"); + assert.strictEqual(skipped._tag, "Success"); + + yield* Effect.result( + checkpoints.captureBaseline({ + scope: { ...otherThread, cwd: "/repo/other" }, + ordinalWithinScope: 0, + }), + ); + assert.strictEqual(attempts, 3, "another workspace must still attempt capture"); + + const failedTurn = yield* checkpoints.capture(turn); + assert.strictEqual(failedTurn.status, "error"); + assert.strictEqual(attempts, 4, "post-turn capture must not back off"); + + yield* checkpoints.captureBaseline(baseline); + assert.strictEqual(attempts, 4, "baseline retries must wait for post-turn recovery"); + healthy = true; + assert.strictEqual((yield* checkpoints.capture(turn)).status, "ready"); + assert.strictEqual(attempts, 5); + yield* checkpoints.captureBaseline(baseline); + assert.strictEqual(attempts, 6, "a successful post-turn capture must clear backoff"); + + healthy = false; + yield* Effect.result(checkpoints.captureBaseline(baseline)); + yield* Effect.result(checkpoints.captureBaseline(baseline)); + yield* checkpoints.captureBaseline(baseline); + assert.strictEqual(attempts, 8); + nonTimeoutFailure = true; + assert.strictEqual((yield* checkpoints.capture(turn)).status, "error"); + nonTimeoutFailure = false; + yield* Effect.result(checkpoints.captureBaseline(baseline)); + assert.strictEqual(attempts, 10, "a non-timeout failure must clear backoff"); + healthy = true; + yield* checkpoints.captureBaseline(baseline); + healthy = false; + yield* Effect.result(checkpoints.captureBaseline(baseline)); + yield* Effect.result(checkpoints.captureBaseline(baseline)); + assert.strictEqual(attempts, 13, "a successful baseline must clear the timeout streak"); + }).pipe(Effect.provide(layerTest)); + }), +); diff --git a/apps/server/src/orchestration-v2/CheckpointService.ts b/apps/server/src/orchestration-v2/CheckpointService.ts index 3e0fbe95e8aa4..fb6490834c7f6 100644 --- a/apps/server/src/orchestration-v2/CheckpointService.ts +++ b/apps/server/src/orchestration-v2/CheckpointService.ts @@ -9,6 +9,7 @@ import { RunId, ThreadId, } from "@t3tools/contracts"; +import * as Cache from "effect/Cache"; import * as Context from "effect/Context"; import * as Digest from "effect/crypto/Digest"; import * as DateTime from "effect/DateTime"; @@ -17,6 +18,7 @@ import * as Base64Url from "effect/encoding/Base64Url"; import * as Hex from "effect/encoding/Hex"; import * as KeyedLock from "@t3tools/shared/KeyedLock"; import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; import { isGitImport, parseTurnDiffFilesFromNumstat } from "../checkpointing/Diffs.ts"; @@ -250,6 +252,28 @@ export const layer: Layer.Layer< const withWorkspaceLock = (cwd: string, effect: Effect.Effect) => workspaceLocks.withLock(cwd, effect); + const captureTimeouts = yield* Cache.make({ + capacity: 128, + lookup: () => Effect.succeed(0), + }); + // Both callers hold the workspace lock; post-turn captures always probe for recovery. + const captureWorkspaceCheckpoint = Effect.fn("CheckpointService.captureWorkspaceCheckpoint")( + function* (input: CheckpointStore.CaptureCheckpointInput, baseline = false) { + const capture = checkpointStore.captureCheckpoint(input); + yield* (baseline ? capture.pipe(Effect.timeout(BASELINE_CAPTURE_BUDGET)) : capture).pipe( + Effect.tap(() => Cache.invalidate(captureTimeouts, input.cwd)), + Effect.tapError((error) => + error._tag === "VcsProcessTimeoutError" || error._tag === "TimeoutError" + ? Effect.gen(function* () { + const previous = yield* Cache.get(captureTimeouts, input.cwd); + yield* Cache.set(captureTimeouts, input.cwd, previous + 1); + }) + : Cache.invalidate(captureTimeouts, input.cwd), + ), + ); + }, + ); + // A failed probe is an operational error, not proof that the workspace has no repository. const probeRepository = (scope: OrchestrationV2CheckpointScope) => checkpointStore.isGitRepository(scope.cwd).pipe( @@ -284,17 +308,19 @@ export const layer: Layer.Layer< return; } - yield* checkpointStore - .captureCheckpoint({ - cwd: input.scope.cwd, - checkpointRef, - }) - .pipe( - Effect.timeout(BASELINE_CAPTURE_BUDGET), - Effect.catchTags({ - VcsUnsupportedOperationError: () => Effect.void, - }), + const timeouts = yield* Cache.getOption(captureTimeouts, input.scope.cwd); + if (Option.isSome(timeouts) && timeouts.value >= 2) { + return yield* Effect.logWarning( + "orchestration V2 checkpoint baseline skipped after repeated capture timeouts", + { scopeId: input.scope.id, ordinalWithinScope: input.ordinalWithinScope }, ); + } + + yield* captureWorkspaceCheckpoint({ cwd: input.scope.cwd, checkpointRef }, true).pipe( + Effect.catchTags({ + VcsUnsupportedOperationError: () => Effect.void, + }), + ); }), ).pipe( Effect.mapError( @@ -406,25 +432,23 @@ export const layer: Layer.Layer< }); } - const captureStatus = yield* checkpointStore - .captureCheckpoint({ - cwd: input.scope.cwd, - checkpointRef, - ...(input.ordinalWithinScope > 0 ? { previousCheckpointRef } : {}), - }) - .pipe( - Effect.as("ready" as const), - Effect.catchTags({ - VcsUnsupportedOperationError: () => Effect.succeed("missing" as const), - }), - Effect.catch((cause) => - Effect.logWarning("orchestration V2 checkpoint capture failed", { - scopeId: input.scope.id, - checkpointRef, - cause: String(cause), - }).pipe(Effect.as("error" as const)), - ), - ); + const captureStatus = yield* captureWorkspaceCheckpoint({ + cwd: input.scope.cwd, + checkpointRef, + ...(input.ordinalWithinScope > 0 ? { previousCheckpointRef } : {}), + }).pipe( + Effect.as("ready" as const), + Effect.catchTags({ + VcsUnsupportedOperationError: () => Effect.succeed("missing" as const), + }), + Effect.catch((cause) => + Effect.logWarning("orchestration V2 checkpoint capture failed", { + scopeId: input.scope.id, + checkpointRef, + cause: String(cause), + }).pipe(Effect.as("error" as const)), + ), + ); if (captureStatus !== "ready") { return makeCheckpoint({ From 800b0748bcd26591c914844e22297175a0cccb59 Mon Sep 17 00:00:00 2001 From: Jolymmiles <75259437+Jolymmiles@users.noreply.github.com> Date: Thu, 19 Nov 2026 23:03:04 +0300 Subject: [PATCH 20/97] fix(server): restart recovery no longer reads every idle thread on a shared session (#32396) Co-authored-by: Julius Marminge Co-authored-by: Claude Opus 5.5 --- .../ProjectionRecovery.test.ts | 47 +++++++++++++--- .../src/orchestration-v2/ProjectionStore.ts | 53 +++++++++++++------ 2 files changed, 78 insertions(+), 22 deletions(-) diff --git a/apps/server/src/orchestration-v2/ProjectionRecovery.test.ts b/apps/server/src/orchestration-v2/ProjectionRecovery.test.ts index d8b7dae693632..94788c7fbfc43 100644 --- a/apps/server/src/orchestration-v2/ProjectionRecovery.test.ts +++ b/apps/server/src/orchestration-v2/ProjectionRecovery.test.ts @@ -763,8 +763,10 @@ it.effect("includes shared sessions and provider-owned background rosters in rec const now = yield* DateTime.now; const first = yield* createThread("shared-first"); const second = yield* createThread("shared-second", { archivedAt: now }); + const idleShared = [first, second]; + const sharedWork = yield* createThread("shared-work"); const providerSessionId = ProviderSessionId.make("session:recovery:shared"); - for (const threadId of [first, second]) { + for (const threadId of [...idleShared, sharedWork]) { yield* projections.apply({ id: EventId.make(`event:${threadId}:session`), type: "provider-session.attached", @@ -786,6 +788,34 @@ it.effect("includes shared sessions and provider-owned background rosters in rec }, }); } + yield* projections.apply({ + id: EventId.make("event:recovery:shared-work"), + type: "provider-thread.updated", + threadId: sharedWork, + driver, + providerInstanceId, + occurredAt: now, + payload: { + id: ProviderThreadId.make("provider-thread:recovery:shared-work"), + appThreadId: sharedWork, + ownerNodeId: null, + driver, + providerInstanceId, + providerSessionId, + nativeThreadRef: { driver, nativeId: "native:shared-work", strength: "strong" }, + nativeConversationHeadRef: null, + status: "idle", + firstRunOrdinal: 1, + lastRunOrdinal: 1, + handoffIds: [], + forkedFrom: null, + createdAt: now, + updatedAt: now, + pendingBackgroundTasks: [ + { taskId: "awaited", description: "Awaited subagent", kind: "subagent" }, + ], + }, + }); const roster = yield* createThread("roster"); yield* projections.apply({ id: EventId.make("event:recovery:roster"), @@ -869,13 +899,16 @@ it.effect("includes shared sessions and provider-owned background rosters in rec restartContinuationOfRunId: RunId.make("run:recovery:source"), }); assert.deepEqual( - new Set(yield* projections.getRecoveryThreadIds("runtime")), - new Set([first, second, roster, prepared]), + new Set(yield* projections.getRecoveryThreadIds("restart-continuations")), + new Set([sharedWork, prepared]), ); + // One idle bound thread stops the shared session; the rest have nothing to recover. + const runtime = yield* projections.getRecoveryThreadIds("runtime"); assert.deepEqual( - new Set(yield* projections.getRecoveryThreadIds("restart-continuations")), - new Set([first, second, prepared]), + new Set(runtime.filter((threadId) => !idleShared.includes(threadId))), + new Set([sharedWork, roster, prepared]), ); + assert.equal(runtime.filter((threadId) => idleShared.includes(threadId)).length, 1); assert.deepEqual( yield* projections.getRecoveryThreadIds("restart-continuations", { include: [] }), [], @@ -892,7 +925,7 @@ it.effect("includes shared sessions and provider-owned background rosters in rec include: ["project:recovery"], }), ), - new Set([first, second, prepared]), + new Set([sharedWork, prepared]), ); const preparedState = yield* projections.getRuntimeRecoveryProjection(prepared); assert.deepEqual( @@ -908,7 +941,7 @@ it.effect("includes shared sessions and provider-owned background rosters in rec `; assert.deepEqual( new Set(yield* projections.getUnreadableThreadIds()), - new Set([first, second]), + new Set([...idleShared, sharedWork]), ); }).pipe(Effect.provide(layerTest)), ); diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index 33e1355ec15c0..7824fce056c4f 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -5110,18 +5110,33 @@ export const layer: Layer.Layer = `; case "restart-continuations": return sql` - SELECT bindings.thread_id - FROM orchestration_v2_projection_provider_sessions AS sessions - JOIN orchestration_v2_projection_provider_session_bindings AS bindings - ON bindings.provider_session_id = sessions.provider_session_id - WHERE sessions.status NOT IN ('stopped', 'error') - UNION - SELECT thread_id FROM orchestration_v2_projection_provider_sessions AS sessions - WHERE status NOT IN ('stopped', 'error') AND thread_id IS NOT NULL - AND NOT EXISTS ( - SELECT 1 FROM orchestration_v2_projection_provider_session_bindings AS bindings - WHERE bindings.provider_session_id = sessions.provider_session_id - ) + SELECT thread_id FROM ( + SELECT bindings.thread_id + FROM orchestration_v2_projection_provider_sessions AS sessions + JOIN orchestration_v2_projection_provider_session_bindings AS bindings + ON bindings.provider_session_id = sessions.provider_session_id + WHERE sessions.status NOT IN ('stopped', 'error') + UNION + SELECT thread_id FROM orchestration_v2_projection_provider_sessions AS sessions + WHERE status NOT IN ('stopped', 'error') AND thread_id IS NOT NULL + AND NOT EXISTS ( + SELECT 1 FROM orchestration_v2_projection_provider_session_bindings AS bindings + WHERE bindings.provider_session_id = sessions.provider_session_id + ) + ) + -- A live session alone continues nothing: restartContinuationRun + -- also needs an active provider thread or open background work. + WHERE thread_id IN ( + SELECT thread_id FROM orchestration_v2_projection_provider_threads + WHERE status = 'active' + OR CASE WHEN json_valid(payload_json) + THEN json_array_length(payload_json, '$.pendingBackgroundTasks') > 0 + ELSE 0 END + UNION + SELECT thread_id FROM orchestration_v2_projection_turn_items + WHERE type IN ('command_execution', 'dynamic_tool', 'subagent') + AND status IN ('pending', 'running', 'waiting') + ) UNION SELECT thread_id FROM orchestration_v2_projection_runs WHERE status = 'starting' @@ -5153,10 +5168,18 @@ export const layer: Layer.Layer = SELECT thread_id FROM orchestration_v2_projection_runtime_requests WHERE status = 'pending' UNION - SELECT bindings.thread_id + -- One bound thread stops a session; the other arms select the + -- bound threads with work, so idle threads on a shared session stay out. + SELECT ( + SELECT bindings.thread_id + FROM orchestration_v2_projection_provider_session_bindings AS bindings + JOIN orchestration_v2_projection_threads AS threads + ON threads.thread_id = bindings.thread_id + WHERE bindings.provider_session_id = sessions.provider_session_id + AND threads.deleted_at IS NULL + ORDER BY bindings.thread_id LIMIT 1 + ) FROM orchestration_v2_projection_provider_sessions AS sessions - CROSS JOIN orchestration_v2_projection_provider_session_bindings AS bindings - ON bindings.provider_session_id = sessions.provider_session_id WHERE sessions.status NOT IN ('stopped', 'error') OR (sessions.status = 'error' AND CASE WHEN json_valid(sessions.payload_json) THEN json_array_length(sessions.payload_json, '$.extensionStatuses') > 0 From 1e7021025038c18f2a7d11b63818334224fe31ee Mon Sep 17 00:00:00 2001 From: Adamulek123 Date: Thu, 19 Nov 2026 21:03:23 +0100 Subject: [PATCH 21/97] perf(server): avoid discarded history when retrieving remote task results (#26664) --- apps/server/src/peer/RemoteDelegation.test.ts | 381 +++++++++++++++--- apps/server/src/peer/RemoteDelegation.ts | 36 +- 2 files changed, 358 insertions(+), 59 deletions(-) diff --git a/apps/server/src/peer/RemoteDelegation.test.ts b/apps/server/src/peer/RemoteDelegation.test.ts index 34e021cc798d0..d4af55cae0313 100644 --- a/apps/server/src/peer/RemoteDelegation.test.ts +++ b/apps/server/src/peer/RemoteDelegation.test.ts @@ -9,6 +9,7 @@ import { type ModelSelection, NodeId, type OrchestrationV2Run, + type OrchestratorMcpThreadReadInput, ProjectId, ProviderDriverKind, ProviderInstanceId, @@ -34,6 +35,7 @@ import * as Schedule from "effect/Schedule"; import * as Stream from "effect/Stream"; import * as SubscriptionRef from "effect/SubscriptionRef"; import * as Tracer from "effect/Tracer"; +import * as FetchHttpClient from "effect/http/FetchHttpClient"; import * as TestClock from "effect/testing/TestClock"; import type * as SqlClient from "effect/sql/SqlClient"; import { McpSchema, McpServer } from "effect/ai"; @@ -88,7 +90,18 @@ type LaunchedWith = Pick< >; /** The thread the box launches for the task, which the test finishes. */ +interface TimelineEntry { + readonly id: TurnItemId; + readonly runId: RunId; + readonly text: string; + readonly type: "assistant_message" | "error"; +} + interface BoxThread { + readonly timeline: Ref.Ref | null>; + readonly pageSize: Ref.Ref; + readonly holdRefill: Ref.Ref; + readonly beforeTail: Ref.Ref>; readonly launched: Ref.Ref; /** The link session that launched it, as the box stamps it. */ readonly linkOrigin: Ref.Ref<{ readonly sessionId: string; readonly label: string } | null>; @@ -145,6 +158,10 @@ interface BoxThread { const makeBoxThread = Effect.gen(function* () { return { + timeline: yield* Ref.make | null>(null), + pageSize: yield* Ref.make(1), + holdRefill: yield* Ref.make(false), + beforeTail: yield* Ref.make>(Effect.void), launched: yield* Ref.make(null), linkOrigin: yield* Ref.make<{ readonly sessionId: string; readonly label: string } | null>( null, @@ -361,7 +378,13 @@ const boxToolkitLayer = (thread: BoxThread) => { }), getTimelinePage: (threadId, options) => Effect.gen(function* () { - if (yield* Ref.get(thread.holdRead)) { + if (options.afterPosition === 299 && options.itemId === undefined) { + yield* Ref.getAndSet(thread.beforeTail, Effect.void).pipe(Effect.flatten); + } + if ( + (yield* Ref.get(thread.holdRead)) || + (options.itemId !== undefined && (yield* Ref.get(thread.holdRefill))) + ) { yield* Deferred.succeed(thread.readStarted, undefined); yield* Deferred.await(thread.releaseRead); } @@ -372,61 +395,63 @@ const boxToolkitLayer = (thread: BoxThread) => { const laterError = yield* Ref.get(thread.laterError); const restart = yield* Ref.get(thread.restart); // One item per page, with errors available only in the activity view. - const replies = [ - ...(reply === null - ? [] - : [ - { - id: TurnItemId.make("item:reply"), - runId, - text: reply, - type: "assistant_message", - }, - ]), - ...(error === null - ? [] - : [{ id: TurnItemId.make("item:error"), runId, text: error, type: "error" }]), - ...(later === null - ? [] - : [ - { - id: TurnItemId.make("item:later-reply"), - runId: boxLaterRunId, - text: later, - type: "assistant_message", - }, - ]), - ...(laterError === null - ? [] - : [ - { - id: TurnItemId.make("item:later-error"), - runId: boxLaterRunId, - text: laterError, - type: "error", - }, - ]), - ...(queued === null - ? [] - : [ - { - id: TurnItemId.make("item:queued-reply"), - runId: boxQueuedRunId, - text: queued, - type: "assistant_message", - }, - ]), - ...(restart === null - ? [] - : [ - { - id: TurnItemId.make("item:restarted-reply"), - runId: continuationOf(restart.of), - text: restart.reply, - type: "assistant_message", - }, - ]), - ].map((entry, position) => ({ ...entry, position })); + const replies = ( + (yield* Ref.get(thread.timeline)) ?? [ + ...(reply === null + ? [] + : [ + { + id: TurnItemId.make("item:reply"), + runId, + text: reply, + type: "assistant_message", + }, + ]), + ...(error === null + ? [] + : [{ id: TurnItemId.make("item:error"), runId, text: error, type: "error" }]), + ...(later === null + ? [] + : [ + { + id: TurnItemId.make("item:later-reply"), + runId: boxLaterRunId, + text: later, + type: "assistant_message", + }, + ]), + ...(laterError === null + ? [] + : [ + { + id: TurnItemId.make("item:later-error"), + runId: boxLaterRunId, + text: laterError, + type: "error", + }, + ]), + ...(queued === null + ? [] + : [ + { + id: TurnItemId.make("item:queued-reply"), + runId: boxQueuedRunId, + text: queued, + type: "assistant_message", + }, + ]), + ...(restart === null + ? [] + : [ + { + id: TurnItemId.make("item:restarted-reply"), + runId: continuationOf(restart.of), + text: restart.reply, + type: "assistant_message", + }, + ]), + ] + ).map((entry, position) => ({ ...entry, position })); const visible = options.itemId === undefined ? replies.filter( @@ -435,7 +460,7 @@ const boxToolkitLayer = (thread: BoxThread) => { : replies.filter((entry) => entry.id === options.itemId); const matching = visible .filter((entry) => entry.position > (options.afterPosition ?? -1)) - .slice(0, 1); + .slice(0, yield* Ref.get(thread.pageSize)); return { items: matching.map(({ id, runId: itemRunId, text, position, type }) => ({ position, @@ -918,6 +943,28 @@ const taskResult = (laptopEnv: Effect.Success>, ta ), ); +const captureThreadReads = (nativeFetch: typeof globalThis.fetch) => { + const reads: Array = []; + const fetch: typeof globalThis.fetch = (input, init) => { + const body = init?.body instanceof Uint8Array ? new TextDecoder().decode(init.body) : null; + if (body?.startsWith("{")) { + const rpc: { + method?: string; + params?: { name?: string; arguments?: OrchestratorMcpThreadReadInput }; + } = JSON.parse(body); + if ( + rpc.method === "tools/call" && + rpc.params?.name === "t3_thread_read" && + rpc.params.arguments !== undefined + ) { + reads.push(rpc.params.arguments); + } + } + return nativeFetch(input, init); + }; + return { reads, fetch }; +}; + it.effect("a task delegated to the box wakes the laptop's parent when it ends there", () => Effect.scoped( Effect.gen(function* () { @@ -1605,6 +1652,226 @@ it.effect.each([false, true])( ).pipe(Effect.provide(NodeHttpServer.layerTest)), ); +it.effect.each(["tail-error", "middle-error", "reply-fallback", "cancel-refill"] as const)( + "reads a failed task through full activity pages (%s)", + (scenario) => + Effect.gen(function* () { + const { reads, fetch } = captureThreadReads(yield* FetchHttpClient.Fetch); + return yield* Effect.scoped( + Effect.gen(function* () { + const thread = yield* makeBoxThread; + const b = yield* serveBox(thread); + const offers = yield* SubscriptionRef.make< + ReadonlyArray + >([]); + const database = yield* SqlitePersistence.layerMemory.pipe(Layer.build); + const a = yield* makeLaptop(database, offers); + yield* linkTo(a.links, b, "full-access"); + yield* seedParent(a); + const delegated = yield* delegateToBox(a); + const result = `Provider details: ${"detail ".repeat(8_000)}end.`; + const middle = scenario !== "tail-error"; + const ownType = scenario === "reply-fallback" ? "assistant_message" : "error"; + const history = (count: number, runId: RunId, prefix: string): Array => + Array.from({ length: count }, (_, index) => ({ + id: TurnItemId.make(`${prefix}:${index}`), + runId, + text: "discarded history ".repeat(120), + type: "assistant_message", + })); + const timeline: Array = [ + ...history(middle ? 150 : 300, boxRunId, "before"), + { id: TurnItemId.make("selected"), runId: boxRunId, text: result, type: ownType }, + ...(middle ? history(200, boxLaterRunId, "later") : []), + { + id: TurnItemId.make("other-error"), + runId: boxLaterRunId, + text: "Wrong run", + type: "error", + }, + ]; + yield* Ref.set(thread.timeline, timeline); + yield* Ref.set(thread.pageSize, 100); + yield* Ref.set(thread.status, "failed"); + if (scenario === "cancel-refill") yield* Ref.set(thread.holdRefill, true); + yield* Deferred.succeed(thread.finished, undefined); + if (scenario === "cancel-refill") { + yield* Deferred.await(thread.readStarted); + yield* a.threads.stopDelegatedTasks({ + threadId: parentThreadId, + commandId: CommandId.make("command:stop:mid-refill"), + }); + yield* Deferred.succeed(thread.releaseRead, undefined); + expect(yield* taskResult(a, delegated.taskId)).toMatchObject({ status: "interrupted" }); + yield* Deferred.await(thread.interruptedOnce); + expect(yield* Ref.get(thread.stops)).toContain("thread.stop"); + } else { + expect(yield* taskResult(a, delegated.taskId)).toMatchObject({ + status: "failed", + result, + }); + } + const pages = reads.filter((read) => read.itemId === undefined && read.limit === 100); + // A page moves on by however many items the response budget left it. + const remaining = (read: OrchestratorMcpThreadReadInput) => + timeline.length - 1 - (read.afterPosition ?? -1); + expect(pages[0]).toMatchObject({ + view: "activity", + limit: 100, + maxCharsPerItem: 20_000, + }); + expect(pages.slice(1).some((read) => remaining(read) > 100)).toBe(true); + for (const read of pages.slice(1)) + expect(read.maxCharsPerItem).toBe(remaining(read) > 100 ? 1 : 20_000); + const forwards = pages.slice(1).map((read) => read.afterPosition ?? -1); + expect(forwards).toEqual([...forwards].sort((left, right) => left - right)); + expect(new Set(forwards).size).toBe(forwards.length); + const refills = reads.filter((read) => read.itemId !== undefined); + expect(refills[0]).toMatchObject({ itemId: "selected", textOffset: middle ? 1 : 20_000 }); + if (scenario !== "cancel-refill") expect(refills).toHaveLength(middle ? 3 : 2); + }), + ).pipe( + Effect.provide(NodeHttpServer.layerTest), + Effect.provideService(FetchHttpClient.Fetch, fetch), + ); + }), +); + +it.effect.each([ + "terminal", + "long", + "later-run", + "sparse", + "growing", + "shrinking", + "cancel", + "no-run", + "cancelled", + "interrupted", +] as const)("reads a successful task with an aligned tail probe (%s)", (scenario) => + Effect.gen(function* () { + const { reads, fetch } = captureThreadReads(yield* FetchHttpClient.Fetch); + return yield* Effect.scoped( + Effect.gen(function* () { + const thread = yield* makeBoxThread; + const b = yield* serveBox(thread); + const offers = yield* SubscriptionRef.make< + ReadonlyArray + >([]); + const database = yield* SqlitePersistence.layerMemory.pipe(Layer.build); + const a = yield* makeLaptop(database, offers); + yield* linkTo(a.links, b, "full-access"); + yield* seedParent(a); + const result = + scenario === "long" + ? `Complete ${"detail ".repeat(12_000)}end.` + : "Authoritative result."; + const middle = scenario === "later-run" || scenario === "shrinking"; + const history = (count: number, runId: RunId, prefix: string): Array => + Array.from({ length: count }, (_, index) => ({ + id: TurnItemId.make(`${prefix}:${index}`), + runId, + text: "History", + type: scenario === "sparse" && index % 2 === 0 ? "error" : "assistant_message", + })); + const timeline: Array = [ + ...history(middle ? 150 : 300, boxRunId, "before"), + { + id: TurnItemId.make("selected"), + runId: scenario === "no-run" ? boxLaterRunId : boxRunId, + text: result, + type: "assistant_message", + }, + ...(middle ? history(200, boxLaterRunId, "later") : []), + ]; + yield* Ref.set(thread.timeline, timeline); + yield* Ref.set(thread.pageSize, 100); + if (scenario === "growing") { + yield* Ref.set( + thread.beforeTail, + Ref.set(thread.timeline, [...timeline, ...history(101, boxLaterRunId, "growth")]), + ); + } + if (scenario === "shrinking") { + yield* Ref.set(thread.beforeTail, Ref.set(thread.timeline, timeline.slice(0, 151))); + } + if (scenario === "cancel") { + yield* Ref.set( + thread.beforeTail, + Effect.gen(function* () { + yield* Deferred.succeed(thread.readStarted, undefined); + yield* Deferred.await(thread.releaseRead); + }), + ); + } + if (scenario === "no-run") yield* Ref.set(thread.runless, true); + const delegated = yield* delegateToBox(a); + const status = + scenario === "cancelled" || scenario === "interrupted" ? scenario : "completed"; + const modelNote = scenario === "terminal" || scenario === "long"; + if (modelNote) yield* Ref.set(thread.executedModel, "gpt-5.4-mini"); + yield* Ref.set(thread.status, status); + yield* Deferred.succeed(thread.finished, undefined); + if (scenario === "cancel") { + yield* Deferred.await(thread.readStarted); + yield* a.threads.stopDelegatedTasks({ + threadId: parentThreadId, + commandId: CommandId.make("command:stop:tail-probe"), + }); + yield* Deferred.succeed(thread.releaseRead, undefined); + expect(yield* taskResult(a, delegated.taskId)).toMatchObject({ status: "interrupted" }); + yield* Deferred.await(thread.interruptedOnce); + expect(yield* Ref.get(thread.stops)).toContain("thread.stop"); + } else { + expect(yield* taskResult(a, delegated.taskId)).toMatchObject({ + status, + result: modelNote + ? `Requested model gpt-5.4; the provider reported running gpt-5.4-mini.\n\n${result}` + : result, + }); + } + const pages = reads.filter((read) => read.itemId === undefined && read.limit === 100); + // The thread's final page starts at its canonical 100-item boundary. + const tailPosition = Math.floor((timeline.length - 1) / 100) * 100 - 1; + expect(pages.at(0)?.afterPosition).toBeUndefined(); + expect( + pages.every( + (read) => + read.view === "messages" && read.limit === 100 && read.maxCharsPerItem === 20_000, + ), + ).toBe(true); + if (scenario === "cancelled" || scenario === "interrupted") { + // A run that did not complete keeps the established scan, without the probe. + expect(pages.map((read) => read.afterPosition)).not.toContain(tailPosition); + const forwards = pages.slice(1).map((read) => read.afterPosition ?? -1); + expect(forwards.length).toBeGreaterThan(0); + expect(forwards).toEqual([...forwards].sort((left, right) => left - right)); + } else { + expect(pages.at(1)?.afterPosition).toBe(tailPosition); + const rest = pages.slice(2); + if (scenario === "later-run" || scenario === "shrinking" || scenario === "growing") { + // An inconclusive tail falls back to scanning from where the first page ended. + expect(rest.length).toBeGreaterThan(0); + const resumed = rest.map((read) => read.afterPosition ?? -1); + expect(resumed[0]).toBeLessThan(tailPosition); + expect(resumed).toEqual([...resumed].sort((left, right) => left - right)); + } else { + // A terminal page holding the run's last reply ends the read there. + expect(rest).toHaveLength(0); + } + } + const refills = reads.filter((read) => read.itemId !== undefined); + expect(refills).toHaveLength(scenario === "long" ? 4 : 0); + if (scenario === "long") + expect(refills.map((read) => read.textOffset)).toEqual([20_000, 40_000, 60_000, 80_000]); + }), + ).pipe( + Effect.provide(NodeHttpServer.layerTest), + Effect.provideService(FetchHttpClient.Fetch, fetch), + ); + }), +); + it.effect("keeps a successful remote reply despite an error item in the run's activity", () => Effect.scoped( Effect.gen(function* () { diff --git a/apps/server/src/peer/RemoteDelegation.ts b/apps/server/src/peer/RemoteDelegation.ts index 8fcd240e70577..6e48aa5fa61fe 100644 --- a/apps/server/src/peer/RemoteDelegation.ts +++ b/apps/server/src/peer/RemoteDelegation.ts @@ -615,18 +615,23 @@ const make = Effect.gen(function* () { remote: OrchestrationV2RemoteTaskChild, runId: RunId | null, failed = false, + probeSuccess = true, ) { let reply: OrchestratorMcpThreadTimelineItem | undefined; let error: OrchestratorMcpThreadTimelineItem | undefined; let afterPosition: number | undefined; let run: OrchestratorMcpThreadRun | undefined; + let remainingItems = 0; + let tailProbed = false; while (true) { const read = yield* forwarding.readThread(scope, remote.environmentId, { threadId: remote.threadId, view: failed ? "activity" : "messages", limit: 100, runLimit: 50, - maxCharsPerItem: 20_000, + // Keep the first and expected final activity pages whole. A result on a + // middle page then needs an extra text read after the scan. + maxCharsPerItem: failed && remainingItems > 100 ? 1 : 20_000, ...(afterPosition === undefined ? {} : { afterPosition }), }); run ??= read.recentRuns.find((candidate) => candidate.runId === runId); @@ -641,7 +646,28 @@ const make = Effect.gen(function* () { ) ?? error; } if (!read.hasMore || read.nextPosition === null) break; + if (!failed && probeSuccess && !tailProbed) { + tailProbed = true; + const tailPosition = Math.floor((read.thread.itemCount - 1) / 100) * 100 - 1; + if (tailPosition > read.nextPosition) { + const tail = yield* forwarding.readThread(scope, remote.environmentId, { + threadId: remote.threadId, + view: "messages", + limit: 100, + maxCharsPerItem: 20_000, + afterPosition: tailPosition, + }); + const tailReply = tail.items.findLast( + (item) => item.type === "assistant_message" && (runId === null || item.runId === runId), + ); + if (!tail.hasMore && tailReply !== undefined) { + reply = tailReply; + break; + } + } + } afterPosition = read.nextPosition; + remainingItems = read.thread.itemCount - afterPosition - 1; } reply = error ?? reply; const executedModel = run?.executedModel ?? undefined; @@ -861,7 +887,13 @@ const make = Effect.gen(function* () { waited.resultRun !== undefined && !sharedThread ? waited.resultRun : { runId: waited.runId, status: waited.status }; - const result = yield* lastReply(scope, remote, resultRun.runId, resultRun.status === "failed"); + const result = yield* lastReply( + scope, + remote, + resultRun.runId, + resultRun.status === "failed", + resultRun.status === "completed", + ); yield* complete( parentThreadId, taskId, From 1e9f4c45c3c143c4f405d47d250b649f82c5d656 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ilkka=20Lappetel=C3=A4inen?= <38039015+pnupu@users.noreply.github.com> Date: Thu, 19 Nov 2026 22:03:41 +0200 Subject: [PATCH 22/97] fix(triage): file labeled reports through the issue template (#31321) Co-authored-by: Claude Fable 5.2 --- .github/triage/PLAYBOOK.md | 17 ++++++++++++++--- apps/server/src/triage/triagePrompt.ts | 17 ++++++++++++++--- 2 files changed, 28 insertions(+), 6 deletions(-) diff --git a/.github/triage/PLAYBOOK.md b/.github/triage/PLAYBOOK.md index cc922de448005..b11731e54e8f7 100644 --- a/.github/triage/PLAYBOOK.md +++ b/.github/triage/PLAYBOOK.md @@ -125,9 +125,20 @@ of `main` for that work, never the tag-pinned diagnosis clone. - Show the user the complete final issue text and get an explicit yes before posting. Never post without it. - Note at the end of the issue which model and agent produced it. -- Post with `gh issue create --repo pingdotgg/t3code --label via-triage` only - if `gh api repos/pingdotgg/t3code --jq .permissions.triage` prints `true`. -- Otherwise, or if `gh` is not authenticated, build a prefilled +- If `gh` is authenticated to github.com, post through the "Triage report" + issue template. It applies `via-triage` for every reporter, while + `gh issue create --label` drops the label without triage permission. Write + the approved title and body to files, the title without a trailing newline, + so the shell never parses their text. Then run: + + gh api --hostname github.com graphql -f repo="$(gh api --hostname github.com repos/pingdotgg/t3code --jq .node_id)" -f template="Triage report" -F title=@ -F body=@ -f query='mutation($repo:ID!,$template:String!,$title:String!,$body:String!){createIssue(input:{repositoryId:$repo,issueTemplate:$template,title:$title,body:$body}){issue{url labels(first:20){nodes{name}}}}}' + + Report the issue URL and whether its labels include `via-triage`. Never file a + second issue to repair a label. If you cannot tell whether the issue was + created, check the user's recent issues before you retry. + +- If `gh` is not authenticated, or the request was rejected and created + nothing, build a prefilled https://github.com/pingdotgg/t3code/issues/new?template=via-triage.yml URL. The form applies the label whoever submits it. Add `title` plus one URL-encoded query parameter per form field id: `what-happened`, `diagnosis`, diff --git a/apps/server/src/triage/triagePrompt.ts b/apps/server/src/triage/triagePrompt.ts index 7a7625dcbe15c..0e9dbb4470a05 100644 --- a/apps/server/src/triage/triagePrompt.ts +++ b/apps/server/src/triage/triagePrompt.ts @@ -129,9 +129,20 @@ of \`main\` for that work, never the tag-pinned diagnosis clone. - Show the user the complete final issue text and get an explicit yes before posting. Never post without it. - Note at the end of the issue which model and agent produced it. -- Post with \`gh issue create --repo pingdotgg/t3code --label via-triage\` only - if \`gh api repos/pingdotgg/t3code --jq .permissions.triage\` prints \`true\`. -- Otherwise, or if \`gh\` is not authenticated, build a prefilled +- If \`gh\` is authenticated to github.com, post through the "Triage report" + issue template. It applies \`via-triage\` for every reporter, while + \`gh issue create --label\` drops the label without triage permission. Write + the approved title and body to files, the title without a trailing newline, + so the shell never parses their text. Then run: + + gh api --hostname github.com graphql -f repo="$(gh api --hostname github.com repos/pingdotgg/t3code --jq .node_id)" -f template="Triage report" -F title=@ -F body=@ -f query='mutation($repo:ID!,$template:String!,$title:String!,$body:String!){createIssue(input:{repositoryId:$repo,issueTemplate:$template,title:$title,body:$body}){issue{url labels(first:20){nodes{name}}}}}' + + Report the issue URL and whether its labels include \`via-triage\`. Never file a + second issue to repair a label. If you cannot tell whether the issue was + created, check the user's recent issues before you retry. + +- If \`gh\` is not authenticated, or the request was rejected and created + nothing, build a prefilled https://github.com/pingdotgg/t3code/issues/new?template=via-triage.yml URL. The form applies the label whoever submits it. Add \`title\` plus one URL-encoded query parameter per form field id: \`what-happened\`, \`diagnosis\`, From 6d05c5f4964633d296e53d88706b5ab4213971d0 Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Thu, 19 Nov 2026 21:03:59 +0100 Subject: [PATCH 23/97] fix(server): HTML reports in dot-prefixed folders no longer open as Not Found (#38210) Co-authored-by: Claude Opus 5.5 Co-authored-by: GPT 6.1 Sol --- apps/server/src/assets/AssetAccess.test.ts | 75 +++++++++++++++++++ apps/server/src/assets/AssetAccess.ts | 20 ++++- .../html-report-in-dot-folder.e2e.ts | 27 +++++++ 3 files changed, 118 insertions(+), 4 deletions(-) create mode 100644 scripts/scenarios/html-report-in-dot-folder.e2e.ts diff --git a/apps/server/src/assets/AssetAccess.test.ts b/apps/server/src/assets/AssetAccess.test.ts index be4122e6f559e..682ced374e221 100644 --- a/apps/server/src/assets/AssetAccess.test.ts +++ b/apps/server/src/assets/AssetAccess.test.ts @@ -1056,6 +1056,52 @@ describe("AssetAccess", () => { }).pipe(Effect.provide(layerTest)), ); + it.effect.skipIf(!symlinksSupported)( + "validates canonical sibling assets for previews in dot-prefixed folders", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* fs.makeTempDirectoryScoped(); + const reportsDirectory = path.join(root, ".reports"); + yield* fs.makeDirectory(path.join(reportsDirectory, ".cache"), { recursive: true }); + yield* fs.makeDirectory(path.join(root, ".secret")); + const page = path.join(reportsDirectory, "report.html"); + yield* fs.writeFileString(page, ""); + const dependencies = [ + { name: "linked.css", target: path.join(root, ".secret", "key.css"), allowed: false }, + { + name: "inner.css", + target: path.join(reportsDirectory, ".cache", "hidden.css"), + allowed: false, + }, + { name: "shared.css", target: path.join(root, "shared.css"), allowed: true }, + ]; + for (const { name, target } of dependencies) { + yield* fs.writeFileString(target, "fixture"); + yield* fs.symlink(target, path.join(reportsDirectory, name)); + } + const result = yield* issueAssetUrl({ + resource: { _tag: "workspace-file", threadId: ThreadId.make("thread-1"), path: page }, + workspaceRoot: root, + }); + const suffix = result.relativeUrl.slice(ASSET_ROUTE_PREFIX.length + 1); + const token = suffix.slice(0, suffix.indexOf("/")); + for (const { name, target, allowed } of dependencies) { + const resolved = yield* resolveAsset(token, name); + if (allowed) { + expect(resolved).toEqual({ + kind: "file", + path: yield* fs.realPath(target), + renderIntent: "file-preview", + }); + } else { + expect(resolved).toBeNull(); + } + } + }).pipe(Effect.provide(layerTest)), + ); + it.effect("issues workspace URLs that resolve the entry file and sibling assets", () => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; @@ -1123,6 +1169,35 @@ describe("AssetAccess", () => { expect(yield* resolveAsset(token, "../secret.txt")).toBeNull(); expect(yield* resolveAsset(token, ".env")).toBeNull(); expect(yield* resolveAsset(`${token}tampered`, "report.html")).toBeNull(); + + const reportsDirectory = path.join(root, ".reports"); + yield* fileSystem.makeDirectory(path.join(reportsDirectory, ".cache"), { recursive: true }); + const dotHtmlPath = path.join(reportsDirectory, "report.html"); + const dotCssPath = path.join(reportsDirectory, "report.css"); + yield* fileSystem.writeFileString(dotHtmlPath, "

Quarterly report

"); + yield* fileSystem.writeFileString(dotCssPath, "body { color: red; }"); + yield* fileSystem.writeFileString(path.join(reportsDirectory, ".cache", "hidden.css"), ""); + const dotUrl = yield* issueAssetUrl({ + resource: { + _tag: "workspace-file", + threadId: ThreadId.make("thread-1"), + path: dotHtmlPath, + }, + workspaceRoot: root, + }); + const dotSuffix = dotUrl.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length); + const dotToken = dotSuffix.slice(0, dotSuffix.indexOf("/")); + expect(yield* resolveAsset(dotToken, "report.html")).toEqual({ + kind: "file", + path: yield* fileSystem.realPath(dotHtmlPath), + renderIntent: "file-preview", + }); + expect(yield* resolveAsset(dotToken, "report.css")).toEqual({ + kind: "file", + path: yield* fileSystem.realPath(dotCssPath), + renderIntent: "file-preview", + }); + expect(yield* resolveAsset(dotToken, ".cache/hidden.css")).toBeNull(); for (const extension of [ "odt", "ods", diff --git a/apps/server/src/assets/AssetAccess.ts b/apps/server/src/assets/AssetAccess.ts index ba6254e8ca639..7dba4ecfa7a38 100644 --- a/apps/server/src/assets/AssetAccess.ts +++ b/apps/server/src/assets/AssetAccess.ts @@ -314,7 +314,8 @@ const resolveCanonicalWorkspaceFile = Effect.fn("AssetAccess.resolveCanonicalWor function* (input: { readonly workspaceRoot: string; readonly relativePath: string; - readonly previewDependency?: true; + /** The HTML entry's folder, relative to the root, when serving one of its dependencies. */ + readonly previewBaseRelativePath?: string; }) { const fileSystem = yield* FileSystem.FileSystem; const workspacePaths = yield* WorkspacePaths.WorkspacePaths; @@ -336,7 +337,18 @@ const resolveCanonicalWorkspaceFile = Effect.fn("AssetAccess.resolveCanonicalWor const relative = path.relative(canonicalRoot.value, canonicalFile.value); if (relative === "" || relative.startsWith("..") || path.isAbsolute(relative)) return null; - if (input.previewDependency && !isPreviewDependencyPath(relative, path)) return null; + if (input.previewBaseRelativePath !== undefined) { + // The opened entry's own folder may be hidden; nothing below it, or reached outside it, may. + const canonicalBase = yield* ProjectFaviconResolver.optionOnNotFound( + fileSystem.realPath(path.join(canonicalRoot.value, input.previewBaseRelativePath)), + ); + const belowBase = Option.isSome(canonicalBase) + ? path.relative(canonicalBase.value, canonicalFile.value) + : ".."; + const dependency = + belowBase.startsWith("..") || path.isAbsolute(belowBase) ? relative : belowBase; + if (!isPreviewDependencyPath(dependency, path)) return null; + } const info = yield* ProjectFaviconResolver.optionOnNotFound( fileSystem.stat(canonicalFile.value), @@ -350,7 +362,7 @@ const resolveCanonicalWorkspaceFile = Effect.fn("AssetAccess.resolveCanonicalWor const resolveCanonicalWorkspaceFileForRequest = (input: { readonly workspaceRoot: string; readonly relativePath: string; - readonly previewDependency?: true; + readonly previewBaseRelativePath?: string; }) => resolveCanonicalWorkspaceFile(input).pipe( Effect.tapError((cause) => @@ -1089,7 +1101,7 @@ export const resolveAsset = Effect.fn("AssetAccess.resolveAsset")(function* ( const workspaceFile = yield* resolveCanonicalWorkspaceFileForRequest({ workspaceRoot: claims.workspaceRoot, relativePath: joinedRelativePath, - previewDependency: true, + previewBaseRelativePath: claims.baseRelativePath, }); return workspaceFile ? ({ kind: "file", path: workspaceFile, renderIntent: "file-preview" } satisfies ResolvedAsset) diff --git a/scripts/scenarios/html-report-in-dot-folder.e2e.ts b/scripts/scenarios/html-report-in-dot-folder.e2e.ts new file mode 100644 index 0000000000000..562addf766294 --- /dev/null +++ b/scripts/scenarios/html-report-in-dot-folder.e2e.ts @@ -0,0 +1,27 @@ +import { expect } from "e2e"; + +import { test, WEB } from "./t3.ts"; + +test( + "An explicitly opened HTML report in a dot-prefixed folder renders its contents", + WEB, + async ({ t3, app, screen, browser }) => { + const project = await t3.project("demo", { + ".reports/report.html": "

Quarterly report

", + }); + const thread = await t3.thread({ project, title: "Review report", messages: ["Start"] }); + await t3.open(thread); + await expect(screen.getByText("fixture turn complete", { exact: false })).toBeVisible(); + + await browser.keyboard.press("Control+p"); + await screen.getByPlaceholder("Search files…").fill("report.html"); + await screen.getByRole("option", "report.html", { exact: false }).tap(); + + const document = browser.frameLocator('iframe[title=".reports/report.html"]'); + try { + await expect(document.locator("body")).toContainText("Quarterly report"); + } finally { + await app.screenshot("report-preview"); + } + }, +); From 0f326458521e6f86355fc413074f45fdd6557921 Mon Sep 17 00:00:00 2001 From: Yukun Shan <92423096+nateEc@users.noreply.github.com> Date: Fri, 20 Nov 2026 04:07:10 +0800 Subject: [PATCH 24/97] fix(dev): avoid dependency-triggered server restarts on Windows (#38870) Co-authored-by: Julius Marminge --- apps/server/package.json | 2 +- apps/server/scripts/dev.ts | 99 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 100 insertions(+), 1 deletion(-) create mode 100644 apps/server/scripts/dev.ts diff --git a/apps/server/package.json b/apps/server/package.json index bea918f407870..af62337797439 100644 --- a/apps/server/package.json +++ b/apps/server/package.json @@ -15,7 +15,7 @@ ], "type": "module", "scripts": { - "dev": "node --watch --watch-path=src --watch-path=../../packages --watch-path=package.json src/bin.ts", + "dev": "node scripts/dev.ts", "dev:built": "vp run dev", "build:bundle": "vp pack", "build:exe": "node scripts/cli.ts build-exe", diff --git a/apps/server/scripts/dev.ts b/apps/server/scripts/dev.ts new file mode 100644 index 0000000000000..544d4ea61dbee --- /dev/null +++ b/apps/server/scripts/dev.ts @@ -0,0 +1,99 @@ +// @effect-diagnostics nodeBuiltinImport:off globalConsole:off globalDate:off globalTimers:off - Standalone Node watch launcher. +import * as NodeChildProcess from "node:child_process"; +import * as NodeFS from "node:fs"; +import * as NodeOS from "node:os"; +import * as NodePath from "node:path"; + +const serverDir = NodePath.resolve(import.meta.dirname, ".."); +const entry = "src/bin.ts"; +const packageDirs = [ + serverDir, + ...NodeFS.globSync("../../packages/*/package.json", { cwd: serverDir }).map((file) => + NodePath.resolve(serverDir, NodePath.dirname(file)), + ), +]; + +let child: NodeChildProcess.ChildProcess | undefined; +let startedAt = 0; +let restartPending = false; +let stopping = false; +let debounce: NodeJS.Timeout | undefined; +const changedPaths = new Set(); + +// `node --watch` cannot be used: on Windows, libuv reports NTFS last-access updates as changes, +// so merely reading a source file (or an installed dependency directory) restarted the server. +// A path counts as changed only when it is gone or written since the running server started. +const isWrittenSinceStart = (path: string) => { + try { + const stats = NodeFS.statSync(path); + return !stats.isDirectory() && Math.max(stats.mtimeMs, stats.ctimeMs) >= startedAt; + } catch { + return true; + } +}; + +const start = () => { + startedAt = Date.now(); + restartPending = false; + child = NodeChildProcess.spawn(process.execPath, [entry, ...process.argv.slice(2)], { + cwd: serverDir, + stdio: "inherit", + }); + child.on("error", (error) => console.error(error)); + child.on("exit", (code, signal) => { + child = undefined; + if (stopping) { + process.exitCode = code ?? (signal === null ? 1 : 128 + NodeOS.constants.signals[signal]); + return; + } + if (restartPending) return start(); + console.log( + `[dev] '${entry}' exited (${signal ?? code}). Waiting for file changes before restarting...`, + ); + }); +}; + +const flush = () => { + debounce = undefined; + const changed = [...changedPaths].find(isWrittenSinceStart); + changedPaths.clear(); + if (changed === undefined || stopping || restartPending) return; + console.log(`[dev] Restarting '${entry}': ${NodePath.relative(serverDir, changed)} changed`); + if (!child) return start(); + restartPending = true; + child.kill("SIGTERM"); +}; + +const onChange = (path: string) => { + changedPaths.add(path); + debounce ??= setTimeout(flush, 200); +}; + +// Watch only each workspace package's src and package.json, never its node_modules. +const watchers = packageDirs.flatMap((dir) => { + const src = NodePath.join(dir, "src"); + return [ + NodeFS.watch(dir, (_event, name) => { + if (name === "package.json") onChange(NodePath.join(dir, name)); + }), + ...(NodeFS.existsSync(src) + ? [ + NodeFS.watch(src, { recursive: true }, (_event, name) => + onChange(name ? NodePath.join(src, name) : src), + ), + ] + : []), + ]; +}); + +const stop = (signal: NodeJS.Signals) => { + stopping = true; + clearTimeout(debounce); + for (const watcher of watchers) watcher.close(); + if (child) child.kill(signal); +}; +process.on("SIGINT", () => stop("SIGINT")); +process.on("SIGTERM", () => stop("SIGTERM")); +process.on("SIGHUP", () => stop("SIGTERM")); + +start(); From 1d3932570c8bdc3ec52465270e7d66db4ce58db5 Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Thu, 19 Nov 2026 21:09:29 +0100 Subject: [PATCH 25/97] fix(themes): keep escaped quotes in CSS text (#39296) Co-authored-by: Julius Marminge --- packages/shared/src/themeCss.test.ts | 4 ++ packages/shared/src/themeCss.ts | 29 +++++++----- ...eme-renders-escaped-quotation-marks.e2e.ts | 44 +++++++++++++++++++ 3 files changed, 66 insertions(+), 11 deletions(-) create mode 100644 scripts/scenarios/theme-renders-escaped-quotation-marks.e2e.ts diff --git a/packages/shared/src/themeCss.test.ts b/packages/shared/src/themeCss.test.ts index 9aecb1c1f7931..38cc33a793dbd 100644 --- a/packages/shared/src/themeCss.test.ts +++ b/packages/shared/src/themeCss.test.ts @@ -21,6 +21,10 @@ describe("themeCssValueFetches", () => { ["background-image", `url("${SVG_WITH_OWN_GRADIENT}")`, false], // The url( sits inside a string, so the address after that string is a real remote url(). ["content", `"url('data:" url("https://evil.example/a") "'"`, true], + ["--leak", '/* " */ url(https://evil.example/a) /* " */', true], + ["content", String.raw`"Theme preview: \"ready\""`, false], + ["--label", String.raw`'It\'s ready'`, false], + ["content", String.raw`url("#icon") / "The \"ready\" icon"`, false], ["filter", 'url("#blur")', false], ["background-image", "var(--pattern)", false], ["color", "red", false], diff --git a/packages/shared/src/themeCss.ts b/packages/shared/src/themeCss.ts index 6fa05e57336c9..9668040f97be4 100644 --- a/packages/shared/src/themeCss.ts +++ b/packages/shared/src/themeCss.ts @@ -9,19 +9,25 @@ const URL_NOT_LOCAL = /url\((?![ \t\n\f\r]*["']?(?:data:|#))/i; const ESCAPE = String.raw`\\(?:(?:[0-9a-fA-F]{6}|[0-9a-fA-F]{1,5}(?![0-9a-fA-F]))(?:\r\n|[\n\r\f])?|\r\n|[^0-9a-fA-F])`; const STRING = String.raw`"(?:${ESCAPE}|[^"\\\n\r\f])*"|'(?:${ESCAPE}|[^'\\\n\r\f])*'`; const URL_OR_STRING = String.raw`url\((?![ \t\n\f\r]*["'])([^)]*)|url\([ \t\n\f\r]*(${STRING})|${STRING}|${ESCAPE}`; -const VALUE_TOKENS = new RegExp(URL_OR_STRING, "gi"); -const STYLESHEET_TOKENS = new RegExp(String.raw`\/\*[\s\S]*?\*\/|${URL_OR_STRING}`, "gi"); +const CSS_TOKENS = new RegExp(String.raw`\/\*[\s\S]*?\*\/|${URL_OR_STRING}`, "gi"); /** - * The code with its strings removed, keeping `url(` where a quoted url() can load a file. A - * stylesheet also loses its comments, and an unquoted url() there is judged by its address too. + * The code with its strings and comments removed, keeping `url(` where a quoted url() can load a + * file. A declaration value keeps a comment or quoted url() that holds an escape. In a stylesheet + * an unquoted url() is judged by its address too. */ function withoutStrings(code: string, stylesheet: boolean): string { - const tokens = stylesheet ? STYLESHEET_TOKENS : VALUE_TOKENS; - return code.replace(tokens, (token, address?: string, urlString?: string) => { + return code.replace(CSS_TOKENS, (token, address?: string, urlString?: string) => { const url = stylesheet ? (address ?? urlString) : urlString; - if (url !== undefined) return /^[ \t\n\f\r]*["']?(?:data:|#)/i.test(url) ? "" : "url("; - return /^["'/]/.test(token) ? "" : token; + if (url !== undefined) { + if (!stylesheet && url.includes("\\")) return token; + return /^[ \t\n\f\r]*["']?(?:data:|#)/i.test(url) ? "" : "url("; + } + if (token.startsWith("/*")) { + if (stylesheet) return ""; + return token.includes("\\") ? token : " "; + } + return /^["']/.test(token) ? "" : token; }); } @@ -31,11 +37,12 @@ function fetchesOutsideStrings(code: string): boolean { /** * Whether one declaration value can load a remote file. Clients drop those declarations. - * A value with var() stays unparsed until use, and an escape can spell `var` or `url` in it, - * so every value that still has a backslash is refused. + * Values with var() can keep escapes that spell `var` or `url`. Refuse escapes that survive + * removing plain strings, including escapes in URL addresses. */ export function themeCssValueFetches(value: string): boolean { - return value.includes("\\") || fetchesOutsideStrings(withoutStrings(value, false)); + const code = withoutStrings(value, false); + return code.includes("\\") || fetchesOutsideStrings(code); } /** A text check for early feedback. CSS escapes can dodge it; the client check is the guard. */ diff --git a/scripts/scenarios/theme-renders-escaped-quotation-marks.e2e.ts b/scripts/scenarios/theme-renders-escaped-quotation-marks.e2e.ts new file mode 100644 index 0000000000000..8e26cf6a63712 --- /dev/null +++ b/scripts/scenarios/theme-renders-escaped-quotation-marks.e2e.ts @@ -0,0 +1,44 @@ +/// +import { expect } from "e2e"; + +import { test, WEB } from "./t3.ts"; + +const CONTENT = String.raw`"Theme preview: \"ready\""`; + +test( + "A theme renders custom text containing quotation marks", + WEB, + async ({ t3, app, screen, browser }) => { + await t3.project("demo"); + await t3.open("/settings/appearance"); + await screen.getByRole("button", "Add theme", { exact: true }).tap(); + const dialog = screen.getByRole("dialog", "Add a theme"); + await dialog.getByRole("textbox", "Theme JSON").fill( + JSON.stringify({ + version: 1, + name: "Quoted Preview", + appearance: "light", + colors: { canvas: "#ffffff", accent: "#734ee4" }, + css: `[data-settings-page-scroll]::before { display: block; content: ${CONTENT}; }`, + }), + ); + await dialog.getByRole("button", "Add theme", { exact: true }).tap(); + await dialog.waitFor({ state: "hidden" }); + await screen.getByRole("button", "Use Quoted Preview theme", { exact: true }).tap(); + + try { + await expect + .poll( + () => + browser.evaluate(() => { + const settings = document.querySelector("[data-settings-page-scroll]"); + return settings ? getComputedStyle(settings, "::before").content : ""; + }), + { message: "The selected theme displays its custom text with quotation marks" }, + ) + .toBe(CONTENT); + } finally { + await app.screenshot("theme-custom-text"); + } + }, +); From dbee5a0af04ea4a3db351669003d6281953d2c38 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 19 Nov 2026 12:11:06 -0800 Subject: [PATCH 26/97] fix(mobile,web): saves, account switches and registrations report their own outcome (#38911) Co-authored-by: Claude Fable 5.2 --- .../remoteRegistration.test.ts | 16 +++ .../agent-awareness/remoteRegistration.ts | 57 ++++---- .../SettingsDiagnosticsRouteScreen.tsx | 14 +- .../features/home/home-list-options.test.tsx | 10 +- .../src/features/home/home-list-options.ts | 9 +- .../layout/workspace/SavedViewsMenu.tsx | 21 +-- .../layout/workspace/WorkspaceTabsContext.tsx | 9 +- .../PullRequestMergeControls.tsx | 8 +- .../usePullRequestActivityFilter.ts | 9 +- .../pull-requests/usePullRequestFileFilter.ts | 15 +- .../usePullRequestListControls.ts | 25 ++-- .../settings/SettingsFollowUpRouteScreen.tsx | 11 +- .../settings/SettingsKeyboardRouteScreen.tsx | 11 +- .../settings/SettingsLanguageRouteScreen.tsx | 11 +- .../SettingsNavigationRouteScreen.tsx | 35 ++--- .../SettingsNotificationsRouteScreen.tsx | 9 +- .../SettingsProjectGroupingRouteScreen.tsx | 11 +- ...SettingsServerControlsRouteScreen.test.tsx | 2 +- .../settings/SettingsVoiceRouteScreen.tsx | 15 +- .../settings/ThreadSettingsSections.tsx | 16 ++- .../AppearancePreferencesProvider.tsx | 13 +- .../sections/ToolCallsAppearanceSection.tsx | 11 +- .../components/DatabaseStorageNotice.tsx | 15 +- .../showcase/ShowcaseCaptureCoordinator.tsx | 8 +- .../use-thread-list-v2-shelf-preferences.ts | 13 +- .../threads/useRememberThreadProject.ts | 11 +- .../voice-input/VoiceInputProvider.tsx | 8 +- apps/mobile/src/state/preferences.test.ts | 80 +++++++---- apps/mobile/src/state/preferences.ts | 135 ++++++++---------- apps/web/src/cloud/managedAuth.tsx | 35 ++--- 30 files changed, 367 insertions(+), 276 deletions(-) diff --git a/apps/mobile/src/features/agent-awareness/remoteRegistration.test.ts b/apps/mobile/src/features/agent-awareness/remoteRegistration.test.ts index d4438911eb7bf..c7f2e02468ea2 100644 --- a/apps/mobile/src/features/agent-awareness/remoteRegistration.test.ts +++ b/apps/mobile/src/features/agent-awareness/remoteRegistration.test.ts @@ -599,6 +599,22 @@ describe("makeRelayDeviceRegistrationRequest", () => { }).pipe(Effect.provide(layerRelayTest)); }); + it.effect("leaves the signed-out status alone when an obsolete registration fails", () => { + Constants.expoConfig!.extra = { + relay: { + url: "https://relay.example.test/", + }, + }; + vi.mocked(loadOrCreateAgentAwarenessDeviceId).mockRejectedValue(new Error("storage failure")); + setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a")); + setAgentAwarenessRelayTokenProvider(null); + + return Effect.gen(function* () { + yield* runBackgroundOperations(); + expect(getAgentAwarenessRegistrationStatus()).toBe("unknown"); + }).pipe(Effect.provide(layerRelayTest)); + }); + it.effect("does not re-register the same account when nothing has changed", () => { Constants.expoConfig!.extra = { relay: { diff --git a/apps/mobile/src/features/agent-awareness/remoteRegistration.ts b/apps/mobile/src/features/agent-awareness/remoteRegistration.ts index 2c995bd8eafa8..b50da67e86433 100644 --- a/apps/mobile/src/features/agent-awareness/remoteRegistration.ts +++ b/apps/mobile/src/features/agent-awareness/remoteRegistration.ts @@ -660,7 +660,8 @@ function startPendingDeviceRegistration(): void { ); if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { // Refresh failures leave the relay's accepted registration intact; preserve registered status. - if (registrationStatus !== "registered") { + // A sign-out or account switch meanwhile owns the status, so an obsolete run leaves it alone. + if (generation === deviceRegistrationGeneration && registrationStatus !== "registered") { setRegistrationStatus("failed"); } logRegistrationError(next.context, squashAtomCommandFailure(result)); @@ -759,14 +760,6 @@ const registerDevice = Effect.fn("remoteRegistration.registerDevice")(function* ); }); -function registerDeviceForCurrentUser(): Effect.Effect< - void, - AgentAwarenessRegistrationError, - ManagedRelay.ManagedRelayClient -> { - return registerDevice(undefined); -} - function ensurePushTokenListener(): void { if (pushTokenSubscription || !canRegisterPushNotifications()) { return; @@ -842,31 +835,37 @@ export function refreshAgentAwarenessRegistration(): Effect.Effect< never, ManagedRelay.ManagedRelayClient > { - return registerDeviceForCurrentUser().pipe( - Effect.catch((error) => - Effect.sync(() => { - if (registrationStatus !== "registered") { - setRegistrationStatus("failed"); - } - logRegistrationError("device registration refresh failed", error); - }), - ), - ); + return Effect.suspend(() => { + const generation = deviceRegistrationGeneration; + return registerDevice(undefined, generation).pipe( + Effect.catch((error) => + Effect.sync(() => { + if (generation === deviceRegistrationGeneration && registrationStatus !== "registered") { + setRegistrationStatus("failed"); + } + logRegistrationError("device registration refresh failed", error); + }), + ), + ); + }); } export function updateAgentAwarenessRegistrationPreferences( preferencesOverride: Partial, ): Effect.Effect { - return registerDevice({ preferencesOverride }).pipe( - Effect.tapError((error) => - Effect.sync(() => { - if (registrationStatus !== "registered") { - setRegistrationStatus("failed"); - } - logRegistrationError("device preference registration refresh failed", error); - }), - ), - ); + return Effect.suspend(() => { + const generation = deviceRegistrationGeneration; + return registerDevice({ preferencesOverride }, generation).pipe( + Effect.tapError((error) => + Effect.sync(() => { + if (generation === deviceRegistrationGeneration && registrationStatus !== "registered") { + setRegistrationStatus("failed"); + } + logRegistrationError("device preference registration refresh failed", error); + }), + ), + ); + }); } export function __resetAgentAwarenessRemoteRegistrationForTest(): void { diff --git a/apps/mobile/src/features/diagnostics/SettingsDiagnosticsRouteScreen.tsx b/apps/mobile/src/features/diagnostics/SettingsDiagnosticsRouteScreen.tsx index 63ea30d9a8820..b5a52d92755d3 100644 --- a/apps/mobile/src/features/diagnostics/SettingsDiagnosticsRouteScreen.tsx +++ b/apps/mobile/src/features/diagnostics/SettingsDiagnosticsRouteScreen.tsx @@ -3,9 +3,8 @@ import { ScreenScrollView as ScrollView } from "../../components/ui/ScreenScroll import * as Application from "expo-application"; import Constants from "expo-constants"; import * as Updates from "expo-updates"; -import { useAtomSet, useAtomValue } from "@effect/atom-react"; +import { useAtomValue } from "@effect/atom-react"; import * as Effect from "effect/Effect"; -import * as Exit from "effect/Exit"; import * as Schema from "effect/Schema"; import { AsyncResult, Atom } from "effect/reactivity"; import { T, useGT } from "gt-react-native"; @@ -16,7 +15,8 @@ import { useSafeAreaInsets } from "react-native-safe-area-context"; import { SymbolView } from "../../components/ui/AppSymbol"; import { AppText as Text } from "../../components/ui/AppText"; import { tryCopyTextWithHaptic } from "../../lib/copyTextWithHaptic"; -import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/preferences"; +import { mobilePreferencesAtom, saveMobilePreferences } from "../../state/preferences"; +import { useAtomCommand } from "../../state/use-atom-command"; import { crashReportingAvailable, setCrashReportsEnabled } from "../observability/observe"; import { ListActionRow as SettingsActionRow } from "../../components/ui/ListActionRow"; import { SettingsScreen } from "../settings/components/SettingsScreen"; @@ -156,7 +156,7 @@ export function SettingsDiagnosticsRouteScreen() { function CrashReportsSetting() { const preferences = useAtomValue(mobilePreferencesAtom); - const savePreferences = useAtomSet(updateMobilePreferencesAtom, { mode: "promiseExit" }); + const savePreferences = useAtomCommand(saveMobilePreferences, { reportFailure: false }); // One change at a time, so a slow save never turns sending back on after a later opt-out. const [saving, setSaving] = useState(false); const gt = useGT(); @@ -170,9 +170,9 @@ function CrashReportsSetting() { // Sending stops before the save and starts only after it. if (!value) void setCrashReportsEnabled(false); savePreferences({ crashReportsEnabled: value }) - .then((exit) => { - if (Exit.isFailure(exit)) { - console.warn("[diagnostics] could not save the crash report setting", exit.cause); + .then((result) => { + if (result._tag === "Failure") { + console.warn("[diagnostics] could not save the crash report setting", result.cause); return value ? undefined : setCrashReportsEnabled(true); } return value ? setCrashReportsEnabled(true) : undefined; diff --git a/apps/mobile/src/features/home/home-list-options.test.tsx b/apps/mobile/src/features/home/home-list-options.test.tsx index f25d4ff690851..475d00dae69ac 100644 --- a/apps/mobile/src/features/home/home-list-options.test.tsx +++ b/apps/mobile/src/features/home/home-list-options.test.tsx @@ -5,10 +5,12 @@ import { expect, it, vi } from "vite-plus/test"; const harness = vi.hoisted(() => ({ saved: [] as unknown[] })); -vi.mock("../../state/preferences", () => ({ updateMobilePreferencesAtom: {} })); -vi.mock("@effect/atom-react", async (importOriginal) => ({ - ...(await importOriginal()), - useAtomSet: () => (value: unknown) => harness.saved.push(value), +vi.mock("../../state/preferences", () => ({ saveMobilePreferences: {} })); +vi.mock("../../state/use-atom-command", () => ({ + useAtomCommand: () => async (value: unknown) => { + harness.saved.push(value); + return { _tag: "Success", value: undefined }; + }, })); import { HomeListOptionsProvider, useHomeListOptions } from "./home-list-options"; diff --git a/apps/mobile/src/features/home/home-list-options.ts b/apps/mobile/src/features/home/home-list-options.ts index 09c8be2c9a7c1..c41765be40e98 100644 --- a/apps/mobile/src/features/home/home-list-options.ts +++ b/apps/mobile/src/features/home/home-list-options.ts @@ -1,11 +1,12 @@ import type { EnvironmentId, SidebarProjectGroupingMode } from "@t3tools/contracts"; import { DEFAULT_SIDEBAR_PROJECT_SORT_ORDER } from "@t3tools/contracts"; -import { RegistryContext, useAtomSet, useAtomValue } from "@effect/atom-react"; +import { RegistryContext, useAtomValue } from "@effect/atom-react"; import { Atom } from "effect/reactivity"; import { createContext, createElement, useContext, useState, type PropsWithChildren } from "react"; import type { ThreadListFilters } from "../../persistence/mobile-preferences"; -import { updateMobilePreferencesAtom } from "../../state/preferences"; +import { saveMobilePreferences } from "../../state/preferences"; +import { useAtomCommand } from "../../state/use-atom-command"; import type { HomeProjectSortOrder } from "./homeThreadList"; export interface HomeListOptions { @@ -48,7 +49,7 @@ export function HomeListOptionsProvider({ const registry = useContext(RegistryContext); const [optionsAtom] = useState(() => Atom.make(defaultHomeListOptions(savedFilters))); const options = useAtomValue(optionsAtom); - const savePreferences = useAtomSet(updateMobilePreferencesAtom); + const savePreferences = useAtomCommand(saveMobilePreferences); // Only the scope persists; the sort order is per session. Updates read the // registry, so several in one event each build on the last and save it. const updateOptions = (patch: Partial) => { @@ -59,7 +60,7 @@ export function HomeListOptionsProvider({ next.selectedEnvironmentId !== current.selectedEnvironmentId || next.selectedProjectKey !== current.selectedProjectKey ) { - savePreferences({ + void savePreferences({ threadListFilters: { environmentId: next.selectedEnvironmentId, projectKey: next.selectedProjectKey, diff --git a/apps/mobile/src/features/layout/workspace/SavedViewsMenu.tsx b/apps/mobile/src/features/layout/workspace/SavedViewsMenu.tsx index 79f3ab0ff04a2..c7f54cb71d45f 100644 --- a/apps/mobile/src/features/layout/workspace/SavedViewsMenu.tsx +++ b/apps/mobile/src/features/layout/workspace/SavedViewsMenu.tsx @@ -1,4 +1,4 @@ -import { useAtomSet, useAtomValue } from "@effect/atom-react"; +import { useAtomValue } from "@effect/atom-react"; import { type SavedViewIdentity as SavedViewIdentitySchema, savedViewNameError, @@ -12,7 +12,8 @@ import { prompt as showTextInputDialog } from "../../../components/ui/Dialog"; import type { MenuProps } from "../../../components/ui/Menu.types"; import { uuidv4 } from "../../../lib/uuid"; import type { Preferences } from "../../../persistence/mobile-preferences"; -import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../../state/preferences"; +import { mobilePreferencesAtom, saveMobilePreferences } from "../../../state/preferences"; +import { useAtomCommand } from "../../../state/use-atom-command"; import { ListFilterMenu } from "./ListFilterMenu"; type SavedViewIdentity = typeof SavedViewIdentitySchema.Type; @@ -40,7 +41,7 @@ export function SavedViewsMenu({ const gt = useGT(); const messages = useMessages(); const preferences = useAtomValue(mobilePreferencesAtom); - const savePreferences = useAtomSet(updateMobilePreferencesAtom, { mode: "promise" }); + const savePreferences = useAtomCommand(saveMobilePreferences, { reportFailure: false }); const ready = AsyncResult.isSuccess(preferences) && !preferences.waiting; const views: ReadonlyArray = AsyncResult.isSuccess(preferences) ? (read(preferences.value) ?? EMPTY_SAVED_VIEWS) @@ -74,12 +75,13 @@ export function SavedViewsMenu({ async function persist(transform: (current: ReadonlyArray) => ReadonlyArray) { setBusy(true); - let saved = true; - try { - await savePreferences({ - transform: (current) => write(transform(read(current) ?? EMPTY_SAVED_VIEWS)), - }); - } catch { + const saved = + ( + await savePreferences({ + transform: (current) => write(transform(read(current) ?? EMPTY_SAVED_VIEWS)), + }) + )._tag === "Success"; + if (!saved) { Alert.alert( gt( "{list, select, pullRequest {Could not save PR views} other {Could not save issue views}}", @@ -89,7 +91,6 @@ export function SavedViewsMenu({ ), gt("The device could not save your views. Try again."), ); - saved = false; } setBusy(false); return saved; diff --git a/apps/mobile/src/features/layout/workspace/WorkspaceTabsContext.tsx b/apps/mobile/src/features/layout/workspace/WorkspaceTabsContext.tsx index 07d1006839c0b..03b8ed4b23ba1 100644 --- a/apps/mobile/src/features/layout/workspace/WorkspaceTabsContext.tsx +++ b/apps/mobile/src/features/layout/workspace/WorkspaceTabsContext.tsx @@ -1,8 +1,9 @@ -import { RegistryContext, useAtomSet, useAtomValue } from "@effect/atom-react"; +import { RegistryContext, useAtomValue } from "@effect/atom-react"; import { AsyncResult, Atom } from "effect/reactivity"; import { createContext, use, useState, type Dispatch, type ReactNode } from "react"; -import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../../state/preferences"; +import { mobilePreferencesAtom, saveMobilePreferences } from "../../../state/preferences"; +import { useAtomCommand } from "../../../state/use-atom-command"; import { isSharedSlotTab, sharedSlotAbsentee, @@ -88,11 +89,11 @@ export function WorkspaceTabsProvider(props: { const registry = use(RegistryContext); const [model] = useState(() => createWorkspaceTabsModel(props.initialTab)); const state = useAtomValue(model.resolved); - const savePreferences = useAtomSet(updateMobilePreferencesAtom); + const savePreferences = useAtomCommand(saveMobilePreferences); const dispatch = (action: WorkspaceTabsAction) => { registry.set(model.stored, workspaceTabsReducer(registry.get(model.resolved), action)); if (action.type === "select" && isSharedSlotTab(action.tab)) - savePreferences({ sharedSlotTab: action.tab }); + void savePreferences({ sharedSlotTab: action.tab }); }; const context = { state, diff --git a/apps/mobile/src/features/pull-requests/PullRequestMergeControls.tsx b/apps/mobile/src/features/pull-requests/PullRequestMergeControls.tsx index f33104765a5af..42894c06b3785 100644 --- a/apps/mobile/src/features/pull-requests/PullRequestMergeControls.tsx +++ b/apps/mobile/src/features/pull-requests/PullRequestMergeControls.tsx @@ -1,6 +1,6 @@ import { errorDisplayMessage } from "@t3tools/client-runtime/errors"; import * as Dialog from "../../components/ui/Dialog"; -import { useAtomRefresh, useAtomSet, useAtomValue } from "@effect/atom-react"; +import { useAtomRefresh, useAtomValue } from "@effect/atom-react"; import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime"; import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients"; import { changeRequestTermKind } from "../../lib/changeRequestTerm"; @@ -14,7 +14,7 @@ import { AppText as Text } from "../../components/ui/AppText"; import { Button } from "../../components/ui/Button"; import { SplitButton } from "../../components/ui/SplitButton"; import { useEnvironmentServerConfig } from "../../state/entities"; -import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/preferences"; +import { mobilePreferencesAtom, saveMobilePreferences } from "../../state/preferences"; import { composerPullRequests } from "../../state/pull-requests"; import { useAtomCommand } from "../../state/use-atom-command"; import { @@ -50,7 +50,7 @@ export function PullRequestMergeControls(props: { const stateAction = usePullRequestAction(props.params, pr); const preferences = useAtomValue(mobilePreferencesAtom); const serverSettings = useEnvironmentServerConfig(target.environmentId)?.settings; - const savePreferences = useAtomSet(updateMobilePreferencesAtom); + const savePreferences = useAtomCommand(saveMobilePreferences); const runAction = useAtomCommand(composerPullRequests.runAction, { reportFailure: false }); const refreshDetail = useAtomRefresh(composerPullRequests.detail(target)); const refreshActivity = useAtomRefresh(composerPullRequests.activity(target)); @@ -336,7 +336,7 @@ export function PullRequestMergeControls(props: { const selected = methods.find((method) => method === id); if (selected) { setSelectedMethod(selected); - savePreferences({ pullRequestMergeMethod: selected }); + void savePreferences({ pullRequestMergeMethod: selected }); } else if (id === autoAction && canAutoMerge) confirm(autoAction); }} /> diff --git a/apps/mobile/src/features/pull-requests/usePullRequestActivityFilter.ts b/apps/mobile/src/features/pull-requests/usePullRequestActivityFilter.ts index 1f2d0d8582de1..246bdad015131 100644 --- a/apps/mobile/src/features/pull-requests/usePullRequestActivityFilter.ts +++ b/apps/mobile/src/features/pull-requests/usePullRequestActivityFilter.ts @@ -1,8 +1,9 @@ -import { useAtomSet, useAtomValue } from "@effect/atom-react"; +import { useAtomValue } from "@effect/atom-react"; import { AsyncResult } from "effect/reactivity"; import { useState } from "react"; import type { PullRequestActivityVisibility } from "../../persistence/mobile-preferences"; -import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/preferences"; +import { mobilePreferencesAtom, saveMobilePreferences } from "../../state/preferences"; +import { useAtomCommand } from "../../state/use-atom-command"; import { DEFAULT_ACTIVITY_FILTER, type ActivityFilter } from "./pullRequestActivityFilter"; const SHOW_EVERYTHING: PullRequestActivityVisibility = { bots: true, resolved: true }; @@ -13,7 +14,7 @@ const SHOW_EVERYTHING: PullRequestActivityVisibility = { bots: true, resolved: t */ export function usePullRequestActivityFilter(link: string | undefined) { const preferences = useAtomValue(mobilePreferencesAtom); - const savePreferences = useAtomSet(updateMobilePreferencesAtom); + const savePreferences = useAtomCommand(saveMobilePreferences); const [view, setView] = useState(() => ({ kind: link === "commits" ? ("commits" as const) : DEFAULT_ACTIVITY_FILTER.kind, newestFirst: DEFAULT_ACTIVITY_FILTER.newestFirst, @@ -35,7 +36,7 @@ export function usePullRequestActivityFilter(link: string | undefined) { filter, setFilter: (next: ActivityFilter) => { if (visibilityChanged(next)) { - savePreferences({ + void savePreferences({ pullRequestActivityVisibility: { bots: next.bots, resolved: next.resolved }, }); } diff --git a/apps/mobile/src/features/pull-requests/usePullRequestFileFilter.ts b/apps/mobile/src/features/pull-requests/usePullRequestFileFilter.ts index d8d824c1ae5fc..220bcadb0f5be 100644 --- a/apps/mobile/src/features/pull-requests/usePullRequestFileFilter.ts +++ b/apps/mobile/src/features/pull-requests/usePullRequestFileFilter.ts @@ -1,13 +1,14 @@ -import { useAtomSet, useAtomValue } from "@effect/atom-react"; +import { useAtomValue } from "@effect/atom-react"; import { AsyncResult } from "effect/reactivity"; import { useMemo } from "react"; import type { ReviewParsedDiff } from "../review/reviewModel"; -import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/preferences"; +import { mobilePreferencesAtom, saveMobilePreferences } from "../../state/preferences"; +import { useAtomCommand } from "../../state/use-atom-command"; import { filterPullRequestTestFiles } from "./pullRequestFileFilters"; export function usePullRequestFileFilter(parsed: ReviewParsedDiff, includePath?: string) { const preferences = useAtomValue(mobilePreferencesAtom); - const savePreferences = useAtomSet(updateMobilePreferencesAtom); + const savePreferences = useAtomCommand(saveMobilePreferences); const hideTestFiles = AsyncResult.isSuccess(preferences) && preferences.value.pullRequestHideTestFiles === true; const visible = useMemo( @@ -20,7 +21,11 @@ export function usePullRequestFileFilter(parsed: ReviewParsedDiff, includePath?: parsed: visible, hideTestFiles, hiddenCount, - toggle: () => savePreferences({ pullRequestHideTestFiles: !hideTestFiles }), - showAll: () => savePreferences({ pullRequestHideTestFiles: false }), + toggle: () => { + void savePreferences({ pullRequestHideTestFiles: !hideTestFiles }); + }, + showAll: () => { + void savePreferences({ pullRequestHideTestFiles: false }); + }, }; } diff --git a/apps/mobile/src/features/pull-requests/usePullRequestListControls.ts b/apps/mobile/src/features/pull-requests/usePullRequestListControls.ts index 5a83d26554234..ea60012b3ae08 100644 --- a/apps/mobile/src/features/pull-requests/usePullRequestListControls.ts +++ b/apps/mobile/src/features/pull-requests/usePullRequestListControls.ts @@ -1,23 +1,24 @@ -import { useAtomSet, useAtomValue } from "@effect/atom-react"; +import { useAtomValue } from "@effect/atom-react"; +import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime"; import { AsyncResult } from "effect/reactivity"; -import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/preferences"; +import { mobilePreferencesAtom, saveMobilePreferences } from "../../state/preferences"; +import { useAtomCommand } from "../../state/use-atom-command"; import { DEFAULT_PR_LIST_CONTROLS, type PullRequestListControls } from "./pullRequestList"; import type { PullRequestSavedView } from "../../persistence/mobile-preferences"; import { pullRequestSavedViewPreferences } from "./pullRequestSavedViews"; export function usePullRequestListControls() { const preferences = useAtomValue(mobilePreferencesAtom); - const savePreferences = useAtomSet(updateMobilePreferencesAtom); - const applyPreferences = useAtomSet(updateMobilePreferencesAtom, { mode: "promise" }); + const savePreferences = useAtomCommand(saveMobilePreferences, { reportFailure: false }); const saved = AsyncResult.isSuccess(preferences) ? preferences.value.pullRequestListFilters : undefined; const environmentId = saved?.environmentId ?? null; const controlsFor = (environment: string | null) => saved?.controls[environment ?? ""] ?? DEFAULT_PR_LIST_CONTROLS; - const setEnvironmentId = (next: string | null) => - savePreferences({ + const setEnvironmentId = (next: string | null) => { + void savePreferences({ transform: (current) => ({ pullRequestListFilters: { controls: current.pullRequestListFilters?.controls ?? {}, @@ -25,8 +26,9 @@ export function usePullRequestListControls() { }, }), }); - const setControls = (environment: string | null, controls: PullRequestListControls) => - savePreferences({ + }; + const setControls = (environment: string | null, controls: PullRequestListControls) => { + void savePreferences({ transform: (current) => ({ pullRequestListFilters: { environmentId: current.pullRequestListFilters?.environmentId ?? null, @@ -38,10 +40,13 @@ export function usePullRequestListControls() { }, }), }); - const applyView = (view: PullRequestSavedView) => - applyPreferences({ + }; + const applyView = async (view: PullRequestSavedView) => { + const result = await savePreferences({ transform: (current) => pullRequestSavedViewPreferences(current, view), }); + if (result._tag === "Failure") throw squashAtomCommandFailure(result); + }; return { environmentId, controlsFor, setEnvironmentId, setControls, applyView } as const; } diff --git a/apps/mobile/src/features/settings/SettingsFollowUpRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsFollowUpRouteScreen.tsx index f62aba2c73668..cfc5783e24aa2 100644 --- a/apps/mobile/src/features/settings/SettingsFollowUpRouteScreen.tsx +++ b/apps/mobile/src/features/settings/SettingsFollowUpRouteScreen.tsx @@ -1,13 +1,14 @@ import { msg, T, useGT, useMessages, Var } from "gt-react-native"; import { ScreenScrollView as ScrollView } from "../../components/ui/ScreenScrollView"; -import { useAtomSet, useAtomValue } from "@effect/atom-react"; +import { useAtomValue } from "@effect/atom-react"; import { AsyncResult } from "effect/reactivity"; import { Platform } from "react-native"; import { useSafeAreaInsets } from "react-native-safe-area-context"; import { AppText as Text } from "../../components/ui/AppText"; import { DEFAULT_FOLLOW_UP_BEHAVIOR, type FollowUpBehavior } from "../../lib/followUpBehavior"; -import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/preferences"; +import { mobilePreferencesAtom, saveMobilePreferences } from "../../state/preferences"; +import { useAtomCommand } from "../../state/use-atom-command"; import { ListChoiceRow as SettingsChoiceRow } from "../../components/ui/ListChoiceRow"; import { SettingsSection } from "./components/SettingsSection"; import { SettingsScreen } from "./components/SettingsScreen"; @@ -34,7 +35,7 @@ export function SettingsFollowUpRouteScreen() { const m = useMessages(); const insets = useSafeAreaInsets(); const preferencesResult = useAtomValue(mobilePreferencesAtom); - const savePreferences = useAtomSet(updateMobilePreferencesAtom); + const savePreferences = useAtomCommand(saveMobilePreferences); const preferencesReady = AsyncResult.isSuccess(preferencesResult) && !preferencesResult.waiting; const selectedBehavior = AsyncResult.isSuccess(preferencesResult) ? (preferencesResult.value.followUpBehavior ?? DEFAULT_FOLLOW_UP_BEHAVIOR) @@ -57,7 +58,9 @@ export function SettingsFollowUpRouteScreen() { selected={selectedBehavior === option.behavior} separated={index > 0} disabled={!preferencesReady} - onPress={() => savePreferences({ followUpBehavior: option.behavior })} + onPress={() => { + void savePreferences({ followUpBehavior: option.behavior }); + }} /> ))} diff --git a/apps/mobile/src/features/settings/SettingsKeyboardRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsKeyboardRouteScreen.tsx index 7d7076ab0d014..7b61f80c445fb 100644 --- a/apps/mobile/src/features/settings/SettingsKeyboardRouteScreen.tsx +++ b/apps/mobile/src/features/settings/SettingsKeyboardRouteScreen.tsx @@ -1,6 +1,6 @@ import { msg, T, useGT, useMessages } from "gt-react-native"; import { ScreenScrollView as ScrollView } from "../../components/ui/ScreenScrollView"; -import { useAtomSet, useAtomValue } from "@effect/atom-react"; +import { useAtomValue } from "@effect/atom-react"; import { AsyncResult } from "effect/reactivity"; import { Platform } from "react-native"; import { useSafeAreaInsets } from "react-native-safe-area-context"; @@ -10,7 +10,8 @@ import { DEFAULT_COMPOSER_ENTER_BEHAVIOR, type ComposerEnterBehavior, } from "../../lib/composerEnterBehavior"; -import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/preferences"; +import { mobilePreferencesAtom, saveMobilePreferences } from "../../state/preferences"; +import { useAtomCommand } from "../../state/use-atom-command"; import { ListChoiceRow as SettingsChoiceRow } from "../../components/ui/ListChoiceRow"; import { SettingsScreen } from "./components/SettingsScreen"; import { SettingsSection } from "./components/SettingsSection"; @@ -45,7 +46,7 @@ export function SettingsKeyboardRouteScreen() { const m = useMessages(); const insets = useSafeAreaInsets(); const preferencesResult = useAtomValue(mobilePreferencesAtom); - const savePreferences = useAtomSet(updateMobilePreferencesAtom); + const savePreferences = useAtomCommand(saveMobilePreferences); const preferencesReady = AsyncResult.isSuccess(preferencesResult) && !preferencesResult.waiting; const selectedBehavior = AsyncResult.isSuccess(preferencesResult) ? (preferencesResult.value.composerEnterBehavior ?? DEFAULT_COMPOSER_ENTER_BEHAVIOR) @@ -69,7 +70,9 @@ export function SettingsKeyboardRouteScreen() { selected={selectedBehavior === option.behavior} separated={index > 0} disabled={!preferencesReady} - onPress={() => savePreferences({ composerEnterBehavior: option.behavior })} + onPress={() => { + void savePreferences({ composerEnterBehavior: option.behavior }); + }} /> ))} diff --git a/apps/mobile/src/features/settings/SettingsLanguageRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsLanguageRouteScreen.tsx index a8c0bbe6bfa84..068aab494c1bf 100644 --- a/apps/mobile/src/features/settings/SettingsLanguageRouteScreen.tsx +++ b/apps/mobile/src/features/settings/SettingsLanguageRouteScreen.tsx @@ -1,5 +1,5 @@ import { ScreenScrollView as ScrollView } from "../../components/ui/ScreenScrollView"; -import { useAtomSet, useAtomValue } from "@effect/atom-react"; +import { useAtomValue } from "@effect/atom-react"; import { AsyncResult } from "effect/reactivity"; import { useSafeAreaInsets } from "react-native-safe-area-context"; @@ -7,7 +7,8 @@ import { useGT } from "gt-react-native"; import { useLanguagePreference } from "../../i18n/I18nProvider"; import { SYSTEM_LANGUAGE, nativeLanguageName } from "@t3tools/client-runtime/locales"; import { SUPPORTED_LOCALES } from "../../i18n/locales"; -import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/preferences"; +import { mobilePreferencesAtom, saveMobilePreferences } from "../../state/preferences"; +import { useAtomCommand } from "../../state/use-atom-command"; import { ListChoiceRow as SettingsChoiceRow } from "../../components/ui/ListChoiceRow"; import { SettingsRow } from "./components/SettingsRow"; import { SettingsSection } from "./components/SettingsSection"; @@ -35,7 +36,7 @@ export function SettingsLanguageRouteScreen() { const gt = useGT(); const insets = useSafeAreaInsets(); const preferencesResult = useAtomValue(mobilePreferencesAtom); - const savePreferences = useAtomSet(updateMobilePreferencesAtom); + const savePreferences = useAtomCommand(saveMobilePreferences); const preferencesReady = AsyncResult.isSuccess(preferencesResult) && !preferencesResult.waiting; const language = useLanguagePreference(); const options = [ @@ -60,7 +61,9 @@ export function SettingsLanguageRouteScreen() { selected={preferencesReady && language === option.language} separated={index > 0} disabled={!preferencesReady} - onPress={() => savePreferences({ language: option.language })} + onPress={() => { + void savePreferences({ language: option.language }); + }} /> ))} diff --git a/apps/mobile/src/features/settings/SettingsNavigationRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsNavigationRouteScreen.tsx index 65ff95a8e5cc8..979f358aad9cc 100644 --- a/apps/mobile/src/features/settings/SettingsNavigationRouteScreen.tsx +++ b/apps/mobile/src/features/settings/SettingsNavigationRouteScreen.tsx @@ -1,5 +1,5 @@ import { useGT, useMessages } from "gt-react-native"; -import { useAtomSet, useAtomValue } from "@effect/atom-react"; +import { useAtomValue } from "@effect/atom-react"; import { AsyncResult } from "effect/reactivity"; import { useAdaptiveWorkspaceLayout } from "../layout/adaptive-workspace-context"; import { Platform, View } from "react-native"; @@ -14,7 +14,8 @@ import { IconButton } from "../../components/ui/IconButton"; import { Button } from "../../components/ui/Button"; import { ScreenScrollView } from "../../components/ui/ScreenScrollView"; import { SymbolView } from "../../components/ui/AppSymbol"; -import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/preferences"; +import { mobilePreferencesAtom, saveMobilePreferences } from "../../state/preferences"; +import { useAtomCommand } from "../../state/use-atom-command"; import { NAVIGATION_TAB_ICONS, WORKSPACE_TAB_LABELS, @@ -38,7 +39,7 @@ export function SettingsNavigationRouteScreen() { const preferences = useAtomValue(mobilePreferencesAtom); const customizable = navigationCustomizationAvailable(); const ready = customizable && AsyncResult.isSuccess(preferences) && !preferences.waiting; - const save = useAtomSet(updateMobilePreferencesAtom); + const save = useAtomCommand(saveMobilePreferences); return ( - save({ + onPress={() => { + void save({ transform: (current) => ({ hiddenNavigationTabs: toggleNavigationTabVisibility( current.hiddenNavigationTabs, tab, ), }), - }) - } + }); + }} /> - save({ + onPress={() => { + void save({ transform: (current) => ({ navigationTabOrder: moveNavigationTab( resolveWorkspaceTabOrder(current.navigationTabOrder), @@ -105,15 +106,15 @@ export function SettingsNavigationRouteScreen() { index - 1, ), }), - }) - } + }); + }} /> - save({ + onPress={() => { + void save({ transform: (current) => ({ navigationTabOrder: moveNavigationTab( resolveWorkspaceTabOrder(current.navigationTabOrder), @@ -121,8 +122,8 @@ export function SettingsNavigationRouteScreen() { index + 1, ), }), - }) - } + }); + }} /> ))} @@ -131,7 +132,9 @@ export function SettingsNavigationRouteScreen() { label={gt("Reset tabs")} tone="text" disabled={!ready} - onPress={() => save({ navigationTabOrder: [], hiddenNavigationTabs: [] })} + onPress={() => { + void save({ navigationTabOrder: [], hiddenNavigationTabs: [] }); + }} /> diff --git a/apps/mobile/src/features/settings/SettingsNotificationsRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsNotificationsRouteScreen.tsx index b7524355f2e9a..9875978c92c3b 100644 --- a/apps/mobile/src/features/settings/SettingsNotificationsRouteScreen.tsx +++ b/apps/mobile/src/features/settings/SettingsNotificationsRouteScreen.tsx @@ -58,7 +58,8 @@ import { refreshManagedRelayEnvironments } from "../cloud/managedRelayState"; import { hasCloudPublicConfig, resolveRelayClerkTokenOptions } from "../cloud/publicConfig"; import { makePermissionStatusAtom } from "../../lib/permissionStatusAtom"; import { runtime } from "../../lib/runtime"; -import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/preferences"; +import { mobilePreferencesAtom, saveMobilePreferences } from "../../state/preferences"; +import { useAtomCommand } from "../../state/use-atom-command"; import { useSavedRemoteConnections } from "../../state/use-remote-environment-registry"; import { SettingsRow } from "./components/SettingsRow"; import { SettingsSection } from "./components/SettingsSection"; @@ -206,7 +207,7 @@ function ConfiguredSettingsNotificationsRouteScreen() { const gt = useGT(); const m = useMessages(); const preferencesResult = useAtomValue(mobilePreferencesAtom); - const savePreferences = useAtomSet(updateMobilePreferencesAtom); + const savePreferences = useAtomCommand(saveMobilePreferences); const agentAwarenessPushAvailable = supportsAgentAwarenessPush(); const agentAwarenessPlatform = resolveAgentAwarenessPlatformPresentation(Platform.OS, m); const agentAwarenessSubtitle = @@ -411,7 +412,7 @@ function ConfiguredSettingsNotificationsRouteScreen() { return; } - savePreferences({ liveActivitiesEnabled: true }); + void savePreferences({ liveActivitiesEnabled: true }); refreshManagedRelayEnvironments(); setLiveActivityStatus("enabled"); // Environment linking can precede device registration; only registered devices can receive Live Activities. @@ -501,7 +502,7 @@ function ConfiguredSettingsNotificationsRouteScreen() { } return; } - savePreferences({ liveActivitiesEnabled: false }); + void savePreferences({ liveActivitiesEnabled: false }); refreshManagedRelayEnvironments(); setLiveActivityStatus("disabled"); if (updateResult.value) { diff --git a/apps/mobile/src/features/settings/SettingsProjectGroupingRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsProjectGroupingRouteScreen.tsx index 0afc578c994fe..ff1bae1c6ec92 100644 --- a/apps/mobile/src/features/settings/SettingsProjectGroupingRouteScreen.tsx +++ b/apps/mobile/src/features/settings/SettingsProjectGroupingRouteScreen.tsx @@ -1,6 +1,6 @@ import { msg, useGT, useMessages } from "gt-react-native"; import { ScreenScrollView as ScrollView } from "../../components/ui/ScreenScrollView"; -import { useAtomSet, useAtomValue } from "@effect/atom-react"; +import { useAtomValue } from "@effect/atom-react"; import type { SidebarProjectGroupingMode } from "@t3tools/contracts"; import { AsyncResult } from "effect/reactivity"; import { useSafeAreaInsets } from "react-native-safe-area-context"; @@ -10,7 +10,8 @@ import { mobileProjectGroupingModePatch, resolveMobileProjectGroupingSettings, } from "../../state/project-grouping"; -import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/preferences"; +import { mobilePreferencesAtom, saveMobilePreferences } from "../../state/preferences"; +import { useAtomCommand } from "../../state/use-atom-command"; import { ListChoiceRow as SettingsChoiceRow } from "../../components/ui/ListChoiceRow"; import { SettingsSection } from "./components/SettingsSection"; import { LanguageSettingsSection } from "./SettingsLanguageRouteScreen"; @@ -43,7 +44,7 @@ export function SettingsProjectGroupingRouteScreen() { const m = useMessages(); const insets = useSafeAreaInsets(); const preferencesResult = useAtomValue(mobilePreferencesAtom); - const savePreferences = useAtomSet(updateMobilePreferencesAtom); + const savePreferences = useAtomCommand(saveMobilePreferences); const preferencesReady = AsyncResult.isSuccess(preferencesResult) && !preferencesResult.waiting; const selectedMode = AsyncResult.isSuccess(preferencesResult) ? resolveMobileProjectGroupingSettings(preferencesResult.value).sidebarProjectGroupingMode @@ -68,7 +69,9 @@ export function SettingsProjectGroupingRouteScreen() { selected={selectedMode === option.mode} separated={index > 0} disabled={!preferencesReady} - onPress={() => savePreferences(mobileProjectGroupingModePatch(option.mode))} + onPress={() => { + void savePreferences(mobileProjectGroupingModePatch(option.mode)); + }} /> ))} diff --git a/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.test.tsx b/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.test.tsx index 61aeef42e84e4..5c07345dce4d3 100644 --- a/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.test.tsx +++ b/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.test.tsx @@ -42,7 +42,7 @@ vi.mock("@effect/atom-react", () => ({ })); vi.mock("../../state/preferences", () => ({ mobilePreferencesAtom: {}, - updateMobilePreferencesAtom: {}, + saveMobilePreferences: {}, })); vi.mock("./components/AutoSettleDaysField", () => ({ AutoSettleDaysField: () => null })); vi.mock("./components/IssueTrackerSection", () => ({ IssueTrackerSection: () => null })); diff --git a/apps/mobile/src/features/settings/SettingsVoiceRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsVoiceRouteScreen.tsx index dcefd506c4e99..6e18e2146dd92 100644 --- a/apps/mobile/src/features/settings/SettingsVoiceRouteScreen.tsx +++ b/apps/mobile/src/features/settings/SettingsVoiceRouteScreen.tsx @@ -19,7 +19,8 @@ import { type MicrophoneKind, microphoneEntryKey, } from "../../lib/microphonePriority"; -import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/preferences"; +import { mobilePreferencesAtom, saveMobilePreferences } from "../../state/preferences"; +import { useAtomCommand } from "../../state/use-atom-command"; import { ListRowLayout } from "../../components/ui/ListRowLayout"; import { ListChoiceRow } from "../../components/ui/ListChoiceRow"; import * as Dialog from "../../components/ui/Dialog"; @@ -240,7 +241,7 @@ export function SettingsVoiceRouteScreen() { const methodEnvironment = sheetEnvironment ?? grantEnvironment; const insets = useSafeAreaInsets(); const preferencesResult = useAtomValue(mobilePreferencesAtom); - const savePreferences = useAtomSet(updateMobilePreferencesAtom); + const savePreferences = useAtomCommand(saveMobilePreferences); const ready = AsyncResult.isSuccess(preferencesResult) && !preferencesResult.waiting; const entries = deviceMicrophoneOrder( AsyncResult.isSuccess(preferencesResult) ? preferencesResult.value.microphones : undefined, @@ -254,8 +255,8 @@ export function SettingsVoiceRouteScreen() { const [drops, setDrops] = useState(0); // Transforms apply to the stored order, so a device recorded meanwhile is kept. - const move = (key: string, steps: number) => - savePreferences({ + const move = (key: string, steps: number) => { + void savePreferences({ transform: (current) => { const next = [...deviceMicrophoneOrder(current.microphones)]; const from = next.findIndex((entry) => microphoneEntryKey(entry) === key); @@ -266,14 +267,16 @@ export function SettingsVoiceRouteScreen() { return { microphones: next }; }, }); - const forget = (key: string) => - savePreferences({ + }; + const forget = (key: string) => { + void savePreferences({ transform: (current) => ({ microphones: deviceMicrophoneOrder(current.microphones).filter( (entry) => microphoneEntryKey(entry) !== key, ), }), }); + }; const dropSteps = (from: number, translation: number) => rowHeight === 0 ? 0 diff --git a/apps/mobile/src/features/settings/ThreadSettingsSections.tsx b/apps/mobile/src/features/settings/ThreadSettingsSections.tsx index a23f0c98932ea..55c45eae31f01 100644 --- a/apps/mobile/src/features/settings/ThreadSettingsSections.tsx +++ b/apps/mobile/src/features/settings/ThreadSettingsSections.tsx @@ -8,7 +8,7 @@ import { import { useEnvironmentsWithScope } from "../../state/session"; import { AutoSettleDaysField } from "./components/AutoSettleDaysField"; import { ScreenScrollView as ScrollView } from "../../components/ui/ScreenScrollView"; -import { useAtomSet, useAtomValue } from "@effect/atom-react"; +import { useAtomValue } from "@effect/atom-react"; import { AsyncResult } from "effect/reactivity"; import type { ComponentProps } from "react"; import { View } from "react-native"; @@ -18,7 +18,7 @@ import { DEFAULT_SERVER_SETTINGS } from "@t3tools/contracts"; import { supportsSharedSettingsSync } from "@t3tools/client-runtime/state/shared-settings"; import { AppText as Text } from "../../components/ui/AppText"; import { useEnvironments } from "../../state/environments"; -import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/preferences"; +import { mobilePreferencesAtom, saveMobilePreferences } from "../../state/preferences"; import { serverEnvironment } from "../../state/server"; import { useAtomCommand } from "../../state/use-atom-command"; import { SettingsSection } from "./components/SettingsSection"; @@ -211,7 +211,7 @@ export function AutoSettleSettingsRows(props: { export function WorkingSectionSettings() { const gt = useGT(); - const savePreferences = useAtomSet(updateMobilePreferencesAtom); + const savePreferences = useAtomCommand(saveMobilePreferences); const preferences = useAtomValue(mobilePreferencesAtom); const workingShelfEnabled = AsyncResult.isSuccess(preferences) && preferences.value.workingShelfEnabled !== false; @@ -223,7 +223,9 @@ export function WorkingSectionSettings() { icon="bolt.circle" label={gt("Working section")} value={workingShelfEnabled} - onValueChange={(value) => savePreferences({ workingShelfEnabled: value })} + onValueChange={(value) => { + void savePreferences({ workingShelfEnabled: value }); + }} /> @@ -239,7 +241,7 @@ export function WorkingSectionSettings() { export function NewThreadSettingsSection() { const gt = useGT(); - const savePreferences = useAtomSet(updateMobilePreferencesAtom); + const savePreferences = useAtomCommand(saveMobilePreferences); const preferences = useAtomValue(mobilePreferencesAtom); const useLastProject = AsyncResult.isSuccess(preferences) && preferences.value.useLastProjectForNewThreads !== false; @@ -251,7 +253,9 @@ export function NewThreadSettingsSection() { label={gt("Use last project")} subtitle={gt("Start new threads in the last project you used on this device.")} value={useLastProject} - onValueChange={(value) => savePreferences({ useLastProjectForNewThreads: value })} + onValueChange={(value) => { + void savePreferences({ useLastProjectForNewThreads: value }); + }} /> ); diff --git a/apps/mobile/src/features/settings/appearance/AppearancePreferencesProvider.tsx b/apps/mobile/src/features/settings/appearance/AppearancePreferencesProvider.tsx index 26e17f45afb13..6ce7bfd673491 100644 --- a/apps/mobile/src/features/settings/appearance/AppearancePreferencesProvider.tsx +++ b/apps/mobile/src/features/settings/appearance/AppearancePreferencesProvider.tsx @@ -7,7 +7,7 @@ import { type AndroidNavigationStyle, } from "../../../lib/androidNavigationStyle"; -import { useAtomSet, useAtomValue } from "@effect/atom-react"; +import { useAtomValue } from "@effect/atom-react"; import { Atom, AsyncResult } from "effect/reactivity"; import { ScopedTheme, ScopedVariables, Uniwind } from "uniwind"; @@ -18,7 +18,8 @@ import { type ResolvedAppearance, } from "../../../lib/appearancePreferences"; import { appAtomRegistry } from "../../../state/atom-registry"; -import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../../state/preferences"; +import { mobilePreferencesAtom, saveMobilePreferences } from "../../../state/preferences"; +import { useAtomCommand } from "../../../state/use-atom-command"; import type { Preferences } from "../../../persistence/mobile-preferences"; import { isSystemColorsAvailable, @@ -187,7 +188,7 @@ export function installAppearanceRuntime(): () => void { export function AppearancePreferencesProvider(props: { readonly children: ReactNode }) { const preferencesResult = useAtomValue(mobilePreferencesAtom); - const savePreferences = useAtomSet(updateMobilePreferencesAtom); + const savePreferences = useAtomCommand(saveMobilePreferences); const systemColorScheme = useColorScheme() === "dark" ? "dark" : "light"; const storedPreferences = AsyncResult.isSuccess(preferencesResult) ? preferencesResult.value @@ -224,11 +225,13 @@ export function AppearancePreferencesProvider(props: { readonly children: ReactN ); const isReady = AsyncResult.isSuccess(preferencesResult); const updatePreferences = (patch: Partial) => { - startTransition(() => savePreferences(patch)); + startTransition(() => { + void savePreferences(patch); + }); }; const updateThemePreferences = (patch: Partial) => { - savePreferences(patch); + void savePreferences(patch); }; const setThemeIdForAppearance = (appearance: MobileThemeAppearance, value: MobileThemeId) => { diff --git a/apps/mobile/src/features/settings/appearance/sections/ToolCallsAppearanceSection.tsx b/apps/mobile/src/features/settings/appearance/sections/ToolCallsAppearanceSection.tsx index 51d0da1328fc8..dabe5f22f6a17 100644 --- a/apps/mobile/src/features/settings/appearance/sections/ToolCallsAppearanceSection.tsx +++ b/apps/mobile/src/features/settings/appearance/sections/ToolCallsAppearanceSection.tsx @@ -1,12 +1,13 @@ import { msg, T, useGT, useMessages } from "gt-react-native"; -import { useAtomSet, useAtomValue } from "@effect/atom-react"; +import { useAtomValue } from "@effect/atom-react"; import type { ToolCallVisibility } from "@t3tools/contracts/settings"; import { AsyncResult } from "effect/reactivity"; import { View } from "react-native"; import { AppText as Text } from "../../../../components/ui/AppText"; import { ListChoiceRow } from "../../../../components/ui/ListChoiceRow"; -import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../../../state/preferences"; +import { mobilePreferencesAtom, saveMobilePreferences } from "../../../../state/preferences"; +import { useAtomCommand } from "../../../../state/use-atom-command"; import { SettingsSection } from "../../components/SettingsSection"; const TOOL_CALL_VISIBILITY_OPTIONS: ReadonlyArray<{ @@ -22,7 +23,7 @@ const TOOL_CALL_VISIBILITY_OPTIONS: ReadonlyArray<{ export function ToolCallsAppearanceSection() { const gt = useGT(); const m = useMessages(); - const savePreferences = useAtomSet(updateMobilePreferencesAtom); + const savePreferences = useAtomCommand(saveMobilePreferences); const preferences = useAtomValue(mobilePreferencesAtom); const selected = AsyncResult.isSuccess(preferences) ? (preferences.value.toolCallVisibility ?? "showAll") @@ -38,7 +39,9 @@ export function ToolCallsAppearanceSection() { selected={selected === option.value} separated={index > 0} disabled={selected === null} - onPress={() => savePreferences({ toolCallVisibility: option.value })} + onPress={() => { + void savePreferences({ toolCallVisibility: option.value }); + }} /> ))} diff --git a/apps/mobile/src/features/settings/components/DatabaseStorageNotice.tsx b/apps/mobile/src/features/settings/components/DatabaseStorageNotice.tsx index 2b2ce8daed764..414597cf4333d 100644 --- a/apps/mobile/src/features/settings/components/DatabaseStorageNotice.tsx +++ b/apps/mobile/src/features/settings/components/DatabaseStorageNotice.tsx @@ -1,10 +1,11 @@ import { useGT } from "gt-react-native"; -import { useAtomSet, useAtomValue } from "@effect/atom-react"; +import { useAtomValue } from "@effect/atom-react"; import { AsyncResult } from "effect/reactivity"; import { copyTextWithHaptic } from "../../../lib/copyTextWithHaptic"; -import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../../state/preferences"; +import { mobilePreferencesAtom, saveMobilePreferences } from "../../../state/preferences"; import { serverEnvironment } from "../../../state/server"; +import { useAtomCommand } from "../../../state/use-atom-command"; import type { SettingsTarget } from "../settings-environment-filter"; import { ListActionRow as SettingsActionRow } from "../../../components/ui/ListActionRow"; import { SettingsSection } from "./SettingsSection"; @@ -22,7 +23,7 @@ export function DatabaseStorageNotice({ ), ); const preferences = useAtomValue(mobilePreferencesAtom); - const updatePreferences = useAtomSet(updateMobilePreferencesAtom); + const updatePreferences = useAtomCommand(saveMobilePreferences); const dismissed = AsyncResult.isSuccess(preferences) ? (preferences.value.dismissedDatabaseStorageNotices ?? []) : []; @@ -50,8 +51,8 @@ export function DatabaseStorageNotice({ - updatePreferences({ + onPress={() => { + void updatePreferences({ transform: (current) => ({ dismissedDatabaseStorageNotices: [ ...new Set([ @@ -60,8 +61,8 @@ export function DatabaseStorageNotice({ ]), ], }), - }) - } + }); + }} /> ); diff --git a/apps/mobile/src/features/showcase/ShowcaseCaptureCoordinator.tsx b/apps/mobile/src/features/showcase/ShowcaseCaptureCoordinator.tsx index 884b76ea889f9..8d9b759731447 100644 --- a/apps/mobile/src/features/showcase/ShowcaseCaptureCoordinator.tsx +++ b/apps/mobile/src/features/showcase/ShowcaseCaptureCoordinator.tsx @@ -18,7 +18,7 @@ import { } from "../../lib/mobileTheme"; import { rootNavigationRef } from "../../lib/rootNavigation"; import { appAtomRegistry } from "../../state/atom-registry"; -import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/preferences"; +import { mobilePreferencesAtom, saveMobilePreferences } from "../../state/preferences"; import { environmentProjects } from "../../state/projects"; import { enqueueThreadOutboxMessage } from "../../state/thread-outbox"; import { environmentThreadShells } from "../../state/threads"; @@ -288,7 +288,11 @@ export function installShowcaseCapture( // already sees the theme applied. A failed save rolls the patch back, and // the next step writes again. if (requestedTheme !== null && !themeApplied && storedPreferences) { - appAtomRegistry.set(updateMobilePreferencesAtom, createMobileThemePairPatch(requestedTheme)); + void runAtomCommand( + appAtomRegistry, + saveMobilePreferences, + createMobileThemePairPatch(requestedTheme), + ); } const themeId = themeIds[resolveThemeAppearance(storedPreferences)]; diff --git a/apps/mobile/src/features/threads/use-thread-list-v2-shelf-preferences.ts b/apps/mobile/src/features/threads/use-thread-list-v2-shelf-preferences.ts index 4348908e5371b..13ba59cce2cff 100644 --- a/apps/mobile/src/features/threads/use-thread-list-v2-shelf-preferences.ts +++ b/apps/mobile/src/features/threads/use-thread-list-v2-shelf-preferences.ts @@ -1,11 +1,12 @@ -import { useAtomSet, useAtomValue } from "@effect/atom-react"; +import { useAtomValue } from "@effect/atom-react"; import { AsyncResult } from "effect/reactivity"; -import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/preferences"; +import { mobilePreferencesAtom, saveMobilePreferences } from "../../state/preferences"; +import { useAtomCommand } from "../../state/use-atom-command"; export function useThreadListV2ShelfPreferences() { const preferencesResult = useAtomValue(mobilePreferencesAtom); - const savePreferences = useAtomSet(updateMobilePreferencesAtom); + const savePreferences = useAtomCommand(saveMobilePreferences); const loaded = AsyncResult.isSuccess(preferencesResult); const snoozedShelfExpanded = loaded && preferencesResult.value.threadListSnoozedShelfExpanded === true; @@ -18,7 +19,7 @@ export function useThreadListV2ShelfPreferences() { // Transforms read optimistic state so same-frame presses toggle twice. const toggleSnoozedShelf = () => { if (!loaded) return; - savePreferences({ + void savePreferences({ transform: (current) => ({ threadListSnoozedShelfExpanded: current.threadListSnoozedShelfExpanded !== true, }), @@ -26,7 +27,7 @@ export function useThreadListV2ShelfPreferences() { }; const toggleSettledShelf = () => { if (!loaded) return; - savePreferences({ + void savePreferences({ transform: (current) => ({ threadListSettledShelfExpanded: current.threadListSettledShelfExpanded !== true, }), @@ -34,7 +35,7 @@ export function useThreadListV2ShelfPreferences() { }; const toggleWorkingShelf = () => { if (!loaded) return; - savePreferences({ + void savePreferences({ transform: (current) => ({ threadListWorkingShelfExpanded: current.threadListWorkingShelfExpanded !== true, }), diff --git a/apps/mobile/src/features/threads/useRememberThreadProject.ts b/apps/mobile/src/features/threads/useRememberThreadProject.ts index a5e501e801914..2d48cda9b83ab 100644 --- a/apps/mobile/src/features/threads/useRememberThreadProject.ts +++ b/apps/mobile/src/features/threads/useRememberThreadProject.ts @@ -1,16 +1,15 @@ -import { useAtomSet } from "@effect/atom-react"; import { useFocusEffect } from "@react-navigation/native"; import { isScratchProject } from "@t3tools/client-runtime/state/projects"; +import { runAtomCommand } from "@t3tools/client-runtime/state/runtime"; import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell"; import { AsyncResult } from "effect/reactivity"; import { useCallback } from "react"; import { appAtomRegistry } from "../../state/atom-registry"; import { useEnvironmentServerConfig } from "../../state/entities"; -import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/preferences"; +import { mobilePreferencesAtom, saveMobilePreferences } from "../../state/preferences"; export function useRememberThreadProject(project: EnvironmentProject | null) { - const savePreferences = useAtomSet(updateMobilePreferencesAtom); const serverConfig = useEnvironmentServerConfig(project?.environmentId ?? null); const environmentId = project?.environmentId; const projectId = project?.id; @@ -26,7 +25,9 @@ export function useRememberThreadProject(project: EnvironmentProject | null) { if (!AsyncResult.isSuccess(preferences)) return; const last = preferences.value.lastThreadProject; if (last?.environmentId === environmentId && last.projectId === projectId) return; - savePreferences({ lastThreadProject: { environmentId, projectId } }); - }, [environmentId, projectId, remember, savePreferences]), + void runAtomCommand(appAtomRegistry, saveMobilePreferences, { + lastThreadProject: { environmentId, projectId }, + }); + }, [environmentId, projectId, remember]), ); } diff --git a/apps/mobile/src/features/voice-input/VoiceInputProvider.tsx b/apps/mobile/src/features/voice-input/VoiceInputProvider.tsx index 6e891dd04e7e9..e489416df9c54 100644 --- a/apps/mobile/src/features/voice-input/VoiceInputProvider.tsx +++ b/apps/mobile/src/features/voice-input/VoiceInputProvider.tsx @@ -1,3 +1,4 @@ +import { runAtomCommand } from "@t3tools/client-runtime/state/runtime"; import { useAtomValue } from "@effect/atom-react"; import { AudioModule, RecordingPresets, type RecordingStatus } from "expo-audio"; import { File } from "expo-file-system"; @@ -15,7 +16,7 @@ import { } from "../../lib/microphonePriority"; import { getLocalVoiceTranscriber } from "../../native/voiceTranscription"; import { createVoiceRecorder } from "../../native/voiceRecorder"; -import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/preferences"; +import { mobilePreferencesAtom, saveMobilePreferences } from "../../state/preferences"; import { getNativeShowcaseScene } from "../showcase/nativeShowcaseScene"; import { voiceInputBlocksSubmission, @@ -77,9 +78,8 @@ const voiceInputAvailableAtom = Atom.make((get) => { */ const voiceInputAtom = Atom.make((get) => { const registry = get.registry; - // Mounted so the recorder can read and remember microphones synchronously. + // Mounted so the recorder can read known microphones synchronously. get.mount(mobilePreferencesAtom); - get.mount(updateMobilePreferencesAtom); const audioLevels = makeMutable>( Array(VOICE_WAVEFORM_SAMPLE_COUNT).fill(0), ); @@ -109,7 +109,7 @@ const voiceInputAtom = Atom.make((get) => { const known = deviceMicrophoneOrder(preferences.value.microphones); const order = rememberMicrophones(known, inputs); if (order !== known) { - registry.set(updateMobilePreferencesAtom, { + void runAtomCommand(registry, saveMobilePreferences, { transform: (current) => ({ microphones: rememberMicrophones(deviceMicrophoneOrder(current.microphones), inputs), }), diff --git a/apps/mobile/src/state/preferences.test.ts b/apps/mobile/src/state/preferences.test.ts index cd9669c51d2d7..1da7a30b542ad 100644 --- a/apps/mobile/src/state/preferences.test.ts +++ b/apps/mobile/src/state/preferences.test.ts @@ -1,10 +1,12 @@ import { describe, expect, it } from "@effect/vitest"; +import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity"; import { vi } from "vite-plus/test"; import { ProviderInstanceId } from "@t3tools/contracts"; -import { RegistryContext, useAtomSet } from "@effect/atom-react"; +import { RegistryContext } from "@effect/atom-react"; import { createElement } from "react"; import { renderToString } from "react-dom/server"; @@ -26,6 +28,7 @@ vi.mock("../lib/runtime", async () => { }); import { createMobilePreferencesState } from "./preferences"; +import { useAtomCommand } from "./use-atom-command"; import * as MobilePreferences from "../persistence/mobile-preferences"; function deferred() { @@ -72,9 +75,8 @@ describe("mobile preferences state", () => { }); const registry = AtomRegistry.make(); const unmountPreferences = registry.mount(state.preferencesAtom); - const unmountUpdate = registry.mount(state.updatePreferencesAtom); - registry.set(state.updatePreferencesAtom, { + const save = state.savePreferences.run(registry, { collapsedProjectGroups: ["project:new"], }); pendingLoad.resolve({ @@ -85,6 +87,7 @@ describe("mobile preferences state", () => { const preferences = yield* AtomRegistry.getResult(registry, state.preferencesAtom, { suspendOnWaiting: true, }); + const saveResult = yield* Effect.promise(() => save); expect(preferences).toEqual({ baseFontSize: 18, collapsedProjectGroups: ["project:new"], @@ -92,15 +95,14 @@ describe("mobile preferences state", () => { expect(savePatch).toHaveBeenCalledWith({ collapsedProjectGroups: ["project:new"], }); - expect(AsyncResult.isFailure(registry.get(state.updatePreferencesAtom))).toBe(false); + expect(AsyncResult.isFailure(saveResult)).toBe(false); - unmountUpdate(); unmountPreferences(); registry.dispose(); }), ); - it.effect("keeps both favorites when the React setter sends updates before a render", () => + it.effect("keeps both favorites when the React command sends updates before a render", () => Effect.gen(function* () { let persisted: MobilePreferences.Preferences = { modelFavorites: [] }; const state = makePreferencesState({ @@ -118,60 +120,90 @@ describe("mobile preferences state", () => { }); const registry = AtomRegistry.make(); const unmountPreferences = registry.mount(state.preferencesAtom); - const unmountUpdate = registry.mount(state.updatePreferencesAtom); yield* AtomRegistry.getResult(registry, state.preferencesAtom, { suspendOnWaiting: true }); function useSavePreferences() { - return useAtomSet(state.updatePreferencesAtom); + return useAtomCommand(state.savePreferences, { reportFailure: false }); } const setters: Array> = []; function CaptureSetter() { setters.push(useSavePreferences()); return null; } - // Use the React setter; registry.set bypasses bare-function update semantics. renderToString( createElement(RegistryContext.Provider, { value: registry }, createElement(CaptureSetter)), ); const savePreferences = setters[0]!; const provider = ProviderInstanceId.make("codex"); - savePreferences({ + const first = savePreferences({ transform: (current) => ({ modelFavorites: [...(current.modelFavorites ?? []), { provider, model: "astra" }], }), }); - savePreferences({ + const second = savePreferences({ transform: (current) => ({ modelFavorites: [...(current.modelFavorites ?? []), { provider, model: "sol" }], }), }); - yield* AtomRegistry.getResult(registry, state.updatePreferencesAtom, { - suspendOnWaiting: true, - }); + yield* Effect.promise(() => Promise.all([first, second])); expect(persisted.modelFavorites).toEqual([ { provider, model: "astra" }, { provider, model: "sol" }, ]); - savePreferences({ - transform: (current) => ({ - modelFavorites: (current.modelFavorites ?? []).filter( - (favorite) => favorite.model !== "astra", - ), + yield* Effect.promise(() => + savePreferences({ + transform: (current) => ({ + modelFavorites: (current.modelFavorites ?? []).filter( + (favorite) => favorite.model !== "astra", + ), + }), }), - }); - yield* AtomRegistry.getResult(registry, state.updatePreferencesAtom, { - suspendOnWaiting: true, - }); + ); expect(persisted.modelFavorites).toEqual([{ provider, model: "sol" }]); - unmountUpdate(); unmountPreferences(); registry.dispose(); }), ); + it.effect("clears the optimistic patch when a save is interrupted", () => + Effect.gen(function* () { + const started = yield* Deferred.make(); + const store = { + load: Effect.succeed({ baseFontSize: 16 }), + savePatch: () => Deferred.succeed(started, undefined).pipe(Effect.andThen(Effect.never)), + }; + const state = makePreferencesState(store); + const registry = AtomRegistry.make(); + const unmount = registry.mount(state.preferencesAtom); + yield* AtomRegistry.getResult(registry, state.preferencesAtom, { suspendOnWaiting: true }); + + const fiber = yield* Effect.forkChild( + state.save({ baseFontSize: 20 }, registry).pipe( + Effect.provide( + Layer.succeed( + MobilePreferences.MobilePreferencesStore, + MobilePreferences.MobilePreferencesStore.of({ + ...store, + update: () => Effect.die("unexpected"), + }), + ), + ), + ), + ); + yield* Deferred.await(started); + yield* Fiber.interrupt(fiber); + + expect(AsyncResult.getOrElse(registry.get(state.preferencesAtom), () => ({}))).toEqual({ + baseFontSize: 16, + }); + unmount(); + registry.dispose(); + }), + ); + it.effect("falls back to empty preferences when secure storage cannot be read", () => Effect.gen(function* () { const state = makePreferencesState({ diff --git a/apps/mobile/src/state/preferences.ts b/apps/mobile/src/state/preferences.ts index 0331581789b26..67cec9845a86c 100644 --- a/apps/mobile/src/state/preferences.ts +++ b/apps/mobile/src/state/preferences.ts @@ -1,5 +1,6 @@ +import { createRuntimeCommand } from "@t3tools/client-runtime/state/runtime"; import * as Effect from "effect/Effect"; -import { AsyncResult, Atom } from "effect/reactivity"; +import { AsyncResult, Atom, type AtomRegistry } from "effect/reactivity"; import * as MobilePreferences from "../persistence/mobile-preferences"; import * as Runtime from "../lib/runtime"; @@ -9,7 +10,6 @@ interface OptimisticPreferences { readonly versions: Partial>; } -// useAtomSet treats bare functions as AsyncResult updates; wrap preference transforms in payloads. type PreferencesUpdate = | Partial | { @@ -56,81 +56,70 @@ export function createMobilePreferencesState( })); }).pipe(Atom.keepAlive, Atom.withLabel("mobile:preferences")); - const updatePreferencesAtom = runtime - .fn( - (update: PreferencesUpdate, get) => { - const currentPreferences = get(preferencesAtom); - const patch = - "transform" in update - ? update.transform( - AsyncResult.isSuccess(currentPreferences) ? currentPreferences.value : {}, - ) - : update; - const version = ++nextPatchVersion; - const current = get(optimisticPatchAtom); - const versions = { ...current.versions }; - for (const key of Object.keys(patch) as Array) { - versions[key] = version; - } - get.set(optimisticPatchAtom, { - values: { ...current.values, ...patch }, - versions, - }); - return MobilePreferences.MobilePreferencesStore.pipe( - Effect.flatMap((store) => - "transform" in update ? store.update(update.transform) : store.savePatch(patch), - ), - Effect.tap((saved) => - Effect.sync(() => { - get.set(confirmedPreferencesAtom, saved); - const optimistic = get(optimisticPatchAtom); - const values = { ...optimistic.values } as Record; - const currentVersions = { ...optimistic.versions } as Record; - for (const key of Object.keys(patch) as Array) { - if (optimistic.versions[key] === version) { - delete values[key]; - delete currentVersions[key]; - } - } - get.set(optimisticPatchAtom, { - values: values as Partial, - versions: currentVersions as Partial< - Record - >, - }); - }), - ), - Effect.tapError(() => - Effect.sync(() => { - const optimistic = get(optimisticPatchAtom); - const values = { ...optimistic.values } as Record; - const currentVersions = { ...optimistic.versions } as Record; - for (const key of Object.keys(patch) as Array) { - if (optimistic.versions[key] === version) { - delete values[key]; - delete currentVersions[key]; - } - } - get.set(optimisticPatchAtom, { - values: values as Partial, - versions: currentVersions as Partial< - Record - >, - }); - }), - ), - ); - }, - // Storage serializes shared-blob updates; keep concurrent invocations alive to prevent cross-field interruption. - { concurrent: true }, - ) - .pipe(Atom.keepAlive, Atom.withLabel("mobile:preferences:update")); + const settlePatch = ( + registry: AtomRegistry.AtomRegistry, + patch: Partial, + version: number, + ) => { + const optimistic = registry.get(optimisticPatchAtom); + const values = { ...optimistic.values } as Record; + const versions = { ...optimistic.versions } as Record; + for (const key of Object.keys(patch) as Array) { + if (optimistic.versions[key] === version) { + delete values[key]; + delete versions[key]; + } + } + registry.set(optimisticPatchAtom, { + values: values as Partial, + versions: versions as Partial>, + }); + }; + + // The optimistic patch lands when a save starts, before the store finishes writing. + const stage = (update: PreferencesUpdate, registry: AtomRegistry.AtomRegistry) => { + const currentPreferences = registry.get(preferencesAtom); + const patch = + "transform" in update + ? update.transform( + AsyncResult.isSuccess(currentPreferences) ? currentPreferences.value : {}, + ) + : update; + const version = ++nextPatchVersion; + const current = registry.get(optimisticPatchAtom); + const versions = { ...current.versions }; + for (const key of Object.keys(patch) as Array) { + versions[key] = version; + } + registry.set(optimisticPatchAtom, { values: { ...current.values, ...patch }, versions }); + return { patch, version } as const; + }; + + const save = Effect.fn("MobilePreferencesState.save")(function* ( + update: PreferencesUpdate, + registry: AtomRegistry.AtomRegistry, + ) { + const store = yield* MobilePreferences.MobilePreferencesStore; + const staged = yield* Effect.sync(() => stage(update, registry)); + return yield* ( + "transform" in update ? store.update(update.transform) : store.savePatch(staged.patch) + ).pipe( + Effect.tap((saved) => Effect.sync(() => registry.set(confirmedPreferencesAtom, saved))), + Effect.ensuring(Effect.sync(() => settlePatch(registry, staged.patch, staged.version))), + ); + }); + + // One command gives every caller its own settled result, even when saves overlap. + const savePreferences = createRuntimeCommand(runtime, { + label: "mobile:preferences:save", + execute: save, + }); - return { preferencesAtom, updatePreferencesAtom } as const; + return { preferencesAtom, save, savePreferences } as const; } const mobilePreferencesRuntime = Atom.runtime(Runtime.layer); const mobilePreferencesState = createMobilePreferencesState(mobilePreferencesRuntime); export const mobilePreferencesAtom = mobilePreferencesState.preferencesAtom; -export const updateMobilePreferencesAtom = mobilePreferencesState.updatePreferencesAtom; +export const saveMobilePreferences = mobilePreferencesState.savePreferences; diff --git a/apps/web/src/cloud/managedAuth.tsx b/apps/web/src/cloud/managedAuth.tsx index 59bc69f7640d2..c78ee4e513c8b 100644 --- a/apps/web/src/cloud/managedAuth.tsx +++ b/apps/web/src/cloud/managedAuth.tsx @@ -8,6 +8,7 @@ import { reportAtomCommandResult, runAtomCommand, settleAsyncResult, + squashAtomCommandFailure, } from "@t3tools/client-runtime/state/runtime"; import * as Effect from "effect/Effect"; import { useEffect, type ReactNode } from "react"; @@ -38,25 +39,27 @@ function clerkTokenReader(clerk: ClerkInstance): () => Promise { clerk.session ? await clerk.session.getToken(resolveRelayClerkTokenOptions()) : null; } +// A failed route removal fails the switch, so the next account never activates over the old routes. +async function cleanUpManagedRelayAccount(): Promise { + const [removal, tokenReset] = await Promise.all([ + runAtomCommand(appAtomRegistry, environmentCatalog.removeRelayEnvironments, undefined, { + reportFailure: false, + reportDefect: false, + }), + settleAsyncResult(() => + runtime.runPromiseExit( + ManagedRelay.ManagedRelayClient.pipe(Effect.flatMap((client) => client.resetTokenCache)), + ), + ), + ]); + reportAtomCommandResult(tokenReset, { label: "cloud account cleanup" }); + if (removal._tag !== "Success") throw squashAtomCommandFailure(removal); +} + const managedRelayAccountService = createCloudAccountService({ deactivate: deactivateManagedRelayAuthentication, detach: deactivateManagedRelayAuthentication, - cleanUp: async () => { - const results = await Promise.all([ - runAtomCommand(appAtomRegistry, environmentCatalog.removeRelayEnvironments, undefined, { - reportFailure: false, - reportDefect: false, - }), - settleAsyncResult(() => - runtime.runPromiseExit( - ManagedRelay.ManagedRelayClient.pipe(Effect.flatMap((client) => client.resetTokenCache)), - ), - ), - ]); - for (const result of results) { - reportAtomCommandResult(result, { label: "cloud account cleanup" }); - } - }, + cleanUp: cleanUpManagedRelayAccount, activate: ({ source, accountId }) => activateManagedRelayAuthentication(accountId, clerkTokenReader(source)), }); From 73caab68e33c3a42f71b181b9d852da7badbfcb0 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 19 Nov 2026 12:11:06 -0800 Subject: [PATCH 27/97] fix(client): commands run as Effects on the caller's fiber, so interrupting a caller stops them (#38912) Co-authored-by: Claude Fable 5.2 --- .../pull-requests/PullRequestRouteScreen.tsx | 13 +- .../pull-requests/usePullRequestList.ts | 16 +- .../SettingsNotificationsRouteScreen.tsx | 14 +- .../src/features/threads/useFileChipShare.ts | 5 +- .../features/usage/usageLimitsRefresh.test.ts | 23 +- apps/mobile/src/lib/attachmentUpload.test.ts | 51 ++- .../mobile/src/persistence/mobile-database.ts | 7 +- apps/mobile/src/state/attachments.test.ts | 68 +-- apps/mobile/src/state/attachments.ts | 27 +- .../state/composer-attachment-uploads.test.ts | 81 ++-- apps/mobile/src/state/peerPairingCode.ts | 9 +- apps/mobile/src/state/preferences.test.ts | 16 +- .../threadOutboxDelivery.permissions.test.ts | 35 +- apps/mobile/src/state/threadOutboxDelivery.ts | 11 +- apps/mobile/src/state/use-atom-command.ts | 8 +- .../mobile/src/state/use-atom-query-runner.ts | 7 +- ...hipsControl.remote-parent.browser.test.tsx | 25 +- .../ThreadVisitWatermark.browser.test.tsx | 5 +- .../src/components/chat/citationProcedure.ts | 7 +- .../device/useDeviceControls.browser.test.tsx | 19 +- .../ScheduledTasksSettings.browser.test.tsx | 3 +- .../sidebar/updateEverythingRun.test.ts | 5 +- .../sidebar/updateEverythingRun.tsx | 6 +- .../web/src/environments/primary/httpLayer.ts | 10 +- .../useSettings.favorites.browser.test.tsx | 15 +- .../web/src/lib/attachmentUploadQueue.test.ts | 48 ++- apps/web/src/state/connectMcpApproval.ts | 9 +- apps/web/src/state/device.ts | 44 +- apps/web/src/state/peerPairingCode.ts | 16 +- apps/web/src/state/use-atom-command.ts | 8 +- apps/web/src/state/use-atom-query-runner.ts | 7 +- apps/web/src/textGenerators.ts | 22 +- .../client-runtime/src/providerSkills.test.ts | 25 +- .../src/relay/discovery.test.ts | 19 +- .../src/state/attachments.test.ts | 14 +- .../client-runtime/src/state/attachments.ts | 57 ++- .../src/state/commandPermissions.test.ts | 11 +- .../src/state/projectCommands.test.ts | 6 +- .../src/state/pullRequests.test.ts | 186 ++++---- .../client-runtime/src/state/pullRequests.ts | 25 +- .../client-runtime/src/state/runtime.test.ts | 322 ++++++++------ packages/client-runtime/src/state/runtime.ts | 400 ++++++++++-------- .../client-runtime/src/state/server.test.ts | 86 ++-- packages/client-runtime/src/state/server.ts | 4 +- .../client-runtime/src/state/terminal.test.ts | 20 +- .../src/state/threadCommands.test.ts | 305 ++++++++----- .../src/state/threadCommands.ts | 40 +- .../src/state/threadLifecycle.ts | 51 +-- .../src/state/threadTitleRegeneration.ts | 15 +- .../src/state/threadVisits.test.ts | 33 +- .../client-runtime/src/state/usage.test.ts | 11 +- packages/client-runtime/src/state/vcs.test.ts | 32 +- .../src/state/vcsAction.test.ts | 45 +- .../src/state/vcsStatusRevalidation.test.ts | 5 +- 54 files changed, 1403 insertions(+), 949 deletions(-) diff --git a/apps/mobile/src/features/pull-requests/PullRequestRouteScreen.tsx b/apps/mobile/src/features/pull-requests/PullRequestRouteScreen.tsx index aab1a08298f64..883a8708eeb02 100644 --- a/apps/mobile/src/features/pull-requests/PullRequestRouteScreen.tsx +++ b/apps/mobile/src/features/pull-requests/PullRequestRouteScreen.tsx @@ -59,6 +59,7 @@ import { } from "@react-navigation/native"; import type { NativeStackNavigationProp } from "@react-navigation/native-stack"; import { RegistryContext, useAtomRefresh, useAtomValue } from "@effect/atom-react"; +import { runAtomCommand } from "@t3tools/client-runtime/state/runtime"; import { pullRequestReviewKey } from "./pullRequestReviewDrafts"; import { pullRequestConversationThreads, @@ -569,12 +570,12 @@ export function PullRequestRouteScreen({ route }: StaticScreenProps pullRefresh.onRefresh(async (signal) => { const target = requestTarget(params); - await composerPullRequests.invalidate - .run(registry, { - environmentId: target.environmentId, - input: { reference: target.input }, - }) - .catch(() => undefined); + await runAtomCommand( + registry, + composerPullRequests.invalidate, + { environmentId: target.environmentId, input: { reference: target.input } }, + { reportFailure: false }, + ); if (signal.aborted) return; if (guidesEnabled) refreshGuide(); stack.refresh(); diff --git a/apps/mobile/src/features/pull-requests/usePullRequestList.ts b/apps/mobile/src/features/pull-requests/usePullRequestList.ts index c1b13cb152e56..b7ad230e69db8 100644 --- a/apps/mobile/src/features/pull-requests/usePullRequestList.ts +++ b/apps/mobile/src/features/pull-requests/usePullRequestList.ts @@ -5,7 +5,11 @@ import { pullRequestPendingEditsFor, } from "@t3tools/client-runtime/state/pull-requests"; import { RegistryContext, useAtomMount, useAtomSubscribe, useAtomValue } from "@effect/atom-react"; -import { executeAtomQuery, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime"; +import { + executeAtomQuery, + runAtomCommand, + squashAtomCommandFailure, +} from "@t3tools/client-runtime/state/runtime"; import type { EnvironmentId, PullRequestDiffStat, PullRequestListInput } from "@t3tools/contracts"; import * as Cause from "effect/Cause"; import * as Effect from "effect/Effect"; @@ -130,10 +134,12 @@ async function refreshHeads( ) { const responses = await Promise.allSettled( targets.map(async (target) => { - await composerPullRequests.invalidate.run(registry, { - environmentId: target.environmentId, - input: {}, - }); + await runAtomCommand( + registry, + composerPullRequests.invalidate, + { environmentId: target.environmentId, input: {} }, + { reportFailure: false }, + ); if (signal.aborted) return; const response = await executeAtomQuery( registry, diff --git a/apps/mobile/src/features/settings/SettingsNotificationsRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsNotificationsRouteScreen.tsx index 9875978c92c3b..8a3d8ad0dfc85 100644 --- a/apps/mobile/src/features/settings/SettingsNotificationsRouteScreen.tsx +++ b/apps/mobile/src/features/settings/SettingsNotificationsRouteScreen.tsx @@ -15,7 +15,9 @@ import { useAuth } from "@clerk/expo"; import { useAtomSet, useAtomValue } from "@effect/atom-react"; import * as Notifications from "expo-notifications"; import { useNavigation } from "@react-navigation/native"; +import * as Cause from "effect/Cause"; import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; import * as Schema from "effect/Schema"; import { AsyncResult } from "effect/reactivity"; import { useRef, useState, useSyncExternalStore } from "react"; @@ -90,12 +92,12 @@ const updateEnvironmentPreference = Effect.fn("updateEnvironmentPreference")(fun environmentId: EnvironmentId, enabled: boolean, ) { - const result = yield* Effect.promise(() => + const exit = yield* Effect.exit( updateLiveActivityPreference.run(appAtomRegistry, { environmentId, input: enabled }), ); - if (result._tag === "Success") return result.value; + if (Exit.isSuccess(exit)) return exit.value; return yield* toCloudEnvironmentLinkError( - squashAtomCommandFailure(result), + Cause.squash(exit.cause), resolveMessage(msg("Could not update the environment's Live Activity preference.")), ); }); @@ -104,12 +106,12 @@ const linkEnvironmentWithPreference = Effect.fn("linkEnvironmentWithPreference") environmentId: EnvironmentId, input: { readonly clerkToken: string; readonly liveActivitiesEnabled: boolean }, ) { - const result = yield* Effect.promise(() => + const exit = yield* Effect.exit( linkLiveActivityEnvironment.run(appAtomRegistry, { environmentId, input }), ); - if (result._tag === "Success") return; + if (Exit.isSuccess(exit)) return; return yield* toCloudEnvironmentLinkError( - squashAtomCommandFailure(result), + Cause.squash(exit.cause), resolveMessage(msg("Could not configure environment relay access.")), ); }); diff --git a/apps/mobile/src/features/threads/useFileChipShare.ts b/apps/mobile/src/features/threads/useFileChipShare.ts index 3bbbf4fe388e8..0a454880f880d 100644 --- a/apps/mobile/src/features/threads/useFileChipShare.ts +++ b/apps/mobile/src/features/threads/useFileChipShare.ts @@ -36,7 +36,10 @@ export function useFileChipShare( requestRef.current = request; void (async () => { if (httpBaseUrl === null) throw new Error(gt("Reconnect to the environment and try again.")); - const result = await createUrl({ environmentId, input: { resource: source.resource } }); + const result = await createUrl( + { environmentId, input: { resource: source.resource } }, + { signal: request.signal }, + ); if (request.signal.aborted) return; const url = result._tag === "Success" ? resolveAssetUrl(httpBaseUrl, result.value.relativeUrl) : null; diff --git a/apps/mobile/src/features/usage/usageLimitsRefresh.test.ts b/apps/mobile/src/features/usage/usageLimitsRefresh.test.ts index 80310b98d8aed..fc10f0c7d9215 100644 --- a/apps/mobile/src/features/usage/usageLimitsRefresh.test.ts +++ b/apps/mobile/src/features/usage/usageLimitsRefresh.test.ts @@ -11,15 +11,22 @@ const state = vi.hoisted(() => ({ throw new Error("refresh not set up"); }, })); -vi.mock("../../state/server", () => ({ - serverEnvironment: { - refreshProviders: { - label: "refresh providers", - run: (_registry: unknown, input: { readonly environmentId: string }) => - state.refresh(input.environmentId), +vi.mock("../../state/server", async () => { + const Effect = await import("effect/Effect"); + return { + serverEnvironment: { + refreshProviders: { + label: "refresh providers", + run: (_registry: unknown, input: { readonly environmentId: string }) => + Effect.promise(() => state.refresh(input.environmentId)).pipe( + Effect.flatMap((result) => + result._tag === "Failure" ? Effect.failCause(result.cause) : Effect.void, + ), + ), + }, }, - }, -})); + }; +}); import { environmentIdsKey, diff --git a/apps/mobile/src/lib/attachmentUpload.test.ts b/apps/mobile/src/lib/attachmentUpload.test.ts index 9c58c9a3b05f6..e72996f41648a 100644 --- a/apps/mobile/src/lib/attachmentUpload.test.ts +++ b/apps/mobile/src/lib/attachmentUpload.test.ts @@ -17,14 +17,32 @@ const mocks = vi.hoisted(() => ({ writeFile: vi.fn(), deleteFile: vi.fn(), readBase64: vi.fn(), + // Verification and minting run as Effects; tests steer them with the settled results above. + settledEffect: ( + Effect: typeof import("effect/Effect"), + settle: () => Promise<{ + readonly _tag: string; + readonly value?: unknown; + readonly error?: object; + }>, + ) => + Effect.promise(settle).pipe( + Effect.flatMap((result) => + result._tag === "Success" ? Effect.succeed(result.value) : Effect.fail(result.error), + ), + ), })); -vi.mock("@t3tools/client-runtime/state/runtime", () => ({ - createEnvironmentRpcCommand: () => Symbol("rpc-command"), - executeAtomQuery: mocks.executeAtomQuery, - runAtomCommand: mocks.runAtomCommand, - squashAtomCommandFailure: (result: { readonly error: unknown }) => result.error, -})); +vi.mock("@t3tools/client-runtime/state/runtime", async () => { + const Effect = await import("effect/Effect"); + return { + createEnvironmentRpcCommand: () => Symbol("rpc-command"), + awaitAtomResult: (...args: ReadonlyArray) => + mocks.settledEffect(Effect, () => mocks.executeAtomQuery(...args)), + runAtomCommand: mocks.runAtomCommand, + squashAtomCommandFailure: (result: { readonly error: unknown }) => result.error, + }; +}); vi.mock("../state/atom-registry", () => ({ appAtomRegistry: { get: mocks.readAtom }, @@ -38,12 +56,20 @@ vi.mock("../state/assets", () => ({ assetEnvironment: { createUrl: mocks.createAssetUrl }, })); -vi.mock("../state/attachments", () => ({ - attachmentEnvironment: { - createUploadUrl: mocks.createUploadUrl, - remove: mocks.removeUpload, - }, -})); +vi.mock("../state/attachments", async () => { + const Effect = await import("effect/Effect"); + return { + attachmentEnvironment: { + createUploadUrl: { + run: (registry: unknown, input: unknown) => + mocks.settledEffect(Effect, () => + mocks.runAtomCommand(registry, mocks.createUploadUrl, input), + ), + }, + remove: mocks.removeUpload, + }, + }; +}); vi.mock("../state/session", () => ({ readEnvironmentScope: () => mocks.canOperate, @@ -449,7 +475,6 @@ describe("prepareTurnAttachments", () => { sizeBytes: largeImage.sizeBytes, }, }), - expect.anything(), ); expect(prepared.status).toBe("ready"); if (prepared.status !== "ready") return; diff --git a/apps/mobile/src/persistence/mobile-database.ts b/apps/mobile/src/persistence/mobile-database.ts index cbe8d3b74ca79..8c07d44f703d0 100644 --- a/apps/mobile/src/persistence/mobile-database.ts +++ b/apps/mobile/src/persistence/mobile-database.ts @@ -43,6 +43,7 @@ const ClientCacheSummaryRows = Schema.Array( const MobileDatabaseOperation = Schema.Literals([ "open", + "close", "migrate", "load-cache", "list-cache", @@ -127,7 +128,11 @@ const makeAvailable = Effect.gen(function* () { }, catch: databaseError("open"), }), - (openDatabase) => Effect.promise(() => openDatabase.closeAsync()).pipe(Effect.ignore), + (openDatabase) => + Effect.tryPromise({ + try: () => openDatabase.closeAsync(), + catch: databaseError("close"), + }).pipe(Effect.ignore), ); yield* Effect.tryPromise({ diff --git a/apps/mobile/src/state/attachments.test.ts b/apps/mobile/src/state/attachments.test.ts index 052c5ef045cb1..31acc4821b821 100644 --- a/apps/mobile/src/state/attachments.test.ts +++ b/apps/mobile/src/state/attachments.test.ts @@ -5,7 +5,7 @@ import { } from "@t3tools/contracts"; import { runAttachmentUploadCycle } from "@t3tools/client-runtime/state/attachments"; import * as Cause from "effect/Cause"; -import { AsyncResult, AtomRegistry } from "effect/reactivity"; +import { AtomRegistry } from "effect/reactivity"; import { describe, expect, it } from "@effect/vitest"; import * as Effect from "effect/Effect"; import * as Fiber from "effect/Fiber"; @@ -35,49 +35,55 @@ const environmentId = EnvironmentId.make("secondary"); const registry = AtomRegistry.make(); beforeEach(() => { state.grantedEnvironments = new Set(["primary"]); - state.create.mockReset().mockResolvedValue( - AsyncResult.success({ + state.create.mockReset().mockReturnValue( + Effect.succeed({ attachmentId: "pending", relativeUrl: "/upload", expiresAt: 1, }), ); - state.remove.mockReset().mockResolvedValue(AsyncResult.success(undefined)); + state.remove.mockReset().mockReturnValue(Effect.void); }); afterEach(() => { vi.restoreAllMocks(); }); describe("attachment mutation grants", () => { - it("uses the attachment environment for both mint and deletion", async () => { - const mintResult = await attachmentEnvironment.createUploadUrl.run(registry, { - environmentId, - input: { name: "image.png", mimeType: "image/png", sizeBytes: 1 }, - }); - const removeResult = await attachmentEnvironment.remove.run(registry, { - environmentId, - input: { attachmentId: "pending" }, - }); - for (const result of [mintResult, removeResult]) { - expect(result._tag).toBe("Failure"); - if (result._tag !== "Failure") throw new Error("Expected permission denial"); - const error = Cause.squash(result.cause); - expect(error).toBeInstanceOf(EnvironmentAuthorizationError); - expect(error).toMatchObject({ requiredScope: AuthOrchestrationOperateScope }); - } - expect(state.create).not.toHaveBeenCalled(); - expect(state.remove).not.toHaveBeenCalled(); - state.grantedEnvironments.add("secondary"); - expect( - ( - await attachmentEnvironment.remove.run(registry, { + it.effect("uses the attachment environment for both mint and deletion", () => + Effect.gen(function* () { + const mintResult = yield* Effect.exit( + attachmentEnvironment.createUploadUrl.run(registry, { + environmentId, + input: { name: "image.png", mimeType: "image/png", sizeBytes: 1 }, + }), + ); + const removeResult = yield* Effect.exit( + attachmentEnvironment.remove.run(registry, { environmentId, input: { attachmentId: "pending" }, - }) - )._tag, - ).toBe("Success"); - expect(state.remove).toHaveBeenCalledOnce(); - }); + }), + ); + for (const result of [mintResult, removeResult]) { + expect(result._tag).toBe("Failure"); + if (result._tag !== "Failure") throw new Error("Expected permission denial"); + const error = Cause.squash(result.cause); + expect(error).toBeInstanceOf(EnvironmentAuthorizationError); + expect(error).toMatchObject({ requiredScope: AuthOrchestrationOperateScope }); + } + expect(state.create).not.toHaveBeenCalled(); + expect(state.remove).not.toHaveBeenCalled(); + state.grantedEnvironments.add("secondary"); + expect( + (yield* Effect.exit( + attachmentEnvironment.remove.run(registry, { + environmentId, + input: { attachmentId: "pending" }, + }), + ))._tag, + ).toBe("Success"); + expect(state.remove).toHaveBeenCalledOnce(); + }), + ); it.effect("blocks the upload cycle's cleanup after grant revocation", () => Effect.gen(function* () { diff --git a/apps/mobile/src/state/attachments.ts b/apps/mobile/src/state/attachments.ts index 5406302363f74..3fa51740e8679 100644 --- a/apps/mobile/src/state/attachments.ts +++ b/apps/mobile/src/state/attachments.ts @@ -5,10 +5,9 @@ import { EnvironmentAuthorizationError, type EnvironmentId, } from "@t3tools/contracts"; -import * as Cause from "effect/Cause"; +import * as Effect from "effect/Effect"; import { msg } from "gt-react-native"; import { m } from "../i18n/messages"; -import { AsyncResult } from "effect/reactivity"; import { connectionAtomRuntime } from "../connection/runtime"; import { readEnvironmentScope } from "./session"; @@ -18,19 +17,17 @@ function requireAttachmentWriteAccess { return { ...command, - run: async (registry, input) => { - if (!readEnvironmentScope(input.environmentId, AuthOrchestrationOperateScope)) { - return AsyncResult.failure( - Cause.fail( - new EnvironmentAuthorizationError({ - message: m(msg("This connection cannot change attachments.")), - requiredScope: AuthOrchestrationOperateScope, - }), - ), - ); - } - return command.run(registry, input); - }, + run: (registry, input) => + Effect.suspend((): Effect.Effect => + readEnvironmentScope(input.environmentId, AuthOrchestrationOperateScope) + ? command.run(registry, input) + : Effect.fail( + new EnvironmentAuthorizationError({ + message: m(msg("This connection cannot change attachments.")), + requiredScope: AuthOrchestrationOperateScope, + }), + ), + ), }; } diff --git a/apps/mobile/src/state/composer-attachment-uploads.test.ts b/apps/mobile/src/state/composer-attachment-uploads.test.ts index 7d8a431150d26..7cda3b8e7c21f 100644 --- a/apps/mobile/src/state/composer-attachment-uploads.test.ts +++ b/apps/mobile/src/state/composer-attachment-uploads.test.ts @@ -17,7 +17,6 @@ const native = vi.hoisted(() => ({ canOperate: true, nextId: 0, nextUuid: 0, - mint: Symbol("mint"), remove: Symbol("remove"), transfer: vi.fn<(uri: string, url: string, options: UploadOptions) => Promise<{ status: number }>>(), @@ -130,43 +129,51 @@ vi.mock("./session", async () => { }, }; }); -vi.mock("./attachments", () => ({ - attachmentEnvironment: { createUploadUrl: native.mint, remove: native.remove }, -})); +vi.mock("./attachments", async () => { + const Effect = await import("effect/Effect"); + return { + attachmentEnvironment: { + createUploadUrl: { + run: () => + Effect.sync(() => { + const id = `pending-${++native.nextId}`; + native.server.set(id, null); + return { attachmentId: id, relativeUrl: `/upload/${id}`, expiresAt: 1 }; + }), + }, + remove: native.remove, + }, + }; +}); vi.mock("./assets", () => ({ assetEnvironment: { createUrl: (input: unknown) => input } })); -vi.mock("@t3tools/client-runtime/state/runtime", async (importOriginal) => ({ - ...(await importOriginal()), - createEnvironmentRpcCommand: () => Symbol("rpc-command"), - executeAtomQuery: async ( - _registry: unknown, - query: { input: { resource: { attachmentId: string } } }, - ) => - native.server.get(query.input.resource.attachmentId) - ? { _tag: "Success", value: {} } - : (await import("effect/reactivity")).AsyncResult.failure( - (await import("effect/Cause")).fail({ _tag: "AssetAttachmentNotFoundError" }), - ), - runAtomCommand: async ( - _registry: unknown, - command: unknown, - target: { input: { attachmentId?: string } }, - ) => { - if (command === native.mint) { - const id = `pending-${++native.nextId}`; - native.server.set(id, null); - return { - _tag: "Success", - value: { attachmentId: id, relativeUrl: `/upload/${id}`, expiresAt: 1 }, - }; - } - if (command === native.remove && target.input.attachmentId) { - native.deleted.push(target.input.attachmentId); - native.server.delete(target.input.attachmentId); - return { _tag: "Success", value: undefined }; - } - throw new Error("Unexpected RPC command"); - }, -})); +vi.mock("@t3tools/client-runtime/state/runtime", async (importOriginal) => { + const Effect = await import("effect/Effect"); + return { + ...(await importOriginal()), + createEnvironmentRpcCommand: () => Symbol("rpc-command"), + awaitAtomResult: ( + _registry: unknown, + query: { input: { resource: { attachmentId: string } } }, + ) => + Effect.suspend(() => + native.server.get(query.input.resource.attachmentId) + ? Effect.succeed({}) + : Effect.fail({ _tag: "AssetAttachmentNotFoundError" }), + ), + runAtomCommand: async ( + _registry: unknown, + command: unknown, + target: { input: { attachmentId?: string } }, + ) => { + if (command === native.remove && target.input.attachmentId) { + native.deleted.push(target.input.attachmentId); + native.server.delete(target.input.attachmentId); + return { _tag: "Success", value: undefined }; + } + throw new Error("Unexpected RPC command"); + }, + }; +}); vi.mock("./use-thread-outbox", async () => { const { Atom } = await import("effect/reactivity"); return { diff --git a/apps/mobile/src/state/peerPairingCode.ts b/apps/mobile/src/state/peerPairingCode.ts index 6cf4c6dc33426..0956f444f6ed9 100644 --- a/apps/mobile/src/state/peerPairingCode.ts +++ b/apps/mobile/src/state/peerPairingCode.ts @@ -1,5 +1,5 @@ import { createPeerPairingCodeCommand } from "@t3tools/client-runtime/state/peerPairingCode"; -import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime"; +import { runAtomCommand, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime"; import type { AuthMcpClientAccess, EnvironmentId } from "@t3tools/contracts"; import * as Result from "effect/Result"; @@ -17,7 +17,12 @@ export async function mintPairingCodeOn( environmentId: EnvironmentId, access: AuthMcpClientAccess, ): Promise> { - const result = await mintPairingCode.run(appAtomRegistry, { environmentId, input: access }); + const result = await runAtomCommand( + appAtomRegistry, + mintPairingCode, + { environmentId, input: access }, + { reportFailure: false }, + ); return result._tag === "Success" ? Result.succeed(result.value) : Result.fail(squashAtomCommandFailure(result)); diff --git a/apps/mobile/src/state/preferences.test.ts b/apps/mobile/src/state/preferences.test.ts index 1da7a30b542ad..862883d30803e 100644 --- a/apps/mobile/src/state/preferences.test.ts +++ b/apps/mobile/src/state/preferences.test.ts @@ -1,6 +1,7 @@ import { describe, expect, it } from "@effect/vitest"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity"; @@ -76,9 +77,14 @@ describe("mobile preferences state", () => { const registry = AtomRegistry.make(); const unmountPreferences = registry.mount(state.preferencesAtom); - const save = state.savePreferences.run(registry, { - collapsedProjectGroups: ["project:new"], - }); + const save = yield* Effect.forkChild( + Effect.exit( + state.savePreferences.run(registry, { + collapsedProjectGroups: ["project:new"], + }), + ), + { startImmediately: true }, + ); pendingLoad.resolve({ baseFontSize: 18, collapsedProjectGroups: ["project:old"], @@ -87,7 +93,7 @@ describe("mobile preferences state", () => { const preferences = yield* AtomRegistry.getResult(registry, state.preferencesAtom, { suspendOnWaiting: true, }); - const saveResult = yield* Effect.promise(() => save); + const saveResult = yield* Fiber.join(save); expect(preferences).toEqual({ baseFontSize: 18, collapsedProjectGroups: ["project:new"], @@ -95,7 +101,7 @@ describe("mobile preferences state", () => { expect(savePatch).toHaveBeenCalledWith({ collapsedProjectGroups: ["project:new"], }); - expect(AsyncResult.isFailure(saveResult)).toBe(false); + expect(Exit.isFailure(saveResult)).toBe(false); unmountPreferences(); registry.dispose(); diff --git a/apps/mobile/src/state/threadOutboxDelivery.permissions.test.ts b/apps/mobile/src/state/threadOutboxDelivery.permissions.test.ts index b8588e0d40082..49663f2340f47 100644 --- a/apps/mobile/src/state/threadOutboxDelivery.permissions.test.ts +++ b/apps/mobile/src/state/threadOutboxDelivery.permissions.test.ts @@ -27,6 +27,21 @@ const state = vi.hoisted(() => ({ interaction: vi.fn(), prepare: vi.fn(), checkout: vi.fn(), + // Delivery runs commands as Effects; tests steer them with the settled results the mocks return. + command: (Effect: typeof import("effect/Effect"), settle: (input: unknown) => unknown) => ({ + label: "command", + run: (_registry: unknown, input: unknown) => + Effect.promise( + async () => + (await settle(input)) as + | import("effect/reactivity").AsyncResult.Success + | import("effect/reactivity").AsyncResult.Failure, + ).pipe( + Effect.flatMap((result) => + result._tag === "Failure" ? Effect.failCause(result.cause) : Effect.succeed(result.value), + ), + ), + }), modelUnavailable: vi.fn(() => false), familyMount: vi.fn(() => () => {}), threadShells: null as unknown as Atom.Writable>, @@ -48,11 +63,6 @@ const state = vi.hoisted(() => ({ }, })); vi.mock("react-native", () => ({ Alert: { alert: vi.fn() } })); -vi.mock("@t3tools/client-runtime/state/runtime", async (importOriginal) => ({ - ...(await importOriginal()), - runAtomCommand: (_registry: unknown, command: (input: unknown) => unknown, input: unknown) => - command(input), -})); vi.mock("./session", async () => { const { Atom } = await import("effect/reactivity"); const { appAtomRegistry } = await import("./atom-registry"); @@ -88,13 +98,14 @@ vi.mock("./server", async () => { }); vi.mock("./threads", async () => { const { Atom, AsyncResult } = await import("effect/reactivity"); + const Effect = await import("effect/Effect"); state.threadShells = Atom.make>([state.thread]).pipe(Atom.keepAlive); return { threadEnvironment: { - startTurn: state.start, - updateMetadata: state.metadata, - setRuntimeMode: state.runtime, - setInteractionMode: state.interaction, + startTurn: state.command(Effect, state.start), + updateMetadata: state.command(Effect, state.metadata), + setRuntimeMode: state.command(Effect, state.runtime), + setInteractionMode: state.command(Effect, state.interaction), }, environmentThreadShells: { threadShellsAtom: state.threadShells }, threadFamilies: { @@ -105,7 +116,11 @@ vi.mock("./threads", async () => { environmentThreadDetails: { stateAtom: () => Atom.make(null) }, }; }); -vi.mock("./git", () => ({ gitEnvironment: { preparePullRequestThread: state.checkout } })); +vi.mock("./git", async () => ({ + gitEnvironment: { + preparePullRequestThread: state.command(await import("effect/Effect"), state.checkout), + }, +})); vi.mock("../lib/modelOptions", () => ({ isModelSelectionUnavailable: state.modelUnavailable })); vi.mock("../lib/uuid", () => ({ uuidv4: () => "uuid", randomHex: () => "abcd" })); vi.mock("../lib/attachmentUpload", () => ({ prepareTurnAttachments: state.prepare })); diff --git a/apps/mobile/src/state/threadOutboxDelivery.ts b/apps/mobile/src/state/threadOutboxDelivery.ts index d9e56da0d9229..1e12bd5d96c89 100644 --- a/apps/mobile/src/state/threadOutboxDelivery.ts +++ b/apps/mobile/src/state/threadOutboxDelivery.ts @@ -9,7 +9,7 @@ import { import { type AtomCommand, type AtomCommandResult, - runAtomCommand, + reportAtomCommandResult, } from "@t3tools/client-runtime/state/runtime"; import { threadFamilyRead, type ThreadFamilyRead } from "@t3tools/client-runtime/state/threads"; import { deriveThreadTitleSeed } from "@t3tools/client-runtime/operations"; @@ -708,7 +708,14 @@ const deliveryCommand = ( command: AtomCommand, input: W, ): Effect.Effect> => - Effect.promise(() => runAtomCommand(appAtomRegistry, command, input, { reportFailure: false })); + command.run(appAtomRegistry, input).pipe( + Effect.exit, + Effect.map((exit) => { + const result = AsyncResult.fromExit(exit); + reportAtomCommandResult(result, { label: command.label, reportFailure: false }); + return result; + }), + ); function reportCommandFailure( queuedMessage: QueuedThreadMessage, diff --git a/apps/mobile/src/state/use-atom-command.ts b/apps/mobile/src/state/use-atom-command.ts index b969091e7fa58..a0eaa765ab852 100644 --- a/apps/mobile/src/state/use-atom-command.ts +++ b/apps/mobile/src/state/use-atom-command.ts @@ -9,13 +9,13 @@ import { useContext } from "react"; export function useAtomCommand( command: AtomCommand, - options?: string | AtomCommandOptions, -): (value: W) => Promise> { + options?: string | Omit, +): (value: W, call?: Pick) => Promise> { const registry = useContext(RegistryContext); const label = typeof options === "string" ? options : (options?.label ?? command.label); const reportFailure = typeof options === "string" ? true : (options?.reportFailure ?? true); const reportDefect = typeof options === "string" ? true : (options?.reportDefect ?? true); - return (value: W) => - runAtomCommand(registry, command, value, { label, reportFailure, reportDefect }); + return (value, call) => + runAtomCommand(registry, command, value, { label, reportFailure, reportDefect, ...call }); } diff --git a/apps/mobile/src/state/use-atom-query-runner.ts b/apps/mobile/src/state/use-atom-query-runner.ts index 81b4140b227b3..4687d3e08f46b 100644 --- a/apps/mobile/src/state/use-atom-query-runner.ts +++ b/apps/mobile/src/state/use-atom-query-runner.ts @@ -9,21 +9,22 @@ import { useContext } from "react"; export function useAtomQueryRunner( family: (target: T) => Atom.Atom>, - options?: string | AtomQueryOptions, -): (target: T) => Promise> { + options?: string | Omit, +): (target: T, call?: Pick) => Promise> { const registry = useContext(RegistryContext); const explicitLabel = typeof options === "string" ? options : options?.label; const reportFailure = typeof options === "string" ? true : (options?.reportFailure ?? true); const reportDefect = typeof options === "string" ? true : (options?.reportDefect ?? true); const refresh = typeof options === "string" ? false : (options?.refresh ?? false); - return (target: T) => { + return (target, call) => { const atom = family(target); return executeAtomQuery(registry, atom, { label: explicitLabel ?? atom.label?.[0] ?? "atom query", reportFailure, reportDefect, refresh, + ...call, }); }; } diff --git a/apps/web/src/components/chat/ThreadRelationshipsControl.remote-parent.browser.test.tsx b/apps/web/src/components/chat/ThreadRelationshipsControl.remote-parent.browser.test.tsx index 08108cd835885..3e32be81a5000 100644 --- a/apps/web/src/components/chat/ThreadRelationshipsControl.remote-parent.browser.test.tsx +++ b/apps/web/src/components/chat/ThreadRelationshipsControl.remote-parent.browser.test.tsx @@ -25,13 +25,24 @@ const child = { }, } as Partial as OrchestrationV2ThreadShell; -vi.mock(import("../../state/orchestration"), async (original) => ({ - ...(await original()), - threadTitlesRead: { - label: "thread-titles-read", - run: (_registry: unknown, input: unknown) => read(input), - } as never, -})); +vi.mock(import("../../state/orchestration"), async (original) => { + const Effect = await import("effect/Effect"); + type Reply = + | { readonly _tag: "Success"; readonly value: unknown } + | { readonly _tag: "Failure"; readonly cause: Cause.Cause }; + return { + ...(await original()), + threadTitlesRead: { + label: "thread-titles-read", + run: (_registry: unknown, input: unknown) => + Effect.promise(() => read(input) as Promise).pipe( + Effect.flatMap((reply) => + reply._tag === "Success" ? Effect.succeed(reply.value) : Effect.failCause(reply.cause), + ), + ), + } as never, + }; +}); vi.mock(import("../../state/entities"), async (original) => ({ ...(await original()), useThreadProjection: () => null, diff --git a/apps/web/src/components/chat/ThreadVisitWatermark.browser.test.tsx b/apps/web/src/components/chat/ThreadVisitWatermark.browser.test.tsx index a730db051bf0e..3e35d2fcc0cb9 100644 --- a/apps/web/src/components/chat/ThreadVisitWatermark.browser.test.tsx +++ b/apps/web/src/components/chat/ThreadVisitWatermark.browser.test.tsx @@ -1,6 +1,7 @@ import { claimThreadOpen } from "@t3tools/client-runtime/state/thread-search"; import { EnvironmentId, type ScopedThreadRef, ThreadId } from "@t3tools/contracts"; -import { AsyncResult, Atom } from "effect/reactivity"; +import * as Effect from "effect/Effect"; +import { Atom } from "effect/reactivity"; import { expect, it, vi } from "vite-plus/test"; import { fakeTimers, render } from "../../../test/render"; @@ -55,7 +56,7 @@ function visitedThreadIds() { it("records the visit of the next thread at once after switching threads", async () => { mocks.visitRun.mockReset(); - mocks.visitRun.mockResolvedValue(AsyncResult.success(undefined)); + mocks.visitRun.mockReturnValue(Effect.void); setShell(threadA, "2026-01-02T00:00:00.000Z"); setShell(threadB, "2026-01-03T00:00:00.000Z"); using _timers = fakeTimers(); diff --git a/apps/web/src/components/chat/citationProcedure.ts b/apps/web/src/components/chat/citationProcedure.ts index cd3fc0d40e3a4..b8fed7df1da27 100644 --- a/apps/web/src/components/chat/citationProcedure.ts +++ b/apps/web/src/components/chat/citationProcedure.ts @@ -1,6 +1,7 @@ import { useAtomValue } from "@effect/atom-react"; -import { type AtomCommandSuccess, runAtomCommand } from "@t3tools/client-runtime/state/runtime"; +import { runAtomCommand } from "@t3tools/client-runtime/state/runtime"; import { sentMessageFromToolItem } from "@t3tools/shared/toolOutput"; +import type * as Effect from "effect/Effect"; import { Atom, type AtomRegistry } from "effect/reactivity"; import { msg } from "gt-react"; import { m } from "../../i18n/messages"; @@ -33,8 +34,8 @@ export type CitedHistoryOutcome = | { readonly _tag: "failed"; readonly title: string; readonly description: string } | { readonly _tag: "aborted" }; -type HistoryPageResult = AtomCommandSuccess< - Awaited> +type HistoryPageResult = Effect.Success< + ReturnType >; const MAX_CITATION_PAGES = 20; diff --git a/apps/web/src/components/device/useDeviceControls.browser.test.tsx b/apps/web/src/components/device/useDeviceControls.browser.test.tsx index 85c484bfd520c..b97a0b6b36721 100644 --- a/apps/web/src/components/device/useDeviceControls.browser.test.tsx +++ b/apps/web/src/components/device/useDeviceControls.browser.test.tsx @@ -3,13 +3,16 @@ import type { DeviceHubAccess } from "@t3tools/client-runtime/device/hub-access" import type { AtomCommandConcurrency } from "@t3tools/client-runtime/state/runtime"; import { RegistryContext } from "@effect/atom-react"; import * as Cause from "effect/Cause"; +import type { Effect } from "effect/Effect"; import { AtomRegistry } from "effect/reactivity"; import { useEffect } from "react"; import { expect, it, vi } from "vite-plus/test"; import { act, render } from "../../../test/render"; -type Result = { _tag: "Success"; value: DeviceDetail } | { _tag: "Failure"; cause: unknown }; +type Result = + | { _tag: "Success"; value: DeviceDetail } + | { _tag: "Failure"; cause: Cause.Cause }; const { read, action, subscribe } = vi.hoisted(() => ({ read: vi.fn<() => Promise>(), action: vi.fn<() => Promise>(), @@ -19,6 +22,7 @@ const { read, action, subscribe } = vi.hoisted(() => ({ // Stubs only the transport; the device atoms' real scheduler and lanes decide ordering. vi.mock(import("@t3tools/client-runtime/state/runtime"), async (original) => { const runtime = await original(); + const Effects = await import("effect/Effect"); const createEnvironmentRpcCommand = ( _runtime: unknown, options: { @@ -28,19 +32,24 @@ vi.mock(import("@t3tools/client-runtime/state/runtime"), async (original) => { registry: AtomRegistry.AtomRegistry, concurrency: AtomCommandConcurrency, input: unknown, - execute: () => Promise, - ) => Promise; + effect: Effect, + ) => Effect; }; readonly concurrency?: AtomCommandConcurrency; }, ) => { const send = options.label === "environment-data:device:detail" ? read : action; + const sent = Effects.promise(() => send()).pipe( + Effects.flatMap((result) => + result._tag === "Success" ? Effects.succeed(result.value) : Effects.failCause(result.cause), + ), + ); return { label: options.label, run: (registry: AtomRegistry.AtomRegistry, input: unknown) => options.scheduler && options.concurrency - ? options.scheduler.schedule(registry, options.concurrency, input, () => send()) - : send(), + ? options.scheduler.schedule(registry, options.concurrency, input, sent) + : sent, }; }; return { ...runtime, createEnvironmentRpcCommand: createEnvironmentRpcCommand as never }; diff --git a/apps/web/src/components/settings/ScheduledTasksSettings.browser.test.tsx b/apps/web/src/components/settings/ScheduledTasksSettings.browser.test.tsx index de655f374af5e..7ba2d17d7291d 100644 --- a/apps/web/src/components/settings/ScheduledTasksSettings.browser.test.tsx +++ b/apps/web/src/components/settings/ScheduledTasksSettings.browser.test.tsx @@ -1,4 +1,5 @@ import { RegistryContext } from "@effect/atom-react"; +import * as Effect from "effect/Effect"; import { Atom, AtomRegistry } from "effect/reactivity"; import { DEFAULT_UNIFIED_SETTINGS, @@ -66,7 +67,7 @@ const permissions = new Map>(); function setup() { state.connected = true; state.tasksLoaded = true; - state.remove.mockReset().mockResolvedValue({ _tag: "Success", value: { id: task.id } }); + state.remove.mockReset().mockReturnValue(Effect.succeed({ id: task.id })); state.secondary = false; permissions.clear(); permissions.set(environmentId, Atom.make(true)); diff --git a/apps/web/src/components/sidebar/updateEverythingRun.test.ts b/apps/web/src/components/sidebar/updateEverythingRun.test.ts index c06ff106c1c30..eb0736741082b 100644 --- a/apps/web/src/components/sidebar/updateEverythingRun.test.ts +++ b/apps/web/src/components/sidebar/updateEverythingRun.test.ts @@ -1,5 +1,6 @@ import { AVAILABLE_CONNECTION_STATE } from "@t3tools/client-runtime/connection"; import { EnvironmentId, type ServerConfig } from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; import { AsyncResult, Atom } from "effect/reactivity"; import { afterEach, describe, expect, it, vi } from "vite-plus/test"; @@ -71,9 +72,7 @@ describe("startDesktopUpdateLaunchNotice", () => { AsyncResult.success({ ...AVAILABLE_CONNECTION_STATE, phase: "backoff" as const }), ) as unknown as ReturnType, ); - using retryNow = vi - .spyOn(environmentCatalog.retryNow, "run") - .mockResolvedValue(AsyncResult.success(undefined)); + using retryNow = vi.spyOn(environmentCatalog.retryNow, "run").mockReturnValue(Effect.void); const stop = relaunchWhileRestarting(environmentId); try { await vi.advanceTimersByTimeAsync(1_000); diff --git a/apps/web/src/components/sidebar/updateEverythingRun.tsx b/apps/web/src/components/sidebar/updateEverythingRun.tsx index 613650cd77cf9..bd0990095b16d 100644 --- a/apps/web/src/components/sidebar/updateEverythingRun.tsx +++ b/apps/web/src/components/sidebar/updateEverythingRun.tsx @@ -350,9 +350,9 @@ function followHandedOffServers(servers: ReadonlyArray): void { ).pipe( Stream.map((state) => AsyncResult.getOrElse(state, () => AVAILABLE_CONNECTION_STATE)), ), - retryNow: Effect.promise(() => - environmentCatalog.retryNow.run(appAtomRegistry, server.environmentId), - ).pipe(Effect.asVoid), + retryNow: environmentCatalog.retryNow + .run(appAtomRegistry, server.environmentId) + .pipe(Effect.ignoreCause), }), ); const unsubscribe = appAtomRegistry.subscribe( diff --git a/apps/web/src/environments/primary/httpLayer.ts b/apps/web/src/environments/primary/httpLayer.ts index 96b493129f463..e28ecdfb1515d 100644 --- a/apps/web/src/environments/primary/httpLayer.ts +++ b/apps/web/src/environments/primary/httpLayer.ts @@ -1,7 +1,7 @@ import { layerRemoteHttpClient } from "@t3tools/client-runtime/rpc"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; -import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/http"; +import { FetchHttpClient, HttpClient, HttpClientError, HttpClientRequest } from "effect/http"; import { readDesktopPrimaryBearerToken } from "./desktopAuth"; import { resolvePrimaryEnvironmentHttpUrl } from "./target"; @@ -21,7 +21,13 @@ function isSameOriginBrowserPrimary(): boolean { function withPrimaryBearerToken(client: HttpClient.HttpClient): HttpClient.HttpClient { return client.pipe( HttpClient.mapRequestEffect((request) => - Effect.promise(readDesktopPrimaryBearerToken).pipe( + Effect.tryPromise({ + try: readDesktopPrimaryBearerToken, + catch: (cause) => + new HttpClientError.HttpClientError({ + reason: new HttpClientError.TransportError({ request, cause }), + }), + }).pipe( Effect.map((bearerToken) => bearerToken ? HttpClientRequest.bearerToken(request, bearerToken) : request, ), diff --git a/apps/web/src/hooks/useSettings.favorites.browser.test.tsx b/apps/web/src/hooks/useSettings.favorites.browser.test.tsx index 434123191dba6..acbe2d5e64b97 100644 --- a/apps/web/src/hooks/useSettings.favorites.browser.test.tsx +++ b/apps/web/src/hooks/useSettings.favorites.browser.test.tsx @@ -59,6 +59,7 @@ vi.mock("~/localApi", () => ({ vi.mock(import("~/state/server"), async (original) => { const actual = await original(); + const Effect = await import("effect/Effect"); return { ...actual, serverEnvironment: { @@ -66,7 +67,19 @@ vi.mock(import("~/state/server"), async (original) => { settingsValueAtom: ((id: EnvironmentId) => state.settings.get(id)) as never, updateSettings: { ...actual.serverEnvironment.updateSettings, - run: (_registry: unknown, input: unknown) => state.persist(input), + run: (_registry: unknown, input: unknown) => + Effect.promise( + () => + state.persist(input) as Promise< + AsyncResult.Success | AsyncResult.Failure + >, + ).pipe( + Effect.flatMap((result) => + result._tag === "Failure" + ? Effect.failCause(result.cause) + : Effect.succeed(result.value), + ), + ), } as never, }, }; diff --git a/apps/web/src/lib/attachmentUploadQueue.test.ts b/apps/web/src/lib/attachmentUploadQueue.test.ts index a9483e1755e35..d1ca469029b63 100644 --- a/apps/web/src/lib/attachmentUploadQueue.test.ts +++ b/apps/web/src/lib/attachmentUploadQueue.test.ts @@ -20,13 +20,31 @@ const mocks = vi.hoisted(() => ({ runAtomCommand: vi.fn(), readEnvironmentScope: vi.fn(), readPreparedConnection: vi.fn(), + // Verification and minting run as Effects; tests steer them with the settled results above. + settledEffect: ( + Effect: typeof import("effect/Effect"), + settle: () => Promise<{ + readonly _tag: string; + readonly value?: unknown; + readonly error?: object; + }>, + ) => + Effect.promise(settle).pipe( + Effect.flatMap((result) => + result._tag === "Success" ? Effect.succeed(result.value) : Effect.fail(result.error), + ), + ), })); -vi.mock("@t3tools/client-runtime/state/runtime", () => ({ - executeAtomQuery: mocks.executeAtomQuery, - runAtomCommand: mocks.runAtomCommand, - squashAtomCommandFailure: (result: { readonly error: unknown }) => result.error, -})); +vi.mock("@t3tools/client-runtime/state/runtime", async () => { + const Effect = await import("effect/Effect"); + return { + awaitAtomResult: (...args: ReadonlyArray) => + mocks.settledEffect(Effect, () => mocks.executeAtomQuery(...args)), + runAtomCommand: mocks.runAtomCommand, + squashAtomCommandFailure: (result: { readonly error: unknown }) => result.error, + }; +}); vi.mock("../rpc/atomRegistry", async () => { const { AtomRegistry } = await import("effect/reactivity"); @@ -41,12 +59,20 @@ vi.mock("../state/assets", () => ({ assetEnvironment: { createUrl: mocks.createAssetUrl }, })); -vi.mock("../state/attachments", () => ({ - attachmentEnvironment: { - createUploadUrl: mocks.createUploadUrl, - remove: mocks.removeUpload, - }, -})); +vi.mock("../state/attachments", async () => { + const Effect = await import("effect/Effect"); + return { + attachmentEnvironment: { + createUploadUrl: { + run: (registry: unknown, input: unknown) => + mocks.settledEffect(Effect, () => + mocks.runAtomCommand(registry, mocks.createUploadUrl, input), + ), + }, + remove: mocks.removeUpload, + }, + }; +}); vi.mock("../state/session", () => ({ readEnvironmentScope: mocks.readEnvironmentScope, diff --git a/apps/web/src/state/connectMcpApproval.ts b/apps/web/src/state/connectMcpApproval.ts index 0f044fc47fb2c..c634926d03cc8 100644 --- a/apps/web/src/state/connectMcpApproval.ts +++ b/apps/web/src/state/connectMcpApproval.ts @@ -2,7 +2,7 @@ import { type ConnectMcpApprovalCall, createConnectMcpApprovalCommand, } from "@t3tools/client-runtime/state/connectMcpApproval"; -import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime"; +import { runAtomCommand, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime"; import type { EnvironmentId } from "@t3tools/contracts"; import * as Result from "effect/Result"; @@ -16,7 +16,12 @@ export async function runConnectMcpApproval( environmentId: EnvironmentId, call: ConnectMcpApprovalCall, ) { - const result = await connectMcpApproval.run(appAtomRegistry, { environmentId, call }); + const result = await runAtomCommand( + appAtomRegistry, + connectMcpApproval, + { environmentId, call }, + { reportFailure: false }, + ); return result._tag === "Success" ? Result.succeed(result.value) : Result.fail(squashAtomCommandFailure(result)); diff --git a/apps/web/src/state/device.ts b/apps/web/src/state/device.ts index c1e7e4ec7f396..a386d8b5d3650 100644 --- a/apps/web/src/state/device.ts +++ b/apps/web/src/state/device.ts @@ -4,10 +4,7 @@ import { type DeviceHubAccess, resolveDeviceHubAccess, } from "@t3tools/client-runtime/state/deviceHubAccess"; -import { - createEnvironmentRpcQueryAtomFamily, - runAtomCommand, -} from "@t3tools/client-runtime/state/runtime"; +import { createEnvironmentRpcQueryAtomFamily } from "@t3tools/client-runtime/state/runtime"; import { type DeviceDetail, type DeviceServiceState, @@ -130,23 +127,21 @@ export const deviceDetailAtom = Atom.family((key: DeviceDetailKey) => */ export const deviceDetailReadAtom = Atom.family((key: DeviceDetailKey) => Atom.make((get) => - Effect.promise(() => - runAtomCommand( - get.registry, - deviceEnvironment.detail, - { environmentId: key.environmentId, input: { hostId: key.hostId, deviceId: key.deviceId } }, - { reportFailure: false }, - ), - ).pipe( - Effect.map((result) => - get.set( - deviceDetailAtom(key), - result._tag === "Success" - ? { detail: result.value, error: null } - : { detail: null, error: formatEnvironmentQueryError(result.cause) }, - ), + deviceEnvironment.detail + .run(get.registry, { + environmentId: key.environmentId, + input: { hostId: key.hostId, deviceId: key.deviceId }, + }) + .pipe( + Effect.matchCause({ + onSuccess: (detail) => get.set(deviceDetailAtom(key), { detail, error: null }), + onFailure: (cause) => + get.set(deviceDetailAtom(key), { + detail: null, + error: formatEnvironmentQueryError(cause), + }), + }), ), - ), ).pipe(Atom.withLabel(`device-detail-read:${key.hostId}:${key.deviceId}`)), ); @@ -156,14 +151,7 @@ export const deviceDetailReadAtom = Atom.family((key: DeviceDetailKey) => */ export const deviceHostProbeAtom = Atom.family((environmentId: EnvironmentId) => Atom.make((get) => - Effect.promise(() => - runAtomCommand( - get.registry, - deviceEnvironment.list, - { environmentId, input: {} }, - { reportFailure: false }, - ), - ).pipe(Effect.asVoid), + deviceEnvironment.list.run(get.registry, { environmentId, input: {} }).pipe(Effect.ignore), ).pipe(Atom.withLabel(`device-host-probe:${environmentId}`)), ); diff --git a/apps/web/src/state/peerPairingCode.ts b/apps/web/src/state/peerPairingCode.ts index e84ecc857789d..5ae8c7210fba7 100644 --- a/apps/web/src/state/peerPairingCode.ts +++ b/apps/web/src/state/peerPairingCode.ts @@ -2,7 +2,7 @@ import { createMcpApprovalCodeCommand, createPeerPairingCodeCommand, } from "@t3tools/client-runtime/state/peerPairingCode"; -import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime"; +import { runAtomCommand, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime"; import type { AuthMcpClientAccess, AuthPairingCredentialResult, @@ -25,7 +25,12 @@ export async function mintPairingCodeOn( environmentId: EnvironmentId, access: AuthMcpClientAccess, ): Promise> { - const result = await mintPairingCode.run(appAtomRegistry, { environmentId, input: access }); + const result = await runAtomCommand( + appAtomRegistry, + mintPairingCode, + { environmentId, input: access }, + { reportFailure: false }, + ); return result._tag === "Success" ? Result.succeed(result.value) : Result.fail(squashAtomCommandFailure(result)); @@ -36,7 +41,12 @@ export async function mintMcpApprovalCodeOn( environmentId: EnvironmentId, access: AuthMcpClientAccess, ): Promise> { - const result = await mintMcpApprovalCode.run(appAtomRegistry, { environmentId, input: access }); + const result = await runAtomCommand( + appAtomRegistry, + mintMcpApprovalCode, + { environmentId, input: access }, + { reportFailure: false }, + ); return result._tag === "Success" ? Result.succeed(result.value) : Result.fail(squashAtomCommandFailure(result)); diff --git a/apps/web/src/state/use-atom-command.ts b/apps/web/src/state/use-atom-command.ts index b969091e7fa58..a0eaa765ab852 100644 --- a/apps/web/src/state/use-atom-command.ts +++ b/apps/web/src/state/use-atom-command.ts @@ -9,13 +9,13 @@ import { useContext } from "react"; export function useAtomCommand( command: AtomCommand, - options?: string | AtomCommandOptions, -): (value: W) => Promise> { + options?: string | Omit, +): (value: W, call?: Pick) => Promise> { const registry = useContext(RegistryContext); const label = typeof options === "string" ? options : (options?.label ?? command.label); const reportFailure = typeof options === "string" ? true : (options?.reportFailure ?? true); const reportDefect = typeof options === "string" ? true : (options?.reportDefect ?? true); - return (value: W) => - runAtomCommand(registry, command, value, { label, reportFailure, reportDefect }); + return (value, call) => + runAtomCommand(registry, command, value, { label, reportFailure, reportDefect, ...call }); } diff --git a/apps/web/src/state/use-atom-query-runner.ts b/apps/web/src/state/use-atom-query-runner.ts index 81b4140b227b3..4687d3e08f46b 100644 --- a/apps/web/src/state/use-atom-query-runner.ts +++ b/apps/web/src/state/use-atom-query-runner.ts @@ -9,21 +9,22 @@ import { useContext } from "react"; export function useAtomQueryRunner( family: (target: T) => Atom.Atom>, - options?: string | AtomQueryOptions, -): (target: T) => Promise> { + options?: string | Omit, +): (target: T, call?: Pick) => Promise> { const registry = useContext(RegistryContext); const explicitLabel = typeof options === "string" ? options : options?.label; const reportFailure = typeof options === "string" ? true : (options?.reportFailure ?? true); const reportDefect = typeof options === "string" ? true : (options?.reportDefect ?? true); const refresh = typeof options === "string" ? false : (options?.refresh ?? false); - return (target: T) => { + return (target, call) => { const atom = family(target); return executeAtomQuery(registry, atom, { label: explicitLabel ?? atom.label?.[0] ?? "atom query", reportFailure, reportDefect, refresh, + ...call, }); }; } diff --git a/apps/web/src/textGenerators.ts b/apps/web/src/textGenerators.ts index 57a7ab089d300..21ceb58f7ec30 100644 --- a/apps/web/src/textGenerators.ts +++ b/apps/web/src/textGenerators.ts @@ -1,6 +1,6 @@ +import { runAtomCommand } from "@t3tools/client-runtime/state/runtime"; import { useAtomValue } from "@effect/atom-react"; import { providerClients } from "@t3tools/client-runtime/provider-clients"; -import { runAtomCommand } from "@t3tools/client-runtime/state/runtime"; import { type EnvironmentId, type ModelSelection, @@ -135,20 +135,12 @@ const textGeneratorModelsAtom = Atom.family((key: string) => { return Atom.make((get) => { // Read again after a refresh; the server's cache already holds the new list by then. get(refreshCountAtom(`${environmentId}:${id}`)); - return Effect.promise(() => - runAtomCommand( - get.registry, - serverEnvironment.listTextGeneratorModels, - { environmentId, input: { id } }, - { reportFailure: false }, - ), - ).pipe( - Effect.flatMap((result) => - result._tag === "Success" - ? Effect.succeed(result.value.models) - : Effect.fail(formatEnvironmentQueryError(result.cause)), - ), - ); + return serverEnvironment.listTextGeneratorModels + .run(get.registry, { environmentId, input: { id } }) + .pipe( + Effect.map((result) => result.models), + Effect.catchCause((cause) => Effect.fail(formatEnvironmentQueryError(cause))), + ); }).pipe(Atom.setIdleTTL(5 * 60_000), Atom.withLabel(`text-generator-models:${key}`)); }); diff --git a/packages/client-runtime/src/providerSkills.test.ts b/packages/client-runtime/src/providerSkills.test.ts index 143efdbe7869b..ec6a8593ae98d 100644 --- a/packages/client-runtime/src/providerSkills.test.ts +++ b/packages/client-runtime/src/providerSkills.test.ts @@ -4,8 +4,8 @@ import { ProviderInstanceId, type ServerProvider, } from "@t3tools/contracts"; -import * as Cause from "effect/Cause"; -import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity"; +import * as Effect from "effect/Effect"; +import { Atom, AtomRegistry } from "effect/reactivity"; import { afterEach, describe, expect, it, vi } from "vite-plus/test"; import { @@ -185,17 +185,16 @@ describe("provider workspace snapshot refresh atom", () => { let droppedReplies = options?.droppedReplies ?? 0; const providersAtom = Atom.make | null>(initialProviders); const responses: Response[] = [...(initialResponses ?? [])]; - const run = vi.fn(async () => { - const providers = await (responses.shift() ?? (() => null))(); - if (providers === null) { - return AsyncResult.failure<{ providers: ReadonlyArray }, string>( - Cause.fail("offline"), - ); - } - if (droppedReplies > 0) droppedReplies -= 1; - else registry.set(providersAtom, providers); - return AsyncResult.success({ providers }); - }); + const run = vi.fn(() => + Effect.promise(async () => (responses.shift() ?? (() => null))()).pipe( + Effect.flatMap((providers) => { + if (providers === null) return Effect.fail("offline"); + if (droppedReplies > 0) droppedReplies -= 1; + else registry.set(providersAtom, providers); + return Effect.succeed({ providers }); + }), + ), + ); const family = createProviderWorkspaceSnapshotRefreshAtomFamily({ providers: () => providersAtom, refreshProviders: { label: "refresh", run }, diff --git a/packages/client-runtime/src/relay/discovery.test.ts b/packages/client-runtime/src/relay/discovery.test.ts index f0445e4968faf..85f4a73189f19 100644 --- a/packages/client-runtime/src/relay/discovery.test.ts +++ b/packages/client-runtime/src/relay/discovery.test.ts @@ -200,14 +200,23 @@ describe("RelayEnvironmentDiscovery", () => { const registry = AtomRegistry.make(); yield* Effect.addFinalizer(() => Effect.sync(() => registry.dispose())); - const refresh = atoms.refresh.run(registry, undefined); + const refresh = yield* Effect.forkChild( + Effect.exit(atoms.refresh.run(registry, undefined)), + { startImmediately: true }, + ); yield* SubscriptionRef.changes(discovery.state).pipe( Stream.filter((state) => state.environments.size === environments.length), Stream.runHead, ); - const coalescedRefresh = atoms.refresh.run(registry, undefined); + const coalescedRefresh = yield* Effect.forkChild( + Effect.exit(atoms.refresh.run(registry, undefined)), + { startImmediately: true }, + ); yield* Ref.set(harness.listedEnvironments, [environments[1]!]); - const mutationRefresh = atoms.refreshAfterMutation.run(registry, undefined); + const mutationRefresh = yield* Effect.forkChild( + Effect.exit(atoms.refreshAfterMutation.run(registry, undefined)), + { startImmediately: true }, + ); const requests = yield* Ref.get(harness.statusRequests); for (const environment of environments) { @@ -216,9 +225,7 @@ describe("RelayEnvironmentDiscovery", () => { status(environment, "online"), ); } - const results = yield* Effect.promise(() => - Promise.all([refresh, coalescedRefresh, mutationRefresh]), - ); + const results = yield* Fiber.joinAll([refresh, coalescedRefresh, mutationRefresh]); for (const result of results) { expect(result._tag).toBe("Success"); } diff --git a/packages/client-runtime/src/state/attachments.test.ts b/packages/client-runtime/src/state/attachments.test.ts index 5a467311ad5a0..0860e7fde5eb8 100644 --- a/packages/client-runtime/src/state/attachments.test.ts +++ b/packages/client-runtime/src/state/attachments.test.ts @@ -7,7 +7,7 @@ import { } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; import * as Fiber from "effect/Fiber"; -import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity"; +import { Atom, AtomRegistry } from "effect/reactivity"; import type { AtomCommand } from "./runtime.ts"; import { @@ -34,8 +34,8 @@ type RemoveCommand = AtomCommand< function makeCreateUploadUrl(attachmentId: string): CreateUploadUrlCommand { return { label: "test:create-upload-url", - run: async () => - AsyncResult.success({ + run: () => + Effect.succeed({ attachmentId, relativeUrl: `/api/attachments/upload/${attachmentId}`, expiresAt: 1, @@ -46,10 +46,10 @@ function makeCreateUploadUrl(attachmentId: string): CreateUploadUrlCommand { const removeCalls: string[] = []; const remove: RemoveCommand = { label: "test:remove", - run: async (_registry, input) => { - removeCalls.push(input.input.attachmentId); - return AsyncResult.success(undefined); - }, + run: (_registry, input) => + Effect.sync(() => { + removeCalls.push(input.input.attachmentId); + }), }; const uploadInput: AttachmentCreateUploadUrlInput = { diff --git a/packages/client-runtime/src/state/attachments.ts b/packages/client-runtime/src/state/attachments.ts index 1759663f52bef..03494e139f1f6 100644 --- a/packages/client-runtime/src/state/attachments.ts +++ b/packages/client-runtime/src/state/attachments.ts @@ -6,7 +6,9 @@ import { type AttachmentDeleteInput, type EnvironmentId, } from "@t3tools/contracts"; +import * as Cause from "effect/Cause"; import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; import { mFallback, msg } from "gt-i18n"; import type { MFunctionType } from "gt-i18n/types"; import type { AsyncResult, Atom, AtomRegistry } from "effect/reactivity"; @@ -14,9 +16,8 @@ import type { AsyncResult, Atom, AtomRegistry } from "effect/reactivity"; import type { EnvironmentRegistry } from "../connection/registry.ts"; import { createEnvironmentRpcCommand, - executeAtomQuery, + awaitAtomResult, runAtomCommand, - squashAtomCommandFailure, type AtomCommand, } from "./runtime.ts"; @@ -65,25 +66,25 @@ export function verifyPersistedAttachmentUpload(input: { readonly environmentId: EnvironmentId; readonly attachmentId: string; }): Effect.Effect { - return Effect.promise(() => - executeAtomQuery( - input.registry, - input.createAssetUrl({ - environmentId: input.environmentId, - input: { resource: { _tag: "attachment", attachmentId: input.attachmentId } }, - }), - // `refresh` forces a server round trip: the asset URL query atom caches - // results (SWR), so a retry right after a transient failure would - // otherwise re-observe the cached failure and never ask the server. - { reportFailure: false, reportDefect: false, refresh: true }, - ), + return awaitAtomResult( + input.registry, + input.createAssetUrl({ + environmentId: input.environmentId, + input: { resource: { _tag: "attachment", attachmentId: input.attachmentId } }, + }), + // `refresh` forces a server round trip: the asset URL query atom caches + // results (SWR), so a retry right after a transient failure would + // otherwise re-observe the cached failure and never ask the server. + { refresh: true }, ).pipe( - Effect.map((result): PersistedAttachmentVerification => { - if (result._tag === "Success") return { status: "verified" }; - const error = squashAtomCommandFailure(result); - return isAssetAttachmentNotFoundFailure(error) - ? { status: "missing" } - : { status: "failed", error }; + Effect.matchCause({ + onSuccess: (): PersistedAttachmentVerification => ({ status: "verified" }), + onFailure: (cause): PersistedAttachmentVerification => { + const error = Cause.squash(cause); + return isAssetAttachmentNotFoundFailure(error) + ? { status: "missing" } + : { status: "failed", error }; + }, }), Effect.withSpan("Attachments.verifyPersistedUpload"), ); @@ -141,20 +142,18 @@ export function runAttachmentUploadCycle(input: { }): Effect.Effect { return Effect.uninterruptibleMask((restore) => Effect.gen(function* () { - const minted = yield* Effect.promise(() => - runAtomCommand( - input.registry, - input.createUploadUrl, - { environmentId: input.environmentId, input: input.upload }, - { reportFailure: false }, - ), + const minted = yield* Effect.exit( + input.createUploadUrl.run(input.registry, { + environmentId: input.environmentId, + input: input.upload, + }), ); - if (minted._tag !== "Success") { + if (Exit.isFailure(minted)) { return { status: "failed", step: "mint", attachmentId: null, - error: squashAtomCommandFailure(minted), + error: Cause.squash(minted.cause), } as const; } const attachmentId = minted.value.attachmentId; diff --git a/packages/client-runtime/src/state/commandPermissions.test.ts b/packages/client-runtime/src/state/commandPermissions.test.ts index 403f44394656b..0fc89a1fd2f63 100644 --- a/packages/client-runtime/src/state/commandPermissions.test.ts +++ b/packages/client-runtime/src/state/commandPermissions.test.ts @@ -32,7 +32,7 @@ import * as Layer from "effect/Layer"; import { Atom, AtomRegistry, AsyncResult } from "effect/reactivity"; import { EnvironmentRegistry } from "../connection/registry.ts"; import { createCommandPermissions } from "./commandPermissions.ts"; -import { createEnvironmentRpcCommand } from "./runtime.ts"; +import { createEnvironmentRpcCommand, runAtomCommand } from "./runtime.ts"; import { AVAILABLE_CONNECTION_STATE, BearerConnectionTarget } from "../connection/model.ts"; import { createPeerLinkEnvironmentAtoms } from "./peerLinks.ts"; @@ -290,9 +290,10 @@ describe("command permissions", () => { }); const target = { environmentId: env, input: { id: ScheduledTaskId.make("task") } }; try { - const first = command.run(registry, target); + const quiet = { reportFailure: false, reportDefect: false }; + const first = runAtomCommand(registry, command, target, quiet); await entered; - const second = command.run(registry, target); + const second = runAtomCommand(registry, command, target, quiet); registry.set(sessions(env), AsyncResult.success(grant(false))); release(); expect((await first)._tag).toBe("Success"); @@ -468,10 +469,10 @@ it.effect( setAccess(false); expect(yield* readLinks).toEqual({ links: [] }); const linkInput = { url: peer.urls[0]!, pairingCode: "test-code", access: peer.access }; - const link = Effect.promise(() => + const link = Effect.exit( peerLinks.link.run(registry, { environmentId: env, input: linkInput }), ); - const unlink = Effect.promise(() => + const unlink = Effect.exit( peerLinks.unlink.run(registry, { environmentId: env, input: { environmentId: peer.environmentId }, diff --git a/packages/client-runtime/src/state/projectCommands.test.ts b/packages/client-runtime/src/state/projectCommands.test.ts index c49e86d08bba8..ca93479d461ba 100644 --- a/packages/client-runtime/src/state/projectCommands.test.ts +++ b/packages/client-runtime/src/state/projectCommands.test.ts @@ -140,7 +140,7 @@ const makeHarness = Effect.fn("TestProjectCommands.makeHarness")(function* () { permissions: [AuthFilesystemWriteScope], }), ); - const openScratch = Effect.promise(() => + const openScratch = Effect.exit( commands.openScratch.run(registry, { environmentId: ENVIRONMENT_ID, input: {} }), ); return { registry, storedProject, openScratch, commands, metadataRequests, readResponse }; @@ -307,7 +307,7 @@ describe("writeFile metadata", () => { { suspendOnWaiting: true }, ).pipe(Effect.forkChild); yield* Deferred.await(started); - const write = yield* Effect.promise(() => + const write = yield* Effect.exit( h.commands.writeFile.run(h.registry, { environmentId: ENVIRONMENT_ID, input: { cwd: "/repo", relativePath: "foo", contents: "new" }, @@ -342,7 +342,7 @@ describe("writeFile metadata", () => { { kind: "file", byteLength: 5 }, { kind: "file", byteLength: 5 }, ]); - const result = yield* Effect.promise(() => + const result = yield* Effect.exit( h.commands.writeFile.run(h.registry, { environmentId: ENVIRONMENT_ID, input: { cwd: "/repo", relativePath: "./foo", contents: "new" }, diff --git a/packages/client-runtime/src/state/pullRequests.test.ts b/packages/client-runtime/src/state/pullRequests.test.ts index c90b279679751..daa8f041a2e1f 100644 --- a/packages/client-runtime/src/state/pullRequests.test.ts +++ b/packages/client-runtime/src/state/pullRequests.test.ts @@ -16,6 +16,7 @@ import { import { expect, it } from "@effect/vitest"; import * as Schema from "effect/Schema"; import * as Deferred from "effect/Deferred"; +import * as Exit from "effect/Exit"; import * as Fiber from "effect/Fiber"; import * as TestClock from "effect/testing/TestClock"; import * as Effect from "effect/Effect"; @@ -980,18 +981,28 @@ it.effect("keeps concurrent diff file reads on different hosts separate", () => oldPath: "src/app.ts", newPath: "src/app.ts", } as const; - const first = atoms.diffFileContents.run(registry, { - environmentId: TARGET.environmentId, - input: { ...input, host: "github.com" }, - }); + const first = yield* Effect.forkChild( + Effect.exit( + atoms.diffFileContents.run(registry, { + environmentId: TARGET.environmentId, + input: { ...input, host: "github.com" }, + }), + ), + { startImmediately: true }, + ); yield* started.await; - const second = atoms.diffFileContents.run(registry, { - environmentId: TARGET.environmentId, - input: { ...input, host: "github.example.com" }, - }); + const second = yield* Effect.forkChild( + Effect.exit( + atoms.diffFileContents.run(registry, { + environmentId: TARGET.environmentId, + input: { ...input, host: "github.example.com" }, + }), + ), + { startImmediately: true }, + ); yield* release.open; - const results = yield* Effect.promise(() => Promise.all([first, second])); + const results = yield* Fiber.joinAll([first, second]); expect(results).toMatchObject([ { _tag: "Success", value: { newContents: "github.com" } }, { _tag: "Success", value: { newContents: "github.example.com" } }, @@ -1022,22 +1033,32 @@ it.effect.each(["closed", "draft", "permission", "stack", "method"] as const)( environmentId: TARGET.environmentId, input: { projectId: ProjectId.make("project-1"), repository: "acme/web", number: 1 }, }; - const merge = atoms.runAction.run(registry, { - ...target, - input: { - ...target.input, - action: "merge", - resolveMergeMethod: () => { - if (reason === "method") throw new Error("No merge method is available."); - return "squash"; - }, - }, - }); - const close = atoms.runAction.run(registry, { - ...target, - input: { ...target.input, action: "close" }, - }); - const results = yield* Effect.promise(() => Promise.all([merge, close])); + const merge = yield* Effect.forkChild( + Effect.exit( + atoms.runAction.run(registry, { + ...target, + input: { + ...target.input, + action: "merge", + resolveMergeMethod: () => { + if (reason === "method") throw new Error("No merge method is available."); + return "squash"; + }, + }, + }), + ), + { startImmediately: true }, + ); + const close = yield* Effect.forkChild( + Effect.exit( + atoms.runAction.run(registry, { + ...target, + input: { ...target.input, action: "close" }, + }), + ), + { startImmediately: true }, + ); + const results = yield* Fiber.joinAll([merge, close]); expect(results.map((result) => result._tag)).toEqual(["Failure", "Success"]); expect(calls).toEqual(["close"]); }), @@ -1065,21 +1086,26 @@ it.effect("keeps a close batch ordered and continues after a refused close", () }), } as unknown as WsRpcProtocolClient; const { atoms, registry } = yield* makeTestRuntime(client); - const batch = [6, 5, 4].map((number) => - atoms.runAction.run(registry, { - environmentId: TARGET.environmentId, - input: { - projectId: ProjectId.make("project-1"), - repository: "acme/web", - number, - action: "close", - }, - }), + const batch = yield* Effect.forEach([6, 5, 4], (number) => + Effect.forkChild( + Effect.exit( + atoms.runAction.run(registry, { + environmentId: TARGET.environmentId, + input: { + projectId: ProjectId.make("project-1"), + repository: "acme/web", + number, + action: "close", + }, + }), + ), + { startImmediately: true }, + ), ); yield* Deferred.await(started); expect(calls).toEqual([6]); yield* Deferred.succeed(release, undefined); - const results = yield* Effect.promise(() => Promise.all(batch)); + const results = yield* Fiber.joinAll(batch); expect(results.map((result) => result._tag)).toEqual(["Success", "Failure", "Success"]); expect(calls).toEqual([6, 5, 4]); }), @@ -1185,7 +1211,7 @@ it.effect("shows an action's reply in loaded readers and moves list rows without } reads.length = 0; - const answer = yield* Effect.promise(() => + const answer = yield* Effect.exit( atoms.runAction.run(registry, { ...target, input: { ...target.input, action: "merge" } }), ); @@ -1251,7 +1277,7 @@ it.effect("keeps an action's reply when a refresh started before the action answ registry.refresh(detail); yield* Deferred.await(started); - yield* Effect.promise(() => + yield* Effect.exit( atoms.runAction.run(registry, { ...target, input: { ...actionReference, action: "merge" }, @@ -1314,7 +1340,7 @@ it.effect("keeps a list read the server's refresh started before the action repl }); yield* Effect.addFinalizer(() => Effect.sync(stop)); - yield* Effect.promise(() => + yield* Effect.exit( atoms.runAction.run(registry, { ...target, input: { ...actionReference, action: "merge" }, @@ -1386,7 +1412,7 @@ it.effect("restarts a list page read sent while the action was in flight", () => yield* Effect.promise(() => executeAtomQuery(registry, atom)); } - const action = yield* Effect.promise(() => + const action = yield* Effect.exit( atoms.runAction.run(registry, { ...target, input: { ...actionReference, action: "close" }, @@ -1425,7 +1451,7 @@ it.effect("shows a reopen reply at once and re-reads the fields it lacks", () => registry.mount(detail); yield* AtomRegistry.getResult(registry, detail, { suspendOnWaiting: true }); - yield* Effect.promise(() => + yield* Effect.exit( atoms.runAction.run(registry, { ...target, input: { ...actionReference, action: "reopen" }, @@ -1482,7 +1508,7 @@ it.effect("keeps each reader's read time when a reply leaves its checks as they yield* Effect.promise(() => executeAtomQuery(registry, atom)); } - yield* Effect.promise(() => + yield* Effect.exit( atoms.runAction.run(registry, { ...target, input: { ...actionReference, action: "ready" }, @@ -1529,7 +1555,7 @@ it.effect("re-reads an unstamped preview rather than order a reply against it", registry.mount(preview); yield* AtomRegistry.getResult(registry, preview, { suspendOnWaiting: true }); - yield* Effect.promise(() => + yield* Effect.exit( atoms.runAction.run(registry, { ...target, input: { ...actionReference, action: "close" }, @@ -1580,7 +1606,7 @@ it.effect("leaves a loaded list page alone when the reply concerns none of its r yield* Effect.addFinalizer(() => Effect.sync(unmount)); yield* Effect.promise(() => executeAtomQuery(registry, page)); - yield* Effect.promise(() => + yield* Effect.exit( atoms.runAction.run(registry, { ...target, input: { ...actionReference, action: "ready" }, @@ -1626,7 +1652,7 @@ it.effect("keeps the server's post-commit read when a reopen reply lacks fields" }); yield* Effect.addFinalizer(() => Effect.sync(stop)); - yield* Effect.promise(() => + yield* Effect.exit( atoms.runAction.run(registry, { ...target, input: { ...actionReference, action: "reopen" }, @@ -1670,7 +1696,7 @@ it.effect.each([ yield* AtomRegistry.getResult(registry, reader, { suspendOnWaiting: true }); } - yield* Effect.promise(() => + yield* Effect.exit( atoms.runAction.run(registry, { ...target, input: { ...actionReference, action: "ready" }, @@ -1726,21 +1752,21 @@ it.effect("keeps hover previews fresh after edits and turns", () => ).toBe(title); yield* Effect.promise(() => executeAtomQuery(registry, preview)); expect(reads).toBe(1); - const edited = yield* Effect.promise(() => + const edited = yield* Effect.exit( atoms.update.run(registry, { ...target, input: { ...reference, title: "Edited" } }), ); - expect(AsyncResult.isSuccess(edited)).toBe(true); + expect(Exit.isSuccess(edited)).toBe(true); expect( (yield* AtomRegistry.getResult(registry, preview, { suspendOnWaiting: true })).title, ).toBe("Edited"); - yield* Effect.promise(() => + yield* Effect.exit( atoms.runAction.run(registry, { ...target, input: { ...reference, action: "close" } }), ); expect( (yield* AtomRegistry.getResult(registry, preview, { suspendOnWaiting: true })).title, ).toBe("Closed"); title = "Refreshed"; - yield* Effect.promise(() => + yield* Effect.exit( atoms.invalidate.run(registry, { environmentId: target.environmentId, input: { reference }, @@ -1933,13 +1959,13 @@ it.effect("shares close, reopen, and merge with an untouched client's mounted PR }), ]; yield* Effect.addFinalizer(() => Effect.sync(() => stops.forEach((stop) => stop()))); - const result = yield* Effect.promise(() => + const result = yield* Effect.exit( writer.atoms.runAction.run(writer.registry, { ...target, input: { ...target.input, action }, }), ); - expect(AsyncResult.isSuccess(result)).toBe(true); + expect(Exit.isSuccess(result)).toBe(true); yield* detailChanged.await; yield* summaryChanged.await; yield* listChanged.await; @@ -2110,7 +2136,7 @@ it.effect("updates cached labels after successful edits without rereading the ho yield* AtomRegistry.getResult(registry, detail, { suspendOnWaiting: true }); yield* AtomRegistry.getResult(registry, candidates, { suspendOnWaiting: true }); - const added = yield* Effect.promise(() => + const added = yield* Effect.exit( atoms.setLabels.run(registry, { ...target, input: { @@ -2123,7 +2149,7 @@ it.effect("updates cached labels after successful edits without rereading the ho }, }), ); - expect(AsyncResult.isSuccess(added)).toBe(true); + expect(Exit.isSuccess(added)).toBe(true); expect(yield* AtomRegistry.getResult(registry, detail)).toEqual({ title: "keep this title", labels: [existing, addedLabel], @@ -2138,7 +2164,7 @@ it.effect("updates cached labels after successful edits without rereading the ho for (const name of ["existing", "new"]) { refuse = name === "new"; - const result = yield* Effect.promise(() => + const result = yield* Effect.exit( atoms.setLabels.run(registry, { ...target, input: { ...target.input, labels: [name], applied: false }, @@ -2279,7 +2305,7 @@ it.effect("publishes the accepted guide run before the follow-up read finishes", const query = atoms.reviewGuide(target); registry.mount(query); yield* AtomRegistry.getResult(registry, query, { suspendOnWaiting: true }); - const result = yield* Effect.promise(() => atoms.generateReviewGuide.run(registry, target)); + const result = yield* Effect.exit(atoms.generateReviewGuide.run(registry, target)); expect(result._tag).toBe("Success"); yield* refreshStarted.await; expect(AsyncResult.getOrElse(registry.get(query), () => null)).toEqual(accepted); @@ -2358,7 +2384,7 @@ it.effect.each([ } reads = 0; - const acting = yield* Effect.promise(() => + const acting = yield* Effect.exit( atoms.runAction.run(registry, { ...target, input: { ...actionReference, action } }), ).pipe(Effect.forkScoped); yield* Deferred.await(sent); @@ -2424,7 +2450,7 @@ it.effect("puts readers back when the host refuses an action, and saves nothing yield* Effect.promise(() => executeAtomQuery(registry, atom)); } - const acting = yield* Effect.promise(() => + const acting = yield* Effect.exit( atoms.runAction.run(registry, { ...target, input: { ...actionReference, action: "close" }, @@ -2497,7 +2523,7 @@ it.effect( registry.mount(detail); yield* Effect.promise(() => executeAtomQuery(registry, detail)); - yield* Effect.promise(() => + yield* Effect.exit( atoms.runAction.run(registry, { ...target, input: { ...actionReference, action: "close" }, @@ -2561,30 +2587,40 @@ it.effect.each([ registry.mount(list); yield* Effect.promise(() => executeAtomQuery(registry, list)); - const closes = [1, 2].map((number) => - atoms.runAction.run(registry, { - environmentId: TARGET.environmentId, - input: { ...actionReference, number, action: "close" }, - }), + const closes = yield* Effect.forEach([1, 2], (number) => + Effect.forkChild( + Effect.exit( + atoms.runAction.run(registry, { + environmentId: TARGET.environmentId, + input: { ...actionReference, number, action: "close" }, + }), + ), + { startImmediately: true }, + ), ); yield* Deferred.await(firstSent); expect(Option.getOrThrow(AsyncResult.value(registry.get(list))).entries).toEqual([]); - const reopen = atoms.runAction.run(registry, { - environmentId: TARGET.environmentId, - input: { ...actionReference, number: 1, action: "reopen" }, - }); + const reopen = yield* Effect.forkChild( + Effect.exit( + atoms.runAction.run(registry, { + environmentId: TARGET.environmentId, + input: { ...actionReference, number: 1, action: "reopen" }, + }), + ), + { startImmediately: true }, + ); expect( Option.getOrThrow(AsyncResult.value(registry.get(list))).entries.map((row) => row.number), ).toEqual([1]); yield* Deferred.succeed(release, undefined); - yield* Effect.promise(() => Promise.all(closes)); + yield* Fiber.joinAll(closes); expect( Option.getOrThrow(AsyncResult.value(registry.get(list))).entries.map((row) => row.number), ).toEqual([1]); yield* Deferred.succeed(releaseReopen, undefined); - expect((yield* Effect.promise(() => reopen))._tag).toBe("Failure"); + expect((yield* Fiber.join(reopen))._tag).toBe("Failure"); expect(Option.getOrThrow(AsyncResult.value(registry.get(list))).entries).toEqual([]); }), ), @@ -2612,7 +2648,7 @@ it.effect("leaves a merge as it is until the host says what it did", () => registry.mount(detail); yield* Effect.promise(() => executeAtomQuery(registry, detail)); - const acting = yield* Effect.promise(() => + const acting = yield* Effect.exit( atoms.runAction.run(registry, { ...target, input: { ...actionReference, action: "merge" }, @@ -2716,7 +2752,7 @@ it.effect.each(["accepted", "refused"] as const)( )?.title, ]; - const editing = yield* Effect.promise(() => + const editing = yield* Effect.exit( atoms.update.run(registry, { ...target, input: { ...actionReference, title: "Edited" } }), ).pipe(Effect.forkScoped); yield* Deferred.await(sent); @@ -2794,7 +2830,7 @@ it.effect.each(["accepted", "refused"] as const)( yield* Effect.promise(() => executeAtomQuery(registry, atom)); } - const labelling = yield* Effect.promise(() => + const labelling = yield* Effect.exit( atoms.setLabels.run(registry, { ...target, input: { ...actionReference, labels: ["new"], applied: true }, @@ -2869,7 +2905,7 @@ it.effect.each(["loaded", "loading"] as const)( } yield* Deferred.await(readStarted); - yield* Effect.promise(() => + yield* Effect.exit( atoms.setLabels.run(registry, { ...target, input: { ...actionReference, labels: ["new"], applied: true }, @@ -2916,7 +2952,7 @@ it.effect.each(["accepted", "refused"] as const)( yield* Effect.promise(() => executeAtomQuery(registry, checks)); const state = () => Option.getOrThrow(AsyncResult.value(registry.get(checks)))?.state; - const acting = yield* Effect.promise(() => + const acting = yield* Effect.exit( atoms.runAction.run(registry, { ...target, input: { ...actionReference, action: "close" }, diff --git a/packages/client-runtime/src/state/pullRequests.ts b/packages/client-runtime/src/state/pullRequests.ts index a207f69902f7f..6ca8705a5735a 100644 --- a/packages/client-runtime/src/state/pullRequests.ts +++ b/packages/client-runtime/src/state/pullRequests.ts @@ -316,17 +316,20 @@ function showWhileInFlight { - const edit = editOf(registry, target); - if (edit === null) return command.run(registry, target); - const edits = pullRequestPendingEditsAtom(target.environmentId); - registry.update(edits, (current) => [...current, edit]); - try { - return await command.run(registry, target); - } finally { - registry.update(edits, (current) => current.filter((entry) => entry !== edit)); - } - }, + run: (registry, target) => + Effect.suspend(() => { + const edit = editOf(registry, target); + if (edit === null) return command.run(registry, target); + const edits = pullRequestPendingEditsAtom(target.environmentId); + return Effect.acquireUseRelease( + Effect.sync(() => registry.update(edits, (current) => [...current, edit])), + () => command.run(registry, target), + () => + Effect.sync(() => + registry.update(edits, (current) => current.filter((entry) => entry !== edit)), + ), + ); + }), } satisfies AtomCommand; } diff --git a/packages/client-runtime/src/state/runtime.test.ts b/packages/client-runtime/src/state/runtime.test.ts index 2a47459ec5cf4..27a1b22c91f41 100644 --- a/packages/client-runtime/src/state/runtime.test.ts +++ b/packages/client-runtime/src/state/runtime.test.ts @@ -26,6 +26,7 @@ import * as DateTime from "effect/DateTime"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; +import * as Fiber from "effect/Fiber"; import * as Latch from "effect/Latch"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; @@ -67,7 +68,6 @@ import { createEnvironmentSubscriptionAtomFamily, createRuntimeCommand, environmentSessionGenerationAtom, - scheduleAtomCommandEffect, executeAtomQuery, type QueryAnswerHandler, } from "./runtime.ts"; @@ -1559,64 +1559,100 @@ describe("executeAtomQuery", () => { }); describe("runtime command runner", () => { - it("settles generated command scheduler defects from direct callers", async () => { - const defect = new Error("invalid command key"); - const runtime = Atom.runtime(Layer.empty); - const command = createRuntimeCommand(runtime, { - label: "test.invalid-key", - concurrency: { - mode: "serial", - key: () => { - throw defect; + const start = (effect: Effect.Effect) => + Effect.forkChild(Effect.exit(effect), { startImmediately: true }); + + it.effect("fails the run with a defect when its lane key throws", () => + Effect.gen(function* () { + const defect = new Error("invalid command key"); + const command = createRuntimeCommand(Atom.runtime(Layer.empty), { + label: "test.invalid-key", + concurrency: { + mode: "serial", + key: () => { + throw defect; + }, }, - }, - execute: () => Effect.void, - }); - const registry = AtomRegistry.make(); + execute: () => Effect.void, + }); + const registry = AtomRegistry.make(); - const result = await command.run(registry, undefined); - expect(result._tag).toBe("Failure"); - if (result._tag === "Failure") { - expect(Cause.hasDies(result.cause)).toBe(true); - expect(Cause.squash(result.cause)).toBe(defect); - } - registry.dispose(); - }); + const exit = yield* Effect.exit(command.run(registry, undefined)); + expect(Exit.isFailure(exit) && Cause.squash(exit.cause)).toBe(defect); + registry.dispose(); + }), + ); - it("serializes commands that share a scheduler and lane", async () => { - const firstLatch = Latch.makeUnsafe(); - const events: string[] = []; - const runtime = Atom.runtime(Layer.empty); - const scheduler = createAtomCommandScheduler(); - const concurrency = { mode: "serial" as const, key: () => "shared" }; - const firstCommand = createRuntimeCommand(runtime, { - label: "test.first", - scheduler, - concurrency, - execute: () => - Effect.sync(() => events.push("first:start")).pipe( - Effect.andThen(firstLatch.await), - Effect.tap(() => Effect.sync(() => events.push("first:end"))), - ), - }); - const secondCommand = createRuntimeCommand(runtime, { - label: "test.second", - scheduler, - concurrency, - execute: () => Effect.sync(() => events.push("second:start")), - }); - const registry = AtomRegistry.make(); + it.effect("stops a command when its caller is interrupted", () => + Effect.gen(function* () { + const started = Latch.makeUnsafe(); + let stopped = false; + const command = createRuntimeCommand(Atom.runtime(Layer.empty), { + label: "test.interrupt", + execute: () => + Effect.sync(() => started.openUnsafe()).pipe( + Effect.andThen(Effect.never), + Effect.onInterrupt(() => + Effect.sync(() => { + stopped = true; + }), + ), + ), + }); + const registry = AtomRegistry.make(); - const first = firstCommand.run(registry, undefined); - const second = secondCommand.run(registry, undefined); - await Promise.resolve(); - expect(events).toEqual(["first:start"]); + const run = yield* start(command.run(registry, undefined)); + yield* started.await; + yield* Fiber.interrupt(run); - firstLatch.openUnsafe(); - await Promise.all([first, second]); - expect(events).toEqual(["first:start", "first:end", "second:start"]); - registry.dispose(); - }); + expect(stopped).toBe(true); + registry.dispose(); + }), + ); + + it.effect("serializes a lane, and skips a queued command its caller stopped waiting for", () => + Effect.gen(function* () { + const firstStarted = Latch.makeUnsafe(); + const firstLatch = Latch.makeUnsafe(); + const events: string[] = []; + const runtime = Atom.runtime(Layer.empty); + const scheduler = createAtomCommandScheduler(); + const concurrency = { mode: "serial" as const, key: () => "shared" }; + const firstCommand = createRuntimeCommand(runtime, { + label: "test.first", + scheduler, + concurrency, + execute: () => + Effect.sync(() => { + events.push("first:start"); + firstStarted.openUnsafe(); + }).pipe( + Effect.andThen(firstLatch.await), + Effect.tap(() => Effect.sync(() => events.push("first:end"))), + ), + }); + const queuedCommand = createRuntimeCommand(runtime, { + label: "test.queued", + scheduler, + concurrency, + execute: (name: string) => Effect.sync(() => events.push(`${name}:start`)), + }); + const registry = AtomRegistry.make(); + + const first = yield* start(firstCommand.run(registry, undefined)); + yield* firstStarted.await; + const abandoned = yield* start(queuedCommand.run(registry, "abandoned")); + const third = yield* start(queuedCommand.run(registry, "third")); + yield* Fiber.interrupt(abandoned); + expect(events).toEqual(["first:start"]); + + firstLatch.openUnsafe(); + yield* Fiber.join(first); + yield* Fiber.join(third); + expect(events).toEqual(["first:start", "first:end", "third:start"]); + registry.dispose(); + }), + ); it.effect("releases a shared scheduler lane before the outer command finishes", () => Effect.gen(function* () { @@ -1629,15 +1665,16 @@ describe("runtime command runner", () => { const updateCommand = createRuntimeCommand(runtime, { label: "test.update", execute: (_input: void, registry) => - scheduleAtomCommandEffect( - registry, - scheduler, - concurrency, - undefined, - Effect.sync(() => handoffStarted.openUnsafe()).pipe( - Effect.andThen(handoffComplete.await), - ), - ).pipe(Effect.andThen(resumeComplete.await)), + scheduler + .schedule( + registry, + concurrency, + undefined, + Effect.sync(() => handoffStarted.openUnsafe()).pipe( + Effect.andThen(handoffComplete.await), + ), + ) + .pipe(Effect.andThen(resumeComplete.await)), }); const configCommand = createRuntimeCommand(runtime, { label: "test.config", @@ -1647,21 +1684,14 @@ describe("runtime command runner", () => { }); const registry = AtomRegistry.make(); - const update = updateCommand.run(registry, undefined); + const update = yield* start(updateCommand.run(registry, undefined)); yield* handoffStarted.await; - const config = configCommand.run(registry, undefined); + const config = yield* start(configCommand.run(registry, undefined)); handoffComplete.openUnsafe(); - expect(yield* Effect.promise(() => config)).toMatchObject({ - _tag: "Success", - value: "configured", - waiting: false, - }); + expect(yield* Fiber.join(config)).toEqual(Exit.succeed("configured")); resumeComplete.openUnsafe(); - expect(yield* Effect.promise(() => update)).toMatchObject({ - _tag: "Success", - waiting: false, - }); + expect(Exit.isSuccess(yield* Fiber.join(update))).toBe(true); registry.dispose(); }), ); @@ -1673,10 +1703,9 @@ describe("runtime command runner", () => { const reconnected = yield* Deferred.make(); const states = yield* Queue.unbounded<{ readonly phase: string }>(); yield* Queue.offer(states, { phase: "connected" }); - const runtime = Atom.runtime(Layer.empty); const scheduler = createAtomCommandScheduler(); const concurrency = { mode: "serial" as const, key: () => "shared" }; - const command = createRuntimeCommand(runtime, { + const command = createRuntimeCommand(Atom.runtime(Layer.empty), { label: "test.desktop-update-handoff", execute: (_input: void, registry) => Effect.gen(function* () { @@ -1692,9 +1721,8 @@ describe("runtime command runner", () => { Effect.andThen(Deferred.succeed(reconnected, undefined)), Effect.forkChild, ); - yield* scheduleAtomCommandEffect( + yield* scheduler.schedule( registry, - scheduler, concurrency, undefined, Deferred.succeed(commitStarting, undefined).pipe( @@ -1708,62 +1736,106 @@ describe("runtime command runner", () => { }); const registry = AtomRegistry.make(); - expect(yield* Effect.promise(() => command.run(registry, undefined))).toMatchObject({ - _tag: "Success", - }); + yield* command.run(registry, undefined); registry.dispose(); }), ); - it("deduplicates single-flight commands by key", async () => { - const latch = Latch.makeUnsafe(); - let executions = 0; - const runtime = Atom.runtime(Layer.empty); - const command = createRuntimeCommand(runtime, { - label: "test.single-flight", - concurrency: { mode: "singleFlight", key: (key: string) => key }, - execute: () => - Effect.sync(() => executions++).pipe(Effect.andThen(latch.await), Effect.as("done")), - }); - const registry = AtomRegistry.make(); + it.effect("shares a single-flight run, which stops once its last caller stops waiting", () => + Effect.gen(function* () { + const started = Latch.makeUnsafe(); + let executions = 0; + let stopped = false; + const command = createRuntimeCommand(Atom.runtime(Layer.empty), { + label: "test.single-flight", + concurrency: { mode: "singleFlight", key: (key: string) => key }, + execute: () => + Effect.sync(() => { + executions++; + started.openUnsafe(); + }).pipe( + Effect.andThen(Effect.never), + Effect.onInterrupt(() => + Effect.sync(() => { + stopped = true; + }), + ), + ), + }); + const registry = AtomRegistry.make(); - const first = command.run(registry, "same"); - const second = command.run(registry, "same"); - latch.openUnsafe(); + const first = yield* start(command.run(registry, "same")); + const second = yield* start(command.run(registry, "same")); + yield* started.await; + yield* Fiber.interrupt(first); + expect({ executions, stopped }).toEqual({ executions: 1, stopped: false }); - expect(await first).toMatchObject({ _tag: "Success", value: "done", waiting: false }); - expect(await second).toMatchObject({ _tag: "Success", value: "done", waiting: false }); - expect(executions).toBe(1); - registry.dispose(); - }); + yield* Fiber.interrupt(second); + expect(stopped).toBe(true); + registry.dispose(); + }), + ); - it("coalesces pending latest-value commands without interrupting the active call", async () => { - const firstLatch = Latch.makeUnsafe(); - const executed: number[] = []; - const runtime = Atom.runtime(Layer.empty); - const command = createRuntimeCommand(runtime, { - label: "test.latest", - concurrency: { mode: "latest", key: () => "shared" }, - execute: (value: number) => - Effect.sync(() => executed.push(value)).pipe( - Effect.andThen(value === 1 ? firstLatch.await : Effect.void), - Effect.as(value), - ), - }); - const registry = AtomRegistry.make(); + it.effect("gives every single-flight caller the shared result", () => + Effect.gen(function* () { + const latch = Latch.makeUnsafe(); + let executions = 0; + const command = createRuntimeCommand(Atom.runtime(Layer.empty), { + label: "test.single-flight", + concurrency: { mode: "singleFlight", key: (key: string) => key }, + execute: () => + Effect.sync(() => executions++).pipe(Effect.andThen(latch.await), Effect.as("done")), + }); + const registry = AtomRegistry.make(); - const first = command.run(registry, 1); - await Promise.resolve(); - const second = command.run(registry, 2); - const third = command.run(registry, 3); - firstLatch.openUnsafe(); + const first = yield* start(command.run(registry, "same")); + const second = yield* start(command.run(registry, "same")); + latch.openUnsafe(); - expect(await first).toMatchObject({ _tag: "Success", value: 1, waiting: false }); - expect(await second).toMatchObject({ _tag: "Success", value: 3, waiting: false }); - expect(await third).toMatchObject({ _tag: "Success", value: 3, waiting: false }); - expect(executed).toEqual([1, 3]); - registry.dispose(); - }); + expect(yield* Fiber.join(first)).toEqual(Exit.succeed("done")); + expect(yield* Fiber.join(second)).toEqual(Exit.succeed("done")); + expect(executions).toBe(1); + registry.dispose(); + }), + ); + + it.effect("coalesces queued latest-value commands, and drops one nobody waits for", () => + Effect.gen(function* () { + const firstStarted = Latch.makeUnsafe(); + const firstLatch = Latch.makeUnsafe(); + const executed: number[] = []; + const command = createRuntimeCommand(Atom.runtime(Layer.empty), { + label: "test.latest", + concurrency: { mode: "latest", key: () => "shared" }, + execute: (value: number) => + Effect.sync(() => { + executed.push(value); + firstStarted.openUnsafe(); + }).pipe(Effect.andThen(value === 1 ? firstLatch.await : Effect.void), Effect.as(value)), + }); + const registry = AtomRegistry.make(); + + const first = yield* start(command.run(registry, 1)); + yield* firstStarted.await; + const second = yield* start(command.run(registry, 2)); + const third = yield* start(command.run(registry, 3)); + firstLatch.openUnsafe(); + + expect(yield* Fiber.join(first)).toEqual(Exit.succeed(1)); + expect(yield* Fiber.join(second)).toEqual(Exit.succeed(3)); + expect(yield* Fiber.join(third)).toEqual(Exit.succeed(3)); + expect(executed).toEqual([1, 3]); + + firstLatch.closeUnsafe(); + const running = yield* start(command.run(registry, 1)); + const abandoned = yield* start(command.run(registry, 4)); + yield* Fiber.interrupt(abandoned); + firstLatch.openUnsafe(); + yield* Fiber.join(running); + expect(executed).toEqual([1, 3, 1]); + registry.dispose(); + }), + ); }); describe("persisted environment queries", () => { diff --git a/packages/client-runtime/src/state/runtime.ts b/packages/client-runtime/src/state/runtime.ts index ac55aba2da28c..7740f126b865d 100644 --- a/packages/client-runtime/src/state/runtime.ts +++ b/packages/client-runtime/src/state/runtime.ts @@ -11,10 +11,13 @@ import { type EnvironmentId as EnvironmentIdType, } from "@t3tools/contracts"; import * as Cause from "effect/Cause"; +import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; -import * as Exit from "effect/Exit"; +import type * as Exit from "effect/Exit"; +import * as Fiber from "effect/Fiber"; import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; +import * as Semaphore from "effect/Semaphore"; import * as Stream from "effect/Stream"; import * as SubscriptionRef from "effect/SubscriptionRef"; import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity"; @@ -140,6 +143,8 @@ export interface AtomCommandOptions { readonly label?: string; readonly reportFailure?: boolean; readonly reportDefect?: boolean; + /** Aborting interrupts the run. */ + readonly signal?: AbortSignal | undefined; } export interface AtomCommandReporter { @@ -149,7 +154,11 @@ export interface AtomCommandReporter { export interface AtomCommand { readonly label: string; - readonly run: (registry: AtomRegistry.AtomRegistry, input: W) => Promise>; + /** + * Runs on the calling fiber, so interrupting the caller stops the command. Code outside + * Effect starts it with `runAtomCommand`. + */ + readonly run: (registry: AtomRegistry.AtomRegistry, input: W) => Effect.Effect; } export type AtomCommandConcurrency = @@ -159,194 +168,220 @@ export type AtomCommandConcurrency = readonly key: (input: W) => string; }; -interface AtomCommandSchedulerState { - readonly serial: Map>; - readonly singleFlight: Map>; - readonly latest: Map; +/** One run that several callers wait on. It is interrupted once the last of them stops waiting. */ +interface SharedRun { + readonly result: Deferred.Deferred; + waiters: number; + fiber: Fiber.Fiber | undefined; } -interface AtomCommandLatestBatch { - execute: () => Promise>; - readonly resolve: Array<(result: AtomCommandResult) => void>; +interface AtomCommandLatestLane { + pending: (SharedRun & { start: Effect.Effect }) | undefined; } -interface AtomCommandLatestLane { - running: boolean; - pending: AtomCommandLatestBatch | undefined; +interface AtomCommandSchedulerState { + readonly serial: Map; + readonly singleFlight: Map; + readonly latest: Map; } export interface AtomCommandScheduler { - readonly schedule: ( + readonly schedule: ( registry: AtomRegistry.AtomRegistry, concurrency: AtomCommandConcurrency, input: W, - execute: () => Promise>, - ) => Promise>; + effect: Effect.Effect, + ) => Effect.Effect; } -async function settleAtomCommandResult( - execute: () => Promise>, -): Promise> { - try { - return await execute(); - } catch (defect) { - return AsyncResult.failure(Cause.die(defect)); - } -} +const startSharedRun = (run: SharedRun, effect: Effect.Effect) => + effect.pipe( + Effect.interruptible, + Effect.onExit((exit) => Deferred.done(run.result, exit)), + Effect.ignoreCause, + Effect.forkDetach({ startImmediately: true }), + Effect.map((fiber) => { + run.fiber = fiber; + }), + ); + +const awaitSharedRun = ( + run: SharedRun, + restore: (effect: Effect.Effect) => Effect.Effect, + abandon: Effect.Effect, +): Effect.Effect => { + run.waiters++; + return restore(Deferred.await(run.result as Deferred.Deferred)).pipe( + Effect.onInterrupt(() => (--run.waiters === 0 ? abandon : Effect.void)), + ); +}; + +const interruptSharedRun = (run: SharedRun) => + run.fiber === undefined ? Effect.void : Fiber.interrupt(run.fiber); export function createAtomCommandScheduler(): AtomCommandScheduler { const registryStates = new WeakMap(); - - const stateFor = (registry: AtomRegistry.AtomRegistry): AtomCommandSchedulerState => { - const existing = registryStates.get(registry); - if (existing !== undefined) { - return existing; + const stateFor = (registry: AtomRegistry.AtomRegistry) => { + let state = registryStates.get(registry); + if (state === undefined) { + state = { serial: new Map(), singleFlight: new Map(), latest: new Map() }; + registryStates.set(registry, state); } - const state: AtomCommandSchedulerState = { - serial: new Map(), - singleFlight: new Map(), - latest: new Map(), - }; - registryStates.set(registry, state); return state; }; - return { - schedule: ( - registry: AtomRegistry.AtomRegistry, - concurrency: AtomCommandConcurrency, - input: W, - execute: () => Promise>, - ): Promise> => { - if (concurrency.mode === "parallel") { - return execute(); - } + const serial = ( + lanes: AtomCommandSchedulerState["serial"], + key: string, + effect: Effect.Effect, + ) => + Effect.acquireUseRelease( + Effect.sync(() => { + const lane = lanes.get(key) ?? { semaphore: Semaphore.makeUnsafe(1), users: 0 }; + lanes.set(key, lane); + lane.users++; + return lane; + }), + (lane) => lane.semaphore.withPermit(effect), + (lane) => + Effect.sync(() => { + if (--lane.users === 0) lanes.delete(key); + }), + ); - const key = concurrency.key(input); - const state = stateFor(registry); - if (concurrency.mode === "singleFlight") { - const existing = state.singleFlight.get(key) as - | Promise> - | undefined; - if (existing !== undefined) { - return existing; + const singleFlight = ( + flights: AtomCommandSchedulerState["singleFlight"], + key: string, + effect: Effect.Effect, + ) => + Effect.uninterruptibleMask((restore) => + Effect.gen(function* () { + let flight = flights.get(key); + if (flight === undefined) { + const started: SharedRun = { + result: Deferred.makeUnsafe(), + waiters: 0, + fiber: undefined, + }; + flight = started; + flights.set(key, started); + const context = yield* Effect.context(); + yield* startSharedRun( + started, + effect.pipe( + Effect.provide(context), + Effect.ensuring( + Effect.sync(() => { + if (flights.get(key) === started) flights.delete(key); + }), + ), + ), + ); } - const current = execute(); - state.singleFlight.set(key, current); - void current.then( - () => { - if (state.singleFlight.get(key) === current) { - state.singleFlight.delete(key); - } - }, - () => { - if (state.singleFlight.get(key) === current) { - state.singleFlight.delete(key); - } - }, + const joined = flight; + return yield* awaitSharedRun( + joined, + restore, + Effect.suspend(() => { + // Left the map first, so a caller arriving during the interrupt starts a fresh run. + if (flights.get(key) === joined) flights.delete(key); + return interruptSharedRun(joined); + }), ); - return current; - } + }), + ); - if (concurrency.mode === "serial") { - const previous = state.serial.get(key); - const current = previous === undefined ? execute() : previous.then(execute, execute); - state.serial.set(key, current); - void current.then( - () => { - if (state.serial.get(key) === current) { - state.serial.delete(key); - } - }, - () => { - if (state.serial.get(key) === current) { - state.serial.delete(key); + const latest = ( + lanes: AtomCommandSchedulerState["latest"], + key: string, + effect: Effect.Effect, + ) => + Effect.uninterruptibleMask((restore) => + Effect.gen(function* () { + const context = yield* Effect.context(); + const existing = lanes.get(key); + const lane = existing ?? { pending: undefined }; + lanes.set(key, lane); + // Callers that queue behind a run share the next one, which runs the newest of them. + const batch = lane.pending ?? { + result: Deferred.makeUnsafe(), + waiters: 0, + fiber: undefined, + start: Effect.void, + }; + batch.start = startSharedRun(batch, Effect.provide(effect, context)); + lane.pending = batch; + + if (existing === undefined) { + const drain: Effect.Effect = Effect.suspend(() => { + const next = lane.pending; + if (next === undefined) { + lanes.delete(key); + return Effect.void; } - }, - ); - return current; - } - - let lane = state.latest.get(key); - if (lane === undefined) { - lane = { running: false, pending: undefined }; - state.latest.set(key, lane); - } - const activeLane = lane; - - const result = new Promise>((resolve) => { - if (activeLane.pending === undefined) { - activeLane.pending = { - execute: execute as () => Promise>, - resolve: [resolve as (result: AtomCommandResult) => void], - }; - return; + lane.pending = undefined; + return next.start.pipe( + Effect.andThen(Deferred.await(next.result)), + Effect.exit, + Effect.andThen(drain), + ); + }); + yield* drain.pipe(Effect.forkDetach({ startImmediately: true })); } - activeLane.pending.execute = execute as () => Promise>; - activeLane.pending.resolve.push( - resolve as (result: AtomCommandResult) => void, + return yield* awaitSharedRun( + batch, + restore, + Effect.suspend(() => { + if (lane.pending === batch) lane.pending = undefined; + return interruptSharedRun(batch); + }), ); - }); + }), + ); - if (!activeLane.running) { - activeLane.running = true; - void (async () => { - while (activeLane.pending !== undefined) { - const batch = activeLane.pending; - activeLane.pending = undefined; - let batchResult: AtomCommandResult; - try { - batchResult = await batch.execute(); - } catch (defect) { - batchResult = AsyncResult.failure(Cause.die(defect)); - } - for (const resolve of batch.resolve) { - resolve(batchResult); + return { + schedule: (registry, concurrency, input, effect) => + concurrency.mode === "parallel" + ? effect + : Effect.suspend(() => { + const key = concurrency.key(input); + const state = stateFor(registry); + switch (concurrency.mode) { + case "serial": + return serial(state.serial, key, effect); + case "singleFlight": + return singleFlight(state.singleFlight, key, effect); + case "latest": + return latest(state.latest, key, effect); } - } - activeLane.running = false; - if (state.latest.get(key) === activeLane) { - state.latest.delete(key); - } - })(); - } - - return result; - }, + }), }; } -export const scheduleAtomCommandEffect = - /* Every atom command passes through this scheduler; the command owns its tracing boundary. */ - Effect.fnUntraced(function* ( - registry: AtomRegistry.AtomRegistry, - scheduler: AtomCommandScheduler, - concurrency: AtomCommandConcurrency, - input: W, - effect: Effect.Effect, - ): Effect.fn.Return { - const context = yield* Effect.context(); - const result = yield* Effect.promise((signal) => - scheduler.schedule(registry, concurrency, input, async () => { - const exit = await Effect.runPromiseExitWith(context)(effect, { signal }); - return Exit.isSuccess(exit) - ? AsyncResult.success(exit.value) - : AsyncResult.failure(exit.cause); - }), - ); - return result._tag === "Success" ? result.value : yield* Effect.failCause(result.cause); +const settleAtEdge = ( + effect: Effect.Effect, + options: AtomCommandOptions, + reporter: AtomCommandReporter, +): Promise> => + Effect.runPromiseExit(effect, { signal: options.signal }).then((exit) => { + const result = AsyncResult.fromExit(exit); + reportAtomCommandResult(result, options, reporter); + return result; }); -export async function runAtomCommand( +/** Starts a command from outside Effect. Effect callers yield `command.run` instead. */ +export function runAtomCommand( registry: AtomRegistry.AtomRegistry, command: AtomCommand, input: W, options: AtomCommandOptions = {}, reporter: AtomCommandReporter = console, ): Promise> { - const result = await settleAtomCommandResult(() => command.run(registry, input)); - reportAtomCommandResult(result, { ...options, label: options.label ?? command.label }, reporter); - return result; + return settleAtEdge( + Effect.suspend(() => command.run(registry, input)), + { ...options, label: options.label ?? command.label }, + reporter, + ); } export function mapAtomCommandResult( @@ -378,16 +413,6 @@ export async function settleAsyncResult( } } -async function executeAtomCommand( - execute: () => Promise>, - options: AtomCommandOptions = {}, - reporter: AtomCommandReporter = console, -): Promise> { - const result = await settleAsyncResult(execute); - reportAtomCommandResult(result, options, reporter); - return result; -} - export interface AtomQueryOptions extends AtomCommandOptions { /** * Force a fresh execution instead of accepting a value the atom already @@ -395,16 +420,18 @@ export interface AtomQueryOptions extends AtomCommandOptions { * verification flows where a cached failure must not satisfy a retry. */ readonly refresh?: boolean; - readonly signal?: AbortSignal; } -export async function executeAtomQuery( +/** + * A query atom's settled value. The atom stays mounted while the caller waits, and + * interrupting the caller releases it. + */ +export const awaitAtomResult = ( registry: AtomRegistry.AtomRegistry, atom: Atom.Atom>, - options: AtomQueryOptions = {}, - reporter: AtomCommandReporter = console, -): Promise> { - const query = Effect.scoped( + options: Pick = {}, +): Effect.Effect => + Effect.scoped( Effect.gen(function* () { yield* AtomRegistry.mount(registry, atom); if (options.refresh) { @@ -420,13 +447,28 @@ export async function executeAtomQuery( }); }), ); - return executeAtomCommand( - () => Effect.runPromiseExit(query, { signal: options.signal }), - options, - reporter, - ); + +/** Reads a query atom from outside Effect. Effect callers yield `awaitAtomResult` instead. */ +export function executeAtomQuery( + registry: AtomRegistry.AtomRegistry, + atom: Atom.Atom>, + options: AtomQueryOptions = {}, + reporter: AtomCommandReporter = console, +): Promise> { + return settleAtEdge(awaitAtomResult(registry, atom, options), options, reporter); } +/** Runs an effect on the calling fiber with the services of an atom runtime. */ +export const provideAtomRuntime = + (registry: AtomRegistry.AtomRegistry, runtime: Atom.AtomRuntime) => + (effect: Effect.Effect): Effect.Effect => + Effect.scoped( + AtomRegistry.mount(registry, runtime).pipe( + Effect.andThen(AtomRegistry.getResult(registry, runtime)), + Effect.flatMap((context) => Effect.provide(effect, context)), + ), + ); + export function createRuntimeCommand( runtime: Atom.AtomRuntime, options: { @@ -441,13 +483,13 @@ export function createRuntimeCommand( return { label: options.label, run: (registry, input) => - settleAtomCommandResult(() => - scheduler.schedule(registry, concurrency, input, () => { - const atom = runtime - .atom(options.execute(input, registry)) - .pipe(Atom.withLabel(options.label)); - return executeAtomQuery(registry, atom, { reportDefect: false, reportFailure: false }); - }), + scheduler.schedule( + registry, + concurrency, + input, + Effect.suspend(() => options.execute(input, registry)).pipe( + provideAtomRuntime(registry, runtime), + ), ), }; } diff --git a/packages/client-runtime/src/state/server.test.ts b/packages/client-runtime/src/state/server.test.ts index e6ce1725cc15f..1778f91ebc764 100644 --- a/packages/client-runtime/src/state/server.test.ts +++ b/packages/client-runtime/src/state/server.test.ts @@ -72,6 +72,7 @@ import { waitForDesktopUpdateTarget, runDesktopCommitWithReconnectObserver, } from "./server.ts"; +import { runAtomCommand } from "./runtime.ts"; import { applyServerConfigProjection } from "./serverConfigProjection.ts"; const CONFIG = { @@ -350,10 +351,14 @@ describe("accepted server update recovery", () => { const registry = yield* Effect.acquireRelease(Effect.sync(AtomRegistry.make), (value) => Effect.sync(() => value.dispose()), ); - const pending = atoms.updateServer.run(registry, { - environmentId: TARGET.environmentId, - input: { targetVersion: "0.0.31" }, - }); + // The registry drops an unmounted atom's value while the update is still running. + yield* AtomRegistry.mount(registry, serverUpdateStateAtom(TARGET.environmentId)); + const pending = runAtomCommand( + registry, + atoms.updateServer, + { environmentId: TARGET.environmentId, input: { targetVersion: "0.0.31" } }, + { reportFailure: false, reportDefect: false }, + ); if (loss === "cancel") { yield* Fiber.interrupt(yield* Deferred.await(cancelFiber)); const cancelled = yield* Effect.promise(() => pending); @@ -1584,11 +1589,13 @@ describe("launcher update resume", () => { const updateStateAtom = serverUpdateStateAtom(TARGET.environmentId); yield* AtomRegistry.mount(registry, updateStateAtom); - yield* Effect.promise(() => - atoms.updateServer.run(registry, { - environmentId: TARGET.environmentId, - input: { targetVersion: "0.0.31" }, - }), + yield* Effect.promise((signal) => + runAtomCommand( + registry, + atoms.updateServer, + { environmentId: TARGET.environmentId, input: { targetVersion: "0.0.31" } }, + { reportFailure: false, reportDefect: false, signal }, + ), ).pipe(Effect.forkScoped); return { // The host saw its first call: the update request or a lifecycle subscription. @@ -1743,25 +1750,28 @@ describe("provider setup commands", () => { Effect.sync(() => registry.dispose()), ); const install = (instanceId: string) => - atoms.startProviderInstall.run(registry, { - environmentId: TARGET.environmentId, - input: { instanceId: ProviderInstanceId.make(instanceId) }, - }); + Effect.forkChild( + Effect.exit( + atoms.startProviderInstall.run(registry, { + environmentId: TARGET.environmentId, + input: { instanceId: ProviderInstanceId.make(instanceId) }, + }), + ), + { startImmediately: true }, + ); - const codex = install("codex"); + const codex = yield* install("codex"); expect(yield* Queue.take(requested)).toBe("codex"); - const duplicateCodex = install("codex"); - const antigravity = install("antigravity"); + const duplicateCodex = yield* install("codex"); + const antigravity = yield* install("antigravity"); yield* Deferred.succeed(release, undefined); - expect(yield* Effect.promise(() => codex)).toMatchObject({ + expect(yield* Fiber.join(codex)).toMatchObject({ _tag: "Success", value: { driver: "codex" }, }); - expect(yield* Effect.promise(() => duplicateCodex)).toEqual( - yield* Effect.promise(() => codex), - ); - expect(yield* Effect.promise(() => antigravity)).toMatchObject({ + expect(yield* Fiber.join(duplicateCodex)).toEqual(yield* Fiber.join(codex)); + expect(yield* Fiber.join(antigravity)).toMatchObject({ _tag: "Success", value: { driver: "antigravity" }, }); @@ -1811,22 +1821,28 @@ describe("provider setup commands", () => { Effect.sync(() => registry.dispose()), ); - void atoms.updateProvider.run(registry, { - environmentId: TARGET.environmentId, - input: { provider: ProviderDriverKind.make("opencode") }, - }); + yield* Effect.forkChild( + atoms.updateProvider.run(registry, { + environmentId: TARGET.environmentId, + input: { provider: ProviderDriverKind.make("opencode") }, + }), + { startImmediately: true }, + ); yield* Deferred.await(updateStarted); - void atoms.mutateProviderInstance.run(registry, { - environmentId: TARGET.environmentId, - input: { - patch: {}, - providerInstanceMutation: { - operation: "upsert", - instanceId: ProviderInstanceId.make("codex"), - instance: { driver: ProviderDriverKind.make("codex"), enabled: false }, + yield* Effect.forkChild( + atoms.mutateProviderInstance.run(registry, { + environmentId: TARGET.environmentId, + input: { + patch: {}, + providerInstanceMutation: { + operation: "upsert", + instanceId: ProviderInstanceId.make("codex"), + instance: { driver: ProviderDriverKind.make("codex"), enabled: false }, + }, }, - }, - }); + }), + { startImmediately: true }, + ); const saved = yield* Deferred.await(settingsSaved).pipe( Effect.as(true), diff --git a/packages/client-runtime/src/state/server.ts b/packages/client-runtime/src/state/server.ts index cb02405722fe0..8cf0be6f31705 100644 --- a/packages/client-runtime/src/state/server.ts +++ b/packages/client-runtime/src/state/server.ts @@ -43,7 +43,6 @@ import { createEnvironmentRpcSubscriptionAtomFamily, createEnvironmentSubscriptionAtomFamily, createRuntimeCommand, - scheduleAtomCommandEffect, } from "./runtime.ts"; import * as EnvironmentRegistry from "../connection/registry.ts"; import * as EnvironmentSupervisor from "../connection/supervisor.ts"; @@ -1068,9 +1067,8 @@ export function createServerEnvironmentAtoms( Effect.andThen(Deferred.succeed(desktopReconnected, undefined)), Effect.forkChild, ); - const result = yield* scheduleAtomCommandEffect( + const result = yield* configScheduler.schedule( atomRegistry, - configScheduler, configConcurrency, target, Effect.gen(function* () { diff --git a/packages/client-runtime/src/state/terminal.test.ts b/packages/client-runtime/src/state/terminal.test.ts index 5c194c043983e..cc21cb5fe84bc 100644 --- a/packages/client-runtime/src/state/terminal.test.ts +++ b/packages/client-runtime/src/state/terminal.test.ts @@ -6,7 +6,7 @@ import { type TerminalWriteInput, type TerminalCloseInput, } from "@t3tools/contracts"; -import * as Cause from "effect/Cause"; +import * as Effect from "effect/Effect"; import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity"; import { expect, it } from "vite-plus/test"; @@ -104,15 +104,19 @@ function setup( const command = (name: string) => ({ label: name, run: (_registry: AtomRegistry.AtomRegistry, value: { readonly input: CommandInput }) => { - const result = (async () => { + const settled = Promise.withResolvers(); + pending.push(settled.promise); + return Effect.promise(async () => { calls.push({ command: name, input: value.input }); if (options.beforeCommand) await options.beforeCommand(name, value.input); - return name === "resize" && options.resizeFailure?.() - ? AsyncResult.failure(Cause.fail("resize rejected")) - : AsyncResult.success(undefined); - })(); - pending.push(result); - return result; + }).pipe( + Effect.flatMap(() => + name === "resize" && options.resizeFailure?.() + ? Effect.fail("resize rejected") + : Effect.void, + ), + Effect.ensuring(Effect.sync(settled.resolve)), + ); }, }); const write = command("write"); diff --git a/packages/client-runtime/src/state/threadCommands.test.ts b/packages/client-runtime/src/state/threadCommands.test.ts index 031ef68a14502..c01450353457e 100644 --- a/packages/client-runtime/src/state/threadCommands.test.ts +++ b/packages/client-runtime/src/state/threadCommands.test.ts @@ -188,38 +188,53 @@ describe("history loading", () => { ), }); yield* Effect.addFinalizer(() => Deferred.succeed(historyReply, { _tag: "loaded" })); - const history = h.commands.loadEarlierHistory.run(h.registry, { - environmentId: ENVIRONMENT_ID, - input: { threadId: THREAD_ID }, - }); + const history = yield* Effect.forkChild( + Effect.exit( + h.commands.loadEarlierHistory.run(h.registry, { + environmentId: ENVIRONMENT_ID, + input: { threadId: THREAD_ID }, + }), + ), + { startImmediately: true }, + ); yield* Deferred.await(historyStarted); - const send = h.commands.startTurn.run(h.registry, { - environmentId: ENVIRONMENT_ID, - input: { - threadId: THREAD_ID, - message: { - messageId: MessageId.make("message"), - role: "user", - text: "Send while history loads", - attachments: [], - }, - runtimeMode: "full-access", - interactionMode: "default", - dispatchMode: "start", - }, - }); + const send = yield* Effect.forkChild( + Effect.exit( + h.commands.startTurn.run(h.registry, { + environmentId: ENVIRONMENT_ID, + input: { + threadId: THREAD_ID, + message: { + messageId: MessageId.make("message"), + role: "user", + text: "Send while history loads", + attachments: [], + }, + runtimeMode: "full-access", + interactionMode: "default", + dispatchMode: "start", + }, + }), + ), + { startImmediately: true }, + ); // Dispatched after Send on another thread, so it arrives first only if Send is queued. const controlThreadId = ThreadId.make("control-thread"); - const control = h.commands.interruptTurn.run(h.registry, { - environmentId: ENVIRONMENT_ID, - input: { threadId: controlThreadId, runId: RunId.make("control-run") }, - }); + const control = yield* Effect.forkChild( + Effect.exit( + h.commands.interruptTurn.run(h.registry, { + environmentId: ENVIRONMENT_ID, + input: { threadId: controlThreadId, runId: RunId.make("control-run") }, + }), + ), + { startImmediately: true }, + ); const first = yield* Queue.take(h.requests); yield* Deferred.succeed(first.reply, { sequence: 1 }); yield* Deferred.succeed(historyReply, { _tag: "loaded" }); const second = yield* Queue.take(h.requests); yield* Deferred.succeed(second.reply, { sequence: 2 }); - const results = yield* Effect.promise(() => Promise.all([history, send, control])); + const results = yield* Fiber.joinAll([history, send, control]); expect(first.command).toMatchObject({ type: "message.dispatch", threadId: THREAD_ID }); expect(second.command).toMatchObject({ type: "run.interrupt", threadId: controlThreadId }); @@ -233,14 +248,19 @@ describe("interrupt turn", () => { it.effect("reconciles pending work when the server rejects the interrupt", () => Effect.gen(function* () { const h = yield* makeHarness(); - const result = h.commands.interruptTurn.run(h.registry, { - environmentId: ENVIRONMENT_ID, - input: { threadId: THREAD_ID, runId: RunId.make("finished-run") }, - }); + const result = yield* Effect.forkChild( + Effect.exit( + h.commands.interruptTurn.run(h.registry, { + environmentId: ENVIRONMENT_ID, + input: { threadId: THREAD_ID, runId: RunId.make("finished-run") }, + }), + ), + { startImmediately: true }, + ); const request = yield* Queue.take(h.requests); expect(request.command.type).toBe("run.interrupt"); yield* Deferred.fail(request.reply, new Error("Run is not interruptible")); - expect((yield* Effect.promise(() => result))._tag).toBe("Failure"); + expect((yield* Fiber.join(result))._tag).toBe("Failure"); expect(yield* Queue.take(h.reconciled)).toBe(THREAD_ID); }), ); @@ -257,10 +277,15 @@ describe("interrupt turn", () => { Effect.flatMap(Fiber.join), ), }); - const result = h.commands.interruptTurn.run(h.registry, { - environmentId: ENVIRONMENT_ID, - input: { threadId: THREAD_ID, runId: RunId.make("running-run") }, - }); + const result = yield* Effect.forkChild( + Effect.exit( + h.commands.interruptTurn.run(h.registry, { + environmentId: ENVIRONMENT_ID, + input: { threadId: THREAD_ID, runId: RunId.make("running-run") }, + }), + ), + { startImmediately: true }, + ); const request = yield* Queue.take(h.requests); yield* Deferred.succeed(request.reply, { sequence: 1 }); yield* Deferred.await(asked); @@ -270,7 +295,7 @@ describe("interrupt turn", () => { it.effect("resolves Stop without waiting for the pending work lookup", () => Effect.gen(function* () { const { threadScope, result } = yield* stopWithBlockedLookup(); - expect((yield* Effect.promise(() => result))._tag).toBe("Success"); + expect((yield* Fiber.join(result))._tag).toBe("Success"); yield* Scope.close(threadScope, Exit.void); }), ); @@ -279,7 +304,7 @@ describe("interrupt turn", () => { Effect.gen(function* () { const { threadScope, result } = yield* stopWithBlockedLookup(); yield* Scope.close(threadScope, Exit.void); - expect((yield* Effect.promise(() => result))._tag).toBe("Success"); + expect((yield* Fiber.join(result))._tag).toBe("Success"); }), ); }); @@ -298,7 +323,10 @@ describe("title regeneration", () => { }; h.registry.set(source, null); - const result = h.commands.regenerateTitle.run(h.registry, target); + const result = yield* Effect.forkChild( + Effect.exit(h.commands.regenerateTitle.run(h.registry, target)), + { startImmediately: true }, + ); const request = yield* Queue.take(h.requests); const requestId = request.command.commandId; yield* Deferred.succeed(request.reply, { sequence: 2 }); @@ -332,13 +360,16 @@ describe("title regeneration", () => { }, ], }); - const outcome = yield* Effect.promise(() => result); + const outcome = yield* Fiber.join(result); expect(outcome).toMatchObject({ _tag: "Success", value: { status: "failed", message: "model unavailable" }, }); - const superseded = h.commands.regenerateTitle.run(h.registry, target); + const superseded = yield* Effect.forkChild( + Effect.exit(h.commands.regenerateTitle.run(h.registry, target)), + { startImmediately: true }, + ); const second = yield* Queue.take(h.requests); h.registry.set(source, { ...SNAPSHOT, @@ -346,7 +377,7 @@ describe("title regeneration", () => { threads: [{ ...thread, titleRegeneration: null, lastTitleRegeneration: earlier }], }); yield* Deferred.succeed(second.reply, { sequence: 4 }); - expect(yield* Effect.promise(() => superseded)).toMatchObject({ + expect(yield* Fiber.join(superseded)).toMatchObject({ _tag: "Success", value: null, }); @@ -356,17 +387,22 @@ describe("title regeneration", () => { it.effect("settles without an outcome when the environment disconnects while waiting", () => Effect.gen(function* () { const h = yield* makeHarness(); - const result = h.commands.regenerateTitle.run(h.registry, { - environmentId: ENVIRONMENT_ID, - input: { threadId: THREAD_ID }, - }); + const result = yield* Effect.forkChild( + Effect.exit( + h.commands.regenerateTitle.run(h.registry, { + environmentId: ENVIRONMENT_ID, + input: { threadId: THREAD_ID }, + }), + ), + { startImmediately: true }, + ); const request = yield* Queue.take(h.requests); yield* Deferred.succeed(request.reply, { sequence: 2 }); yield* SubscriptionRef.update(h.connection, (state) => ({ ...state, phase: "backoff" as const, })); - expect(yield* Effect.promise(() => result)).toMatchObject({ _tag: "Success", value: null }); + expect(yield* Fiber.join(result)).toMatchObject({ _tag: "Success", value: null }); }), ); }); @@ -408,23 +444,28 @@ describe("remote thread lifecycle commands", () => { ], }; h.registry.set(source, initial); - const result = h.commands[action].run(h.registry, { - environmentId: ENVIRONMENT_ID, - input: { - threadId: THREAD_ID, - commandId: CommandId.make(action), - reason: "user", - enabled: false, - orderKey: "a", - snoozedUntil: "2099-01-01T00:00:00.000Z", - ...input, - }, - }); + const result = yield* Effect.forkChild( + Effect.exit( + h.commands[action].run(h.registry, { + environmentId: ENVIRONMENT_ID, + input: { + threadId: THREAD_ID, + commandId: CommandId.make(action), + reason: "user", + enabled: false, + orderKey: "a", + snoozedUntil: "2099-01-01T00:00:00.000Z", + ...input, + }, + }), + ), + { startImmediately: true }, + ); expect(h.registry.get(h.visibleAtom)?.threads[0]).toMatchObject(expected); const request = yield* Queue.take(h.requests); expect(h.registry.get(source)).toBe(initial); yield* Deferred.fail(request.reply, new Error("Remote rejected the action")); - expect((yield* Effect.promise(() => result))._tag).toBe("Failure"); + expect((yield* Fiber.join(result))._tag).toBe("Failure"); expect(h.registry.get(h.visibleAtom)).toBe(initial); }), ); @@ -437,30 +478,40 @@ describe("remote thread lifecycle commands", () => { ...SNAPSHOT, threads: [{ ...SNAPSHOT.threads[0]!, snoozedUntil: FUTURE, snoozedAt: earlierSnoozedAt }], }); - const result = h.commands.snooze.run(h.registry, { - environmentId: ENVIRONMENT_ID, - input: { threadId: THREAD_ID, snoozedUntil: DateTime.formatIso(FUTURE) }, - }); + const result = yield* Effect.forkChild( + Effect.exit( + h.commands.snooze.run(h.registry, { + environmentId: ENVIRONMENT_ID, + input: { threadId: THREAD_ID, snoozedUntil: DateTime.formatIso(FUTURE) }, + }), + ), + { startImmediately: true }, + ); const snoozedAt = h.registry.get(h.visibleAtom)?.threads[0]?.snoozedAt; expect(DateTime.toEpochMillis(snoozedAt!)).toBeGreaterThan( DateTime.toEpochMillis(earlierSnoozedAt), ); const request = yield* Queue.take(h.requests); yield* Deferred.succeed(request.reply, { sequence: 2 }); - expect((yield* Effect.promise(() => result))._tag).toBe("Success"); + expect((yield* Fiber.join(result))._tag).toBe("Success"); }), ); it.effect("keeps the preview after acknowledgement until the matching shell update arrives", () => Effect.gen(function* () { const h = yield* makeHarness(); - const result = h.commands.settle.run(h.registry, { - environmentId: ENVIRONMENT_ID, - input: { threadId: THREAD_ID }, - }); + const result = yield* Effect.forkChild( + Effect.exit( + h.commands.settle.run(h.registry, { + environmentId: ENVIRONMENT_ID, + input: { threadId: THREAD_ID }, + }), + ), + { startImmediately: true }, + ); const request = yield* Queue.take(h.requests); yield* Deferred.succeed(request.reply, { sequence: 3 }); - expect((yield* Effect.promise(() => result))._tag).toBe("Success"); + expect((yield* Fiber.join(result))._tag).toBe("Success"); const changed = { ...SNAPSHOT, snapshotSequence: 2, @@ -494,18 +545,28 @@ describe("remote thread lifecycle commands", () => { () => Effect.gen(function* () { const h = yield* makeHarness(); - const settle = h.commands.settle.run(h.registry, { - environmentId: ENVIRONMENT_ID, - input: { threadId: THREAD_ID }, - }); + const settle = yield* Effect.forkChild( + Effect.exit( + h.commands.settle.run(h.registry, { + environmentId: ENVIRONMENT_ID, + input: { threadId: THREAD_ID }, + }), + ), + { startImmediately: true }, + ); const first = yield* Queue.take(h.requests); - const unsettle = h.commands.unsettle.run(h.registry, { - environmentId: ENVIRONMENT_ID, - input: { threadId: THREAD_ID, reason: "user" }, - }); + const unsettle = yield* Effect.forkChild( + Effect.exit( + h.commands.unsettle.run(h.registry, { + environmentId: ENVIRONMENT_ID, + input: { threadId: THREAD_ID, reason: "user" }, + }), + ), + { startImmediately: true }, + ); expect(h.registry.get(h.visibleAtom)?.threads[0]?.settledOverride).toBe("active"); yield* Deferred.fail(first.reply, new Error("Settle rejected")); - yield* Effect.promise(() => settle); + yield* Fiber.join(settle); expect(h.registry.get(h.visibleAtom)?.threads[0]?.settledOverride).toBe("active"); const second = yield* Queue.take(h.requests); expect(second.command.type).toBe("thread.unsettle"); @@ -516,7 +577,7 @@ describe("remote thread lifecycle commands", () => { }; h.registry.set(h.snapshotAtom(ENVIRONMENT_ID), confirmed); yield* Deferred.succeed(second.reply, { sequence: 2 }); - yield* Effect.promise(() => unsettle); + yield* Fiber.join(unsettle); expect(h.registry.get(h.visibleAtom)).toBe(confirmed); }), ); @@ -525,10 +586,15 @@ describe("remote thread lifecycle commands", () => { Effect.gen(function* () { const h = yield* makeHarness(); const otherEnvironment = EnvironmentId.make("other-remote"); - const result = h.commands.settle.run(h.registry, { - environmentId: ENVIRONMENT_ID, - input: { threadId: THREAD_ID }, - }); + const result = yield* Effect.forkChild( + Effect.exit( + h.commands.settle.run(h.registry, { + environmentId: ENVIRONMENT_ID, + input: { threadId: THREAD_ID }, + }), + ), + { startImmediately: true }, + ); const request = yield* Queue.take(h.requests); expect(h.registry.get(h.commands.snapshotAtom(otherEnvironment))).toBe(SNAPSHOT); expect(h.registry.get(h.commands.rowActionsAtom(ENVIRONMENT_ID))).toBe(1); @@ -537,7 +603,7 @@ describe("remote thread lifecycle commands", () => { h.registry.set(h.snapshotAtom(ENVIRONMENT_ID), removed); expect(h.registry.get(h.visibleAtom)?.threads).toEqual([]); yield* Deferred.fail(request.reply, new Error("Thread removed")); - yield* Effect.promise(() => result); + yield* Fiber.join(result); expect(h.registry.get(h.visibleAtom)).toBe(removed); }), ); @@ -550,18 +616,28 @@ describe("remote thread lifecycle commands", () => { const parked = action === "settle" ? { settledOverride: "settled" as const } : { snoozedUntil: FUTURE }; const awake = action === "settle" ? { settledOverride: "active" } : { snoozedUntil: null }; - const result = h.commands[action].run(h.registry, { - environmentId: ENVIRONMENT_ID, - input: { threadId: THREAD_ID, snoozedUntil: "2099-01-01T00:00:00.000Z" }, - }); + const result = yield* Effect.forkChild( + Effect.exit( + h.commands[action].run(h.registry, { + environmentId: ENVIRONMENT_ID, + input: { threadId: THREAD_ID, snoozedUntil: "2099-01-01T00:00:00.000Z" }, + }), + ), + { startImmediately: true }, + ); const first = yield* Queue.take(h.requests); - const undo = h.commands[action === "settle" ? "unsettle" : "unsnooze"].run(h.registry, { - environmentId: ENVIRONMENT_ID, - input: { threadId: THREAD_ID, reason: "user" }, - }); + const undo = yield* Effect.forkChild( + Effect.exit( + h.commands[action === "settle" ? "unsettle" : "unsnooze"].run(h.registry, { + environmentId: ENVIRONMENT_ID, + input: { threadId: THREAD_ID, reason: "user" }, + }), + ), + { startImmediately: true }, + ); expect(h.registry.get(h.visibleAtom)?.threads[0]).toMatchObject(awake); yield* Deferred.succeed(first.reply, { sequence: 2 }); - expect((yield* Effect.promise(() => result))._tag).toBe("Success"); + expect((yield* Fiber.join(result))._tag).toBe("Success"); expect(h.registry.get(h.visibleAtom)?.threads[0]).toMatchObject(awake); const confirmed = { ...SNAPSHOT, @@ -573,7 +649,7 @@ describe("remote thread lifecycle commands", () => { const second = yield* Queue.take(h.requests); expect(second.command.type).toBe(action === "settle" ? "thread.unsettle" : "thread.unsnooze"); yield* Deferred.fail(second.reply, new Error("Undo rejected")); - expect((yield* Effect.promise(() => undo))._tag).toBe("Failure"); + expect((yield* Fiber.join(undo))._tag).toBe("Failure"); expect(h.registry.get(h.visibleAtom)).toBe(confirmed); }), ); @@ -583,10 +659,15 @@ describe("remote thread lifecycle commands", () => { (action) => Effect.gen(function* () { const h = yield* makeHarness(); - const result = h.commands[action].run(h.registry, { - environmentId: ENVIRONMENT_ID, - input: { threadId: THREAD_ID, snoozedUntil: "2099-01-01T00:00:00.000Z" }, - }); + const result = yield* Effect.forkChild( + Effect.exit( + h.commands[action].run(h.registry, { + environmentId: ENVIRONMENT_ID, + input: { threadId: THREAD_ID, snoozedUntil: "2099-01-01T00:00:00.000Z" }, + }), + ), + { startImmediately: true }, + ); const request = yield* Queue.take(h.requests); const newer = { ...SNAPSHOT, @@ -596,7 +677,7 @@ describe("remote thread lifecycle commands", () => { h.registry.set(h.snapshotAtom(ENVIRONMENT_ID), newer); expect(h.registry.get(h.visibleAtom)?.threads[0]).toBe(newer.threads[0]); yield* Deferred.succeed(request.reply, { sequence: 2 }); - expect((yield* Effect.promise(() => result))._tag).toBe("Success"); + expect((yield* Fiber.join(result))._tag).toBe("Success"); expect(h.registry.get(h.visibleAtom)).toBe(newer); }), ); @@ -611,10 +692,15 @@ describe("remote thread lifecycle commands", () => { threads: [{ ...SNAPSHOT.threads[0]!, pendingRuntimeRequest: USER_INPUT }], }; h.registry.set(h.snapshotAtom(ENVIRONMENT_ID), stale); - const result = h.commands[action].run(h.registry, { - environmentId: ENVIRONMENT_ID, - input: { threadId: THREAD_ID, snoozedUntil: "2099-01-01T00:00:00.000Z" }, - }); + const result = yield* Effect.forkChild( + Effect.exit( + h.commands[action].run(h.registry, { + environmentId: ENVIRONMENT_ID, + input: { threadId: THREAD_ID, snoozedUntil: "2099-01-01T00:00:00.000Z" }, + }), + ), + { startImmediately: true }, + ); const request = yield* Queue.take(h.requests); if (action === "settle") { expect(h.registry.get(h.visibleAtom)?.threads[0]).toBe(stale.threads[0]); @@ -625,7 +711,7 @@ describe("remote thread lifecycle commands", () => { }); } yield* Deferred.succeed(request.reply, { sequence: 2 }); - expect((yield* Effect.promise(() => result))._tag).toBe("Success"); + expect((yield* Fiber.join(result))._tag).toBe("Success"); expect(h.registry.get(h.visibleAtom)?.threads[0]).toMatchObject( action === "settle" ? { settledOverride: "settled" } : { snoozedUntil: FUTURE }, ); @@ -650,10 +736,15 @@ describe("remote thread lifecycle commands", () => { ], }; h.registry.set(h.snapshotAtom(ENVIRONMENT_ID), initial); - const result = h.commands.snooze.run(h.registry, { - environmentId: ENVIRONMENT_ID, - input: { threadId: THREAD_ID, snoozedUntil: "2099-01-01T00:00:00.000Z" }, - }); + const result = yield* Effect.forkChild( + Effect.exit( + h.commands.snooze.run(h.registry, { + environmentId: ENVIRONMENT_ID, + input: { threadId: THREAD_ID, snoozedUntil: "2099-01-01T00:00:00.000Z" }, + }), + ), + { startImmediately: true }, + ); const request = yield* Queue.take(h.requests); const snoozed = h.registry.get(h.visibleAtom)?.threads[0]; expect(DateTime.toEpochMillis(snoozed!.snoozedAt!)).toBeGreaterThanOrEqual( @@ -661,7 +752,7 @@ describe("remote thread lifecycle commands", () => { ); expect(snoozed?.pendingRuntimeRequest).toEqual(USER_INPUT); yield* Deferred.succeed(request.reply, { sequence: 2 }); - expect((yield* Effect.promise(() => result))._tag).toBe("Success"); + expect((yield* Fiber.join(result))._tag).toBe("Success"); }), ); }); diff --git a/packages/client-runtime/src/state/threadCommands.ts b/packages/client-runtime/src/state/threadCommands.ts index 41b74e9f2ac78..9f2edf5cfad79 100644 --- a/packages/client-runtime/src/state/threadCommands.ts +++ b/packages/client-runtime/src/state/threadCommands.ts @@ -18,7 +18,6 @@ import { createEnvironmentCommand, createEnvironmentRpcCommand, environmentConnectionAtom, - mapAtomCommandResult, } from "./runtime.ts"; import { waitForTitleRegenerationOutcome } from "./threadTitleRegeneration.ts"; import { @@ -148,10 +147,11 @@ export function createThreadEnvironmentAtoms( command: AtomCommand, ): AtomCommand => ({ label: command.label, - run: (registry, target) => { - registry.update(rowActionsAtom(target.environmentId), (count) => count + 1); - return command.run(registry, target); - }, + run: (registry, target) => + Effect.suspend(() => { + registry.update(rowActionsAtom(target.environmentId), (count) => count + 1); + return command.run(registry, target); + }), }); const sent = { @@ -460,24 +460,22 @@ export function createThreadEnvironmentAtoms( ); const regenerateTitle = { label: commands.armTitleRegeneration.label, - run: async ( + run: ( registry: AtomRegistry.AtomRegistry, target: { readonly environmentId: EnvironmentId; readonly input: { threadId: ThreadId } }, - ) => { - const armed = await commands.armTitleRegeneration.run(registry, target); - const outcome = - armed._tag === "Success" - ? await waitForTitleRegenerationOutcome( - registry, - { - snapshot: snapshotAtom(target.environmentId), - disconnected: disconnectedAtom(target.environmentId), - }, - { threadId: target.input.threadId, ...armed.value }, - ) - : null; - return mapAtomCommandResult(armed, () => outcome); - }, + ) => + commands.armTitleRegeneration.run(registry, target).pipe( + Effect.flatMap((armed) => + waitForTitleRegenerationOutcome( + registry, + { + snapshot: snapshotAtom(target.environmentId), + disconnected: disconnectedAtom(target.environmentId), + }, + { threadId: target.input.threadId, ...armed }, + ), + ), + ), }; return { ...commands, diff --git a/packages/client-runtime/src/state/threadLifecycle.ts b/packages/client-runtime/src/state/threadLifecycle.ts index 7dc7bbf89c11c..55c27c8ef6a10 100644 --- a/packages/client-runtime/src/state/threadLifecycle.ts +++ b/packages/client-runtime/src/state/threadLifecycle.ts @@ -5,6 +5,8 @@ import type { ThreadId, } from "@t3tools/contracts"; import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; import { Atom } from "effect/reactivity"; import type { AtomCommand } from "./runtime.ts"; @@ -71,38 +73,39 @@ export function createOptimisticThreadLifecycle( ): typeof command { return { label: command.label, - run: async (registry, target) => { - const now = DateTime.nowUnsafe(); - const pending = pendingAtom(target.environmentId); - const source = sourceSnapshotAtom(target.environmentId); - const update: PendingThreadUpdate = { - threadId: target.input.threadId, - apply: (thread) => apply(thread, target.input, now, update.sequence !== undefined), - }; - const remove = () => - registry.update(pending, (current) => current.filter((item) => item !== update)); - registry.update(pending, (current) => [...current, update]); - let confirmed = false; - try { - const result = await command.run(registry, target); - if (result._tag === "Success") { - update.sequence = result.value.sequence; + run: (registry, target) => + Effect.suspend(() => { + const now = DateTime.nowUnsafe(); + const pending = pendingAtom(target.environmentId); + const source = sourceSnapshotAtom(target.environmentId); + const update: PendingThreadUpdate = { + threadId: target.input.threadId, + apply: (thread) => apply(thread, target.input, now, update.sequence !== undefined), + }; + const remove = () => + registry.update(pending, (current) => current.filter((item) => item !== update)); + // Stays applied after the reply until a snapshot at or past its sequence replaces it. + const confirm = (sequence: number) => { + update.sequence = sequence; registry.update(pending, (current) => [...current]); const reconcile = (snapshot: OrchestrationV2ShellSnapshot | null) => { - if (snapshot === null || snapshot.snapshotSequence >= result.value.sequence) { + if (snapshot === null || snapshot.snapshotSequence >= sequence) { remove(); unsubscribe(); } }; const unsubscribe = registry.subscribe(source, reconcile); reconcile(registry.get(source)); - confirmed = true; - } - return result; - } finally { - if (!confirmed) remove(); - } - }, + }; + registry.update(pending, (current) => [...current, update]); + return command + .run(registry, target) + .pipe( + Effect.onExit((exit) => + Effect.sync(() => (Exit.isSuccess(exit) ? confirm(exit.value.sequence) : remove())), + ), + ); + }), }; } diff --git a/packages/client-runtime/src/state/threadTitleRegeneration.ts b/packages/client-runtime/src/state/threadTitleRegeneration.ts index 07779dd779837..e863635988bf1 100644 --- a/packages/client-runtime/src/state/threadTitleRegeneration.ts +++ b/packages/client-runtime/src/state/threadTitleRegeneration.ts @@ -4,6 +4,7 @@ import type { ThreadId, ThreadTitleRegenerationOutcome, } from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; import type { Atom, AtomRegistry } from "effect/reactivity"; export interface TitleRegenerationRequest { @@ -40,27 +41,25 @@ export function waitForTitleRegenerationOutcome( registry: AtomRegistry.AtomRegistry, sources: TitleRegenerationSources, request: TitleRegenerationRequest, -): Promise { - return new Promise((resolve) => { - let settled = false; +): Effect.Effect { + return Effect.callback((resume) => { let unsubscribes: ReadonlyArray<() => void> = []; const release = () => { for (const unsubscribe of unsubscribes) unsubscribe(); + unsubscribes = []; }; const check = () => { - if (settled) return; let outcome = settledOutcome(registry.get(sources.snapshot), request); if (outcome === undefined && registry.get(sources.disconnected)) outcome = null; if (outcome === undefined) return; - settled = true; release(); - resolve(outcome); + resume(Effect.succeed(outcome)); }; unsubscribes = [ registry.subscribe(sources.snapshot, check), registry.subscribe(sources.disconnected, check), ]; - if (settled) release(); - else check(); + check(); + return Effect.sync(release); }); } diff --git a/packages/client-runtime/src/state/threadVisits.test.ts b/packages/client-runtime/src/state/threadVisits.test.ts index eefa16c6fbe7f..556ea683b7a46 100644 --- a/packages/client-runtime/src/state/threadVisits.test.ts +++ b/packages/client-runtime/src/state/threadVisits.test.ts @@ -1,10 +1,10 @@ import { EnvironmentId, ThreadId } from "@t3tools/contracts"; -import * as Cause from "effect/Cause"; -import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity"; +import * as Deferred from "effect/Deferred"; +import * as Effect from "effect/Effect"; +import { Atom, AtomRegistry } from "effect/reactivity"; import { expect, it, vi } from "vite-plus/test"; import type { VisitThreadInput } from "../operations/commands.ts"; -import type { AtomCommandResult } from "./runtime.ts"; import { claimThreadOpen } from "./threadSearch.ts"; import { createThreadVisitTracker, VISIT_DISPATCH_THROTTLE_MS } from "./threadVisits.ts"; @@ -35,7 +35,7 @@ function setup(threadName: string, initial: Omit const visits: Array = []; const localVisits: Array = []; let online = true; - let pendingResult: Promise> | undefined; + let pendingResult: Effect.Effect | undefined; const attempts: Array = []; const sessionGenerationAtom = Atom.make(1); const tracker = createThreadVisitTracker({ @@ -43,15 +43,16 @@ function setup(threadName: string, initial: Omit sessionGenerationAtom: () => sessionGenerationAtom, visit: { label: "test-visit", - run: async (_registry, value) => { - attempts.push(value.input); - const pending = pendingResult; - pendingResult = undefined; - if (online) visits.push(value.input); - if (pending) return pending; - if (!online) return AsyncResult.failure(Cause.fail("disconnected")); - return AsyncResult.success(undefined); - }, + run: (_registry, value) => + Effect.suspend(() => { + attempts.push(value.input); + const pending = pendingResult; + pendingResult = undefined; + if (online) visits.push(value.input); + if (pending) return pending; + if (!online) return Effect.fail("disconnected"); + return Effect.void; + }), }, markLocalVisit: (_ref, visitedAt) => localVisits.push(visitedAt), }); @@ -62,9 +63,9 @@ function setup(threadName: string, initial: Omit localVisits, attempts, deferNextVisit: () => { - const deferred = Promise.withResolvers>(); - pendingResult = deferred.promise; - return () => deferred.resolve(AsyncResult.failure(Cause.fail("disconnected"))); + const deferred = Deferred.makeUnsafe(); + pendingResult = Deferred.await(deferred); + return () => Deferred.doneUnsafe(deferred, Effect.fail("disconnected")); }, reconnect: () => registry.set(sessionGenerationAtom, registry.get(sessionGenerationAtom) + 1), mount: () => registry.mount(tracker(ref)), diff --git a/packages/client-runtime/src/state/usage.test.ts b/packages/client-runtime/src/state/usage.test.ts index 380e2de731b5d..0140688ae94dc 100644 --- a/packages/client-runtime/src/state/usage.test.ts +++ b/packages/client-runtime/src/state/usage.test.ts @@ -39,7 +39,7 @@ function harness(ids = ["a"], modelFilters: Record = { const environments = ids.map((id) => { const environmentId = EnvironmentId.make(id); const rates = Promise.withResolvers< - AsyncResult.Success | AsyncResult.Failure + AsyncResult.Success | AsyncResult.Failure >(); const scan = Promise.withResolvers(); const scanStarted = Promise.withResolvers(); @@ -78,7 +78,14 @@ function harness(ids = ["a"], modelFilters: Record = { run: ( _registry: AtomRegistry.AtomRegistry, { environmentId }: { environmentId: EnvironmentId }, - ) => get(environmentId).rates.promise, + ) => + Effect.promise(() => get(environmentId).rates.promise).pipe( + Effect.flatMap((result) => + AsyncResult.isSuccess(result) + ? Effect.succeed(result.value) + : Effect.failCause(result.cause), + ), + ), }, }, presentations: { diff --git a/packages/client-runtime/src/state/vcs.test.ts b/packages/client-runtime/src/state/vcs.test.ts index 6b15f8bc95db0..5626c8eef10eb 100644 --- a/packages/client-runtime/src/state/vcs.test.ts +++ b/packages/client-runtime/src/state/vcs.test.ts @@ -12,6 +12,7 @@ import { import { describe, expect, it } from "@effect/vitest"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; import * as Logger from "effect/Logger"; @@ -426,36 +427,36 @@ describe("cached VCS refs", () => { Effect.sync(() => registry.dispose()), ); - const result = yield* Effect.promise(() => + const result = yield* Effect.exit( atoms.pull.run(registry, { environmentId: TARGET.environmentId, input: { cwd: "/repo" }, }), ); - expect(AsyncResult.isFailure(result)).toBe(true); + expect(Exit.isFailure(result)).toBe(true); expect(yield* Ref.get(clears)).toBe(1); expect(registry.get(vcsRefsCacheStateAtom(TARGET)).revision).toBe(1); - const refreshResult = yield* Effect.promise(() => + const refreshResult = yield* Effect.exit( atoms.refreshStatus.run(registry, { environmentId: TARGET.environmentId, input: { cwd: "/repo" }, }), ); - expect(AsyncResult.isSuccess(refreshResult)).toBe(true); + expect(Exit.isSuccess(refreshResult)).toBe(true); expect(yield* Ref.get(clears)).toBe(2); expect(registry.get(vcsRefsCacheStateAtom(TARGET)).revision).toBe(2); - const prepareResult = yield* Effect.promise(() => + const prepareResult = yield* Effect.exit( createGitEnvironmentAtoms(runtime).preparePullRequestThread.run(registry, { environmentId: TARGET.environmentId, input: { cwd: "/repo", reference: "42", mode: "local" }, }), ); - expect(AsyncResult.isSuccess(prepareResult)).toBe(true); + expect(Exit.isSuccess(prepareResult)).toBe(true); expect(yield* Ref.get(clears)).toBe(3); expect(registry.get(vcsRefsCacheStateAtom(TARGET)).revision).toBe(3); }), @@ -502,21 +503,26 @@ describe("cached VCS refs", () => { ); const target = { environmentId: TARGET.environmentId, input: { cwd: "/repo" } }; - const refresh = atoms.refreshLocalStatusForPicker.run(registry, { - ...target, - input: { cwd: "/repo", localOnly: true }, - }); + const refresh = yield* Effect.forkChild( + Effect.exit( + atoms.refreshLocalStatusForPicker.run(registry, { + ...target, + input: { cwd: "/repo", localOnly: true }, + }), + ), + { startImmediately: true }, + ); yield* Deferred.await(refreshStarted); - const checkout = yield* Effect.promise(() => + const checkout = yield* Effect.exit( atoms.switchRef.run(registry, { ...target, input: { cwd: "/repo", refName: "feature" }, }), ); - expect(AsyncResult.isSuccess(checkout)).toBe(true); + expect(Exit.isSuccess(checkout)).toBe(true); yield* Deferred.succeed(releaseRefresh, undefined); - expect(AsyncResult.isSuccess(yield* Effect.promise(() => refresh))).toBe(true); + expect(Exit.isSuccess(yield* Fiber.join(refresh))).toBe(true); }), ); diff --git a/packages/client-runtime/src/state/vcsAction.test.ts b/packages/client-runtime/src/state/vcsAction.test.ts index 67e9253cba4f3..c9edd639bf6a3 100644 --- a/packages/client-runtime/src/state/vcsAction.test.ts +++ b/packages/client-runtime/src/state/vcsAction.test.ts @@ -30,7 +30,7 @@ import * as EnvironmentSupervisor from "../connection/supervisor.ts"; import * as Persistence from "../platform/persistence.ts"; import type { WsRpcProtocolClient } from "../rpc/protocol.ts"; import type { RpcSession } from "../rpc/session.ts"; -import type { AtomCommandResult } from "./runtime.ts"; +import { runAtomCommand, type AtomCommandResult } from "./runtime.ts"; import { applyVcsActionProgressEvent, beginVcsActionState, @@ -521,12 +521,17 @@ describe("vcsActionState", () => { const threadId = ThreadId.make("thread-stacked-action"); const projectId = ProjectId.make("project-stacked-action"); const successfulResult = yield* Effect.promise(() => - manager.runStackedAction(targetKey).run(registry, { - actionId: successfulActionId, - action, - threadId, - projectId, - }), + runAtomCommand( + registry, + manager.runStackedAction(targetKey), + { + actionId: successfulActionId, + action, + threadId, + projectId, + }, + { reportFailure: false, reportDefect: false }, + ), ); expect(AsyncResult.isSuccess(successfulResult)).toBe(true); @@ -538,10 +543,15 @@ describe("vcsActionState", () => { ]); const failedResult = yield* Effect.promise(() => - manager.runStackedAction(targetKey).run(registry, { - actionId: failedActionId, - action, - }), + runAtomCommand( + registry, + manager.runStackedAction(targetKey), + { + actionId: failedActionId, + action, + }, + { reportFailure: false, reportDefect: false }, + ), ); expect(AsyncResult.isFailure(failedResult)).toBe(true); @@ -555,10 +565,15 @@ describe("vcsActionState", () => { expect(removed).toEqual([`${environmentId}:*`, `${environmentId}:*`]); const interruptedResult = yield* Effect.promise(() => - manager.runStackedAction(targetKey).run(registry, { - actionId: interruptedActionId, - action, - }), + runAtomCommand( + registry, + manager.runStackedAction(targetKey), + { + actionId: interruptedActionId, + action, + }, + { reportFailure: false, reportDefect: false }, + ), ); expect(AsyncResult.isFailure(interruptedResult)).toBe(true); diff --git a/packages/client-runtime/src/state/vcsStatusRevalidation.test.ts b/packages/client-runtime/src/state/vcsStatusRevalidation.test.ts index 9a1d8c3dd2717..d3cdc8210e77e 100644 --- a/packages/client-runtime/src/state/vcsStatusRevalidation.test.ts +++ b/packages/client-runtime/src/state/vcsStatusRevalidation.test.ts @@ -1,5 +1,6 @@ import { EnvironmentId } from "@t3tools/contracts"; -import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity"; +import * as Effect from "effect/Effect"; +import { Atom, AtomRegistry } from "effect/reactivity"; import { describe, expect, it, vi } from "vite-plus/test"; import { createVcsStatusRevalidationAtomFamily } from "./vcsStatusRevalidation.ts"; @@ -9,7 +10,7 @@ const environmentId = EnvironmentId.make("environment-1"); function setup(options: { readonly connected?: boolean; readonly wake?: boolean }) { const connectedAtom = Atom.make(options.connected ?? false); const wakes = new Set<() => void>(); - const run = vi.fn(async () => AsyncResult.success(null)); + const run = vi.fn(() => Effect.succeed(null)); const family = createVcsStatusRevalidationAtomFamily({ refreshStatus: { label: "refresh-status", run }, ...(options.connected === undefined ? {} : { connected: () => connectedAtom }), From 46b14a6808f6d130725cc5cb814c6b1b68f080c3 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 19 Nov 2026 12:11:07 -0800 Subject: [PATCH 28/97] fix(mobile): device registration and Live Activity updates stay in Effect (#38913) Co-authored-by: Claude Fable 5.2 --- .../liveActivityPreferences.test.ts | 50 +++++- .../liveActivityPreferences.ts | 165 +++++++++--------- .../remoteRegistration.test.ts | 60 ++++++- .../agent-awareness/remoteRegistration.ts | 146 +++++++++------- .../SettingsNotificationsRouteScreen.tsx | 9 +- 5 files changed, 275 insertions(+), 155 deletions(-) diff --git a/apps/mobile/src/features/agent-awareness/liveActivityPreferences.test.ts b/apps/mobile/src/features/agent-awareness/liveActivityPreferences.test.ts index 4ea1aea9989b3..2bf255d39e099 100644 --- a/apps/mobile/src/features/agent-awareness/liveActivityPreferences.test.ts +++ b/apps/mobile/src/features/agent-awareness/liveActivityPreferences.test.ts @@ -3,10 +3,16 @@ import { describe, expect, it } from "@effect/vitest"; import * as Exit from "effect/Exit"; import * as Option from "effect/Option"; import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; import type { EnvironmentId } from "@t3tools/contracts"; import { ManagedRelay } from "@t3tools/client-runtime/relay"; import type { SavedRemoteConnection } from "../../lib/connection"; +import { + MobilePreferencesSaveError, + MobilePreferencesStore, +} from "../../persistence/mobile-preferences"; +import { MobileStorage } from "../../persistence/mobile-storage"; import { CloudEnvironmentLinkError } from "../cloud/linkEnvironment"; import { setLiveActivityUpdatesEnabled } from "./liveActivityPreferences"; import { updateAgentAwarenessRegistrationPreferences } from "./remoteRegistration"; @@ -48,6 +54,10 @@ const linkEnvironment = vi.fn< ) => Effect.Effect >(() => Effect.void); +const saveLocalPreference = vi.fn< + (enabled: boolean) => Effect.Effect +>(() => Effect.void); + const connection: SavedRemoteConnection = { environmentId: "env-1" as EnvironmentId, environmentLabel: "Desktop", @@ -58,7 +68,13 @@ const connection: SavedRemoteConnection = { bearerToken: "local-bearer", }; -const withRelayClient = Effect.provideService(ManagedRelay.ManagedRelayClient, null as never); +const withRelayClient = Effect.provide( + Layer.mergeAll( + Layer.succeed(ManagedRelay.ManagedRelayClient, null as never), + Layer.succeed(MobileStorage, null as never), + Layer.succeed(MobilePreferencesStore, null as never), + ), +); describe("liveActivityPreferences", () => { beforeEach(() => { @@ -76,6 +92,7 @@ describe("liveActivityPreferences", () => { setLiveActivityUpdatesEnabled({ updateEnvironment, linkEnvironment, + saveLocalPreference, enabled: false, previousEnabled: true, clerkToken: "clerk-token", @@ -103,6 +120,33 @@ describe("liveActivityPreferences", () => { }).pipe(withRelayClient); }); + it.effect("restores the device preference when the device cannot save the setting", () => { + saveLocalPreference.mockImplementationOnce(() => + Effect.fail(new MobilePreferencesSaveError({ cause: new Error("storage full") })), + ); + + return Effect.gen(function* () { + const exit = yield* Effect.exit( + setLiveActivityUpdatesEnabled({ + updateEnvironment, + linkEnvironment, + saveLocalPreference, + enabled: true, + previousEnabled: false, + clerkToken: "clerk-token", + connections: [connection], + canConfigureEnvironment: () => false, + canUpdateEnvironment: () => true, + }), + ); + + expect(Exit.isFailure(exit)).toBe(true); + expect(updateAgentAwarenessRegistrationPreferences).toHaveBeenLastCalledWith({ + liveActivitiesEnabled: false, + }); + }).pipe(withRelayClient); + }); + it.effect("reports a relay preference committed before environment configuration fails", () => { const failure = new CloudEnvironmentLinkError({ message: "environment configuration failed", @@ -116,6 +160,7 @@ describe("liveActivityPreferences", () => { setLiveActivityUpdatesEnabled({ updateEnvironment, linkEnvironment, + saveLocalPreference, enabled: true, previousEnabled: false, clerkToken: "clerk-token", @@ -156,6 +201,7 @@ describe("liveActivityPreferences", () => { yield* setLiveActivityUpdatesEnabled({ updateEnvironment, linkEnvironment, + saveLocalPreference, enabled: true, previousEnabled: false, clerkToken: "clerk-token", @@ -185,6 +231,7 @@ describe("liveActivityPreferences", () => { const partial = yield* setLiveActivityUpdatesEnabled({ updateEnvironment, linkEnvironment, + saveLocalPreference, enabled: false, previousEnabled: true, clerkToken: "clerk-token", @@ -209,6 +256,7 @@ describe("liveActivityPreferences", () => { yield* setLiveActivityUpdatesEnabled({ updateEnvironment, linkEnvironment, + saveLocalPreference, enabled: false, previousEnabled: true, clerkToken: "clerk-token", diff --git a/apps/mobile/src/features/agent-awareness/liveActivityPreferences.ts b/apps/mobile/src/features/agent-awareness/liveActivityPreferences.ts index 6ff47c294a4cb..a8cbe09ddfebd 100644 --- a/apps/mobile/src/features/agent-awareness/liveActivityPreferences.ts +++ b/apps/mobile/src/features/agent-awareness/liveActivityPreferences.ts @@ -15,92 +15,95 @@ export class LiveActivityEnvironmentUpdateError extends Schema.TaggedError; - readonly updateEnvironment: ( - environmentId: EnvironmentId, - enabled: boolean, - ) => Effect.Effect< - "updated" | "unlinked" | "unsupported" | "disconnected", - CloudEnvironmentLinkError - >; - readonly linkEnvironment: ( - environmentId: EnvironmentId, - input: { readonly clerkToken: string; readonly liveActivitiesEnabled: boolean }, - ) => Effect.Effect; - readonly canUpdateEnvironment: (environmentId: EnvironmentId) => boolean; - readonly canConfigureEnvironment: (environmentId: EnvironmentId) => boolean; - }) { - const updateEnvironmentPreference = Effect.fn("updateEnvironmentPreference")(function* ( - connection: SavedRemoteConnection, - enabled: boolean, - clerkToken: string | null, - ) { - const result = input.canUpdateEnvironment(connection.environmentId) - ? yield* input.updateEnvironment(connection.environmentId, enabled) - : "unlinked"; - if (result === "updated" || result === "disconnected") return result; - if (!enabled || !clerkToken || !input.canConfigureEnvironment(connection.environmentId)) { - return result; - } +export const setLiveActivityUpdatesEnabled = Effect.fn("setLiveActivityUpdatesEnabled")(function* < + SaveError, +>(input: { + readonly enabled: boolean; + readonly previousEnabled: boolean; + readonly clerkToken: string | null; + readonly connections: ReadonlyArray; + readonly updateEnvironment: ( + environmentId: EnvironmentId, + enabled: boolean, + ) => Effect.Effect< + "updated" | "unlinked" | "unsupported" | "disconnected", + CloudEnvironmentLinkError + >; + readonly linkEnvironment: ( + environmentId: EnvironmentId, + input: { readonly clerkToken: string; readonly liveActivitiesEnabled: boolean }, + ) => Effect.Effect; + readonly canUpdateEnvironment: (environmentId: EnvironmentId) => boolean; + readonly canConfigureEnvironment: (environmentId: EnvironmentId) => boolean; + readonly saveLocalPreference: (enabled: boolean) => Effect.Effect; +}) { + const updateEnvironmentPreference = Effect.fn("updateEnvironmentPreference")(function* ( + connection: SavedRemoteConnection, + enabled: boolean, + clerkToken: string | null, + ) { + const result = input.canUpdateEnvironment(connection.environmentId) + ? yield* input.updateEnvironment(connection.environmentId, enabled) + : "unlinked"; + if (result === "updated" || result === "disconnected") return result; + if (!enabled || !clerkToken || !input.canConfigureEnvironment(connection.environmentId)) { + return result; + } - yield* input.linkEnvironment(connection.environmentId, { - clerkToken, - liveActivitiesEnabled: enabled, - }); - return "updated" as const; + yield* input.linkEnvironment(connection.environmentId, { + clerkToken, + liveActivitiesEnabled: enabled, }); + return "updated" as const; + }); - const updateRelayPreference = Effect.fn("updateRelayPreference")(function* (enabled: boolean) { - yield* updateAgentAwarenessRegistrationPreferences({ - liveActivitiesEnabled: enabled, - }); + const updateRelayPreference = Effect.fn("updateRelayPreference")(function* (enabled: boolean) { + yield* updateAgentAwarenessRegistrationPreferences({ + liveActivitiesEnabled: enabled, + }); - const clerkToken = input.clerkToken; - if (!clerkToken) return false; + const clerkToken = input.clerkToken; + if (!clerkToken) return false; - const results = yield* Effect.forEach( - input.connections, - (connection) => - updateEnvironmentPreference(connection, enabled, clerkToken).pipe( - Effect.result, - Effect.map((result) => ({ connection, result })), - ), - { concurrency: "unbounded" }, - ); - const failure = results.find(({ result }) => Result.isFailure(result)); - if (failure && Result.isFailure(failure.result)) { - const updatedEnvironments = results.flatMap(({ connection, result }) => { - const changed = Result.isSuccess(result) - ? result.success === "updated" - : result.failure.relayLinkCommitted === true; - return changed ? [connection.environmentLabel] : []; - }); - if (updatedEnvironments.length === 0) return yield* failure.result.failure; - return yield* new LiveActivityEnvironmentUpdateError({ - updatedEnvironments, - cause: failure.result.failure, - }); - } - return results.some( - ({ result }) => Result.isSuccess(result) && result.success === "unsupported", - ); - }); + const results = yield* Effect.forEach( + input.connections, + (connection) => + updateEnvironmentPreference(connection, enabled, clerkToken).pipe( + Effect.result, + Effect.map((result) => ({ connection, result })), + ), + { concurrency: "unbounded" }, + ); + const failure = results.find(({ result }) => Result.isFailure(result)); + if (failure && Result.isFailure(failure.result)) { + const updatedEnvironments = results.flatMap(({ connection, result }) => { + const changed = Result.isSuccess(result) + ? result.success === "updated" + : result.failure.relayLinkCommitted === true; + return changed ? [connection.environmentLabel] : []; + }); + if (updatedEnvironments.length === 0) return yield* failure.result.failure; + return yield* new LiveActivityEnvironmentUpdateError({ + updatedEnvironments, + cause: failure.result.failure, + }); + } + return results.some( + ({ result }) => Result.isSuccess(result) && result.success === "unsupported", + ); + }); - return yield* updateRelayPreference(input.enabled).pipe( - Effect.onError(() => - updateAgentAwarenessRegistrationPreferences({ - liveActivitiesEnabled: input.previousEnabled, - }).pipe( - Effect.catchCause((cause) => - Effect.logWarning("Could not restore Live Activity device preference.", cause), - ), + return yield* updateRelayPreference(input.enabled).pipe( + // Saved here so a device that cannot keep the setting restores its registration too. + Effect.tap(() => input.saveLocalPreference(input.enabled)), + Effect.onError(() => + updateAgentAwarenessRegistrationPreferences({ + liveActivitiesEnabled: input.previousEnabled, + }).pipe( + Effect.catchCause((cause) => + Effect.logWarning("Could not restore Live Activity device preference.", cause), ), ), - ); - }, -); + ), + ); +}); diff --git a/apps/mobile/src/features/agent-awareness/remoteRegistration.test.ts b/apps/mobile/src/features/agent-awareness/remoteRegistration.test.ts index c7f2e02468ea2..5f5a46b653b1b 100644 --- a/apps/mobile/src/features/agent-awareness/remoteRegistration.test.ts +++ b/apps/mobile/src/features/agent-awareness/remoteRegistration.test.ts @@ -21,12 +21,19 @@ import * as Dpop from "../cloud/dpop"; import * as ManagedRelayLayer from "../cloud/managedRelayLayer"; import { clearAgentAwarenessRegistrationRecord, + loadAgentAwarenessDeviceId, loadAgentAwarenessRegistrationRecord, loadOrCreateAgentAwarenessDeviceId, loadPreferences, saveAgentAwarenessRegistrationRecord, } from "../../persistence/imperative"; -import type { Preferences } from "../../persistence/mobile-preferences"; +import { + MobilePreferencesLoadError, + MobilePreferencesStore, + type Preferences, +} from "../../persistence/mobile-preferences"; +import { MobileSecureStorageError } from "../../persistence/mobile-secure-storage"; +import * as MobileStorage from "../../persistence/mobile-storage"; import { makeRelayDeviceRegistrationRequest } from "./registrationPayload"; import { __resetAgentAwarenessRemoteRegistrationForTest, @@ -40,6 +47,7 @@ import { subscribeAgentAwarenessRegistrationStatus, updateAgentAwarenessRegistrationPreferences, type AgentAwarenessRegistrationError, + type AgentAwarenessRegistrationServices, } from "./remoteRegistration"; import * as Notifications from "expo-notifications"; import { Platform } from "react-native"; @@ -218,8 +226,53 @@ function proofIat(proof: string): number { return decoded.iat; } +const storageFailure = (cause: unknown) => + new MobileSecureStorageError({ operation: "read", key: "test", cause }); +const unexpectedStorage = () => Effect.die("Unexpected storage request"); + +// Delegates to the persistence/imperative mocks so each test steers both paths the same way. +const layerPersistenceTest = Layer.merge( + Layer.succeed( + MobileStorage.MobileStorage, + MobileStorage.MobileStorage.of({ + loadOrCreateAgentAwarenessDeviceId: Effect.tryPromise({ + try: () => loadOrCreateAgentAwarenessDeviceId(), + catch: storageFailure, + }), + loadAgentAwarenessDeviceId: Effect.tryPromise({ + try: () => loadAgentAwarenessDeviceId(), + catch: storageFailure, + }), + loadAgentAwarenessRegistrationRecord: Effect.tryPromise({ + try: () => loadAgentAwarenessRegistrationRecord(), + catch: storageFailure, + }), + saveAgentAwarenessRegistrationRecord: (record) => + Effect.tryPromise({ + try: () => saveAgentAwarenessRegistrationRecord(record), + catch: storageFailure, + }), + clearAgentAwarenessRegistrationRecord: unexpectedStorage(), + loadRecentThreadShortcuts: unexpectedStorage(), + saveRecentThreadShortcuts: unexpectedStorage, + }), + ), + Layer.succeed( + MobilePreferencesStore, + MobilePreferencesStore.of({ + load: Effect.tryPromise({ + try: () => loadPreferences(), + catch: (cause) => new MobilePreferencesLoadError({ cause }), + }), + savePatch: unexpectedStorage, + update: unexpectedStorage, + }), + ), +); + const layerRelayTest = ManagedRelayLayer.layer("https://relay.example.test").pipe( Layer.provide(Layer.mergeAll(FetchHttpClient.layer, Dpop.layer)), + Layer.merge(layerPersistenceTest), ); const runBackgroundOperations = Effect.fn("TestRemoteRegistration.runBackgroundOperations")( @@ -241,7 +294,7 @@ const runBackgroundOperations = Effect.fn("TestRemoteRegistration.runBackgroundO pending.operation as Effect.Effect< unknown, AgentAwarenessRegistrationError, - ManagedRelay.ManagedRelayClient + AgentAwarenessRegistrationServices >, ); yield* Effect.sync(() => { @@ -722,6 +775,7 @@ describe("makeRelayDeviceRegistrationRequest", () => { Effect.provide( ManagedRelayLayer.layer("https://permission-relay.example.test").pipe( Layer.provide(Layer.mergeAll(FetchHttpClient.layer, Dpop.layer)), + Layer.merge(layerPersistenceTest), ), ), ); @@ -1021,7 +1075,7 @@ describe("makeRelayDeviceRegistrationRequest", () => { getAgentActivitySnapshot, resetTokenCache: Effect.void, }), - ); + ).pipe(Layer.merge(layerPersistenceTest)); } it.effect("registers an existing Live Activity before waiting on the widget read", () => { diff --git a/apps/mobile/src/features/agent-awareness/remoteRegistration.ts b/apps/mobile/src/features/agent-awareness/remoteRegistration.ts index b50da67e86433..bea319f0877d3 100644 --- a/apps/mobile/src/features/agent-awareness/remoteRegistration.ts +++ b/apps/mobile/src/features/agent-awareness/remoteRegistration.ts @@ -29,14 +29,11 @@ import { m } from "../../i18n/messages"; import { runtime } from "../../lib/runtime"; import { appAtomRegistry } from "../../state/atom-registry"; import { environmentServerConfigsAtom } from "../../state/server"; -import type { Preferences } from "../../persistence/mobile-preferences"; +import { MobilePreferencesStore, type Preferences } from "../../persistence/mobile-preferences"; +import * as MobileStorage from "../../persistence/mobile-storage"; import { clearAgentAwarenessRegistrationRecord, - loadAgentAwarenessDeviceId, - loadAgentAwarenessRegistrationRecord, - loadOrCreateAgentAwarenessDeviceId, loadPreferences, - saveAgentAwarenessRegistrationRecord, } from "../../persistence/imperative"; import type { AgentActivityProps } from "../../widgets/AgentActivity"; import { @@ -88,6 +85,11 @@ export type AgentAwarenessRegistrationError = | AgentAwarenessOperationError | ManagedRelay.ManagedRelayClientError; +export type AgentAwarenessRegistrationServices = + | ManagedRelay.ManagedRelayClient + | MobileStorage.MobileStorage + | MobilePreferencesStore; + // ActivityKit returns new wrappers per id; serialize by id to prevent stale-token registration. const activityPushTokenLocks = new Map(); // Each accepted registration replays the relay aggregate, repairing drifted or orphaned activities. @@ -387,7 +389,7 @@ function registrationSignature(body: RelayDeviceRegistrationRequest): string { const registerDeviceWithRelay = Effect.fn("remoteRegistration.registerDeviceWithRelay")(function* ( body: RelayDeviceRegistrationRequest, expectedGeneration: number, -): Effect.fn.Return { +): Effect.fn.Return { if (expectedGeneration !== deviceRegistrationGeneration) { return; } @@ -406,11 +408,13 @@ const registerDeviceWithRelay = Effect.fn("remoteRegistration.registerDeviceWith } const identity = relayTokenProviderIdentity ?? ""; - const persisted = yield* Effect.tryPromise({ - try: () => loadAgentAwarenessRegistrationRecord(), - catch: (cause) => - new AgentAwarenessOperationError({ operation: "load-registration-record", cause }), - }).pipe(Effect.orElseSucceed(() => null)); + const storage = yield* MobileStorage.MobileStorage; + const persisted = yield* storage.loadAgentAwarenessRegistrationRecord.pipe( + Effect.mapError( + (cause) => new AgentAwarenessOperationError({ operation: "load-registration-record", cause }), + ), + Effect.orElseSucceed(() => null), + ); if (expectedGeneration !== deviceRegistrationGeneration) { // Signed out while the record loaded — do not resurrect the cleared // record or report the previous account's registration as current. @@ -449,13 +453,12 @@ const registerDeviceWithRelay = Effect.fn("remoteRegistration.registerDeviceWith } if (body.platform === "android") androidDeviceReplayedAt = yield* Clock.currentTimeMillis; setRegistrationStatus("registered", Boolean(payload.pushToken)); - yield* Effect.promise(() => - saveAgentAwarenessRegistrationRecord({ - identity, - signature, - }).catch((error: unknown) => { - logRegistrationError("persist registration record failed", error); - }), + yield* storage.saveAgentAwarenessRegistrationRecord({ identity, signature }).pipe( + Effect.catch((error) => + Effect.sync(() => { + logRegistrationError("persist registration record failed", error); + }), + ), ); }); @@ -610,7 +613,7 @@ function logRegistrationError(context: string, error: unknown): void { } function runRegistrationInBackground( - operation: Effect.Effect, + operation: Effect.Effect, context: string, ): void { void (async () => { @@ -693,28 +696,32 @@ function enqueueDeviceRegistration(input: DeviceRegistrationInput, context: stri const registerDevice = Effect.fn("remoteRegistration.registerDevice")(function* ( input: RegisterDeviceInput = {}, expectedGeneration = deviceRegistrationGeneration, -): Effect.fn.Return { +): Effect.fn.Return { if (!canRegisterPushNotifications()) { return; } + const storage = yield* MobileStorage.MobileStorage; + const preferencesStore = yield* MobilePreferencesStore; const [deviceId, storedPreferences] = yield* Effect.all([ - Effect.tryPromise({ - try: () => loadOrCreateAgentAwarenessDeviceId(), - catch: (cause) => - new AgentAwarenessOperationError({ - operation: "load-device-registration-identifier", - cause, - }), - }), - Effect.tryPromise({ - try: () => loadPreferences(), - catch: (cause) => - new AgentAwarenessOperationError({ - operation: "load-device-registration-preferences", - cause, - }), - }), + storage.loadOrCreateAgentAwarenessDeviceId.pipe( + Effect.mapError( + (cause) => + new AgentAwarenessOperationError({ + operation: "load-device-registration-identifier", + cause, + }), + ), + ), + preferencesStore.load.pipe( + Effect.mapError( + (cause) => + new AgentAwarenessOperationError({ + operation: "load-device-registration-preferences", + cause, + }), + ), + ), ]); const preferences = mergeAgentAwarenessRegistrationPreferences( storedPreferences, @@ -833,7 +840,7 @@ function endLocalLiveActivities(context: string): void { export function refreshAgentAwarenessRegistration(): Effect.Effect< void, never, - ManagedRelay.ManagedRelayClient + AgentAwarenessRegistrationServices > { return Effect.suspend(() => { const generation = deviceRegistrationGeneration; @@ -852,7 +859,7 @@ export function refreshAgentAwarenessRegistration(): Effect.Effect< export function updateAgentAwarenessRegistrationPreferences( preferencesOverride: Partial, -): Effect.Effect { +): Effect.Effect { return Effect.suspend(() => { const generation = deviceRegistrationGeneration; return registerDevice({ preferencesOverride }, generation).pipe( @@ -895,18 +902,20 @@ export function __resetAgentAwarenessRemoteRegistrationForTest(): void { export const unregisterAgentAwarenessDeviceForCurrentUser: ( tokenProvider: () => Promise, -) => Effect.Effect = Effect.fn( +) => Effect.Effect = Effect.fn( "remoteRegistration.unregisterAgentAwarenessDeviceForCurrentUser", )( function* (tokenProvider: () => Promise) { - const deviceId = yield* Effect.tryPromise({ - try: () => loadAgentAwarenessDeviceId(), - catch: (cause) => - new AgentAwarenessOperationError({ - operation: "load-device-unregistration-identifier", - cause, - }), - }); + const storage = yield* MobileStorage.MobileStorage; + const deviceId = yield* storage.loadAgentAwarenessDeviceId.pipe( + Effect.mapError( + (cause) => + new AgentAwarenessOperationError({ + operation: "load-device-unregistration-identifier", + cause, + }), + ), + ); if (!deviceId) { return; } @@ -923,7 +932,7 @@ export const registerLiveActivityPushToken = Effect.fn( "remoteRegistration.registerLiveActivityPushToken", )(function* (input: { readonly activity: LiveActivity; -}): Effect.fn.Return { +}): Effect.fn.Return { if (!canRegisterRemoteLiveActivities()) { return false; } @@ -971,7 +980,7 @@ const registerLiveActivityPushTokenValue = Effect.fn( "remoteRegistration.registerLiveActivityPushTokenValue", )(function* (input: { readonly activityPushToken: string; -}): Effect.fn.Return { +}): Effect.fn.Return { const acceptedAt = registeredActivityPushTokens.get(input.activityPushToken); if ( acceptedAt !== undefined && @@ -979,14 +988,16 @@ const registerLiveActivityPushTokenValue = Effect.fn( ) { return true; } - const deviceId = yield* Effect.tryPromise({ - try: () => loadOrCreateAgentAwarenessDeviceId(), - catch: (cause) => - new AgentAwarenessOperationError({ - operation: "load-live-activity-registration-identifier", - cause, - }), - }); + const storage = yield* MobileStorage.MobileStorage; + const deviceId = yield* storage.loadOrCreateAgentAwarenessDeviceId.pipe( + Effect.mapError( + (cause) => + new AgentAwarenessOperationError({ + operation: "load-live-activity-registration-identifier", + cause, + }), + ), + ); const registered = yield* registerLiveActivityWithRelay({ deviceId, activityPushToken: input.activityPushToken, @@ -1013,7 +1024,7 @@ function scheduleActiveLiveActivityRegistrationRetry(): void { export const refreshActiveLiveActivityRemoteRegistration = Effect.fn( "remoteRegistration.refreshActiveLiveActivityRemoteRegistration", -)(function* (): Effect.fn.Return { +)(function* (): Effect.fn.Return { if (!canRegisterRemoteLiveActivities() || !relayTokenProvider) { return; } @@ -1084,14 +1095,17 @@ export const refreshActiveLiveActivityRemoteRegistration = Effect.fn( return; } const { snapshot } = widgetRead; - const preferences = yield* Effect.tryPromise({ - try: () => loadPreferences(), - catch: (cause) => - new AgentAwarenessOperationError({ - operation: "load-live-activity-prime-preferences", - cause, - }), - }).pipe(Effect.orElseSucceed(() => null)); + const preferencesStore = yield* MobilePreferencesStore; + const preferences = yield* preferencesStore.load.pipe( + Effect.mapError( + (cause) => + new AgentAwarenessOperationError({ + operation: "load-live-activity-prime-preferences", + cause, + }), + ), + Effect.orElseSucceed(() => null), + ); // A sign-out, account switch, or newer read during the preference read // makes this snapshot stale; priming now could bring old rows back. if (!isNewestRead()) { diff --git a/apps/mobile/src/features/settings/SettingsNotificationsRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsNotificationsRouteScreen.tsx index 8a3d8ad0dfc85..6bc53854d25f3 100644 --- a/apps/mobile/src/features/settings/SettingsNotificationsRouteScreen.tsx +++ b/apps/mobile/src/features/settings/SettingsNotificationsRouteScreen.tsx @@ -61,7 +61,6 @@ import { hasCloudPublicConfig, resolveRelayClerkTokenOptions } from "../cloud/pu import { makePermissionStatusAtom } from "../../lib/permissionStatusAtom"; import { runtime } from "../../lib/runtime"; import { mobilePreferencesAtom, saveMobilePreferences } from "../../state/preferences"; -import { useAtomCommand } from "../../state/use-atom-command"; import { useSavedRemoteConnections } from "../../state/use-remote-environment-registry"; import { SettingsRow } from "./components/SettingsRow"; import { SettingsSection } from "./components/SettingsSection"; @@ -102,6 +101,9 @@ const updateEnvironmentPreference = Effect.fn("updateEnvironmentPreference")(fun ); }); +const saveLocalPreference = (liveActivitiesEnabled: boolean) => + saveMobilePreferences.run(appAtomRegistry, { liveActivitiesEnabled }); + const linkEnvironmentWithPreference = Effect.fn("linkEnvironmentWithPreference")(function* ( environmentId: EnvironmentId, input: { readonly clerkToken: string; readonly liveActivitiesEnabled: boolean }, @@ -209,7 +211,6 @@ function ConfiguredSettingsNotificationsRouteScreen() { const gt = useGT(); const m = useMessages(); const preferencesResult = useAtomValue(mobilePreferencesAtom); - const savePreferences = useAtomCommand(saveMobilePreferences); const agentAwarenessPushAvailable = supportsAgentAwarenessPush(); const agentAwarenessPlatform = resolveAgentAwarenessPlatformPresentation(Platform.OS, m); const agentAwarenessSubtitle = @@ -386,6 +387,7 @@ function ConfiguredSettingsNotificationsRouteScreen() { setLiveActivityUpdatesEnabled({ updateEnvironment: updateEnvironmentPreference, linkEnvironment: linkEnvironmentWithPreference, + saveLocalPreference, canConfigureEnvironment: (id) => canManageConnect(id, AuthRelayConfigureScope) && canManageConnect(id, AuthRelayWriteScope), @@ -414,7 +416,6 @@ function ConfiguredSettingsNotificationsRouteScreen() { return; } - void savePreferences({ liveActivitiesEnabled: true }); refreshManagedRelayEnvironments(); setLiveActivityStatus("enabled"); // Environment linking can precede device registration; only registered devices can receive Live Activities. @@ -484,6 +485,7 @@ function ConfiguredSettingsNotificationsRouteScreen() { setLiveActivityUpdatesEnabled({ updateEnvironment: updateEnvironmentPreference, linkEnvironment: linkEnvironmentWithPreference, + saveLocalPreference, canConfigureEnvironment: (id) => canManageConnect(id, AuthRelayConfigureScope) && canManageConnect(id, AuthRelayWriteScope), @@ -504,7 +506,6 @@ function ConfiguredSettingsNotificationsRouteScreen() { } return; } - void savePreferences({ liveActivitiesEnabled: false }); refreshManagedRelayEnvironments(); setLiveActivityStatus("disabled"); if (updateResult.value) { From 938feb32464352d61e7e474792d69da01a7e6e87 Mon Sep 17 00:00:00 2001 From: Elias <69803556+elias1218@users.noreply.github.com> Date: Thu, 19 Nov 2026 15:11:34 -0500 Subject: [PATCH 29/97] fix(server): a stalled poll no longer stalls headless T3 Connect login (#39214) Co-authored-by: Julius Marminge --- apps/server/src/cloud/CliTokenManager.test.ts | 37 +++++++++++++++---- apps/server/src/cloud/CliTokenManager.ts | 4 +- 2 files changed, 31 insertions(+), 10 deletions(-) diff --git a/apps/server/src/cloud/CliTokenManager.test.ts b/apps/server/src/cloud/CliTokenManager.test.ts index 4d5e888725b9a..4f1f4536c9642 100644 --- a/apps/server/src/cloud/CliTokenManager.test.ts +++ b/apps/server/src/cloud/CliTokenManager.test.ts @@ -56,7 +56,7 @@ const provideTestEnv = Effect.provide( interface DeviceFlowServer { readonly requests: Array; - readonly tokenReplies: Array<{ readonly status: number; readonly body: string }>; + readonly tokenReplies: Array<{ readonly status: number; readonly body: string } | "stall">; } const DEVICE_AUTHORIZATION_BODY = JSON.stringify({ @@ -84,7 +84,7 @@ const layerDeviceFlow = (server: DeviceFlowServer) => Layer.succeed( HttpClient.HttpClient, HttpClient.make((request) => - Effect.sync(() => { + Effect.suspend(() => { const body = request.body._tag === "Uint8Array" ? new TextDecoder().decode(request.body.body) : ""; server.requests.push({ url: request.url, params: new URLSearchParams(body) }); @@ -93,12 +93,15 @@ const layerDeviceFlow = (server: DeviceFlowServer) => : ((server.tokenReplies.length > 1 ? server.tokenReplies.shift() : server.tokenReplies[0]) ?? oauthError("invalid_grant")); - return HttpClientResponse.fromWeb( - request, - new Response(reply.body, { - status: reply.status, - headers: { "content-type": "application/json" }, - }), + if (reply === "stall") return Effect.never; + return Effect.succeed( + HttpClientResponse.fromWeb( + request, + new Response(reply.body, { + status: reply.status, + headers: { "content-type": "application/json" }, + }), + ), ); }), ), @@ -302,6 +305,24 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))( }), ); + it.effect("retries a poll that never answers instead of waiting out the device code", () => + Effect.gen(function* () { + const server: DeviceFlowServer = { requests: [], tokenReplies: ["stall", tokenGranted] }; + + const fiber = yield* CliTokenManager.deviceAuthorizationLogin(() => Effect.void).pipe( + Effect.provide(layerDeviceFlow(server)), + provideTestEnv, + Effect.forkChild, + ); + // 5 s interval, a 10 s request timeout, then the 10 s slowed-down interval. + yield* TestClock.adjust(Duration.seconds(25)); + + assert.lengthOf(tokenRequests(server.requests), 2); + const { token } = yield* Fiber.join(fiber); + assert.equal(token.accessToken, "access-token-1"); + }), + ); + it.effect("fails with a denied error when the user rejects the request", () => Effect.gen(function* () { const server: DeviceFlowServer = { diff --git a/apps/server/src/cloud/CliTokenManager.ts b/apps/server/src/cloud/CliTokenManager.ts index 11a09f481ac4b..596c594a0a343 100644 --- a/apps/server/src/cloud/CliTokenManager.ts +++ b/apps/server/src/cloud/CliTokenManager.ts @@ -404,10 +404,10 @@ const pollDeviceToken = Effect.fn("cloud.cli_token.poll_device_token")(function* const response = yield* HttpClientRequest.post(metadata.tokenEndpoint).pipe( HttpClientRequest.bodyUrlParams(params), httpClient.execute, - Effect.asSome, + Effect.timeoutOption(OAUTH_REQUEST_TIMEOUT), Effect.catchIf(isTransportError, () => Effect.succeedNone), ); - // Retry transport errors and 5xx while the device code is valid, backing off per RFC 8628 §3.5. Drain bodies to reuse connections. + // Retry transport errors, timeouts and 5xx while the device code is valid, backing off per RFC 8628 §3.5. Drain bodies to reuse connections. if (Option.isNone(response) || response.value.status >= 500) { if (Option.isSome(response)) yield* Effect.ignore(response.value.text); interval = Duration.sum(interval, DEVICE_AUTHORIZATION_SLOW_DOWN_INCREMENT); From f6881ceba049ae2a4e97e9ea8ec28ccd6a069005 Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Thu, 19 Nov 2026 21:11:46 +0100 Subject: [PATCH 30/97] fix(acp-registry): keep managed npm commands out of user PATH (#37542) Co-authored-by: Julius Marminge --- .../src/server/AcpRegistrySupport.test.ts | 21 +++++++++++++++++++ .../src/server/AcpRegistrySupport.ts | 4 ++-- .../testing/AcpRegistrySupport.npm.fixture.sh | 6 ++++-- 3 files changed, 27 insertions(+), 4 deletions(-) diff --git a/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts b/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts index beb10b6fa89e8..bc37033f3b360 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts @@ -511,6 +511,27 @@ describe("AcpRegistrySupport", () => { const npmCommands = yield* fileSystem.readFileString(toolchain.logPath); expect(npmCommands.match(/^install --global /gmu)).toHaveLength(1); expect(npmCommands).toContain("install --global @example/acp@V1.2.3"); + + // A missing npm bin link must not select an unrelated command from the user's PATH. + const userBin = `${cacheDir}/user-bin`; + yield* fileSystem.makeDirectory(userBin); + yield* fileSystem.writeFileString(`${userBin}/example-agent`, "#!/bin/sh\n"); + yield* fileSystem.chmod(`${userBin}/example-agent`, 0o755); + yield* fileSystem.remove(toolchain.executablePath); + const userEnvironment = { + ...toolchain.environment, + PATH: `${userBin}:${toolchain.environment.PATH}`, + }; + const repaired = yield* resolver.resolve(settings(), "/workspace", userEnvironment); + expect(repaired.spawn.command).toBe(toolchain.executablePath); + const repairCommands = yield* fileSystem.readFileString(toolchain.logPath); + expect(repairCommands.match(/^install --global /gmu)).toHaveLength(2); + + yield* fileSystem.remove(toolchain.executablePath); + const failedRepair = yield* resolver + .resolve(settings(), "/workspace", { ...userEnvironment, npm_config_bin_links: "false" }) + .pipe(Effect.flip); + expect(failedRepair.reason).toBe("install_failed"); }).pipe( Effect.scoped, Effect.provide( diff --git a/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts b/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts index 42f2e38433f5d..a2f01f201ef78 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts @@ -1241,9 +1241,9 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct if (commandName === undefined) return Option.none(); const binDirectory = platform === "win32" ? globalPrefix : path.join(globalPrefix, "bin"); const executablePath = resolveExecutable( - commandName, + path.join(binDirectory, commandName), platform, - withPreferredPath(environment, binDirectory, platform), + environment, ); return executablePath === undefined ? Option.none() diff --git a/packages/provider-acp-registry/src/server/testing/AcpRegistrySupport.npm.fixture.sh b/packages/provider-acp-registry/src/server/testing/AcpRegistrySupport.npm.fixture.sh index 496983cb74aab..0256f86d9e884 100755 --- a/packages/provider-acp-registry/src/server/testing/AcpRegistrySupport.npm.fixture.sh +++ b/packages/provider-acp-registry/src/server/testing/AcpRegistrySupport.npm.fixture.sh @@ -19,8 +19,10 @@ if [ "$1" = "install" ] && [ "$2" = "--global" ]; then executable="$prefix/bin/example-agent" mkdir -p "$package_root" "$prefix/bin" printf '%s' "$FAKE_NPM_MANIFEST" > "$package_root/package.json" - printf '#!/bin/sh\n' > "$executable" - chmod 755 "$executable" + if [ "$npm_config_bin_links" != "false" ]; then + printf '#!/bin/sh\n' > "$executable" + chmod 755 "$executable" + fi exit 0 fi exit 64 From 3f5cc38805b48d527d0ca18b9edb69e16a326cf2 Mon Sep 17 00:00:00 2001 From: "M.Umais Adeed" <165276382+Umais-Adeed@users.noreply.github.com> Date: Fri, 20 Nov 2026 01:11:58 +0500 Subject: [PATCH 31/97] fix(server): denying a device that was already approved no longer reports success (#38420) Co-authored-by: Julius Marminge --- apps/server/src/auth/EnvironmentAuth.test.ts | 2 ++ apps/server/src/persistence/AuthPairingLinks.ts | 5 +++++ 2 files changed, 7 insertions(+) diff --git a/apps/server/src/auth/EnvironmentAuth.test.ts b/apps/server/src/auth/EnvironmentAuth.test.ts index cc8953762049f..c452dde064030 100644 --- a/apps/server/src/auth/EnvironmentAuth.test.ts +++ b/apps/server/src/auth/EnvironmentAuth.test.ts @@ -352,6 +352,8 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodePlatformCrypto.layer))( expect(retried.credential).toBe(requested.credential); expect(yield* serverAuth.approveConnectDevice(request!.id)).toBe(true); + // A stale prompt on another client must not report denying an approved device. + expect(yield* serverAuth.revokePairingLink(request!.id)).toBe(false); expect( (yield* serverAuth.listPairingLinks()).some((link) => link.connectDeviceRequest), ).toBe(false); diff --git a/apps/server/src/persistence/AuthPairingLinks.ts b/apps/server/src/persistence/AuthPairingLinks.ts index dc1fae88e68a1..e83a94b3f8d23 100644 --- a/apps/server/src/persistence/AuthPairingLinks.ts +++ b/apps/server/src/persistence/AuthPairingLinks.ts @@ -329,6 +329,11 @@ export const make = Effect.gen(function* () { WHERE id = ${id} AND revoked_at IS NULL AND consumed_at IS NULL + -- An approved request is answered; denying it now would leave the device trusted. + AND NOT ( + requires_connect_approval = 1 + AND proof_key_thumbprint IN (SELECT proof_key_thumbprint FROM auth_connect_devices) + ) RETURNING id AS "id" `, }); From 571c27acaba142f63376067aff32ede793eb3245 Mon Sep 17 00:00:00 2001 From: Alex Tyh Wang <78991111+alextyhwang@users.noreply.github.com> Date: Thu, 19 Nov 2026 15:12:34 -0500 Subject: [PATCH 32/97] fix(server): MCP apps resume an idle Codex thread in its own workspace (#38468) Co-authored-by: Julius Marminge --- .../Adapters/CodexAdapterV2.test.ts | 13 ++++++++++++- .../src/orchestration-v2/Adapters/CodexAdapterV2.ts | 8 ++++---- 2 files changed, 16 insertions(+), 5 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts index fd5f89b86a0c1..05e83ec4c84f8 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts @@ -8619,7 +8619,12 @@ describe("CodexAdapterV2 post-settle continuation", () => { ], }); - const harness = yield* makeCodexReplayHarness(transcript); + const resumeParams: Array = []; + const harness = yield* makeCodexReplayHarness(transcript, undefined, (method, params) => + Effect.sync(() => { + if (method === "thread/resume") resumeParams.push(params); + }), + ); const mcpApps = harness.runtime.mcpApps; assert.ok(mcpApps, "Codex runtime should expose MCP apps"); @@ -8630,6 +8635,12 @@ describe("CodexAdapterV2 post-settle continuation", () => { }); assert.deepEqual(result, resourceResult); + // The shared app-server session's cwd and model belong to whichever thread opened it. + // Codex must resume this thread with its own saved cwd, or it loads another + // project's MCP servers and drops this project's. + assert.equal(resumeParams.length, 1); + assert.ok(!Predicate.hasProperty(resumeParams[0], "cwd"), "resume must not send a cwd"); + assert.ok(!Predicate.hasProperty(resumeParams[0], "model"), "resume must not send a model"); }).pipe( Effect.provide( Layer.mergeAll( diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts index 530bd88ee96fd..f865802b023d2 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts @@ -7770,6 +7770,9 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( payload: cause, }); // Codex unloads idle threads; MCP requests against one fail until it is resumed. + // The session's model and cwd belong to whichever thread opened this shared + // app-server, so leave them out: Codex resumes with the thread's saved settings + // and loads that workspace's project MCP servers. const withLoadedThread = ( providerThread: OrchestrationV2ProviderThread, threadId: string, @@ -7784,8 +7787,6 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( ...codexThreadRuntimeParams({ threadId: providerThread.appThreadId, mcpSession, - modelSelection: input.modelSelection, - runtimePolicy: input.runtimePolicy, }), }), ), @@ -8855,14 +8856,13 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( }); } // thread/revert requires the thread loaded in this app-server; resume after restart or idle release. + // Like withLoadedThread, resume with the thread's saved model and cwd, not the session's. if (!loaded) { yield* resumeNativeThread(threadId, { excludeTurns: true, ...codexThreadRuntimeParams({ threadId: threadInput.providerThread.appThreadId, mcpSession: yield* readMcpSession(threadInput.providerThread.appThreadId), - modelSelection: input.modelSelection, - runtimePolicy: input.runtimePolicy, }), }); } From 314a11498e1ac1c29a553bef7fe6032146d51287 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 19 Nov 2026 12:12:48 -0800 Subject: [PATCH 33/97] fix(web): preserve Connect environments on unreachable auth at launch (#24642) Co-authored-by: Otavio Salvador --- .../src/relay/cloudAccountService.test.ts | 31 +++++++++++++++++-- .../src/relay/cloudAccountService.ts | 29 +++++++++++++++-- 2 files changed, 55 insertions(+), 5 deletions(-) diff --git a/packages/client-runtime/src/relay/cloudAccountService.test.ts b/packages/client-runtime/src/relay/cloudAccountService.test.ts index f66d8a9423f25..1549f9e4f6a62 100644 --- a/packages/client-runtime/src/relay/cloudAccountService.test.ts +++ b/packages/client-runtime/src/relay/cloudAccountService.test.ts @@ -6,7 +6,7 @@ import { planCloudAccountStep, } from "./cloudAccountService.ts"; -type Emit = (user: { readonly id: string } | null | undefined) => void; +type Emit = (user: { readonly id: string } | null | undefined, clientId?: string) => void; function makeSource() { let listener: Parameters[0] | null = null; @@ -18,7 +18,8 @@ function makeSource() { }; }, }; - const emit: Emit = (user) => listener?.({ user }); + const emit: Emit = (user, clientId = "client_1") => + listener?.({ user, client: { id: clientId } }); return { source, emit, isSubscribed: () => listener !== null }; } @@ -154,6 +155,32 @@ describe("createCloudAccountService", () => { expect(log).toEqual(["signOutTransition", "deactivate", "cleanUp:a:true"]); }); + it("waits for Clerk's API to confirm a signed-out launch before cleaning up", async () => { + const { service, log, nextActivation, nextCleanUp } = makeService(); + const { source, emit } = makeSource(); + service.attach(source); + + // Offline: an id-less client, or the placeholder built from the session cookie. + emit(null, ""); + emit(null, "client_init"); + expect(service.getState()).toEqual({ _tag: "Unobserved" }); + expect(log).toEqual([]); + + const cleanUp = nextCleanUp(); + emit(null); + await cleanUp; + expect(log).toEqual(["deactivate", "cleanUp:null:false"]); + + const activation = nextActivation(); + emit({ id: "a" }); + await activation; + log.length = 0; + const signOut = nextCleanUp(); + emit(null, "client_init"); + await signOut; + expect(log).toEqual(["signOutTransition", "deactivate", "cleanUp:a:true"]); + }); + it("never activates an account that signed out while it was activating", async () => { const { service, log, nextCleanUp, gate } = makeService(); const { source, emit } = makeSource(); diff --git a/packages/client-runtime/src/relay/cloudAccountService.ts b/packages/client-runtime/src/relay/cloudAccountService.ts index 6592fba687b78..7f885281d3b90 100644 --- a/packages/client-runtime/src/relay/cloudAccountService.ts +++ b/packages/client-runtime/src/relay/cloudAccountService.ts @@ -7,10 +7,22 @@ import { reportAtomCommandResult, settlePromise } from "../state/runtime.ts"; */ export interface CloudAccountSource { readonly addListener: ( - listener: (resources: { readonly user?: { readonly id: string } | null | undefined }) => void, + listener: (resources: { + readonly client?: { readonly id?: string | null | undefined } | null | undefined; + readonly user?: { readonly id: string } | null | undefined; + }) => void, ) => () => void; } +/** + * Clerk's load status cannot prove its API answered: offline it emits an + * id-less client, and a failed launch fetch emits a "client_init" placeholder + * built from the session cookie. Only a real /v1/client response has an id. + */ +const isClientFromClerkApi = ( + client: { readonly id?: string | null | undefined } | null | undefined, +) => Boolean(client?.id) && client?.id !== "client_init"; + interface CloudAccountSignIn { readonly _tag: "SignIn"; readonly accountId: string; @@ -32,7 +44,8 @@ export type CloudAccountStep = /** * `previous` is undefined until Clerk's first emission. A first emission that * is signed out still cleans up, so data left by an account that signed out - * while the app was closed does not linger. + * while the app was closed does not linger. The service only plans that step + * once Clerk's API has confirmed the sign-out. */ export function planCloudAccountStep( previous: string | null | undefined, @@ -200,7 +213,17 @@ export function createCloudAccountService( // Clerk reports `user: undefined` until it loads; pending sessions // still carry a user and count as signed in. if (resources.user === undefined) return; - observe(source, resources.user?.id ?? null); + const next = resources.user?.id ?? null; + // An unreachable Clerk API at launch looks signed out; stay unobserved + // until Clerk confirms it, so saved environments survive offline starts. + if ( + next === null && + state._tag === "Unobserved" && + !isClientFromClerkApi(resources.client) + ) { + return; + } + observe(source, next); }), }; attached = current; From a2a463a32e6b8cf673c326be06bfe9699b8a8518 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 19 Nov 2026 12:13:05 -0800 Subject: [PATCH 34/97] fix(server): gh credential lookups no longer leak D-Bus daemons (#23824) Co-authored-by: HelixNebula <249811984+helixnebulatech@users.noreply.github.com> --- .../src/server/GitHubAppSignIn.test.ts | 2 + .../src/server/GitHubCredentials.test.ts | 2 + .../src/server/GitHubCredentials.ts | 3 +- .../src/server/GitHubRest.test.ts | 2 + .../src/server/GitHubSourceControlProvider.ts | 3 +- .../src/server/gitHubCliProcess.test.ts | 116 ++++++++++++++++++ .../src/server/gitHubCliProcess.ts | 63 ++++++++++ .../src/server/gitHubDiscovery.test.ts | 3 + 8 files changed, 192 insertions(+), 2 deletions(-) create mode 100644 packages/source-control-github/src/server/gitHubCliProcess.test.ts create mode 100644 packages/source-control-github/src/server/gitHubCliProcess.ts diff --git a/packages/source-control-github/src/server/GitHubAppSignIn.test.ts b/packages/source-control-github/src/server/GitHubAppSignIn.test.ts index 2f78a3aab83e9..c42175d35b898 100644 --- a/packages/source-control-github/src/server/GitHubAppSignIn.test.ts +++ b/packages/source-control-github/src/server/GitHubAppSignIn.test.ts @@ -3,6 +3,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "@effect/vitest" import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as Fiber from "effect/Fiber"; +import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Redacted from "effect/Redacted"; @@ -113,6 +114,7 @@ function harness(options: { Layer.provideMerge(SourceControlRateLimit.layer), Layer.provideMerge(options.settingsWritesFail === true ? failingWrites : host), Layer.provide(NodeCrypto.layer), + Layer.provide(FileSystem.layerNoop({})), Layer.provide(Layer.succeed(HttpClient.HttpClient, http)), ); return { layer, requests }; diff --git a/packages/source-control-github/src/server/GitHubCredentials.test.ts b/packages/source-control-github/src/server/GitHubCredentials.test.ts index 88d37393c83e0..5601edaa8b308 100644 --- a/packages/source-control-github/src/server/GitHubCredentials.test.ts +++ b/packages/source-control-github/src/server/GitHubCredentials.test.ts @@ -1,6 +1,7 @@ import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import { afterEach, beforeEach, describe, expect, it, vi } from "@effect/vitest"; import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Redacted from "effect/Redacted"; import { HttpClient } from "effect/http"; @@ -63,6 +64,7 @@ function harness( }), ), Layer.provide(NodeCrypto.layer), + Layer.provide(FileSystem.layerNoop({})), Layer.provide( Layer.succeed( HttpClient.HttpClient, diff --git a/packages/source-control-github/src/server/GitHubCredentials.ts b/packages/source-control-github/src/server/GitHubCredentials.ts index cbecc95676cff..f29d182344ca0 100644 --- a/packages/source-control-github/src/server/GitHubCredentials.ts +++ b/packages/source-control-github/src/server/GitHubCredentials.ts @@ -23,6 +23,7 @@ import { } from "@t3tools/contracts"; import * as GitHubClient from "../shared/definition.ts"; +import { makeGhProcess } from "./gitHubCliProcess.ts"; /** * Every gh run on the server shares this. A burst of them (a status poll across many checkouts) @@ -149,7 +150,7 @@ export function environmentToken( /** @public */ export const make = Effect.gen(function* () { const sourceControlHost = yield* SourceControlHost.SourceControlHost; - const process = sourceControlHost.process; + const process = yield* makeGhProcess; const crypto = yield* Digest.Digest; const environment = yield* HostProcess.Environment; const workingDirectory = yield* HostProcess.WorkingDirectory; diff --git a/packages/source-control-github/src/server/GitHubRest.test.ts b/packages/source-control-github/src/server/GitHubRest.test.ts index 5ce3ebe690545..460bfbc16d82c 100644 --- a/packages/source-control-github/src/server/GitHubRest.test.ts +++ b/packages/source-control-github/src/server/GitHubRest.test.ts @@ -10,6 +10,7 @@ import * as NodeOS from "node:os"; import * as NodePath from "node:path"; import * as HostProcess from "@t3tools/shared/HostProcess"; import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Redacted from "effect/Redacted"; import * as TestClock from "effect/testing/TestClock"; @@ -611,6 +612,7 @@ describe("GitHubCredentials", () => { GitHubCredentials.layer.pipe( Layer.provide(TestSourceControlHost.layer({ process: { run } })), Layer.provide(NodeCrypto.layer), + Layer.provide(FileSystem.layerNoop({})), Layer.provide(Layer.succeed(HttpClient.HttpClient, unexpectedHttp)), ); diff --git a/packages/source-control-github/src/server/GitHubSourceControlProvider.ts b/packages/source-control-github/src/server/GitHubSourceControlProvider.ts index e657240f4cc94..f69e06fedc663 100644 --- a/packages/source-control-github/src/server/GitHubSourceControlProvider.ts +++ b/packages/source-control-github/src/server/GitHubSourceControlProvider.ts @@ -68,6 +68,7 @@ import { } from "@t3tools/source-control-core/shared/definition"; import * as GitHubClient from "../shared/definition.ts"; +import { makeGhProcess } from "./gitHubCliProcess.ts"; import { PullRequestByNumber, PullRequestNode, @@ -215,7 +216,7 @@ function environmentTokenVariable(environment: NodeJS.ProcessEnv): string | null export const makeDiscovery = Effect.gen(function* () { const api = yield* GitHubRest.GitHubRest; const sourceControlHost = yield* SourceControlHost.SourceControlHost; - const process = sourceControlHost.process; + const process = yield* makeGhProcess; const environment = yield* HostProcess.Environment; const appSignIn = yield* GitHubAppSignIn.GitHubAppSignIn; const offerAppSignIn = (item: A): A => diff --git a/packages/source-control-github/src/server/gitHubCliProcess.test.ts b/packages/source-control-github/src/server/gitHubCliProcess.test.ts new file mode 100644 index 0000000000000..587fb6e5d900b --- /dev/null +++ b/packages/source-control-github/src/server/gitHubCliProcess.test.ts @@ -0,0 +1,116 @@ +import { describe, expect, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Layer from "effect/Layer"; +import * as PlatformError from "effect/PlatformError"; +import { ChildProcessSpawner } from "effect/process"; + +import * as HostProcess from "@t3tools/shared/HostProcess"; +import type * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost"; +import * as TestSourceControlHost from "@t3tools/source-control-testing/TestSourceControlHost"; +import { makeGhProcess } from "./gitHubCliProcess.ts"; + +function spawnedBusAddress(input: { + readonly platform?: NodeJS.Platform; + readonly address?: string; + readonly spawnAddress?: string; + /** File contents by path; a path not listed does not exist. */ + readonly files?: Readonly>; + /** A path that exists but cannot be stat'ed or read. */ + readonly unreadable?: string; +}) { + const files = input.files ?? {}; + const denied = (path: string, method: string) => + Effect.fail( + PlatformError.systemError({ + _tag: path === input.unreadable ? "PermissionDenied" : "NotFound", + module: "FileSystem", + method, + pathOrDescriptor: path, + }), + ); + const envs: Array = []; + const run: SourceControlHost.SourceControlHost["Service"]["process"]["run"] = (spawn) => + Effect.sync(() => { + envs.push(spawn.env); + return { + exitCode: ChildProcessSpawner.ExitCode(0), + stdout: "", + stderr: "", + stdoutTruncated: false, + stderrTruncated: false, + }; + }); + return Effect.gen(function* () { + const gh = yield* makeGhProcess; + yield* gh.run({ + operation: "test", + command: "gh", + args: ["auth", "status"], + cwd: "/", + ...(input.spawnAddress === undefined + ? {} + : { env: { DBUS_SESSION_BUS_ADDRESS: input.spawnAddress } }), + }); + return envs[0]?.DBUS_SESSION_BUS_ADDRESS; + }).pipe( + Effect.provide( + Layer.mergeAll( + TestSourceControlHost.layer({ process: { run } }), + FileSystem.layerNoop({ + exists: (path) => + path === input.unreadable ? denied(path, "exists") : Effect.succeed(path in files), + readFileString: (path) => + path in files ? Effect.succeed(files[path]!) : denied(path, "readFileString"), + }), + ), + ), + Effect.provideService(HostProcess.Platform, input.platform ?? "linux"), + Effect.provideService(HostProcess.UserId, 1000), + Effect.provideService( + HostProcess.Environment, + input.address === undefined ? {} : { DBUS_SESSION_BUS_ADDRESS: input.address }, + ), + ); +} + +describe("makeGhProcess", () => { + it.effect("turns the bus off when godbus would have to autolaunch one", () => + Effect.gen(function* () { + expect(yield* spawnedBusAddress({})).toBe("disabled:"); + expect(yield* spawnedBusAddress({ address: "autolaunch:" })).toBe("disabled:"); + expect(yield* spawnedBusAddress({ spawnAddress: "autolaunch:" })).toBe("disabled:"); + // A spawn that clears the host's address leaves godbus nothing to use either. + expect(yield* spawnedBusAddress({ address: "unix:path=/tmp/bus", spawnAddress: "" })).toBe( + "disabled:", + ); + // godbus ignores a `dbus-session` file it cannot read or that names no address. + const session = "/run/user/1000/dbus-session"; + expect(yield* spawnedBusAddress({ unreadable: session })).toBe("disabled:"); + expect(yield* spawnedBusAddress({ files: { [session]: "garbage\n" } })).toBe("disabled:"); + expect( + yield* spawnedBusAddress({ files: { [session]: "DBUS_SESSION_BUS_ADDRESS=\r\n" } }), + ).toBe("disabled:"); + }), + ); + + it.effect("leaves a bus godbus can find or was given", () => + Effect.gen(function* () { + expect(yield* spawnedBusAddress({ files: { "/run/user/1000/bus": "" } })).toBeUndefined(); + expect( + yield* spawnedBusAddress({ + files: { + "/run/user/1000/dbus-session": "DBUS_SESSION_BUS_ADDRESS=unix:abstract=/tmp/dbus-x\n", + }, + }), + ).toBeUndefined(); + expect(yield* spawnedBusAddress({ address: "unix:path=/tmp/bus" })).toBeUndefined(); + expect(yield* spawnedBusAddress({ spawnAddress: "unix:path=/tmp/bus" })).toBe( + "unix:path=/tmp/bus", + ); + expect(yield* spawnedBusAddress({ platform: "darwin" })).toBeUndefined(); + // godbus counts a socket it cannot stat as present, so an unreadable one is left alone too. + expect(yield* spawnedBusAddress({ unreadable: "/run/user/1000/bus" })).toBeUndefined(); + }), + ); +}); diff --git a/packages/source-control-github/src/server/gitHubCliProcess.ts b/packages/source-control-github/src/server/gitHubCliProcess.ts new file mode 100644 index 0000000000000..084599e136041 --- /dev/null +++ b/packages/source-control-github/src/server/gitHubCliProcess.ts @@ -0,0 +1,63 @@ +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; + +import * as HostProcess from "@t3tools/shared/HostProcess"; +import * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost"; + +const SESSION_ADDRESS_PREFIX = "DBUS_SESSION_BUS_ADDRESS="; + +/** + * gh reads its keyring through godbus, which autolaunches a `dbus-launch` daemon that outlives gh + * when no session bus is configured or discoverable. On WSL and headless hosts each lookup leaks one + * until inotify runs out, so only then turn the bus off and let the keyring read fail. + */ +export const makeGhProcess = Effect.gen(function* () { + const { process } = yield* SourceControlHost.SourceControlHost; + const fileSystem = yield* FileSystem.FileSystem; + const environment = yield* HostProcess.Environment; + const platform = yield* HostProcess.Platform; + const userId = yield* HostProcess.UserId; + + const noBusToDiscover = Effect.gen(function* () { + if (platform === "darwin" || userId === undefined) return false; + const runtimeDir = `/run/user/${userId}`; + // godbus takes the bus socket if stat finds anything there, but uses `dbus-session` only + // when it reads as `DBUS_SESSION_BUS_ADDRESS=
`; otherwise it still autolaunches. + if (yield* fileSystem.exists(`${runtimeDir}/bus`).pipe(Effect.orElseSucceed(() => true))) { + return false; + } + const session = yield* fileSystem + .readFileString(`${runtimeDir}/dbus-session`) + .pipe(Effect.orElseSucceed(() => "")); + if (!session.startsWith(SESSION_ADDRESS_PREFIX)) return true; + // Trailing line breaks are not an address; a loop keeps this linear on a malformed file. + let end = session.length; + while ( + end > SESSION_ADDRESS_PREFIX.length && + (session[end - 1] === "\n" || session[end - 1] === "\r") + ) { + end--; + } + return end === SESSION_ADDRESS_PREFIX.length; + }); + + return { + run: (input) => { + // The spawn's own env extends the host's, so its address is the one gh will see. + const address = + input.env !== undefined && "DBUS_SESSION_BUS_ADDRESS" in input.env + ? input.env.DBUS_SESSION_BUS_ADDRESS + : environment.DBUS_SESSION_BUS_ADDRESS; + if (address && address !== "autolaunch:") return process.run(input); + return noBusToDiscover.pipe( + Effect.flatMap((missing) => + process.run( + missing + ? { ...input, env: { ...input.env, DBUS_SESSION_BUS_ADDRESS: "disabled:" } } + : input, + ), + ), + ); + }, + } satisfies SourceControlHost.SourceControlHost["Service"]["process"]; +}); diff --git a/packages/source-control-github/src/server/gitHubDiscovery.test.ts b/packages/source-control-github/src/server/gitHubDiscovery.test.ts index 3c34ddd05bb84..f45afb5ec8db2 100644 --- a/packages/source-control-github/src/server/gitHubDiscovery.test.ts +++ b/packages/source-control-github/src/server/gitHubDiscovery.test.ts @@ -2,6 +2,7 @@ import { ServerSettings, SourceControlProviderKind } from "@t3tools/contracts"; import * as HostProcess from "@t3tools/shared/HostProcess"; import { assert, it } from "@effect/vitest"; import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Redacted from "effect/Redacted"; @@ -29,6 +30,7 @@ const makeDiscovery = (credential: GitHubRest.GitHubRest["Service"]["credential" Layer.mock(GitHubRest.GitHubRest)({ credential }), Layer.mock(GitHubAppSignIn.GitHubAppSignIn)({ enabled: false }), TestSourceControlHost.layer(), + FileSystem.layerNoop({}), ), ), Effect.provideService(HostProcess.Environment, {}), @@ -155,6 +157,7 @@ it.effect.each([ }, }), Layer.mock(GitHubAppSignIn.GitHubAppSignIn)({ enabled: false }), + FileSystem.layerNoop({}), Layer.effect( SourceControlHost.SourceControlHost, Effect.gen(function* () { From eb62a3715059bfb8c836c8999fbd3615e363210c Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 19 Nov 2026 12:13:25 -0800 Subject: [PATCH 35/97] fix(shared): atomic saves preserve file modes and sync to disk (#24310) --- apps/server/src/telemetry/Identify.test.ts | 33 +-- packages/shared/src/atomicWrite.test.ts | 270 +++++++++++++++++---- packages/shared/src/atomicWrite.ts | 55 ++++- 3 files changed, 288 insertions(+), 70 deletions(-) diff --git a/apps/server/src/telemetry/Identify.test.ts b/apps/server/src/telemetry/Identify.test.ts index 6a0951875106f..b888e07641d81 100644 --- a/apps/server/src/telemetry/Identify.test.ts +++ b/apps/server/src/telemetry/Identify.test.ts @@ -105,21 +105,26 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("telemetry identi const path = yield* Path.Path; const tornWrites = FileSystem.FileSystem.of({ ...fileSystem, - writeFileString: (filePath, data, options) => - fileSystem - .writeFileString(filePath, data.slice(0, Math.floor(data.length / 2)), options) - .pipe( - Effect.andThen( - Effect.fail( - PlatformError.systemError({ - _tag: "WriteZero", - module: "FileSystem", - method: "writeFileString", - pathOrDescriptor: filePath, - }), - ), - ), + open: (filePath, options) => + fileSystem.open(filePath, options).pipe( + Effect.map((file): FileSystem.File => + Object.assign(Object.create(file), { + writeAll: (buffer: Uint8Array) => + file.writeAll(buffer.subarray(0, Math.floor(buffer.length / 2))).pipe( + Effect.andThen( + Effect.fail( + PlatformError.systemError({ + _tag: "WriteZero", + module: "FileSystem", + method: "writeAll", + pathOrDescriptor: filePath, + }), + ), + ), + ), + }), ), + ), }); const identity = yield* Identify.getTelemetryIdentityForHome( diff --git a/packages/shared/src/atomicWrite.test.ts b/packages/shared/src/atomicWrite.test.ts index f0e3bc129cf0a..83a8b9682d232 100644 --- a/packages/shared/src/atomicWrite.test.ts +++ b/packages/shared/src/atomicWrite.test.ts @@ -191,6 +191,231 @@ it.layer(NodeServices.layer)("writeFileStringAtomically", (it) => { assert.deepStrictEqual(yield* fs.readDirectory(root), ["settings.json"]); }), ); + + // Read-only and unreadable targets still save, since the mode lands after the temp file opens. + it.effect.each(HostProcess.Platform.defaultValue() === "win32" ? [] : ["644", "444", "000"])( + "keeps the %s permissions of the file it replaces", + (octal) => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-atomic-write-" }); + const filePath = path.join(root, "settings.json"); + const mode = Number.parseInt(octal, 8); + yield* fs.writeFileString(filePath, "before"); + yield* fs.chmod(filePath, mode); + + yield* writeFileStringAtomically({ filePath, contents: "after" }); + + assert.strictEqual((yield* fs.stat(filePath)).mode & 0o777, mode); + yield* fs.chmod(filePath, 0o600); + assert.strictEqual(yield* fs.readFileString(filePath), "after"); + }), + ); + + it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")( + "creates a new file readable only by its owner", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-atomic-write-" }); + const filePath = path.join(root, "settings.json"); + + yield* writeFileStringAtomically({ filePath, contents: "fresh" }); + + assert.strictEqual(((yield* fs.stat(filePath)).mode & 0o777).toString(8), "600"); + }), + ); + + // Root ignores the missing read bit, so only a regular user sees the failure. + it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32" || process.getuid?.() === 0)( + "saves when the umask removes owner read access", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-atomic-write-" }); + const filePath = path.join(root, "settings.json"); + yield* fs.writeFileString(filePath, "before"); + yield* fs.chmod(filePath, 0o600); + yield* Effect.acquireRelease( + Effect.sync(() => process.umask(0o400)), + (previous) => Effect.sync(() => process.umask(previous)), + ); + + yield* writeFileStringAtomically({ filePath, contents: "after" }); + + assert.strictEqual(yield* fs.readFileString(filePath), "after"); + assert.strictEqual((yield* fs.stat(filePath)).mode & 0o777, 0o600); + }), + ); + + it.effect("syncs the contents before the rename and the directory after it", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-atomic-write-" }); + const filePath = path.join(root, "settings.json"); + const events: Array = []; + const recording = FileSystem.make({ + ...fs, + open: (openedPath, options) => + fs.open(openedPath, options).pipe( + // The real handle keeps its methods on its prototype, so it is extended, not spread. + Effect.map((file): FileSystem.File => + Object.create(file, { + sync: { + value: file.sync.pipe( + Effect.tap(() => + Effect.sync(() => { + events.push(openedPath === root ? "sync directory" : "sync temp file"); + }), + ), + ), + }, + }), + ), + ), + rename: (from, to) => + fs + .rename(from, to) + .pipe( + Effect.tap(() => + Effect.sync(() => + events.push(from === filePath ? "rename target" : "rename temp file"), + ), + ), + ), + }); + + yield* writeFileStringAtomically({ filePath, contents: "after" }).pipe( + Effect.provideService(FileSystem.FileSystem, recording), + ); + + assert.strictEqual(yield* fs.readFileString(filePath), "after"); + // Windows cannot open a directory to sync it. + assert.deepStrictEqual( + events, + HostProcess.Platform.defaultValue() === "win32" + ? ["sync temp file", "rename temp file"] + : ["sync temp file", "rename temp file", "sync directory"], + ); + }), + ); + + // EIO means the rename may not survive a crash; ENOTSUP means directories cannot sync at all. + it.effect.each( + HostProcess.Platform.defaultValue() === "win32" + ? [] + : [ + { code: "EIO", fails: true }, + { code: "ENOTSUP", fails: false }, + ], + )("handles a directory sync failing with $code after the rename", ({ code, fails }) => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-atomic-write-" }); + const filePath = path.join(root, "settings.json"); + const syncFailure = PlatformError.systemError({ + _tag: "Unknown", + module: "FileSystem", + method: "sync", + pathOrDescriptor: root, + cause: Object.assign(new Error(`${code}, fsync`), { code }), + }); + const failingDirectorySync = FileSystem.make({ + ...fs, + open: (openedPath, options) => + fs + .open(openedPath, options) + .pipe( + Effect.map((file): FileSystem.File => + openedPath === root + ? Object.create(file, { sync: { value: Effect.fail(syncFailure) } }) + : file, + ), + ), + }); + + const exit = yield* writeFileStringAtomically({ filePath, contents: "after" }).pipe( + Effect.provideService(FileSystem.FileSystem, failingDirectorySync), + Effect.exit, + ); + + assert.deepStrictEqual(exit, fails ? Exit.fail(syncFailure) : Exit.void); + assert.strictEqual(yield* fs.readFileString(filePath), "after"); + }), + ); + + // Injected because root ignores a chmod that drops read access. + it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")( + "saves when its directory cannot be opened for the sync", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-atomic-write-" }); + const filePath = path.join(root, "settings.json"); + yield* fs.writeFileString(filePath, "before"); + const openFailure = PlatformError.systemError({ + _tag: "PermissionDenied", + module: "FileSystem", + method: "open", + pathOrDescriptor: root, + }); + const unopenableDirectory = FileSystem.make({ + ...fs, + open: (openedPath, options) => + openedPath === root ? Effect.fail(openFailure) : fs.open(openedPath, options), + }); + + const exit = yield* writeFileStringAtomically({ filePath, contents: "after" }).pipe( + Effect.provideService(FileSystem.FileSystem, unopenableDirectory), + Effect.exit, + ); + + assert.deepStrictEqual(exit, Exit.void); + assert.strictEqual(yield* fs.readFileString(filePath), "after"); + }), + ); + + it.effect("succeeds when the write lands but its temp directory cannot be removed", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-atomic-write-" }); + const filePath = path.join(root, "settings.json"); + const removeAttempts: Array = []; + const unremovable = FileSystem.make({ + ...fs, + remove: (removedPath) => + Effect.suspend(() => { + removeAttempts.push(removedPath); + return Effect.fail( + PlatformError.systemError({ + _tag: "PermissionDenied", + module: "FileSystem", + method: "remove", + pathOrDescriptor: removedPath, + }), + ); + }), + }); + + yield* writeFileStringAtomically({ filePath, contents: "after" }).pipe( + Effect.provideService(FileSystem.FileSystem, unremovable), + ); + + assert.strictEqual(yield* fs.readFileString(filePath), "after"); + assert.strictEqual(removeAttempts.length, 1); + assert.deepStrictEqual( + (yield* fs.readDirectory(root)).toSorted(), + [path.basename(removeAttempts[0]!), "settings.json"].toSorted(), + ); + }), + ); }); const renameError = (code: string, path: string) => @@ -237,48 +462,3 @@ it.effect("surfaces an unreadable link instead of writing over it", () => ), ), ); - -it.effect("succeeds when the write lands but its temp directory cannot be removed", () => - Effect.gen(function* () { - const renamed: Array = []; - const removed: Array = []; - const fileSystem = FileSystem.layerNoop({ - readLink: (path) => - Effect.fail( - PlatformError.systemError({ - _tag: "NotFound", - module: "FileSystem", - method: "readLink", - pathOrDescriptor: path, - }), - ), - makeDirectory: () => Effect.void, - makeTempDirectory: () => Effect.succeed("/home/settings.json.abc123"), - writeFileString: () => Effect.void, - rename: (_from, to) => Effect.sync(() => void renamed.push(to)), - remove: (path) => - Effect.sync(() => void removed.push(path)).pipe( - Effect.andThen( - Effect.fail( - PlatformError.systemError({ - _tag: "PermissionDenied", - module: "FileSystem", - method: "remove", - pathOrDescriptor: path, - }), - ), - ), - ), - }); - - const result = yield* Effect.exit( - writeFileStringAtomically({ filePath: "/home/settings.json", contents: "after" }).pipe( - Effect.provide(Layer.mergeAll(Path.layer, fileSystem)), - ), - ); - - assert.deepStrictEqual(result, Exit.void); - assert.deepStrictEqual(renamed, ["/home/settings.json"]); - assert.deepStrictEqual(removed, ["/home/settings.json.abc123"]); - }), -); diff --git a/packages/shared/src/atomicWrite.ts b/packages/shared/src/atomicWrite.ts index febd1a98fbfca..4767374b89958 100644 --- a/packages/shared/src/atomicWrite.ts +++ b/packages/shared/src/atomicWrite.ts @@ -18,6 +18,21 @@ const LOCKED_RENAME_RETRIES = 20; const LOCKED_RENAME_RETRY_DELAY = "100 millis"; const CHUNK_WRITE_LENGTH = 1 << 20; +// Saves keep the replaced file's mode and create new files owner-only; chmod, since the umask narrows an open mode. +const replacedMode = (fs: FileSystem.FileSystem, targetPath: string) => + fs.stat(targetPath).pipe( + Effect.map((info) => info.mode & 0o777), + Effect.catchIf( + (error) => error.reason._tag === "NotFound", + () => Effect.succeed(0o600), + ), + ); + +const isUnsupportedSync = (error: PlatformError.PlatformError) => { + const code = (error.reason.cause as NodeJS.ErrnoException | undefined)?.code; + return code === "EINVAL" || code === "ENOTSUP" || code === "ENOSYS"; +}; + /** Resolves symlink targets before renaming so writes preserve the link. Iterable contents stream in bounded batches. */ export const writeFileStringAtomically = (input: { readonly filePath: string; @@ -42,15 +57,17 @@ export const writeFileStringAtomically = (input: { ); const tempPath = path.join(tempDirectory, "contents.tmp"); - const contents = input.contents; - if (typeof contents === "string") { - yield* fs.writeFileString(tempPath, contents); - } else { - // Closed before the rename, which Windows refuses for open files. - yield* Effect.scoped( - Effect.gen(function* () { - const file = yield* fs.open(tempPath, { flag: "w" }); - const encoder = new TextEncoder(); + // One write-only handle: a reopen fails when the umask or the chmod drops access. + // Without the sync, a crash soon after the rename can leave the target empty. + // Closed before the rename, which Windows refuses for open files. + yield* Effect.scoped( + Effect.gen(function* () { + const file = yield* fs.open(tempPath, { flag: "w" }); + const encoder = new TextEncoder(); + const contents = input.contents; + if (typeof contents === "string") { + yield* file.writeAll(encoder.encode(contents)); + } else { let batch: string[] = []; let batchLength = 0; for (const chunk of contents) { @@ -62,10 +79,26 @@ export const writeFileStringAtomically = (input: { batchLength = 0; } if (batchLength > 0) yield* file.writeAll(encoder.encode(batch.join(""))); - }), + } + if (platform !== "win32") { + yield* fs.chmod(tempPath, yield* replacedMode(fs, targetPath)); + } + yield* file.sync; + }), + ); + if (platform !== "win32") { + yield* fs.rename(tempPath, targetPath); + // Persists the rename. A directory without read access cannot be opened to sync, and + // replacing in one needs only write and search access, so that save stands. + return yield* fs.open(targetDirectory, { flag: "r" }).pipe( + Effect.flatMap((directory) => directory.sync), + Effect.scoped, + Effect.catchIf( + (error) => error.reason._tag === "PermissionDenied" || isUnsupportedSync(error), + (error) => Effect.logWarning(error), + ), ); } - if (platform !== "win32") return yield* fs.rename(tempPath, targetPath); // Stop retrying if another save changes the target; read-only targets also return permanent EPERM. const targetVersion = fs.stat(targetPath).pipe( From 5478e44cc900577de62e271a43c4c341a1268977 Mon Sep 17 00:00:00 2001 From: Ibrahim Elkamali Date: Thu, 19 Nov 2026 22:13:40 +0200 Subject: [PATCH 36/97] fix(claude): every repeated --plugin-dir launch argument loads its plugin (#38634) Co-authored-by: asssslay Co-authored-by: Julius Marminge --- .../Adapters/ClaudeAdapterV2.test.ts | 19 +++++++++-- .../Adapters/ClaudeAdapterV2.ts | 32 ++++++++++++++++++- 2 files changed, 48 insertions(+), 3 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts index fe7559f603aaa..70e0ad8cfa7bb 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts @@ -380,7 +380,7 @@ describe("ClaudeAdapterV2 runtime query policy", () => { assert.isUndefined(options.extraArgs?.["dangerously-skip-permissions"]); }); - it("passes every --add-dir launch directory to Claude", () => { + it("passes every --add-dir and --plugin-dir launch directory to Claude", () => { const options = ClaudeAdapterV2.makeClaudeQueryOptions({ modelSelection: CLAUDE_TEST_MODEL_SELECTION, nativeThreadId: "native-add-dir", @@ -389,7 +389,8 @@ describe("ClaudeAdapterV2 runtime query policy", () => { attachmentsDir: "/attachments", settings: { ...AUTO_COMPACT_CLAUDE_SETTINGS, - launchArgs: "--add-dir ../apps ../lib --verbose --add-dir=/shared", + launchArgs: + '--add-dir ../apps ../lib --verbose --add-dir=/shared --plugin-dir ./a --plugin-dir=./b.zip --append-system-prompt "--plugin-dir=./prompt"', }, }); assert.deepEqual(options.additionalDirectories, [ @@ -400,6 +401,20 @@ describe("ClaudeAdapterV2 runtime query policy", () => { "/shared", ]); assert.isUndefined(options.extraArgs?.["add-dir"]); + assert.deepEqual(options.plugins, [ + { type: "local", path: "./a" }, + { type: "local", path: "./b.zip" }, + ]); + assert.isUndefined(options.extraArgs?.["plugin-dir"]); + const bare = ClaudeAdapterV2.makeClaudeQueryOptions({ + modelSelection: CLAUDE_TEST_MODEL_SELECTION, + nativeThreadId: "native-bare-plugin-dir", + resume: false, + cwd: "/workspace", + settings: { ...AUTO_COMPACT_CLAUDE_SETTINGS, launchArgs: "--plugin-dir --verbose" }, + }); + assert.isUndefined(bare.plugins); + assert.isNull(bare.extraArgs?.["plugin-dir"]); }); it("gives delegated children Claude's subagent prompt cache TTL", () => { diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index c1f1eef7bc1ae..9ab5c94e26259 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -72,7 +72,7 @@ import type { // @effect-diagnostics-next-line nodeBuiltinImport:off -- the SDK takes a Node ChildProcess for the CLI. import * as NodeChildProcess from "node:child_process"; import * as NodeUtil from "node:util"; -import { parseCliArgs } from "@t3tools/shared/cliArgs"; +import { parseCliArgs, tokenizeCliArgs } from "@t3tools/shared/cliArgs"; import { fromLenientJson } from "@t3tools/shared/schemaJson"; import { claudeMcpToolName, @@ -358,6 +358,27 @@ export const CLAUDE_DEFAULT_INSTANCE_ID = defaultInstanceIdForDriver(CLAUDE_PROV // The Claude CLI takes the next token as this flag's value even when it starts with `--`. const claudeLaunchArgParseOptions = { valueFlags: ["append-system-prompt"] }; +// Claude's --plugin-dir is repeatable; parseCliArgs keeps only the last one. +function claudeLaunchArgPluginDirectories(launchArgs: string): ReadonlyArray { + const tokens = tokenizeCliArgs(launchArgs); + const directories: string[] = []; + for (let index = 0; index < tokens.length && tokens[index] !== "--"; index++) { + const token = tokens[index]!; + if (!token.startsWith("--") || token.includes("=")) { + if (token.startsWith("--plugin-dir=")) directories.push(token.slice("--plugin-dir=".length)); + continue; + } + const next = tokens[index + 1]; + const takesNext = + next !== undefined && + (!next.startsWith("--") || claudeLaunchArgParseOptions.valueFlags.includes(token.slice(2))); + if (!takesNext) continue; + if (token === "--plugin-dir") directories.push(next); + index++; + } + return directories; +} + const CLAUDE_SCRIPT_EXTENSIONS = [".js", ".mjs", ".tsx", ".ts", ".jsx"]; // The SDK has no control-request deadline; the CLI waits up to 30 s per MCP server. const CLAUDE_MCP_REGISTRATION_TIMEOUT = "90 seconds"; @@ -2225,6 +2246,8 @@ export function makeClaudeQueryOptions(input: { const { // claudeLaunchArgDirectories reads every --add-dir into additionalDirectories. "add-dir": _launchArgAddDir, + // claudeLaunchArgPluginDirectories reads every --plugin-dir into plugins. + "plugin-dir": launchArgPluginDir, "permission-mode": launchArgPermissionMode, "dangerously-skip-permissions": launchArgSkipPermissions, "append-system-prompt": launchArgAppendSystemPrompt, @@ -2248,6 +2271,10 @@ export function makeClaudeQueryOptions(input: { if (requestThinkingSummaries && extraArgs["thinking-display"] === undefined) { extraArgs["thinking-display"] = "summarized"; } + const pluginDirectories = + input.settings === undefined ? [] : claudeLaunchArgPluginDirectories(input.settings.launchArgs); + // A bare --plugin-dir still reaches Claude, which reports the missing path. + if (launchArgPluginDir === null) extraArgs["plugin-dir"] = null; const threadIdentity: ClaudeAgentSdkThreadIdentity = input.resume ? { resume: input.nativeThreadId } : { sessionId: input.nativeThreadId }; @@ -2379,6 +2406,9 @@ export function makeClaudeQueryOptions(input: { }, } : {}), + ...(pluginDirectories.length === 0 + ? {} + : { plugins: pluginDirectories.map((path) => ({ type: "local" as const, path })) }), ...(Object.keys(extraArgs).length === 0 ? {} : { extraArgs }), }; const additionalDirectories = [ From 6d6c4614aa009f0be00fbbd9142ae1f7a874a86f Mon Sep 17 00:00:00 2001 From: Svetlomir <60934699+SvetlomirB@users.noreply.github.com> Date: Thu, 19 Nov 2026 21:13:50 +0100 Subject: [PATCH 37/97] fix(server): request_secret opens a new card when a later run reuses a clientRequestId (#38167) Co-authored-by: Julius Marminge --- .../src/mcp/OrchestratorMcpService.test.ts | 70 +++++++++++++++++++ apps/server/src/mcp/OrchestratorMcpService.ts | 2 +- 2 files changed, 71 insertions(+), 1 deletion(-) diff --git a/apps/server/src/mcp/OrchestratorMcpService.test.ts b/apps/server/src/mcp/OrchestratorMcpService.test.ts index c384d9e0a46ac..0890d5de0340e 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.test.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.test.ts @@ -1950,6 +1950,76 @@ describe("OrchestratorMcpService provider resolution", () => { }), ); + // Command receipts dedupe by commandId, so a later run reusing the identity gets no card. + it.effect("opens a new secret card when a later run reuses a clientRequestId", () => + Effect.gen(function* () { + const runId = yield* Ref.make(parentRunId); + const pending = yield* Queue.unbounded<{ + readonly commandId: CommandId; + readonly turnItemId: string; + }>(); + const dependencies = Layer.mergeAll( + NodeServices.layer, + NodeCrypto.layer, + Layer.mock(ThreadManagementService.ThreadManagementService)({ + getThreadRecords: () => + Ref.get(runId).pipe( + Effect.map((id) => { + const projection = parentProjection([]); + return { + ...projection, + runs: projection.runs.map((run) => ({ ...run, id })), + turnItems: [], + }; + }), + ), + dispatch: (command) => { + if (command.type !== "secret_request.record") return Effect.die("Unexpected command"); + return ( + command.secretStatus === "pending" + ? Queue.offer(pending, { + commandId: command.commandId, + turnItemId: command.turnItemId, + }) + : Effect.void + ).pipe(Effect.as({} as never)); + }, + }), + ServerSettings.layerTest(), + providerRegistryLayer([]), + adapterRegistryLayer([]), + Layer.mock(ProjectService.ProjectService)({}), + Layer.mock(SecretRequests.SecretRequests)({}), + Layer.mock(RemoteDelegation.RemoteDelegation)({}), + Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), + ); + yield* Effect.gen(function* () { + const service = yield* OrchestratorMcpService.OrchestratorMcpService; + const ask = Effect.gen(function* () { + const call = yield* service + .requestSecret(scope, { + label: "Router API key", + reason: "Reads the firewall rules.", + clientRequestId: "router-key", + timeoutMs: 1_000, + }) + .pipe(Effect.forkChild); + const card = yield* Queue.take(pending); + yield* TestClock.adjust(Duration.seconds(1)); + assert.include(yield* Fiber.join(call), { status: "timed_out" }); + return card; + }); + + const first = yield* ask; + assert.deepEqual(yield* ask, first); + yield* Ref.set(runId, RunId.make("run:mcp-providers-parent-later")); + const later = yield* ask; + assert.notEqual(later.commandId, first.commandId); + assert.notEqual(later.turnItemId, first.turnItemId); + }).pipe(Effect.provide(layerOrchestratorService.pipe(Layer.provide(dependencies)))); + }), + ); + it.effect( "advertises orchestration capability from registered adapters rather than a driver allowlist", () => diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts index 35957b9db8b62..74599bbade796 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.ts @@ -2519,7 +2519,7 @@ const make = Effect.gen(function* () { } const runId = run.id; const nodeId = run.rootNodeId; - const key = yield* requestKey(input.clientRequestId); + const key = `${runId}:${yield* requestKey(input.clientRequestId)}`; const turnItemId = TurnItemId.make( `turn-item:secret-request:${stablePart(threadId)}:${stablePart(key)}`, ); From 47583f8682344a078c353eec01e95346bd770e8d Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 19 Nov 2026 12:14:03 -0800 Subject: [PATCH 38/97] fix(server): Codex goal turns after a server restart are paused instead of running unseen (#25935) --- .../Adapters/CodexAdapterV2.test.ts | 98 +++++++++++++++++++ .../Adapters/CodexAdapterV2.ts | 18 +++- 2 files changed, 115 insertions(+), 1 deletion(-) diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts index 05e83ec4c84f8..87f48cc671d1f 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts @@ -11906,6 +11906,104 @@ describe("CodexAdapterV2 post-settle continuation", () => { ), ), ); + + // regression: #21865 goal turns Codex continues after a server restart ran with no UI + it.effect.each(["decoded", "undecodable"] as const)( + "pauses a goal turn Codex starts on a resumed thread whose response is %s", + (resumeResponse) => + Effect.gen(function* () { + const transcript = makeCodexReplayTranscript({ + scenario: "goal-turn-after-resume", + entries: [ + ...sessionStart, + ...request( + 3, + "thread/resume", + { + threadId: nativeThreadId, + excludeTurns: true, + config: CodexAdapterV2.CODEX_THREAD_CONFIG, + }, + resumeResponse === "decoded" + ? { thread: { id: nativeThreadId, updatedAt: 1782622450 } } + : { thread: { id: nativeThreadId } }, + ), + notification("goal resumed", "thread/goal/updated", { + threadId: nativeThreadId, + turnId: null, + goal: codexGoal("active", 10), + }), + notification("goal continuation", "turn/started", { + threadId: nativeThreadId, + turn: makeCodexReplayTurn({ id: "orphan-goal-turn", status: "inProgress" }), + }), + ...request( + 4, + "thread/goal/set", + { threadId: nativeThreadId, status: "paused" }, + { goal: codexGoal("paused", 10) }, + ), + ...request( + 5, + "turn/interrupt", + { threadId: nativeThreadId, turnId: "orphan-goal-turn" }, + {}, + ), + notification("interrupted", "turn/completed", { + threadId: nativeThreadId, + turn: makeCodexReplayTurn({ id: "orphan-goal-turn", status: "interrupted" }), + }), + ], + }); + const requests: Array<[string, unknown]> = []; + const interrupted = yield* Deferred.make(); + const harness = yield* makeCodexReplayHarness( + transcript, + () => Effect.void, + (method, params) => + Effect.sync(() => { + requests.push([method, params]); + }).pipe( + Effect.andThen( + method === "turn/interrupt" + ? Deferred.succeed(interrupted, undefined) + : Effect.void, + ), + ), + ); + const resumed = yield* harness.runtime + .resumeThread({ + providerThread: harness.providerThread, + modelSelection: CODEX_TEST_MODEL_SELECTION, + runtimePolicy: CODEX_TEST_RUNTIME_POLICY, + }) + .pipe(Effect.exit); + assert.equal(Exit.isSuccess(resumed), resumeResponse === "decoded"); + yield* Deferred.await(interrupted); + const goalStatuses = () => + harness.events.flatMap((event) => + event.type === "provider_thread.updated" + ? [event.providerThread.goal?.status ?? null] + : [], + ); + yield* harness.until(() => goalStatuses().length > 0); + assert.deepEqual(goalStatuses(), ["active"]); + assert.deepEqual(requests.slice(-2), [ + ["thread/goal/set", { threadId: nativeThreadId, status: "paused" }], + ["turn/interrupt", { threadId: nativeThreadId, turnId: "orphan-goal-turn" }], + ]); + }).pipe( + Effect.scoped, + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); }); describe("Codex file-change approval paths", () => { diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts index f865802b023d2..f52d13e691c86 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts @@ -8001,11 +8001,24 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( : { runtimePolicy: threadInput.runtimePolicy }), }), }); + // Codex resumes an active goal's turns right after the response; own them before it. + const previousRoot = rootProviderThreads.get(nativeThreadId); + rootProviderThreads.set(nativeThreadId, threadInput.providerThread); + goalUpdatesHeld.add(nativeThreadId); const response = yield* ensureInitialized.pipe( Effect.andThen(resume), Effect.flatMap(decodeCodexResumeMetadata), + // Stay registered: a lost or undecodable response may still have resumed the thread. + Effect.onError(() => + Effect.suspend(() => { + if (previousRoot !== undefined) { + rootProviderThreads.set(nativeThreadId, previousRoot); + } + return releaseGoalUpdates(nativeThreadId); + }), + ), ); - return { + const resumed = { ...threadInput.providerThread, providerSessionId: input.providerSessionId, providerInstanceId: adapterOptions.instanceId, @@ -8018,6 +8031,9 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( nativeConversationHeadRef: threadInput.providerThread.nativeConversationHeadRef, updatedAt: codexTimestamp(response.thread.updatedAt), } satisfies OrchestrationV2ProviderThread; + rootProviderThreads.set(nativeThreadId, resumed); + yield* releaseGoalUpdates(nativeThreadId); + return rootProviderThreads.get(nativeThreadId) ?? resumed; }, (effect, threadInput) => effect.pipe( From 4c099280f60022e0d099afb8071fed0cd3bdb042 Mon Sep 17 00:00:00 2001 From: Lenori Date: Thu, 19 Nov 2026 21:14:14 +0100 Subject: [PATCH 39/97] fix(dev): dev runner never points a dev server at the live ~/.t3/userdata (#38807) Co-authored-by: Julius Marminge --- AGENTS.md | 2 +- docs/operations/development.md | 11 ++++++++++- scripts/dev-runner.test.ts | 5 ++++- scripts/dev-runner.ts | 6 +++++- 4 files changed, 20 insertions(+), 4 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 6d788cd6c9e20..2ce4be8b77640 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -80,7 +80,7 @@ The most common defect in this repo is a change that works on the path you teste - `vp i` installs. Worktrees get this from the t3.json setup script; if module resolution looks broken, it probably did not run. - Setup runs in the background. While `.t3/setup-running` names a live PID, wait for it and do not run `vp i`. It ends with `.t3/setup-done` or `.t3/setup-failed` (with the error tail). With no marker at all, setup never ran here, so run `vp i` yourself. -- `vp run dev` starts server and web. In a worktree, state defaults to that worktree's gitignored `.t3`, which deliberately outranks an ambient `T3CODE_HOME` so you cannot land on shared state by accident. An explicit `--home-dir` still wins. +- `vp run dev` starts server and web. In a worktree, state defaults to that worktree's gitignored `.t3`, which deliberately outranks an ambient `T3CODE_HOME` so you cannot land on shared state by accident. An explicit `--home-dir` still wins. A plain `git clone` is not a worktree: it shares `~/.t3/dev` with the main checkout and is not seeded. To isolate one, run `vp run migrate-dev-db --base-dir /.t3`, then `vp run dev --home-dir /.t3`. - Ports derive from the worktree path and are stable across restarts, but read the real ones from the `[dev-runner]` line since occupied ports shift. - Sharing over the tailnet is three steps: run `vp run dev --share` in the background, wait for the `pairingUrl:` line in its output, then give that full URL to an unpaired browser. Do not wire up `tailscale serve` by hand, open the URL yourself, or consume the user's pairing link. A browser with the reusable dev cookie can use the bare origin. If a normal one-time token was consumed, mint a fresh one with `node apps/server/src/bin.ts pair`. It carries standard scopes, while the startup URL carries admin scopes needed for Connections settings. - To reuse web dev auth across worktrees, configure one fixed `T3CODE_DEV_AUTH_TOKEN` in the main checkout's gitignored `.env`. The `t3.json` setup links that file into worktrees. Never commit or publish the token or a startup URL. See [Reusable dev credential](docs/operations/development.md#reusable-dev-credential). diff --git a/docs/operations/development.md b/docs/operations/development.md index 9523c253c7620..2e22dd6d3649f 100644 --- a/docs/operations/development.md +++ b/docs/operations/development.md @@ -60,10 +60,19 @@ Running `vp run dev` through an agent's own shell tool does not attach it to thi ### State and ports Linked worktrees default to their own `.t3/userdata`, even when `T3CODE_HOME` is set. -The main checkout defaults to `~/.t3/dev`. An explicit `--home-dir` wins in both cases. +Any other checkout, including the main checkout and every plain `git clone`, uses +`T3CODE_HOME` when it is set and otherwise `~/.t3/dev`, with default ports. Checkouts on +`~/.t3/dev` share one database, settings, and secrets, and only one of their servers can run +at a time. An explicit `--home-dir` wins in both cases. It and `T3CODE_HOME` store state in +`/userdata`. +A home of `~/.t3`, from either source, still selects `~/.t3/dev`, because `~/.t3/userdata` is +the live install. The first start in a worktree seeds its empty database from a read-only copy of `~/.t3/userdata/statev2.sqlite` if the source is at most 500 MiB. Larger sources warn and dev starts with an empty database. `--no-seed` or `T3CODE_DEV_SEED=0` skips seeding. +Seeding targets only a worktree's own `.t3`, so a plain clone or a `--home-dir` outside the +worktree starts empty. To give a clone its own seeded state, run +`vp run migrate-dev-db --base-dir /.t3` and then `vp run dev --home-dir /.t3`. To copy a larger source, run `vp run migrate-dev-db` with dev stopped. It may use substantial disk space before pruning. The first start in any checkout also builds the native resource monitor with Cargo when diff --git a/scripts/dev-runner.test.ts b/scripts/dev-runner.test.ts index 9d0f6ba70589d..99efdbf4e6737 100644 --- a/scripts/dev-runner.test.ts +++ b/scripts/dev-runner.test.ts @@ -549,6 +549,9 @@ it.layer(NodeServices.layer)("dev-runner", (it) => { assert.equal(yield* homeFor("~someone/t3-dev"), path.resolve("~someone/t3-dev")); assert.equal(yield* homeFor("relative/t3-dev"), path.resolve("relative/t3-dev")); assert.equal(yield* homeFor("/tmp/t3-dev"), path.resolve("/tmp/t3-dev")); + // An explicit ~/.t3 would put state in the live userdata; leaving it implicit selects ~/.t3/dev. + assert.equal(yield* homeFor("~/.t3"), undefined); + assert.equal(yield* homeFor("/home/dev/.t3/"), undefined); }), ); @@ -795,7 +798,7 @@ it.layer(NodeServices.layer)("dev-runner", (it) => { Effect.provideService(HostProcess.Platform, "linux"), Effect.provideService(HostProcess.WorkingDirectory, input.cwd), // No ~/.t3 here, so these runs never seed from this machine's install. - Effect.provideService(HostProcess.HomeDirectory, input.cwd), + Effect.provideService(HostProcess.HomeDirectory, NodePath.join(input.cwd, "home")), Effect.provideService( HostProcess.Environment, input.ambientHome === undefined ? {} : { T3CODE_HOME: input.ambientHome }, diff --git a/scripts/dev-runner.ts b/scripts/dev-runner.ts index fcd22cc5a061f..48e0d08bb2182 100644 --- a/scripts/dev-runner.ts +++ b/scripts/dev-runner.ts @@ -329,7 +329,11 @@ export const createDevRunnerEnv = Effect.fn("dev-runner.createDevRunnerEnv")(fun `http://${isDesktopMode ? DESKTOP_DEV_LOOPBACK_HOST : "localhost"}:${webPort}`, }; - if (configuredBaseDir !== undefined) { + const path = yield* Path.Path; + // The server stores an explicit home's state in userdata, which for ~/.t3 is the live + // install. Left implicit, dev state goes to ~/.t3/dev. + const isLiveHome = resolvedBaseDir === path.join(yield* HostProcess.HomeDirectory, ".t3"); + if (configuredBaseDir !== undefined && !isLiveHome) { output.T3CODE_HOME = resolvedBaseDir; } else { delete output.T3CODE_HOME; From 4fccab84a0e67a43f752bb87acd7e7302c418a7c Mon Sep 17 00:00:00 2001 From: Simone Date: Thu, 19 Nov 2026 21:14:35 +0100 Subject: [PATCH 40/97] fix(server): keep Codex apps and plugins off during text generation (#39086) Co-authored-by: Simone <185146821+Lucenx9@users.noreply.github.com> --- .../src/provider/codexLaunchArgs.test.ts | 28 ++++++++++++++----- apps/server/src/provider/codexLaunchArgs.ts | 24 ++++++++-------- .../CodexTextGeneration.test.ts | 5 ++-- .../src/textGeneration/CodexTextGeneration.ts | 3 ++ 4 files changed, 40 insertions(+), 20 deletions(-) diff --git a/apps/server/src/provider/codexLaunchArgs.test.ts b/apps/server/src/provider/codexLaunchArgs.test.ts index fd70cdbf5d2d4..969979551fd84 100644 --- a/apps/server/src/provider/codexLaunchArgs.test.ts +++ b/apps/server/src/provider/codexLaunchArgs.test.ts @@ -38,13 +38,27 @@ describe("codexExecLaunchArgs", () => { ); }); - it("drops launch args that enable user hooks", () => { - NodeAssert.deepStrictEqual( - codexExecLaunchArgs( - "--enable hooks --enable=hooks --enable codex_hooks --enable=codex_hooks --enable foo --disable hooks", - ), - ["--enable", "foo", "--disable", "hooks"], - ); + it("keeps user hooks, apps, and plugins off during text generation", () => { + const launchArgs = + "--enable hooks --enable=hooks --enable codex_hooks --enable=codex_hooks --enable apps --enable=apps --enable connectors --enable=connectors --enable plugins --enable=plugins --enable foo --disable hooks"; + NodeAssert.deepStrictEqual(codexExecLaunchArgs(launchArgs), [ + "--enable", + "foo", + "--disable", + "hooks", + ]); + NodeAssert.deepStrictEqual(codexMcpListLaunchArgs(launchArgs), [ + "--enable", + "hooks", + "--enable=hooks", + "--enable", + "codex_hooks", + "--enable=codex_hooks", + "--enable", + "foo", + "--disable", + "hooks", + ]); }); it("does not pair value-taking flags with adjacent flags", () => { diff --git a/apps/server/src/provider/codexLaunchArgs.ts b/apps/server/src/provider/codexLaunchArgs.ts index 1de1f6d09199a..ec18d287cb1db 100644 --- a/apps/server/src/provider/codexLaunchArgs.ts +++ b/apps/server/src/provider/codexLaunchArgs.ts @@ -63,17 +63,19 @@ const filterLaunchArgs = (launchArgs: string | undefined, allowed: LaunchArgFilt return kept; }; -const HOOK_FEATURES = new Set(["hooks", "codex_hooks"]); - -// Feature toggles beat config overrides, so a launch arg's hook enable would undo ours. -export const codexExecLaunchArgs = (launchArgs?: string) => { - const args = filterLaunchArgs(launchArgs, EXEC_FILTER); - return args.filter((arg, index) => { - if (arg.startsWith("--enable=")) return !HOOK_FEATURES.has(arg.slice("--enable=".length)); - if (arg === "--enable") return !HOOK_FEATURES.has(args[index + 1] ?? ""); - return !(args[index - 1] === "--enable" && HOOK_FEATURES.has(arg)); +const MCP_LIST_DISABLED_FEATURES = new Set(["apps", "connectors", "plugins"]); +const EXEC_DISABLED_FEATURES = new Set([...MCP_LIST_DISABLED_FEATURES, "hooks", "codex_hooks"]); + +// Codex can apply explicit --enable flags after trailing -c overrides. +const omitFeatureEnables = (args: ReadonlyArray, features: ReadonlySet) => + args.filter((arg, index) => { + if (arg.startsWith("--enable=")) return !features.has(arg.slice("--enable=".length)); + if (arg === "--enable") return !features.has(args[index + 1] ?? ""); + return !(args[index - 1] === "--enable" && features.has(arg)); }); -}; + +export const codexExecLaunchArgs = (launchArgs?: string) => + omitFeatureEnables(filterLaunchArgs(launchArgs, EXEC_FILTER), EXEC_DISABLED_FEATURES); export const codexMcpListLaunchArgs = (launchArgs?: string) => - filterLaunchArgs(launchArgs, MCP_LIST_FILTER); + omitFeatureEnables(filterLaunchArgs(launchArgs, MCP_LIST_FILTER), MCP_LIST_DISABLED_FEATURES); diff --git a/apps/server/src/textGeneration/CodexTextGeneration.test.ts b/apps/server/src/textGeneration/CodexTextGeneration.test.ts index 5d0fd95b455f0..9fc0e43f4f6e2 100644 --- a/apps/server/src/textGeneration/CodexTextGeneration.test.ts +++ b/apps/server/src/textGeneration/CodexTextGeneration.test.ts @@ -488,9 +488,10 @@ it.layer(layerCodexTextGenerationTest)("CodexTextGeneration", (it) => { withFakeCodexEnv( { output: JSON.stringify({ title: "Remove default shapes" }), - launchArgs: "--config features.plugins=true --config features.apps=true", + launchArgs: + "--config features.plugins=true --config features.apps=true --config features.connectors=true", requireArg: - "--config features.plugins=true --config features.apps=true --config features.plugins=false --config features.apps=false --ephemeral", + "--config features.plugins=true --config features.apps=true --config features.connectors=true --config features.connectors=false --config features.plugins=false --config features.apps=false --ephemeral", }, (textGeneration) => Effect.gen(function* () { diff --git a/apps/server/src/textGeneration/CodexTextGeneration.ts b/apps/server/src/textGeneration/CodexTextGeneration.ts index c9810e3cfe360..d1db00f7690f8 100644 --- a/apps/server/src/textGeneration/CodexTextGeneration.ts +++ b/apps/server/src/textGeneration/CodexTextGeneration.ts @@ -40,7 +40,10 @@ import * as HostProcess from "@t3tools/shared/HostProcess"; const CODEX_TIMEOUT_MS = 180_000; const CODEX_MCP_LIST_TIMEOUT_MS = 10_000; // Plugins/apps add MCP servers; use trailing config overrides because --disable loses to user -c flags. +// Codex also reads the legacy connectors key for apps. const CODEX_NO_PLUGIN_ARGS = [ + "--config", + "features.connectors=false", "--config", "features.plugins=false", "--config", From 1a51984153fd99c06d7f49846bac48c840a5a7d0 Mon Sep 17 00:00:00 2001 From: Entrpi <133157614+Entrpi@users.noreply.github.com> Date: Fri, 20 Nov 2026 07:15:24 +1100 Subject: [PATCH 41/97] fix(web): a tool call's diff names its files relative to the workspace (#32697) Co-authored-by: maria-rcks Co-authored-by: Julius Marminge --- apps/web/src/components/DiffPanel.tsx | 2 +- apps/web/src/lib/toolCallDiff.test.ts | 62 +++++++++++++++++++++++++++ apps/web/src/lib/toolCallDiff.ts | 44 ++++++++++++++++++- 3 files changed, 106 insertions(+), 2 deletions(-) diff --git a/apps/web/src/components/DiffPanel.tsx b/apps/web/src/components/DiffPanel.tsx index 77200799d6a74..f2902f8738d29 100644 --- a/apps/web/src/components/DiffPanel.tsx +++ b/apps/web/src/components/DiffPanel.tsx @@ -484,7 +484,7 @@ export default function DiffPanel({ const toolCallPreview = toolCallSelection && toolCallItem?.type === "file_change" - ? toolCallDiff(toolCallItem, messages) + ? toolCallDiff(toolCallItem, activeCwd, messages) : null; const selectedPatch = toolCallSelection ? toolCallPreview?.patch diff --git a/apps/web/src/lib/toolCallDiff.test.ts b/apps/web/src/lib/toolCallDiff.test.ts index 8efd08ddfa38e..93d205756119d 100644 --- a/apps/web/src/lib/toolCallDiff.test.ts +++ b/apps/web/src/lib/toolCallDiff.test.ts @@ -104,6 +104,68 @@ describe("toolCallDiff", () => { }); }); + it("names files under the workspace relative to it in headers only", () => { + const root = "/Users/me/project"; + const paths = (patch: string | undefined) => { + const rendered = getRenderablePatch(patch); + if (rendered?.kind !== "files") throw new Error("Expected a file diff"); + return rendered.files.map((file) => resolveFileDiffPath(file)); + }; + // Claude's Edit: absolute headers; hunk lines that look like headers keep the root. + const claude = `--- ${root}/docs/plan.md\n+++ ${root}/docs/plan.md\n@@ -2 +2 @@\n-- ${root}/x\n++ ${root}/y\n`; + const { patch } = toolCallDiff({ fileName: `${root}/docs/plan.md`, diffStr: claude }, root); + expect(paths(patch)).toEqual(["docs/plan.md"]); + expect(patch).toContain(`\n-- ${root}/x\n++ ${root}/y\n`); + // Synthesized headers, a trailing separator on the root, and a path outside it. + const hunk = "@@ -1 +1 @@\n-x\n+y\n"; + expect( + paths(toolCallDiff({ fileName: `${root}/src/a.ts`, diffStr: hunk }, `${root}/`).patch), + ).toEqual(["src/a.ts"]); + expect(paths(toolCallDiff({ fileName: "/elsewhere/b.ts", diffStr: hunk }, root).patch)).toEqual( + ["/elsewhere/b.ts"], + ); + // A relative path, and on POSIX a backslash that is part of a name, keep theirs. + for (const [fileName, workspace] of [ + ["repo/src/a.ts", "/repo"], + ["/repo/back/slash/a.ts", "/repo/back\\slash"], + ] as const) { + const diffStr = `--- ${fileName}\n+++ ${fileName}\n${hunk}`; + expect(toolCallDiff({ fileName, diffStr }, workspace).patch).toBe(diffStr); + } + const backslash = toolCallDiff( + { fileName: "/repo/back\\slash/a.ts", diffStr: hunk }, + "/repo/back\\slash", + ).patch; + expect(paths(backslash)).toEqual(["a.ts"]); + // Each file of a multi-file patch; a path that merely contains the root keeps it. + const twoFiles = [ + `diff --git a/${root}/a.ts b/${root}/a.ts`, + `--- a/${root}/a.ts`, + `+++ b/${root}/a.ts`, + hunk.trimEnd(), + `diff --git a/backup${root}/b.ts b/backup${root}/b.ts`, + `--- a/backup${root}/b.ts`, + `+++ b/backup${root}/b.ts`, + hunk, + ].join("\n"); + expect( + paths(toolCallDiff({ fileName: `${root}/a.ts`, diffStr: twoFiles }, root).patch), + ).toEqual(["a.ts", `backup${root}/b.ts`]); + // Only where a name starts: a quoted name with a space before the root. + expect( + paths(toolCallDiff({ fileName: `${root}/docs ${root}/a.md`, diffStr: hunk }, root).patch), + ).toEqual([`docs ${root}/a.md`]); + expect( + paths(toolCallDiff({ fileName: `/backup ${root}/a.md`, diffStr: hunk }, root).patch), + ).toEqual([`/backup ${root}/a.md`]); + // Windows paths, which a quoted header escapes, compared without case. + const windows = toolCallDiff( + { fileName: "C:\\repo\\src\\a.ts", diffStr: hunk }, + "c:\\repo", + ).patch; + expect(paths(windows)).toEqual(["src\\a.ts"]); + }); + it("preserves complete patches and unsupported provider output", () => { for (const operation of ["add", "delete"]) { const diffStr = [ diff --git a/apps/web/src/lib/toolCallDiff.ts b/apps/web/src/lib/toolCallDiff.ts index 83a59aa49f2b3..92873cda85ae6 100644 --- a/apps/web/src/lib/toolCallDiff.ts +++ b/apps/web/src/lib/toolCallDiff.ts @@ -53,6 +53,44 @@ function toolCallPatch(item: Pick + segment + .split("\\") + .map((text) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")) + .join(String.raw`\\\\?`), + ) + .join(separator); + const prefix = new RegExp(String.raw`^("?(?:[ab]/)?)${root}${separator}`, windows ? "i" : ""); + const relative = (name: string) => name.replace(prefix, "$1"); + let inHeader = true; + return patch + .split("\n") + .map((line) => { + if (line.startsWith("diff --git ")) { + inHeader = true; + // Split the names as Pierre's parser does, so a name containing a space stays whole. + const names = + /^diff --git ("a\/(?:[^"\\]|\\.)*"|a\/.+?) ("b\/(?:[^"\\]|\\.)*"|b\/.+?)$/.exec(line); + return names ? `diff --git ${relative(names[1]!)} ${relative(names[2]!)}` : line; + } + if (line.startsWith("@@")) inHeader = false; + const name = inHeader ? /^(---|\+\+\+)(\s+)(.*)$/.exec(line) : null; + return name ? `${name[1]}${name[2]}${relative(name[3]!)}` : line; + }) + .join("\n"); +} + function recordedText(value: string | undefined) { const suffix = "\n… output truncated for transport"; const truncated = value !== undefined && value.endsWith(suffix); @@ -61,6 +99,7 @@ function recordedText(value: string | undefined) { export function toolCallDiff( item: Pick, + workspaceRoot?: string, resolve: MessageResolver = m, ) { const diff = recordedText(item.diffStr); @@ -69,7 +108,10 @@ export function toolCallDiff( const before = recordedText(item.oldStr ?? (operation === "delete" ? emptyContent : undefined)); const after = recordedText(item.newStr ?? (operation === "add" ? emptyContent : undefined)); return { - patch: toolCallPatch({ ...item, ...(diff.text === undefined ? {} : { diffStr: diff.text }) }), + patch: relativeHeaderPaths( + toolCallPatch({ ...item, ...(diff.text === undefined ? {} : { diffStr: diff.text }) }), + workspaceRoot, + ), content: diff.text?.trim() ? [] : [ From c3e82a93fe73ab571fb6d8f5bbfedbf5b4d2eaa2 Mon Sep 17 00:00:00 2001 From: project516 <138796702+Project516@users.noreply.github.com> Date: Thu, 19 Nov 2026 14:15:36 -0600 Subject: [PATCH 42/97] fix(shared): T3 Connect no longer runs cloudflared releases that trust the compromised eMudhra intermediates (#26040) Co-authored-by: maria-rcks Co-authored-by: Julius Marminge --- docs/internals/t3-connect.md | 6 ++++-- packages/shared/src/relayClient.test.ts | 25 ++++++++++++++----------- packages/shared/src/relayClient.ts | 4 ++-- 3 files changed, 20 insertions(+), 15 deletions(-) diff --git a/docs/internals/t3-connect.md b/docs/internals/t3-connect.md index ebb5c55e9647b..ae3938fd0cd7b 100644 --- a/docs/internals/t3-connect.md +++ b/docs/internals/t3-connect.md @@ -197,8 +197,10 @@ The version comes from running `cloudflared version`, not from the folder name. Connectors from before `--no-autoupdate` replaced themselves in place, so a managed folder can hold another release. Such a binary still runs as a fallback while the pin installs. Every binary needs `CLOUDFLARED_MIN_VERSION`, the oldest -release that accepts every flag the connector is started with. Raise it whenever -a new flag is added. +release that accepts every flag the connector is started with and rejects the +compromised eMudhra intermediates. No binary below it runs, even as a fallback, +so a host without an eligible one stays off the relay until it has one. Raise it +whenever a new flag or security fix needs it. ## OAuth traps diff --git a/packages/shared/src/relayClient.test.ts b/packages/shared/src/relayClient.test.ts index 88559182143bf..594d5ad215b1a 100644 --- a/packages/shared/src/relayClient.test.ts +++ b/packages/shared/src/relayClient.test.ts @@ -682,7 +682,7 @@ describe("RelayClient", () => { ), ); - it.effect.skipIf(windowsHost)("skips a PATH binary older than the minimum version", () => { + it.effect.skipIf(windowsHost)("skips binaries older than the minimum version", () => { const versions: Record = {}; return run( (baseDir) => @@ -691,8 +691,11 @@ describe("RelayClient", () => { const newPath = `${baseDir}/new/cloudflared`; yield* writeExecutable(oldPath); yield* writeExecutable(newPath); - versions[oldPath] = "2023.8.2"; - versions[newPath] = RelayClient.CLOUDFLARED_MIN_VERSION; + const managed = managedPathFor(baseDir, "2026.10.0"); + yield* writeExecutable(managed); + versions[managed] = "2026.10.0"; + versions[oldPath] = "2026.10.2"; + versions[newPath] = "2026.10.3"; const manager = yield* RelayClient.makeCloudflaredRelayClient({ baseDir }); const env = { PATH: `${baseDir}/old:${baseDir}/new` }; expect( @@ -721,7 +724,7 @@ describe("RelayClient", () => { Effect.gen(function* () { const overridePath = `${baseDir}/override/cloudflared`; yield* writeExecutable(overridePath); - versions[overridePath] = "2025.6.0"; + versions[overridePath] = "2026.10.2"; const manager = yield* RelayClient.makeCloudflaredRelayClient({ baseDir }); const env = { PATH: "", T3CODE_CLOUDFLARED_PATH: overridePath }; const withEnv = Effect.provideService( @@ -754,9 +757,9 @@ describe("RelayClient", () => { const newerServer = managedPathFor(baseDir, "2099.1.0"); versions[newerServer] = "2099.1.0"; yield* writeExecutable(newerServer); - versions[pathBinary] = "2026.9.3"; + versions[pathBinary] = "2026.10.3"; versions[older] = "2025.9.0"; - versions[newer] = "2026.1.0"; + versions[newer] = "2026.10.3"; yield* writeExecutable(pathBinary); yield* writeExecutable(older); yield* writeExecutable(newer); @@ -769,7 +772,7 @@ describe("RelayClient", () => { Effect.provideService(HostProcess.Environment, { PATH: `${baseDir}/bin` }), ); - expect(yield* resolveWith).toMatchObject({ source: "managed", version: "2026.1.0" }); + expect(yield* resolveWith).toMatchObject({ source: "managed", version: "2026.10.3" }); yield* writeExecutable(pinned); expect(yield* resolveWith).toMatchObject({ @@ -784,11 +787,11 @@ describe("RelayClient", () => { ).toEqual(["2026.1.0", RelayClient.CLOUDFLARED_VERSION, "2099.1.0"]); yield* fileSystem.remove(pinned); - expect(yield* resolveWith).toMatchObject({ source: "managed", version: "2026.1.0" }); + expect(yield* resolveWith).toMatchObject({ source: "managed", version: "2026.10.3" }); yield* fileSystem.remove(`${baseDir}/tools/cloudflared/2026.1.0`, { recursive: true, }); - expect(yield* resolveWith).toMatchObject({ source: "path", version: "2026.9.3" }); + expect(yield* resolveWith).toMatchObject({ source: "path", version: "2026.10.3" }); }), { versions }, ); @@ -803,7 +806,7 @@ describe("RelayClient", () => { (baseDir) => Effect.gen(function* () { const pinned = managedPathFor(baseDir, RelayClient.CLOUDFLARED_VERSION); - versions[pinned] = "2026.9.3"; + versions[pinned] = "2026.10.3"; yield* writeExecutable(pinned); const manager = yield* RelayClient.makeCloudflaredRelayClient({ baseDir }); const resolved = yield* manager.resolve; @@ -811,7 +814,7 @@ describe("RelayClient", () => { status: "available", executablePath: pinned, source: "managed", - version: "2026.9.3", + version: "2026.10.3", }); expect( resolved.status === "available" && RelayClient.isPinnedManagedRelayClient(resolved), diff --git a/packages/shared/src/relayClient.ts b/packages/shared/src/relayClient.ts index e3cf71abbe1bf..19e42955ea554 100644 --- a/packages/shared/src/relayClient.ts +++ b/packages/shared/src/relayClient.ts @@ -29,8 +29,8 @@ import { isWindowsRenameLock } from "./atomicWrite.ts"; import * as HostProcess from "./HostProcess.ts"; export const CLOUDFLARED_VERSION = "2026.10.4"; -// Minimum for --output support; older connectors exit on that flag. -export const CLOUDFLARED_MIN_VERSION = "2025.6.1"; +// Minimum for --output support and the eMudhra fix, which 2026.10.2 macOS builds lack. +export const CLOUDFLARED_MIN_VERSION = "2026.10.3"; const CLOUDFLARED_PATH_ENV_NAME = "T3CODE_CLOUDFLARED_PATH"; const CLOUDFLARED_DOWNLOAD_TIMEOUT = "10 minutes"; From 56b077777468b247030bdb2ff9b0e42b58555520 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 19 Nov 2026 12:15:49 -0800 Subject: [PATCH 43/97] fix(evals): GPT evals use the configured Codex provider and CODEX_HOME (#38573) --- evals/mcp-tool-use/README.md | 2 +- evals/mcp-tool-use/run.ts | 2 +- evals/shared/proxy.ts | 38 +++++++++++++++++++++++++++--------- evals/test-signal/README.md | 2 +- 4 files changed, 32 insertions(+), 12 deletions(-) diff --git a/evals/mcp-tool-use/README.md b/evals/mcp-tool-use/README.md index 7004bcc65e163..c96a39259dc8e 100644 --- a/evals/mcp-tool-use/README.md +++ b/evals/mcp-tool-use/README.md @@ -13,7 +13,7 @@ pnpm mcp-tool-use --model claude-opus-5-5 --out runs/opus ``` - `ANTHROPIC_API_KEY` in the repo root `.env` pays for Claude models and the Haiku shell simulator. -- Codex models (`gpt-*` in `MODELS` in `run.ts`) go through a CLIProxyAPI server, set up as the `vibeproxy` model provider in `~/.codex/config.toml`. Keep the proxy under about 12 samples in flight across all runs. +- Codex models (`gpt-*` in `MODELS` in `run.ts`) go through a CLIProxyAPI server, set up as the Codex model provider: `model_provider` in `$CODEX_HOME/config.toml` (default `~/.codex/config.toml`) when it names a `[model_providers.]` table, otherwise `[model_providers.vibeproxy]`. That table needs `base_url` (the proxy's OpenAI-compatible URL, such as `http://localhost:8317/v1`) and a key in `experimental_bearer_token` or the variable named by `env_key`. Keep the proxy under about 12 samples in flight across all runs. - `--shell-model` picks the model that plays the shell: `claude-haiku-5-5` by default, or `gpt-6.1-terra` / `gpt-6-luna` through the same proxy, so Codex runs need no Anthropic key. Prefer Terra: Luna often contradicts the case's world (it calls named checkouts missing or files empty). Compare runs only when they used the same shell model. - Flags: `--case `, `--cases `, `--samples ` (default 2, and a 3rd when the first 2 disagree), `--concurrency ` (samples in flight, default 8), `--max-steps `, `--effort `, `--dry-run` (prints request bodies, no model calls), and `--context` (prints the size of T3's text and schemas, no key needed). - `--baseline --stop-on-regression` stops as soon as a case that passed every baseline sample fails. Use it to test one copy change against a baseline run. diff --git a/evals/mcp-tool-use/run.ts b/evals/mcp-tool-use/run.ts index eb40912e1a3f6..4157a6666262d 100644 --- a/evals/mcp-tool-use/run.ts +++ b/evals/mcp-tool-use/run.ts @@ -2802,7 +2802,7 @@ export const summarize = ( `- Pass: ${percent(passRate(rows))} of ${finished} samples.`, ...(errors.length > 0 ? [errorNote] : []), codex - ? "- Cost: the agent is not priced. `vibeproxy` in `~/.codex/config.toml` may use a subscription or bill an API key per token; agent tokens are below." + ? "- Cost: the agent is not priced. the Codex model provider (see README) may use a subscription or bill an API key per token; agent tokens are below." : `- Estimated cost $${cost.toFixed(2)}, $${(cost / rows.length).toFixed(3)} per sample.`, `- Agent tokens: ${agent.tokens}${codex ? "." : ` ($${agent.cost.toFixed(2)}).`}`, `- Shell simulator (${options.shellModel}) tokens: ${shell.tokens} (API-price estimate $${shell.cost.toFixed(2)}).`, diff --git a/evals/shared/proxy.ts b/evals/shared/proxy.ts index ede72be8fdab2..12ea4c150e80c 100644 --- a/evals/shared/proxy.ts +++ b/evals/shared/proxy.ts @@ -5,24 +5,41 @@ import * as Schema from "effect/Schema"; // Read credentials into memory only. Python's TOML parser avoids another runner dependency. const decodeProxyConfig = Schema.decodeUnknownSync( - Schema.Struct({ url: Schema.String, headers: Schema.Record(Schema.String, Schema.String) }), + Schema.Union([ + Schema.Struct({ error: Schema.String }), + Schema.Struct({ url: Schema.String, headers: Schema.Record(Schema.String, Schema.String) }), + ]), ); -/** Reads the `vibeproxy` CLIProxyAPI provider from `~/.codex/config.toml`. */ -export const proxyConfig = () => - decodeProxyConfig( +/** + * Reads the CLIProxyAPI provider from `$CODEX_HOME/config.toml` (default `~/.codex`): the + * configured `model_provider` when it is a custom provider, otherwise `vibeproxy`. + */ +export const proxyConfig = () => { + const config = decodeProxyConfig( JSON.parse( NodeChildProcess.execFileSync( "python3", [ "-c", ` -import json, os, pathlib, tomllib -home = pathlib.Path.home() / '.codex' -p = tomllib.loads((home / 'config.toml').read_text())['model_providers']['vibeproxy'] +import json, os, pathlib, sys, tomllib +home = pathlib.Path(os.environ.get('CODEX_HOME') or pathlib.Path.home() / '.codex') +def fail(message): + print(json.dumps({'error': message + ' The GPT evals call models through a CLIProxyAPI server set up as a custom model provider in Codex: set model_provider = "" and add [model_providers.] with base_url and its key.'})) + sys.exit() +path = home / 'config.toml' +if not path.is_file(): fail(f'No Codex config at {path}.') +config = tomllib.loads(path.read_text()) +providers = config.get('model_providers', {}) +name = config.get('model_provider') if config.get('model_provider') in providers else 'vibeproxy' +if name not in providers: fail(f'{path} has no custom model provider to use (model_provider is {config.get("model_provider", "unset")!r}).') +p = providers[name] +if not p.get('base_url'): fail(f'[model_providers.{name}] in {path} has no base_url.') h = p.get('http_headers', {}).copy() h.update({k: os.environ[v] for k,v in p.get('env_http_headers', {}).items()}) -key = os.environ[p['env_key']] if p.get('env_key') else p.get('experimental_bearer_token') -if not key and p.get('requires_openai_auth'): key = json.loads((home / 'auth.json').read_text()).get('OPENAI_API_KEY') +key = os.environ.get(p['env_key']) if p.get('env_key') else p.get('experimental_bearer_token') +if p.get('env_key') and not key: fail(f'[model_providers.{name}] in {path} reads its key from {p["env_key"]}, which is not set.') +if not key and p.get('requires_openai_auth') and (home / 'auth.json').is_file(): key = json.loads((home / 'auth.json').read_text()).get('OPENAI_API_KEY') if key: h['Authorization'] = 'Bearer ' + key print(json.dumps({'url': p['base_url'].rstrip('/'), 'headers': h})) `, @@ -31,3 +48,6 @@ print(json.dumps({'url': p['base_url'].rstrip('/'), 'headers': h})) ), ), ); + if ("error" in config) throw new Error(config.error); + return config; +}; diff --git a/evals/test-signal/README.md b/evals/test-signal/README.md index 0b1969618af86..4b40abe494724 100644 --- a/evals/test-signal/README.md +++ b/evals/test-signal/README.md @@ -12,7 +12,7 @@ pnpm test-signal --out runs/baseline pnpm test-signal --out runs/cut --prompt /path/to/variant.md --case new-table-row ``` -- Models go through the `vibeproxy` CLIProxyAPI provider in `~/.codex/config.toml`. Default models: `gpt-6.1-terra` and `gpt-6-luna`. Pass `--model` once per model to change them. +- Models go through a CLIProxyAPI server, set up as the Codex model provider: `model_provider` in `$CODEX_HOME/config.toml` (default `~/.codex/config.toml`) when it names a `[model_providers.]` table, otherwise `[model_providers.vibeproxy]`. That table needs `base_url` (the proxy's OpenAI-compatible URL, such as `http://localhost:8317/v1`) and a key in `experimental_bearer_token` or the variable named by `env_key`. Default models: `gpt-6.1-terra` and `gpt-6-luna`. Pass `--model` once per model to change them. - Flags: `--prompt ` (a variant of the check, default the real one), `--case ` (repeatable), `--samples ` (default 2, and a 3rd when the first 2 disagree), `--concurrency ` (default 6), `--reasoning ` (default `low`, as the check runs). - A bad case passes when a comment lands inside a target test. A guard case passes when the check posts nothing and replies exactly `All clear`. - `summary.md` gives the prompt hash and word count, then per model: bad cases caught, guards clean, errors, and tokens. From 54038e14eca280d7b5ff131fe8a146dd3e1efffc Mon Sep 17 00:00:00 2001 From: Fatih Yilmaz <40797475+yilmazff@users.noreply.github.com> Date: Thu, 19 Nov 2026 12:16:01 -0800 Subject: [PATCH 44/97] fix(pi): Pi agents get T3's pull request linking rules (#31727) Co-authored-by: maria-rcks Co-authored-by: Julius Marminge --- .../src/server/mcpExtensionSource.test.ts | 14 ++++++++++++++ .../provider-pi/src/server/mcpExtensionSource.ts | 7 +++++-- 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/packages/provider-pi/src/server/mcpExtensionSource.test.ts b/packages/provider-pi/src/server/mcpExtensionSource.test.ts index 6a909f4e374f9..63556422bf41a 100644 --- a/packages/provider-pi/src/server/mcpExtensionSource.test.ts +++ b/packages/provider-pi/src/server/mcpExtensionSource.test.ts @@ -5,6 +5,7 @@ import * as NodeOS from "node:os"; import * as NodeModule from "node:module"; import * as NodeVM from "node:vm"; import { assert, describe, it } from "@effect/vitest"; +import { PULL_REQUEST_LINKING_INSTRUCTIONS } from "@t3tools/provider-core/server/runtimeInstructions"; import { PI_T3_MCP_EXTENSION_SOURCE, PI_T3_SERVICE_TIER_COMMAND } from "./mcpExtensionSource.ts"; import { loadMcpBridge } from "./mcpBridge.testkit.ts"; @@ -79,8 +80,21 @@ describe("Pi orchestration prompt section", () => { assert.isDefined(result); assert.isTrue(result!.systemPrompt.startsWith(`${event.systemPrompt}\n\n`)); assert.include(result!.systemPrompt, "orchestrator_capabilities"); + assert.include(result!.systemPrompt, PULL_REQUEST_LINKING_INSTRUCTIONS); } }); + + it("sets the guidance section on Pi builds with prompt sections", async () => { + const bridge = await loadMcpBridge(); + const sections: Record = {}; + const result = await bridge.handlers.get("before_agent_start")!( + { systemPrompt: "base", systemPromptOptions: { sections } }, + { ui: { notify: assert.fail } }, + ); + assert.isUndefined(result); + assert.include(sections.t3_code_orchestration, "orchestrator_capabilities"); + assert.include(sections.t3_code_orchestration, PULL_REQUEST_LINKING_INSTRUCTIONS); + }); }); describe("Pi project trust", () => { diff --git a/packages/provider-pi/src/server/mcpExtensionSource.ts b/packages/provider-pi/src/server/mcpExtensionSource.ts index 0f137d0f4d4d0..2e7844a23ac94 100644 --- a/packages/provider-pi/src/server/mcpExtensionSource.ts +++ b/packages/provider-pi/src/server/mcpExtensionSource.ts @@ -1,5 +1,6 @@ // No T3 imports inside the string; resolve Pi and typebox from the user's Pi install. import { T3_CODE_ORCHESTRATION_INSTRUCTIONS } from "@t3tools/provider-core/server/orchestrationInstructions"; +import { PULL_REQUEST_LINKING_INSTRUCTIONS } from "@t3tools/provider-core/server/runtimeInstructions"; export const PI_T3_MCP_EXTENSION_FILENAME = "pi-t3-mcp-extension.ts"; @@ -24,6 +25,7 @@ const TOKEN_ENV = ${JSON.stringify(T3_MCP_BEARER_ENV)}; const RUNTIME_MODE_ENV = ${JSON.stringify(T3_PI_RUNTIME_MODE_ENV)}; const EXTENSION_PATH_ENV = ${JSON.stringify(T3_PI_MCP_EXTENSION_PATH_ENV)}; const ORCHESTRATION_INSTRUCTIONS = ${JSON.stringify(T3_CODE_ORCHESTRATION_INSTRUCTIONS.trim())}; +const PULL_REQUEST_LINKING_INSTRUCTIONS = ${JSON.stringify(PULL_REQUEST_LINKING_INSTRUCTIONS)}; const SERVICE_TIER_COMMAND = ${JSON.stringify(PI_T3_SERVICE_TIER_COMMAND)}; const PROTOCOL = "2025-06-18"; const READ_ONLY_TOOLS = new Set(["read", "grep", "find", "ls"]); @@ -497,13 +499,14 @@ export default async function t3McpExtension(pi: ExtensionAPI) { // Keep guidance in the system prompt so leading slash commands still expand. pi.on("before_agent_start", (event, ctx) => { reconcileDiscovery(ctx); + const instructions = ORCHESTRATION_INSTRUCTIONS + "\\n\\n" + PULL_REQUEST_LINKING_INSTRUCTIONS; const sections = event.systemPromptOptions?.sections; if (sections && typeof sections === "object" && event.systemPromptOptions?.forceSystemPrompt === undefined) { // A full prompt override bypasses Pi's later section rendering. - sections.t3_code_orchestration = ORCHESTRATION_INSTRUCTIONS; + sections.t3_code_orchestration = instructions; return undefined; } - return { systemPrompt: event.systemPrompt + "\\n\\n" + ORCHESTRATION_INSTRUCTIONS }; + return { systemPrompt: event.systemPrompt + "\\n\\n" + instructions }; }); } `; From 178a2f1cd4cd708532be5caa90bacc0d96c4fb6a Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 19 Nov 2026 12:16:15 -0800 Subject: [PATCH 45/97] fix(server): t3_thread_launch refuses a defaulted worktree launch when Git cannot read HEAD (#38459) --- .../src/mcp/toolkits/project/handlers.test.ts | 64 +++++++++++++++++++ .../src/mcp/toolkits/project/handlers.ts | 35 ++++++---- 2 files changed, 88 insertions(+), 11 deletions(-) diff --git a/apps/server/src/mcp/toolkits/project/handlers.test.ts b/apps/server/src/mcp/toolkits/project/handlers.test.ts index 8dff0fc012643..5c0f377c17bee 100644 --- a/apps/server/src/mcp/toolkits/project/handlers.test.ts +++ b/apps/server/src/mcp/toolkits/project/handlers.test.ts @@ -758,6 +758,70 @@ it.effect("a launch that omits its workspace follows the new-threads-in-a-worktr }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); +it.effect("a defaulted worktree launch stays shared only when Git says HEAD has no commit", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const commitArgs = ["-c", "user.email=t@t", "-c", "user.name=t", "commit", "--allow-empty"]; + for (const [checkout, expected] of [ + ["not a repository", "root"], + ["no commit yet", "root"], + ["branch tip object missing", "worktree"], + ["git refuses the repository", "refused"], + ] as const) { + const repo = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-launch-head-" }); + const launched: Array = []; + const { projectId, dependencies } = clientLaunchHarness({ + runtimeModeCeiling: "auto", + launched, + workspaceRoot: repo, + defaultThreadEnvMode: "worktree", + }); + const git = yield* GitVcsDriver.GitVcsDriver.pipe(Effect.provide(dependencies)); + if (checkout !== "not a repository") + yield* git.execute({ + operation: "test.setupRepo", + cwd: repo, + args: ["init", "-b", "main"], + }); + if (checkout === "branch tip object missing") + yield* fileSystem.writeFileString(`${repo}/.git/refs/heads/main`, `${"1".repeat(40)}\n`); + if (checkout === "git refuses the repository") { + yield* git.execute({ + operation: "test.setupRepo", + cwd: repo, + args: [...commitArgs, "-m", "init"], + }); + // Git quotes the broken file's path in its refusal; that path must not read as "not a repository". + yield* fileSystem.writeFileString(`${repo}/not a git repository`, "[core\n"); + yield* fileSystem.writeFileString( + `${repo}/.git/config`, + `[include]\n\tpath = ${repo}/not a git repository\n`, + ); + } + const toolkit = yield* ProjectToolkit.pipe( + Effect.provide( + McpToolAccess.HandlersLayer.layer(ProjectHandlers.layer).pipe( + Layer.provide(dependencies), + ), + ), + ); + const result = (yield* toolkit + .handle("t3_thread_launch", { title: "Fix", projectId }) + .pipe(Stream.unwrap, Stream.runCollect, Effect.provide(dependencies))).at(-1)?.result; + + if (expected === "refused") { + expect(result, checkout).toMatchObject({ code: "orchestration_error" }); + expect(launched, checkout).toHaveLength(0); + } else { + expect( + launched.map((launch) => launch.workspaceStrategy.type), + checkout, + ).toEqual([expected]); + } + } + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), +); + it.effect("a launch into a new worktree creates nothing when its branch collides", () => Effect.gen(function* () { const launched: Array = []; diff --git a/apps/server/src/mcp/toolkits/project/handlers.ts b/apps/server/src/mcp/toolkits/project/handlers.ts index 845a570b4e1c7..f4a401586a59e 100644 --- a/apps/server/src/mcp/toolkits/project/handlers.ts +++ b/apps/server/src/mcp/toolkits/project/handlers.ts @@ -116,6 +116,10 @@ const projectFileThreadEnvMode = Effect.fn("mcp.projectFileThreadEnvMode")(funct ).value; }); +// Anchored to the fatal line: other diagnostics, such as a dubious-ownership refusal, quote the path. +const NON_REPOSITORY_FATAL = + /^fatal: (?:not a git repository|gitfile does not point to a valid repository)/im; + /** Branches from the checkout's current branch, as the composer does; a checkout with no commit or a detached HEAD stays shared. */ const defaultWorktreeStrategy = Effect.fn("mcp.defaultWorktreeStrategy")(function* ( workspaceRoot: string, @@ -125,11 +129,25 @@ const defaultWorktreeStrategy = Effect.fn("mcp.defaultWorktreeStrategy")(functio GitVcsDriver.GitVcsDriver > { const git = yield* GitVcsDriver.GitVcsDriver; - const hasCommit = yield* git.resolveCommit({ cwd: workspaceRoot, revision: "HEAD" }).pipe( - Effect.as(true), - Effect.orElseSucceed(() => false), - ); - if (!hasCommit) return undefined; + const unreadable = new OrchestratorMcpFailure({ + code: "orchestration_error", + message: + "Could not read the project's current branch for the new worktree. No thread was created. Retry, or pass workspaceStrategy.", + }); + const commit = yield* git + .execute({ + operation: "mcp.defaultWorktreeStrategy", + cwd: workspaceRoot, + // Not peeled: a branch whose tip object is missing still resolves, so only an unborn HEAD exits 1. + args: ["rev-parse", "--verify", "--quiet", "HEAD"], + allowNonZeroExit: true, + timeoutMs: 5_000, + }) + .pipe(Effect.orElseSucceed(() => null)); + // Only Git saying "no commit yet" (exit 1) or "not a repository" keeps the launch shared. + if (commit?.exitCode === 1 || (commit !== null && NON_REPOSITORY_FATAL.test(commit.stderr))) + return undefined; + if (commit?.exitCode !== 0) return yield* unreadable; // symbolic-ref skips the index, so a held index lock cannot drop the launch into the shared checkout. const head = yield* git .execute({ @@ -142,12 +160,7 @@ const defaultWorktreeStrategy = Effect.fn("mcp.defaultWorktreeStrategy")(functio .pipe(Effect.orElseSucceed(() => null)); if (head?.exitCode === 1) return undefined; const branch = head?.exitCode === 0 ? head.stdout.trim() : ""; - if (branch.length === 0) - return yield* new OrchestratorMcpFailure({ - code: "orchestration_error", - message: - "Could not read the project's current branch for the new worktree. No thread was created. Retry, or pass workspaceStrategy.", - }); + if (branch.length === 0) return yield* unreadable; return { type: "worktree" as const, baseRef: branch }; }); From a8b57b07ea8dc1cd27caedc668eb9a534c6d736b Mon Sep 17 00:00:00 2001 From: Kwan Li <71382503+Kwan-Li@users.noreply.github.com> Date: Fri, 20 Nov 2026 06:16:29 +1000 Subject: [PATCH 46/97] fix(server): let parents revert after their subagents complete (#31874) Co-authored-by: Julius Marminge --- .../CheckpointRestoreSafety.test.ts | 145 ++++++++++++++++++ .../CheckpointRestoreSafety.ts | 106 ++++++++++++- docs/user/composer.md | 6 +- 3 files changed, 253 insertions(+), 4 deletions(-) diff --git a/apps/server/src/orchestration-v2/CheckpointRestoreSafety.test.ts b/apps/server/src/orchestration-v2/CheckpointRestoreSafety.test.ts index 145de122f387a..371a28763eaa1 100644 --- a/apps/server/src/orchestration-v2/CheckpointRestoreSafety.test.ts +++ b/apps/server/src/orchestration-v2/CheckpointRestoreSafety.test.ts @@ -252,3 +252,148 @@ it.effect.each([ assert.equal(result, isolated); }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); + +it.effect.each([ + { name: "completed child", isolated: true }, + { name: "completed native child", isolated: true }, + { name: "native child with running tool", isolated: false }, + { name: "native child with provider background task", isolated: false }, + { name: "native child with parent background task", isolated: false }, + { name: "native child with another provider parent task", isolated: true }, + { name: "native child grandchild with root background task", isolated: false }, + { name: "missing task record", isolated: false }, + { name: "task belongs to another child", isolated: false }, + { name: "completed child with pending task", isolated: false }, + { name: "grandchild through fork", isolated: false }, + { name: "completed grandchild", isolated: true }, + { name: "unrelated child", isolated: false }, + { name: "running child", isolated: false }, + { name: "held queue", isolated: false }, + { name: "failed child", isolated: false }, + { name: "cyclic ancestry", isolated: false }, +] as const)("parent file restore with $name: $isolated", ({ name, isolated }) => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const worktreePath = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-restore-child-" }); + const parentId = ThreadId.make("restore-parent"); + const childId = ThreadId.make("restore-child"); + const ancestorId = ThreadId.make("restore-ancestor"); + const child = { + id: childId, + projectId: ProjectId.make("restore-project"), + deletedAt: null, + worktreePath, + activeRunId: name === "running child" ? "child-run" : null, + activityRunStatus: null, + latestRunId: name.includes("native child") ? null : "child-run", + creationSource: name.includes("native child") ? "provider" : "user", + forkedFrom: { type: "node", nodeId: "child-task" }, + status: name.includes("native child") + ? "idle" + : name === "running child" + ? "running" + : name === "failed child" + ? "failed" + : "completed", + pendingRuntimeRequest: null, + pendingBackgroundTasks: [], + lineage: { + parentThreadId: + name === "completed grandchild" || + name === "native child grandchild with root background task" || + name === "grandchild through fork" || + name === "cyclic ancestry" + ? ancestorId + : name === "unrelated child" + ? ThreadId.make("another-parent") + : parentId, + relationshipToParent: "subagent", + rootThreadId: parentId, + }, + }; + const ancestor = { + ...child, + id: ancestorId, + forkedFrom: { type: "node", nodeId: "ancestor-task" }, + lineage: { + ...child.lineage, + relationshipToParent: name === "grandchild through fork" ? "fork" : "subagent", + parentThreadId: name === "cyclic ancestry" ? childId : parentId, + }, + }; + const children = + name === "completed grandchild" || + name === "native child grandchild with root background task" || + name === "grandchild through fork" || + name === "cyclic ancestry" + ? [child, ancestor] + : [child]; + const projections = { + getShellSnapshot: () => + Effect.succeed({ + threads: children, + archivedThreads: [], + }), + getCheckpointContext: () => + Effect.succeed({ + checkpointScopes: [], + runs: name === "held queue" ? [{ status: "queued" }] : [], + }), + getThreadProviderContext: () => Effect.succeed({ providerSessions: [] }), + getThreadRecords: ( + _threadId: unknown, + _fields: readonly string[], + filter: { subagentIds?: string[]; turnItemStatuses?: string[] } = {}, + ) => + Effect.succeed({ + providerThreads: + _threadId === parentId && + (name.includes("parent") || + name === "native child grandchild with root background task") && + name.includes("native child") + ? [ + { + providerInstanceId: + name === "native child with another provider parent task" + ? "other-provider" + : "claude", + status: "idle", + pendingBackgroundTasks: [{ taskId: "background", kind: "command" }], + }, + ] + : name === "native child with provider background task" + ? [{ status: "idle", pendingBackgroundTasks: [{ taskId: "background" }] }] + : [], + turnItems: + filter.turnItemStatuses !== undefined && name === "native child with running tool" + ? [{ type: "command_execution", status: "running" }] + : [], + subagents: + name === "missing task record" + ? [] + : [ + { + id: filter.subagentIds?.[0], + providerInstanceId: "claude", + nativeTaskRef: { nativeId: "native-task" }, + childThreadId: + name === "task belongs to another child" + ? "another-child" + : filter.subagentIds?.[0] === "ancestor-task" + ? ancestorId + : childId, + origin: name.includes("native child") ? "provider_native" : "app_owned", + status: name === "completed child with pending task" ? "running" : "completed", + }, + ], + }), + }; + const result = yield* isCheckpointRestoreIsolated( + { id: parentId, worktreePath }, + { cwd: worktreePath }, + { fileSystem, path, projections: projections as never, projects: {} as never }, + ); + assert.equal(result, isolated); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), +); diff --git a/apps/server/src/orchestration-v2/CheckpointRestoreSafety.ts b/apps/server/src/orchestration-v2/CheckpointRestoreSafety.ts index b7dc08018a896..4197691af5eda 100644 --- a/apps/server/src/orchestration-v2/CheckpointRestoreSafety.ts +++ b/apps/server/src/orchestration-v2/CheckpointRestoreSafety.ts @@ -1,4 +1,11 @@ -import type { OrchestrationV2AppThread, OrchestrationV2CheckpointScope } from "@t3tools/contracts"; +import { + isLiveSubagentShell, + isProviderNativeSubagentThread, + type OrchestrationV2AppThread, + type OrchestrationV2CheckpointScope, + type OrchestrationV2ProviderThread, + type OrchestrationV2ThreadShell, +} from "@t3tools/contracts"; import * as Effect from "effect/Effect"; import type * as FileSystem from "effect/FileSystem"; import * as Option from "effect/Option"; @@ -6,6 +13,8 @@ import type * as Path from "effect/Path"; import type { ProjectionStoreV2 } from "./ProjectionStore.ts"; import type * as ProjectStore from "./ProjectStore.ts"; +const UNFINISHED_RUN_STATUSES = new Set(["queued", "preparing", "starting", "running", "waiting"]); + export const SHARED_WORKSPACE_RESTORE_MESSAGE = "File restore requires an isolated worktree. This workspace may contain changes from another thread or a side chat. Rewind the conversation without restoring files instead, or delete side chats you no longer need."; @@ -45,8 +54,29 @@ export const isCheckpointRestoreIsolated = Effect.fn("orchestrationV2.isCheckpoi shared = cwd !== worktreeCwd; if (!shared) { const shell = yield* projections.getShellSnapshot(); + const threads = [...shell.threads, ...shell.archivedThreads]; + const threadsById = new Map(threads.map((candidate) => [candidate.id, candidate])); + const subagentAncestors = (candidate: OrchestrationV2ThreadShell) => { + const ancestors: OrchestrationV2AppThread["id"][] = []; + const seen = new Set(); + let current: OrchestrationV2ThreadShell | undefined = candidate; + while (current !== undefined && !seen.has(current.id)) { + seen.add(current.id); + if (current.lineage.relationshipToParent !== "subagent") return undefined; + const parentId: OrchestrationV2AppThread["id"] | null = current.lineage.parentThreadId; + if (parentId === null) return undefined; + ancestors.push(parentId); + if (parentId === thread.id) return ancestors; + current = threadsById.get(parentId); + } + return undefined; + }; + const ancestorProviders = new Map< + OrchestrationV2AppThread["id"], + ReadonlyArray + >(); const checkedPaths = new Set(); - for (const otherThread of [...shell.threads, ...shell.archivedThreads]) { + for (const otherThread of threads) { if (otherThread.id === thread.id || otherThread.deletedAt !== null) continue; // An idle side chat that only answered questions never touched the shared worktree. if ( @@ -64,6 +94,78 @@ export const isCheckpointRestoreIsolated = Effect.fn("orchestrationV2.isCheckpoi if (turnItems.length === 0) continue; } const other = yield* projections.getCheckpointContext(otherThread.id); + const nativeSubagent = isProviderNativeSubagentThread(otherThread); + const ancestors = subagentAncestors(otherThread); + // Native children can be runless; their completion lives on the parent's task record. + if ( + otherThread.worktreePath === worktreePath && + (otherThread.status === "completed" || + (nativeSubagent && otherThread.status === "idle" && other.runs.length === 0)) && + otherThread.activeRunId === null && + !isLiveSubagentShell(otherThread) && + ancestors !== undefined && + !other.runs.some((run) => UNFINISHED_RUN_STATUSES.has(run.status)) && + otherThread.lineage.parentThreadId !== null && + otherThread.forkedFrom?.type === "node" + ) { + const taskNodeId = otherThread.forkedFrom.nodeId; + const { subagents } = yield* projections.getThreadRecords( + otherThread.lineage.parentThreadId, + ["subagents"], + { subagentIds: [taskNodeId] }, + ); + const task = subagents.find( + (candidate) => + candidate.id === taskNodeId && candidate.childThreadId === otherThread.id, + ); + if ( + task?.status === "completed" && + task.origin === (nativeSubagent ? "provider_native" : "app_owned") + ) { + if (!nativeSubagent) continue; + // Runless shells omit background work; inspect the raw records before restoring files. + const { providerThreads, turnItems } = yield* projections.getThreadRecords( + otherThread.id, + ["providerThreads", "turnItems"], + { + turnItemTypes: ["command_execution", "file_change", "dynamic_tool", "subagent"], + turnItemStatuses: ["pending", "running", "waiting"], + }, + ); + if ( + turnItems.length === 0 && + !providerThreads.some( + (providerThread) => + providerThread.status === "active" || + (providerThread.pendingBackgroundTasks?.length ?? 0) > 0, + ) + ) { + // Claude can keep a child's unattributed background commands on an ancestor session. + let pendingAncestorWork = false; + for (const ancestorId of ancestors) { + let providers = ancestorProviders.get(ancestorId); + if (providers === undefined) { + const records = yield* projections.getThreadRecords(ancestorId, [ + "providerThreads", + ]); + providers = records.providerThreads; + ancestorProviders.set(ancestorId, providers); + } + if ( + providers.some( + (provider) => + provider.providerInstanceId === task.providerInstanceId && + (provider.pendingBackgroundTasks?.length ?? 0) > 0, + ) + ) { + pendingAncestorWork = true; + break; + } + } + if (!pendingAncestorWork) continue; + } + } + } const providerContext = yield* projections.getThreadProviderContext(otherThread.id); const paths = [ otherThread.worktreePath, diff --git a/docs/user/composer.md b/docs/user/composer.md index 7f27587971a2b..9fc9b69ef22a6 100644 --- a/docs/user/composer.md +++ b/docs/user/composer.md @@ -181,8 +181,10 @@ to its checkpoint from before that message. That also undoes edits you made your File restore is only offered for threads running in a worktree, and it is refused when another thread or agent session also uses that directory, a folder inside it, or a folder that contains it, since -restoring would erase their changes. A thread that works in the project directory -rewinds the conversation only. The selected prompt and its attachments return to the composer for editing and +restoring would erase their changes. Completed subagents belonging to the reverting +thread do not block restoring that same worktree, provided they have no queued or +active work, pending requests, or background tasks. A thread that works in the project +directory rewinds the conversation only. The selected prompt and its attachments return to the composer for editing and resending. Any unsent draft stays above the restored prompt. This removes the selected message and later conversation from the active thread From d6b5aac30a5444936dc66f35a8f1cb6cde1d6895 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 19 Nov 2026 12:16:43 -0800 Subject: [PATCH 47/97] fix(server): t3_project_create names the link that refuses it and rejects a model default it would drop (#30471) --- apps/server/src/mcp/McpToolAccess.ts | 14 +++++++-- apps/server/src/mcp/linkOrigin.ts | 21 +++++++++++-- .../src/mcp/toolkits/project/handlers.test.ts | 30 +++++++++++++++++++ .../src/mcp/toolkits/project/handlers.ts | 6 ++++ apps/server/src/peer/PeerForwarding.test.ts | 6 +++- 5 files changed, 71 insertions(+), 6 deletions(-) diff --git a/apps/server/src/mcp/McpToolAccess.ts b/apps/server/src/mcp/McpToolAccess.ts index 20a9274798d0f..3115d776ba4d8 100644 --- a/apps/server/src/mcp/McpToolAccess.ts +++ b/apps/server/src/mcp/McpToolAccess.ts @@ -23,7 +23,12 @@ import { type DispatchModeRefusal, } from "../orchestration-v2/DispatchModeLimit.ts"; import * as PeerForwarding from "../peer/PeerForwarding.ts"; -import { assertNotLinked, assertSameLink, callerLinkOrigin } from "./linkOrigin.ts"; +import { + assertFullAccessNamingLink, + assertNotLinked, + assertSameLink, + callerLinkOrigin, +} from "./linkOrigin.ts"; import * as McpInvocationContext from "./McpInvocationContext.ts"; import { resolveInteractionMode, resolveRuntimeMode } from "./delegatedTaskModes.ts"; import { @@ -320,6 +325,7 @@ export const afterForwarding = ( const fullAccessRequired = "Changing projects or environment settings needs a live full-access/default calling thread or a full-access client."; +const changesEnvironment = "change projects or environment settings"; /** Recheck after waits before writing; caller modes may have changed. */ export const writesEnvironment = ( @@ -339,9 +345,11 @@ export const writesEnvironment = ( Effect.tap((caller) => options?.linkedCallers === "allowed" ? Effect.void - : assertNotLinked(caller, "change projects or environment settings"), + : assertNotLinked(caller, changesEnvironment), + ), + Effect.tap((caller) => + assertFullAccessNamingLink(caller, fullAccessRequired, changesEnvironment), ), - Effect.tap((caller) => assertFullAccess(caller, fullAccessRequired)), ); return declare( (params: P) => check.pipe(Effect.flatMap(() => handle(params, check))), diff --git a/apps/server/src/mcp/linkOrigin.ts b/apps/server/src/mcp/linkOrigin.ts index 742ac2cea3624..25763b759a36b 100644 --- a/apps/server/src/mcp/linkOrigin.ts +++ b/apps/server/src/mcp/linkOrigin.ts @@ -6,7 +6,7 @@ import { } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; -import type { Caller } from "./threadAccess.ts"; +import { assertFullAccess, type Caller } from "./threadAccess.ts"; /** * Below full access, work a link starts here (all of it carries that session in `linkOrigin`) @@ -34,10 +34,13 @@ export const fencingLinkOrigin = (caller: Pick) => { return origin !== undefined && linkOriginIsFenced(origin) ? origin : undefined; }; +const outsideLinkMessage = (origin: OrchestrationV2LinkOrigin, message: string) => + `This work was started from ${origin.label} through a linked environment, so ${message} A link paired with full access is not limited this way.`; + const outsideLink = (origin: OrchestrationV2LinkOrigin, message: string) => new OrchestratorMcpFailure({ code: "capability_denied", - message: `This work was started from ${origin.label} through a linked environment, so ${message} A link paired with full access is not limited this way.`, + message: outsideLinkMessage(origin, message), }); /** A thread a fenced caller may change: one its own link started. */ @@ -58,3 +61,17 @@ export const assertNotLinked = (caller: Pick, what: ? Effect.void : Effect.fail(outsideLink(origin, `it cannot ${what}.`)); }; + +/** A fenced caller is held below full access by its link, not its thread, so the refusal names the link. */ +export const assertFullAccessNamingLink = (caller: Caller, message: string, what: string) => { + const origin = fencingLinkOrigin(caller); + return assertFullAccess( + caller, + origin === undefined + ? message + : outsideLinkMessage( + origin, + `it has that link's ${origin.access === undefined ? "" : `${origin.access} `}access, which is below the full access needed to ${what}.`, + ), + ); +}; diff --git a/apps/server/src/mcp/toolkits/project/handlers.test.ts b/apps/server/src/mcp/toolkits/project/handlers.test.ts index 5c0f377c17bee..bcd1d7276aa16 100644 --- a/apps/server/src/mcp/toolkits/project/handlers.test.ts +++ b/apps/server/src/mcp/toolkits/project/handlers.test.ts @@ -986,6 +986,36 @@ it.effect("a client launches with the fallback for an exhausted default", () => }), ); +it.effect("creating a project through MCP refuses a model default instead of dropping it", () => + Effect.gen(function* () { + const harness = clientLaunchHarness({ runtimeModeCeiling: "full-access", launched: [] }); + const dependencies = Layer.merge( + harness.dependencies, + Layer.mock(Project.ProjectService)({ + create: () => Effect.die("the project was created without its model default"), + }), + ); + const toolkit = yield* ProjectToolkit.pipe( + Effect.provide( + McpToolAccess.HandlersLayer.layer(ProjectHandlers.layer).pipe(Layer.provide(dependencies)), + ), + ); + + const refused = yield* toolkit + .handle("t3_project_create", { + title: "client-target", + workspaceRoot: "/projects/client-target", + defaultModelSelection: harness.modelSelection, + }) + .pipe(Stream.unwrap, Stream.runCollect, Effect.provide(dependencies)); + + expect(refused.at(-1)?.result).toMatchObject({ + code: "invalid_request", + message: expect.stringContaining("t3_project_update"), + }); + }), +); + it.effect("an agent's clone is not cut off while git is still transferring", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; diff --git a/apps/server/src/mcp/toolkits/project/handlers.ts b/apps/server/src/mcp/toolkits/project/handlers.ts index f4a401586a59e..08f372e2fcef2 100644 --- a/apps/server/src/mcp/toolkits/project/handlers.ts +++ b/apps/server/src/mcp/toolkits/project/handlers.ts @@ -526,6 +526,12 @@ export const layer = McpToolAccess.toLayer(ProjectToolkit, { ...(created.commitError === undefined ? {} : { commitError: created.commitError }), }; } + if (input.defaultModelSelection !== undefined && input.defaultModelSelection !== null) + return yield* new OrchestratorMcpFailure({ + code: "invalid_request", + message: + "Creating a project does not set its default model; set defaultModelSelection afterwards with t3_project_update.", + }); const commandId = yield* newCommandId(); return yield* projects .create({ ...input, workspaceRoot, commandId, projectId: ProjectId.make(commandId) }) diff --git a/apps/server/src/peer/PeerForwarding.test.ts b/apps/server/src/peer/PeerForwarding.test.ts index 5f53bfdf5b9dd..a70c0d25792b8 100644 --- a/apps/server/src/peer/PeerForwarding.test.ts +++ b/apps/server/src/peer/PeerForwarding.test.ts @@ -593,7 +593,11 @@ it.effect("brings a repository to a linked environment, only through full access environmentId: box.environmentId, ...args, }); - expect(failureOf(refused), name).toMatchObject({ code: "capability_denied" }); + const failure = failureOf(refused); + expect(failure, name).toMatchObject({ code: "capability_denied" }); + // The agent's thread is full access; what holds it is the link's access. + expect(failure.message, name).toContain("linked environment"); + expect(failure.message, name).not.toContain("calling thread"); } expect((yield* Ref.get(seen)).clones).toHaveLength(1); expect((yield* Ref.get(seen)).projects).toHaveLength(1); From 554be2c6174d3b3ae4fe37113b67830bbbebe2b8 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 19 Nov 2026 12:16:56 -0800 Subject: [PATCH 48/97] fix(server): Full access rejects Claude Code's reworded dangerous-removal check (#38581) --- .../src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts | 5 +++++ apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts | 1 + 2 files changed, 6 insertions(+) diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts index 70e0ad8cfa7bb..0077d99f03f4e 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts @@ -2003,6 +2003,11 @@ describe("ClaudeAdapterV2 resume compaction", () => { }, { askRule: false, reason: "This shell -c script runs rm and could not be checked" }, { askRule: false, reason: "A permission rule denies a command in this shell -c script" }, + { + askRule: false, + reason: + "Claude Code can't be sure it read this command the way the shell will, so it can't rule out a dangerous removal. Read the command, and don't go ahead if you can't tell what it does.", + }, ].entries()) { const safetyRequest = yield* runtime.events.pipe( Stream.filter((event) => event.type === "runtime_request.updated"), diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index 9ab5c94e26259..523d3f09c537e 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -12526,6 +12526,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( activePermissionMode === "bypassPermissions" && callbackOptions.matchedAskRule === undefined && (/^Dangerous rm(?:dir)?\b/i.test(safetyReason) || + /\bdangerous removal\b/i.test(safetyReason) || safetyReason === "This shell -c script runs rm and could not be checked" || safetyReason === "A permission rule denies a command in this shell -c script") ) { From ebb3dd0b76009c44373d7cc558f36efb28779a0d Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 19 Nov 2026 12:18:06 -0800 Subject: [PATCH 49/97] fix(source-control-github): sign out an app sign-in GitHub refuses to refresh for the client's credentials (#39048) --- .../src/server/GitHubAppSignIn.test.ts | 14 ++++++++++++++ .../src/server/GitHubAppSignIn.ts | 12 +++++++++--- 2 files changed, 23 insertions(+), 3 deletions(-) diff --git a/packages/source-control-github/src/server/GitHubAppSignIn.test.ts b/packages/source-control-github/src/server/GitHubAppSignIn.test.ts index c42175d35b898..1d8652f06495f 100644 --- a/packages/source-control-github/src/server/GitHubAppSignIn.test.ts +++ b/packages/source-control-github/src/server/GitHubAppSignIn.test.ts @@ -350,6 +350,20 @@ describe("GitHubAppSignIn", () => { }).pipe(Effect.provide(layer)); }); + it.effect("does not ask GitHub again after it rejects the client's credentials", () => { + const { layer, requests } = harness({ + signIns: { "github.com": session({ accessTokenExpiresAt: 0 }) }, + handle: () => ({ body: { error: "incorrect_client_credentials" } }), + }); + return Effect.gen(function* () { + const signIn = yield* GitHubAppSignIn.GitHubAppSignIn; + yield* Effect.exit(signIn.token("github.com")); + yield* Effect.exit(signIn.token("github.com")); + expect(requests).toHaveLength(1); + expect(yield* savedSignIns).toEqual({}); + }).pipe(Effect.provide(layer)); + }); + it.effect("serves the still-valid token when a refresh ahead of expiry fails", () => { const { layer } = harness({ signIns: { "github.com": session({ accessTokenExpiresAt: 3 * 60_000 }) }, diff --git a/packages/source-control-github/src/server/GitHubAppSignIn.ts b/packages/source-control-github/src/server/GitHubAppSignIn.ts index 5c339c66010c0..28bde65ed84a8 100644 --- a/packages/source-control-github/src/server/GitHubAppSignIn.ts +++ b/packages/source-control-github/src/server/GitHubAppSignIn.ts @@ -213,9 +213,15 @@ export const make = Effect.gen(function* () { }, TokenResponse, ).pipe(Effect.mapError((cause) => new GitHubAppSessionError({ host, cause }))); - if (response.error === "bad_refresh_token") { - // Final: the user revoked the app or the session lapsed. - yield* Effect.logWarning("GitHub refused the app sign-in refresh; signing out.", { host }); + if ( + response.error === "bad_refresh_token" || + response.error === "incorrect_client_credentials" + ) { + // Final: the user revoked the app, the session lapsed, or this server's client cannot refresh it. + yield* Effect.logWarning("GitHub refused the app sign-in refresh; signing out.", { + host, + error: response.error, + }); yield* replaceSession(host, session, null).pipe(Effect.ignore); return Option.none(); } From 916fcdc364859f6cc0eddd00995aa092c7b55687 Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Thu, 19 Nov 2026 21:19:16 +0100 Subject: [PATCH 50/97] fix(web): preserve newer project action drafts when imports fail (#39312) Co-authored-by: Julius Marminge --- .../ProjectScriptsControl.browser.test.tsx | 72 ++++++++++++++ .../src/components/ProjectScriptsControl.tsx | 29 ++++-- apps/web/src/i18n/translations/de.json | 1 + apps/web/src/i18n/translations/en.json | 1 + apps/web/src/i18n/translations/es.json | 1 + apps/web/src/i18n/translations/fr.json | 1 + apps/web/src/i18n/translations/ja.json | 1 + apps/web/src/i18n/translations/ko.json | 1 + apps/web/src/i18n/translations/pt-BR.json | 1 + apps/web/src/i18n/translations/ru.json | 1 + apps/web/src/i18n/translations/sv.json | 1 + apps/web/src/i18n/translations/zh.json | 1 + ...action-draft-survives-failed-import.e2e.ts | 94 +++++++++++++++++++ 13 files changed, 198 insertions(+), 7 deletions(-) create mode 100644 apps/web/src/components/ProjectScriptsControl.browser.test.tsx create mode 100644 scripts/scenarios/project-action-draft-survives-failed-import.e2e.ts diff --git a/apps/web/src/components/ProjectScriptsControl.browser.test.tsx b/apps/web/src/components/ProjectScriptsControl.browser.test.tsx new file mode 100644 index 0000000000000..dd8c17c610e2a --- /dev/null +++ b/apps/web/src/components/ProjectScriptsControl.browser.test.tsx @@ -0,0 +1,72 @@ +import { EnvironmentId } from "@t3tools/contracts"; +import * as Cause from "effect/Cause"; +import { AsyncResult } from "effect/reactivity"; +import { expect, it } from "vite-plus/test"; +import { page, userEvent } from "vite-plus/test/browser"; + +import { act, render } from "../../test/render"; +import ProjectScriptsControl, { type ProjectScriptActionResult } from "./ProjectScriptsControl"; + +it.each(["edit", "dismiss", "newer import fails first"] as const)( + "keeps a failed import from replacing a newer action after %s", + async (nextAction) => { + const older = Promise.withResolvers(); + const newer = Promise.withResolvers(); + await using screen = await render( + {}} + onAddScript={({ name }) => (name === "Shared build" ? older.promise : newer.promise)} + onUpdateScript={async () => AsyncResult.success(undefined)} + onDeleteScript={async () => AsyncResult.success(undefined)} + />, + ); + + const actions = screen.getByRole("button", { name: "Script actions" }); + const dialog = page.getByRole("dialog"); + const name = dialog.getByRole("textbox", { name: "Name" }); + const failure = AsyncResult.failure( + Cause.fail(new Error("Settings write failed")), + ); + + await actions.click(); + await page.getByRole("menuitem", { name: /Shared build/ }).click(); + await actions.click(); + + switch (nextAction) { + case "edit": + await page.getByRole("button", { name: "Edit Local check" }).click(); + await act(async () => older.resolve(failure)); + expect(name.query()).toHaveProperty("value", "Local check"); + break; + case "dismiss": + await page.getByRole("menuitem", { name: "Add project script" }).click(); + await expect.element(dialog).toBeVisible(); + await userEvent.keyboard("{Escape}"); + await expect.element(dialog).not.toBeInTheDocument(); + await act(async () => older.resolve(failure)); + expect(dialog.query() === null).toBe(true); + break; + case "newer import fails first": + await page.getByRole("menuitem", { name: /Shared lint/ }).click(); + await act(async () => newer.resolve(failure)); + await act(async () => older.resolve(failure)); + expect(name.query()).toHaveProperty("value", "Shared lint"); + break; + } + }, +); diff --git a/apps/web/src/components/ProjectScriptsControl.tsx b/apps/web/src/components/ProjectScriptsControl.tsx index f92aa27c9da07..210762bfdebf9 100644 --- a/apps/web/src/components/ProjectScriptsControl.tsx +++ b/apps/web/src/components/ProjectScriptsControl.tsx @@ -47,6 +47,7 @@ import { MenuSubTrigger, MenuSubPopup, } from "./ui/menu"; +import { stackedThreadToast, toastManager } from "./ui/toast"; import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip"; import { cn } from "~/lib/utils"; import { @@ -108,6 +109,7 @@ export default function ProjectScriptsControl({ setActionsMenuOpen({ presentation, scripts: false, imports: false }); } const [editorRequest, setEditorRequest] = useState(null); + const editorRequestIdRef = React.useRef(0); const primaryScript = (preferredScriptId ? scripts.find((script) => script.id === preferredScriptId) : undefined) ?? @@ -122,10 +124,12 @@ export default function ProjectScriptsControl({ ); const openAddDialog = () => { + editorRequestIdRef.current += 1; setEditorRequest({ scriptId: null, initial: EMPTY_PROJECT_SCRIPT_INPUT }); }; const openEditDialog = (script: ProjectScript) => { + editorRequestIdRef.current += 1; onRequestMenuClose?.(); setActionsMenuOpen({ presentation, scripts: false, imports: false }); setEditorRequest(editorRequestForScript(script, keybindings)); @@ -135,6 +139,7 @@ export default function ProjectScriptsControl({ scriptId === null ? onAddScript(input) : onUpdateScript(scriptId, input); const importFileScript = async (fileScript: T3ProjectFileScript) => { + const requestId = ++editorRequestIdRef.current; const payload: NewProjectScriptInput = { name: fileScript.name, command: fileScript.command, @@ -148,14 +153,24 @@ export default function ProjectScriptsControl({ autoOpenPreview: fileScript.previewUrl ? (fileScript.autoOpenPreview ?? false) : false, }; const result = await onAddScript(payload); - if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { - const error = squashAtomCommandFailure(result); - setEditorRequest({ - scriptId: null, - initial: payload, - error: thrownErrorMessage(error, m) ?? gt("Failed to import action."), - }); + if (result._tag !== "Failure" || isAtomCommandInterrupted(result)) return; + + const message = thrownErrorMessage(squashAtomCommandFailure(result), m); + if (requestId !== editorRequestIdRef.current) { + toastManager.add( + stackedThreadToast({ + type: "error", + title: gt("Failed to import {name}.", { name: fileScript.name }), + ...(message ? { description: message } : {}), + }), + ); + return; } + setEditorRequest({ + scriptId: null, + initial: payload, + error: message ?? gt("Failed to import action."), + }); }; const importMenuItems = importableScripts.length > 0 && ( diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index e6ea47432d43e..22f9bcf953f2b 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -2194,6 +2194,7 @@ "63977cd5e4535393": "{name} loslösen", "c4c2d240ffe55dec": "{name} anheften", "a1190e56375f2032": "{action} ({shortcut})", + "f16b6d8ef68bab61": "{name} konnte nicht importiert werden.", "924d4b8e011c9127": "Aktion konnte nicht importiert werden.", "0421f870f82997bc": "Importieren", "06690d4ce0d19c30": "{name} bearbeiten", diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index 195984c8bc9c6..442486e2decb0 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -2194,6 +2194,7 @@ "63977cd5e4535393": "Unpin {name}", "c4c2d240ffe55dec": "Pin {name}", "a1190e56375f2032": "{action} ({shortcut})", + "f16b6d8ef68bab61": "Failed to import {name}.", "924d4b8e011c9127": "Failed to import action.", "0421f870f82997bc": "Import", "06690d4ce0d19c30": "Edit {name}", diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index 1c0ecfca61eb4..87c7e9a861a93 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -2194,6 +2194,7 @@ "63977cd5e4535393": "Desfijar {name}", "c4c2d240ffe55dec": "Fijar {name}", "a1190e56375f2032": "{action} ({shortcut})", + "f16b6d8ef68bab61": "No se pudo importar {name}.", "924d4b8e011c9127": "No se pudo importar la acción.", "0421f870f82997bc": "Importar", "06690d4ce0d19c30": "Editar {name}", diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index 5d9f5bce153c5..a3a16e772103e 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -2194,6 +2194,7 @@ "63977cd5e4535393": "Désépingler {name}", "c4c2d240ffe55dec": "Épingler {name}", "a1190e56375f2032": "{action} ({shortcut})", + "f16b6d8ef68bab61": "Échec de l’import de « {name} ».", "924d4b8e011c9127": "Échec de l’import de l’action.", "0421f870f82997bc": "Importer", "06690d4ce0d19c30": "Modifier {name}", diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index 70a5135906665..8459e9cf87854 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -2192,6 +2192,7 @@ "63977cd5e4535393": "{name} のピン留めを解除", "c4c2d240ffe55dec": "{name} をピン留め", "a1190e56375f2032": "{action} ({shortcut})", + "f16b6d8ef68bab61": "「{name}」をインポートできませんでした。", "924d4b8e011c9127": "アクションをインポートできませんでした。", "0421f870f82997bc": "インポート", "06690d4ce0d19c30": "{name} を編集", diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index 2690d7cd556ca..c523c5dc7b1fc 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -2193,6 +2193,7 @@ "63977cd5e4535393": "{name} 고정 해제", "c4c2d240ffe55dec": "{name} 고정", "a1190e56375f2032": "{action}({shortcut})", + "f16b6d8ef68bab61": "‘{name}’을(를) 가져오지 못했습니다.", "924d4b8e011c9127": "작업을 가져오지 못했습니다.", "0421f870f82997bc": "가져오기", "06690d4ce0d19c30": "{name} 편집", diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index 3b57bb68c1b11..bd34cd96c3d8b 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -2194,6 +2194,7 @@ "63977cd5e4535393": "Desafixar {name}", "c4c2d240ffe55dec": "Fixar {name}", "a1190e56375f2032": "{action} ({shortcut})", + "f16b6d8ef68bab61": "Não foi possível importar {name}.", "924d4b8e011c9127": "Falha ao importar a ação.", "0421f870f82997bc": "Importar", "06690d4ce0d19c30": "Editar {name}", diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index 64ac787207b45..4242d78d5f3c5 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -2194,6 +2194,7 @@ "63977cd5e4535393": "Открепить {name}", "c4c2d240ffe55dec": "Закрепить {name}", "a1190e56375f2032": "{action} ({shortcut})", + "f16b6d8ef68bab61": "Не удалось импортировать «{name}».", "924d4b8e011c9127": "Не удалось импортировать действие.", "0421f870f82997bc": "Импортировать", "06690d4ce0d19c30": "Изменить {name}", diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index 0767578a42c58..d3d7bec015020 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -2194,6 +2194,7 @@ "63977cd5e4535393": "Lossa {name}", "c4c2d240ffe55dec": "Fäst {name}", "a1190e56375f2032": "{action} ({shortcut})", + "f16b6d8ef68bab61": "Det gick inte att importera {name}.", "924d4b8e011c9127": "Det gick inte att importera åtgärden.", "0421f870f82997bc": "Importera", "06690d4ce0d19c30": "Redigera {name}", diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index 277b7fe77da0f..5923adef292f5 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -2198,6 +2198,7 @@ "63977cd5e4535393": "取消置顶 {name}", "c4c2d240ffe55dec": "置顶 {name}", "a1190e56375f2032": "{action} ({shortcut})", + "f16b6d8ef68bab61": "无法导入“{name}”。", "924d4b8e011c9127": "无法导入操作。", "0421f870f82997bc": "导入", "06690d4ce0d19c30": "编辑 {name}", diff --git a/scripts/scenarios/project-action-draft-survives-failed-import.e2e.ts b/scripts/scenarios/project-action-draft-survives-failed-import.e2e.ts new file mode 100644 index 0000000000000..f3b5ee6709e64 --- /dev/null +++ b/scripts/scenarios/project-action-draft-survives-failed-import.e2e.ts @@ -0,0 +1,94 @@ +/// +import { expect } from "e2e"; + +import { test, WEB } from "./t3.ts"; + +declare global { + interface Window { + projectActionImportFailure?: Promise<() => void>; + } +} + +test( + "A failed project action import preserves a manual action draft", + WEB, + async ({ t3, app, browser, screen }) => { + const project = await t3.project("demo", { + "t3.json": JSON.stringify({ + scripts: [{ name: "Shared build", command: "echo build" }], + }), + }); + const thread = await t3.thread({ project, title: "Action import", messages: ["Start"] }); + await browser.setViewport({ width: 1920, height: 1000 }); + + await browser.addInitScript(() => { + const pending = Promise.withResolvers<() => void>(); + window.projectActionImportFailure = pending.promise; + const send = WebSocket.prototype.send; + WebSocket.prototype.send = function (data) { + const request: { _tag: string; id: string; tag: string } | null = + typeof data === "string" ? JSON.parse(data) : null; + if ( + typeof data !== "string" || + request?._tag !== "Request" || + request.tag !== "server.updateSettings" || + !data.includes("Shared build") + ) { + return send.call(this, data); + } + // Delay a settings write failure until the user has started a different action. + WebSocket.prototype.send = send; + pending.resolve(() => { + this.dispatchEvent( + new MessageEvent("message", { + data: JSON.stringify({ + _tag: "Exit", + requestId: request.id, + exit: { + _tag: "Failure", + cause: [ + { + _tag: "Fail", + error: { + _tag: "ServerSettingsError", + operation: "write-file", + settingsPath: "settings.json", + }, + }, + ], + }, + }), + }), + ); + }); + }; + }); + + await t3.open(thread); + const actions = screen.getByRole("button", "Choose project action", { exact: true }); + await actions.tap(); + await screen.getByRole("menuitem", /Shared build/).tap(); + await browser.evaluate(async () => { + await window.projectActionImportFailure; + return null; + }); + + await actions.tap(); + await screen.getByRole("menuitem", "Add project script", { exact: true }).tap(); + const draftName = "My local check"; + await browser.locator("#script-name").fill(draftName); + await browser.locator("#script-command").fill("echo local"); + await browser.evaluate(async () => { + const release = await window.projectActionImportFailure!; + release(); + return null; + }); + + await screen.getByText("Server settings write-file failed at settings.json.").waitFor(); + await app.screenshot("action-draft-after-import-fails"); + const name = await browser.evaluate( + () => document.querySelector("#script-name")?.value ?? null, + ); + expect(name, "The failed import preserves the manual action name").toBe(draftName); + }, +); From 767f194fd9876afb2d2e08c884cf6b92b1bba286 Mon Sep 17 00:00:00 2001 From: "Paul Dupuy, Jr." <70114489+pauldupuyjr@users.noreply.github.com> Date: Thu, 19 Nov 2026 12:19:41 -0800 Subject: [PATCH 51/97] fix(server): Codex thread name follows T3 thread renames (#37442) Co-authored-by: maria-rcks Co-authored-by: Julius Marminge --- ...OrchestratorMcpToolkit.integration.test.ts | 9 +- .../Adapters/CodexAdapterV2.test.ts | 204 +++++++++++++++--- .../Adapters/CodexAdapterV2.ts | 26 +++ .../CodexReplayFixtures.integration.test.ts | 32 +++ .../codex_transcript.ndjson | 19 +- .../codex_transcript.ndjson | 11 +- .../codex_transcript.ndjson | 46 ++-- .../message_steering/codex_transcript.ndjson | 15 +- .../multi_turn/codex_transcript.ndjson | 19 +- .../plan_questions/codex_transcript.ndjson | 11 +- .../proposed_plan/codex_transcript.ndjson | 11 +- .../codex_transcript.ndjson | 22 +- .../queued_turn/codex_transcript.ndjson | 19 +- .../fixtures/simple/codex_transcript.ndjson | 11 +- .../fixtures/subagent/codex_transcript.ndjson | 11 +- .../subagent_continue/codex_transcript.ndjson | 19 +- .../subagent_v2/codex_transcript.ndjson | 11 +- .../codex_transcript.ndjson | 11 +- .../codex_transcript.ndjson | 11 +- .../codex_transcript.ndjson | 11 +- .../codex_transcript.ndjson | 34 +-- .../codex_transcript.ndjson | 65 +++--- .../thread_rollback/codex_transcript.ndjson | 39 ++-- .../codex_transcript.ndjson | 30 +-- .../codex_transcript.ndjson | 55 ++--- .../todo_list/codex_transcript.ndjson | 11 +- .../codex_transcript.ndjson | 11 +- .../codex_transcript.ndjson | 11 +- .../codex_transcript.ndjson | 11 +- .../turn_interrupt/codex_transcript.ndjson | 15 +- .../codex_transcript.ndjson | 19 +- .../web_search/codex_transcript.ndjson | 11 +- 32 files changed, 581 insertions(+), 260 deletions(-) diff --git a/apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts b/apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts index ccf6a84a16d75..777a5d6df3a56 100644 --- a/apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts +++ b/apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts @@ -103,8 +103,15 @@ const readDelegatedTaskStatusTranscript = Effect.fn("readDelegatedTaskStatusTran function* (followupResult: string) { const fs = yield* FileSystem.FileSystem; const text = yield* fs.readFileString(NodeURL.fileURLToPath(delegatedTaskStatusTranscriptFile)); + // The recording names the parent, then the child, after the fixture's titles; this test's differ. + const threadNames = ["MCP replay parent", delegatedPrompt]; const transcript = yield* decodeProviderReplayNdjson( - text.replaceAll(queuedFollowupResult, followupResult), + text + .replaceAll(queuedFollowupResult, followupResult) + .replace( + /"name":"Replay fixture: delegated_task_status"/g, + () => `"name":${JSON.stringify(threadNames.shift())}`, + ), ); // The recording ends when the recorder closes the app-server while the parent // turn is still open. This test keeps acting as that parent afterwards, and diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts index 87f48cc671d1f..cf5439e3eb254 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts @@ -579,6 +579,8 @@ const threadEnvOf = (params: unknown) => ? params.config[T3_THREAD_ENV_KEY] : undefined; +const CODEX_TEST_THREAD_TITLE = "Codex continuation test"; + function makeCodexTestAppThread(input: { readonly threadId: ThreadId; readonly providerThread: OrchestrationV2ProviderThread; @@ -589,7 +591,7 @@ function makeCodexTestAppThread(input: { creationSource: "web", id: input.threadId, projectId: ProjectId.make(`project-${input.threadId}`), - title: "Codex continuation test", + title: CODEX_TEST_THREAD_TITLE, providerInstanceId: CodexAdapterV2.CODEX_DEFAULT_INSTANCE_ID, modelSelection: CODEX_TEST_MODEL_SELECTION, runtimeMode: "full-access", @@ -801,13 +803,18 @@ function codexReplayPreamble(input: { ]; } -/** Every turn/start follows a config/read; inserts that exchange and shifts later client ids. */ +/** + * Every turn/start follows a config/read, and a thread's first turn on a connection names it + * unless the transcript names it itself. Inserts those exchanges and shifts later client ids. + */ function withConfigReadBeforeTurnStart( entries: ReadonlyArray, + threadName = CODEX_TEST_THREAD_TITLE, ): Array { const result: Array = []; let offset = 0; let clientIds = new Map(); + let namedThreads = new Set(); for (const entry of entries) { const frame = entry.type === "runtime_exit" ? undefined : entry.frame; if (!Predicate.isObject(frame) || typeof frame.id !== "number") { @@ -815,26 +822,36 @@ function withConfigReadBeforeTurnStart( continue; } if (entry.type === "expect_outbound" && typeof frame.method === "string") { + const params = Predicate.isObject(frame.params) ? frame.params : {}; if (frame.method === "initialize") { offset = 0; clientIds = new Map(); + namedThreads = new Set(); } + if (frame.method === "thread/name/set") namedThreads.add(params.threadId); if (frame.method === "turn/start") { - const id = frame.id + offset; - const params = Predicate.isObject(frame.params) ? frame.params : {}; - result.push( - { - type: "expect_outbound", - label: "config/read", - frame: { id, method: "config/read", params: { cwd: params.cwd, includeLayers: false } }, - }, - { - type: "emit_inbound", - label: "config/read", - frame: { id, result: { config: {}, origins: {} } }, - }, - ); - offset += 1; + const exchanges: Array = []; + if (!namedThreads.has(params.threadId)) { + namedThreads.add(params.threadId); + exchanges.push(["thread/name/set", { threadId: params.threadId, name: threadName }, {}]); + } + exchanges.push([ + "config/read", + { cwd: params.cwd, includeLayers: false }, + { config: {}, origins: {} }, + ]); + for (const [method, requestParams, response] of exchanges) { + const id = frame.id + offset; + result.push( + { + type: "expect_outbound", + label: method, + frame: { id, method, params: requestParams }, + }, + { type: "emit_inbound", label: method, frame: { id, result: response } }, + ); + offset += 1; + } } clientIds.set(frame.id, frame.id + offset); result.push(withReplayRequestId(entry, frame.id + offset)); @@ -852,8 +869,9 @@ function withConfigReadBeforeTurnStart( function withConfigReads( transcript: CodexReplay.CodexAppServerReplayTranscript, + threadName?: string, ): CodexReplay.CodexAppServerReplayTranscript { - return { ...transcript, entries: withConfigReadBeforeTurnStart(transcript.entries) }; + return { ...transcript, entries: withConfigReadBeforeTurnStart(transcript.entries, threadName) }; } function makeCodexReplayTranscript(input: { @@ -3283,6 +3301,115 @@ describe("CodexAdapterV2 post-settle continuation", () => { ), ); + it.effect("names the native thread after the T3 title and retries a failed rename", () => + Effect.gen(function* () { + const nativeThreadId = "thread-name-thread"; + const nameSet = ( + id: number, + name: string, + response: "result" | "error", + ): Array => [ + { + type: "expect_outbound", + label: "thread/name/set", + frame: { id, method: "thread/name/set", params: { threadId: nativeThreadId, name } }, + }, + { + type: "emit_inbound", + label: "thread/name/set", + frame: + response === "result" + ? { id, result: {} } + : { id, error: { code: -32601, message: "Method not found" } }, + }, + ]; + const turn = ( + id: number, + nativeTurnId: string, + ): Array => { + const entries = codexReplayPreamble({ nativeThreadId, nativeTurnId, prompt: "work" }); + return [ + withReplayRequestId(entries[5]!, id), + withReplayRequestId(entries[6]!, id), + { + type: "emit_inbound", + label: "turn/completed", + frame: { + method: "turn/completed", + params: { + threadId: nativeThreadId, + turn: makeCodexReplayTurn({ id: nativeTurnId, status: "completed" }), + }, + }, + }, + ]; + }; + const names: Array = []; + const harness = yield* makeCodexReplayHarness( + makeCodexReplayTranscript({ + scenario: "codex-thread-name", + entries: [ + ...codexReplayPreamble({ + nativeThreadId, + nativeTurnId: "unused", + prompt: "work", + }).slice(0, 5), + ...nameSet(3, CODEX_TEST_THREAD_TITLE, "error"), + ...turn(4, "thread-name-turn-1"), + ...nameSet(5, CODEX_TEST_THREAD_TITLE, "result"), + ...turn(6, "thread-name-turn-2"), + ...turn(7, "thread-name-turn-3"), + ...nameSet(8, "Renamed", "result"), + ], + }), + () => Effect.void, + (method, params) => + Effect.sync(() => { + if (method === "thread/name/set") names.push(params); + }), + ); + const now = yield* DateTime.now; + for (const ordinal of [1, 2, 3]) { + yield* harness.runtime.startTurn({ + ...makeCodexTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make(`thread-name-${ordinal}`), + text: "work", + }), + runOrdinal: ordinal, + providerTurnOrdinal: ordinal, + }); + yield* harness.awaitTerminal(ordinal); + } + const applyThreadTitle = harness.runtime.applyThreadTitle; + assert.isDefined(applyThreadTitle); + for (const title of ["Renamed", "Renamed"]) { + yield* applyThreadTitle({ providerThread: harness.providerThread, title }); + } + + assert.deepEqual(names, [ + { threadId: nativeThreadId, name: CODEX_TEST_THREAD_TITLE }, + { threadId: nativeThreadId, name: CODEX_TEST_THREAD_TITLE }, + { threadId: nativeThreadId, name: "Renamed" }, + ]); + assert.deepEqual( + harness.terminalEvents().map((event) => event.status), + ["completed", "completed", "completed"], + ); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); + it.effect.each(["before", "during"] as const)( "surfaces a user MCP server that fails to start %s the turn", (timing) => @@ -4510,7 +4637,6 @@ describe("CodexAdapterV2 post-settle continuation", () => { }); // A speed picked while the first attempt runs; the retry must not send the old one. const changedTier = outcome === "keep-changed-tier" ? "fast" : undefined; - const retryRequestId = (attempt: number) => (changedTier === undefined ? 3 : 4) + attempt; if (changedTier !== undefined) { entries.push( { @@ -4529,9 +4655,25 @@ describe("CodexAdapterV2 post-settle continuation", () => { ...(outcome === "completion-only" ? failureEntries(0).slice(1) : failureEntries(0)), ); if (outcome === "completion-only") entries.push(...failureEntries(0).slice(1)); + // A live rename between attempts must not be undone by the retry. + const renamedBeforeRetry = outcome === "started-first"; + if (renamedBeforeRetry) { + entries.push( + { + type: "expect_outbound", + frame: { + id: 4, + method: "thread/name/set", + params: { threadId: nativeThreadId, name: "Renamed" }, + }, + }, + { type: "emit_inbound", frame: { id: 4, result: {} } }, + ); + } const retries = outcome === "exhaust" ? 5 : outcome === "stop" ? 0 : 1; const steeredText = "Use the smaller change."; for (let attempt = 1; attempt <= retries; attempt++) { + const startId = 3 + attempt + (renamedBeforeRetry || changedTier !== undefined ? 1 : 0); const start = codexReplayPreamble({ nativeThreadId, nativeTurnId: nativeTurnId(attempt), @@ -4550,7 +4692,7 @@ describe("CodexAdapterV2 post-settle continuation", () => { entries.push({ ...entry, frame: { - id: retryRequestId(attempt), + id: startId, method: "turn/start", params: { threadId: nativeThreadId, @@ -4595,11 +4737,11 @@ describe("CodexAdapterV2 post-settle continuation", () => { ? { type: "emit_inbound", frame: { - id: 3 + attempt, + id: startId, error: { code: -32603, message: "Start failed" }, }, } - : withReplayRequestId(entry, retryRequestId(attempt)), + : withReplayRequestId(entry, startId), ); } else if (outcome !== "start-fails") { entries.push( @@ -4756,6 +4898,12 @@ describe("CodexAdapterV2 post-settle continuation", () => { }) .pipe(Effect.forkScoped) : undefined; + if (renamedBeforeRetry) { + yield* harness.runtime.applyThreadTitle!({ + providerThread: harness.providerThread, + title: "Renamed", + }); + } yield* TestClock.adjust(Math.min(2_000 * 2 ** (attempt - 1), 30_000)); if (outcome === "stop-starting") { yield* Deferred.await(retryStarted); @@ -4835,7 +4983,9 @@ describe("CodexAdapterV2 post-settle continuation", () => { makeCodexReplayTranscript({ scenario, entries }), )).replaceAll(yield* encodeStringJson("/workspace"), yield* encodeStringJson(cwd)), ); - const driver = yield* CodexReplay.makeReplayDriver(withConfigReads(localTranscript)); + const driver = yield* CodexReplay.makeReplayDriver( + withConfigReads(localTranscript, "Capacity retry"), + ); yield* Effect.gen(function* () { const orchestrator = yield* Orchestrator.OrchestratorV2; const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; @@ -6537,7 +6687,9 @@ describe("CodexAdapterV2 post-settle continuation", () => { yield* encodeStringJson(cwd), ), ); - const replayDriver = yield* CodexReplay.makeReplayDriver(withConfigReads(localTranscript)); + const replayDriver = yield* CodexReplay.makeReplayDriver( + withConfigReads(localTranscript, "Background stop"), + ); const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; assert.equal( Number(yield* spawner.exitCode(ChildProcess.make("git", ["init", "--quiet"], { cwd }))), @@ -6744,7 +6896,9 @@ describe("CodexAdapterV2 post-settle continuation", () => { Effect.provide( ProviderReplayHarness.layerWithRegistry( { name: "codex-background-stop-untracked", runtimePolicyOverride: { cwd } }, - CodexAdapterV2Testkit.layer({ transcript: withConfigReads(localTranscript) }), + CodexAdapterV2Testkit.layer({ + transcript: withConfigReads(localTranscript, "Background stop untracked"), + }), { runEffectWorker: false }, ), ), diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts index f52d13e691c86..4474dd04273a0 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts @@ -2156,6 +2156,20 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( string, { readonly runtimeMode: RuntimeMode; readonly kinds: Set } >(); + // `codex resume` and the Codex app list the native name. A failed rename, including on a + // Codex without thread/name/set, is forgotten so the next turn sends it again. + const appliedThreadNames = new Map(); + const applyThreadName = Effect.fn("CodexAdapterV2.applyThreadName")(function* ( + threadId: string, + name: string, + ) { + if (appliedThreadNames.get(threadId) === name) return; + const renamed = yield* client + .request("thread/name/set", { threadId, name }) + .pipe(Effect.timeout("10 seconds"), Effect.isSuccess); + if (renamed) appliedThreadNames.set(threadId, name); + else appliedThreadNames.delete(threadId); + }); /** Bind answers to the request's approval set so mode changes invalidate late answers. */ const endSessionApprovalsOnModeChange = (context: ActiveCodexTurnContext) => { const nativeThreadId = context.providerThread.nativeThreadRef?.nativeId; @@ -7638,6 +7652,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( const activation = { stopped: false }; goalActivations.set(threadId, activation); yield* Effect.gen(function* () { + yield* applyThreadName(threadId, turnInput.appThread.title); yield* startNativeTurn(turnInput, yield* codexInput); if (activation.stopped) return; const { goal } = yield* client.request("thread/goal/set", { @@ -8127,6 +8142,10 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( ) { return yield* activateGoal(turnInput, nativeThreadId, toCodexInput(turnInput)); } + // Not in startNativeTurn: a capacity retry would replay its captured, possibly stale title. + if (nativeThreadId != null) { + yield* applyThreadName(nativeThreadId, turnInput.appThread.title); + } yield* startNativeTurn( turnInput, !continuation ? yield* toCodexInput(turnInput) : [], @@ -8217,6 +8236,13 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( ), ), ), + applyThreadTitle: Effect.fn("CodexAdapterV2.applyThreadTitle")(function* ({ + providerThread, + title, + }) { + const nativeThreadId = providerThread.nativeThreadRef?.nativeId; + if (nativeThreadId != null) yield* applyThreadName(nativeThreadId, title); + }), applyModelSelection: Effect.fn("CodexAdapterV2.applyModelSelection")(function* ({ providerThread, modelSelection, diff --git a/apps/server/src/orchestration-v2/testkit/CodexReplayFixtures.integration.test.ts b/apps/server/src/orchestration-v2/testkit/CodexReplayFixtures.integration.test.ts index 1274c9eaee2e9..5e61e138b533e 100644 --- a/apps/server/src/orchestration-v2/testkit/CodexReplayFixtures.integration.test.ts +++ b/apps/server/src/orchestration-v2/testkit/CodexReplayFixtures.integration.test.ts @@ -1,7 +1,9 @@ import { assert, describe, it } from "@effect/vitest"; import * as Tracer from "effect/Tracer"; import * as Effect from "effect/Effect"; +import * as Predicate from "effect/Predicate"; +import type { ProviderReplayTranscript } from "@t3tools/contracts"; import { materializeReplayTranscriptWorkspace } from "@t3tools/provider-testing/replayTranscript"; import { CodexOrchestratorReplayHarness } from "../Adapters/CodexAdapterV2.testkit.ts"; import { @@ -10,6 +12,28 @@ import { runReplayFixture, } from "./ProviderReplayFixtures.ts"; +/** A transcript borrowed from another scenario names the thread after that scenario's title. */ +const renameRecordedThread = + (recordedScenario: string, scenario: string) => + (transcript: ProviderReplayTranscript): ProviderReplayTranscript => ({ + ...transcript, + entries: transcript.entries.map((entry) => + entry.type === "expect_outbound" && + Predicate.isObject(entry.frame) && + entry.frame.method === "thread/name/set" && + Predicate.isObject(entry.frame.params) && + entry.frame.params.name === `Replay fixture: ${recordedScenario}` + ? { + ...entry, + frame: { + ...entry.frame, + params: { ...entry.frame.params, name: `Replay fixture: ${scenario}` }, + }, + } + : entry, + ), + }); + describe("Codex replay fixtures", () => { itRunsReplayFixtures("codex", (input) => runReplayFixture({ @@ -17,6 +41,14 @@ describe("Codex replay fixtures", () => { harness: CodexOrchestratorReplayHarness, materializeWorkspace: (transcript, workspace) => Effect.succeed(materializeReplayTranscriptWorkspace(transcript, workspace)), + ...(input.driver.recordedScenario === undefined + ? {} + : { + transformTranscript: renameRecordedThread( + input.driver.recordedScenario, + input.fixtureName, + ), + }), }), ); }); diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/codex_model_reroute/codex_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/codex_model_reroute/codex_transcript.ndjson index 8dbd1758215aa..aa14fb3b08d50 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/codex_model_reroute/codex_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/codex_model_reroute/codex_transcript.ndjson @@ -6,13 +6,16 @@ {"type":"emit_inbound","label":"configWarning","frame":{"method":"configWarning","params":{"summary":"Codex could not find bubblewrap on PATH. Install bubblewrap with your OS package manager. See the sandbox prerequisites: https://developers.openai.com/codex/concepts/sandboxing#prerequisites. Codex will use the bundled bubblewrap in the meantime.","details":null},"emittedAtMs":1790295480414}} {"type":"emit_inbound","label":"remoteControl/status/changed","frame":{"method":"remoteControl/status/changed","params":{"status":"disabled","serverName":"replay-host","installationId":"00000000-0000-4000-8000-000000000000","environmentId":null},"emittedAtMs":1790295480414}} {"type":"emit_inbound","label":"thread/start","frame":{"id":2,"result":{"thread":{"id":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790295480,"updatedAt":1790295480,"recencyAt":1790295480,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-18-00-01a0d5ed-187d-70c2-b4b6-b6881a68de09.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]},"model":"gpt-6-luna","modelProvider":"openai","serviceTier":null,"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"],"instructionSources":["/home/replay-user/.codex/AGENTS.md","/home/replay-user/t3code/AGENTS.md"],"approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":{"id":":workspace","extends":null},"reasoningEffort":null,"multiAgentMode":"explicitRequestOnly"}}} -{"type":"expect_outbound","label":"config/read","frame":{"id":3,"method":"config/read","params":{"cwd":"","includeLayers":false}}} -{"type":"emit_inbound","label":"config/read","frame":{"id":3,"result":{"config":{},"origins":{}}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":4,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Respond with exactly: first fixture turn complete","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"auto","threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} +{"type":"expect_outbound","label":"thread/name/set","frame":{"id":3,"method":"thread/name/set","params":{"name":"Replay fixture: codex_model_reroute","threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09"}}} +{"type":"emit_inbound","label":"thread/name/set","frame":{"id":3,"result":{}}} +{"type":"emit_inbound","label":"thread/name/updated","frame":{"method":"thread/name/updated","params":{"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","threadName":"Replay fixture: codex_model_reroute"}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":4,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":4,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":5,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Respond with exactly: first fixture turn complete","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"auto","threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} {"type":"emit_inbound","label":"thread/started","frame":{"method":"thread/started","params":{"thread":{"id":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790295480,"updatedAt":1790295480,"recencyAt":1790295480,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-18-00-01a0d5ed-187d-70c2-b4b6-b6881a68de09.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]}},"emittedAtMs":1790295480656}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","name":"codex_apps","status":"starting","error":null,"failureReason":null},"emittedAtMs":1790295480656}} {"type":"emit_inbound","label":"thread/settings/updated","frame":{"method":"thread/settings/updated","params":{"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","threadSettings":{"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","approvalPolicy":"never","approvalsReviewer":"user","sandboxPolicy":{"type":"dangerFullAccess"},"activePermissionProfile":null,"model":"gpt-6-luna","modelProvider":"openai","serviceTier":null,"effort":null,"summary":"detailed","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna","reasoning_effort":null,"developer_instructions":null}},"multiAgentMode":"explicitRequestOnly","personality":null}},"emittedAtMs":1790295480666}} -{"type":"emit_inbound","label":"turn/start","frame":{"id":4,"result":{"turn":{"id":"01a0d5ed-1957-7a22-8399-d0172af342fd","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} +{"type":"emit_inbound","label":"turn/start","frame":{"id":5,"result":{"turn":{"id":"01a0d5ed-1957-7a22-8399-d0172af342fd","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","status":{"type":"active","activeFlags":[]}},"emittedAtMs":1790295480718}} {"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","turn":{"id":"01a0d5ed-1957-7a22-8399-d0172af342fd","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1790295480,"completedAt":null,"durationMs":null}},"emittedAtMs":1790295480718}} {"type":"emit_inbound","label":"model/rerouted","frame":{"method":"model/rerouted","params":{"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","turnId":"01a0d5ed-1957-7a22-8399-d0172af342fd","fromModel":"gpt-6-luna","toModel":"gpt-6-astra","reason":"highRiskCyberActivity"}}} @@ -30,11 +33,11 @@ {"type":"emit_inbound","label":"thread/tokenUsage/updated","frame":{"method":"thread/tokenUsage/updated","params":{"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","turnId":"01a0d5ed-1957-7a22-8399-d0172af342fd","tokenUsage":{"total":{"totalTokens":21426,"inputTokens":21418,"cachedInputTokens":6912,"cacheWriteInputTokens":0,"outputTokens":8,"reasoningOutputTokens":0},"last":{"totalTokens":21426,"inputTokens":21418,"cachedInputTokens":6912,"cacheWriteInputTokens":0,"outputTokens":8,"reasoningOutputTokens":0},"modelContextWindow":258400}},"emittedAtMs":1790295485211}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","status":{"type":"idle"}},"emittedAtMs":1790295485220}} {"type":"emit_inbound","label":"turn/completed","frame":{"method":"turn/completed","params":{"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","turn":{"id":"01a0d5ed-1957-7a22-8399-d0172af342fd","items":[{"type":"agentMessage","id":"msg_06900ecb02a780a6016ab5bdbcd76887d0ba52ca8fee9da2e1","text":"first fixture turn complete","phase":"final_answer","memoryCitation":null,"delivery":null,"questions":null}],"itemsView":"summary","status":"completed","error":null,"startedAt":1790295480,"completedAt":1790295485,"durationMs":4550}},"emittedAtMs":1790295485220}} -{"type":"expect_outbound","label":"config/read","frame":{"id":5,"method":"config/read","params":{"cwd":"","includeLayers":false}}} -{"type":"emit_inbound","label":"config/read","frame":{"id":5,"result":{"config":{},"origins":{}}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":6,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Respond with exactly: second fixture turn complete","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"auto","threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":6,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":6,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":7,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Respond with exactly: second fixture turn complete","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"auto","threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","name":"xcodebuildmcp","status":"ready","error":null,"failureReason":null},"emittedAtMs":1790295485265}} -{"type":"emit_inbound","label":"turn/start","frame":{"id":6,"result":{"turn":{"id":"01a0d5ed-2b29-7353-a6d5-7745731173b7","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} +{"type":"emit_inbound","label":"turn/start","frame":{"id":7,"result":{"turn":{"id":"01a0d5ed-2b29-7353-a6d5-7745731173b7","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","status":{"type":"active","activeFlags":[]}},"emittedAtMs":1790295485286}} {"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","turn":{"id":"01a0d5ed-2b29-7353-a6d5-7745731173b7","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1790295485,"completedAt":null,"durationMs":null}},"emittedAtMs":1790295485286}} {"type":"emit_inbound","label":"item/started","frame":{"method":"item/started","params":{"item":{"type":"userMessage","id":"01a0d5ed-2bdf-7093-9e82-b961af1fe132","clientId":null,"content":[{"type":"text","text":"Respond with exactly: second fixture turn complete","text_elements":[]}]},"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","turnId":"01a0d5ed-2b29-7353-a6d5-7745731173b7","startedAtMs":1790295485409},"emittedAtMs":1790295485409}} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/command_output_streaming/codex_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/command_output_streaming/codex_transcript.ndjson index 5278ce59a6c74..954c6e4a48f26 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/command_output_streaming/codex_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/command_output_streaming/codex_transcript.ndjson @@ -5,9 +5,12 @@ {"type":"expect_outbound","label":"thread/start","frame":{"id":2,"method":"thread/start","params":{"config":{"tools.update_plan.enabled":true,"mcp_optional_startup_grace_ms":10000,"features.concurrent_reasoning_summaries":true},"cwd":"","model":"gpt-6-luna"}}} {"type":"emit_inbound","label":"remoteControl/status/changed","frame":{"method":"remoteControl/status/changed","params":{"status":"disabled","serverName":"replay-host","installationId":"00000000-0000-4000-8000-000000000000","environmentId":null},"emittedAtMs":1791001627148}} {"type":"emit_inbound","label":"thread/start","frame":{"id":2,"result":{"thread":{"id":"01a10004-0a27-7421-852d-0f7f99ace2d6","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/apps/server","runtimeWorkspaceRoots":["/home/replay-user/t3code/apps/server"]}],"extra":null,"sessionId":"01a10004-0a27-7421-852d-0f7f99ace2d6","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"cpa","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1791001627,"updatedAt":1791001627,"recencyAt":1791001627,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/10/03/rollout-2026-10-03T00-27-07-01a10004-0a27-7421-852d-0f7f99ace2d6.jsonl","cwd":"/home/replay-user/t3code/apps/server","cliVersion":"0.157.0","originator":"T3 Code","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]},"model":"gpt-6-luna","modelProvider":"cpa","serviceTier":"default","disabledPluginIds":[],"cwd":"/home/replay-user/t3code/apps/server","runtimeWorkspaceRoots":["/home/replay-user/t3code/apps/server"],"instructionSources":["/home/replay-user/.codex/AGENTS.md","/home/replay-user/t3code/AGENTS.md"],"approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"readOnly","networkAccess":false},"activePermissionProfile":{"id":":read-only","extends":null},"reasoningEffort":null,"multiAgentMode":"explicitRequestOnly"}}} -{"type":"expect_outbound","label":"config/read","frame":{"id":3,"method":"config/read","params":{"cwd":"","includeLayers":false}}} -{"type":"emit_inbound","label":"config/read","frame":{"id":3,"result":{"config":{},"origins":{}}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":4,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Run this exact shell command in the foreground and wait for it to finish: `for i in 1 2 3 4; do printf '\\033[32mstream line %s\\033[0m\\n' $i; sleep 1; done; printf 'progress 50%%\\rprogress 100%%\\n'`. Then respond exactly: command output fixture complete","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"networkAccess":false,"type":"workspaceWrite","writableRoots":[]},"summary":"auto","threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} +{"type":"expect_outbound","label":"thread/name/set","frame":{"id":3,"method":"thread/name/set","params":{"name":"Replay fixture: command_output_streaming","threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6"}}} +{"type":"emit_inbound","label":"thread/name/set","frame":{"id":3,"result":{}}} +{"type":"emit_inbound","label":"thread/name/updated","frame":{"method":"thread/name/updated","params":{"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","threadName":"Replay fixture: command_output_streaming"}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":4,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":4,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":5,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Run this exact shell command in the foreground and wait for it to finish: `for i in 1 2 3 4; do printf '\\033[32mstream line %s\\033[0m\\n' $i; sleep 1; done; printf 'progress 50%%\\rprogress 100%%\\n'`. Then respond exactly: command output fixture complete","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"networkAccess":false,"type":"workspaceWrite","writableRoots":[]},"summary":"auto","threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} {"type":"emit_inbound","label":"thread/started","frame":{"method":"thread/started","params":{"thread":{"id":"01a10004-0a27-7421-852d-0f7f99ace2d6","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/apps/server","runtimeWorkspaceRoots":["/home/replay-user/t3code/apps/server"]}],"extra":null,"sessionId":"01a10004-0a27-7421-852d-0f7f99ace2d6","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"cpa","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1791001627,"updatedAt":1791001627,"recencyAt":1791001627,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/10/03/rollout-2026-10-03T00-27-07-01a10004-0a27-7421-852d-0f7f99ace2d6.jsonl","cwd":"/home/replay-user/t3code/apps/server","cliVersion":"0.157.0","originator":"T3 Code","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]}},"emittedAtMs":1791001627410}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","name":"cua_repl","status":"starting","error":null,"failureReason":null},"emittedAtMs":1791001627411}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","name":"codex_apps","status":"starting","error":null,"failureReason":null},"emittedAtMs":1791001627411}} @@ -15,7 +18,7 @@ {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","name":"paper","status":"starting","error":null,"failureReason":null},"emittedAtMs":1791001627411}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","name":"node_repl","status":"starting","error":null,"failureReason":null},"emittedAtMs":1791001627411}} {"type":"emit_inbound","label":"thread/settings/updated","frame":{"method":"thread/settings/updated","params":{"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","threadSettings":{"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/apps/server","approvalPolicy":"never","approvalsReviewer":"user","sandboxPolicy":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":null,"model":"gpt-6-luna","modelProvider":"cpa","serviceTier":"default","effort":null,"summary":"detailed","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna","reasoning_effort":null,"developer_instructions":null}},"multiAgentMode":"explicitRequestOnly","personality":null}},"emittedAtMs":1791001627437}} -{"type":"emit_inbound","label":"turn/start","frame":{"id":4,"result":{"turn":{"id":"01a10004-0b1b-78f0-a41c-b253bded078e","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} +{"type":"emit_inbound","label":"turn/start","frame":{"id":5,"result":{"turn":{"id":"01a10004-0b1b-78f0-a41c-b253bded078e","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"account/updated","frame":{"method":"account/updated","params":{"authMode":"chatgpt","planType":"unknown"},"emittedAtMs":1791001627550}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","status":{"type":"active","activeFlags":[]}},"emittedAtMs":1791001627553}} {"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","turn":{"id":"01a10004-0b1b-78f0-a41c-b253bded078e","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1791001627,"completedAt":null,"durationMs":null}},"emittedAtMs":1791001627553}} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/delegated_task_status/codex_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/delegated_task_status/codex_transcript.ndjson index 8f42b9cc89a8e..95427ba136636 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/delegated_task_status/codex_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/delegated_task_status/codex_transcript.ndjson @@ -4,20 +4,26 @@ {"type":"expect_outbound","label":"initialized","frame":{"method":"initialized"}} {"type":"expect_outbound","label":"parent.thread/start","frame":{"id":2,"method":"thread/start","params":{"config":{"tools.update_plan.enabled":true,"mcp_optional_startup_grace_ms":10000,"features.concurrent_reasoning_summaries":true}}}} {"type":"emit_inbound","label":"parent.thread/start","frame":{"id":2,"result":{"thread":{"id":"019f1000-0000-7000-8000-000000000001","forkedFromId":null,"preview":"","ephemeral":false,"modelProvider":"openai","createdAt":1776739467,"updatedAt":1776739467,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/delegated-task-status-parent.jsonl","cwd":"/home/replay-user/t3code","cliVersion":"0.120.0","source":"vscode","agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"turns":[]},"model":"gpt-5.4","modelProvider":"openai","serviceTier":"fast","cwd":"/home/replay-user/t3code","approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"readOnlyAccess":{"type":"fullAccess"},"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"reasoningEffort":"xhigh"}}} -{"type":"expect_outbound","label":"config/read","frame":{"id":3,"method":"config/read","params":{"cwd":"","includeLayers":false}}} -{"type":"emit_inbound","label":"config/read","frame":{"id":3,"result":{"config":{},"origins":{}}}} -{"type":"expect_outbound","label":"parent.turn/start","frame":{"id":4,"method":"turn/start","params":{"approvalPolicy":"never","cwd":"","input":[{"text":"Keep this parent turn active while orchestration tools are tested.","type":"text"}],"model":"gpt-5.4","sandboxPolicy":{"type":"dangerFullAccess"},"threadId":"019f1000-0000-7000-8000-000000000001","approvalsReviewer":"user","summary":"auto","collaborationMode":{"mode":"default","settings":{"model":"gpt-5.4"}}}}} +{"type":"expect_outbound","label":"thread/name/set","frame":{"id":3,"method":"thread/name/set","params":{"name":"Replay fixture: delegated_task_status","threadId":"019f1000-0000-7000-8000-000000000001"}}} +{"type":"emit_inbound","label":"thread/name/set","frame":{"id":3,"result":{}}} +{"type":"emit_inbound","label":"thread/name/updated","frame":{"method":"thread/name/updated","params":{"threadId":"019f1000-0000-7000-8000-000000000001","threadName":"Replay fixture: delegated_task_status"}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":4,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":4,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"parent.turn/start","frame":{"id":5,"method":"turn/start","params":{"approvalPolicy":"never","cwd":"","input":[{"text":"Keep this parent turn active while orchestration tools are tested.","type":"text"}],"model":"gpt-5.4","sandboxPolicy":{"type":"dangerFullAccess"},"threadId":"019f1000-0000-7000-8000-000000000001","approvalsReviewer":"user","summary":"auto","collaborationMode":{"mode":"default","settings":{"model":"gpt-5.4"}}}}} {"type":"emit_inbound","label":"parent.thread/started","frame":{"method":"thread/started","params":{"thread":{"id":"019f1000-0000-7000-8000-000000000001","forkedFromId":null,"preview":"","ephemeral":false,"modelProvider":"openai","createdAt":1776739467,"updatedAt":1776739467,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/delegated-task-status-parent.jsonl","cwd":"/home/replay-user/t3code","cliVersion":"0.120.0","source":"vscode","agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"turns":[]}}}} -{"type":"emit_inbound","label":"parent.turn/start","frame":{"id":4,"result":{"turn":{"id":"019f1000-0000-7000-8000-000000000002","items":[],"status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} +{"type":"emit_inbound","label":"parent.turn/start","frame":{"id":5,"result":{"turn":{"id":"019f1000-0000-7000-8000-000000000002","items":[],"status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"parent.thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"019f1000-0000-7000-8000-000000000001","status":{"type":"active","activeFlags":[]}}}} {"type":"emit_inbound","label":"parent.turn/started","frame":{"method":"turn/started","params":{"threadId":"019f1000-0000-7000-8000-000000000001","turn":{"id":"019f1000-0000-7000-8000-000000000002","items":[],"status":"inProgress","error":null,"startedAt":1776739467,"completedAt":null,"durationMs":null}}}} -{"type":"expect_outbound","label":"child.thread/start","frame":{"id":5,"method":"thread/start","params":{"config":{"tools.update_plan.enabled":true,"mcp_optional_startup_grace_ms":10000,"features.concurrent_reasoning_summaries":true},"threadSource":"subagent"}}} -{"type":"emit_inbound","label":"child.thread/start","frame":{"id":5,"result":{"thread":{"id":"019f1000-0000-7000-8000-000000000003","forkedFromId":null,"preview":"","ephemeral":false,"modelProvider":"openai","createdAt":1776739468,"updatedAt":1776739468,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/delegated-task-status-child.jsonl","cwd":"/home/replay-user/t3code","cliVersion":"0.120.0","source":"vscode","agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"turns":[]},"model":"gpt-5.4","modelProvider":"openai","serviceTier":"fast","cwd":"/home/replay-user/t3code","approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"readOnlyAccess":{"type":"fullAccess"},"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"reasoningEffort":"xhigh"}}} -{"type":"expect_outbound","label":"config/read","frame":{"id":6,"method":"config/read","params":{"cwd":"","includeLayers":false}}} -{"type":"emit_inbound","label":"config/read","frame":{"id":6,"result":{"config":{},"origins":{}}}} -{"type":"expect_outbound","label":"child.original.turn/start","frame":{"id":7,"method":"turn/start","params":{"approvalPolicy":"never","cwd":"","input":[{"text":"Inspect the delegated API boundary and return the result.","type":"text"}],"model":"gpt-5.4","sandboxPolicy":{"type":"dangerFullAccess"},"threadId":"019f1000-0000-7000-8000-000000000003","approvalsReviewer":"user","summary":"auto","collaborationMode":{"mode":"default","settings":{"model":"gpt-5.4"}}}}} +{"type":"expect_outbound","label":"child.thread/start","frame":{"id":6,"method":"thread/start","params":{"config":{"tools.update_plan.enabled":true,"mcp_optional_startup_grace_ms":10000,"features.concurrent_reasoning_summaries":true},"threadSource":"subagent"}}} +{"type":"emit_inbound","label":"child.thread/start","frame":{"id":6,"result":{"thread":{"id":"019f1000-0000-7000-8000-000000000003","forkedFromId":null,"preview":"","ephemeral":false,"modelProvider":"openai","createdAt":1776739468,"updatedAt":1776739468,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/delegated-task-status-child.jsonl","cwd":"/home/replay-user/t3code","cliVersion":"0.120.0","source":"vscode","agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"turns":[]},"model":"gpt-5.4","modelProvider":"openai","serviceTier":"fast","cwd":"/home/replay-user/t3code","approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"readOnlyAccess":{"type":"fullAccess"},"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"reasoningEffort":"xhigh"}}} +{"type":"expect_outbound","label":"thread/name/set","frame":{"id":7,"method":"thread/name/set","params":{"name":"Replay fixture: delegated_task_status","threadId":"019f1000-0000-7000-8000-000000000003"}}} +{"type":"emit_inbound","label":"thread/name/set","frame":{"id":7,"result":{}}} +{"type":"emit_inbound","label":"thread/name/updated","frame":{"method":"thread/name/updated","params":{"threadId":"019f1000-0000-7000-8000-000000000003","threadName":"Replay fixture: delegated_task_status"}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":8,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":8,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"child.original.turn/start","frame":{"id":9,"method":"turn/start","params":{"approvalPolicy":"never","cwd":"","input":[{"text":"Inspect the delegated API boundary and return the result.","type":"text"}],"model":"gpt-5.4","sandboxPolicy":{"type":"dangerFullAccess"},"threadId":"019f1000-0000-7000-8000-000000000003","approvalsReviewer":"user","summary":"auto","collaborationMode":{"mode":"default","settings":{"model":"gpt-5.4"}}}}} {"type":"emit_inbound","label":"child.thread/started","frame":{"method":"thread/started","params":{"thread":{"id":"019f1000-0000-7000-8000-000000000003","forkedFromId":null,"preview":"","ephemeral":false,"modelProvider":"openai","createdAt":1776739468,"updatedAt":1776739468,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/delegated-task-status-child.jsonl","cwd":"/home/replay-user/t3code","cliVersion":"0.120.0","source":"vscode","agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"turns":[]}}}} -{"type":"emit_inbound","label":"child.original.turn/start","frame":{"id":7,"result":{"turn":{"id":"019f1000-0000-7000-8000-000000000004","items":[],"status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} +{"type":"emit_inbound","label":"child.original.turn/start","frame":{"id":9,"result":{"turn":{"id":"019f1000-0000-7000-8000-000000000004","items":[],"status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"child.original.thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"019f1000-0000-7000-8000-000000000003","status":{"type":"active","activeFlags":[]}}}} {"type":"emit_inbound","label":"child.original.turn/started","frame":{"method":"turn/started","params":{"threadId":"019f1000-0000-7000-8000-000000000003","turn":{"id":"019f1000-0000-7000-8000-000000000004","items":[],"status":"inProgress","error":null,"startedAt":1776739468,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"child.original.item/started","frame":{"method":"item/started","params":{"item":{"type":"agentMessage","id":"msg_delegated_task_status_original","text":"","phase":"final_answer","memoryCitation":null},"threadId":"019f1000-0000-7000-8000-000000000003","turnId":"019f1000-0000-7000-8000-000000000004"}}} @@ -25,20 +31,20 @@ {"type":"emit_inbound","label":"child.original.item/completed","frame":{"method":"item/completed","params":{"item":{"type":"agentMessage","id":"msg_delegated_task_status_original","text":"Delegated API boundary inspected.","phase":"final_answer","memoryCitation":null},"threadId":"019f1000-0000-7000-8000-000000000003","turnId":"019f1000-0000-7000-8000-000000000004"}}} {"type":"emit_inbound","label":"child.original.thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"019f1000-0000-7000-8000-000000000003","status":{"type":"idle"}}}} {"type":"emit_inbound","label":"child.original.turn/completed","frame":{"method":"turn/completed","params":{"threadId":"019f1000-0000-7000-8000-000000000003","turn":{"id":"019f1000-0000-7000-8000-000000000004","items":[],"status":"completed","error":null,"startedAt":1776739468,"completedAt":1776739469,"durationMs":1000}}}} -{"type":"expect_outbound","label":"config/read","frame":{"id":8,"method":"config/read","params":{"cwd":"","includeLayers":false}}} -{"type":"emit_inbound","label":"config/read","frame":{"id":8,"result":{"config":{},"origins":{}}}} -{"type":"expect_outbound","label":"child.running.turn/start","frame":{"id":9,"method":"turn/start","params":{"approvalPolicy":"never","cwd":"","input":[{"text":"Remain active until the parent cancels this delegated task.","type":"text"}],"model":"gpt-5.4","sandboxPolicy":{"type":"dangerFullAccess"},"threadId":"019f1000-0000-7000-8000-000000000003","approvalsReviewer":"user","summary":"auto","collaborationMode":{"mode":"default","settings":{"model":"gpt-5.4"}}}}} -{"type":"emit_inbound","label":"child.running.turn/start","frame":{"id":9,"result":{"turn":{"id":"019f1000-0000-7000-8000-000000000005","items":[],"status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":10,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":10,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"child.running.turn/start","frame":{"id":11,"method":"turn/start","params":{"approvalPolicy":"never","cwd":"","input":[{"text":"Remain active until the parent cancels this delegated task.","type":"text"}],"model":"gpt-5.4","sandboxPolicy":{"type":"dangerFullAccess"},"threadId":"019f1000-0000-7000-8000-000000000003","approvalsReviewer":"user","summary":"auto","collaborationMode":{"mode":"default","settings":{"model":"gpt-5.4"}}}}} +{"type":"emit_inbound","label":"child.running.turn/start","frame":{"id":11,"result":{"turn":{"id":"019f1000-0000-7000-8000-000000000005","items":[],"status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"child.running.thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"019f1000-0000-7000-8000-000000000003","status":{"type":"active","activeFlags":[]}}}} {"type":"emit_inbound","label":"child.running.turn/started","frame":{"method":"turn/started","params":{"threadId":"019f1000-0000-7000-8000-000000000003","turn":{"id":"019f1000-0000-7000-8000-000000000005","items":[],"status":"inProgress","error":null,"startedAt":1776739470,"completedAt":null,"durationMs":null}}}} -{"type":"expect_outbound","label":"child.running.turn/interrupt","frame":{"id":10,"method":"turn/interrupt","params":{"threadId":"019f1000-0000-7000-8000-000000000003","turnId":"019f1000-0000-7000-8000-000000000005"}}} -{"type":"emit_inbound","label":"child.running.turn/interrupt","frame":{"id":10,"result":{}}} +{"type":"expect_outbound","label":"child.running.turn/interrupt","frame":{"id":12,"method":"turn/interrupt","params":{"threadId":"019f1000-0000-7000-8000-000000000003","turnId":"019f1000-0000-7000-8000-000000000005"}}} +{"type":"emit_inbound","label":"child.running.turn/interrupt","frame":{"id":12,"result":{}}} {"type":"emit_inbound","label":"child.running.thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"019f1000-0000-7000-8000-000000000003","status":{"type":"idle"}}}} {"type":"emit_inbound","label":"child.running.turn/completed","frame":{"method":"turn/completed","params":{"threadId":"019f1000-0000-7000-8000-000000000003","turn":{"id":"019f1000-0000-7000-8000-000000000005","items":[],"status":"interrupted","error":null,"startedAt":1776739470,"completedAt":1776739471,"durationMs":1000}}}} -{"type":"expect_outbound","label":"config/read","frame":{"id":11,"method":"config/read","params":{"cwd":"","includeLayers":false}}} -{"type":"emit_inbound","label":"config/read","frame":{"id":11,"result":{"config":{},"origins":{}}}} -{"type":"expect_outbound","label":"child.queued.turn/start","frame":{"id":12,"method":"turn/start","params":{"approvalPolicy":"never","cwd":"","input":[{"text":"Complete the queued follow-up and return the final result.","type":"text"}],"model":"gpt-5.4","sandboxPolicy":{"type":"dangerFullAccess"},"threadId":"019f1000-0000-7000-8000-000000000003","approvalsReviewer":"user","summary":"auto","collaborationMode":{"mode":"default","settings":{"model":"gpt-5.4"}}}}} -{"type":"emit_inbound","label":"child.queued.turn/start","frame":{"id":12,"result":{"turn":{"id":"019f1000-0000-7000-8000-000000000006","items":[],"status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":13,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":13,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"child.queued.turn/start","frame":{"id":14,"method":"turn/start","params":{"approvalPolicy":"never","cwd":"","input":[{"text":"Complete the queued follow-up and return the final result.","type":"text"}],"model":"gpt-5.4","sandboxPolicy":{"type":"dangerFullAccess"},"threadId":"019f1000-0000-7000-8000-000000000003","approvalsReviewer":"user","summary":"auto","collaborationMode":{"mode":"default","settings":{"model":"gpt-5.4"}}}}} +{"type":"emit_inbound","label":"child.queued.turn/start","frame":{"id":14,"result":{"turn":{"id":"019f1000-0000-7000-8000-000000000006","items":[],"status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"child.queued.thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"019f1000-0000-7000-8000-000000000003","status":{"type":"active","activeFlags":[]}}}} {"type":"emit_inbound","label":"child.queued.turn/started","frame":{"method":"turn/started","params":{"threadId":"019f1000-0000-7000-8000-000000000003","turn":{"id":"019f1000-0000-7000-8000-000000000006","items":[],"status":"inProgress","error":null,"startedAt":1776739472,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"child.queued.item/started","frame":{"method":"item/started","params":{"item":{"type":"agentMessage","id":"msg_delegated_task_status_queued","text":"","phase":"final_answer","memoryCitation":null},"threadId":"019f1000-0000-7000-8000-000000000003","turnId":"019f1000-0000-7000-8000-000000000006"}}} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/message_steering/codex_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/message_steering/codex_transcript.ndjson index 516e93a236bca..04326cba7f59d 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/message_steering/codex_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/message_steering/codex_transcript.ndjson @@ -6,17 +6,20 @@ {"type":"emit_inbound","label":"configWarning","frame":{"method":"configWarning","params":{"summary":"Codex could not find bubblewrap on PATH. Install bubblewrap with your OS package manager. See the sandbox prerequisites: https://developers.openai.com/codex/concepts/sandboxing#prerequisites. Codex will use the bundled bubblewrap in the meantime.","details":null},"emittedAtMs":1790295500250}} {"type":"emit_inbound","label":"remoteControl/status/changed","frame":{"method":"remoteControl/status/changed","params":{"status":"disabled","serverName":"replay-host","installationId":"00000000-0000-4000-8000-000000000000","environmentId":null},"emittedAtMs":1790295500250}} {"type":"emit_inbound","label":"thread/start","frame":{"id":2,"result":{"thread":{"id":"01a0d5ed-65ea-7d42-b8e9-d06f045cfa86","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d5ed-65ea-7d42-b8e9-d06f045cfa86","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790295500,"updatedAt":1790295500,"recencyAt":1790295500,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-18-20-01a0d5ed-65ea-7d42-b8e9-d06f045cfa86.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]},"model":"gpt-6-luna","modelProvider":"openai","serviceTier":null,"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"],"instructionSources":["/home/replay-user/.codex/AGENTS.md","/home/replay-user/t3code/AGENTS.md"],"approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":{"id":":workspace","extends":null},"reasoningEffort":null,"multiAgentMode":"explicitRequestOnly"}}} -{"type":"expect_outbound","label":"config/read","frame":{"id":3,"method":"config/read","params":{"cwd":"","includeLayers":false}}} -{"type":"emit_inbound","label":"config/read","frame":{"id":3,"result":{"config":{},"origins":{}}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":4,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Respond with exactly: steering fixture initial response","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"auto","threadId":"01a0d5ed-65ea-7d42-b8e9-d06f045cfa86","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} +{"type":"expect_outbound","label":"thread/name/set","frame":{"id":3,"method":"thread/name/set","params":{"name":"Replay fixture: message_steering","threadId":"01a0d5ed-65ea-7d42-b8e9-d06f045cfa86"}}} +{"type":"emit_inbound","label":"thread/name/set","frame":{"id":3,"result":{}}} +{"type":"emit_inbound","label":"thread/name/updated","frame":{"method":"thread/name/updated","params":{"threadId":"01a0d5ed-65ea-7d42-b8e9-d06f045cfa86","threadName":"Replay fixture: message_steering"}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":4,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":4,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":5,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Respond with exactly: steering fixture initial response","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"auto","threadId":"01a0d5ed-65ea-7d42-b8e9-d06f045cfa86","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} {"type":"emit_inbound","label":"thread/started","frame":{"method":"thread/started","params":{"thread":{"id":"01a0d5ed-65ea-7d42-b8e9-d06f045cfa86","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d5ed-65ea-7d42-b8e9-d06f045cfa86","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790295500,"updatedAt":1790295500,"recencyAt":1790295500,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-18-20-01a0d5ed-65ea-7d42-b8e9-d06f045cfa86.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]}},"emittedAtMs":1790295500547}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0d5ed-65ea-7d42-b8e9-d06f045cfa86","name":"codex_apps","status":"starting","error":null,"failureReason":null},"emittedAtMs":1790295500547}} {"type":"emit_inbound","label":"thread/settings/updated","frame":{"method":"thread/settings/updated","params":{"threadId":"01a0d5ed-65ea-7d42-b8e9-d06f045cfa86","threadSettings":{"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","approvalPolicy":"never","approvalsReviewer":"user","sandboxPolicy":{"type":"dangerFullAccess"},"activePermissionProfile":null,"model":"gpt-6-luna","modelProvider":"openai","serviceTier":null,"effort":null,"summary":"detailed","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna","reasoning_effort":null,"developer_instructions":null}},"multiAgentMode":"explicitRequestOnly","personality":null}},"emittedAtMs":1790295500567}} -{"type":"emit_inbound","label":"turn/start","frame":{"id":4,"result":{"turn":{"id":"01a0d5ed-670e-7032-9a87-707c736491a6","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} +{"type":"emit_inbound","label":"turn/start","frame":{"id":5,"result":{"turn":{"id":"01a0d5ed-670e-7032-9a87-707c736491a6","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d5ed-65ea-7d42-b8e9-d06f045cfa86","status":{"type":"active","activeFlags":[]}},"emittedAtMs":1790295500626}} {"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"01a0d5ed-65ea-7d42-b8e9-d06f045cfa86","turn":{"id":"01a0d5ed-670e-7032-9a87-707c736491a6","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1790295500,"completedAt":null,"durationMs":null}},"emittedAtMs":1790295500626}} -{"type":"expect_outbound","label":"turn/steer","frame":{"id":5,"method":"turn/steer","params":{"expectedTurnId":"01a0d5ed-670e-7032-9a87-707c736491a6","input":[{"text":"Actually, respond with exactly: steering fixture observed","type":"text"}],"threadId":"01a0d5ed-65ea-7d42-b8e9-d06f045cfa86"}}} -{"type":"emit_inbound","label":"turn/steer","frame":{"id":5,"result":{"turnId":"01a0d5ed-670e-7032-9a87-707c736491a6"}}} +{"type":"expect_outbound","label":"turn/steer","frame":{"id":6,"method":"turn/steer","params":{"expectedTurnId":"01a0d5ed-670e-7032-9a87-707c736491a6","input":[{"text":"Actually, respond with exactly: steering fixture observed","type":"text"}],"threadId":"01a0d5ed-65ea-7d42-b8e9-d06f045cfa86"}}} +{"type":"emit_inbound","label":"turn/steer","frame":{"id":6,"result":{"turnId":"01a0d5ed-670e-7032-9a87-707c736491a6"}}} {"type":"emit_inbound","label":"account/updated","frame":{"method":"account/updated","params":{"authMode":"chatgpt","planType":"unknown"},"emittedAtMs":1790295500936}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0d5ed-65ea-7d42-b8e9-d06f045cfa86","name":"xcodebuildmcp","status":"starting","error":null,"failureReason":null},"emittedAtMs":1790295501151}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0d5ed-65ea-7d42-b8e9-d06f045cfa86","name":"codex_apps","status":"ready","error":null,"failureReason":null},"emittedAtMs":1790295501388}} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/multi_turn/codex_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/multi_turn/codex_transcript.ndjson index 01fd4315f53ea..47194cff98a1d 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/multi_turn/codex_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/multi_turn/codex_transcript.ndjson @@ -6,13 +6,16 @@ {"type":"emit_inbound","label":"configWarning","frame":{"method":"configWarning","params":{"summary":"Codex could not find bubblewrap on PATH. Install bubblewrap with your OS package manager. See the sandbox prerequisites: https://developers.openai.com/codex/concepts/sandboxing#prerequisites. Codex will use the bundled bubblewrap in the meantime.","details":null},"emittedAtMs":1790295480414}} {"type":"emit_inbound","label":"remoteControl/status/changed","frame":{"method":"remoteControl/status/changed","params":{"status":"disabled","serverName":"replay-host","installationId":"00000000-0000-4000-8000-000000000000","environmentId":null},"emittedAtMs":1790295480414}} {"type":"emit_inbound","label":"thread/start","frame":{"id":2,"result":{"thread":{"id":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790295480,"updatedAt":1790295480,"recencyAt":1790295480,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-18-00-01a0d5ed-187d-70c2-b4b6-b6881a68de09.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]},"model":"gpt-6-luna","modelProvider":"openai","serviceTier":null,"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"],"instructionSources":["/home/replay-user/.codex/AGENTS.md","/home/replay-user/t3code/AGENTS.md"],"approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":{"id":":workspace","extends":null},"reasoningEffort":null,"multiAgentMode":"explicitRequestOnly"}}} -{"type":"expect_outbound","label":"config/read","frame":{"id":3,"method":"config/read","params":{"cwd":"","includeLayers":false}}} -{"type":"emit_inbound","label":"config/read","frame":{"id":3,"result":{"config":{},"origins":{}}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":4,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Respond with exactly: first fixture turn complete","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"auto","threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} +{"type":"expect_outbound","label":"thread/name/set","frame":{"id":3,"method":"thread/name/set","params":{"name":"Replay fixture: multi_turn","threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09"}}} +{"type":"emit_inbound","label":"thread/name/set","frame":{"id":3,"result":{}}} +{"type":"emit_inbound","label":"thread/name/updated","frame":{"method":"thread/name/updated","params":{"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","threadName":"Replay fixture: multi_turn"}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":4,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":4,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":5,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Respond with exactly: first fixture turn complete","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"auto","threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} {"type":"emit_inbound","label":"thread/started","frame":{"method":"thread/started","params":{"thread":{"id":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790295480,"updatedAt":1790295480,"recencyAt":1790295480,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-18-00-01a0d5ed-187d-70c2-b4b6-b6881a68de09.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]}},"emittedAtMs":1790295480656}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","name":"codex_apps","status":"starting","error":null,"failureReason":null},"emittedAtMs":1790295480656}} {"type":"emit_inbound","label":"thread/settings/updated","frame":{"method":"thread/settings/updated","params":{"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","threadSettings":{"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","approvalPolicy":"never","approvalsReviewer":"user","sandboxPolicy":{"type":"dangerFullAccess"},"activePermissionProfile":null,"model":"gpt-6-luna","modelProvider":"openai","serviceTier":null,"effort":null,"summary":"detailed","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna","reasoning_effort":null,"developer_instructions":null}},"multiAgentMode":"explicitRequestOnly","personality":null}},"emittedAtMs":1790295480666}} -{"type":"emit_inbound","label":"turn/start","frame":{"id":4,"result":{"turn":{"id":"01a0d5ed-1957-7a22-8399-d0172af342fd","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} +{"type":"emit_inbound","label":"turn/start","frame":{"id":5,"result":{"turn":{"id":"01a0d5ed-1957-7a22-8399-d0172af342fd","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","status":{"type":"active","activeFlags":[]}},"emittedAtMs":1790295480718}} {"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","turn":{"id":"01a0d5ed-1957-7a22-8399-d0172af342fd","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1790295480,"completedAt":null,"durationMs":null}},"emittedAtMs":1790295480718}} {"type":"emit_inbound","label":"account/updated","frame":{"method":"account/updated","params":{"authMode":"chatgpt","planType":"unknown"},"emittedAtMs":1790295481015}} @@ -29,11 +32,11 @@ {"type":"emit_inbound","label":"thread/tokenUsage/updated","frame":{"method":"thread/tokenUsage/updated","params":{"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","turnId":"01a0d5ed-1957-7a22-8399-d0172af342fd","tokenUsage":{"total":{"totalTokens":21426,"inputTokens":21418,"cachedInputTokens":6912,"cacheWriteInputTokens":0,"outputTokens":8,"reasoningOutputTokens":0},"last":{"totalTokens":21426,"inputTokens":21418,"cachedInputTokens":6912,"cacheWriteInputTokens":0,"outputTokens":8,"reasoningOutputTokens":0},"modelContextWindow":258400}},"emittedAtMs":1790295485211}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","status":{"type":"idle"}},"emittedAtMs":1790295485220}} {"type":"emit_inbound","label":"turn/completed","frame":{"method":"turn/completed","params":{"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","turn":{"id":"01a0d5ed-1957-7a22-8399-d0172af342fd","items":[{"type":"agentMessage","id":"msg_06900ecb02a780a6016ab5bdbcd76887d0ba52ca8fee9da2e1","text":"first fixture turn complete","phase":"final_answer","memoryCitation":null,"delivery":null,"questions":null}],"itemsView":"summary","status":"completed","error":null,"startedAt":1790295480,"completedAt":1790295485,"durationMs":4550}},"emittedAtMs":1790295485220}} -{"type":"expect_outbound","label":"config/read","frame":{"id":5,"method":"config/read","params":{"cwd":"","includeLayers":false}}} -{"type":"emit_inbound","label":"config/read","frame":{"id":5,"result":{"config":{},"origins":{}}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":6,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Respond with exactly: second fixture turn complete","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"auto","threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":6,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":6,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":7,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Respond with exactly: second fixture turn complete","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"auto","threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","name":"xcodebuildmcp","status":"ready","error":null,"failureReason":null},"emittedAtMs":1790295485265}} -{"type":"emit_inbound","label":"turn/start","frame":{"id":6,"result":{"turn":{"id":"01a0d5ed-2b29-7353-a6d5-7745731173b7","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} +{"type":"emit_inbound","label":"turn/start","frame":{"id":7,"result":{"turn":{"id":"01a0d5ed-2b29-7353-a6d5-7745731173b7","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","status":{"type":"active","activeFlags":[]}},"emittedAtMs":1790295485286}} {"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","turn":{"id":"01a0d5ed-2b29-7353-a6d5-7745731173b7","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1790295485,"completedAt":null,"durationMs":null}},"emittedAtMs":1790295485286}} {"type":"emit_inbound","label":"item/started","frame":{"method":"item/started","params":{"item":{"type":"userMessage","id":"01a0d5ed-2bdf-7093-9e82-b961af1fe132","clientId":null,"content":[{"type":"text","text":"Respond with exactly: second fixture turn complete","text_elements":[]}]},"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","turnId":"01a0d5ed-2b29-7353-a6d5-7745731173b7","startedAtMs":1790295485409},"emittedAtMs":1790295485409}} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/plan_questions/codex_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/plan_questions/codex_transcript.ndjson index 938155bb3f7e6..b44351ebb9ce3 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/plan_questions/codex_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/plan_questions/codex_transcript.ndjson @@ -6,13 +6,16 @@ {"type":"emit_inbound","label":"configWarning","frame":{"method":"configWarning","params":{"summary":"Codex could not find bubblewrap on PATH. Install bubblewrap with your OS package manager. See the sandbox prerequisites: https://developers.openai.com/codex/concepts/sandboxing#prerequisites. Codex will use the bundled bubblewrap in the meantime.","details":null},"emittedAtMs":1790295620180}} {"type":"emit_inbound","label":"remoteControl/status/changed","frame":{"method":"remoteControl/status/changed","params":{"status":"disabled","serverName":"replay-host","installationId":"00000000-0000-4000-8000-000000000000","environmentId":null},"emittedAtMs":1790295620180}} {"type":"emit_inbound","label":"thread/start","frame":{"id":2,"result":{"thread":{"id":"01a0d5ef-3a6a-75d0-9942-61b29ab82328","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d5ef-3a6a-75d0-9942-61b29ab82328","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790295620,"updatedAt":1790295620,"recencyAt":1790295620,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-20-20-01a0d5ef-3a6a-75d0-9942-61b29ab82328.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]},"model":"gpt-6-luna","modelProvider":"openai","serviceTier":null,"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"],"instructionSources":["/home/replay-user/.codex/AGENTS.md","/home/replay-user/t3code/AGENTS.md"],"approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":{"id":":workspace","extends":null},"reasoningEffort":null,"multiAgentMode":"explicitRequestOnly"}}} -{"type":"expect_outbound","label":"config/read","frame":{"id":3,"method":"config/read","params":{"cwd":"","includeLayers":false}}} -{"type":"emit_inbound","label":"config/read","frame":{"id":3,"result":{"config":{},"origins":{}}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":4,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Use request_user_input to ask one multiple-choice clarifying question about whether this fixture should prefer strict schemas or UI flexibility. After receiving the answer, respond exactly: plan questions fixture complete","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"networkAccess":false,"type":"readOnly"},"summary":"auto","threadId":"01a0d5ef-3a6a-75d0-9942-61b29ab82328","collaborationMode":{"mode":"plan","settings":{"model":"gpt-6-luna"}}}}} +{"type":"expect_outbound","label":"thread/name/set","frame":{"id":3,"method":"thread/name/set","params":{"name":"Replay fixture: plan_questions","threadId":"01a0d5ef-3a6a-75d0-9942-61b29ab82328"}}} +{"type":"emit_inbound","label":"thread/name/set","frame":{"id":3,"result":{}}} +{"type":"emit_inbound","label":"thread/name/updated","frame":{"method":"thread/name/updated","params":{"threadId":"01a0d5ef-3a6a-75d0-9942-61b29ab82328","threadName":"Replay fixture: plan_questions"}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":4,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":4,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":5,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Use request_user_input to ask one multiple-choice clarifying question about whether this fixture should prefer strict schemas or UI flexibility. After receiving the answer, respond exactly: plan questions fixture complete","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"networkAccess":false,"type":"readOnly"},"summary":"auto","threadId":"01a0d5ef-3a6a-75d0-9942-61b29ab82328","collaborationMode":{"mode":"plan","settings":{"model":"gpt-6-luna"}}}}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0d5ef-3a6a-75d0-9942-61b29ab82328","name":"codex_apps","status":"starting","error":null,"failureReason":null},"emittedAtMs":1790295620428}} {"type":"emit_inbound","label":"thread/started","frame":{"method":"thread/started","params":{"thread":{"id":"01a0d5ef-3a6a-75d0-9942-61b29ab82328","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d5ef-3a6a-75d0-9942-61b29ab82328","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790295620,"updatedAt":1790295620,"recencyAt":1790295620,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-20-20-01a0d5ef-3a6a-75d0-9942-61b29ab82328.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]}},"emittedAtMs":1790295620428}} {"type":"emit_inbound","label":"thread/settings/updated","frame":{"method":"thread/settings/updated","params":{"threadId":"01a0d5ef-3a6a-75d0-9942-61b29ab82328","threadSettings":{"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","approvalPolicy":"never","approvalsReviewer":"user","sandboxPolicy":{"type":"readOnly","networkAccess":false},"activePermissionProfile":null,"model":"gpt-6-luna","modelProvider":"openai","serviceTier":null,"effort":"medium","summary":"detailed","collaborationMode":{"mode":"plan","settings":{"model":"gpt-6-luna","reasoning_effort":"medium","developer_instructions":"You are in Plan mode. Prefer request_user_input for clarifying questions. When presenting a complete plan, wrap it in and ."}},"multiAgentMode":"explicitRequestOnly","personality":null}},"emittedAtMs":1790295620457}} -{"type":"emit_inbound","label":"turn/start","frame":{"id":4,"result":{"turn":{"id":"01a0d5ef-3b5a-7bb2-9cd2-da112b6b158f","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} +{"type":"emit_inbound","label":"turn/start","frame":{"id":5,"result":{"turn":{"id":"01a0d5ef-3b5a-7bb2-9cd2-da112b6b158f","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d5ef-3a6a-75d0-9942-61b29ab82328","status":{"type":"active","activeFlags":[]}},"emittedAtMs":1790295620520}} {"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"01a0d5ef-3a6a-75d0-9942-61b29ab82328","turn":{"id":"01a0d5ef-3b5a-7bb2-9cd2-da112b6b158f","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1790295620,"completedAt":null,"durationMs":null}},"emittedAtMs":1790295620520}} {"type":"emit_inbound","label":"account/updated","frame":{"method":"account/updated","params":{"authMode":"chatgpt","planType":"unknown"},"emittedAtMs":1790295620774}} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/proposed_plan/codex_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/proposed_plan/codex_transcript.ndjson index 0894cf067e26f..01e59956ea15f 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/proposed_plan/codex_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/proposed_plan/codex_transcript.ndjson @@ -6,13 +6,16 @@ {"type":"emit_inbound","label":"configWarning","frame":{"method":"configWarning","params":{"summary":"Codex could not find bubblewrap on PATH. Install bubblewrap with your OS package manager. See the sandbox prerequisites: https://developers.openai.com/codex/concepts/sandboxing#prerequisites. Codex will use the bundled bubblewrap in the meantime.","details":null},"emittedAtMs":1790295608195}} {"type":"emit_inbound","label":"remoteControl/status/changed","frame":{"method":"remoteControl/status/changed","params":{"status":"disabled","serverName":"replay-host","installationId":"00000000-0000-4000-8000-000000000000","environmentId":null},"emittedAtMs":1790295608195}} {"type":"emit_inbound","label":"thread/start","frame":{"id":2,"result":{"thread":{"id":"01a0d5ef-0ba3-7552-b090-7cfbb328e278","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d5ef-0ba3-7552-b090-7cfbb328e278","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790295608,"updatedAt":1790295608,"recencyAt":1790295608,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-20-08-01a0d5ef-0ba3-7552-b090-7cfbb328e278.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]},"model":"gpt-6-luna","modelProvider":"openai","serviceTier":null,"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"],"instructionSources":["/home/replay-user/.codex/AGENTS.md","/home/replay-user/t3code/AGENTS.md"],"approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":{"id":":workspace","extends":null},"reasoningEffort":null,"multiAgentMode":"explicitRequestOnly"}}} -{"type":"expect_outbound","label":"config/read","frame":{"id":3,"method":"config/read","params":{"cwd":"","includeLayers":false}}} -{"type":"emit_inbound","label":"config/read","frame":{"id":3,"result":{"config":{},"origins":{}}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":4,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Create a short implementation plan for adding deterministic replay fixtures. Do not ask questions. Present the final plan in a proposed plan block.","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"networkAccess":false,"type":"readOnly"},"summary":"auto","threadId":"01a0d5ef-0ba3-7552-b090-7cfbb328e278","collaborationMode":{"mode":"plan","settings":{"model":"gpt-6-luna"}}}}} +{"type":"expect_outbound","label":"thread/name/set","frame":{"id":3,"method":"thread/name/set","params":{"name":"Replay fixture: proposed_plan","threadId":"01a0d5ef-0ba3-7552-b090-7cfbb328e278"}}} +{"type":"emit_inbound","label":"thread/name/set","frame":{"id":3,"result":{}}} +{"type":"emit_inbound","label":"thread/name/updated","frame":{"method":"thread/name/updated","params":{"threadId":"01a0d5ef-0ba3-7552-b090-7cfbb328e278","threadName":"Replay fixture: proposed_plan"}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":4,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":4,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":5,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Create a short implementation plan for adding deterministic replay fixtures. Do not ask questions. Present the final plan in a proposed plan block.","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"networkAccess":false,"type":"readOnly"},"summary":"auto","threadId":"01a0d5ef-0ba3-7552-b090-7cfbb328e278","collaborationMode":{"mode":"plan","settings":{"model":"gpt-6-luna"}}}}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0d5ef-0ba3-7552-b090-7cfbb328e278","name":"codex_apps","status":"starting","error":null,"failureReason":null},"emittedAtMs":1790295608443}} {"type":"emit_inbound","label":"thread/started","frame":{"method":"thread/started","params":{"thread":{"id":"01a0d5ef-0ba3-7552-b090-7cfbb328e278","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d5ef-0ba3-7552-b090-7cfbb328e278","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790295608,"updatedAt":1790295608,"recencyAt":1790295608,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-20-08-01a0d5ef-0ba3-7552-b090-7cfbb328e278.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]}},"emittedAtMs":1790295608443}} {"type":"emit_inbound","label":"thread/settings/updated","frame":{"method":"thread/settings/updated","params":{"threadId":"01a0d5ef-0ba3-7552-b090-7cfbb328e278","threadSettings":{"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","approvalPolicy":"never","approvalsReviewer":"user","sandboxPolicy":{"type":"readOnly","networkAccess":false},"activePermissionProfile":null,"model":"gpt-6-luna","modelProvider":"openai","serviceTier":null,"effort":"medium","summary":"detailed","collaborationMode":{"mode":"plan","settings":{"model":"gpt-6-luna","reasoning_effort":"medium","developer_instructions":"You are in Plan mode. Prefer request_user_input for clarifying questions. When presenting a complete plan, wrap it in and ."}},"multiAgentMode":"explicitRequestOnly","personality":null}},"emittedAtMs":1790295608464}} -{"type":"emit_inbound","label":"turn/start","frame":{"id":4,"result":{"turn":{"id":"01a0d5ef-0c85-7f41-ad02-13753158be02","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} +{"type":"emit_inbound","label":"turn/start","frame":{"id":5,"result":{"turn":{"id":"01a0d5ef-0c85-7f41-ad02-13753158be02","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d5ef-0ba3-7552-b090-7cfbb328e278","status":{"type":"active","activeFlags":[]}},"emittedAtMs":1790295608547}} {"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"01a0d5ef-0ba3-7552-b090-7cfbb328e278","turn":{"id":"01a0d5ef-0c85-7f41-ad02-13753158be02","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1790295608,"completedAt":null,"durationMs":null}},"emittedAtMs":1790295608548}} {"type":"emit_inbound","label":"account/updated","frame":{"method":"account/updated","params":{"authMode":"chatgpt","planType":"unknown"},"emittedAtMs":1790295608936}} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/provider_thread_resume/codex_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/provider_thread_resume/codex_transcript.ndjson index 9acdc4e0a05ca..38a7a83c45fc5 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/provider_thread_resume/codex_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/provider_thread_resume/codex_transcript.ndjson @@ -6,13 +6,16 @@ {"type":"emit_inbound","label":"configWarning","frame":{"method":"configWarning","params":{"summary":"Codex could not find bubblewrap on PATH. Install bubblewrap with your OS package manager. See the sandbox prerequisites: https://developers.openai.com/codex/concepts/sandboxing#prerequisites. Codex will use the bundled bubblewrap in the meantime.","details":null},"emittedAtMs":1790295630509}} {"type":"emit_inbound","label":"remoteControl/status/changed","frame":{"method":"remoteControl/status/changed","params":{"status":"disabled","serverName":"replay-host","installationId":"00000000-0000-4000-8000-000000000000","environmentId":null},"emittedAtMs":1790295630509}} {"type":"emit_inbound","label":"thread/start","frame":{"id":2,"result":{"thread":{"id":"01a0d5ef-62bd-7c20-861b-0528ff7d86bd","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d5ef-62bd-7c20-861b-0528ff7d86bd","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790295630,"updatedAt":1790295630,"recencyAt":1790295630,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-20-30-01a0d5ef-62bd-7c20-861b-0528ff7d86bd.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]},"model":"gpt-6-luna","modelProvider":"openai","serviceTier":null,"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"],"instructionSources":["/home/replay-user/.codex/AGENTS.md","/home/replay-user/t3code/AGENTS.md"],"approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":{"id":":workspace","extends":null},"reasoningEffort":null,"multiAgentMode":"explicitRequestOnly"}}} -{"type":"expect_outbound","label":"config/read","frame":{"id":3,"method":"config/read","params":{"cwd":"","includeLayers":false}}} -{"type":"emit_inbound","label":"config/read","frame":{"id":3,"result":{"config":{},"origins":{}}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":4,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Respond with exactly: provider thread resume fixture first turn complete","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"auto","threadId":"01a0d5ef-62bd-7c20-861b-0528ff7d86bd","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} +{"type":"expect_outbound","label":"thread/name/set","frame":{"id":3,"method":"thread/name/set","params":{"name":"Replay fixture: provider_thread_resume","threadId":"01a0d5ef-62bd-7c20-861b-0528ff7d86bd"}}} +{"type":"emit_inbound","label":"thread/name/set","frame":{"id":3,"result":{}}} +{"type":"emit_inbound","label":"thread/name/updated","frame":{"method":"thread/name/updated","params":{"threadId":"01a0d5ef-62bd-7c20-861b-0528ff7d86bd","threadName":"Replay fixture: provider_thread_resume"}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":4,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":4,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":5,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Respond with exactly: provider thread resume fixture first turn complete","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"auto","threadId":"01a0d5ef-62bd-7c20-861b-0528ff7d86bd","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0d5ef-62bd-7c20-861b-0528ff7d86bd","name":"codex_apps","status":"starting","error":null,"failureReason":null},"emittedAtMs":1790295630711}} {"type":"emit_inbound","label":"thread/started","frame":{"method":"thread/started","params":{"thread":{"id":"01a0d5ef-62bd-7c20-861b-0528ff7d86bd","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d5ef-62bd-7c20-861b-0528ff7d86bd","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790295630,"updatedAt":1790295630,"recencyAt":1790295630,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-20-30-01a0d5ef-62bd-7c20-861b-0528ff7d86bd.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]}},"emittedAtMs":1790295630711}} {"type":"emit_inbound","label":"thread/settings/updated","frame":{"method":"thread/settings/updated","params":{"threadId":"01a0d5ef-62bd-7c20-861b-0528ff7d86bd","threadSettings":{"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","approvalPolicy":"never","approvalsReviewer":"user","sandboxPolicy":{"type":"dangerFullAccess"},"activePermissionProfile":null,"model":"gpt-6-luna","modelProvider":"openai","serviceTier":null,"effort":null,"summary":"detailed","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna","reasoning_effort":null,"developer_instructions":null}},"multiAgentMode":"explicitRequestOnly","personality":null}},"emittedAtMs":1790295630725}} -{"type":"emit_inbound","label":"turn/start","frame":{"id":4,"result":{"turn":{"id":"01a0d5ef-637e-7ba2-bf9a-5534a6f98a83","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} +{"type":"emit_inbound","label":"turn/start","frame":{"id":5,"result":{"turn":{"id":"01a0d5ef-637e-7ba2-bf9a-5534a6f98a83","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d5ef-62bd-7c20-861b-0528ff7d86bd","status":{"type":"active","activeFlags":[]}},"emittedAtMs":1790295630781}} {"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"01a0d5ef-62bd-7c20-861b-0528ff7d86bd","turn":{"id":"01a0d5ef-637e-7ba2-bf9a-5534a6f98a83","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1790295630,"completedAt":null,"durationMs":null}},"emittedAtMs":1790295630781}} {"type":"emit_inbound","label":"account/updated","frame":{"method":"account/updated","params":{"authMode":"chatgpt","planType":"unknown"},"emittedAtMs":1790295631109}} @@ -43,13 +46,16 @@ {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0d5ef-62bd-7c20-861b-0528ff7d86bd","name":"codex_apps","status":"starting","error":null,"failureReason":null},"emittedAtMs":1790295635910}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d5ef-62bd-7c20-861b-0528ff7d86bd","status":{"type":"idle"}},"emittedAtMs":1790295635918}} {"type":"emit_inbound","label":"thread/resume","frame":{"id":2,"result":{"thread":{"id":"01a0d5ef-62bd-7c20-861b-0528ff7d86bd","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d5ef-62bd-7c20-861b-0528ff7d86bd","forkedFromId":null,"parentThreadId":null,"preview":"Respond with exactly: provider thread resume fixture first turn complete","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790295630,"updatedAt":1790295635,"recencyAt":1790295630,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-20-30-01a0d5ef-62bd-7c20-861b-0528ff7d86bd.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":{"sha":"1563a64b41d5e7e2e640b46f52cee724913f8851","branch":"v2/codex-gpt6-luna-rerecord","originUrl":"https://github.com/pingdotgg/t3code.git"},"name":null,"daybreakEnabled":null,"turns":[]},"model":"gpt-6-luna","modelProvider":"openai","serviceTier":null,"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"],"instructionSources":["/home/replay-user/.codex/AGENTS.md","/home/replay-user/t3code/AGENTS.md"],"approvalPolicy":"never","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":{"id":":workspace","extends":null},"reasoningEffort":null,"collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna","reasoning_effort":null,"developer_instructions":null}},"multiAgentMode":"explicitRequestOnly","initialTurnsPage":null,"turnsBackwardsCursor":"{\"requestedThreadId\":\"01a0d5ef-62bd-7c20-861b-0528ff7d86bd\",\"rolloutOrdinal\":1,\"includeAnchor\":true,\"scope\":{\"kind\":\"turns\"}}","itemsBackwardsCursor":"{\"requestedThreadId\":\"01a0d5ef-62bd-7c20-861b-0528ff7d86bd\",\"rolloutOrdinal\":10,\"includeAnchor\":true,\"scope\":{\"kind\":\"itemsByCreatedAtOrdinal\"}}"}}} -{"type":"expect_outbound","label":"config/read","frame":{"id":3,"method":"config/read","params":{"cwd":"","includeLayers":false}}} -{"type":"emit_inbound","label":"config/read","frame":{"id":3,"result":{"config":{},"origins":{}}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":4,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Using the conversation history available in this resumed thread, first repeat the exact final answer you gave in the previous turn. Then on a new line write exactly: provider thread resume fixture second turn complete","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"auto","threadId":"01a0d5ef-62bd-7c20-861b-0528ff7d86bd","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} +{"type":"expect_outbound","label":"thread/name/set","frame":{"id":3,"method":"thread/name/set","params":{"name":"Replay fixture: provider_thread_resume","threadId":"01a0d5ef-62bd-7c20-861b-0528ff7d86bd"}}} +{"type":"emit_inbound","label":"thread/name/set","frame":{"id":3,"result":{}}} +{"type":"emit_inbound","label":"thread/name/updated","frame":{"method":"thread/name/updated","params":{"threadId":"01a0d5ef-62bd-7c20-861b-0528ff7d86bd","threadName":"Replay fixture: provider_thread_resume"}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":4,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":4,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":5,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Using the conversation history available in this resumed thread, first repeat the exact final answer you gave in the previous turn. Then on a new line write exactly: provider thread resume fixture second turn complete","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"auto","threadId":"01a0d5ef-62bd-7c20-861b-0528ff7d86bd","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} {"type":"emit_inbound","label":"thread/tokenUsage/updated","frame":{"method":"thread/tokenUsage/updated","params":{"threadId":"01a0d5ef-62bd-7c20-861b-0528ff7d86bd","turnId":"01a0d5ef-637e-7ba2-bf9a-5534a6f98a83","tokenUsage":{"total":{"totalTokens":21432,"inputTokens":21421,"cachedInputTokens":21248,"cacheWriteInputTokens":0,"outputTokens":11,"reasoningOutputTokens":0},"last":{"totalTokens":21432,"inputTokens":21421,"cachedInputTokens":21248,"cacheWriteInputTokens":0,"outputTokens":11,"reasoningOutputTokens":0},"modelContextWindow":258400}},"emittedAtMs":1790295635930}} {"type":"emit_inbound","label":"thread/goal/cleared","frame":{"method":"thread/goal/cleared","params":{"threadId":"01a0d5ef-62bd-7c20-861b-0528ff7d86bd"},"emittedAtMs":1790295635930}} {"type":"emit_inbound","label":"thread/settings/updated","frame":{"method":"thread/settings/updated","params":{"threadId":"01a0d5ef-62bd-7c20-861b-0528ff7d86bd","threadSettings":{"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","approvalPolicy":"never","approvalsReviewer":"user","sandboxPolicy":{"type":"dangerFullAccess"},"activePermissionProfile":null,"model":"gpt-6-luna","modelProvider":"openai","serviceTier":null,"effort":null,"summary":"detailed","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna","reasoning_effort":null,"developer_instructions":null}},"multiAgentMode":"explicitRequestOnly","personality":null}},"emittedAtMs":1790295635949}} -{"type":"emit_inbound","label":"turn/start","frame":{"id":4,"result":{"turn":{"id":"01a0d5ef-77e2-7e22-a198-4864f687b8b5","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} +{"type":"emit_inbound","label":"turn/start","frame":{"id":5,"result":{"turn":{"id":"01a0d5ef-77e2-7e22-a198-4864f687b8b5","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d5ef-62bd-7c20-861b-0528ff7d86bd","status":{"type":"active","activeFlags":[]}},"emittedAtMs":1790295635967}} {"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"01a0d5ef-62bd-7c20-861b-0528ff7d86bd","turn":{"id":"01a0d5ef-77e2-7e22-a198-4864f687b8b5","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1790295635,"completedAt":null,"durationMs":null}},"emittedAtMs":1790295635967}} {"type":"emit_inbound","label":"account/updated","frame":{"method":"account/updated","params":{"authMode":"chatgpt","planType":"unknown"},"emittedAtMs":1790295636362}} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/queued_turn/codex_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/queued_turn/codex_transcript.ndjson index 3f8dab41f6466..8dc7109ff264c 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/queued_turn/codex_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/queued_turn/codex_transcript.ndjson @@ -6,13 +6,16 @@ {"type":"emit_inbound","label":"configWarning","frame":{"method":"configWarning","params":{"summary":"Codex could not find bubblewrap on PATH. Install bubblewrap with your OS package manager. See the sandbox prerequisites: https://developers.openai.com/codex/concepts/sandboxing#prerequisites. Codex will use the bundled bubblewrap in the meantime.","details":null},"emittedAtMs":1790295489278}} {"type":"emit_inbound","label":"remoteControl/status/changed","frame":{"method":"remoteControl/status/changed","params":{"status":"disabled","serverName":"replay-host","installationId":"00000000-0000-4000-8000-000000000000","environmentId":null},"emittedAtMs":1790295489278}} {"type":"emit_inbound","label":"thread/start","frame":{"id":2,"result":{"thread":{"id":"01a0d5ed-3b1d-7b03-a1a3-075d3fa4bc67","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d5ed-3b1d-7b03-a1a3-075d3fa4bc67","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790295489,"updatedAt":1790295489,"recencyAt":1790295489,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-18-09-01a0d5ed-3b1d-7b03-a1a3-075d3fa4bc67.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]},"model":"gpt-6-luna","modelProvider":"openai","serviceTier":null,"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"],"instructionSources":["/home/replay-user/.codex/AGENTS.md","/home/replay-user/t3code/AGENTS.md"],"approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":{"id":":workspace","extends":null},"reasoningEffort":null,"multiAgentMode":"explicitRequestOnly"}}} -{"type":"expect_outbound","label":"config/read","frame":{"id":3,"method":"config/read","params":{"cwd":"","includeLayers":false}}} -{"type":"emit_inbound","label":"config/read","frame":{"id":3,"result":{"config":{},"origins":{}}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":4,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Respond with exactly: first fixture turn complete","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"auto","threadId":"01a0d5ed-3b1d-7b03-a1a3-075d3fa4bc67","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} +{"type":"expect_outbound","label":"thread/name/set","frame":{"id":3,"method":"thread/name/set","params":{"name":"Replay fixture: queued_turn","threadId":"01a0d5ed-3b1d-7b03-a1a3-075d3fa4bc67"}}} +{"type":"emit_inbound","label":"thread/name/set","frame":{"id":3,"result":{}}} +{"type":"emit_inbound","label":"thread/name/updated","frame":{"method":"thread/name/updated","params":{"threadId":"01a0d5ed-3b1d-7b03-a1a3-075d3fa4bc67","threadName":"Replay fixture: queued_turn"}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":4,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":4,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":5,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Respond with exactly: first fixture turn complete","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"auto","threadId":"01a0d5ed-3b1d-7b03-a1a3-075d3fa4bc67","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} {"type":"emit_inbound","label":"thread/started","frame":{"method":"thread/started","params":{"thread":{"id":"01a0d5ed-3b1d-7b03-a1a3-075d3fa4bc67","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d5ed-3b1d-7b03-a1a3-075d3fa4bc67","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790295489,"updatedAt":1790295489,"recencyAt":1790295489,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-18-09-01a0d5ed-3b1d-7b03-a1a3-075d3fa4bc67.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]}},"emittedAtMs":1790295489585}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0d5ed-3b1d-7b03-a1a3-075d3fa4bc67","name":"codex_apps","status":"starting","error":null,"failureReason":null},"emittedAtMs":1790295489585}} {"type":"emit_inbound","label":"thread/settings/updated","frame":{"method":"thread/settings/updated","params":{"threadId":"01a0d5ed-3b1d-7b03-a1a3-075d3fa4bc67","threadSettings":{"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","approvalPolicy":"never","approvalsReviewer":"user","sandboxPolicy":{"type":"dangerFullAccess"},"activePermissionProfile":null,"model":"gpt-6-luna","modelProvider":"openai","serviceTier":null,"effort":null,"summary":"detailed","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna","reasoning_effort":null,"developer_instructions":null}},"multiAgentMode":"explicitRequestOnly","personality":null}},"emittedAtMs":1790295489600}} -{"type":"emit_inbound","label":"turn/start","frame":{"id":4,"result":{"turn":{"id":"01a0d5ed-3c38-77a3-ab7d-7b1af28c714e","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} +{"type":"emit_inbound","label":"turn/start","frame":{"id":5,"result":{"turn":{"id":"01a0d5ed-3c38-77a3-ab7d-7b1af28c714e","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d5ed-3b1d-7b03-a1a3-075d3fa4bc67","status":{"type":"active","activeFlags":[]}},"emittedAtMs":1790295489653}} {"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"01a0d5ed-3b1d-7b03-a1a3-075d3fa4bc67","turn":{"id":"01a0d5ed-3c38-77a3-ab7d-7b1af28c714e","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1790295489,"completedAt":null,"durationMs":null}},"emittedAtMs":1790295489653}} {"type":"emit_inbound","label":"account/updated","frame":{"method":"account/updated","params":{"authMode":"chatgpt","planType":"unknown"},"emittedAtMs":1790295490048}} @@ -30,10 +33,10 @@ {"type":"emit_inbound","label":"thread/tokenUsage/updated","frame":{"method":"thread/tokenUsage/updated","params":{"threadId":"01a0d5ed-3b1d-7b03-a1a3-075d3fa4bc67","turnId":"01a0d5ed-3c38-77a3-ab7d-7b1af28c714e","tokenUsage":{"total":{"totalTokens":21426,"inputTokens":21418,"cachedInputTokens":11008,"cacheWriteInputTokens":0,"outputTokens":8,"reasoningOutputTokens":0},"last":{"totalTokens":21426,"inputTokens":21418,"cachedInputTokens":11008,"cacheWriteInputTokens":0,"outputTokens":8,"reasoningOutputTokens":0},"modelContextWindow":258400}},"emittedAtMs":1790295494469}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d5ed-3b1d-7b03-a1a3-075d3fa4bc67","status":{"type":"idle"}},"emittedAtMs":1790295494492}} {"type":"emit_inbound","label":"turn/completed","frame":{"method":"turn/completed","params":{"threadId":"01a0d5ed-3b1d-7b03-a1a3-075d3fa4bc67","turn":{"id":"01a0d5ed-3c38-77a3-ab7d-7b1af28c714e","items":[{"type":"agentMessage","id":"msg_0e736caa8e522655016ab5bdc6199487d097782bddce2cbb65","text":"first fixture turn complete","phase":"final_answer","memoryCitation":null,"delivery":null,"questions":null}],"itemsView":"summary","status":"completed","error":null,"startedAt":1790295489,"completedAt":1790295494,"durationMs":4885}},"emittedAtMs":1790295494492}} -{"type":"expect_outbound","label":"config/read","frame":{"id":5,"method":"config/read","params":{"cwd":"","includeLayers":false}}} -{"type":"emit_inbound","label":"config/read","frame":{"id":5,"result":{"config":{},"origins":{}}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":6,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Respond with exactly: second fixture turn complete","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"auto","threadId":"01a0d5ed-3b1d-7b03-a1a3-075d3fa4bc67","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} -{"type":"emit_inbound","label":"turn/start","frame":{"id":6,"result":{"turn":{"id":"01a0d5ed-4f65-7182-8985-cb9fba86acad","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":6,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":6,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":7,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Respond with exactly: second fixture turn complete","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"auto","threadId":"01a0d5ed-3b1d-7b03-a1a3-075d3fa4bc67","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} +{"type":"emit_inbound","label":"turn/start","frame":{"id":7,"result":{"turn":{"id":"01a0d5ed-4f65-7182-8985-cb9fba86acad","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d5ed-3b1d-7b03-a1a3-075d3fa4bc67","status":{"type":"active","activeFlags":[]}},"emittedAtMs":1790295494545}} {"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"01a0d5ed-3b1d-7b03-a1a3-075d3fa4bc67","turn":{"id":"01a0d5ed-4f65-7182-8985-cb9fba86acad","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1790295494,"completedAt":null,"durationMs":null}},"emittedAtMs":1790295494545}} {"type":"emit_inbound","label":"item/started","frame":{"method":"item/started","params":{"item":{"type":"userMessage","id":"01a0d5ed-5011-74c1-aa40-36a1a7a1a79c","clientId":null,"content":[{"type":"text","text":"Respond with exactly: second fixture turn complete","text_elements":[]}]},"threadId":"01a0d5ed-3b1d-7b03-a1a3-075d3fa4bc67","turnId":"01a0d5ed-4f65-7182-8985-cb9fba86acad","startedAtMs":1790295494685},"emittedAtMs":1790295494685}} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/simple/codex_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/simple/codex_transcript.ndjson index 95e194eb1ac60..2663074270d55 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/simple/codex_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/simple/codex_transcript.ndjson @@ -7,14 +7,17 @@ {"type":"emit_inbound","label":"remoteControl/status/changed","frame":{"method":"remoteControl/status/changed","params":{"status":"disabled","serverName":"replay-host","installationId":"00000000-0000-4000-8000-000000000000","environmentId":null},"emittedAtMs":1790295403441}} {"type":"emit_inbound","label":"account/updated","frame":{"method":"account/updated","params":{"authMode":"chatgpt","planType":"unknown"},"emittedAtMs":1790295404347}} {"type":"emit_inbound","label":"thread/start","frame":{"id":2,"result":{"thread":{"id":"01a0d5eb-f0c0-7481-a417-5e8871805cbc","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d5eb-f0c0-7481-a417-5e8871805cbc","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790295404,"updatedAt":1790295404,"recencyAt":1790295404,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-16-44-01a0d5eb-f0c0-7481-a417-5e8871805cbc.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]},"model":"gpt-6-luna","modelProvider":"openai","serviceTier":null,"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"],"instructionSources":["/home/replay-user/.codex/AGENTS.md","/home/replay-user/t3code/AGENTS.md"],"approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":{"id":":workspace","extends":null},"reasoningEffort":null,"multiAgentMode":"explicitRequestOnly"}}} -{"type":"expect_outbound","label":"config/read","frame":{"id":3,"method":"config/read","params":{"cwd":"","includeLayers":false}}} -{"type":"emit_inbound","label":"config/read","frame":{"id":3,"result":{"config":{},"origins":{}}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":4,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Respond with the following text: fixture simple ok","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"auto","threadId":"01a0d5eb-f0c0-7481-a417-5e8871805cbc","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} +{"type":"expect_outbound","label":"thread/name/set","frame":{"id":3,"method":"thread/name/set","params":{"name":"Replay fixture: simple","threadId":"01a0d5eb-f0c0-7481-a417-5e8871805cbc"}}} +{"type":"emit_inbound","label":"thread/name/set","frame":{"id":3,"result":{}}} +{"type":"emit_inbound","label":"thread/name/updated","frame":{"method":"thread/name/updated","params":{"threadId":"01a0d5eb-f0c0-7481-a417-5e8871805cbc","threadName":"Replay fixture: simple"}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":4,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":4,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":5,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Respond with the following text: fixture simple ok","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"auto","threadId":"01a0d5eb-f0c0-7481-a417-5e8871805cbc","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} {"type":"emit_inbound","label":"thread/started","frame":{"method":"thread/started","params":{"thread":{"id":"01a0d5eb-f0c0-7481-a417-5e8871805cbc","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d5eb-f0c0-7481-a417-5e8871805cbc","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790295404,"updatedAt":1790295404,"recencyAt":1790295404,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-16-44-01a0d5eb-f0c0-7481-a417-5e8871805cbc.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]}},"emittedAtMs":1790295404904}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0d5eb-f0c0-7481-a417-5e8871805cbc","name":"xcodebuildmcp","status":"starting","error":null,"failureReason":null},"emittedAtMs":1790295404904}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0d5eb-f0c0-7481-a417-5e8871805cbc","name":"codex_apps","status":"starting","error":null,"failureReason":null},"emittedAtMs":1790295404904}} {"type":"emit_inbound","label":"thread/settings/updated","frame":{"method":"thread/settings/updated","params":{"threadId":"01a0d5eb-f0c0-7481-a417-5e8871805cbc","threadSettings":{"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","approvalPolicy":"never","approvalsReviewer":"user","sandboxPolicy":{"type":"dangerFullAccess"},"activePermissionProfile":null,"model":"gpt-6-luna","modelProvider":"openai","serviceTier":null,"effort":null,"summary":"detailed","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna","reasoning_effort":null,"developer_instructions":null}},"multiAgentMode":"explicitRequestOnly","personality":null}},"emittedAtMs":1790295404923}} -{"type":"emit_inbound","label":"turn/start","frame":{"id":4,"result":{"turn":{"id":"01a0d5eb-f176-71d0-8e1c-a459700443de","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} +{"type":"emit_inbound","label":"turn/start","frame":{"id":5,"result":{"turn":{"id":"01a0d5eb-f176-71d0-8e1c-a459700443de","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d5eb-f0c0-7481-a417-5e8871805cbc","status":{"type":"active","activeFlags":[]}},"emittedAtMs":1790295404965}} {"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"01a0d5eb-f0c0-7481-a417-5e8871805cbc","turn":{"id":"01a0d5eb-f176-71d0-8e1c-a459700443de","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1790295404,"completedAt":null,"durationMs":null}},"emittedAtMs":1790295404965}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0d5eb-f0c0-7481-a417-5e8871805cbc","name":"codex_apps","status":"ready","error":null,"failureReason":null},"emittedAtMs":1790295405685}} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/subagent/codex_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/subagent/codex_transcript.ndjson index 81904eb6928e7..9255c2572ac51 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/subagent/codex_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/subagent/codex_transcript.ndjson @@ -7,13 +7,16 @@ {"type":"emit_inbound","label":"remoteControl/status/changed","frame":{"method":"remoteControl/status/changed","params":{"status":"disabled","serverName":"replay-host","installationId":"00000000-0000-4000-8000-000000000000","environmentId":null},"emittedAtMs":1790298236268}} {"type":"emit_inbound","label":"account/updated","frame":{"method":"account/updated","params":{"authMode":"chatgpt","planType":"unknown"},"emittedAtMs":1790298236941}} {"type":"emit_inbound","label":"thread/start","frame":{"id":2,"result":{"thread":{"id":"01a0d617-2920-75e0-8957-ee5a48afefc4","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d617-2920-75e0-8957-ee5a48afefc4","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-5.6-luna","reasoningEffort":null,"createdAt":1790298237,"updatedAt":1790298237,"recencyAt":1790298237,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T18-03-57-01a0d617-2920-75e0-8957-ee5a48afefc4.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]},"model":"gpt-5.6-luna","modelProvider":"openai","serviceTier":null,"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"],"instructionSources":["/home/replay-user/.codex/AGENTS.md"],"approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":{"id":":workspace","extends":null},"reasoningEffort":null,"multiAgentMode":"explicitRequestOnly"}}} -{"type":"expect_outbound","label":"config/read","frame":{"id":3,"method":"config/read","params":{"cwd":"","includeLayers":false}}} -{"type":"emit_inbound","label":"config/read","frame":{"id":3,"result":{"config":{},"origins":{}}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":4,"method":"turn/start","params":{"approvalPolicy":"on-request","approvalsReviewer":"user","cwd":"","input":[{"text":"Spawn 2 subagents, one to read package.json and one to read tsconfig.json","type":"text"}],"model":"gpt-5.6-luna","sandboxPolicy":{"networkAccess":false,"type":"readOnly"},"summary":"auto","threadId":"01a0d617-2920-75e0-8957-ee5a48afefc4","collaborationMode":{"mode":"default","settings":{"model":"gpt-5.6-luna"}}}}} +{"type":"expect_outbound","label":"thread/name/set","frame":{"id":3,"method":"thread/name/set","params":{"name":"Replay fixture: subagent","threadId":"01a0d617-2920-75e0-8957-ee5a48afefc4"}}} +{"type":"emit_inbound","label":"thread/name/set","frame":{"id":3,"result":{}}} +{"type":"emit_inbound","label":"thread/name/updated","frame":{"method":"thread/name/updated","params":{"threadId":"01a0d617-2920-75e0-8957-ee5a48afefc4","threadName":"Replay fixture: subagent"}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":4,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":4,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":5,"method":"turn/start","params":{"approvalPolicy":"on-request","approvalsReviewer":"user","cwd":"","input":[{"text":"Spawn 2 subagents, one to read package.json and one to read tsconfig.json","type":"text"}],"model":"gpt-5.6-luna","sandboxPolicy":{"networkAccess":false,"type":"readOnly"},"summary":"auto","threadId":"01a0d617-2920-75e0-8957-ee5a48afefc4","collaborationMode":{"mode":"default","settings":{"model":"gpt-5.6-luna"}}}}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0d617-2920-75e0-8957-ee5a48afefc4","name":"codex_apps","status":"starting","error":null,"failureReason":null},"emittedAtMs":1790298237401}} {"type":"emit_inbound","label":"thread/started","frame":{"method":"thread/started","params":{"thread":{"id":"01a0d617-2920-75e0-8957-ee5a48afefc4","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d617-2920-75e0-8957-ee5a48afefc4","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-5.6-luna","reasoningEffort":null,"createdAt":1790298237,"updatedAt":1790298237,"recencyAt":1790298237,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T18-03-57-01a0d617-2920-75e0-8957-ee5a48afefc4.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]}},"emittedAtMs":1790298237402}} {"type":"emit_inbound","label":"thread/settings/updated","frame":{"method":"thread/settings/updated","params":{"threadId":"01a0d617-2920-75e0-8957-ee5a48afefc4","threadSettings":{"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","approvalPolicy":"on-request","approvalsReviewer":"user","sandboxPolicy":{"type":"readOnly","networkAccess":false},"activePermissionProfile":null,"model":"gpt-5.6-luna","modelProvider":"openai","serviceTier":null,"effort":null,"summary":"detailed","collaborationMode":{"mode":"default","settings":{"model":"gpt-5.6-luna","reasoning_effort":null,"developer_instructions":null}},"multiAgentMode":"explicitRequestOnly","personality":null}},"emittedAtMs":1790298237414}} -{"type":"emit_inbound","label":"turn/start","frame":{"id":4,"result":{"turn":{"id":"01a0d617-29e0-73d3-a4fd-856238566501","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} +{"type":"emit_inbound","label":"turn/start","frame":{"id":5,"result":{"turn":{"id":"01a0d617-29e0-73d3-a4fd-856238566501","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d617-2920-75e0-8957-ee5a48afefc4","status":{"type":"active","activeFlags":[]}},"emittedAtMs":1790298237472}} {"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"01a0d617-2920-75e0-8957-ee5a48afefc4","turn":{"id":"01a0d617-29e0-73d3-a4fd-856238566501","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1790298237,"completedAt":null,"durationMs":null}},"emittedAtMs":1790298237472}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0d617-2920-75e0-8957-ee5a48afefc4","name":"xcodebuildmcp","status":"starting","error":null,"failureReason":null},"emittedAtMs":1790298237772}} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/subagent_continue/codex_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/subagent_continue/codex_transcript.ndjson index 6e05d1d8639c2..4deb50c422bd1 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/subagent_continue/codex_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/subagent_continue/codex_transcript.ndjson @@ -6,13 +6,16 @@ {"type":"emit_inbound","label":"configWarning","frame":{"method":"configWarning","params":{"summary":"Codex could not find bubblewrap on PATH. Install bubblewrap with your OS package manager. See the sandbox prerequisites: https://developers.openai.com/codex/concepts/sandboxing#prerequisites. Codex will use the bundled bubblewrap in the meantime.","details":null},"emittedAtMs":1790296707143}} {"type":"emit_inbound","label":"remoteControl/status/changed","frame":{"method":"remoteControl/status/changed","params":{"status":"disabled","serverName":"replay-host","installationId":"00000000-0000-4000-8000-000000000000","environmentId":null},"emittedAtMs":1790296707143}} {"type":"emit_inbound","label":"thread/start","frame":{"id":2,"result":{"thread":{"id":"01a0d5ff-d059-77b3-a2cc-81be5c40d448","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d5ff-d059-77b3-a2cc-81be5c40d448","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-5.6-luna","reasoningEffort":null,"createdAt":1790296707,"updatedAt":1790296707,"recencyAt":1790296707,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-38-27-01a0d5ff-d059-77b3-a2cc-81be5c40d448.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]},"model":"gpt-5.6-luna","modelProvider":"openai","serviceTier":null,"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"],"instructionSources":["/home/replay-user/.codex/AGENTS.md","/home/replay-user/t3code/AGENTS.md"],"approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":{"id":":workspace","extends":null},"reasoningEffort":null,"multiAgentMode":"explicitRequestOnly"}}} -{"type":"expect_outbound","label":"config/read","frame":{"id":3,"method":"config/read","params":{"cwd":"","includeLayers":false}}} -{"type":"emit_inbound","label":"config/read","frame":{"id":3,"result":{"config":{},"origins":{}}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":4,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Spawn one subagent and have it reply exactly: initial subagent response","type":"text"}],"model":"gpt-5.6-luna","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"auto","threadId":"01a0d5ff-d059-77b3-a2cc-81be5c40d448","collaborationMode":{"mode":"default","settings":{"model":"gpt-5.6-luna"}}}}} +{"type":"expect_outbound","label":"thread/name/set","frame":{"id":3,"method":"thread/name/set","params":{"name":"Replay fixture: subagent_continue","threadId":"01a0d5ff-d059-77b3-a2cc-81be5c40d448"}}} +{"type":"emit_inbound","label":"thread/name/set","frame":{"id":3,"result":{}}} +{"type":"emit_inbound","label":"thread/name/updated","frame":{"method":"thread/name/updated","params":{"threadId":"01a0d5ff-d059-77b3-a2cc-81be5c40d448","threadName":"Replay fixture: subagent_continue"}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":4,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":4,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":5,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Spawn one subagent and have it reply exactly: initial subagent response","type":"text"}],"model":"gpt-5.6-luna","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"auto","threadId":"01a0d5ff-d059-77b3-a2cc-81be5c40d448","collaborationMode":{"mode":"default","settings":{"model":"gpt-5.6-luna"}}}}} {"type":"emit_inbound","label":"thread/started","frame":{"method":"thread/started","params":{"thread":{"id":"01a0d5ff-d059-77b3-a2cc-81be5c40d448","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d5ff-d059-77b3-a2cc-81be5c40d448","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-5.6-luna","reasoningEffort":null,"createdAt":1790296707,"updatedAt":1790296707,"recencyAt":1790296707,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-38-27-01a0d5ff-d059-77b3-a2cc-81be5c40d448.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]}},"emittedAtMs":1790296707328}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0d5ff-d059-77b3-a2cc-81be5c40d448","name":"codex_apps","status":"starting","error":null,"failureReason":null},"emittedAtMs":1790296707328}} {"type":"emit_inbound","label":"thread/settings/updated","frame":{"method":"thread/settings/updated","params":{"threadId":"01a0d5ff-d059-77b3-a2cc-81be5c40d448","threadSettings":{"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","approvalPolicy":"never","approvalsReviewer":"user","sandboxPolicy":{"type":"dangerFullAccess"},"activePermissionProfile":null,"model":"gpt-5.6-luna","modelProvider":"openai","serviceTier":null,"effort":null,"summary":"detailed","collaborationMode":{"mode":"default","settings":{"model":"gpt-5.6-luna","reasoning_effort":null,"developer_instructions":null}},"multiAgentMode":"explicitRequestOnly","personality":null}},"emittedAtMs":1790296707337}} -{"type":"emit_inbound","label":"turn/start","frame":{"id":4,"result":{"turn":{"id":"01a0d5ff-d107-72b0-b80e-eee523c86b42","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} +{"type":"emit_inbound","label":"turn/start","frame":{"id":5,"result":{"turn":{"id":"01a0d5ff-d107-72b0-b80e-eee523c86b42","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d5ff-d059-77b3-a2cc-81be5c40d448","status":{"type":"active","activeFlags":[]}},"emittedAtMs":1790296707369}} {"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"01a0d5ff-d059-77b3-a2cc-81be5c40d448","turn":{"id":"01a0d5ff-d107-72b0-b80e-eee523c86b42","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1790296707,"completedAt":null,"durationMs":null}},"emittedAtMs":1790296707369}} {"type":"emit_inbound","label":"account/updated","frame":{"method":"account/updated","params":{"authMode":"chatgpt","planType":"unknown"},"emittedAtMs":1790296707761}} @@ -78,10 +81,10 @@ {"type":"emit_inbound","label":"thread/tokenUsage/updated","frame":{"method":"thread/tokenUsage/updated","params":{"threadId":"01a0d5ff-d059-77b3-a2cc-81be5c40d448","turnId":"01a0d5ff-d107-72b0-b80e-eee523c86b42","tokenUsage":{"total":{"totalTokens":88196,"inputTokens":87953,"cachedInputTokens":61440,"cacheWriteInputTokens":0,"outputTokens":243,"reasoningOutputTokens":74},"last":{"totalTokens":22955,"inputTokens":22918,"cachedInputTokens":22272,"cacheWriteInputTokens":0,"outputTokens":37,"reasoningOutputTokens":27},"modelContextWindow":258400}},"emittedAtMs":1790296721553}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d5ff-d059-77b3-a2cc-81be5c40d448","status":{"type":"idle"}},"emittedAtMs":1790296721558}} {"type":"emit_inbound","label":"turn/completed","frame":{"method":"turn/completed","params":{"threadId":"01a0d5ff-d059-77b3-a2cc-81be5c40d448","turn":{"id":"01a0d5ff-d107-72b0-b80e-eee523c86b42","items":[{"type":"agentMessage","id":"msg_0cd47e60427f33b8016ab5c29140b487d0abe357be8230ade9","text":"initial subagent response","phase":"final_answer","memoryCitation":null,"delivery":null,"questions":null}],"itemsView":"summary","status":"completed","error":null,"startedAt":1790296707,"completedAt":1790296721,"durationMs":14219}},"emittedAtMs":1790296721558}} -{"type":"expect_outbound","label":"config/read","frame":{"id":5,"method":"config/read","params":{"cwd":"","includeLayers":false}}} -{"type":"emit_inbound","label":"config/read","frame":{"id":5,"result":{"config":{},"origins":{}}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":6,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Have the same subagent you spawned earlier reply exactly: continued subagent response","type":"text"}],"model":"gpt-5.6-luna","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"auto","threadId":"01a0d5ff-d059-77b3-a2cc-81be5c40d448","collaborationMode":{"mode":"default","settings":{"model":"gpt-5.6-luna"}}}}} -{"type":"emit_inbound","label":"turn/start","frame":{"id":6,"result":{"turn":{"id":"01a0d600-0899-7c10-9106-0eac1b8d18f9","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":6,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":6,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":7,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Have the same subagent you spawned earlier reply exactly: continued subagent response","type":"text"}],"model":"gpt-5.6-luna","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"auto","threadId":"01a0d5ff-d059-77b3-a2cc-81be5c40d448","collaborationMode":{"mode":"default","settings":{"model":"gpt-5.6-luna"}}}}} +{"type":"emit_inbound","label":"turn/start","frame":{"id":7,"result":{"turn":{"id":"01a0d600-0899-7c10-9106-0eac1b8d18f9","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d5ff-d059-77b3-a2cc-81be5c40d448","status":{"type":"active","activeFlags":[]}},"emittedAtMs":1790296721577}} {"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"01a0d5ff-d059-77b3-a2cc-81be5c40d448","turn":{"id":"01a0d600-0899-7c10-9106-0eac1b8d18f9","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1790296721,"completedAt":null,"durationMs":null}},"emittedAtMs":1790296721577}} {"type":"emit_inbound","label":"item/started","frame":{"method":"item/started","params":{"item":{"type":"userMessage","id":"01a0d600-0931-74b0-9bed-eacf1497bdf5","clientId":null,"content":[{"type":"text","text":"Have the same subagent you spawned earlier reply exactly: continued subagent response","text_elements":[]}]},"threadId":"01a0d5ff-d059-77b3-a2cc-81be5c40d448","turnId":"01a0d600-0899-7c10-9106-0eac1b8d18f9","startedAtMs":1790296721714},"emittedAtMs":1790296721715}} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/subagent_v2/codex_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/subagent_v2/codex_transcript.ndjson index c9e1b84dc34cc..df4278b9e22d7 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/subagent_v2/codex_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/subagent_v2/codex_transcript.ndjson @@ -7,14 +7,17 @@ {"type":"emit_inbound","label":"remoteControl/status/changed","frame":{"method":"remoteControl/status/changed","params":{"status":"disabled","serverName":"replay-host","installationId":"00000000-0000-4000-8000-000000000000","environmentId":null},"emittedAtMs":1790296671810}} {"type":"emit_inbound","label":"account/updated","frame":{"method":"account/updated","params":{"authMode":"chatgpt","planType":"unknown"},"emittedAtMs":1790296672562}} {"type":"emit_inbound","label":"thread/start","frame":{"id":2,"result":{"thread":{"id":"01a0d5ff-49e8-7741-9ca7-b12aa375019a","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d5ff-49e8-7741-9ca7-b12aa375019a","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790296672,"updatedAt":1790296672,"recencyAt":1790296672,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-37-52-01a0d5ff-49e8-7741-9ca7-b12aa375019a.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]},"model":"gpt-6-luna","modelProvider":"openai","serviceTier":null,"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"],"instructionSources":["/home/replay-user/.codex/AGENTS.md","/home/replay-user/t3code/AGENTS.md"],"approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":{"id":":workspace","extends":null},"reasoningEffort":null,"multiAgentMode":"explicitRequestOnly"}}} -{"type":"expect_outbound","label":"config/read","frame":{"id":3,"method":"config/read","params":{"cwd":"","includeLayers":false}}} -{"type":"emit_inbound","label":"config/read","frame":{"id":3,"result":{"config":{},"origins":{}}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":4,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Spawn one subagent whose only task is to reply with exactly: Hello. Wait for it to finish, then reply with exactly what it said.","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"auto","threadId":"01a0d5ff-49e8-7741-9ca7-b12aa375019a","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} +{"type":"expect_outbound","label":"thread/name/set","frame":{"id":3,"method":"thread/name/set","params":{"name":"Replay fixture: subagent_v2","threadId":"01a0d5ff-49e8-7741-9ca7-b12aa375019a"}}} +{"type":"emit_inbound","label":"thread/name/set","frame":{"id":3,"result":{}}} +{"type":"emit_inbound","label":"thread/name/updated","frame":{"method":"thread/name/updated","params":{"threadId":"01a0d5ff-49e8-7741-9ca7-b12aa375019a","threadName":"Replay fixture: subagent_v2"}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":4,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":4,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":5,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Spawn one subagent whose only task is to reply with exactly: Hello. Wait for it to finish, then reply with exactly what it said.","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"auto","threadId":"01a0d5ff-49e8-7741-9ca7-b12aa375019a","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} {"type":"emit_inbound","label":"thread/started","frame":{"method":"thread/started","params":{"thread":{"id":"01a0d5ff-49e8-7741-9ca7-b12aa375019a","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d5ff-49e8-7741-9ca7-b12aa375019a","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790296672,"updatedAt":1790296672,"recencyAt":1790296672,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-37-52-01a0d5ff-49e8-7741-9ca7-b12aa375019a.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]}},"emittedAtMs":1790296673000}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0d5ff-49e8-7741-9ca7-b12aa375019a","name":"codex_apps","status":"starting","error":null,"failureReason":null},"emittedAtMs":1790296673000}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0d5ff-49e8-7741-9ca7-b12aa375019a","name":"xcodebuildmcp","status":"starting","error":null,"failureReason":null},"emittedAtMs":1790296673000}} {"type":"emit_inbound","label":"thread/settings/updated","frame":{"method":"thread/settings/updated","params":{"threadId":"01a0d5ff-49e8-7741-9ca7-b12aa375019a","threadSettings":{"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","approvalPolicy":"never","approvalsReviewer":"user","sandboxPolicy":{"type":"dangerFullAccess"},"activePermissionProfile":null,"model":"gpt-6-luna","modelProvider":"openai","serviceTier":null,"effort":null,"summary":"detailed","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna","reasoning_effort":null,"developer_instructions":null}},"multiAgentMode":"explicitRequestOnly","personality":null}},"emittedAtMs":1790296673032}} -{"type":"emit_inbound","label":"turn/start","frame":{"id":4,"result":{"turn":{"id":"01a0d5ff-4b00-7641-bba1-06faa0ef23f1","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} +{"type":"emit_inbound","label":"turn/start","frame":{"id":5,"result":{"turn":{"id":"01a0d5ff-4b00-7641-bba1-06faa0ef23f1","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d5ff-49e8-7741-9ca7-b12aa375019a","status":{"type":"active","activeFlags":[]}},"emittedAtMs":1790296673081}} {"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"01a0d5ff-49e8-7741-9ca7-b12aa375019a","turn":{"id":"01a0d5ff-4b00-7641-bba1-06faa0ef23f1","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1790296673,"completedAt":null,"durationMs":null}},"emittedAtMs":1790296673081}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0d5ff-49e8-7741-9ca7-b12aa375019a","name":"codex_apps","status":"ready","error":null,"failureReason":null},"emittedAtMs":1790296673765}} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/subagent_v2_approval/codex_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/subagent_v2_approval/codex_transcript.ndjson index bb0e341fed4f0..b7178ee2cd4ce 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/subagent_v2_approval/codex_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/subagent_v2_approval/codex_transcript.ndjson @@ -7,13 +7,16 @@ {"type":"emit_inbound","label":"remoteControl/status/changed","frame":{"method":"remoteControl/status/changed","params":{"status":"disabled","serverName":"replay-host","installationId":"00000000-0000-4000-8000-000000000000","environmentId":null},"emittedAtMs":1790368128814}} {"type":"emit_inbound","label":"account/updated","frame":{"method":"account/updated","params":{"authMode":"chatgpt","planType":"unknown"},"emittedAtMs":1790368129787}} {"type":"emit_inbound","label":"thread/start","frame":{"id":2,"result":{"thread":{"id":"01a0da41-a28d-7271-b6f6-59123b5bb248","environments":[{"environmentId":"local","cwd":"/home/replay-user/tmp/codex-subagent-approval-rec/repo","runtimeWorkspaceRoots":["/home/replay-user/tmp/codex-subagent-approval-rec/repo"]}],"extra":null,"sessionId":"01a0da41-a28d-7271-b6f6-59123b5bb248","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790368129,"updatedAt":1790368129,"recencyAt":1790368129,"status":{"type":"idle"},"path":"/home/replay-user/tmp/codex-subagent-approval-rec/codex-home/sessions/2026/09/25/rollout-2026-09-25T13-28-49-01a0da41-a28d-7271-b6f6-59123b5bb248.jsonl","cwd":"/home/replay-user/tmp/codex-subagent-approval-rec/repo","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]},"model":"gpt-6-luna","modelProvider":"openai","serviceTier":null,"disabledPluginIds":[],"cwd":"/home/replay-user/tmp/codex-subagent-approval-rec/repo","runtimeWorkspaceRoots":["/home/replay-user/tmp/codex-subagent-approval-rec/repo"],"instructionSources":[],"approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":{"id":":workspace","extends":null},"reasoningEffort":null,"multiAgentMode":"explicitRequestOnly"}}} -{"type":"expect_outbound","label":"config/read","frame":{"id":3,"method":"config/read","params":{"cwd":"","includeLayers":false}}} -{"type":"emit_inbound","label":"config/read","frame":{"id":3,"result":{"config":{},"origins":{}}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":4,"method":"turn/start","params":{"approvalPolicy":"untrusted","approvalsReviewer":"user","cwd":"","input":[{"text":"Do not run any commands yourself. Spawn one subagent whose only task is to run this exact shell command: printf 'subagent approval fixture' > subagent-approval.txt and then reply with exactly: Written. Wait for it to finish, then reply with exactly what it said.","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"type":"readOnly"},"summary":"auto","threadId":"01a0da41-a28d-7271-b6f6-59123b5bb248","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} +{"type":"expect_outbound","label":"thread/name/set","frame":{"id":3,"method":"thread/name/set","params":{"name":"Replay fixture: subagent_v2_approval","threadId":"01a0da41-a28d-7271-b6f6-59123b5bb248"}}} +{"type":"emit_inbound","label":"thread/name/set","frame":{"id":3,"result":{}}} +{"type":"emit_inbound","label":"thread/name/updated","frame":{"method":"thread/name/updated","params":{"threadId":"01a0da41-a28d-7271-b6f6-59123b5bb248","threadName":"Replay fixture: subagent_v2_approval"}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":4,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":4,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":5,"method":"turn/start","params":{"approvalPolicy":"untrusted","approvalsReviewer":"user","cwd":"","input":[{"text":"Do not run any commands yourself. Spawn one subagent whose only task is to run this exact shell command: printf 'subagent approval fixture' > subagent-approval.txt and then reply with exactly: Written. Wait for it to finish, then reply with exactly what it said.","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"type":"readOnly"},"summary":"auto","threadId":"01a0da41-a28d-7271-b6f6-59123b5bb248","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} {"type":"emit_inbound","label":"thread/started","frame":{"method":"thread/started","params":{"thread":{"id":"01a0da41-a28d-7271-b6f6-59123b5bb248","environments":[{"environmentId":"local","cwd":"/home/replay-user/tmp/codex-subagent-approval-rec/repo","runtimeWorkspaceRoots":["/home/replay-user/tmp/codex-subagent-approval-rec/repo"]}],"extra":null,"sessionId":"01a0da41-a28d-7271-b6f6-59123b5bb248","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790368129,"updatedAt":1790368129,"recencyAt":1790368129,"status":{"type":"idle"},"path":"/home/replay-user/tmp/codex-subagent-approval-rec/codex-home/sessions/2026/09/25/rollout-2026-09-25T13-28-49-01a0da41-a28d-7271-b6f6-59123b5bb248.jsonl","cwd":"/home/replay-user/tmp/codex-subagent-approval-rec/repo","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]}},"emittedAtMs":1790368129812}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0da41-a28d-7271-b6f6-59123b5bb248","name":"codex_apps","status":"starting","error":null,"failureReason":null},"emittedAtMs":1790368129813}} {"type":"emit_inbound","label":"thread/settings/updated","frame":{"method":"thread/settings/updated","params":{"threadId":"01a0da41-a28d-7271-b6f6-59123b5bb248","threadSettings":{"disabledPluginIds":[],"cwd":"/home/replay-user/tmp/codex-subagent-approval-rec/repo","approvalPolicy":"untrusted","approvalsReviewer":"user","sandboxPolicy":{"type":"readOnly","networkAccess":false},"activePermissionProfile":null,"model":"gpt-6-luna","modelProvider":"openai","serviceTier":null,"effort":null,"summary":"detailed","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna","reasoning_effort":null,"developer_instructions":null}},"multiAgentMode":"explicitRequestOnly","personality":null}},"emittedAtMs":1790368129830}} -{"type":"emit_inbound","label":"turn/start","frame":{"id":4,"result":{"turn":{"id":"01a0da41-a31f-7741-bda3-ebc5ad36c38f","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} +{"type":"emit_inbound","label":"turn/start","frame":{"id":5,"result":{"turn":{"id":"01a0da41-a31f-7741-bda3-ebc5ad36c38f","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0da41-a28d-7271-b6f6-59123b5bb248","status":{"type":"active","activeFlags":[]}},"emittedAtMs":1790368129893}} {"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"01a0da41-a28d-7271-b6f6-59123b5bb248","turn":{"id":"01a0da41-a31f-7741-bda3-ebc5ad36c38f","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1790368129,"completedAt":null,"durationMs":null}},"emittedAtMs":1790368129894}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0da41-a28d-7271-b6f6-59123b5bb248","name":"codex_apps","status":"ready","error":null,"failureReason":null},"emittedAtMs":1790368131004}} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/subagent_v2_nested/codex_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/subagent_v2_nested/codex_transcript.ndjson index badb0b5b0aef8..d895b9ad9849c 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/subagent_v2_nested/codex_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/subagent_v2_nested/codex_transcript.ndjson @@ -6,13 +6,16 @@ {"type":"emit_inbound","label":"configWarning","frame":{"method":"configWarning","params":{"summary":"Codex could not find bubblewrap on PATH. Install bubblewrap with your OS package manager. See the sandbox prerequisites: https://developers.openai.com/codex/concepts/sandboxing#prerequisites. Codex will use the bundled bubblewrap in the meantime.","details":null},"emittedAtMs":1790296685424}} {"type":"emit_inbound","label":"remoteControl/status/changed","frame":{"method":"remoteControl/status/changed","params":{"status":"disabled","serverName":"replay-host","installationId":"00000000-0000-4000-8000-000000000000","environmentId":null},"emittedAtMs":1790296685424}} {"type":"emit_inbound","label":"thread/start","frame":{"id":2,"result":{"thread":{"id":"01a0d5ff-7b98-7e50-a216-1581ca5ebd3a","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d5ff-7b98-7e50-a216-1581ca5ebd3a","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790296685,"updatedAt":1790296685,"recencyAt":1790296685,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-38-05-01a0d5ff-7b98-7e50-a216-1581ca5ebd3a.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]},"model":"gpt-6-luna","modelProvider":"openai","serviceTier":null,"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"],"instructionSources":["/home/replay-user/.codex/AGENTS.md","/home/replay-user/t3code/AGENTS.md"],"approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":{"id":":workspace","extends":null},"reasoningEffort":null,"multiAgentMode":"explicitRequestOnly"}}} -{"type":"expect_outbound","label":"config/read","frame":{"id":3,"method":"config/read","params":{"cwd":"","includeLayers":false}}} -{"type":"emit_inbound","label":"config/read","frame":{"id":3,"result":{"config":{},"origins":{}}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":4,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Spawn one subagent and tell it to spawn its own subagent, which must in turn spawn one more subagent whose only task is to reply with exactly: Hello. Each agent waits for its child and replies with exactly what the child said. Wait for your subagent, then reply with exactly what it said.","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"auto","threadId":"01a0d5ff-7b98-7e50-a216-1581ca5ebd3a","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} +{"type":"expect_outbound","label":"thread/name/set","frame":{"id":3,"method":"thread/name/set","params":{"name":"Replay fixture: subagent_v2_nested","threadId":"01a0d5ff-7b98-7e50-a216-1581ca5ebd3a"}}} +{"type":"emit_inbound","label":"thread/name/set","frame":{"id":3,"result":{}}} +{"type":"emit_inbound","label":"thread/name/updated","frame":{"method":"thread/name/updated","params":{"threadId":"01a0d5ff-7b98-7e50-a216-1581ca5ebd3a","threadName":"Replay fixture: subagent_v2_nested"}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":4,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":4,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":5,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Spawn one subagent and tell it to spawn its own subagent, which must in turn spawn one more subagent whose only task is to reply with exactly: Hello. Each agent waits for its child and replies with exactly what the child said. Wait for your subagent, then reply with exactly what it said.","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"auto","threadId":"01a0d5ff-7b98-7e50-a216-1581ca5ebd3a","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} {"type":"emit_inbound","label":"thread/started","frame":{"method":"thread/started","params":{"thread":{"id":"01a0d5ff-7b98-7e50-a216-1581ca5ebd3a","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d5ff-7b98-7e50-a216-1581ca5ebd3a","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790296685,"updatedAt":1790296685,"recencyAt":1790296685,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-38-05-01a0d5ff-7b98-7e50-a216-1581ca5ebd3a.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]}},"emittedAtMs":1790296685651}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0d5ff-7b98-7e50-a216-1581ca5ebd3a","name":"codex_apps","status":"starting","error":null,"failureReason":null},"emittedAtMs":1790296685651}} {"type":"emit_inbound","label":"thread/settings/updated","frame":{"method":"thread/settings/updated","params":{"threadId":"01a0d5ff-7b98-7e50-a216-1581ca5ebd3a","threadSettings":{"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","approvalPolicy":"never","approvalsReviewer":"user","sandboxPolicy":{"type":"dangerFullAccess"},"activePermissionProfile":null,"model":"gpt-6-luna","modelProvider":"openai","serviceTier":null,"effort":null,"summary":"detailed","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna","reasoning_effort":null,"developer_instructions":null}},"multiAgentMode":"explicitRequestOnly","personality":null}},"emittedAtMs":1790296685666}} -{"type":"emit_inbound","label":"turn/start","frame":{"id":4,"result":{"turn":{"id":"01a0d5ff-7c5b-7bf1-a92a-39f93af77a6c","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} +{"type":"emit_inbound","label":"turn/start","frame":{"id":5,"result":{"turn":{"id":"01a0d5ff-7c5b-7bf1-a92a-39f93af77a6c","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d5ff-7b98-7e50-a216-1581ca5ebd3a","status":{"type":"active","activeFlags":[]}},"emittedAtMs":1790296685723}} {"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"01a0d5ff-7b98-7e50-a216-1581ca5ebd3a","turn":{"id":"01a0d5ff-7c5b-7bf1-a92a-39f93af77a6c","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1790296685,"completedAt":null,"durationMs":null}},"emittedAtMs":1790296685723}} {"type":"emit_inbound","label":"account/updated","frame":{"method":"account/updated","params":{"authMode":"chatgpt","planType":"unknown"},"emittedAtMs":1790296686001}} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/subagent_v2_nested_approval/codex_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/subagent_v2_nested_approval/codex_transcript.ndjson index d4a8488cb6eae..213b6d6d36f6a 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/subagent_v2_nested_approval/codex_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/subagent_v2_nested_approval/codex_transcript.ndjson @@ -6,13 +6,16 @@ {"type":"emit_inbound","label":"configWarning","frame":{"method":"configWarning","params":{"summary":"Codex could not find bubblewrap on PATH. Install bubblewrap with your OS package manager. See the sandbox prerequisites: https://developers.openai.com/codex/concepts/sandboxing#prerequisites. Codex will use the bundled bubblewrap in the meantime.","details":null},"emittedAtMs":1790374254500}} {"type":"emit_inbound","label":"remoteControl/status/changed","frame":{"method":"remoteControl/status/changed","params":{"status":"disabled","serverName":"replay-host","installationId":"00000000-0000-4000-8000-000000000000","environmentId":null},"emittedAtMs":1790374254500}} {"type":"emit_inbound","label":"thread/start","frame":{"id":2,"result":{"thread":{"id":"01a0da9f-1b19-7301-961c-a4f5e1b31832","environments":[{"environmentId":"local","cwd":"/home/replay-user/.cache/codex-nested-approval-rec/repo","runtimeWorkspaceRoots":["/home/replay-user/.cache/codex-nested-approval-rec/repo"]}],"extra":null,"sessionId":"01a0da9f-1b19-7301-961c-a4f5e1b31832","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790374255,"updatedAt":1790374255,"recencyAt":1790374255,"status":{"type":"idle"},"path":"/home/replay-user/.cache/codex-nested-approval-rec/codex-home/sessions/2026/09/25/rollout-2026-09-25T15-10-55-01a0da9f-1b19-7301-961c-a4f5e1b31832.jsonl","cwd":"/home/replay-user/.cache/codex-nested-approval-rec/repo","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]},"model":"gpt-6-luna","modelProvider":"openai","serviceTier":null,"disabledPluginIds":[],"cwd":"/home/replay-user/.cache/codex-nested-approval-rec/repo","runtimeWorkspaceRoots":["/home/replay-user/.cache/codex-nested-approval-rec/repo"],"instructionSources":[],"approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":{"id":":workspace","extends":null},"reasoningEffort":null,"multiAgentMode":"explicitRequestOnly"}}} -{"type":"expect_outbound","label":"config/read","frame":{"id":3,"method":"config/read","params":{"cwd":"","includeLayers":false}}} -{"type":"emit_inbound","label":"config/read","frame":{"id":3,"result":{"config":{},"origins":{}}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":4,"method":"turn/start","params":{"approvalPolicy":"untrusted","approvalsReviewer":"user","cwd":"","input":[{"text":"Do not run any commands yourself. Spawn one subagent and tell it not to run any commands itself but to spawn its own subagent, whose only task is to run this exact shell command: printf 'nested approval fixture' > nested-approval.txt and then reply with exactly: Written. Each agent waits for its child and replies with exactly what the child said. Wait for your subagent, then reply with exactly what it said.","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"type":"readOnly"},"summary":"auto","threadId":"01a0da9f-1b19-7301-961c-a4f5e1b31832","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} +{"type":"expect_outbound","label":"thread/name/set","frame":{"id":3,"method":"thread/name/set","params":{"name":"Replay fixture: subagent_v2_nested_approval","threadId":"01a0da9f-1b19-7301-961c-a4f5e1b31832"}}} +{"type":"emit_inbound","label":"thread/name/set","frame":{"id":3,"result":{}}} +{"type":"emit_inbound","label":"thread/name/updated","frame":{"method":"thread/name/updated","params":{"threadId":"01a0da9f-1b19-7301-961c-a4f5e1b31832","threadName":"Replay fixture: subagent_v2_nested_approval"}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":4,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":4,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":5,"method":"turn/start","params":{"approvalPolicy":"untrusted","approvalsReviewer":"user","cwd":"","input":[{"text":"Do not run any commands yourself. Spawn one subagent and tell it not to run any commands itself but to spawn its own subagent, whose only task is to run this exact shell command: printf 'nested approval fixture' > nested-approval.txt and then reply with exactly: Written. Each agent waits for its child and replies with exactly what the child said. Wait for your subagent, then reply with exactly what it said.","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"type":"readOnly"},"summary":"auto","threadId":"01a0da9f-1b19-7301-961c-a4f5e1b31832","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} {"type":"emit_inbound","label":"thread/started","frame":{"method":"thread/started","params":{"thread":{"id":"01a0da9f-1b19-7301-961c-a4f5e1b31832","environments":[{"environmentId":"local","cwd":"/home/replay-user/.cache/codex-nested-approval-rec/repo","runtimeWorkspaceRoots":["/home/replay-user/.cache/codex-nested-approval-rec/repo"]}],"extra":null,"sessionId":"01a0da9f-1b19-7301-961c-a4f5e1b31832","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790374255,"updatedAt":1790374255,"recencyAt":1790374255,"status":{"type":"idle"},"path":"/home/replay-user/.cache/codex-nested-approval-rec/codex-home/sessions/2026/09/25/rollout-2026-09-25T15-10-55-01a0da9f-1b19-7301-961c-a4f5e1b31832.jsonl","cwd":"/home/replay-user/.cache/codex-nested-approval-rec/repo","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]}},"emittedAtMs":1790374255463}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0da9f-1b19-7301-961c-a4f5e1b31832","name":"codex_apps","status":"starting","error":null,"failureReason":null},"emittedAtMs":1790374255463}} {"type":"emit_inbound","label":"thread/settings/updated","frame":{"method":"thread/settings/updated","params":{"threadId":"01a0da9f-1b19-7301-961c-a4f5e1b31832","threadSettings":{"disabledPluginIds":[],"cwd":"/home/replay-user/.cache/codex-nested-approval-rec/repo","approvalPolicy":"untrusted","approvalsReviewer":"user","sandboxPolicy":{"type":"readOnly","networkAccess":false},"activePermissionProfile":null,"model":"gpt-6-luna","modelProvider":"openai","serviceTier":null,"effort":null,"summary":"detailed","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna","reasoning_effort":null,"developer_instructions":null}},"multiAgentMode":"explicitRequestOnly","personality":null}},"emittedAtMs":1790374255475}} -{"type":"emit_inbound","label":"turn/start","frame":{"id":4,"result":{"turn":{"id":"01a0da9f-1b6f-7dd3-90da-e6c8797c1da6","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} +{"type":"emit_inbound","label":"turn/start","frame":{"id":5,"result":{"turn":{"id":"01a0da9f-1b6f-7dd3-90da-e6c8797c1da6","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0da9f-1b19-7301-961c-a4f5e1b31832","status":{"type":"active","activeFlags":[]}},"emittedAtMs":1790374255518}} {"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"01a0da9f-1b19-7301-961c-a4f5e1b31832","turn":{"id":"01a0da9f-1b6f-7dd3-90da-e6c8797c1da6","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1790374255,"completedAt":null,"durationMs":null}},"emittedAtMs":1790374255518}} {"type":"emit_inbound","label":"account/updated","frame":{"method":"account/updated","params":{"authMode":"chatgpt","planType":"unknown"},"emittedAtMs":1790374255710}} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/thread_fork_native_prior_turn/codex_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/thread_fork_native_prior_turn/codex_transcript.ndjson index 3dd01acb73f7e..8d84a2031d661 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/thread_fork_native_prior_turn/codex_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/thread_fork_native_prior_turn/codex_transcript.ndjson @@ -5,15 +5,18 @@ {"type":"expect_outbound","label":"thread/start","frame":{"id":2,"method":"thread/start","params":{"config":{"tools.update_plan.enabled":true,"mcp_optional_startup_grace_ms":10000,"features.concurrent_reasoning_summaries":true}}}} {"type":"emit_inbound","label":"thread/start","frame":{"id":2,"result":{"thread":{"id":"019dd6ba-2681-7bf0-b051-141b0cbcbb27","forkedFromId":null,"preview":"","ephemeral":false,"modelProvider":"openai","createdAt":1777424017,"updatedAt":1777424017,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/04/28/rollout-2026-04-28T17-53-37-019dd6ba-2681-7bf0-b051-141b0cbcbb27.jsonl","cwd":"/home/replay-user/t3code","cliVersion":"0.124.0-alpha.3","source":"vscode","agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"turns":[]},"model":"gpt-5.5","modelProvider":"openai","serviceTier":"fast","cwd":"/home/replay-user/t3code","instructionSources":["/home/replay-user/.codex/AGENTS.md","/home/replay-user/t3code/AGENTS.md"],"approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":["/home/replay-user/.codex/memories"],"readOnlyAccess":{"type":"fullAccess"},"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"permissionProfile":{"network":{"enabled":false},"fileSystem":{"entries":[{"path":{"type":"special","value":{"kind":"root"}},"access":"read"},{"path":{"type":"special","value":{"kind":"current_working_directory"}},"access":"write"},{"path":{"type":"special","value":{"kind":"slash_tmp"}},"access":"write"},{"path":{"type":"special","value":{"kind":"tmpdir"}},"access":"write"},{"path":{"type":"path","path":"/home/replay-user/.codex/memories"},"access":"write"},{"path":{"type":"path","path":"/home/replay-user/Development/Work/codething-mvp/.git/worktrees/t3code-c1e5e1d1"},"access":"read"},{"path":{"type":"path","path":"/home/replay-user/t3code/.git"},"access":"read"},{"path":{"type":"path","path":"/home/replay-user/t3code/.codex"},"access":"read"}]}},"reasoningEffort":"medium"}}} {"type":"emit_inbound","label":"thread/started","frame":{"method":"thread/started","params":{"thread":{"id":"019dd6ba-2681-7bf0-b051-141b0cbcbb27","forkedFromId":null,"preview":"","ephemeral":false,"modelProvider":"openai","createdAt":1777424017,"updatedAt":1777424017,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/04/28/rollout-2026-04-28T17-53-37-019dd6ba-2681-7bf0-b051-141b0cbcbb27.jsonl","cwd":"/home/replay-user/t3code","cliVersion":"0.124.0-alpha.3","source":"vscode","agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"turns":[]}}}} -{"type":"expect_outbound","label":"config/read","frame":{"id":3,"method":"config/read","params":{"cwd":"","includeLayers":false}}} -{"type":"emit_inbound","label":"config/read","frame":{"id":3,"result":{"config":{},"origins":{}}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":4,"method":"turn/start","params":{"approvalPolicy":"never","cwd":"","input":[{"type":"text","text":"For this fork-boundary fixture, respond with exactly: fork boundary alpha"}],"model":"gpt-5.4","sandboxPolicy":{"type":"readOnly","networkAccess":false},"threadId":"019dd6ba-2681-7bf0-b051-141b0cbcbb27","approvalsReviewer":"user","summary":"auto","collaborationMode":{"mode":"default","settings":{"model":"gpt-5.4"}}}}} +{"type":"expect_outbound","label":"thread/name/set","frame":{"id":3,"method":"thread/name/set","params":{"name":"Source thread","threadId":"019dd6ba-2681-7bf0-b051-141b0cbcbb27"}}} +{"type":"emit_inbound","label":"thread/name/set","frame":{"id":3,"result":{}}} +{"type":"emit_inbound","label":"thread/name/updated","frame":{"method":"thread/name/updated","params":{"threadId":"019dd6ba-2681-7bf0-b051-141b0cbcbb27","threadName":"Source thread"}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":4,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":4,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":5,"method":"turn/start","params":{"approvalPolicy":"never","cwd":"","input":[{"type":"text","text":"For this fork-boundary fixture, respond with exactly: fork boundary alpha"}],"model":"gpt-5.4","sandboxPolicy":{"type":"readOnly","networkAccess":false},"threadId":"019dd6ba-2681-7bf0-b051-141b0cbcbb27","approvalsReviewer":"user","summary":"auto","collaborationMode":{"mode":"default","settings":{"model":"gpt-5.4"}}}}} {"type":"emit_inbound","label":"deprecationNotice","frame":{"method":"deprecationNotice","params":{"summary":"`[features].collab` is deprecated. Use `[features].multi_agent` instead.","details":"Enable it with `--enable multi_agent` or `[features].multi_agent` in config.toml. See https://developers.openai.com/codex/config-basic#feature-flags for details."}}} {"type":"emit_inbound","label":"warning","frame":{"method":"warning","params":{"threadId":"019dd6ba-2681-7bf0-b051-141b0cbcbb27","message":"Under-development features enabled: apply_patch_freeform. Under-development features are incomplete and may behave unpredictably. To suppress this warning, set `suppress_unstable_features_warning = true` in /home/replay-user/.codex/config.toml."}}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"name":"codex_apps","status":"starting","error":null}}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"name":"computer-use","status":"starting","error":null}}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"name":"uidotsh","status":"starting","error":null}}} -{"type":"emit_inbound","label":"turn/start","frame":{"id":4,"result":{"turn":{"id":"019dd6ba-268b-7f82-8f4c-9fde0edcfd55","items":[],"status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} +{"type":"emit_inbound","label":"turn/start","frame":{"id":5,"result":{"turn":{"id":"019dd6ba-268b-7f82-8f4c-9fde0edcfd55","items":[],"status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"019dd6ba-2681-7bf0-b051-141b0cbcbb27","status":{"type":"active","activeFlags":[]}}}} {"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"019dd6ba-2681-7bf0-b051-141b0cbcbb27","turn":{"id":"019dd6ba-268b-7f82-8f4c-9fde0edcfd55","items":[],"status":"inProgress","error":null,"startedAt":1777424017,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"name":"computer-use","status":"ready","error":null}}} @@ -33,10 +36,10 @@ {"type":"emit_inbound","label":"account/rateLimits/updated","frame":{"method":"account/rateLimits/updated","params":{"rateLimits":{"limitId":"codex","limitName":null,"primary":{"usedPercent":61,"windowDurationMins":300,"resetsAt":1777429830},"secondary":{"usedPercent":23,"windowDurationMins":10080,"resetsAt":1777959590},"credits":null,"planType":"unknown","rateLimitReachedType":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"019dd6ba-2681-7bf0-b051-141b0cbcbb27","status":{"type":"idle"}}}} {"type":"emit_inbound","label":"turn/completed","frame":{"method":"turn/completed","params":{"threadId":"019dd6ba-2681-7bf0-b051-141b0cbcbb27","turn":{"id":"019dd6ba-268b-7f82-8f4c-9fde0edcfd55","items":[],"status":"completed","error":null,"startedAt":1777424017,"completedAt":1777424023,"durationMs":6880}}}} -{"type":"expect_outbound","label":"config/read","frame":{"id":5,"method":"config/read","params":{"cwd":"","includeLayers":false}}} -{"type":"emit_inbound","label":"config/read","frame":{"id":5,"result":{"config":{},"origins":{}}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":6,"method":"turn/start","params":{"approvalPolicy":"never","cwd":"","input":[{"type":"text","text":"For this fork-boundary fixture, respond with exactly: fork boundary beta"}],"model":"gpt-5.4","sandboxPolicy":{"type":"readOnly","networkAccess":false},"threadId":"019dd6ba-2681-7bf0-b051-141b0cbcbb27","approvalsReviewer":"user","summary":"auto","collaborationMode":{"mode":"default","settings":{"model":"gpt-5.4"}}}}} -{"type":"emit_inbound","label":"turn/start","frame":{"id":6,"result":{"turn":{"id":"019dd6ba-416d-7902-95cf-d4179c3f4738","items":[],"status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":6,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":6,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":7,"method":"turn/start","params":{"approvalPolicy":"never","cwd":"","input":[{"type":"text","text":"For this fork-boundary fixture, respond with exactly: fork boundary beta"}],"model":"gpt-5.4","sandboxPolicy":{"type":"readOnly","networkAccess":false},"threadId":"019dd6ba-2681-7bf0-b051-141b0cbcbb27","approvalsReviewer":"user","summary":"auto","collaborationMode":{"mode":"default","settings":{"model":"gpt-5.4"}}}}} +{"type":"emit_inbound","label":"turn/start","frame":{"id":7,"result":{"turn":{"id":"019dd6ba-416d-7902-95cf-d4179c3f4738","items":[],"status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"019dd6ba-2681-7bf0-b051-141b0cbcbb27","status":{"type":"active","activeFlags":[]}}}} {"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"019dd6ba-2681-7bf0-b051-141b0cbcbb27","turn":{"id":"019dd6ba-416d-7902-95cf-d4179c3f4738","items":[],"status":"inProgress","error":null,"startedAt":1777424023,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"item/started","frame":{"method":"item/started","params":{"item":{"type":"userMessage","id":"e8550ffa-7e59-48b3-8fd2-7bbca932ab95","content":[{"type":"text","text":"For this fork-boundary fixture, respond with exactly: fork boundary beta","text_elements":[]}]},"threadId":"019dd6ba-2681-7bf0-b051-141b0cbcbb27","turnId":"019dd6ba-416d-7902-95cf-d4179c3f4738"}}} @@ -52,18 +55,21 @@ {"type":"emit_inbound","label":"account/rateLimits/updated","frame":{"method":"account/rateLimits/updated","params":{"rateLimits":{"limitId":"codex","limitName":null,"primary":{"usedPercent":61,"windowDurationMins":300,"resetsAt":1777429830},"secondary":{"usedPercent":23,"windowDurationMins":10080,"resetsAt":1777959590},"credits":null,"planType":"unknown","rateLimitReachedType":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"019dd6ba-2681-7bf0-b051-141b0cbcbb27","status":{"type":"idle"}}}} {"type":"emit_inbound","label":"turn/completed","frame":{"method":"turn/completed","params":{"threadId":"019dd6ba-2681-7bf0-b051-141b0cbcbb27","turn":{"id":"019dd6ba-416d-7902-95cf-d4179c3f4738","items":[],"status":"completed","error":null,"startedAt":1777424023,"completedAt":1777424025,"durationMs":1596}}}} -{"type":"expect_outbound","label":"thread/fork","frame":{"id":7,"method":"thread/fork","params":{"threadId":"019dd6ba-2681-7bf0-b051-141b0cbcbb27","excludeTurns":true,"lastTurnId":"019dd6ba-268b-7f82-8f4c-9fde0edcfd55","config":{"tools.update_plan.enabled":true,"mcp_optional_startup_grace_ms":10000,"features.concurrent_reasoning_summaries":true}}}} +{"type":"expect_outbound","label":"thread/fork","frame":{"id":8,"method":"thread/fork","params":{"threadId":"019dd6ba-2681-7bf0-b051-141b0cbcbb27","excludeTurns":true,"lastTurnId":"019dd6ba-268b-7f82-8f4c-9fde0edcfd55","config":{"tools.update_plan.enabled":true,"mcp_optional_startup_grace_ms":10000,"features.concurrent_reasoning_summaries":true}}}} {"type":"emit_inbound","label":"deprecationNotice","frame":{"method":"deprecationNotice","params":{"summary":"`[features].collab` is deprecated. Use `[features].multi_agent` instead.","details":"Enable it with `--enable multi_agent` or `[features].multi_agent` in config.toml. See https://developers.openai.com/codex/config-basic#feature-flags for details."}}} {"type":"emit_inbound","label":"warning","frame":{"method":"warning","params":{"threadId":"019dd6ba-47b7-7092-8688-9cf7fe5f6498","message":"Under-development features enabled: apply_patch_freeform. Under-development features are incomplete and may behave unpredictably. To suppress this warning, set `suppress_unstable_features_warning = true` in /home/replay-user/.codex/config.toml."}}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"name":"uidotsh","status":"starting","error":null}}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"name":"computer-use","status":"starting","error":null}}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"name":"codex_apps","status":"starting","error":null}}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"name":"computer-use","status":"ready","error":null}}} -{"type":"emit_inbound","label":"thread/fork","frame":{"id":7,"result":{"thread":{"id":"019dd6ba-47b7-7092-8688-9cf7fe5f6498","forkedFromId":"019dd6ba-2681-7bf0-b051-141b0cbcbb27","preview":"For this fork-boundary fixture, respond with exactly: fork boundary alpha","ephemeral":false,"modelProvider":"openai","createdAt":1777424025,"updatedAt":1777424025,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/04/28/rollout-2026-04-28T17-53-45-019dd6ba-47b7-7092-8688-9cf7fe5f6498.jsonl","cwd":"/home/replay-user/t3code","cliVersion":"0.124.0-alpha.3","source":"vscode","agentNickname":null,"agentRole":null,"gitInfo":{"sha":"969e8ea4fac1f2066ed50dd4f82b5fd0014d8a4d","branch":"t3code/codex-turn-mapping","originUrl":"git@github.com:pingdotgg/t3code.git"},"name":null,"turns":[{"id":"019dd6ba-268b-7f82-8f4c-9fde0edcfd55","items":[{"type":"userMessage","id":"item-1","content":[{"type":"text","text":"For this fork-boundary fixture, respond with exactly: fork boundary alpha","text_elements":[]}]},{"type":"agentMessage","id":"item-2","text":"fork boundary alpha","phase":"final_answer","memoryCitation":null}],"status":"completed","error":null,"startedAt":1777424017,"completedAt":1777424023,"durationMs":6880}]},"model":"gpt-5.5","modelProvider":"openai","serviceTier":"fast","cwd":"/home/replay-user/t3code","instructionSources":["/home/replay-user/.codex/AGENTS.md","/home/replay-user/t3code/AGENTS.md"],"approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":["/home/replay-user/.codex/memories"],"readOnlyAccess":{"type":"fullAccess"},"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"permissionProfile":{"network":{"enabled":false},"fileSystem":{"entries":[{"path":{"type":"special","value":{"kind":"root"}},"access":"read"},{"path":{"type":"special","value":{"kind":"current_working_directory"}},"access":"write"},{"path":{"type":"special","value":{"kind":"slash_tmp"}},"access":"write"},{"path":{"type":"special","value":{"kind":"tmpdir"}},"access":"write"},{"path":{"type":"path","path":"/home/replay-user/.codex/memories"},"access":"write"},{"path":{"type":"path","path":"/home/replay-user/Development/Work/codething-mvp/.git/worktrees/t3code-c1e5e1d1"},"access":"read"},{"path":{"type":"path","path":"/home/replay-user/t3code/.git"},"access":"read"},{"path":{"type":"path","path":"/home/replay-user/t3code/.codex"},"access":"read"}]}},"reasoningEffort":"medium"}}} -{"type":"expect_outbound","label":"config/read","frame":{"id":8,"method":"config/read","params":{"cwd":"","includeLayers":false}}} -{"type":"emit_inbound","label":"config/read","frame":{"id":8,"result":{"config":{},"origins":{}}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":9,"method":"turn/start","params":{"approvalPolicy":"never","cwd":"","input":[{"type":"text","text":"Repeat the user-visible conversation so far verbatim. Include only user and assistant messages. Do not include hidden system/developer content."}],"model":"gpt-5.4","sandboxPolicy":{"type":"readOnly","networkAccess":false},"threadId":"019dd6ba-47b7-7092-8688-9cf7fe5f6498","approvalsReviewer":"user","summary":"auto","collaborationMode":{"mode":"default","settings":{"model":"gpt-5.4"}}}}} -{"type":"emit_inbound","label":"turn/start","frame":{"id":9,"result":{"turn":{"id":"019dd6ba-47eb-7041-ad45-5abe752c28c9","items":[],"status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} +{"type":"emit_inbound","label":"thread/fork","frame":{"id":8,"result":{"thread":{"id":"019dd6ba-47b7-7092-8688-9cf7fe5f6498","forkedFromId":"019dd6ba-2681-7bf0-b051-141b0cbcbb27","preview":"For this fork-boundary fixture, respond with exactly: fork boundary alpha","ephemeral":false,"modelProvider":"openai","createdAt":1777424025,"updatedAt":1777424025,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/04/28/rollout-2026-04-28T17-53-45-019dd6ba-47b7-7092-8688-9cf7fe5f6498.jsonl","cwd":"/home/replay-user/t3code","cliVersion":"0.124.0-alpha.3","source":"vscode","agentNickname":null,"agentRole":null,"gitInfo":{"sha":"969e8ea4fac1f2066ed50dd4f82b5fd0014d8a4d","branch":"t3code/codex-turn-mapping","originUrl":"git@github.com:pingdotgg/t3code.git"},"name":null,"turns":[{"id":"019dd6ba-268b-7f82-8f4c-9fde0edcfd55","items":[{"type":"userMessage","id":"item-1","content":[{"type":"text","text":"For this fork-boundary fixture, respond with exactly: fork boundary alpha","text_elements":[]}]},{"type":"agentMessage","id":"item-2","text":"fork boundary alpha","phase":"final_answer","memoryCitation":null}],"status":"completed","error":null,"startedAt":1777424017,"completedAt":1777424023,"durationMs":6880}]},"model":"gpt-5.5","modelProvider":"openai","serviceTier":"fast","cwd":"/home/replay-user/t3code","instructionSources":["/home/replay-user/.codex/AGENTS.md","/home/replay-user/t3code/AGENTS.md"],"approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":["/home/replay-user/.codex/memories"],"readOnlyAccess":{"type":"fullAccess"},"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"permissionProfile":{"network":{"enabled":false},"fileSystem":{"entries":[{"path":{"type":"special","value":{"kind":"root"}},"access":"read"},{"path":{"type":"special","value":{"kind":"current_working_directory"}},"access":"write"},{"path":{"type":"special","value":{"kind":"slash_tmp"}},"access":"write"},{"path":{"type":"special","value":{"kind":"tmpdir"}},"access":"write"},{"path":{"type":"path","path":"/home/replay-user/.codex/memories"},"access":"write"},{"path":{"type":"path","path":"/home/replay-user/Development/Work/codething-mvp/.git/worktrees/t3code-c1e5e1d1"},"access":"read"},{"path":{"type":"path","path":"/home/replay-user/t3code/.git"},"access":"read"},{"path":{"type":"path","path":"/home/replay-user/t3code/.codex"},"access":"read"}]}},"reasoningEffort":"medium"}}} +{"type":"expect_outbound","label":"thread/name/set","frame":{"id":9,"method":"thread/name/set","params":{"name":"Forked from first response","threadId":"019dd6ba-47b7-7092-8688-9cf7fe5f6498"}}} +{"type":"emit_inbound","label":"thread/name/set","frame":{"id":9,"result":{}}} +{"type":"emit_inbound","label":"thread/name/updated","frame":{"method":"thread/name/updated","params":{"threadId":"019dd6ba-47b7-7092-8688-9cf7fe5f6498","threadName":"Forked from first response"}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":10,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":10,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":11,"method":"turn/start","params":{"approvalPolicy":"never","cwd":"","input":[{"type":"text","text":"Repeat the user-visible conversation so far verbatim. Include only user and assistant messages. Do not include hidden system/developer content."}],"model":"gpt-5.4","sandboxPolicy":{"type":"readOnly","networkAccess":false},"threadId":"019dd6ba-47b7-7092-8688-9cf7fe5f6498","approvalsReviewer":"user","summary":"auto","collaborationMode":{"mode":"default","settings":{"model":"gpt-5.4"}}}}} +{"type":"emit_inbound","label":"turn/start","frame":{"id":11,"result":{"turn":{"id":"019dd6ba-47eb-7041-ad45-5abe752c28c9","items":[],"status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"019dd6ba-47b7-7092-8688-9cf7fe5f6498","status":{"type":"active","activeFlags":[]}}}} {"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"019dd6ba-47b7-7092-8688-9cf7fe5f6498","turn":{"id":"019dd6ba-47eb-7041-ad45-5abe752c28c9","items":[],"status":"inProgress","error":null,"startedAt":1777424025,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"name":"uidotsh","status":"ready","error":null}}} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/thread_merge_back_siblings/codex_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/thread_merge_back_siblings/codex_transcript.ndjson index 44ffac5c8c54e..4a9de158436dd 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/thread_merge_back_siblings/codex_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/thread_merge_back_siblings/codex_transcript.ndjson @@ -6,13 +6,16 @@ {"type":"emit_inbound","label":"configWarning","frame":{"method":"configWarning","params":{"summary":"Codex could not find bubblewrap on PATH. Install bubblewrap with your OS package manager. See the sandbox prerequisites: https://developers.openai.com/codex/concepts/sandboxing#prerequisites. Codex will use the bundled bubblewrap in the meantime.","details":null},"emittedAtMs":1790297773374}} {"type":"emit_inbound","label":"remoteControl/status/changed","frame":{"method":"remoteControl/status/changed","params":{"status":"disabled","serverName":"replay-host","installationId":"00000000-0000-4000-8000-000000000000","environmentId":null},"emittedAtMs":1790297773374}} {"type":"emit_inbound","label":"thread/start","frame":{"id":2,"result":{"thread":{"id":"01a0d610-155f-7391-843e-120bf1475357","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d610-155f-7391-843e-120bf1475357","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-sol","reasoningEffort":null,"createdAt":1790297773,"updatedAt":1790297773,"recencyAt":1790297773,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-56-13-01a0d610-155f-7391-843e-120bf1475357.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]},"model":"gpt-6-sol","modelProvider":"openai","serviceTier":null,"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"],"instructionSources":["/home/replay-user/.codex/AGENTS.md"],"approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":{"id":":workspace","extends":null},"reasoningEffort":null,"multiAgentMode":"explicitRequestOnly"}}} -{"type":"expect_outbound","label":"config/read","frame":{"id":3,"method":"config/read","params":{"cwd":"","includeLayers":false}}} -{"type":"emit_inbound","label":"config/read","frame":{"id":3,"result":{"config":{},"origins":{}}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":4,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Remember the opaque marker merge-sibling-source-3C7K for later in this conversation. Respond with exactly: merge sibling source stored","type":"text"}],"model":"gpt-6-sol","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"auto","threadId":"01a0d610-155f-7391-843e-120bf1475357","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-sol"}}}}} +{"type":"expect_outbound","label":"thread/name/set","frame":{"id":3,"method":"thread/name/set","params":{"name":"Merge-back source","threadId":"01a0d610-155f-7391-843e-120bf1475357"}}} +{"type":"emit_inbound","label":"thread/name/set","frame":{"id":3,"result":{}}} +{"type":"emit_inbound","label":"thread/name/updated","frame":{"method":"thread/name/updated","params":{"threadId":"01a0d610-155f-7391-843e-120bf1475357","threadName":"Merge-back source"}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":4,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":4,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":5,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Remember the opaque marker merge-sibling-source-3C7K for later in this conversation. Respond with exactly: merge sibling source stored","type":"text"}],"model":"gpt-6-sol","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"auto","threadId":"01a0d610-155f-7391-843e-120bf1475357","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-sol"}}}}} {"type":"emit_inbound","label":"thread/started","frame":{"method":"thread/started","params":{"thread":{"id":"01a0d610-155f-7391-843e-120bf1475357","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d610-155f-7391-843e-120bf1475357","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-sol","reasoningEffort":null,"createdAt":1790297773,"updatedAt":1790297773,"recencyAt":1790297773,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-56-13-01a0d610-155f-7391-843e-120bf1475357.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]}},"emittedAtMs":1790297773588}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0d610-155f-7391-843e-120bf1475357","name":"codex_apps","status":"starting","error":null,"failureReason":null},"emittedAtMs":1790297773588}} {"type":"emit_inbound","label":"thread/settings/updated","frame":{"method":"thread/settings/updated","params":{"threadId":"01a0d610-155f-7391-843e-120bf1475357","threadSettings":{"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","approvalPolicy":"never","approvalsReviewer":"user","sandboxPolicy":{"type":"dangerFullAccess"},"activePermissionProfile":null,"model":"gpt-6-sol","modelProvider":"openai","serviceTier":null,"effort":null,"summary":"detailed","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-sol","reasoning_effort":null,"developer_instructions":null}},"multiAgentMode":"explicitRequestOnly","personality":null}},"emittedAtMs":1790297773608}} -{"type":"emit_inbound","label":"turn/start","frame":{"id":4,"result":{"turn":{"id":"01a0d610-1619-7d91-bae2-ec4a7b899193","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} +{"type":"emit_inbound","label":"turn/start","frame":{"id":5,"result":{"turn":{"id":"01a0d610-1619-7d91-bae2-ec4a7b899193","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d610-155f-7391-843e-120bf1475357","status":{"type":"active","activeFlags":[]}},"emittedAtMs":1790297773650}} {"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"01a0d610-155f-7391-843e-120bf1475357","turn":{"id":"01a0d610-1619-7d91-bae2-ec4a7b899193","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1790297773,"completedAt":null,"durationMs":null}},"emittedAtMs":1790297773650}} {"type":"emit_inbound","label":"account/updated","frame":{"method":"account/updated","params":{"authMode":"chatgpt","planType":"unknown"},"emittedAtMs":1790297773993}} @@ -29,19 +32,22 @@ {"type":"emit_inbound","label":"thread/tokenUsage/updated","frame":{"method":"thread/tokenUsage/updated","params":{"threadId":"01a0d610-155f-7391-843e-120bf1475357","turnId":"01a0d610-1619-7d91-bae2-ec4a7b899193","tokenUsage":{"total":{"totalTokens":17752,"inputTokens":17744,"cachedInputTokens":14848,"cacheWriteInputTokens":0,"outputTokens":8,"reasoningOutputTokens":0},"last":{"totalTokens":17752,"inputTokens":17744,"cachedInputTokens":14848,"cacheWriteInputTokens":0,"outputTokens":8,"reasoningOutputTokens":0},"modelContextWindow":258400}},"emittedAtMs":1790297778003}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d610-155f-7391-843e-120bf1475357","status":{"type":"idle"}},"emittedAtMs":1790297778011}} {"type":"emit_inbound","label":"turn/completed","frame":{"method":"turn/completed","params":{"threadId":"01a0d610-155f-7391-843e-120bf1475357","turn":{"id":"01a0d610-1619-7d91-bae2-ec4a7b899193","items":[{"type":"agentMessage","id":"msg_0c4d0b070a58ed52016ab5c6b1b0fc87d0a540ea4be4112eb0","text":"merge sibling source stored","phase":"final_answer","memoryCitation":null,"delivery":null,"questions":null}],"itemsView":"summary","status":"completed","error":null,"startedAt":1790297773,"completedAt":1790297778,"durationMs":4400}},"emittedAtMs":1790297778011}} -{"type":"expect_outbound","label":"thread/fork","frame":{"id":5,"method":"thread/fork","params":{"config":{"tools.update_plan.enabled":true,"mcp_optional_startup_grace_ms":10000,"features.concurrent_reasoning_summaries":true},"cwd":"","excludeTurns":true,"lastTurnId":"01a0d610-1619-7d91-bae2-ec4a7b899193","model":"gpt-6-sol","threadId":"01a0d610-155f-7391-843e-120bf1475357"}}} +{"type":"expect_outbound","label":"thread/fork","frame":{"id":6,"method":"thread/fork","params":{"config":{"tools.update_plan.enabled":true,"mcp_optional_startup_grace_ms":10000,"features.concurrent_reasoning_summaries":true},"cwd":"","excludeTurns":true,"lastTurnId":"01a0d610-1619-7d91-bae2-ec4a7b899193","model":"gpt-6-sol","threadId":"01a0d610-155f-7391-843e-120bf1475357"}}} {"type":"emit_inbound","label":"deprecationNotice","frame":{"method":"deprecationNotice","params":{"summary":"Full-history hydration is deprecated for paginated threads; use `excludeTurns: true`, then page with `thread/turns/list` and `thread/items/list`.","details":null},"emittedAtMs":1790297778016}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0d610-155f-7391-843e-120bf1475357","name":"xcodebuildmcp","status":"ready","error":null,"failureReason":null},"emittedAtMs":1790297778263}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0d610-2789-7bb3-a492-ad7fa8a7db9c","name":"codex_apps","status":"starting","error":null,"failureReason":null},"emittedAtMs":1790297778313}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0d610-2789-7bb3-a492-ad7fa8a7db9c","name":"xcodebuildmcp","status":"starting","error":null,"failureReason":null},"emittedAtMs":1790297778313}} -{"type":"emit_inbound","label":"thread/fork","frame":{"id":5,"result":{"thread":{"id":"01a0d610-2789-7bb3-a492-ad7fa8a7db9c","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d610-2789-7bb3-a492-ad7fa8a7db9c","forkedFromId":"01a0d610-155f-7391-843e-120bf1475357","parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-sol","reasoningEffort":null,"createdAt":1790297778,"updatedAt":1790297778,"recencyAt":1790297778,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-56-18-01a0d610-2789-7bb3-a492-ad7fa8a7db9c.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":{"sha":"1563a64b41d5e7e2e640b46f52cee724913f8851","branch":"v2/codex-gpt6-luna-rerecord","originUrl":"https://github.com/pingdotgg/t3code.git"},"name":null,"daybreakEnabled":null,"turns":[{"id":"01a0d610-1619-7d91-bae2-ec4a7b899193","items":[{"type":"userMessage","id":"01a0d610-1f48-7281-871b-c5d12ab0a228","clientId":null,"content":[{"type":"text","text":"Remember the opaque marker merge-sibling-source-3C7K for later in this conversation. Respond with exactly: merge sibling source stored","text_elements":[]}]},{"type":"agentMessage","id":"msg_0c4d0b070a58ed52016ab5c6b1b0fc87d0a540ea4be4112eb0","text":"merge sibling source stored","phase":"final_answer","memoryCitation":null,"delivery":null,"questions":null}],"itemsView":"full","status":"completed","error":null,"startedAt":1790297773,"completedAt":1790297778,"durationMs":4400}]},"model":"gpt-6-sol","modelProvider":"openai","serviceTier":null,"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"],"instructionSources":["/home/replay-user/.codex/AGENTS.md"],"approvalPolicy":"never","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":{"id":":workspace","extends":null},"reasoningEffort":null,"multiAgentMode":"explicitRequestOnly"}}} -{"type":"expect_outbound","label":"config/read","frame":{"id":6,"method":"config/read","params":{"cwd":"","includeLayers":false}}} -{"type":"emit_inbound","label":"config/read","frame":{"id":6,"result":{"config":{},"origins":{}}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":7,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Remember the fork-local marker merge-sibling-first-6V2J. Respond with exactly: first merge sibling stored","type":"text"}],"model":"gpt-6-sol","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"auto","threadId":"01a0d610-2789-7bb3-a492-ad7fa8a7db9c","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-sol"}}}}} +{"type":"emit_inbound","label":"thread/fork","frame":{"id":6,"result":{"thread":{"id":"01a0d610-2789-7bb3-a492-ad7fa8a7db9c","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d610-2789-7bb3-a492-ad7fa8a7db9c","forkedFromId":"01a0d610-155f-7391-843e-120bf1475357","parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-sol","reasoningEffort":null,"createdAt":1790297778,"updatedAt":1790297778,"recencyAt":1790297778,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-56-18-01a0d610-2789-7bb3-a492-ad7fa8a7db9c.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":{"sha":"1563a64b41d5e7e2e640b46f52cee724913f8851","branch":"v2/codex-gpt6-luna-rerecord","originUrl":"https://github.com/pingdotgg/t3code.git"},"name":null,"daybreakEnabled":null,"turns":[{"id":"01a0d610-1619-7d91-bae2-ec4a7b899193","items":[{"type":"userMessage","id":"01a0d610-1f48-7281-871b-c5d12ab0a228","clientId":null,"content":[{"type":"text","text":"Remember the opaque marker merge-sibling-source-3C7K for later in this conversation. Respond with exactly: merge sibling source stored","text_elements":[]}]},{"type":"agentMessage","id":"msg_0c4d0b070a58ed52016ab5c6b1b0fc87d0a540ea4be4112eb0","text":"merge sibling source stored","phase":"final_answer","memoryCitation":null,"delivery":null,"questions":null}],"itemsView":"full","status":"completed","error":null,"startedAt":1790297773,"completedAt":1790297778,"durationMs":4400}]},"model":"gpt-6-sol","modelProvider":"openai","serviceTier":null,"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"],"instructionSources":["/home/replay-user/.codex/AGENTS.md"],"approvalPolicy":"never","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":{"id":":workspace","extends":null},"reasoningEffort":null,"multiAgentMode":"explicitRequestOnly"}}} +{"type":"expect_outbound","label":"thread/name/set","frame":{"id":7,"method":"thread/name/set","params":{"name":"First merge-back sibling","threadId":"01a0d610-2789-7bb3-a492-ad7fa8a7db9c"}}} +{"type":"emit_inbound","label":"thread/name/set","frame":{"id":7,"result":{}}} +{"type":"emit_inbound","label":"thread/name/updated","frame":{"method":"thread/name/updated","params":{"threadId":"01a0d610-2789-7bb3-a492-ad7fa8a7db9c","threadName":"First merge-back sibling"}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":8,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":8,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":9,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Remember the fork-local marker merge-sibling-first-6V2J. Respond with exactly: first merge sibling stored","type":"text"}],"model":"gpt-6-sol","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"auto","threadId":"01a0d610-2789-7bb3-a492-ad7fa8a7db9c","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-sol"}}}}} {"type":"emit_inbound","label":"thread/tokenUsage/updated","frame":{"method":"thread/tokenUsage/updated","params":{"threadId":"01a0d610-2789-7bb3-a492-ad7fa8a7db9c","turnId":"01a0d610-1619-7d91-bae2-ec4a7b899193","tokenUsage":{"total":{"totalTokens":17752,"inputTokens":17744,"cachedInputTokens":14848,"cacheWriteInputTokens":0,"outputTokens":8,"reasoningOutputTokens":0},"last":{"totalTokens":17752,"inputTokens":17744,"cachedInputTokens":14848,"cacheWriteInputTokens":0,"outputTokens":8,"reasoningOutputTokens":0},"modelContextWindow":258400}},"emittedAtMs":1790297778338}} {"type":"emit_inbound","label":"thread/started","frame":{"method":"thread/started","params":{"thread":{"id":"01a0d610-2789-7bb3-a492-ad7fa8a7db9c","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d610-2789-7bb3-a492-ad7fa8a7db9c","forkedFromId":"01a0d610-155f-7391-843e-120bf1475357","parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-sol","reasoningEffort":null,"createdAt":1790297778,"updatedAt":1790297778,"recencyAt":1790297778,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-56-18-01a0d610-2789-7bb3-a492-ad7fa8a7db9c.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":{"sha":"1563a64b41d5e7e2e640b46f52cee724913f8851","branch":"v2/codex-gpt6-luna-rerecord","originUrl":"https://github.com/pingdotgg/t3code.git"},"name":null,"daybreakEnabled":null,"turns":[]}},"emittedAtMs":1790297778338}} {"type":"emit_inbound","label":"thread/settings/updated","frame":{"method":"thread/settings/updated","params":{"threadId":"01a0d610-2789-7bb3-a492-ad7fa8a7db9c","threadSettings":{"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","approvalPolicy":"never","approvalsReviewer":"user","sandboxPolicy":{"type":"dangerFullAccess"},"activePermissionProfile":null,"model":"gpt-6-sol","modelProvider":"openai","serviceTier":null,"effort":null,"summary":"detailed","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-sol","reasoning_effort":null,"developer_instructions":null}},"multiAgentMode":"explicitRequestOnly","personality":null}},"emittedAtMs":1790297778364}} -{"type":"emit_inbound","label":"turn/start","frame":{"id":7,"result":{"turn":{"id":"01a0d610-28ad-7071-82a1-f55ea8178ae8","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} +{"type":"emit_inbound","label":"turn/start","frame":{"id":9,"result":{"turn":{"id":"01a0d610-28ad-7071-82a1-f55ea8178ae8","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d610-2789-7bb3-a492-ad7fa8a7db9c","status":{"type":"active","activeFlags":[]}},"emittedAtMs":1790297778383}} {"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"01a0d610-2789-7bb3-a492-ad7fa8a7db9c","turn":{"id":"01a0d610-28ad-7071-82a1-f55ea8178ae8","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1790297778,"completedAt":null,"durationMs":null}},"emittedAtMs":1790297778383}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0d610-2789-7bb3-a492-ad7fa8a7db9c","name":"codex_apps","status":"ready","error":null,"failureReason":null},"emittedAtMs":1790297779053}} @@ -56,18 +62,21 @@ {"type":"emit_inbound","label":"thread/tokenUsage/updated","frame":{"method":"thread/tokenUsage/updated","params":{"threadId":"01a0d610-2789-7bb3-a492-ad7fa8a7db9c","turnId":"01a0d610-28ad-7071-82a1-f55ea8178ae8","tokenUsage":{"total":{"totalTokens":39723,"inputTokens":39707,"cachedInputTokens":26624,"cacheWriteInputTokens":0,"outputTokens":16,"reasoningOutputTokens":0},"last":{"totalTokens":21971,"inputTokens":21963,"cachedInputTokens":11776,"cacheWriteInputTokens":0,"outputTokens":8,"reasoningOutputTokens":0},"modelContextWindow":258400}},"emittedAtMs":1790297782125}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d610-2789-7bb3-a492-ad7fa8a7db9c","status":{"type":"idle"}},"emittedAtMs":1790297782161}} {"type":"emit_inbound","label":"turn/completed","frame":{"method":"turn/completed","params":{"threadId":"01a0d610-2789-7bb3-a492-ad7fa8a7db9c","turn":{"id":"01a0d610-28ad-7071-82a1-f55ea8178ae8","items":[{"type":"agentMessage","id":"msg_0c4d0b070a58ed52016ab5c6b5b44c87d08e7e5612c5312499","text":"first merge sibling stored","phase":"final_answer","memoryCitation":null,"delivery":null,"questions":null}],"itemsView":"summary","status":"completed","error":null,"startedAt":1790297778,"completedAt":1790297782,"durationMs":3783}},"emittedAtMs":1790297782161}} -{"type":"expect_outbound","label":"thread/fork","frame":{"id":8,"method":"thread/fork","params":{"config":{"tools.update_plan.enabled":true,"mcp_optional_startup_grace_ms":10000,"features.concurrent_reasoning_summaries":true},"cwd":"","excludeTurns":true,"lastTurnId":"01a0d610-1619-7d91-bae2-ec4a7b899193","model":"gpt-6-sol","threadId":"01a0d610-155f-7391-843e-120bf1475357"}}} +{"type":"expect_outbound","label":"thread/fork","frame":{"id":10,"method":"thread/fork","params":{"config":{"tools.update_plan.enabled":true,"mcp_optional_startup_grace_ms":10000,"features.concurrent_reasoning_summaries":true},"cwd":"","excludeTurns":true,"lastTurnId":"01a0d610-1619-7d91-bae2-ec4a7b899193","model":"gpt-6-sol","threadId":"01a0d610-155f-7391-843e-120bf1475357"}}} {"type":"emit_inbound","label":"deprecationNotice","frame":{"method":"deprecationNotice","params":{"summary":"Full-history hydration is deprecated for paginated threads; use `excludeTurns: true`, then page with `thread/turns/list` and `thread/items/list`.","details":null},"emittedAtMs":1790297782170}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0d610-37d1-7ba1-918f-136cfdbd9bfd","name":"xcodebuildmcp","status":"starting","error":null,"failureReason":null},"emittedAtMs":1790297782559}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0d610-37d1-7ba1-918f-136cfdbd9bfd","name":"codex_apps","status":"starting","error":null,"failureReason":null},"emittedAtMs":1790297782559}} -{"type":"emit_inbound","label":"thread/fork","frame":{"id":8,"result":{"thread":{"id":"01a0d610-37d1-7ba1-918f-136cfdbd9bfd","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d610-37d1-7ba1-918f-136cfdbd9bfd","forkedFromId":"01a0d610-155f-7391-843e-120bf1475357","parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-sol","reasoningEffort":null,"createdAt":1790297782,"updatedAt":1790297782,"recencyAt":1790297782,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-56-22-01a0d610-37d1-7ba1-918f-136cfdbd9bfd.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":{"sha":"1563a64b41d5e7e2e640b46f52cee724913f8851","branch":"v2/codex-gpt6-luna-rerecord","originUrl":"https://github.com/pingdotgg/t3code.git"},"name":null,"daybreakEnabled":null,"turns":[{"id":"01a0d610-1619-7d91-bae2-ec4a7b899193","items":[{"type":"userMessage","id":"01a0d610-1f48-7281-871b-c5d12ab0a228","clientId":null,"content":[{"type":"text","text":"Remember the opaque marker merge-sibling-source-3C7K for later in this conversation. Respond with exactly: merge sibling source stored","text_elements":[]}]},{"type":"agentMessage","id":"msg_0c4d0b070a58ed52016ab5c6b1b0fc87d0a540ea4be4112eb0","text":"merge sibling source stored","phase":"final_answer","memoryCitation":null,"delivery":null,"questions":null}],"itemsView":"full","status":"completed","error":null,"startedAt":1790297773,"completedAt":1790297778,"durationMs":4400}]},"model":"gpt-6-sol","modelProvider":"openai","serviceTier":null,"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"],"instructionSources":["/home/replay-user/.codex/AGENTS.md"],"approvalPolicy":"never","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":{"id":":workspace","extends":null},"reasoningEffort":null,"multiAgentMode":"explicitRequestOnly"}}} -{"type":"expect_outbound","label":"config/read","frame":{"id":9,"method":"config/read","params":{"cwd":"","includeLayers":false}}} -{"type":"emit_inbound","label":"config/read","frame":{"id":9,"result":{"config":{},"origins":{}}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":10,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Remember the fork-local marker merge-sibling-second-9X5B. Respond with exactly: second merge sibling stored","type":"text"}],"model":"gpt-6-sol","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"auto","threadId":"01a0d610-37d1-7ba1-918f-136cfdbd9bfd","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-sol"}}}}} +{"type":"emit_inbound","label":"thread/fork","frame":{"id":10,"result":{"thread":{"id":"01a0d610-37d1-7ba1-918f-136cfdbd9bfd","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d610-37d1-7ba1-918f-136cfdbd9bfd","forkedFromId":"01a0d610-155f-7391-843e-120bf1475357","parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-sol","reasoningEffort":null,"createdAt":1790297782,"updatedAt":1790297782,"recencyAt":1790297782,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-56-22-01a0d610-37d1-7ba1-918f-136cfdbd9bfd.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":{"sha":"1563a64b41d5e7e2e640b46f52cee724913f8851","branch":"v2/codex-gpt6-luna-rerecord","originUrl":"https://github.com/pingdotgg/t3code.git"},"name":null,"daybreakEnabled":null,"turns":[{"id":"01a0d610-1619-7d91-bae2-ec4a7b899193","items":[{"type":"userMessage","id":"01a0d610-1f48-7281-871b-c5d12ab0a228","clientId":null,"content":[{"type":"text","text":"Remember the opaque marker merge-sibling-source-3C7K for later in this conversation. Respond with exactly: merge sibling source stored","text_elements":[]}]},{"type":"agentMessage","id":"msg_0c4d0b070a58ed52016ab5c6b1b0fc87d0a540ea4be4112eb0","text":"merge sibling source stored","phase":"final_answer","memoryCitation":null,"delivery":null,"questions":null}],"itemsView":"full","status":"completed","error":null,"startedAt":1790297773,"completedAt":1790297778,"durationMs":4400}]},"model":"gpt-6-sol","modelProvider":"openai","serviceTier":null,"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"],"instructionSources":["/home/replay-user/.codex/AGENTS.md"],"approvalPolicy":"never","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":{"id":":workspace","extends":null},"reasoningEffort":null,"multiAgentMode":"explicitRequestOnly"}}} +{"type":"expect_outbound","label":"thread/name/set","frame":{"id":11,"method":"thread/name/set","params":{"name":"Second merge-back sibling","threadId":"01a0d610-37d1-7ba1-918f-136cfdbd9bfd"}}} +{"type":"emit_inbound","label":"thread/name/set","frame":{"id":11,"result":{}}} +{"type":"emit_inbound","label":"thread/name/updated","frame":{"method":"thread/name/updated","params":{"threadId":"01a0d610-37d1-7ba1-918f-136cfdbd9bfd","threadName":"Second merge-back sibling"}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":12,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":12,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":13,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Remember the fork-local marker merge-sibling-second-9X5B. Respond with exactly: second merge sibling stored","type":"text"}],"model":"gpt-6-sol","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"auto","threadId":"01a0d610-37d1-7ba1-918f-136cfdbd9bfd","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-sol"}}}}} {"type":"emit_inbound","label":"thread/tokenUsage/updated","frame":{"method":"thread/tokenUsage/updated","params":{"threadId":"01a0d610-37d1-7ba1-918f-136cfdbd9bfd","turnId":"01a0d610-1619-7d91-bae2-ec4a7b899193","tokenUsage":{"total":{"totalTokens":17752,"inputTokens":17744,"cachedInputTokens":14848,"cacheWriteInputTokens":0,"outputTokens":8,"reasoningOutputTokens":0},"last":{"totalTokens":17752,"inputTokens":17744,"cachedInputTokens":14848,"cacheWriteInputTokens":0,"outputTokens":8,"reasoningOutputTokens":0},"modelContextWindow":258400}},"emittedAtMs":1790297782630}} {"type":"emit_inbound","label":"thread/started","frame":{"method":"thread/started","params":{"thread":{"id":"01a0d610-37d1-7ba1-918f-136cfdbd9bfd","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d610-37d1-7ba1-918f-136cfdbd9bfd","forkedFromId":"01a0d610-155f-7391-843e-120bf1475357","parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-sol","reasoningEffort":null,"createdAt":1790297782,"updatedAt":1790297782,"recencyAt":1790297782,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-56-22-01a0d610-37d1-7ba1-918f-136cfdbd9bfd.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":{"sha":"1563a64b41d5e7e2e640b46f52cee724913f8851","branch":"v2/codex-gpt6-luna-rerecord","originUrl":"https://github.com/pingdotgg/t3code.git"},"name":null,"daybreakEnabled":null,"turns":[]}},"emittedAtMs":1790297782630}} {"type":"emit_inbound","label":"thread/settings/updated","frame":{"method":"thread/settings/updated","params":{"threadId":"01a0d610-37d1-7ba1-918f-136cfdbd9bfd","threadSettings":{"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","approvalPolicy":"never","approvalsReviewer":"user","sandboxPolicy":{"type":"dangerFullAccess"},"activePermissionProfile":null,"model":"gpt-6-sol","modelProvider":"openai","serviceTier":null,"effort":null,"summary":"detailed","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-sol","reasoning_effort":null,"developer_instructions":null}},"multiAgentMode":"explicitRequestOnly","personality":null}},"emittedAtMs":1790297782690}} -{"type":"emit_inbound","label":"turn/start","frame":{"id":10,"result":{"turn":{"id":"01a0d610-398b-7ea0-b252-1ba58fc7d14d","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} +{"type":"emit_inbound","label":"turn/start","frame":{"id":13,"result":{"turn":{"id":"01a0d610-398b-7ea0-b252-1ba58fc7d14d","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d610-37d1-7ba1-918f-136cfdbd9bfd","status":{"type":"active","activeFlags":[]}},"emittedAtMs":1790297782728}} {"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"01a0d610-37d1-7ba1-918f-136cfdbd9bfd","turn":{"id":"01a0d610-398b-7ea0-b252-1ba58fc7d14d","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1790297782,"completedAt":null,"durationMs":null}},"emittedAtMs":1790297782728}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0d610-2789-7bb3-a492-ad7fa8a7db9c","name":"xcodebuildmcp","status":"ready","error":null,"failureReason":null},"emittedAtMs":1790297782926}} @@ -83,10 +92,10 @@ {"type":"emit_inbound","label":"thread/tokenUsage/updated","frame":{"method":"thread/tokenUsage/updated","params":{"threadId":"01a0d610-37d1-7ba1-918f-136cfdbd9bfd","turnId":"01a0d610-398b-7ea0-b252-1ba58fc7d14d","tokenUsage":{"total":{"totalTokens":39723,"inputTokens":39707,"cachedInputTokens":32384,"cacheWriteInputTokens":0,"outputTokens":16,"reasoningOutputTokens":0},"last":{"totalTokens":21971,"inputTokens":21963,"cachedInputTokens":17536,"cacheWriteInputTokens":0,"outputTokens":8,"reasoningOutputTokens":0},"modelContextWindow":258400}},"emittedAtMs":1790297786356}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d610-37d1-7ba1-918f-136cfdbd9bfd","status":{"type":"idle"}},"emittedAtMs":1790297786381}} {"type":"emit_inbound","label":"turn/completed","frame":{"method":"turn/completed","params":{"threadId":"01a0d610-37d1-7ba1-918f-136cfdbd9bfd","turn":{"id":"01a0d610-398b-7ea0-b252-1ba58fc7d14d","items":[{"type":"agentMessage","id":"msg_0c4d0b070a58ed52016ab5c6b9e23887d0aead55548c08d807","text":"second merge sibling stored","phase":"final_answer","memoryCitation":null,"delivery":null,"questions":null}],"itemsView":"summary","status":"completed","error":null,"startedAt":1790297782,"completedAt":1790297786,"durationMs":3683}},"emittedAtMs":1790297786381}} -{"type":"expect_outbound","label":"config/read","frame":{"id":11,"method":"config/read","params":{"cwd":"","includeLayers":false}}} -{"type":"emit_inbound","label":"config/read","frame":{"id":11,"result":{"config":{},"origins":{}}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":12,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Context handoff (merge_back / fork_delta_summary):\nMerge-back context from first forked conversation.\n\nFork delta:\n- User introduced opaque marker merge-sibling-first-6V2J.\n- Assistant confirmed: first merge sibling stored\n\nUser message:\nRetain the first transferred marker for later. Respond with exactly: first merge delta stored","type":"text"}],"model":"gpt-6-sol","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"auto","threadId":"01a0d610-155f-7391-843e-120bf1475357","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-sol"}}}}} -{"type":"emit_inbound","label":"turn/start","frame":{"id":12,"result":{"turn":{"id":"01a0d610-481e-7522-ab04-234cac3907b5","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":14,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":14,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":15,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Context handoff (merge_back / fork_delta_summary):\nMerge-back context from first forked conversation.\n\nFork delta:\n- User introduced opaque marker merge-sibling-first-6V2J.\n- Assistant confirmed: first merge sibling stored\n\nUser message:\nRetain the first transferred marker for later. Respond with exactly: first merge delta stored","type":"text"}],"model":"gpt-6-sol","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"auto","threadId":"01a0d610-155f-7391-843e-120bf1475357","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-sol"}}}}} +{"type":"emit_inbound","label":"turn/start","frame":{"id":15,"result":{"turn":{"id":"01a0d610-481e-7522-ab04-234cac3907b5","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d610-155f-7391-843e-120bf1475357","status":{"type":"active","activeFlags":[]}},"emittedAtMs":1790297786444}} {"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"01a0d610-155f-7391-843e-120bf1475357","turn":{"id":"01a0d610-481e-7522-ab04-234cac3907b5","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1790297786,"completedAt":null,"durationMs":null}},"emittedAtMs":1790297786444}} {"type":"emit_inbound","label":"item/started","frame":{"method":"item/started","params":{"item":{"type":"userMessage","id":"01a0d610-48e6-7791-90d7-390fdc407d60","clientId":null,"content":[{"type":"text","text":"Context handoff (merge_back / fork_delta_summary):\nMerge-back context from first forked conversation.\n\nFork delta:\n- User introduced opaque marker merge-sibling-first-6V2J.\n- Assistant confirmed: first merge sibling stored\n\nUser message:\nRetain the first transferred marker for later. Respond with exactly: first merge delta stored","text_elements":[]}]},"threadId":"01a0d610-155f-7391-843e-120bf1475357","turnId":"01a0d610-481e-7522-ab04-234cac3907b5","startedAtMs":1790297786608},"emittedAtMs":1790297786608}} @@ -105,10 +114,10 @@ {"type":"emit_inbound","label":"thread/tokenUsage/updated","frame":{"method":"thread/tokenUsage/updated","params":{"threadId":"01a0d610-155f-7391-843e-120bf1475357","turnId":"01a0d610-481e-7522-ab04-234cac3907b5","tokenUsage":{"total":{"totalTokens":39782,"inputTokens":39751,"cachedInputTokens":32384,"cacheWriteInputTokens":0,"outputTokens":31,"reasoningOutputTokens":13},"last":{"totalTokens":22030,"inputTokens":22007,"cachedInputTokens":17536,"cacheWriteInputTokens":0,"outputTokens":23,"reasoningOutputTokens":13},"modelContextWindow":258400}},"emittedAtMs":1790297790394}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d610-155f-7391-843e-120bf1475357","status":{"type":"idle"}},"emittedAtMs":1790297790409}} {"type":"emit_inbound","label":"turn/completed","frame":{"method":"turn/completed","params":{"threadId":"01a0d610-155f-7391-843e-120bf1475357","turn":{"id":"01a0d610-481e-7522-ab04-234cac3907b5","items":[{"type":"agentMessage","id":"msg_0c4d0b070a58ed52016ab5c6be15bc87d0b5c0c3a9a6045bbb","text":"first merge delta stored","phase":"final_answer","memoryCitation":null,"delivery":null,"questions":null}],"itemsView":"summary","status":"completed","error":null,"startedAt":1790297786,"completedAt":1790297790,"durationMs":3979}},"emittedAtMs":1790297790409}} -{"type":"expect_outbound","label":"config/read","frame":{"id":13,"method":"config/read","params":{"cwd":"","includeLayers":false}}} -{"type":"emit_inbound","label":"config/read","frame":{"id":13,"result":{"config":{},"origins":{}}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":14,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Context handoff (merge_back / fork_delta_summary):\nMerge-back context from second forked conversation.\n\nFork delta:\n- User introduced opaque marker merge-sibling-second-9X5B.\n- Assistant confirmed: second merge sibling stored\n\nUser message:\nRetain the second transferred marker for later. Respond with exactly: second merge delta stored","type":"text"}],"model":"gpt-6-sol","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"auto","threadId":"01a0d610-155f-7391-843e-120bf1475357","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-sol"}}}}} -{"type":"emit_inbound","label":"turn/start","frame":{"id":14,"result":{"turn":{"id":"01a0d610-57d2-7671-858a-d9e868574664","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":16,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":16,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":17,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Context handoff (merge_back / fork_delta_summary):\nMerge-back context from second forked conversation.\n\nFork delta:\n- User introduced opaque marker merge-sibling-second-9X5B.\n- Assistant confirmed: second merge sibling stored\n\nUser message:\nRetain the second transferred marker for later. Respond with exactly: second merge delta stored","type":"text"}],"model":"gpt-6-sol","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"auto","threadId":"01a0d610-155f-7391-843e-120bf1475357","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-sol"}}}}} +{"type":"emit_inbound","label":"turn/start","frame":{"id":17,"result":{"turn":{"id":"01a0d610-57d2-7671-858a-d9e868574664","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d610-155f-7391-843e-120bf1475357","status":{"type":"active","activeFlags":[]}},"emittedAtMs":1790297790438}} {"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"01a0d610-155f-7391-843e-120bf1475357","turn":{"id":"01a0d610-57d2-7671-858a-d9e868574664","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1790297790,"completedAt":null,"durationMs":null}},"emittedAtMs":1790297790438}} {"type":"emit_inbound","label":"item/started","frame":{"method":"item/started","params":{"item":{"type":"userMessage","id":"01a0d610-5897-7993-b78c-2e5977b826e8","clientId":null,"content":[{"type":"text","text":"Context handoff (merge_back / fork_delta_summary):\nMerge-back context from second forked conversation.\n\nFork delta:\n- User introduced opaque marker merge-sibling-second-9X5B.\n- Assistant confirmed: second merge sibling stored\n\nUser message:\nRetain the second transferred marker for later. Respond with exactly: second merge delta stored","text_elements":[]}]},"threadId":"01a0d610-155f-7391-843e-120bf1475357","turnId":"01a0d610-57d2-7671-858a-d9e868574664","startedAtMs":1790297790625},"emittedAtMs":1790297790625}} @@ -122,10 +131,10 @@ {"type":"emit_inbound","label":"thread/tokenUsage/updated","frame":{"method":"thread/tokenUsage/updated","params":{"threadId":"01a0d610-155f-7391-843e-120bf1475357","turnId":"01a0d610-57d2-7671-858a-d9e868574664","tokenUsage":{"total":{"totalTokens":61893,"inputTokens":61854,"cachedInputTokens":54272,"cacheWriteInputTokens":0,"outputTokens":39,"reasoningOutputTokens":13},"last":{"totalTokens":22111,"inputTokens":22103,"cachedInputTokens":21888,"cacheWriteInputTokens":0,"outputTokens":8,"reasoningOutputTokens":0},"modelContextWindow":258400}},"emittedAtMs":1790297793240}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d610-155f-7391-843e-120bf1475357","status":{"type":"idle"}},"emittedAtMs":1790297793249}} {"type":"emit_inbound","label":"turn/completed","frame":{"method":"turn/completed","params":{"threadId":"01a0d610-155f-7391-843e-120bf1475357","turn":{"id":"01a0d610-57d2-7671-858a-d9e868574664","items":[{"type":"agentMessage","id":"msg_0c4d0b070a58ed52016ab5c6c071ec87d0ad6a38add1f18e1a","text":"second merge delta stored","phase":"final_answer","memoryCitation":null,"delivery":null,"questions":null}],"itemsView":"summary","status":"completed","error":null,"startedAt":1790297790,"completedAt":1790297793,"durationMs":2814}},"emittedAtMs":1790297793249}} -{"type":"expect_outbound","label":"config/read","frame":{"id":15,"method":"config/read","params":{"cwd":"","includeLayers":false}}} -{"type":"emit_inbound","label":"config/read","frame":{"id":15,"result":{"config":{},"origins":{}}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":16,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Return the source marker followed by both transferred fork markers in merge order, separated by single | characters. Respond with only the markers and separators.","type":"text"}],"model":"gpt-6-sol","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"auto","threadId":"01a0d610-155f-7391-843e-120bf1475357","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-sol"}}}}} -{"type":"emit_inbound","label":"turn/start","frame":{"id":16,"result":{"turn":{"id":"01a0d610-62e7-7610-9b44-1d654367e4bf","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":18,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":18,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":19,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Return the source marker followed by both transferred fork markers in merge order, separated by single | characters. Respond with only the markers and separators.","type":"text"}],"model":"gpt-6-sol","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"auto","threadId":"01a0d610-155f-7391-843e-120bf1475357","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-sol"}}}}} +{"type":"emit_inbound","label":"turn/start","frame":{"id":19,"result":{"turn":{"id":"01a0d610-62e7-7610-9b44-1d654367e4bf","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d610-155f-7391-843e-120bf1475357","status":{"type":"active","activeFlags":[]}},"emittedAtMs":1790297793308}} {"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"01a0d610-155f-7391-843e-120bf1475357","turn":{"id":"01a0d610-62e7-7610-9b44-1d654367e4bf","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1790297793,"completedAt":null,"durationMs":null}},"emittedAtMs":1790297793308}} {"type":"emit_inbound","label":"item/started","frame":{"method":"item/started","params":{"item":{"type":"userMessage","id":"01a0d610-63a5-7aa0-bdd9-6d0a56bf21e7","clientId":null,"content":[{"type":"text","text":"Return the source marker followed by both transferred fork markers in merge order, separated by single | characters. Respond with only the markers and separators.","text_elements":[]}]},"threadId":"01a0d610-155f-7391-843e-120bf1475357","turnId":"01a0d610-62e7-7610-9b44-1d654367e4bf","startedAtMs":1790297793453},"emittedAtMs":1790297793453}} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/thread_rollback/codex_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/thread_rollback/codex_transcript.ndjson index 85cf1ead68bb6..ba52432940a03 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/thread_rollback/codex_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/thread_rollback/codex_transcript.ndjson @@ -6,13 +6,16 @@ {"type":"emit_inbound","label":"configWarning","frame":{"method":"configWarning","params":{"summary":"Codex could not find bubblewrap on PATH. Install bubblewrap with your OS package manager. See the sandbox prerequisites: https://developers.openai.com/codex/concepts/sandboxing#prerequisites. Codex will use the bundled bubblewrap in the meantime.","details":null},"emittedAtMs":1790295644807}} {"type":"emit_inbound","label":"remoteControl/status/changed","frame":{"method":"remoteControl/status/changed","params":{"status":"disabled","serverName":"replay-host","installationId":"00000000-0000-4000-8000-000000000000","environmentId":null},"emittedAtMs":1790295644807}} {"type":"emit_inbound","label":"thread/start","frame":{"id":2,"result":{"thread":{"id":"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790295644,"updatedAt":1790295644,"recencyAt":1790295644,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-20-44-01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]},"model":"gpt-6-luna","modelProvider":"openai","serviceTier":null,"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"],"instructionSources":["/home/replay-user/.codex/AGENTS.md","/home/replay-user/t3code/AGENTS.md"],"approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":{"id":":workspace","extends":null},"reasoningEffort":null,"multiAgentMode":"explicitRequestOnly"}}} -{"type":"expect_outbound","label":"config/read","frame":{"id":3,"method":"config/read","params":{"cwd":"","includeLayers":false}}} -{"type":"emit_inbound","label":"config/read","frame":{"id":3,"result":{"config":{},"origins":{}}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":4,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Respond with exactly: rollback fixture first turn complete","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"auto","threadId":"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} +{"type":"expect_outbound","label":"thread/name/set","frame":{"id":3,"method":"thread/name/set","params":{"name":"Replay fixture: thread_rollback","threadId":"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff"}}} +{"type":"emit_inbound","label":"thread/name/set","frame":{"id":3,"result":{}}} +{"type":"emit_inbound","label":"thread/name/updated","frame":{"method":"thread/name/updated","params":{"threadId":"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff","threadName":"Replay fixture: thread_rollback"}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":4,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":4,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":5,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Respond with exactly: rollback fixture first turn complete","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"auto","threadId":"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} {"type":"emit_inbound","label":"thread/started","frame":{"method":"thread/started","params":{"thread":{"id":"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790295644,"updatedAt":1790295644,"recencyAt":1790295644,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-20-44-01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]}},"emittedAtMs":1790295645009}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff","name":"codex_apps","status":"starting","error":null,"failureReason":null},"emittedAtMs":1790295645009}} {"type":"emit_inbound","label":"thread/settings/updated","frame":{"method":"thread/settings/updated","params":{"threadId":"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff","threadSettings":{"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","approvalPolicy":"never","approvalsReviewer":"user","sandboxPolicy":{"type":"dangerFullAccess"},"activePermissionProfile":null,"model":"gpt-6-luna","modelProvider":"openai","serviceTier":null,"effort":null,"summary":"detailed","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna","reasoning_effort":null,"developer_instructions":null}},"multiAgentMode":"explicitRequestOnly","personality":null}},"emittedAtMs":1790295645023}} -{"type":"emit_inbound","label":"turn/start","frame":{"id":4,"result":{"turn":{"id":"01a0d5ef-9b58-7980-9e7a-2463dd068a8e","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} +{"type":"emit_inbound","label":"turn/start","frame":{"id":5,"result":{"turn":{"id":"01a0d5ef-9b58-7980-9e7a-2463dd068a8e","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff","status":{"type":"active","activeFlags":[]}},"emittedAtMs":1790295645070}} {"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff","turn":{"id":"01a0d5ef-9b58-7980-9e7a-2463dd068a8e","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1790295645,"completedAt":null,"durationMs":null}},"emittedAtMs":1790295645070}} {"type":"emit_inbound","label":"account/updated","frame":{"method":"account/updated","params":{"authMode":"chatgpt","planType":"unknown"},"emittedAtMs":1790295645465}} @@ -30,10 +33,10 @@ {"type":"emit_inbound","label":"thread/tokenUsage/updated","frame":{"method":"thread/tokenUsage/updated","params":{"threadId":"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff","turnId":"01a0d5ef-9b58-7980-9e7a-2463dd068a8e","tokenUsage":{"total":{"totalTokens":21428,"inputTokens":21419,"cachedInputTokens":21248,"cacheWriteInputTokens":0,"outputTokens":9,"reasoningOutputTokens":0},"last":{"totalTokens":21428,"inputTokens":21419,"cachedInputTokens":21248,"cacheWriteInputTokens":0,"outputTokens":9,"reasoningOutputTokens":0},"modelContextWindow":258400}},"emittedAtMs":1790295649339}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff","status":{"type":"idle"}},"emittedAtMs":1790295649352}} {"type":"emit_inbound","label":"turn/completed","frame":{"method":"turn/completed","params":{"threadId":"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff","turn":{"id":"01a0d5ef-9b58-7980-9e7a-2463dd068a8e","items":[{"type":"agentMessage","id":"msg_044082e5a0068297016ab5be60f20c87d0aed9858a5d1f00b2","text":"rollback fixture first turn complete","phase":"final_answer","memoryCitation":null,"delivery":null,"questions":null}],"itemsView":"summary","status":"completed","error":null,"startedAt":1790295645,"completedAt":1790295649,"durationMs":4326}},"emittedAtMs":1790295649352}} -{"type":"expect_outbound","label":"config/read","frame":{"id":5,"method":"config/read","params":{"cwd":"","includeLayers":false}}} -{"type":"emit_inbound","label":"config/read","frame":{"id":5,"result":{"config":{},"origins":{}}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":6,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Respond with exactly: rollback fixture second turn complete","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"auto","threadId":"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} -{"type":"emit_inbound","label":"turn/start","frame":{"id":6,"result":{"turn":{"id":"01a0d5ef-ac4e-7471-a4a8-6776e39e6d29","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":6,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":6,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":7,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Respond with exactly: rollback fixture second turn complete","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"auto","threadId":"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} +{"type":"emit_inbound","label":"turn/start","frame":{"id":7,"result":{"turn":{"id":"01a0d5ef-ac4e-7471-a4a8-6776e39e6d29","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff","status":{"type":"active","activeFlags":[]}},"emittedAtMs":1790295649424}} {"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff","turn":{"id":"01a0d5ef-ac4e-7471-a4a8-6776e39e6d29","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1790295649,"completedAt":null,"durationMs":null}},"emittedAtMs":1790295649424}} {"type":"emit_inbound","label":"item/started","frame":{"method":"item/started","params":{"item":{"type":"userMessage","id":"01a0d5ef-ad0e-78d0-af5c-7145f750bd81","clientId":null,"content":[{"type":"text","text":"Respond with exactly: rollback fixture second turn complete","text_elements":[]}]},"threadId":"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff","turnId":"01a0d5ef-ac4e-7471-a4a8-6776e39e6d29","startedAtMs":1790295649555},"emittedAtMs":1790295649555}} @@ -49,21 +52,21 @@ {"type":"emit_inbound","label":"thread/tokenUsage/updated","frame":{"method":"thread/tokenUsage/updated","params":{"threadId":"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff","turnId":"01a0d5ef-ac4e-7471-a4a8-6776e39e6d29","tokenUsage":{"total":{"totalTokens":47217,"inputTokens":47199,"cachedInputTokens":42496,"cacheWriteInputTokens":0,"outputTokens":18,"reasoningOutputTokens":0},"last":{"totalTokens":25789,"inputTokens":25780,"cachedInputTokens":21248,"cacheWriteInputTokens":0,"outputTokens":9,"reasoningOutputTokens":0},"modelContextWindow":258400}},"emittedAtMs":1790295651330}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff","status":{"type":"idle"}},"emittedAtMs":1790295651335}} {"type":"emit_inbound","label":"turn/completed","frame":{"method":"turn/completed","params":{"threadId":"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff","turn":{"id":"01a0d5ef-ac4e-7471-a4a8-6776e39e6d29","items":[{"type":"agentMessage","id":"msg_044082e5a0068297016ab5be62fefc87d0bbf3fdbed6561ac8","text":"rollback fixture second turn complete","phase":"final_answer","memoryCitation":null,"delivery":null,"questions":null}],"itemsView":"summary","status":"completed","error":null,"startedAt":1790295649,"completedAt":1790295651,"durationMs":1931}},"emittedAtMs":1790295651335}} -{"type":"expect_outbound","label":"thread/read","frame":{"id":7,"method":"thread/read","params":{"includeTurns":false,"threadId":"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff"}}} -{"type":"emit_inbound","label":"thread/read","frame":{"id":7,"result":{"thread":{"id":"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff","forkedFromId":null,"parentThreadId":null,"preview":"Respond with exactly: rollback fixture first turn complete","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790295644,"updatedAt":1790295651,"recencyAt":1790295649,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-20-44-01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":{"sha":"1563a64b41d5e7e2e640b46f52cee724913f8851","branch":"v2/codex-gpt6-luna-rerecord","originUrl":"https://github.com/pingdotgg/t3code.git"},"name":null,"daybreakEnabled":null,"turns":[]}}}} -{"type":"expect_outbound","label":"thread/turns/list","frame":{"id":8,"method":"thread/turns/list","params":{"cursor":null,"itemsView":"summary","limit":1,"sortDirection":"desc","threadId":"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff"}}} -{"type":"emit_inbound","label":"thread/turns/list","frame":{"id":8,"result":{"data":[{"id":"01a0d5ef-ac4e-7471-a4a8-6776e39e6d29","items":[{"type":"userMessage","id":"01a0d5ef-ad0e-78d0-af5c-7145f750bd81","clientId":null,"content":[{"type":"text","text":"Respond with exactly: rollback fixture second turn complete","text_elements":[]}]},{"type":"agentMessage","id":"msg_044082e5a0068297016ab5be62fefc87d0bbf3fdbed6561ac8","text":"rollback fixture second turn complete","phase":"final_answer","memoryCitation":null,"delivery":null,"questions":null}],"itemsView":"summary","status":"completed","error":null,"startedAt":1790295649,"completedAt":1790295651,"durationMs":1931}],"nextCursor":"{\"requestedThreadId\":\"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff\",\"rolloutOrdinal\":16,\"includeAnchor\":false,\"scope\":{\"kind\":\"turns\"}}","backwardsCursor":"{\"requestedThreadId\":\"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff\",\"rolloutOrdinal\":16,\"includeAnchor\":true,\"scope\":{\"kind\":\"turns\"}}"}}} -{"type":"expect_outbound","label":"thread/revert","frame":{"id":9,"method":"thread/revert","params":{"beforeTurnId":"01a0d5ef-ac4e-7471-a4a8-6776e39e6d29","threadId":"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff"}}} +{"type":"expect_outbound","label":"thread/read","frame":{"id":8,"method":"thread/read","params":{"includeTurns":false,"threadId":"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff"}}} +{"type":"emit_inbound","label":"thread/read","frame":{"id":8,"result":{"thread":{"id":"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff","forkedFromId":null,"parentThreadId":null,"preview":"Respond with exactly: rollback fixture first turn complete","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790295644,"updatedAt":1790295651,"recencyAt":1790295649,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-20-44-01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":{"sha":"1563a64b41d5e7e2e640b46f52cee724913f8851","branch":"v2/codex-gpt6-luna-rerecord","originUrl":"https://github.com/pingdotgg/t3code.git"},"name":null,"daybreakEnabled":null,"turns":[]}}}} +{"type":"expect_outbound","label":"thread/turns/list","frame":{"id":9,"method":"thread/turns/list","params":{"cursor":null,"itemsView":"summary","limit":1,"sortDirection":"desc","threadId":"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff"}}} +{"type":"emit_inbound","label":"thread/turns/list","frame":{"id":9,"result":{"data":[{"id":"01a0d5ef-ac4e-7471-a4a8-6776e39e6d29","items":[{"type":"userMessage","id":"01a0d5ef-ad0e-78d0-af5c-7145f750bd81","clientId":null,"content":[{"type":"text","text":"Respond with exactly: rollback fixture second turn complete","text_elements":[]}]},{"type":"agentMessage","id":"msg_044082e5a0068297016ab5be62fefc87d0bbf3fdbed6561ac8","text":"rollback fixture second turn complete","phase":"final_answer","memoryCitation":null,"delivery":null,"questions":null}],"itemsView":"summary","status":"completed","error":null,"startedAt":1790295649,"completedAt":1790295651,"durationMs":1931}],"nextCursor":"{\"requestedThreadId\":\"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff\",\"rolloutOrdinal\":16,\"includeAnchor\":false,\"scope\":{\"kind\":\"turns\"}}","backwardsCursor":"{\"requestedThreadId\":\"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff\",\"rolloutOrdinal\":16,\"includeAnchor\":true,\"scope\":{\"kind\":\"turns\"}}"}}} +{"type":"expect_outbound","label":"thread/revert","frame":{"id":10,"method":"thread/revert","params":{"beforeTurnId":"01a0d5ef-ac4e-7471-a4a8-6776e39e6d29","threadId":"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff"}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff","status":{"type":"notLoaded"}},"emittedAtMs":1790295651358}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff","name":"xcodebuildmcp","status":"starting","error":null,"failureReason":null},"emittedAtMs":1790295651544}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff","name":"codex_apps","status":"starting","error":null,"failureReason":null},"emittedAtMs":1790295651544}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff","status":{"type":"idle"}},"emittedAtMs":1790295651551}} -{"type":"emit_inbound","label":"thread/revert","frame":{"id":9,"result":{"thread":{"id":"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff","forkedFromId":null,"parentThreadId":null,"preview":"Respond with exactly: rollback fixture first turn complete","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790295651,"updatedAt":1790295651,"recencyAt":1790295649,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-20-51-01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff_01a0d5ef-b424-72f2-9853-9b112f028a71.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":{"sha":"1563a64b41d5e7e2e640b46f52cee724913f8851","branch":"v2/codex-gpt6-luna-rerecord","originUrl":"https://github.com/pingdotgg/t3code.git"},"name":null,"daybreakEnabled":null,"turns":[]},"turnsBackwardsCursor":"{\"requestedThreadId\":\"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff\",\"rolloutOrdinal\":1,\"includeAnchor\":true,\"scope\":{\"kind\":\"turns\"}}","itemsBackwardsCursor":"{\"requestedThreadId\":\"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff\",\"rolloutOrdinal\":10,\"includeAnchor\":true,\"scope\":{\"kind\":\"itemsByCreatedAtOrdinal\"}}"}}} -{"type":"expect_outbound","label":"config/read","frame":{"id":10,"method":"config/read","params":{"cwd":"","includeLayers":false}}} -{"type":"emit_inbound","label":"config/read","frame":{"id":10,"result":{"config":{},"origins":{}}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":11,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Repeat the conversation verbatim.","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"auto","threadId":"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} +{"type":"emit_inbound","label":"thread/revert","frame":{"id":10,"result":{"thread":{"id":"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff","forkedFromId":null,"parentThreadId":null,"preview":"Respond with exactly: rollback fixture first turn complete","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790295651,"updatedAt":1790295651,"recencyAt":1790295649,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-20-51-01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff_01a0d5ef-b424-72f2-9853-9b112f028a71.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":{"sha":"1563a64b41d5e7e2e640b46f52cee724913f8851","branch":"v2/codex-gpt6-luna-rerecord","originUrl":"https://github.com/pingdotgg/t3code.git"},"name":null,"daybreakEnabled":null,"turns":[]},"turnsBackwardsCursor":"{\"requestedThreadId\":\"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff\",\"rolloutOrdinal\":1,\"includeAnchor\":true,\"scope\":{\"kind\":\"turns\"}}","itemsBackwardsCursor":"{\"requestedThreadId\":\"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff\",\"rolloutOrdinal\":10,\"includeAnchor\":true,\"scope\":{\"kind\":\"itemsByCreatedAtOrdinal\"}}"}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":11,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":11,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":12,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Repeat the conversation verbatim.","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"auto","threadId":"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} {"type":"emit_inbound","label":"thread/reverted","frame":{"method":"thread/reverted","params":{"threadId":"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff"},"emittedAtMs":1790295651568}} -{"type":"emit_inbound","label":"turn/start","frame":{"id":11,"result":{"turn":{"id":"01a0d5ef-b4f4-7aa2-b4c2-f5f494881401","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} +{"type":"emit_inbound","label":"turn/start","frame":{"id":12,"result":{"turn":{"id":"01a0d5ef-b4f4-7aa2-b4c2-f5f494881401","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff","status":{"type":"active","activeFlags":[]}},"emittedAtMs":1790295651594}} {"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff","turn":{"id":"01a0d5ef-b4f4-7aa2-b4c2-f5f494881401","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1790295651,"completedAt":null,"durationMs":null}},"emittedAtMs":1790295651594}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff","name":"codex_apps","status":"ready","error":null,"failureReason":null},"emittedAtMs":1790295652127}} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/thread_rollback_after_restart/codex_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/thread_rollback_after_restart/codex_transcript.ndjson index be3555213299a..4083e4f61f3f7 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/thread_rollback_after_restart/codex_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/thread_rollback_after_restart/codex_transcript.ndjson @@ -6,13 +6,16 @@ {"type":"emit_inbound","label":"configWarning","frame":{"method":"configWarning","params":{"summary":"Codex could not find bubblewrap on PATH. Install bubblewrap with your OS package manager. See the sandbox prerequisites: https://developers.openai.com/codex/concepts/sandboxing#prerequisites. Codex will use the bundled bubblewrap in the meantime.","details":null},"emittedAtMs":1790404926353}} {"type":"emit_inbound","label":"remoteControl/status/changed","frame":{"method":"remoteControl/status/changed","params":{"status":"disabled","serverName":"replay-host","installationId":"00000000-0000-4000-8000-000000000000","environmentId":null},"emittedAtMs":1790404926353}} {"type":"emit_inbound","label":"thread/start","frame":{"id":2,"result":{"thread":{"id":"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/apps/server","runtimeWorkspaceRoots":["/home/replay-user/t3code/apps/server"]}],"extra":null,"sessionId":"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790404926,"updatedAt":1790404926,"recencyAt":1790404926,"status":{"type":"idle"},"path":"/home/replay-user/tmp/bughunt-codex/codex-home/sessions/2026/09/25/rollout-2026-09-25T23-42-06-01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a.jsonl","cwd":"/home/replay-user/t3code/apps/server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]},"model":"gpt-6-luna","modelProvider":"openai","serviceTier":null,"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/apps/server","runtimeWorkspaceRoots":["/home/replay-user/t3code/apps/server"],"instructionSources":["/home/replay-user/t3code/AGENTS.md"],"approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":{"id":":workspace","extends":null},"reasoningEffort":null,"multiAgentMode":"explicitRequestOnly"}}} -{"type":"expect_outbound","label":"config/read","frame":{"id":3,"method":"config/read","params":{"cwd":"","includeLayers":false}}} -{"type":"emit_inbound","label":"config/read","frame":{"id":3,"result":{"config":{},"origins":{}}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":4,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Respond with exactly: rollback fixture first turn complete","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"auto","threadId":"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} +{"type":"expect_outbound","label":"thread/name/set","frame":{"id":3,"method":"thread/name/set","params":{"name":"Replay fixture: thread_rollback_after_restart","threadId":"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a"}}} +{"type":"emit_inbound","label":"thread/name/set","frame":{"id":3,"result":{}}} +{"type":"emit_inbound","label":"thread/name/updated","frame":{"method":"thread/name/updated","params":{"threadId":"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a","threadName":"Replay fixture: thread_rollback_after_restart"}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":4,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":4,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":5,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Respond with exactly: rollback fixture first turn complete","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"auto","threadId":"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} {"type":"emit_inbound","label":"thread/started","frame":{"method":"thread/started","params":{"thread":{"id":"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/apps/server","runtimeWorkspaceRoots":["/home/replay-user/t3code/apps/server"]}],"extra":null,"sessionId":"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790404926,"updatedAt":1790404926,"recencyAt":1790404926,"status":{"type":"idle"},"path":"/home/replay-user/tmp/bughunt-codex/codex-home/sessions/2026/09/25/rollout-2026-09-25T23-42-06-01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a.jsonl","cwd":"/home/replay-user/t3code/apps/server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]}},"emittedAtMs":1790404926549}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a","name":"codex_apps","status":"starting","error":null,"failureReason":null},"emittedAtMs":1790404926550}} {"type":"emit_inbound","label":"thread/settings/updated","frame":{"method":"thread/settings/updated","params":{"threadId":"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a","threadSettings":{"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/apps/server","approvalPolicy":"never","approvalsReviewer":"user","sandboxPolicy":{"type":"dangerFullAccess"},"activePermissionProfile":null,"model":"gpt-6-luna","modelProvider":"openai","serviceTier":null,"effort":null,"summary":"detailed","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna","reasoning_effort":null,"developer_instructions":null}},"multiAgentMode":"explicitRequestOnly","personality":null}},"emittedAtMs":1790404926569}} -{"type":"emit_inbound","label":"turn/start","frame":{"id":4,"result":{"turn":{"id":"01a0dc73-1c60-70a3-9a3c-d54c0020efa2","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} +{"type":"emit_inbound","label":"turn/start","frame":{"id":5,"result":{"turn":{"id":"01a0dc73-1c60-70a3-9a3c-d54c0020efa2","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a","status":{"type":"active","activeFlags":[]}},"emittedAtMs":1790404926645}} {"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a","turn":{"id":"01a0dc73-1c60-70a3-9a3c-d54c0020efa2","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1790404926,"completedAt":null,"durationMs":null}},"emittedAtMs":1790404926645}} {"type":"emit_inbound","label":"account/updated","frame":{"method":"account/updated","params":{"authMode":"chatgpt","planType":"unknown"},"emittedAtMs":1790404926921}} @@ -30,10 +33,10 @@ {"type":"emit_inbound","label":"thread/tokenUsage/updated","frame":{"method":"thread/tokenUsage/updated","params":{"threadId":"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a","turnId":"01a0dc73-1c60-70a3-9a3c-d54c0020efa2","tokenUsage":{"total":{"totalTokens":19805,"inputTokens":19796,"cachedInputTokens":0,"cacheWriteInputTokens":0,"outputTokens":9,"reasoningOutputTokens":0},"last":{"totalTokens":19805,"inputTokens":19796,"cachedInputTokens":0,"cacheWriteInputTokens":0,"outputTokens":9,"reasoningOutputTokens":0},"modelContextWindow":258400}},"emittedAtMs":1790404930976}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a","status":{"type":"idle"}},"emittedAtMs":1790404931000}} {"type":"emit_inbound","label":"turn/completed","frame":{"method":"turn/completed","params":{"threadId":"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a","turn":{"id":"01a0dc73-1c60-70a3-9a3c-d54c0020efa2","items":[{"type":"agentMessage","id":"msg_0f3ce1c685f16088016ab7694298d087d0a53f8de6070d33ad","text":"rollback fixture first turn complete","phase":"final_answer","memoryCitation":null,"delivery":null,"questions":null}],"itemsView":"summary","status":"completed","error":null,"startedAt":1790404926,"completedAt":1790404930,"durationMs":4426}},"emittedAtMs":1790404931000}} -{"type":"expect_outbound","label":"config/read","frame":{"id":5,"method":"config/read","params":{"cwd":"","includeLayers":false}}} -{"type":"emit_inbound","label":"config/read","frame":{"id":5,"result":{"config":{},"origins":{}}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":6,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Respond with exactly: rollback fixture second turn complete","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"auto","threadId":"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} -{"type":"emit_inbound","label":"turn/start","frame":{"id":6,"result":{"turn":{"id":"01a0dc73-2dc4-7911-a448-c66b9bf3318b","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":6,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":6,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":7,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Respond with exactly: rollback fixture second turn complete","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"auto","threadId":"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} +{"type":"emit_inbound","label":"turn/start","frame":{"id":7,"result":{"turn":{"id":"01a0dc73-2dc4-7911-a448-c66b9bf3318b","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a","status":{"type":"active","activeFlags":[]}},"emittedAtMs":1790404931059}} {"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a","turn":{"id":"01a0dc73-2dc4-7911-a448-c66b9bf3318b","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1790404931,"completedAt":null,"durationMs":null}},"emittedAtMs":1790404931059}} {"type":"emit_inbound","label":"item/started","frame":{"method":"item/started","params":{"item":{"type":"userMessage","id":"01a0dc73-2e86-7131-a632-7a2b7e8186fb","clientId":null,"content":[{"type":"text","text":"Respond with exactly: rollback fixture second turn complete","text_elements":[]}]},"threadId":"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a","turnId":"01a0dc73-2dc4-7911-a448-c66b9bf3318b","startedAtMs":1790404931208},"emittedAtMs":1790404931208}} @@ -73,12 +76,15 @@ {"type":"expect_outbound","label":"thread/resume","frame":{"id":6,"method":"thread/resume","params":{"config":{"tools.update_plan.enabled":true,"mcp_optional_startup_grace_ms":10000,"features.concurrent_reasoning_summaries":true},"cwd":"","excludeTurns":true,"model":"gpt-6-luna","threadId":"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a"}}} {"type":"emit_inbound","label":"thread/reverted","frame":{"method":"thread/reverted","params":{"threadId":"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a"},"emittedAtMs":1790404935694}} {"type":"emit_inbound","label":"thread/resume","frame":{"id":6,"result":{"thread":{"id":"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/apps/server","runtimeWorkspaceRoots":["/home/replay-user/t3code/apps/server"]}],"extra":null,"sessionId":"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a","forkedFromId":null,"parentThreadId":null,"preview":"Respond with exactly: rollback fixture first turn complete","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790404935,"updatedAt":1790404935,"recencyAt":1790404931,"status":{"type":"idle"},"path":"/home/replay-user/tmp/bughunt-codex/codex-home/sessions/2026/09/25/rollout-2026-09-25T23-42-15-01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a_01a0dc73-3f89-7660-9a2a-81865e6273eb.jsonl","cwd":"/home/replay-user/t3code/apps/server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":{"sha":"70629cdddbe2c29749e8dce588b1828580b2777b","branch":"fix/codex-rollback-resume","originUrl":"https://github.com/pingdotgg/t3code.git"},"name":null,"daybreakEnabled":null,"turns":[]},"model":"gpt-6-luna","modelProvider":"openai","serviceTier":"default","disabledPluginIds":[],"cwd":"/home/replay-user/t3code/apps/server","runtimeWorkspaceRoots":["/home/replay-user/t3code/apps/server"],"instructionSources":["/home/replay-user/t3code/AGENTS.md"],"approvalPolicy":"never","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":{"id":":workspace","extends":null},"reasoningEffort":null,"collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna","reasoning_effort":null,"developer_instructions":null}},"multiAgentMode":"explicitRequestOnly","initialTurnsPage":null,"turnsBackwardsCursor":"{\"requestedThreadId\":\"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a\",\"rolloutOrdinal\":1,\"includeAnchor\":true,\"scope\":{\"kind\":\"turns\"}}","itemsBackwardsCursor":"{\"requestedThreadId\":\"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a\",\"rolloutOrdinal\":10,\"includeAnchor\":true,\"scope\":{\"kind\":\"itemsByCreatedAtOrdinal\"}}"}}} -{"type":"expect_outbound","label":"config/read","frame":{"id":7,"method":"config/read","params":{"cwd":"","includeLayers":false}}} -{"type":"emit_inbound","label":"config/read","frame":{"id":7,"result":{"config":{},"origins":{}}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":8,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Repeat the conversation verbatim.","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"auto","threadId":"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} +{"type":"expect_outbound","label":"thread/name/set","frame":{"id":7,"method":"thread/name/set","params":{"name":"Replay fixture: thread_rollback_after_restart","threadId":"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a"}}} +{"type":"emit_inbound","label":"thread/name/set","frame":{"id":7,"result":{}}} +{"type":"emit_inbound","label":"thread/name/updated","frame":{"method":"thread/name/updated","params":{"threadId":"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a","threadName":"Replay fixture: thread_rollback_after_restart"}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":8,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":8,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":9,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Repeat the conversation verbatim.","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"auto","threadId":"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} {"type":"emit_inbound","label":"thread/goal/cleared","frame":{"method":"thread/goal/cleared","params":{"threadId":"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a"},"emittedAtMs":1790404935729}} {"type":"emit_inbound","label":"thread/settings/updated","frame":{"method":"thread/settings/updated","params":{"threadId":"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a","threadSettings":{"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/apps/server","approvalPolicy":"never","approvalsReviewer":"user","sandboxPolicy":{"type":"dangerFullAccess"},"activePermissionProfile":null,"model":"gpt-6-luna","modelProvider":"openai","serviceTier":"default","effort":null,"summary":"detailed","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna","reasoning_effort":null,"developer_instructions":null}},"multiAgentMode":"explicitRequestOnly","personality":null}},"emittedAtMs":1790404935753}} -{"type":"emit_inbound","label":"turn/start","frame":{"id":8,"result":{"turn":{"id":"01a0dc73-4034-7201-88e4-13d0d27303a3","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} +{"type":"emit_inbound","label":"turn/start","frame":{"id":9,"result":{"turn":{"id":"01a0dc73-4034-7201-88e4-13d0d27303a3","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a","status":{"type":"active","activeFlags":[]}},"emittedAtMs":1790404935798}} {"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a","turn":{"id":"01a0dc73-4034-7201-88e4-13d0d27303a3","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1790404935,"completedAt":null,"durationMs":null}},"emittedAtMs":1790404935798}} {"type":"emit_inbound","label":"account/updated","frame":{"method":"account/updated","params":{"authMode":"chatgpt","planType":"unknown"},"emittedAtMs":1790404935820}} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/thread_rollback_to_stopped_turn/codex_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/thread_rollback_to_stopped_turn/codex_transcript.ndjson index b382b070c180e..7868924d82823 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/thread_rollback_to_stopped_turn/codex_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/thread_rollback_to_stopped_turn/codex_transcript.ndjson @@ -6,13 +6,16 @@ {"type":"emit_inbound","label":"configWarning","frame":{"method":"configWarning","params":{"summary":"Codex could not find bubblewrap on PATH. Install bubblewrap with your OS package manager. See the sandbox prerequisites: https://developers.openai.com/codex/concepts/sandboxing#prerequisites. Codex will use the bundled bubblewrap in the meantime.","details":null},"emittedAtMs":1790459891821}} {"type":"emit_inbound","label":"remoteControl/status/changed","frame":{"method":"remoteControl/status/changed","params":{"status":"disabled","serverName":"replay-host","installationId":"00000000-0000-4000-8000-000000000000","environmentId":null},"emittedAtMs":1790459891821}} {"type":"emit_inbound","label":"thread/start","frame":{"id":2,"result":{"thread":{"id":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code","runtimeWorkspaceRoots":["/home/replay-user/t3code"]}],"extra":null,"sessionId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790459892,"updatedAt":1790459892,"recencyAt":1790459892,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/26/rollout-2026-09-26T14-58-12-01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88.jsonl","cwd":"/home/replay-user/t3code","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]},"model":"gpt-6-luna","modelProvider":"openai","serviceTier":null,"disabledPluginIds":[],"cwd":"/home/replay-user/t3code","runtimeWorkspaceRoots":["/home/replay-user/t3code"],"instructionSources":[],"approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":{"id":":workspace","extends":null},"reasoningEffort":null,"multiAgentMode":"explicitRequestOnly"}}} -{"type":"expect_outbound","label":"config/read","frame":{"id":3,"method":"config/read","params":{"cwd":"","includeLayers":false}}} -{"type":"emit_inbound","label":"config/read","frame":{"id":3,"result":{"config":{},"origins":{}}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":4,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Respond with exactly: rollback fixture first turn complete","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"networkAccess":false,"type":"workspaceWrite","writableRoots":[]},"summary":"auto","threadId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} +{"type":"expect_outbound","label":"thread/name/set","frame":{"id":3,"method":"thread/name/set","params":{"name":"Replay fixture: thread_rollback_to_stopped_turn","threadId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88"}}} +{"type":"emit_inbound","label":"thread/name/set","frame":{"id":3,"result":{}}} +{"type":"emit_inbound","label":"thread/name/updated","frame":{"method":"thread/name/updated","params":{"threadId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","threadName":"Replay fixture: thread_rollback_to_stopped_turn"}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":4,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":4,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":5,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Respond with exactly: rollback fixture first turn complete","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"networkAccess":false,"type":"workspaceWrite","writableRoots":[]},"summary":"auto","threadId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} {"type":"emit_inbound","label":"thread/started","frame":{"method":"thread/started","params":{"thread":{"id":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code","runtimeWorkspaceRoots":["/home/replay-user/t3code"]}],"extra":null,"sessionId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790459892,"updatedAt":1790459892,"recencyAt":1790459892,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/26/rollout-2026-09-26T14-58-12-01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88.jsonl","cwd":"/home/replay-user/t3code","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]}},"emittedAtMs":1790459892845}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","name":"codex_apps","status":"starting","error":null,"failureReason":null},"emittedAtMs":1790459892846}} {"type":"emit_inbound","label":"thread/settings/updated","frame":{"method":"thread/settings/updated","params":{"threadId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","threadSettings":{"disabledPluginIds":[],"cwd":"/home/replay-user/t3code","approvalPolicy":"never","approvalsReviewer":"user","sandboxPolicy":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":null,"model":"gpt-6-luna","modelProvider":"openai","serviceTier":null,"effort":null,"summary":"detailed","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna","reasoning_effort":null,"developer_instructions":null}},"multiAgentMode":"explicitRequestOnly","personality":null}},"emittedAtMs":1790459892862}} -{"type":"emit_inbound","label":"turn/start","frame":{"id":4,"result":{"turn":{"id":"01a0dfb9-d479-70c0-9d88-912b52f7f613","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} +{"type":"emit_inbound","label":"turn/start","frame":{"id":5,"result":{"turn":{"id":"01a0dfb9-d479-70c0-9d88-912b52f7f613","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","status":{"type":"active","activeFlags":[]}},"emittedAtMs":1790459892915}} {"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","turn":{"id":"01a0dfb9-d479-70c0-9d88-912b52f7f613","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1790459892,"completedAt":null,"durationMs":null}},"emittedAtMs":1790459892915}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","name":"codex_apps","status":"failed","error":"MCP client for `codex_apps` failed to start: MCP startup failed: handshaking with MCP server failed: Send message error Transport [codex_rmcp_client::event_notification_transport::EventNotificationTransport>>] error: unexpected server response: HTTP 401: {\n \"error\": {\n \"message\": \"Encountered invalidated oauth token for user, failing request\",\n \"type\": null,\n \"code\": \"token_revoked\",\n \"param\": null\n },\n \"status\": 401\n}, when send initialize request: Send message error Transport [codex_rmcp_client::event_notification_transport::EventNotificationTransport>>] error: unexpected server response: HTTP 401: {\n \"error\": {\n \"message\": \"Encountered invalidated oauth token for user, failing request\",\n \"type\": null,\n \"code\": \"token_revoked\",\n \"param\": null\n },\n \"status\": 401\n}, when send initialize request","failureReason":null},"emittedAtMs":1790459893144}} @@ -28,10 +31,10 @@ {"type":"emit_inbound","label":"thread/tokenUsage/updated","frame":{"method":"thread/tokenUsage/updated","params":{"threadId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","turnId":"01a0dfb9-d479-70c0-9d88-912b52f7f613","tokenUsage":{"total":{"totalTokens":15291,"inputTokens":15282,"cachedInputTokens":0,"cacheWriteInputTokens":0,"outputTokens":9,"reasoningOutputTokens":0},"last":{"totalTokens":15291,"inputTokens":15282,"cachedInputTokens":0,"cacheWriteInputTokens":0,"outputTokens":9,"reasoningOutputTokens":0},"modelContextWindow":258400}},"emittedAtMs":1790459897074}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","status":{"type":"idle"}},"emittedAtMs":1790459897082}} {"type":"emit_inbound","label":"turn/completed","frame":{"method":"turn/completed","params":{"threadId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","turn":{"id":"01a0dfb9-d479-70c0-9d88-912b52f7f613","items":[{"type":"agentMessage","id":"msg_0508263b0487774d016ab83ff8973c87d0afab5ac113234803","text":"rollback fixture first turn complete","phase":"final_answer","memoryCitation":null,"delivery":null,"questions":null}],"itemsView":"summary","status":"completed","error":null,"startedAt":1790459892,"completedAt":1790459897,"durationMs":4216}},"emittedAtMs":1790459897082}} -{"type":"expect_outbound","label":"config/read","frame":{"id":5,"method":"config/read","params":{"cwd":"","includeLayers":false}}} -{"type":"emit_inbound","label":"config/read","frame":{"id":5,"result":{"config":{},"origins":{}}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":6,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Run this exact local command: `node -e \"console.log('interrupt fixture tool started'); setTimeout(() => {}, 30000)\"`. Do not answer until it completes, then respond exactly: interrupt fixture should not finish naturally.","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"networkAccess":false,"type":"workspaceWrite","writableRoots":[]},"summary":"auto","threadId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} -{"type":"emit_inbound","label":"turn/start","frame":{"id":6,"result":{"turn":{"id":"01a0dfb9-e509-7001-ba72-fe324f527fb9","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":6,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":6,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":7,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Run this exact local command: `node -e \"console.log('interrupt fixture tool started'); setTimeout(() => {}, 30000)\"`. Do not answer until it completes, then respond exactly: interrupt fixture should not finish naturally.","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"networkAccess":false,"type":"workspaceWrite","writableRoots":[]},"summary":"auto","threadId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} +{"type":"emit_inbound","label":"turn/start","frame":{"id":7,"result":{"turn":{"id":"01a0dfb9-e509-7001-ba72-fe324f527fb9","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","status":{"type":"active","activeFlags":[]}},"emittedAtMs":1790459897121}} {"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","turn":{"id":"01a0dfb9-e509-7001-ba72-fe324f527fb9","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1790459897,"completedAt":null,"durationMs":null}},"emittedAtMs":1790459897121}} {"type":"emit_inbound","label":"item/started","frame":{"method":"item/started","params":{"item":{"type":"userMessage","id":"01a0dfb9-e8f3-7011-a214-7479457edb56","clientId":null,"content":[{"type":"text","text":"Run this exact local command: `node -e \"console.log('interrupt fixture tool started'); setTimeout(() => {}, 30000)\"`. Do not answer until it completes, then respond exactly: interrupt fixture should not finish naturally.","text_elements":[]}]},"threadId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","turnId":"01a0dfb9-e509-7001-ba72-fe324f527fb9","startedAtMs":1790459898101},"emittedAtMs":1790459898101}} @@ -58,19 +61,19 @@ {"type":"emit_inbound","label":"item/agentMessage/delta","frame":{"method":"item/agentMessage/delta","params":{"threadId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","turnId":"01a0dfb9-e509-7001-ba72-fe324f527fb9","itemId":"msg_0508263b0487774d016ab83ffcc71887d0874b12a3fb65dd41","delta":"."},"emittedAtMs":1790459902812}} {"type":"emit_inbound","label":"item/completed","frame":{"method":"item/completed","params":{"item":{"type":"agentMessage","id":"msg_0508263b0487774d016ab83ffcc71887d0874b12a3fb65dd41","text":"I’ll run the command exactly as given and wait for it to exit.","phase":"commentary","memoryCitation":null,"delivery":null,"questions":null},"threadId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","turnId":"01a0dfb9-e509-7001-ba72-fe324f527fb9","completedAtMs":1790459903007},"emittedAtMs":1790459903009}} {"type":"emit_inbound","label":"item/started","frame":{"method":"item/started","params":{"item":{"type":"commandExecution","id":"exec-6964412e-1d91-47b5-8a37-7a669b30c03e","pluginId":null,"scriptPath":null,"command":"/bin/bash -lc \"node -e \\\"console.log('interrupt fixture tool started'); setTimeout(() => {}, 30000)\\\"\"","cwd":"/home/replay-user/t3code","processId":"26675","source":"unifiedExecStartup","status":"inProgress","commandActions":[{"type":"unknown","command":"node -e \"console.log('interrupt fixture tool started'); setTimeout(() => {}, 30000)\""}],"aggregatedOutput":null,"exitCode":null,"durationMs":null},"threadId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","turnId":"01a0dfb9-e509-7001-ba72-fe324f527fb9","startedAtMs":1790459903878},"emittedAtMs":1790459903884}} -{"type":"expect_outbound","label":"turn/interrupt","frame":{"id":7,"method":"turn/interrupt","params":{"threadId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","turnId":"01a0dfb9-e509-7001-ba72-fe324f527fb9"}}} +{"type":"expect_outbound","label":"turn/interrupt","frame":{"id":8,"method":"turn/interrupt","params":{"threadId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","turnId":"01a0dfb9-e509-7001-ba72-fe324f527fb9"}}} {"type":"emit_inbound","label":"thread/tokenUsage/updated","frame":{"method":"thread/tokenUsage/updated","params":{"threadId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","turnId":"01a0dfb9-e509-7001-ba72-fe324f527fb9","tokenUsage":{"total":{"totalTokens":30736,"inputTokens":30626,"cachedInputTokens":15104,"cacheWriteInputTokens":0,"outputTokens":110,"reasoningOutputTokens":15},"last":{"totalTokens":15445,"inputTokens":15344,"cachedInputTokens":15104,"cacheWriteInputTokens":0,"outputTokens":101,"reasoningOutputTokens":15},"modelContextWindow":258400}},"emittedAtMs":1790459903893}} -{"type":"emit_inbound","label":"turn/interrupt","frame":{"id":7,"result":{}}} -{"type":"expect_outbound","label":"thread/backgroundTerminals/terminate","frame":{"id":8,"method":"thread/backgroundTerminals/terminate","params":{"threadId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","processId":"26675"}}} +{"type":"emit_inbound","label":"turn/interrupt","frame":{"id":8,"result":{}}} +{"type":"expect_outbound","label":"thread/backgroundTerminals/terminate","frame":{"id":9,"method":"thread/backgroundTerminals/terminate","params":{"threadId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","processId":"26675"}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","status":{"type":"idle"}},"emittedAtMs":1790459903899}} {"type":"emit_inbound","label":"turn/completed","frame":{"method":"turn/completed","params":{"threadId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","turn":{"id":"01a0dfb9-e509-7001-ba72-fe324f527fb9","items":[],"itemsView":"notLoaded","status":"interrupted","error":null,"startedAt":1790459897,"completedAt":1790459903,"durationMs":6789}},"emittedAtMs":1790459903899}} -{"type":"emit_inbound","label":"thread/backgroundTerminals/terminate","frame":{"id":8,"result":{"terminated":true}}} -{"type":"expect_outbound","label":"config/read","frame":{"id":9,"method":"config/read","params":{"cwd":"","includeLayers":false}}} -{"type":"emit_inbound","label":"config/read","frame":{"id":9,"result":{"config":{},"origins":{}}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":10,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Respond with exactly: rollback fixture second turn complete","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"networkAccess":false,"type":"workspaceWrite","writableRoots":[]},"summary":"auto","threadId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} +{"type":"emit_inbound","label":"thread/backgroundTerminals/terminate","frame":{"id":9,"result":{"terminated":true}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":10,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":10,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":11,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Respond with exactly: rollback fixture second turn complete","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"networkAccess":false,"type":"workspaceWrite","writableRoots":[]},"summary":"auto","threadId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","name":"codex_apps","status":"starting","error":null,"failureReason":null},"emittedAtMs":1790459903907}} {"type":"emit_inbound","label":"item/completed","frame":{"method":"item/completed","params":{"item":{"type":"commandExecution","id":"exec-6964412e-1d91-47b5-8a37-7a669b30c03e","pluginId":null,"scriptPath":null,"command":"/bin/bash -lc \"node -e \\\"console.log('interrupt fixture tool started'); setTimeout(() => {}, 30000)\\\"\"","cwd":"/home/replay-user/t3code","processId":"26675","source":"unifiedExecStartup","status":"failed","commandActions":[{"type":"unknown","command":"node -e \"console.log('interrupt fixture tool started'); setTimeout(() => {}, 30000)\""}],"aggregatedOutput":null,"exitCode":-1,"durationMs":22},"threadId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","turnId":"01a0dfb9-e509-7001-ba72-fe324f527fb9","completedAtMs":1790459903901},"emittedAtMs":1790459903912}} -{"type":"emit_inbound","label":"turn/start","frame":{"id":10,"result":{"turn":{"id":"01a0dfb9-ff9f-7902-a370-d05cc4ec5959","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} +{"type":"emit_inbound","label":"turn/start","frame":{"id":11,"result":{"turn":{"id":"01a0dfb9-ff9f-7902-a370-d05cc4ec5959","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","status":{"type":"active","activeFlags":[]}},"emittedAtMs":1790459903925}} {"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","turn":{"id":"01a0dfb9-ff9f-7902-a370-d05cc4ec5959","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1790459903,"completedAt":null,"durationMs":null}},"emittedAtMs":1790459903925}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","name":"codex_apps","status":"failed","error":"MCP client for `codex_apps` failed to start: MCP startup failed: handshaking with MCP server failed: Send message error Transport [codex_rmcp_client::event_notification_transport::EventNotificationTransport>>] error: unexpected server response: HTTP 401: {\n \"error\": {\n \"message\": \"Encountered invalidated oauth token for user, failing request\",\n \"type\": null,\n \"code\": \"token_revoked\",\n \"param\": null\n },\n \"status\": 401\n}, when send initialize request: Send message error Transport [codex_rmcp_client::event_notification_transport::EventNotificationTransport>>] error: unexpected server response: HTTP 401: {\n \"error\": {\n \"message\": \"Encountered invalidated oauth token for user, failing request\",\n \"type\": null,\n \"code\": \"token_revoked\",\n \"param\": null\n },\n \"status\": 401\n}, when send initialize request","failureReason":null},"emittedAtMs":1790459904186}} @@ -86,20 +89,20 @@ {"type":"emit_inbound","label":"thread/tokenUsage/updated","frame":{"method":"thread/tokenUsage/updated","params":{"threadId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","turnId":"01a0dfb9-ff9f-7902-a370-d05cc4ec5959","tokenUsage":{"total":{"totalTokens":46272,"inputTokens":46153,"cachedInputTokens":30208,"cacheWriteInputTokens":0,"outputTokens":119,"reasoningOutputTokens":15},"last":{"totalTokens":15536,"inputTokens":15527,"cachedInputTokens":15104,"cacheWriteInputTokens":0,"outputTokens":9,"reasoningOutputTokens":0},"modelContextWindow":258400}},"emittedAtMs":1790459906339}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","status":{"type":"idle"}},"emittedAtMs":1790459906344}} {"type":"emit_inbound","label":"turn/completed","frame":{"method":"turn/completed","params":{"threadId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","turn":{"id":"01a0dfb9-ff9f-7902-a370-d05cc4ec5959","items":[{"type":"agentMessage","id":"msg_0508263b0487774d016ab840020e1087d08e559660413ebcd6","text":"rollback fixture second turn complete","phase":"final_answer","memoryCitation":null,"delivery":null,"questions":null}],"itemsView":"summary","status":"completed","error":null,"startedAt":1790459903,"completedAt":1790459906,"durationMs":2423}},"emittedAtMs":1790459906344}} -{"type":"expect_outbound","label":"thread/read","frame":{"id":11,"method":"thread/read","params":{"includeTurns":false,"threadId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88"}}} -{"type":"emit_inbound","label":"thread/read","frame":{"id":11,"result":{"thread":{"id":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code","runtimeWorkspaceRoots":["/home/replay-user/t3code"]}],"extra":null,"sessionId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","forkedFromId":null,"parentThreadId":null,"preview":"Respond with exactly: rollback fixture first turn complete","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790459892,"updatedAt":1790459906,"recencyAt":1790459903,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/26/rollout-2026-09-26T14-58-12-01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88.jsonl","cwd":"/home/replay-user/t3code","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":{"sha":"147b1509eac4291b323371299d0925a44035680c","branch":"master","originUrl":null},"name":null,"daybreakEnabled":null,"turns":[]}}}} -{"type":"expect_outbound","label":"thread/turns/list","frame":{"id":12,"method":"thread/turns/list","params":{"cursor":null,"itemsView":"summary","limit":1,"sortDirection":"desc","threadId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88"}}} -{"type":"emit_inbound","label":"thread/turns/list","frame":{"id":12,"result":{"data":[{"id":"01a0dfb9-ff9f-7902-a370-d05cc4ec5959","items":[{"type":"userMessage","id":"01a0dfba-0390-7aa0-a945-e25ca01302e2","clientId":null,"content":[{"type":"text","text":"Respond with exactly: rollback fixture second turn complete","text_elements":[]}]},{"type":"agentMessage","id":"msg_0508263b0487774d016ab840020e1087d08e559660413ebcd6","text":"rollback fixture second turn complete","phase":"final_answer","memoryCitation":null,"delivery":null,"questions":null}],"itemsView":"summary","status":"completed","error":null,"startedAt":1790459903,"completedAt":1790459906,"durationMs":2423}],"nextCursor":"{\"requestedThreadId\":\"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88\",\"rolloutOrdinal\":32,\"includeAnchor\":false,\"scope\":{\"kind\":\"turns\"}}","backwardsCursor":"{\"requestedThreadId\":\"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88\",\"rolloutOrdinal\":32,\"includeAnchor\":true,\"scope\":{\"kind\":\"turns\"}}"}}} -{"type":"expect_outbound","label":"thread/revert","frame":{"id":13,"method":"thread/revert","params":{"beforeTurnId":"01a0dfb9-ff9f-7902-a370-d05cc4ec5959","threadId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88"}}} +{"type":"expect_outbound","label":"thread/read","frame":{"id":12,"method":"thread/read","params":{"includeTurns":false,"threadId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88"}}} +{"type":"emit_inbound","label":"thread/read","frame":{"id":12,"result":{"thread":{"id":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code","runtimeWorkspaceRoots":["/home/replay-user/t3code"]}],"extra":null,"sessionId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","forkedFromId":null,"parentThreadId":null,"preview":"Respond with exactly: rollback fixture first turn complete","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790459892,"updatedAt":1790459906,"recencyAt":1790459903,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/26/rollout-2026-09-26T14-58-12-01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88.jsonl","cwd":"/home/replay-user/t3code","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":{"sha":"147b1509eac4291b323371299d0925a44035680c","branch":"master","originUrl":null},"name":null,"daybreakEnabled":null,"turns":[]}}}} +{"type":"expect_outbound","label":"thread/turns/list","frame":{"id":13,"method":"thread/turns/list","params":{"cursor":null,"itemsView":"summary","limit":1,"sortDirection":"desc","threadId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88"}}} +{"type":"emit_inbound","label":"thread/turns/list","frame":{"id":13,"result":{"data":[{"id":"01a0dfb9-ff9f-7902-a370-d05cc4ec5959","items":[{"type":"userMessage","id":"01a0dfba-0390-7aa0-a945-e25ca01302e2","clientId":null,"content":[{"type":"text","text":"Respond with exactly: rollback fixture second turn complete","text_elements":[]}]},{"type":"agentMessage","id":"msg_0508263b0487774d016ab840020e1087d08e559660413ebcd6","text":"rollback fixture second turn complete","phase":"final_answer","memoryCitation":null,"delivery":null,"questions":null}],"itemsView":"summary","status":"completed","error":null,"startedAt":1790459903,"completedAt":1790459906,"durationMs":2423}],"nextCursor":"{\"requestedThreadId\":\"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88\",\"rolloutOrdinal\":32,\"includeAnchor\":false,\"scope\":{\"kind\":\"turns\"}}","backwardsCursor":"{\"requestedThreadId\":\"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88\",\"rolloutOrdinal\":32,\"includeAnchor\":true,\"scope\":{\"kind\":\"turns\"}}"}}} +{"type":"expect_outbound","label":"thread/revert","frame":{"id":14,"method":"thread/revert","params":{"beforeTurnId":"01a0dfb9-ff9f-7902-a370-d05cc4ec5959","threadId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88"}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","status":{"type":"notLoaded"}},"emittedAtMs":1790459906373}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","name":"codex_apps","status":"starting","error":null,"failureReason":null},"emittedAtMs":1790459906471}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","status":{"type":"idle"}},"emittedAtMs":1790459906478}} -{"type":"emit_inbound","label":"thread/revert","frame":{"id":13,"result":{"thread":{"id":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code","runtimeWorkspaceRoots":["/home/replay-user/t3code"]}],"extra":null,"sessionId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","forkedFromId":null,"parentThreadId":null,"preview":"Respond with exactly: rollback fixture first turn complete","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790459906,"updatedAt":1790459906,"recencyAt":1790459903,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/26/rollout-2026-09-26T14-58-26-01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88_01a0dfba-094c-77d1-8e0b-8bf690a73635.jsonl","cwd":"/home/replay-user/t3code","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":{"sha":"147b1509eac4291b323371299d0925a44035680c","branch":"master","originUrl":null},"name":null,"daybreakEnabled":null,"turns":[]},"turnsBackwardsCursor":"{\"requestedThreadId\":\"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88\",\"rolloutOrdinal\":16,\"includeAnchor\":true,\"scope\":{\"kind\":\"turns\"}}","itemsBackwardsCursor":"{\"requestedThreadId\":\"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88\",\"rolloutOrdinal\":30,\"includeAnchor\":true,\"scope\":{\"kind\":\"itemsByCreatedAtOrdinal\"}}"}}} -{"type":"expect_outbound","label":"config/read","frame":{"id":14,"method":"config/read","params":{"cwd":"","includeLayers":false}}} -{"type":"emit_inbound","label":"config/read","frame":{"id":14,"result":{"config":{},"origins":{}}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":15,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Repeat the conversation verbatim.","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"networkAccess":false,"type":"workspaceWrite","writableRoots":[]},"summary":"auto","threadId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} +{"type":"emit_inbound","label":"thread/revert","frame":{"id":14,"result":{"thread":{"id":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code","runtimeWorkspaceRoots":["/home/replay-user/t3code"]}],"extra":null,"sessionId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","forkedFromId":null,"parentThreadId":null,"preview":"Respond with exactly: rollback fixture first turn complete","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790459906,"updatedAt":1790459906,"recencyAt":1790459903,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/26/rollout-2026-09-26T14-58-26-01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88_01a0dfba-094c-77d1-8e0b-8bf690a73635.jsonl","cwd":"/home/replay-user/t3code","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":{"sha":"147b1509eac4291b323371299d0925a44035680c","branch":"master","originUrl":null},"name":null,"daybreakEnabled":null,"turns":[]},"turnsBackwardsCursor":"{\"requestedThreadId\":\"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88\",\"rolloutOrdinal\":16,\"includeAnchor\":true,\"scope\":{\"kind\":\"turns\"}}","itemsBackwardsCursor":"{\"requestedThreadId\":\"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88\",\"rolloutOrdinal\":30,\"includeAnchor\":true,\"scope\":{\"kind\":\"itemsByCreatedAtOrdinal\"}}"}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":15,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":15,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":16,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Repeat the conversation verbatim.","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"networkAccess":false,"type":"workspaceWrite","writableRoots":[]},"summary":"auto","threadId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} {"type":"emit_inbound","label":"thread/reverted","frame":{"method":"thread/reverted","params":{"threadId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88"},"emittedAtMs":1790459906490}} -{"type":"emit_inbound","label":"turn/start","frame":{"id":15,"result":{"turn":{"id":"01a0dfba-09be-7112-8c42-4a6a8d1fe1d6","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} +{"type":"emit_inbound","label":"turn/start","frame":{"id":16,"result":{"turn":{"id":"01a0dfba-09be-7112-8c42-4a6a8d1fe1d6","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","status":{"type":"active","activeFlags":[]}},"emittedAtMs":1790459906518}} {"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","turn":{"id":"01a0dfba-09be-7112-8c42-4a6a8d1fe1d6","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1790459906,"completedAt":null,"durationMs":null}},"emittedAtMs":1790459906518}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","name":"codex_apps","status":"failed","error":"MCP client for `codex_apps` failed to start: MCP startup failed: handshaking with MCP server failed: Send message error Transport [codex_rmcp_client::event_notification_transport::EventNotificationTransport>>] error: unexpected server response: HTTP 401: {\n \"error\": {\n \"message\": \"Encountered invalidated oauth token for user, failing request\",\n \"type\": null,\n \"code\": \"token_revoked\",\n \"param\": null\n },\n \"status\": 401\n}, when send initialize request: Send message error Transport [codex_rmcp_client::event_notification_transport::EventNotificationTransport>>] error: unexpected server response: HTTP 401: {\n \"error\": {\n \"message\": \"Encountered invalidated oauth token for user, failing request\",\n \"type\": null,\n \"code\": \"token_revoked\",\n \"param\": null\n },\n \"status\": 401\n}, when send initialize request","failureReason":null},"emittedAtMs":1790459906779}} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/todo_list/codex_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/todo_list/codex_transcript.ndjson index ce114ac234a55..a7efceb7e8ecd 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/todo_list/codex_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/todo_list/codex_transcript.ndjson @@ -7,14 +7,17 @@ {"type":"emit_inbound","label":"remoteControl/status/changed","frame":{"method":"remoteControl/status/changed","params":{"status":"disabled","serverName":"replay-host","installationId":"00000000-0000-4000-8000-000000000000","environmentId":null},"emittedAtMs":1790306244669}} {"type":"emit_inbound","label":"account/updated","frame":{"method":"account/updated","params":{"authMode":"chatgpt","planType":"unknown"},"emittedAtMs":1790306245652}} {"type":"emit_inbound","label":"thread/start","frame":{"id":2,"result":{"thread":{"id":"01a0d691-5ba5-77b1-bf0d-1bf7be8e9abe","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d691-5ba5-77b1-bf0d-1bf7be8e9abe","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790306245,"updatedAt":1790306245,"recencyAt":1790306245,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T20-17-25-01a0d691-5ba5-77b1-bf0d-1bf7be8e9abe.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]},"model":"gpt-6-luna","modelProvider":"openai","serviceTier":null,"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"],"instructionSources":["/home/replay-user/.codex/AGENTS.md","/home/replay-user/t3code/AGENTS.md"],"approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":{"id":":workspace","extends":null},"reasoningEffort":null,"multiAgentMode":"explicitRequestOnly"}}} -{"type":"expect_outbound","label":"config/read","frame":{"id":3,"method":"config/read","params":{"cwd":"","includeLayers":false}}} -{"type":"emit_inbound","label":"config/read","frame":{"id":3,"result":{"config":{},"origins":{}}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":4,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Use the update_plan tool to track exactly three steps: inspect package.json, inspect tsconfig.json, report completion. Then read package.json and tsconfig.json, and answer exactly: todo list fixture complete","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"networkAccess":false,"type":"readOnly"},"summary":"auto","threadId":"01a0d691-5ba5-77b1-bf0d-1bf7be8e9abe","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} +{"type":"expect_outbound","label":"thread/name/set","frame":{"id":3,"method":"thread/name/set","params":{"name":"Replay fixture: todo_list","threadId":"01a0d691-5ba5-77b1-bf0d-1bf7be8e9abe"}}} +{"type":"emit_inbound","label":"thread/name/set","frame":{"id":3,"result":{}}} +{"type":"emit_inbound","label":"thread/name/updated","frame":{"method":"thread/name/updated","params":{"threadId":"01a0d691-5ba5-77b1-bf0d-1bf7be8e9abe","threadName":"Replay fixture: todo_list"}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":4,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":4,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":5,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Use the update_plan tool to track exactly three steps: inspect package.json, inspect tsconfig.json, report completion. Then read package.json and tsconfig.json, and answer exactly: todo list fixture complete","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"networkAccess":false,"type":"readOnly"},"summary":"auto","threadId":"01a0d691-5ba5-77b1-bf0d-1bf7be8e9abe","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} {"type":"emit_inbound","label":"thread/started","frame":{"method":"thread/started","params":{"thread":{"id":"01a0d691-5ba5-77b1-bf0d-1bf7be8e9abe","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d691-5ba5-77b1-bf0d-1bf7be8e9abe","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790306245,"updatedAt":1790306245,"recencyAt":1790306245,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T20-17-25-01a0d691-5ba5-77b1-bf0d-1bf7be8e9abe.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]}},"emittedAtMs":1790306245772}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0d691-5ba5-77b1-bf0d-1bf7be8e9abe","name":"codex_apps","status":"starting","error":null,"failureReason":null},"emittedAtMs":1790306245772}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0d691-5ba5-77b1-bf0d-1bf7be8e9abe","name":"xcodebuildmcp","status":"starting","error":null,"failureReason":null},"emittedAtMs":1790306245772}} {"type":"emit_inbound","label":"thread/settings/updated","frame":{"method":"thread/settings/updated","params":{"threadId":"01a0d691-5ba5-77b1-bf0d-1bf7be8e9abe","threadSettings":{"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","approvalPolicy":"never","approvalsReviewer":"user","sandboxPolicy":{"type":"readOnly","networkAccess":false},"activePermissionProfile":null,"model":"gpt-6-luna","modelProvider":"openai","serviceTier":null,"effort":null,"summary":"detailed","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna","reasoning_effort":null,"developer_instructions":null}},"multiAgentMode":"explicitRequestOnly","personality":null}},"emittedAtMs":1790306245794}} -{"type":"emit_inbound","label":"turn/start","frame":{"id":4,"result":{"turn":{"id":"01a0d691-5c9c-7873-a191-5a599fd58099","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} +{"type":"emit_inbound","label":"turn/start","frame":{"id":5,"result":{"turn":{"id":"01a0d691-5c9c-7873-a191-5a599fd58099","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d691-5ba5-77b1-bf0d-1bf7be8e9abe","status":{"type":"active","activeFlags":[]}},"emittedAtMs":1790306245845}} {"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"01a0d691-5ba5-77b1-bf0d-1bf7be8e9abe","turn":{"id":"01a0d691-5c9c-7873-a191-5a599fd58099","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1790306245,"completedAt":null,"durationMs":null}},"emittedAtMs":1790306245845}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0d691-5ba5-77b1-bf0d-1bf7be8e9abe","name":"codex_apps","status":"ready","error":null,"failureReason":null},"emittedAtMs":1790306246472}} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/tool_call_read_only_on_request/codex_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/tool_call_read_only_on_request/codex_transcript.ndjson index c186020e12395..2fc49ff87b092 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/tool_call_read_only_on_request/codex_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/tool_call_read_only_on_request/codex_transcript.ndjson @@ -6,13 +6,16 @@ {"type":"emit_inbound","label":"configWarning","frame":{"method":"configWarning","params":{"summary":"Codex could not find bubblewrap on PATH. Install bubblewrap with your OS package manager. See the sandbox prerequisites: https://developers.openai.com/codex/concepts/sandboxing#prerequisites. Codex will use the bundled bubblewrap in the meantime.","details":null},"emittedAtMs":1790296989543}} {"type":"emit_inbound","label":"remoteControl/status/changed","frame":{"method":"remoteControl/status/changed","params":{"status":"disabled","serverName":"replay-host","installationId":"00000000-0000-4000-8000-000000000000","environmentId":null},"emittedAtMs":1790296989543}} {"type":"emit_inbound","label":"thread/start","frame":{"id":2,"result":{"thread":{"id":"01a0d604-1f8d-7522-8fe1-371c6626896e","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d604-1f8d-7522-8fe1-371c6626896e","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-sol","reasoningEffort":null,"createdAt":1790296989,"updatedAt":1790296989,"recencyAt":1790296989,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-43-09-01a0d604-1f8d-7522-8fe1-371c6626896e.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]},"model":"gpt-6-sol","modelProvider":"openai","serviceTier":null,"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"],"instructionSources":["/home/replay-user/.codex/AGENTS.md","/home/replay-user/t3code/AGENTS.md"],"approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":{"id":":workspace","extends":null},"reasoningEffort":null,"multiAgentMode":"explicitRequestOnly"}}} -{"type":"expect_outbound","label":"config/read","frame":{"id":3,"method":"config/read","params":{"cwd":"","includeLayers":false}}} -{"type":"emit_inbound","label":"config/read","frame":{"id":3,"result":{"config":{},"origins":{}}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":4,"method":"turn/start","params":{"approvalPolicy":"on-request","approvalsReviewer":"user","cwd":"","input":[{"text":"Create or overwrite .codex-probe-write-action.txt with exactly this text: codex app-server approval fixture. Use a local shell command or file edit only, then briefly report what happened. Do not read package metadata, use GitHub, use web, or use MCP.","type":"text"}],"model":"gpt-6-sol","sandboxPolicy":{"networkAccess":false,"type":"readOnly"},"summary":"auto","threadId":"01a0d604-1f8d-7522-8fe1-371c6626896e","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-sol"}}}}} +{"type":"expect_outbound","label":"thread/name/set","frame":{"id":3,"method":"thread/name/set","params":{"name":"Replay fixture: tool_call_read_only_on_request","threadId":"01a0d604-1f8d-7522-8fe1-371c6626896e"}}} +{"type":"emit_inbound","label":"thread/name/set","frame":{"id":3,"result":{}}} +{"type":"emit_inbound","label":"thread/name/updated","frame":{"method":"thread/name/updated","params":{"threadId":"01a0d604-1f8d-7522-8fe1-371c6626896e","threadName":"Replay fixture: tool_call_read_only_on_request"}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":4,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":4,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":5,"method":"turn/start","params":{"approvalPolicy":"on-request","approvalsReviewer":"user","cwd":"","input":[{"text":"Create or overwrite .codex-probe-write-action.txt with exactly this text: codex app-server approval fixture. Use a local shell command or file edit only, then briefly report what happened. Do not read package metadata, use GitHub, use web, or use MCP.","type":"text"}],"model":"gpt-6-sol","sandboxPolicy":{"networkAccess":false,"type":"readOnly"},"summary":"auto","threadId":"01a0d604-1f8d-7522-8fe1-371c6626896e","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-sol"}}}}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0d604-1f8d-7522-8fe1-371c6626896e","name":"codex_apps","status":"starting","error":null,"failureReason":null},"emittedAtMs":1790296989839}} {"type":"emit_inbound","label":"thread/started","frame":{"method":"thread/started","params":{"thread":{"id":"01a0d604-1f8d-7522-8fe1-371c6626896e","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d604-1f8d-7522-8fe1-371c6626896e","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-sol","reasoningEffort":null,"createdAt":1790296989,"updatedAt":1790296989,"recencyAt":1790296989,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-43-09-01a0d604-1f8d-7522-8fe1-371c6626896e.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]}},"emittedAtMs":1790296989839}} {"type":"emit_inbound","label":"thread/settings/updated","frame":{"method":"thread/settings/updated","params":{"threadId":"01a0d604-1f8d-7522-8fe1-371c6626896e","threadSettings":{"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","approvalPolicy":"on-request","approvalsReviewer":"user","sandboxPolicy":{"type":"readOnly","networkAccess":false},"activePermissionProfile":null,"model":"gpt-6-sol","modelProvider":"openai","serviceTier":null,"effort":null,"summary":"detailed","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-sol","reasoning_effort":null,"developer_instructions":null}},"multiAgentMode":"explicitRequestOnly","personality":null}},"emittedAtMs":1790296989848}} -{"type":"emit_inbound","label":"turn/start","frame":{"id":4,"result":{"turn":{"id":"01a0d604-2095-7fb0-a7e6-3f63d1949bbe","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} +{"type":"emit_inbound","label":"turn/start","frame":{"id":5,"result":{"turn":{"id":"01a0d604-2095-7fb0-a7e6-3f63d1949bbe","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d604-1f8d-7522-8fe1-371c6626896e","status":{"type":"active","activeFlags":[]}},"emittedAtMs":1790296989915}} {"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"01a0d604-1f8d-7522-8fe1-371c6626896e","turn":{"id":"01a0d604-2095-7fb0-a7e6-3f63d1949bbe","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1790296989,"completedAt":null,"durationMs":null}},"emittedAtMs":1790296989915}} {"type":"emit_inbound","label":"account/updated","frame":{"method":"account/updated","params":{"authMode":"chatgpt","planType":"unknown"},"emittedAtMs":1790296990273}} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/tool_call_restricted_granular/codex_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/tool_call_restricted_granular/codex_transcript.ndjson index 0f282b80e8b00..a15f5dd2b1d6e 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/tool_call_restricted_granular/codex_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/tool_call_restricted_granular/codex_transcript.ndjson @@ -6,13 +6,16 @@ {"type":"emit_inbound","label":"configWarning","frame":{"method":"configWarning","params":{"summary":"Codex could not find bubblewrap on PATH. Install bubblewrap with your OS package manager. See the sandbox prerequisites: https://developers.openai.com/codex/concepts/sandboxing#prerequisites. Codex will use the bundled bubblewrap in the meantime.","details":null},"emittedAtMs":1790297006729}} {"type":"emit_inbound","label":"remoteControl/status/changed","frame":{"method":"remoteControl/status/changed","params":{"status":"disabled","serverName":"replay-host","installationId":"00000000-0000-4000-8000-000000000000","environmentId":null},"emittedAtMs":1790297006729}} {"type":"emit_inbound","label":"thread/start","frame":{"id":2,"result":{"thread":{"id":"01a0d604-629d-7162-b667-18c96f6fdf56","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d604-629d-7162-b667-18c96f6fdf56","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-5.6-terra","reasoningEffort":null,"createdAt":1790297006,"updatedAt":1790297006,"recencyAt":1790297006,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-43-26-01a0d604-629d-7162-b667-18c96f6fdf56.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]},"model":"gpt-5.6-terra","modelProvider":"openai","serviceTier":null,"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"],"instructionSources":["/home/replay-user/.codex/AGENTS.md","/home/replay-user/t3code/AGENTS.md"],"approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":{"id":":workspace","extends":null},"reasoningEffort":null,"multiAgentMode":"explicitRequestOnly"}}} -{"type":"expect_outbound","label":"config/read","frame":{"id":3,"method":"config/read","params":{"cwd":"","includeLayers":false}}} -{"type":"emit_inbound","label":"config/read","frame":{"id":3,"result":{"config":{},"origins":{}}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":4,"method":"turn/start","params":{"approvalPolicy":{"granular":{"mcp_elicitations":true,"request_permissions":true,"rules":true,"sandbox_approval":true,"skill_approval":true}},"approvalsReviewer":"user","cwd":"","input":[{"text":"Create or overwrite .codex-probe-write-action.txt with exactly this text: codex app-server approval fixture. Use a local shell command or file edit only, then briefly report what happened. Do not read package metadata, use GitHub, use web, or use MCP.","type":"text"}],"model":"gpt-5.6-terra","sandboxPolicy":{"networkAccess":false,"type":"readOnly"},"summary":"auto","threadId":"01a0d604-629d-7162-b667-18c96f6fdf56","collaborationMode":{"mode":"default","settings":{"model":"gpt-5.6-terra"}}}}} +{"type":"expect_outbound","label":"thread/name/set","frame":{"id":3,"method":"thread/name/set","params":{"name":"Replay fixture: tool_call_restricted_granular","threadId":"01a0d604-629d-7162-b667-18c96f6fdf56"}}} +{"type":"emit_inbound","label":"thread/name/set","frame":{"id":3,"result":{}}} +{"type":"emit_inbound","label":"thread/name/updated","frame":{"method":"thread/name/updated","params":{"threadId":"01a0d604-629d-7162-b667-18c96f6fdf56","threadName":"Replay fixture: tool_call_restricted_granular"}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":4,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":4,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":5,"method":"turn/start","params":{"approvalPolicy":{"granular":{"mcp_elicitations":true,"request_permissions":true,"rules":true,"sandbox_approval":true,"skill_approval":true}},"approvalsReviewer":"user","cwd":"","input":[{"text":"Create or overwrite .codex-probe-write-action.txt with exactly this text: codex app-server approval fixture. Use a local shell command or file edit only, then briefly report what happened. Do not read package metadata, use GitHub, use web, or use MCP.","type":"text"}],"model":"gpt-5.6-terra","sandboxPolicy":{"networkAccess":false,"type":"readOnly"},"summary":"auto","threadId":"01a0d604-629d-7162-b667-18c96f6fdf56","collaborationMode":{"mode":"default","settings":{"model":"gpt-5.6-terra"}}}}} {"type":"emit_inbound","label":"thread/started","frame":{"method":"thread/started","params":{"thread":{"id":"01a0d604-629d-7162-b667-18c96f6fdf56","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d604-629d-7162-b667-18c96f6fdf56","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-5.6-terra","reasoningEffort":null,"createdAt":1790297006,"updatedAt":1790297006,"recencyAt":1790297006,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-43-26-01a0d604-629d-7162-b667-18c96f6fdf56.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]}},"emittedAtMs":1790297006923}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0d604-629d-7162-b667-18c96f6fdf56","name":"codex_apps","status":"starting","error":null,"failureReason":null},"emittedAtMs":1790297006923}} {"type":"emit_inbound","label":"thread/settings/updated","frame":{"method":"thread/settings/updated","params":{"threadId":"01a0d604-629d-7162-b667-18c96f6fdf56","threadSettings":{"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","approvalPolicy":{"granular":{"sandbox_approval":true,"rules":true,"skill_approval":true,"request_permissions":true,"mcp_elicitations":true}},"approvalsReviewer":"user","sandboxPolicy":{"type":"readOnly","networkAccess":false},"activePermissionProfile":null,"model":"gpt-5.6-terra","modelProvider":"openai","serviceTier":null,"effort":null,"summary":"detailed","collaborationMode":{"mode":"default","settings":{"model":"gpt-5.6-terra","reasoning_effort":null,"developer_instructions":null}},"multiAgentMode":"explicitRequestOnly","personality":null}},"emittedAtMs":1790297006943}} -{"type":"emit_inbound","label":"turn/start","frame":{"id":4,"result":{"turn":{"id":"01a0d604-6358-72f1-bb89-7361cce0045c","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} +{"type":"emit_inbound","label":"turn/start","frame":{"id":5,"result":{"turn":{"id":"01a0d604-6358-72f1-bb89-7361cce0045c","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d604-629d-7162-b667-18c96f6fdf56","status":{"type":"active","activeFlags":[]}},"emittedAtMs":1790297007009}} {"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"01a0d604-629d-7162-b667-18c96f6fdf56","turn":{"id":"01a0d604-6358-72f1-bb89-7361cce0045c","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1790297006,"completedAt":null,"durationMs":null}},"emittedAtMs":1790297007009}} {"type":"emit_inbound","label":"account/updated","frame":{"method":"account/updated","params":{"authMode":"chatgpt","planType":"unknown"},"emittedAtMs":1790297007345}} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/tool_call_workspace_never/codex_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/tool_call_workspace_never/codex_transcript.ndjson index bb0cb5051c761..e7fc6334e7fd2 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/tool_call_workspace_never/codex_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/tool_call_workspace_never/codex_transcript.ndjson @@ -6,13 +6,16 @@ {"type":"emit_inbound","label":"configWarning","frame":{"method":"configWarning","params":{"summary":"Codex could not find bubblewrap on PATH. Install bubblewrap with your OS package manager. See the sandbox prerequisites: https://developers.openai.com/codex/concepts/sandboxing#prerequisites. Codex will use the bundled bubblewrap in the meantime.","details":null},"emittedAtMs":1790295509345}} {"type":"emit_inbound","label":"remoteControl/status/changed","frame":{"method":"remoteControl/status/changed","params":{"status":"disabled","serverName":"replay-host","installationId":"00000000-0000-4000-8000-000000000000","environmentId":null},"emittedAtMs":1790295509345}} {"type":"emit_inbound","label":"thread/start","frame":{"id":2,"result":{"thread":{"id":"01a0d5ed-896f-73b3-8c42-3ffa820eb343","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d5ed-896f-73b3-8c42-3ffa820eb343","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790295509,"updatedAt":1790295509,"recencyAt":1790295509,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-18-29-01a0d5ed-896f-73b3-8c42-3ffa820eb343.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]},"model":"gpt-6-luna","modelProvider":"openai","serviceTier":null,"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"],"instructionSources":["/home/replay-user/.codex/AGENTS.md","/home/replay-user/t3code/AGENTS.md"],"approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":{"id":":workspace","extends":null},"reasoningEffort":null,"multiAgentMode":"explicitRequestOnly"}}} -{"type":"expect_outbound","label":"config/read","frame":{"id":3,"method":"config/read","params":{"cwd":"","includeLayers":false}}} -{"type":"emit_inbound","label":"config/read","frame":{"id":3,"result":{"config":{},"origins":{}}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":4,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Create or overwrite .codex-probe-write-action.txt with exactly this text: codex app-server approval fixture. Use a local shell command or file edit only, then briefly report what happened. Do not read package metadata, use GitHub, use web, or use MCP.","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"networkAccess":false,"type":"workspaceWrite","writableRoots":[]},"summary":"auto","threadId":"01a0d5ed-896f-73b3-8c42-3ffa820eb343","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} +{"type":"expect_outbound","label":"thread/name/set","frame":{"id":3,"method":"thread/name/set","params":{"name":"Replay fixture: tool_call_workspace_never","threadId":"01a0d5ed-896f-73b3-8c42-3ffa820eb343"}}} +{"type":"emit_inbound","label":"thread/name/set","frame":{"id":3,"result":{}}} +{"type":"emit_inbound","label":"thread/name/updated","frame":{"method":"thread/name/updated","params":{"threadId":"01a0d5ed-896f-73b3-8c42-3ffa820eb343","threadName":"Replay fixture: tool_call_workspace_never"}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":4,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":4,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":5,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Create or overwrite .codex-probe-write-action.txt with exactly this text: codex app-server approval fixture. Use a local shell command or file edit only, then briefly report what happened. Do not read package metadata, use GitHub, use web, or use MCP.","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"networkAccess":false,"type":"workspaceWrite","writableRoots":[]},"summary":"auto","threadId":"01a0d5ed-896f-73b3-8c42-3ffa820eb343","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} {"type":"emit_inbound","label":"thread/started","frame":{"method":"thread/started","params":{"thread":{"id":"01a0d5ed-896f-73b3-8c42-3ffa820eb343","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d5ed-896f-73b3-8c42-3ffa820eb343","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790295509,"updatedAt":1790295509,"recencyAt":1790295509,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-18-29-01a0d5ed-896f-73b3-8c42-3ffa820eb343.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]}},"emittedAtMs":1790295509540}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0d5ed-896f-73b3-8c42-3ffa820eb343","name":"codex_apps","status":"starting","error":null,"failureReason":null},"emittedAtMs":1790295509540}} {"type":"emit_inbound","label":"thread/settings/updated","frame":{"method":"thread/settings/updated","params":{"threadId":"01a0d5ed-896f-73b3-8c42-3ffa820eb343","threadSettings":{"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","approvalPolicy":"never","approvalsReviewer":"user","sandboxPolicy":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":null,"model":"gpt-6-luna","modelProvider":"openai","serviceTier":null,"effort":null,"summary":"detailed","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna","reasoning_effort":null,"developer_instructions":null}},"multiAgentMode":"explicitRequestOnly","personality":null}},"emittedAtMs":1790295509553}} -{"type":"emit_inbound","label":"turn/start","frame":{"id":4,"result":{"turn":{"id":"01a0d5ed-8a2a-7002-b65d-fe5885c9f4e0","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} +{"type":"emit_inbound","label":"turn/start","frame":{"id":5,"result":{"turn":{"id":"01a0d5ed-8a2a-7002-b65d-fe5885c9f4e0","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d5ed-896f-73b3-8c42-3ffa820eb343","status":{"type":"active","activeFlags":[]}},"emittedAtMs":1790295509613}} {"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"01a0d5ed-896f-73b3-8c42-3ffa820eb343","turn":{"id":"01a0d5ed-8a2a-7002-b65d-fe5885c9f4e0","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1790295509,"completedAt":null,"durationMs":null}},"emittedAtMs":1790295509613}} {"type":"emit_inbound","label":"account/updated","frame":{"method":"account/updated","params":{"authMode":"chatgpt","planType":"unknown"},"emittedAtMs":1790295510000}} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/turn_interrupt/codex_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/turn_interrupt/codex_transcript.ndjson index b89e9a51a96d0..8408743473657 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/turn_interrupt/codex_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/turn_interrupt/codex_transcript.ndjson @@ -6,22 +6,25 @@ {"type":"emit_inbound","label":"configWarning","frame":{"method":"configWarning","params":{"summary":"Codex could not find bubblewrap on PATH. Install bubblewrap with your OS package manager. See the sandbox prerequisites: https://developers.openai.com/codex/concepts/sandboxing#prerequisites. Codex will use the bundled bubblewrap in the meantime.","details":null},"emittedAtMs":1790295488496}} {"type":"emit_inbound","label":"remoteControl/status/changed","frame":{"method":"remoteControl/status/changed","params":{"status":"disabled","serverName":"replay-host","installationId":"00000000-0000-4000-8000-000000000000","environmentId":null},"emittedAtMs":1790295488496}} {"type":"emit_inbound","label":"thread/start","frame":{"id":2,"result":{"thread":{"id":"01a0d5ed-3804-72d0-9a3f-929885a11f32","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d5ed-3804-72d0-9a3f-929885a11f32","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790295488,"updatedAt":1790295488,"recencyAt":1790295488,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-18-08-01a0d5ed-3804-72d0-9a3f-929885a11f32.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]},"model":"gpt-6-luna","modelProvider":"openai","serviceTier":null,"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"],"instructionSources":["/home/replay-user/.codex/AGENTS.md","/home/replay-user/t3code/AGENTS.md"],"approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":{"id":":workspace","extends":null},"reasoningEffort":null,"multiAgentMode":"explicitRequestOnly"}}} -{"type":"expect_outbound","label":"config/read","frame":{"id":3,"method":"config/read","params":{"cwd":"","includeLayers":false}}} -{"type":"emit_inbound","label":"config/read","frame":{"id":3,"result":{"config":{},"origins":{}}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":4,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Do not answer immediately. First run the local shell command `sleep 30`, then respond with exactly: interrupt fixture should not finish naturally.","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"networkAccess":false,"type":"workspaceWrite","writableRoots":[]},"summary":"auto","threadId":"01a0d5ed-3804-72d0-9a3f-929885a11f32","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} +{"type":"expect_outbound","label":"thread/name/set","frame":{"id":3,"method":"thread/name/set","params":{"name":"Replay fixture: turn_interrupt","threadId":"01a0d5ed-3804-72d0-9a3f-929885a11f32"}}} +{"type":"emit_inbound","label":"thread/name/set","frame":{"id":3,"result":{}}} +{"type":"emit_inbound","label":"thread/name/updated","frame":{"method":"thread/name/updated","params":{"threadId":"01a0d5ed-3804-72d0-9a3f-929885a11f32","threadName":"Replay fixture: turn_interrupt"}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":4,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":4,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":5,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Do not answer immediately. First run the local shell command `sleep 30`, then respond with exactly: interrupt fixture should not finish naturally.","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"networkAccess":false,"type":"workspaceWrite","writableRoots":[]},"summary":"auto","threadId":"01a0d5ed-3804-72d0-9a3f-929885a11f32","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} {"type":"emit_inbound","label":"thread/started","frame":{"method":"thread/started","params":{"thread":{"id":"01a0d5ed-3804-72d0-9a3f-929885a11f32","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d5ed-3804-72d0-9a3f-929885a11f32","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790295488,"updatedAt":1790295488,"recencyAt":1790295488,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-18-08-01a0d5ed-3804-72d0-9a3f-929885a11f32.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]}},"emittedAtMs":1790295488683}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0d5ed-3804-72d0-9a3f-929885a11f32","name":"codex_apps","status":"starting","error":null,"failureReason":null},"emittedAtMs":1790295488683}} {"type":"emit_inbound","label":"thread/settings/updated","frame":{"method":"thread/settings/updated","params":{"threadId":"01a0d5ed-3804-72d0-9a3f-929885a11f32","threadSettings":{"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","approvalPolicy":"never","approvalsReviewer":"user","sandboxPolicy":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":null,"model":"gpt-6-luna","modelProvider":"openai","serviceTier":null,"effort":null,"summary":"detailed","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna","reasoning_effort":null,"developer_instructions":null}},"multiAgentMode":"explicitRequestOnly","personality":null}},"emittedAtMs":1790295488699}} -{"type":"emit_inbound","label":"turn/start","frame":{"id":4,"result":{"turn":{"id":"01a0d5ed-38b3-7a11-9203-bd9650a02764","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} +{"type":"emit_inbound","label":"turn/start","frame":{"id":5,"result":{"turn":{"id":"01a0d5ed-38b3-7a11-9203-bd9650a02764","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d5ed-3804-72d0-9a3f-929885a11f32","status":{"type":"active","activeFlags":[]}},"emittedAtMs":1790295488747}} {"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"01a0d5ed-3804-72d0-9a3f-929885a11f32","turn":{"id":"01a0d5ed-38b3-7a11-9203-bd9650a02764","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1790295488,"completedAt":null,"durationMs":null}},"emittedAtMs":1790295488747}} {"type":"emit_inbound","label":"account/updated","frame":{"method":"account/updated","params":{"authMode":"chatgpt","planType":"unknown"},"emittedAtMs":1790295489056}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0d5ed-3804-72d0-9a3f-929885a11f32","name":"xcodebuildmcp","status":"starting","error":null,"failureReason":null},"emittedAtMs":1790295489323}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0d5ed-3804-72d0-9a3f-929885a11f32","name":"codex_apps","status":"ready","error":null,"failureReason":null},"emittedAtMs":1790295489469}} -{"type":"expect_outbound","label":"turn/interrupt","frame":{"id":5,"method":"turn/interrupt","params":{"threadId":"01a0d5ed-3804-72d0-9a3f-929885a11f32","turnId":"01a0d5ed-38b3-7a11-9203-bd9650a02764"}}} +{"type":"expect_outbound","label":"turn/interrupt","frame":{"id":6,"method":"turn/interrupt","params":{"threadId":"01a0d5ed-3804-72d0-9a3f-929885a11f32","turnId":"01a0d5ed-38b3-7a11-9203-bd9650a02764"}}} {"type":"emit_inbound","label":"item/started","frame":{"method":"item/started","params":{"item":{"type":"userMessage","id":"01a0d5ed-3ea7-7aa3-a029-700c3b1aa2e8","clientId":null,"content":[{"type":"text","text":"Do not answer immediately. First run the local shell command `sleep 30`, then respond with exactly: interrupt fixture should not finish naturally.","text_elements":[]}]},"threadId":"01a0d5ed-3804-72d0-9a3f-929885a11f32","turnId":"01a0d5ed-38b3-7a11-9203-bd9650a02764","startedAtMs":1790295490219},"emittedAtMs":1790295490220}} {"type":"emit_inbound","label":"item/completed","frame":{"method":"item/completed","params":{"item":{"type":"userMessage","id":"01a0d5ed-3ea7-7aa3-a029-700c3b1aa2e8","clientId":null,"content":[{"type":"text","text":"Do not answer immediately. First run the local shell command `sleep 30`, then respond with exactly: interrupt fixture should not finish naturally.","text_elements":[]}]},"threadId":"01a0d5ed-3804-72d0-9a3f-929885a11f32","turnId":"01a0d5ed-38b3-7a11-9203-bd9650a02764","completedAtMs":1790295490219},"emittedAtMs":1790295490229}} -{"type":"emit_inbound","label":"turn/interrupt","frame":{"id":5,"result":{}}} +{"type":"emit_inbound","label":"turn/interrupt","frame":{"id":6,"result":{}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d5ed-3804-72d0-9a3f-929885a11f32","status":{"type":"idle"}},"emittedAtMs":1790295490246}} {"type":"emit_inbound","label":"turn/completed","frame":{"method":"turn/completed","params":{"threadId":"01a0d5ed-3804-72d0-9a3f-929885a11f32","turn":{"id":"01a0d5ed-38b3-7a11-9203-bd9650a02764","items":[],"itemsView":"notLoaded","status":"interrupted","error":null,"startedAt":1790295488,"completedAt":1790295490,"durationMs":1544}},"emittedAtMs":1790295490246}} {"type":"runtime_exit","status":"success"} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/turn_interrupt_mid_tool/codex_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/turn_interrupt_mid_tool/codex_transcript.ndjson index 4b7f91e221b8c..c50bb4c3d650f 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/turn_interrupt_mid_tool/codex_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/turn_interrupt_mid_tool/codex_transcript.ndjson @@ -6,13 +6,16 @@ {"type":"emit_inbound","label":"configWarning","frame":{"method":"configWarning","params":{"summary":"Codex could not find bubblewrap on PATH. Install bubblewrap with your OS package manager. See the sandbox prerequisites: https://developers.openai.com/codex/concepts/sandboxing#prerequisites. Codex will use the bundled bubblewrap in the meantime.","details":null},"emittedAtMs":1790297700256}} {"type":"emit_inbound","label":"remoteControl/status/changed","frame":{"method":"remoteControl/status/changed","params":{"status":"disabled","serverName":"replay-host","installationId":"00000000-0000-4000-8000-000000000000","environmentId":null},"emittedAtMs":1790297700256}} {"type":"emit_inbound","label":"thread/start","frame":{"id":2,"result":{"thread":{"id":"01a0d60e-f7cc-7a50-bdff-90174e2c3b56","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d60e-f7cc-7a50-bdff-90174e2c3b56","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790297700,"updatedAt":1790297700,"recencyAt":1790297700,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-55-00-01a0d60e-f7cc-7a50-bdff-90174e2c3b56.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]},"model":"gpt-6-luna","modelProvider":"openai","serviceTier":null,"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"],"instructionSources":["/home/replay-user/.codex/AGENTS.md"],"approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":{"id":":workspace","extends":null},"reasoningEffort":null,"multiAgentMode":"explicitRequestOnly"}}} -{"type":"expect_outbound","label":"config/read","frame":{"id":3,"method":"config/read","params":{"cwd":"","includeLayers":false}}} -{"type":"emit_inbound","label":"config/read","frame":{"id":3,"result":{"config":{},"origins":{}}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":4,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Run this exact local command: `node -e \"console.log('interrupt fixture tool started'); setTimeout(() => {}, 30000)\"`. Do not answer until it completes, then respond exactly: interrupt fixture should not finish naturally.","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"networkAccess":false,"type":"workspaceWrite","writableRoots":[]},"summary":"auto","threadId":"01a0d60e-f7cc-7a50-bdff-90174e2c3b56","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} +{"type":"expect_outbound","label":"thread/name/set","frame":{"id":3,"method":"thread/name/set","params":{"name":"Replay fixture: turn_interrupt_mid_tool","threadId":"01a0d60e-f7cc-7a50-bdff-90174e2c3b56"}}} +{"type":"emit_inbound","label":"thread/name/set","frame":{"id":3,"result":{}}} +{"type":"emit_inbound","label":"thread/name/updated","frame":{"method":"thread/name/updated","params":{"threadId":"01a0d60e-f7cc-7a50-bdff-90174e2c3b56","threadName":"Replay fixture: turn_interrupt_mid_tool"}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":4,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":4,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":5,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Run this exact local command: `node -e \"console.log('interrupt fixture tool started'); setTimeout(() => {}, 30000)\"`. Do not answer until it completes, then respond exactly: interrupt fixture should not finish naturally.","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"networkAccess":false,"type":"workspaceWrite","writableRoots":[]},"summary":"auto","threadId":"01a0d60e-f7cc-7a50-bdff-90174e2c3b56","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} {"type":"emit_inbound","label":"thread/started","frame":{"method":"thread/started","params":{"thread":{"id":"01a0d60e-f7cc-7a50-bdff-90174e2c3b56","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d60e-f7cc-7a50-bdff-90174e2c3b56","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790297700,"updatedAt":1790297700,"recencyAt":1790297700,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-55-00-01a0d60e-f7cc-7a50-bdff-90174e2c3b56.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]}},"emittedAtMs":1790297700615}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0d60e-f7cc-7a50-bdff-90174e2c3b56","name":"codex_apps","status":"starting","error":null,"failureReason":null},"emittedAtMs":1790297700615}} {"type":"emit_inbound","label":"thread/settings/updated","frame":{"method":"thread/settings/updated","params":{"threadId":"01a0d60e-f7cc-7a50-bdff-90174e2c3b56","threadSettings":{"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","approvalPolicy":"never","approvalsReviewer":"user","sandboxPolicy":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":null,"model":"gpt-6-luna","modelProvider":"openai","serviceTier":null,"effort":null,"summary":"detailed","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna","reasoning_effort":null,"developer_instructions":null}},"multiAgentMode":"explicitRequestOnly","personality":null}},"emittedAtMs":1790297700629}} -{"type":"emit_inbound","label":"turn/start","frame":{"id":4,"result":{"turn":{"id":"01a0d60e-f90f-7f23-b6ba-9ca7ee20b5cd","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} +{"type":"emit_inbound","label":"turn/start","frame":{"id":5,"result":{"turn":{"id":"01a0d60e-f90f-7f23-b6ba-9ca7ee20b5cd","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d60e-f7cc-7a50-bdff-90174e2c3b56","status":{"type":"active","activeFlags":[]}},"emittedAtMs":1790297700691}} {"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"01a0d60e-f7cc-7a50-bdff-90174e2c3b56","turn":{"id":"01a0d60e-f90f-7f23-b6ba-9ca7ee20b5cd","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1790297700,"completedAt":null,"durationMs":null}},"emittedAtMs":1790297700691}} {"type":"emit_inbound","label":"account/updated","frame":{"method":"account/updated","params":{"authMode":"chatgpt","planType":"unknown"},"emittedAtMs":1790297700959}} @@ -27,11 +30,11 @@ {"type":"emit_inbound","label":"item/reasoning/summaryTextDelta","frame":{"method":"item/reasoning/summaryTextDelta","params":{"threadId":"01a0d60e-f7cc-7a50-bdff-90174e2c3b56","turnId":"01a0d60e-f90f-7f23-b6ba-9ca7ee20b5cd","itemId":"rs_02867d76e88a025b016ab5c669424c87d09ca784eb308b0650","delta":"**Running exact command**","summaryIndex":0},"emittedAtMs":1790297707152}} {"type":"emit_inbound","label":"item/completed","frame":{"method":"item/completed","params":{"item":{"type":"reasoning","id":"rs_02867d76e88a025b016ab5c669424c87d09ca784eb308b0650","summary":["**Running exact command**"],"content":[]},"threadId":"01a0d60e-f7cc-7a50-bdff-90174e2c3b56","turnId":"01a0d60e-f90f-7f23-b6ba-9ca7ee20b5cd","completedAtMs":1790297707229},"emittedAtMs":1790297707234}} {"type":"emit_inbound","label":"item/started","frame":{"method":"item/started","params":{"item":{"type":"commandExecution","id":"exec-0ce96e49-aa1c-4bae-b4f8-687a7473017c","pluginId":null,"scriptPath":null,"command":"/bin/bash -lc \"node -e \\\"console.log('interrupt fixture tool started'); setTimeout(() => {}, 30000)\\\"\"","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","processId":"87302","source":"unifiedExecStartup","status":"inProgress","commandActions":[{"type":"unknown","command":"node -e \"console.log('interrupt fixture tool started'); setTimeout(() => {}, 30000)\""}],"aggregatedOutput":null,"exitCode":null,"durationMs":null},"threadId":"01a0d60e-f7cc-7a50-bdff-90174e2c3b56","turnId":"01a0d60e-f90f-7f23-b6ba-9ca7ee20b5cd","startedAtMs":1790297707619},"emittedAtMs":1790297707621}} -{"type":"expect_outbound","label":"turn/interrupt","frame":{"id":5,"method":"turn/interrupt","params":{"threadId":"01a0d60e-f7cc-7a50-bdff-90174e2c3b56","turnId":"01a0d60e-f90f-7f23-b6ba-9ca7ee20b5cd"}}} +{"type":"expect_outbound","label":"turn/interrupt","frame":{"id":6,"method":"turn/interrupt","params":{"threadId":"01a0d60e-f7cc-7a50-bdff-90174e2c3b56","turnId":"01a0d60e-f90f-7f23-b6ba-9ca7ee20b5cd"}}} {"type":"emit_inbound","label":"thread/tokenUsage/updated","frame":{"method":"thread/tokenUsage/updated","params":{"threadId":"01a0d60e-f7cc-7a50-bdff-90174e2c3b56","turnId":"01a0d60e-f90f-7f23-b6ba-9ca7ee20b5cd","tokenUsage":{"total":{"totalTokens":17953,"inputTokens":17855,"cachedInputTokens":11008,"cacheWriteInputTokens":0,"outputTokens":98,"reasoningOutputTokens":25},"last":{"totalTokens":17953,"inputTokens":17855,"cachedInputTokens":11008,"cacheWriteInputTokens":0,"outputTokens":98,"reasoningOutputTokens":25},"modelContextWindow":258400}},"emittedAtMs":1790297707635}} -{"type":"emit_inbound","label":"turn/interrupt","frame":{"id":5,"result":{}}} -{"type":"expect_outbound","label":"thread/backgroundTerminals/terminate","frame":{"id":6,"method":"thread/backgroundTerminals/terminate","params":{"threadId":"01a0d60e-f7cc-7a50-bdff-90174e2c3b56","processId":"87302"}}} +{"type":"emit_inbound","label":"turn/interrupt","frame":{"id":6,"result":{}}} +{"type":"expect_outbound","label":"thread/backgroundTerminals/terminate","frame":{"id":7,"method":"thread/backgroundTerminals/terminate","params":{"threadId":"01a0d60e-f7cc-7a50-bdff-90174e2c3b56","processId":"87302"}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d60e-f7cc-7a50-bdff-90174e2c3b56","status":{"type":"idle"}},"emittedAtMs":1790297707650}} {"type":"emit_inbound","label":"turn/completed","frame":{"method":"turn/completed","params":{"threadId":"01a0d60e-f7cc-7a50-bdff-90174e2c3b56","turn":{"id":"01a0d60e-f90f-7f23-b6ba-9ca7ee20b5cd","items":[],"itemsView":"notLoaded","status":"interrupted","error":null,"startedAt":1790297700,"completedAt":1790297707,"durationMs":7017}},"emittedAtMs":1790297707650}} -{"type":"emit_inbound","label":"thread/backgroundTerminals/terminate","frame":{"id":6,"result":{"terminated":true}}} +{"type":"emit_inbound","label":"thread/backgroundTerminals/terminate","frame":{"id":7,"result":{"terminated":true}}} {"type":"runtime_exit","status":"success"} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/web_search/codex_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/web_search/codex_transcript.ndjson index 5826be00f9c9e..13e2b2b73a404 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/web_search/codex_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/web_search/codex_transcript.ndjson @@ -6,13 +6,16 @@ {"type":"emit_inbound","label":"configWarning","frame":{"method":"configWarning","params":{"summary":"Codex could not find bubblewrap on PATH. Install bubblewrap with your OS package manager. See the sandbox prerequisites: https://developers.openai.com/codex/concepts/sandboxing#prerequisites. Codex will use the bundled bubblewrap in the meantime.","details":null},"emittedAtMs":1790295574462}} {"type":"emit_inbound","label":"remoteControl/status/changed","frame":{"method":"remoteControl/status/changed","params":{"status":"disabled","serverName":"replay-host","installationId":"00000000-0000-4000-8000-000000000000","environmentId":null},"emittedAtMs":1790295574462}} {"type":"emit_inbound","label":"thread/start","frame":{"id":2,"result":{"thread":{"id":"01a0d5ee-87e4-7461-9ab7-5c316b503107","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d5ee-87e4-7461-9ab7-5c316b503107","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790295574,"updatedAt":1790295574,"recencyAt":1790295574,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-19-34-01a0d5ee-87e4-7461-9ab7-5c316b503107.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]},"model":"gpt-6-luna","modelProvider":"openai","serviceTier":null,"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"],"instructionSources":["/home/replay-user/.codex/AGENTS.md","/home/replay-user/t3code/AGENTS.md"],"approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":{"id":":workspace","extends":null},"reasoningEffort":null,"multiAgentMode":"explicitRequestOnly"}}} -{"type":"expect_outbound","label":"config/read","frame":{"id":3,"method":"config/read","params":{"cwd":"","includeLayers":false}}} -{"type":"emit_inbound","label":"config/read","frame":{"id":3,"result":{"config":{},"origins":{}}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":4,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Search the web for FIFA World Cup ticket pricing, then answer exactly: web search fixture complete","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"auto","threadId":"01a0d5ee-87e4-7461-9ab7-5c316b503107","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} +{"type":"expect_outbound","label":"thread/name/set","frame":{"id":3,"method":"thread/name/set","params":{"name":"Replay fixture: web_search","threadId":"01a0d5ee-87e4-7461-9ab7-5c316b503107"}}} +{"type":"emit_inbound","label":"thread/name/set","frame":{"id":3,"result":{}}} +{"type":"emit_inbound","label":"thread/name/updated","frame":{"method":"thread/name/updated","params":{"threadId":"01a0d5ee-87e4-7461-9ab7-5c316b503107","threadName":"Replay fixture: web_search"}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":4,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":4,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":5,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Search the web for FIFA World Cup ticket pricing, then answer exactly: web search fixture complete","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"auto","threadId":"01a0d5ee-87e4-7461-9ab7-5c316b503107","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} {"type":"emit_inbound","label":"thread/started","frame":{"method":"thread/started","params":{"thread":{"id":"01a0d5ee-87e4-7461-9ab7-5c316b503107","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d5ee-87e4-7461-9ab7-5c316b503107","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790295574,"updatedAt":1790295574,"recencyAt":1790295574,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-19-34-01a0d5ee-87e4-7461-9ab7-5c316b503107.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]}},"emittedAtMs":1790295574652}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0d5ee-87e4-7461-9ab7-5c316b503107","name":"codex_apps","status":"starting","error":null,"failureReason":null},"emittedAtMs":1790295574652}} {"type":"emit_inbound","label":"thread/settings/updated","frame":{"method":"thread/settings/updated","params":{"threadId":"01a0d5ee-87e4-7461-9ab7-5c316b503107","threadSettings":{"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","approvalPolicy":"never","approvalsReviewer":"user","sandboxPolicy":{"type":"dangerFullAccess"},"activePermissionProfile":null,"model":"gpt-6-luna","modelProvider":"openai","serviceTier":null,"effort":null,"summary":"detailed","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna","reasoning_effort":null,"developer_instructions":null}},"multiAgentMode":"explicitRequestOnly","personality":null}},"emittedAtMs":1790295574669}} -{"type":"emit_inbound","label":"turn/start","frame":{"id":4,"result":{"turn":{"id":"01a0d5ee-8888-7d30-8f2b-68fe28f521bc","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} +{"type":"emit_inbound","label":"turn/start","frame":{"id":5,"result":{"turn":{"id":"01a0d5ee-8888-7d30-8f2b-68fe28f521bc","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d5ee-87e4-7461-9ab7-5c316b503107","status":{"type":"active","activeFlags":[]}},"emittedAtMs":1790295574742}} {"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"01a0d5ee-87e4-7461-9ab7-5c316b503107","turn":{"id":"01a0d5ee-8888-7d30-8f2b-68fe28f521bc","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1790295574,"completedAt":null,"durationMs":null}},"emittedAtMs":1790295574742}} {"type":"emit_inbound","label":"account/updated","frame":{"method":"account/updated","params":{"authMode":"chatgpt","planType":"unknown"},"emittedAtMs":1790295575098}} From c8b214158e0542a80b75100ccb929177d3bb4f7c Mon Sep 17 00:00:00 2001 From: MusseJusse <66657454+MusseJusse@users.noreply.github.com> Date: Thu, 19 Nov 2026 20:23:22 +0000 Subject: [PATCH 52/97] fix(server): Antigravity 1.5 temporary setup and text-helper sessions clean up their files (#39275) Co-authored-by: Julius Marminge --- .../src/provider/acp/AntigravityChildWork.ts | 2 +- .../acp/AntigravitySessionFiles.test.ts | 217 +++++++++++++++++- .../provider/acp/AntigravitySessionFiles.ts | 147 +++++++++++- 3 files changed, 353 insertions(+), 13 deletions(-) diff --git a/apps/server/src/provider/acp/AntigravityChildWork.ts b/apps/server/src/provider/acp/AntigravityChildWork.ts index 554e419421f6c..c502b4de35e53 100644 --- a/apps/server/src/provider/acp/AntigravityChildWork.ts +++ b/apps/server/src/provider/acp/AntigravityChildWork.ts @@ -80,7 +80,7 @@ export function describeAntigravitySubagentLaunches( } /** Length-delimited fields only; varints and fixed values are skipped. */ -function protoFields(bytes: Uint8Array): ReadonlyArray { +export function protoFields(bytes: Uint8Array): ReadonlyArray { const fields: Array = []; let offset = 0; const varint = () => { diff --git a/apps/server/src/provider/acp/AntigravitySessionFiles.test.ts b/apps/server/src/provider/acp/AntigravitySessionFiles.test.ts index 81885dc0c89b2..cec0390f0b764 100644 --- a/apps/server/src/provider/acp/AntigravitySessionFiles.test.ts +++ b/apps/server/src/provider/acp/AntigravitySessionFiles.test.ts @@ -1,11 +1,226 @@ +// @effect-diagnostics nodeBuiltinImport:off -- fixtures write a native session database. +import * as NodeSqlite from "node:sqlite"; +import * as NodeURL from "node:url"; + import * as NodeServices from "@effect/platform-node/NodeServices"; import { expect, it } from "@effect/vitest"; +import { symlinksSupported } from "@t3tools/shared/testing/symlinks"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Path from "effect/Path"; import * as PlatformError from "effect/PlatformError"; -import { retireAntigravityRuntimeTempDirs } from "./AntigravitySessionFiles.ts"; +import { + removeAntigravitySessionFiles, + retireAntigravityRuntimeTempDirs, +} from "./AntigravitySessionFiles.ts"; + +const SESSION_ID = "047c62f6-607b-44db-bfbe-f83b67e9e8b1"; +const OTHER_SESSION_ID = "9b2b7a98-28db-4422-9f46-70e106319548"; + +const varint = (value: number): number[] => { + const bytes: number[] = []; + while (value >= 0x80) { + bytes.push((value & 0x7f) | 0x80); + value = Math.floor(value / 0x80); + } + return [...bytes, value]; +}; +const protoField = (number: number, value: string | Uint8Array) => { + const bytes = typeof value === "string" ? new TextEncoder().encode(value) : value; + return [...varint(number * 8 + 2), ...varint(bytes.length), ...bytes]; +}; +const proto = (...parts: number[][]) => Uint8Array.from(parts.flat()); + +function encodeTrajectoryMetadata(input: { + readonly sessionId?: string; + readonly workspaceUris: ReadonlyArray; +}) { + return proto( + ...input.workspaceUris.map((uri) => protoField(1, proto(protoField(1, uri)))), + ...(input.sessionId === undefined ? [] : [protoField(6, input.sessionId)]), + ...input.workspaceUris.map((uri) => protoField(7, uri)), + ); +} + +function writeNativeSessionDb(dbPath: string, blob?: Uint8Array) { + const database = new NodeSqlite.DatabaseSync(dbPath); + try { + database.exec("CREATE TABLE trajectory_metadata_blob (id TEXT PRIMARY KEY, data BLOB)"); + if (blob !== undefined) { + database + .prepare("INSERT INTO trajectory_metadata_blob (id, data) VALUES (?, ?)") + .run("main", blob); + } + } finally { + database.close(); + } +} + +const makeNativeSessionFixture = Effect.fn("makeNativeSessionFixture")(function* (input: { + readonly sessionId?: string; + readonly workspacePaths: ReadonlyArray; + readonly metadataSessionId?: string; + readonly corruptBlob?: boolean; +}) { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-agy-session-files-" }); + const profileDirectory = path.join(root, "profile"); + const acpDirectory = path.join(profileDirectory, "antigravity-acp"); + const conversations = path.join(acpDirectory, "conversations"); + const annotations = path.join(acpDirectory, "annotations"); + const sessionId = input.sessionId ?? SESSION_ID; + const brain = path.join(acpDirectory, "brain", sessionId); + const base = path.join(conversations, sessionId); + const annotationFile = path.join(annotations, `${sessionId}.pbtxt`); + + yield* fs.makeDirectory(conversations, { recursive: true }); + yield* fs.makeDirectory(annotations, { recursive: true }); + yield* fs.makeDirectory(brain, { recursive: true }); + + const blob = input.corruptBlob + ? Uint8Array.from([0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]) + : encodeTrajectoryMetadata({ + sessionId: input.metadataSessionId ?? sessionId, + workspaceUris: input.workspacePaths.map((entry) => NodeURL.pathToFileURL(entry).href), + }); + writeNativeSessionDb(`${base}.db`, blob); + yield* fs.writeFileString(`${base}.db-wal`, "wal"); + yield* fs.writeFileString(`${base}.db-shm`, "shm"); + yield* fs.writeFileString(path.join(brain, "output.txt"), "artifact"); + yield* fs.writeFileString(annotationFile, "annotation"); + + return { root, profileDirectory, base, brain, annotationFile, sessionId }; +}); + +it.layer(NodeServices.layer)("removeAntigravitySessionFiles", (it) => { + it.effect( + "removes Antigravity 1.5+ session files without a .meta sidecar when the DB matches cwd", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-antigravity-setup-" }); + const realCwd = yield* fs.realPath(cwd); + const fixture = yield* makeNativeSessionFixture({ + workspacePaths: [realCwd, cwd], + }); + + yield* removeAntigravitySessionFiles({ + profileDirectory: fixture.profileDirectory, + sessionId: fixture.sessionId, + cwd, + }); + + expect(yield* fs.exists(`${fixture.base}.db`)).toBe(false); + expect(yield* fs.exists(`${fixture.base}.db-wal`)).toBe(false); + expect(yield* fs.exists(`${fixture.base}.db-shm`)).toBe(false); + expect(yield* fs.exists(fixture.brain)).toBe(false); + expect(yield* fs.exists(fixture.annotationFile)).toBe(false); + expect(yield* fs.exists(path.dirname(fixture.base))).toBe(true); + }), + ); + + it.effect("matches a symlinked temporary cwd against the canonical path stored in the DB", () => + Effect.gen(function* () { + if (!symlinksSupported) return; + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const parent = yield* fs.makeTempDirectoryScoped({ prefix: "t3-agy-symlink-" }); + const targetCwd = path.join(parent, "real-temp"); + const linkCwd = path.join(parent, "link-temp"); + yield* fs.makeDirectory(targetCwd, { recursive: true }); + yield* fs.symlink(targetCwd, linkCwd); + const fixture = yield* makeNativeSessionFixture({ + workspacePaths: [yield* fs.realPath(targetCwd)], + }); + + yield* removeAntigravitySessionFiles({ + profileDirectory: fixture.profileDirectory, + sessionId: fixture.sessionId, + cwd: linkCwd, + }); + + expect(yield* fs.exists(`${fixture.base}.db`)).toBe(false); + expect(yield* fs.exists(fixture.brain)).toBe(false); + expect(yield* fs.exists(fixture.annotationFile)).toBe(false); + }), + ); + + it.effect("keeps a 1.5+ session DB whose metadata belongs to a different workspace", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const projectCwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-agy-project-" }); + const helperCwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-agy-helper-" }); + const fixture = yield* makeNativeSessionFixture({ + workspacePaths: [projectCwd], + }); + + yield* removeAntigravitySessionFiles({ + profileDirectory: fixture.profileDirectory, + sessionId: fixture.sessionId, + cwd: helperCwd, + }); + + expect(yield* fs.exists(`${fixture.base}.db`)).toBe(true); + expect(yield* fs.exists(fixture.brain)).toBe(true); + expect(yield* fs.exists(fixture.annotationFile)).toBe(true); + }), + ); + + it.effect("keeps a 1.5+ session DB that also includes an additional workspace", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const helperCwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-agy-helper-" }); + const attachmentsDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-agy-attachments-" }); + const fixture = yield* makeNativeSessionFixture({ + workspacePaths: [helperCwd, attachmentsDir], + }); + + yield* removeAntigravitySessionFiles({ + profileDirectory: fixture.profileDirectory, + sessionId: fixture.sessionId, + cwd: helperCwd, + }); + + expect(yield* fs.exists(`${fixture.base}.db`)).toBe(true); + expect(yield* fs.exists(fixture.brain)).toBe(true); + expect(yield* fs.exists(fixture.annotationFile)).toBe(true); + }), + ); + + it.effect( + "keeps a 1.5+ session DB when its embedded session id mismatches or metadata is corrupt", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const helperCwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-agy-helper-" }); + const wrongId = yield* makeNativeSessionFixture({ + workspacePaths: [helperCwd], + metadataSessionId: OTHER_SESSION_ID, + }); + const corrupt = yield* makeNativeSessionFixture({ + workspacePaths: [helperCwd], + corruptBlob: true, + }); + + yield* removeAntigravitySessionFiles({ + profileDirectory: wrongId.profileDirectory, + sessionId: wrongId.sessionId, + cwd: helperCwd, + }); + yield* removeAntigravitySessionFiles({ + profileDirectory: corrupt.profileDirectory, + sessionId: corrupt.sessionId, + cwd: helperCwd, + }); + + expect(yield* fs.exists(`${wrongId.base}.db`)).toBe(true); + expect(yield* fs.exists(`${corrupt.base}.db`)).toBe(true); + }), + ); +}); it.layer(NodeServices.layer)("retireAntigravityRuntimeTempDirs", (it) => { it.effect("moves leftovers aside at once and deletes them, plus older retirees, later", () => diff --git a/apps/server/src/provider/acp/AntigravitySessionFiles.ts b/apps/server/src/provider/acp/AntigravitySessionFiles.ts index 819d79a05ed12..f59d785754d44 100644 --- a/apps/server/src/provider/acp/AntigravitySessionFiles.ts +++ b/apps/server/src/provider/acp/AntigravitySessionFiles.ts @@ -1,13 +1,119 @@ +// @effect-diagnostics nodeBuiltinImport:off -- node:sqlite reads the native session database read-only. +import * as NodeSqlite from "node:sqlite"; +import * as NodeURL from "node:url"; + import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Path from "effect/Path"; import * as Schema from "effect/Schema"; +import { protoFields } from "./AntigravityChildWork.ts"; +import { antigravityManagedPath, antigravityProfileRoot } from "./AntigravityProfilePaths.ts"; + const isNativeSessionId = Schema.is(Schema.String.check(Schema.isUUID(4))); const decodeSessionMetadata = Schema.decodeEffect( Schema.fromJsonString(Schema.Struct({ cwd: Schema.String })), ); +// Field numbers from the runtime's TrajectoryMetadata proto in trajectory_metadata_blob. +const TRAJECTORY_WORKSPACES = 1; +const WORKSPACE_URI = 1; +const TRAJECTORY_SESSION_ID = 6; +const TRAJECTORY_WORKSPACE_URIS = 7; +const MAX_METADATA_BLOB_BYTES = 1024 * 1024; + +const utf8Decoder = new TextDecoder("utf-8", { fatal: true }); + +function decodeTrajectoryOwnership(blob: Uint8Array): + | { + readonly sessionId: string | undefined; + readonly workspaceUris: ReadonlyArray; + } + | undefined { + try { + let sessionId: string | undefined; + const workspaceUris: Array = []; + for (const [field, value] of protoFields(blob)) { + if (field === TRAJECTORY_SESSION_ID && sessionId === undefined) { + const decoded = utf8Decoder.decode(value).trim(); + if (decoded.length > 0) sessionId = decoded; + } else if (field === TRAJECTORY_WORKSPACES) { + for (const [nestedField, nestedValue] of protoFields(value)) { + if (nestedField !== WORKSPACE_URI) continue; + const uri = utf8Decoder.decode(nestedValue).trim(); + if (uri.length > 0) workspaceUris.push(uri); + } + } else if (field === TRAJECTORY_WORKSPACE_URIS) { + const uri = utf8Decoder.decode(value).trim(); + if (uri.length > 0) workspaceUris.push(uri); + } + } + return { sessionId, workspaceUris }; + } catch { + return undefined; + } +} + +async function readDatabaseWorkspacePaths( + profileDirectory: string, + sessionId: string, +): Promise | undefined> { + const profileRoot = await antigravityProfileRoot(profileDirectory); + if (profileRoot === undefined) return undefined; + const databasePath = ( + await antigravityManagedPath( + profileRoot, + ["antigravity-acp", "conversations", `${sessionId}.db`], + "file", + ) + )?.path; + if (databasePath === undefined) return undefined; + + let database: NodeSqlite.DatabaseSync | undefined; + try { + database = new NodeSqlite.DatabaseSync(databasePath, { readOnly: true }); + database.exec("PRAGMA busy_timeout = 100"); + const rows = database + .prepare("SELECT data FROM trajectory_metadata_blob WHERE length(data) <= ? LIMIT 2") + .all(MAX_METADATA_BLOB_BYTES); + if (rows.length !== 1) return undefined; + const row = rows[0]; + if ( + row === null || + typeof row !== "object" || + !("data" in row) || + !(row.data instanceof Uint8Array) + ) { + return undefined; + } + const metadata = decodeTrajectoryOwnership(row.data); + if ( + metadata === undefined || + metadata.workspaceUris.length === 0 || + (metadata.sessionId !== undefined && metadata.sessionId !== sessionId) + ) { + return undefined; + } + return metadata.workspaceUris.map((uri) => NodeURL.fileURLToPath(uri)); + } catch { + return undefined; + } finally { + database?.close(); + } +} + +// The runtime may store the resolved path (macOS `/var` -> `/private/var`) or another drive-letter case. +const pathKey = Effect.fnUntraced(function* ( + fs: FileSystem.FileSystem, + path: Path.Path, + target: string, +) { + const resolved = yield* fs + .realPath(target) + .pipe(Effect.orElseSucceed(() => path.resolve(target))); + return path.sep === "\\" ? resolved.toLowerCase() : resolved; +}); + /** Call after the process closes. The unique temporary cwd proves which session we own. */ export const removeAntigravitySessionFiles = Effect.fn("removeAntigravitySessionFiles")( function* (input: { @@ -15,29 +121,48 @@ export const removeAntigravitySessionFiles = Effect.fn("removeAntigravitySession readonly sessionId: string | undefined; readonly cwd: string; }) { - if (input.sessionId === undefined || !isNativeSessionId(input.sessionId)) { + const { sessionId } = input; + if (sessionId === undefined || !isNativeSessionId(sessionId)) { return; } const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; const acpDirectory = path.join(input.profileDirectory, "antigravity-acp"); - const base = path.join(acpDirectory, "conversations", input.sessionId); - if (!(yield* fs.exists(`${base}.meta`))) { - return; - } - const metadata = yield* fs - .readFileString(`${base}.meta`) - .pipe(Effect.flatMap(decodeSessionMetadata)); - if (metadata.cwd !== input.cwd) { - return; + const base = path.join(acpDirectory, "conversations", sessionId); + + if (yield* fs.exists(`${base}.meta`)) { + const metadata = yield* fs + .readFileString(`${base}.meta`) + .pipe(Effect.flatMap(decodeSessionMetadata)); + if (metadata.cwd !== input.cwd) { + return; + } + } else { + // Antigravity CLI 1.5+ writes no `.meta` sidecar; workspace URIs live in the session DB. + const workspacePaths = yield* Effect.promise(() => + readDatabaseWorkspacePaths(input.profileDirectory, sessionId), + ); + if (workspacePaths === undefined || workspacePaths.length === 0) { + return; + } + const cwdKey = yield* pathKey(fs, path, input.cwd); + for (const workspacePath of workspacePaths) { + if ((yield* pathKey(fs, path, workspacePath)) !== cwdKey) { + return; + } + } } + for (const suffix of [".db", ".db-wal", ".db-shm", ".db-journal", ".meta"]) { yield* fs.remove(`${base}${suffix}`, { force: true }); } - yield* fs.remove(path.join(acpDirectory, "brain", input.sessionId), { + yield* fs.remove(path.join(acpDirectory, "brain", sessionId), { recursive: true, force: true, }); + yield* fs.remove(path.join(acpDirectory, "annotations", `${sessionId}.pbtxt`), { + force: true, + }); }, Effect.catch(() => Effect.logWarning("Could not remove temporary Antigravity session files.")), ); From ae268d93502832ba49f5d0a2a6754c958a43d6e2 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 19 Nov 2026 12:24:14 -0800 Subject: [PATCH 53/97] fix(server): a provider CLI that dies at startup names its exit and EPERM (#39299) --- .../Adapters/ClaudeAdapterV2.ts | 49 ++++++++++++++++--- .../ClaudeAgentSdkQueryRunner.test.ts | 2 + .../provider-core/src/server/failure.test.ts | 10 ++++ packages/provider-core/src/server/failure.ts | 20 +++++++- 4 files changed, 72 insertions(+), 9 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index 523d3f09c537e..3e1178912bf80 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -229,6 +229,7 @@ import { makeProviderFailure, makeProviderRetryTurnItem, PROVIDER_RETRY_BUDGET_MS, + providerProcessExitGuidance, } from "@t3tools/provider-core/server/failure"; import { turnScopedSelectionTransition } from "@t3tools/provider-core/server/selectionTransition"; import { providerMessageTextWithAttachmentPaths } from "@t3tools/provider-core/server/attachmentPrompt"; @@ -798,6 +799,19 @@ export class ClaudeConversationNotFoundError extends Schema.TaggedError()( + "ClaudeCodeStartupExitError", + { + status: Schema.String, + guidance: Schema.String, + cause: Schema.Defect(), + }, +) { + override get message(): string { + return `${this.status} before it started. ${this.guidance}`; + } +} + class ClaudeMcpRegistrationTimeoutError extends Schema.TaggedError()( "ClaudeMcpRegistrationTimeoutError", { phase: Schema.Literals(["initialize", "setMcpServers"]) }, @@ -922,20 +936,26 @@ const CLAUDE_PROCESS_EXIT_ERROR_CLASSES: ReadonlySet = new Set([ ]); // The SDK's exit Error appends Claude's stderr tail to `message`; `telemetryMessage` omits it. -function claudeProcessExitFailure( - cause: Cause.Cause, -): { readonly message: string; readonly code: string } | undefined { - const error = Cause.squash(cause); - const sdkError = isClaudeAgentSdkQueryRunnerError(error) ? error.cause : error; +function claudeProcessExit( + sdkError: unknown, +): { readonly status: string; readonly code: string } | undefined { if (typeof sdkError !== "object" || sdkError === null) return undefined; const { errorClass, telemetryMessage } = sdkError as Record; return typeof errorClass === "string" && CLAUDE_PROCESS_EXIT_ERROR_CLASSES.has(errorClass) && typeof telemetryMessage === "string" - ? { message: `${telemetryMessage}.`, code: errorClass } + ? { status: telemetryMessage, code: errorClass } : undefined; } +function claudeProcessExitFailure( + cause: Cause.Cause, +): { readonly message: string; readonly code: string } | undefined { + const error = Cause.squash(cause); + const exit = claudeProcessExit(isClaudeAgentSdkQueryRunnerError(error) ? error.cause : error); + return exit === undefined ? undefined : { message: `${exit.status}.`, code: exit.code }; +} + function closeClaudeQuery(queryRuntime: ClaudeQuery) { return Effect.try({ try: () => queryRuntime.close(), @@ -1752,13 +1772,28 @@ export const layerQueryRunner: Layer.Layer< ); } const refusedRoot = !answered && stderrTail.includes(CLAUDE_ROOT_REFUSAL); + const startupExit = answered ? undefined : claudeProcessExit(cause); + if (startupExit !== undefined) { + // The turn failure omits this output, so the log is the only place it is kept. + yield* Effect.logWarning("orchestration-v2.claude-startup-exit", { + threadId: input.threadId, + status: startupExit.status, + stderr: stderrTail, + }); + } return yield* queryRunnerError( refusedRoot ? new ClaudeCodeRootRefusalError({ cause }) : conversationMissing || (!answered && stderrTail.includes(CLAUDE_CONVERSATION_NOT_FOUND)) ? new ClaudeConversationNotFoundError({ cause }) - : cause, + : startupExit !== undefined + ? new ClaudeCodeStartupExitError({ + status: startupExit.status, + guidance: providerProcessExitGuidance(stderrTail), + cause, + }) + : cause, "fromAsyncIterable", ); }), diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts index 2a2a861ffb3ac..2bf2763c58c66 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts @@ -870,6 +870,8 @@ describe.skipIf(HostProcess.Platform.defaultValue() === "win32")("Claude CLI pro const unknown = yield* startupFailureMessage("token=sk-private-123"); assert.notInclude(unknown, "sk-private-123"); + // The exit status carries no private text and tells the user the CLI itself died. + assert.include(unknown, "Claude Code process exited with code 1"); const missingConversation = yield* startupFailureMessage( "No conversation found with session ID: sk-private-123", diff --git a/packages/provider-core/src/server/failure.test.ts b/packages/provider-core/src/server/failure.test.ts index a07ef21a62211..a29b60d4d25ae 100644 --- a/packages/provider-core/src/server/failure.test.ts +++ b/packages/provider-core/src/server/failure.test.ts @@ -163,6 +163,16 @@ it("names how the provider process exited and the stage it failed in, without it makeProviderFailure({ cause: { _tag: "AcpProcessExitedError", code: 1 } }).message, "The provider process exited with code 1. Check the server logs for the provider's output, then retry the turn.", ); + const denied = makeProviderFailure({ + cause: { + _tag: "CodexAppServerProcessExitedError", + code: 1, + stderr: "Error: Operation not permitted (os error 1) at /Users/private/Desktop", + }, + }).message; + assert.include(denied, "The provider process exited with code 1. It was denied access"); + assert.include(denied, "Files and Folders"); + assert.notInclude(denied, "/Users/private"); }); it("tells the user to sign in only when an ACP agent answers auth_required", () => { diff --git a/packages/provider-core/src/server/failure.ts b/packages/provider-core/src/server/failure.ts index c416596dd45d2..cfdb0eb3df9a6 100644 --- a/packages/provider-core/src/server/failure.ts +++ b/packages/provider-core/src/server/failure.ts @@ -67,6 +67,19 @@ const PROVIDER_FAILURE_CATEGORIES: Partial< }, }; +// macOS privacy protection (TCC) refuses a CLI the project folder with EPERM. +const PERMISSION_DENIED_OUTPUT = /\bEPERM\b|Operation not permitted/u; + +/** + * What to do after a provider CLI exits on its own. Only recognises the + * output; the output itself stays out of the message. + */ +export function providerProcessExitGuidance(output: unknown): string { + return typeof output === "string" && PERMISSION_DENIED_OUTPUT.test(output) + ? "It was denied access to a file or folder (EPERM). On macOS, allow T3 Code under System Settings > Privacy & Security > Files and Folders, or move the project out of Desktop, Documents, or Downloads, then retry the turn." + : "Check the server logs for the provider's output, then retry the turn."; +} + // codex_protocol::protocol::validate_thread_goal_objective const CODEX_GOAL_VALIDATION_MESSAGE = /^goal objective must (?:not be empty|be at most \d{1,6} characters)$/u; @@ -122,6 +135,7 @@ function curatedCauseMessages(cause: unknown): { case "ClaudeSettingsLaunchArgError": case "ClaudeMcpRegistrationTimeoutError": case "ClaudeCodeRootRefusalError": + case "ClaudeCodeStartupExitError": case "ClaudeConversationNotFoundError": case "CursorModelUnavailableError": case "CodexGoalObjectiveTooLongError": @@ -150,11 +164,13 @@ function curatedCauseMessages(cause: unknown): { } break; } - case "AcpProcessExitedError": { + case "AcpProcessExitedError": + case "CodexAppServerProcessExitedError": { const exit = `provider process exited${processExitStatus(cause)}`; const stage = category === undefined ? `The ${exit}` : `${category.summary}: the ${exit}`; + const guidance = providerProcessExitGuidance((cause as Record).stderr); return { - known: `${stage}. Check the server logs for the provider's output, then retry the turn.`, + known: `${stage}. ${guidance}`, category: categoryMessage(), }; } From c5badf4e408ef55d1352040e2fb557d8f36d411a Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Thu, 19 Nov 2026 21:24:37 +0100 Subject: [PATCH 54/97] fix(web): scope Git controls to the active checkout (#39305) Co-authored-by: Julius Marminge --- apps/web/src/components/GitActionsControl.tsx | 16 ++--- .../components/chat/ThreadDetailsPanel.tsx | 6 +- ...mit-message-stays-in-its-repository.e2e.ts | 69 +++++++++++++++++++ 3 files changed, 79 insertions(+), 12 deletions(-) create mode 100644 scripts/scenarios/failed-commit-message-stays-in-its-repository.e2e.ts diff --git a/apps/web/src/components/GitActionsControl.tsx b/apps/web/src/components/GitActionsControl.tsx index 897feb60e1e56..23b515c56c9ca 100644 --- a/apps/web/src/components/GitActionsControl.tsx +++ b/apps/web/src/components/GitActionsControl.tsx @@ -26,7 +26,7 @@ import type { } from "@t3tools/contracts"; import { useNavigate } from "@tanstack/react-router"; import * as Option from "effect/Option"; -import { useEffect, useEffectEvent, useId, useRef, useState } from "react"; +import { memo, useEffect, useEffectEvent, useId, useRef, useState } from "react"; import { useDeadlinePassed } from "../hooks/useDeadline"; import { useNowSecond } from "../hooks/useNowSecond"; import { flushSync } from "react-dom"; @@ -169,7 +169,6 @@ interface RunGitActionWithToastInput { interface InlineGitActionSuccess { readonly title: string; readonly description: string | null; - readonly scopeKey: string; readonly expiresAtMs: number; } @@ -962,7 +961,12 @@ export function PublishRepositoryDialog(props: PublishRepositoryDialogProps) { ); } -export default function GitActionsControl({ +export default memo(function GitActionsControl(props: GitActionsControlProps) { + const checkoutKey = JSON.stringify([props.activeThreadRef?.environmentId ?? null, props.gitCwd]); + return ; +}); + +function CheckoutGitActionsControl({ gitCwd, activeThreadRef, draftId, @@ -981,7 +985,6 @@ export default function GitActionsControl({ "thread branch metadata update", ); const activeEnvironmentId = activeThreadRef?.environmentId ?? null; - const successScopeKey = `${activeEnvironmentId ?? ""}\u0000${gitCwd ?? ""}`; const canWriteSourceControl = useEnvironmentScope( activeEnvironmentId, AuthSourceControlWriteScope, @@ -1020,8 +1023,7 @@ export default function GitActionsControl({ const sourceControlScope = { environmentId: activeEnvironmentId, cwd: gitCwd }; const vcsActionState = useAtomValue(vcsActionManager.stateAtom(sourceControlScope)); const inlineSuccessExpired = useDeadlinePassed(inlineSuccess?.expiresAtMs ?? null); - const visibleInlineSuccess = - inlineSuccess?.scopeKey === successScopeKey && !inlineSuccessExpired ? inlineSuccess : null; + const visibleInlineSuccess = inlineSuccessExpired ? null : inlineSuccess; const persistThreadBranchSync = (branch: string | null, manualSelection = false) => { if (!activeThreadRef) { @@ -1351,7 +1353,6 @@ export default function GitActionsControl({ }) : actionResult.toast.title, description: createdPullRequest ? null : (actionResult.toast.description ?? null), - scopeKey: successScopeKey, expiresAtMs: inlineSuccessExpiresAt(), }); return true; @@ -1438,7 +1439,6 @@ export default function GitActionsControl({ setInlineSuccess({ title, description, - scopeKey: successScopeKey, expiresAtMs: inlineSuccessExpiresAt(), }); })(); diff --git a/apps/web/src/components/chat/ThreadDetailsPanel.tsx b/apps/web/src/components/chat/ThreadDetailsPanel.tsx index d7c3090742008..d91c0156e8ca3 100644 --- a/apps/web/src/components/chat/ThreadDetailsPanel.tsx +++ b/apps/web/src/components/chat/ThreadDetailsPanel.tsx @@ -14,13 +14,13 @@ import type { ComposerThreadTarget, DraftId } from "../../composerDraftStore"; import { useT3ProjectFileScripts } from "../../hooks/useT3ProjectFileScripts"; import { type EnvMode, type EnvironmentOption } from "../BranchToolbar.logic"; import { BranchToolbar } from "../BranchToolbar"; -import BaseGitActionsControl from "../GitActionsControl"; +import GitActionsControl from "../GitActionsControl"; import ProjectScriptsControl, { type NewProjectScriptInput, type ProjectScriptActionResult, } from "../ProjectScriptsControl"; import { T, useGT } from "gt-react"; -import { memo, useState, type ComponentProps } from "react"; +import { useState, type ComponentProps } from "react"; import { ThreadDetailsCard } from "./ThreadDetailsCard"; import { OpenInPicker } from "./OpenInPicker"; import { ThreadDetailsSection } from "./ThreadDetailsSection"; @@ -46,8 +46,6 @@ import { } from "./threadDetailsPanelStyles"; import { Menu, MenuPopup } from "../ui/menu"; -const GitActionsControl = memo(BaseGitActionsControl); - interface ThreadDetailsPanelProps extends Pick< ComponentProps, "anchor" | "handle" diff --git a/scripts/scenarios/failed-commit-message-stays-in-its-repository.e2e.ts b/scripts/scenarios/failed-commit-message-stays-in-its-repository.e2e.ts new file mode 100644 index 0000000000000..8759bda10a5a9 --- /dev/null +++ b/scripts/scenarios/failed-commit-message-stays-in-its-repository.e2e.ts @@ -0,0 +1,69 @@ +/// +import { expect } from "e2e"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; + +import { run } from "./shell.ts"; +import { runPromise, test, WEB } from "./t3.ts"; + +test( + "A failed commit message stays in the repository it was written for", + WEB, + async ({ t3, app, browser, screen }) => { + const first = await t3.project("first-repository"); + const second = await t3.project("second-repository"); + const firstThread = await t3.thread({ + project: first, + title: "First checkout", + messages: ["First"], + }); + await t3.thread({ project: second, title: "Second checkout", messages: ["Second"] }); + + await runPromise( + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const hook = `${first}/.git/hooks/pre-commit`; + yield* fs.writeFileString( + hook, + "#!/bin/sh\necho 'Scenario hook rejected the commit' >&2\nexit 1\n", + ); + yield* fs.chmod(hook, 0o755); + yield* run("git", ["config", "core.hooksPath", ".git/hooks"], { cwd: first }); + yield* run("git", ["config", "user.name", "Scenario"], { cwd: first }); + yield* run("git", ["config", "user.email", "scenario@example.invalid"], { cwd: first }); + yield* fs.writeFileString(`${first}/first.txt`, "A new change in the first repository\n"); + yield* fs.writeFileString( + `${second}/second.txt`, + "A new change in the second repository\n", + ); + }), + ); + + await browser.setViewport({ width: 1920, height: 1000 }); + await t3.open(firstThread); + const openCommit = async (file: string) => { + await screen.getByRole("button", "Git action options").tap(); + await screen.getByRole("menuitem", "Commit", { exact: true }).tap(); + await screen.getByRole("button", `Open ${file} in editor`, { exact: true }).waitFor(); + }; + await openCommit("first.txt"); + await screen + .getByPlaceholder("Leave empty to auto-generate") + .fill("Describe the first checkout"); + await screen.getByRole("button", "Commit", { exact: true }).tap(); + await screen.getByText("Action failed", { exact: true }).waitFor(); + + // Navigate in the running app so the shared thread view stays mounted. + await screen.getByRole("button", /^Second checkout(?:,|$)/).tap(); + await openCommit("second.txt"); + await app.screenshot("commit-message-in-second-repository"); + const message = await browser.evaluate( + () => + "" + + document.querySelector( + 'textarea[placeholder="Leave empty to auto-generate"]', + )?.value, + ); + expect(message, "The second repository starts with a blank commit message").toBe(""); + }, +); From 3b199e77fb42556852648b50b545eebaec8c9430 Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Thu, 19 Nov 2026 21:29:35 +0100 Subject: [PATCH 55/97] fix: index displayed file line ranges in thread search (#39308) Co-authored-by: Julius Marminge --- .../src/orchestration-v2/ThreadFind.test.ts | 31 ++++++ .../server/src/orchestration-v2/ThreadFind.ts | 13 ++- apps/web/src/components/ChatMarkdown.tsx | 17 ++-- .../src/components/chat/threadFindStore.ts | 2 + apps/web/src/components/chat/useThreadFind.ts | 26 ++++- apps/web/src/markdown-links.ts | 37 +++---- packages/client-runtime/src/markdownImages.ts | 68 +------------ packages/contracts/src/orchestrationV2.ts | 1 + packages/shared/src/markdownLinks.ts | 97 ++++++++++++++++++- packages/shared/src/markdownPipeline.ts | 61 ++++++++---- packages/shared/src/threadFindText.test.ts | 53 ++++++++++ packages/shared/src/threadFindText.ts | 84 ++++++++++------ ...thread-find-matches-file-line-range.e2e.ts | 38 ++++++++ 13 files changed, 374 insertions(+), 154 deletions(-) create mode 100644 scripts/scenarios/thread-find-matches-file-line-range.e2e.ts diff --git a/apps/server/src/orchestration-v2/ThreadFind.test.ts b/apps/server/src/orchestration-v2/ThreadFind.test.ts index c3cb93da2214d..6c6d0232bfce7 100644 --- a/apps/server/src/orchestration-v2/ThreadFind.test.ts +++ b/apps/server/src/orchestration-v2/ThreadFind.test.ts @@ -463,6 +463,37 @@ describe("V2 thread find", () => { }).pipe(Effect.provide(layerTest)), ); + it.effect("searches only the picture file chips visible in the viewer's theme", () => + Effect.gen(function* () { + const projection = yield* setup; + yield* putItems([ + item( + "picture", + 1, + 'notes', + ), + item( + "fallback", + 2, + 'notes', + ), + ]); + const dark = { threadId, query: "L42–64", theme: "dark" } as const; + const light = { ...dark, theme: "light" } as const; + const darkResult = yield* projection.searchThread(dark); + assert.equal(darkResult.totalMatches, 1); + assert.equal(darkResult.match?.entryId, "picture"); + assert.equal( + (yield* projection.searchThread({ ...light, query: "notes.ts" })).totalMatches, + 0, + ); + const lightResult = yield* projection.searchThread(light); + assert.equal(lightResult.totalMatches, 1); + assert.equal(lightResult.match?.entryId, "fallback"); + assert.equal((yield* projection.searchThread(dark)).match?.entryId, "picture"); + }).pipe(Effect.provide(layerTest)), + ); + it.effect("refreshes file labels when the project cwd changes without a thread event", () => Effect.gen(function* () { const projection = yield* setup; diff --git a/apps/server/src/orchestration-v2/ThreadFind.ts b/apps/server/src/orchestration-v2/ThreadFind.ts index e0f732ba9425a..b2370dc83b23d 100644 --- a/apps/server/src/orchestration-v2/ThreadFind.ts +++ b/apps/server/src/orchestration-v2/ThreadFind.ts @@ -72,12 +72,14 @@ class TextKey extends Data.Class<{ hasContext: boolean; cwd: string | undefined; skills: NonNullable; + theme: OrchestrationV2SearchThreadInput["theme"]; }> {} function textKey( item: OrchestrationV2TurnItem, cwd: string | undefined, skills: TextKey["skills"], + theme: TextKey["theme"], ) { return new TextKey({ text: @@ -92,12 +94,13 @@ function textKey( hasContext: item.type === "user_message" && item.context !== undefined, cwd, skills, + theme, }); } function parseText(key: TextKey): readonly string[] { return key.role === "plan" - ? searchablePlanSegments(key.text, key.cwd) + ? searchablePlanSegments(key.text, key.cwd, key.theme) : (searchableMessageSegments( { role: key.role, @@ -107,6 +110,7 @@ function parseText(key: TextKey): readonly string[] { }, key.cwd, key.skills, + key.theme, ) ?? []); } @@ -207,6 +211,7 @@ export const makeThreadFind = Effect.fn("makeThreadFind")(function* ( cwd: Schema.optional(Schema.String), query: Schema.optional(Schema.String), skills: OrchestrationV2SearchThreadInput.fields.skills, + theme: OrchestrationV2SearchThreadInput.fields.theme, }), ), ); @@ -309,7 +314,7 @@ export const makeThreadFind = Effect.fn("makeThreadFind")(function* ( scans: CompletedScans, renderedSnapshot: RenderedSnapshot, ) { - const { threadId } = input; + const { threadId, theme } = input; const active = yield* sql<{ cwd: string | null }>` SELECT COALESCE(json_extract(t.payload_json, '$.worktreePath'), p.workspace_root) AS cwd FROM orchestration_v2_projection_threads t JOIN projection_projects p ON p.project_id = t.project_id @@ -322,6 +327,7 @@ export const makeThreadFind = Effect.fn("makeThreadFind")(function* ( cwd, query: input.query, skills: input.skills ?? [], + ...(theme === undefined ? {} : { theme }), }); const cached = scans.get(cacheKey); if (cached && cached.sequence === (yield* readRevision(cached.sourceThreadIds))) { @@ -334,6 +340,7 @@ export const makeThreadFind = Effect.fn("makeThreadFind")(function* ( threadId, cwd, skills: input.skills ?? [], + ...(theme === undefined ? {} : { theme }), }); const rendered = renderedSnapshot.current; if ( @@ -449,7 +456,7 @@ export const makeThreadFind = Effect.fn("makeThreadFind")(function* ( rendered = row; } else { const decoded = yield* decode(row); - const key = textKey(decoded.item, cwd, input.skills ?? []); + const key = textKey(decoded.item, cwd, input.skills ?? [], input.theme); const segments = decoded.item.type === "assistant_message" && decoded.item.text === "" && diff --git a/apps/web/src/components/ChatMarkdown.tsx b/apps/web/src/components/ChatMarkdown.tsx index 73274151172f6..f6062475ac25b 100644 --- a/apps/web/src/components/ChatMarkdown.tsx +++ b/apps/web/src/components/ChatMarkdown.tsx @@ -5,7 +5,9 @@ import { resolvePathLinkTarget } from "@t3tools/shared/fileLinks"; import { clientHostEnvironmentAtom } from "../state/clientHostEnvironment"; import { buildFileLinkParentSuffixByPath, fileLinkLabel } from "@t3tools/shared/fileLinks"; import { + isMarkdownFileLinkLabel, isWindowsDrivePathHref, + shouldRenderMarkdownImageAsFileLink, normalizeMarkdownLinkDestination, extractInlineCodeSpans, extractMarkdownLinkHrefs, @@ -23,6 +25,7 @@ import { CHAT_MARKDOWN_REMARK_PLUGINS, CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS, CHAT_MARKDOWN_REHYPE_PLUGINS, + chatMarkdownImageSource, decodeMarkdownLinkEscapes, remarkAssistantInsights, } from "@t3tools/shared/markdownPipeline"; @@ -156,7 +159,6 @@ import { markdownFileEditorTarget, resolveMarkdownFileHostPath, } from "../markdownFileHostPath"; -import { isMarkdownFileLinkLabel } from "@t3tools/shared/markdownLinks"; import { isElectron } from "../env"; import { readLocalApi } from "../localApi"; import { appAtomRegistry } from "../rpc/atomRegistry"; @@ -1586,18 +1588,11 @@ const CHAT_MARKDOWN_COMPONENTS = { {label} ); } - // A ``'s source for this theme, resolved like any other image. - const themeSrc = node?.properties?.[resolvedTheme === "dark" ? "dataDarkSrc" : "dataLightSrc"]; - const localSrc = typeof themeSrc === "string" ? undefined : node?.properties?.dataLocalSrc; + const { authoredSrc: srcString = "", classifiedSrc = "" } = + chatMarkdownImageSource(node?.properties ?? { src }, resolvedTheme) ?? {}; const markdownTitle = node?.properties?.dataMarkdownTitle; const standalone = node?.properties?.dataStandalone === true; - const authoredSrc = - typeof themeSrc === "string" ? themeSrc : typeof localSrc === "string" ? localSrc : src; const authoredTitle = typeof markdownTitle === "string" ? markdownTitle : title; - const srcString = - typeof authoredSrc === "string" ? normalizeMarkdownLinkDestination(authoredSrc) : ""; - const classifiedSrc = - typeof localSrc === "string" ? srcString.replaceAll("\\", "/") : srcString; const altText = alt ?? ""; const copyMarkdown = markdownImageCopy(altText, srcString, authoredTitle); const { className, style: _style, width, height, ...imageProps } = props; @@ -1634,7 +1629,7 @@ const CHAT_MARKDOWN_COMPONENTS = { /> ); } - if (mediaKind === null && imageSource._tag === "WorkspaceFile") { + if (shouldRenderMarkdownImageAsFileLink(imageSource, mediaKind)) { const fileLinkMeta = resolveMarkdownFileLinkMeta(srcString, cwd, imageBaseDir ?? cwd); if (fileLinkMeta) return fileLinkChip(fileLinkMeta, copyMarkdown, srcString); } diff --git a/apps/web/src/components/chat/threadFindStore.ts b/apps/web/src/components/chat/threadFindStore.ts index ea52de6c2747e..e3004c64adda0 100644 --- a/apps/web/src/components/chat/threadFindStore.ts +++ b/apps/web/src/components/chat/threadFindStore.ts @@ -10,9 +10,11 @@ import { messageSearchTokens, } from "@t3tools/shared/paletteSearch"; import { create } from "zustand"; +import type { ThemeAppearance } from "~/themePalette"; import type { ThreadFindPositionReader, ThreadFindStart } from "./threadFind"; export interface ThreadFindLocalSelection { + readonly theme: ThemeAppearance; readonly base: OrchestrationV2SearchThreadResult; readonly baseNavigationId: number; readonly activeIndex: number; diff --git a/apps/web/src/components/chat/useThreadFind.ts b/apps/web/src/components/chat/useThreadFind.ts index ada7955e1c2ad..f415e34586deb 100644 --- a/apps/web/src/components/chat/useThreadFind.ts +++ b/apps/web/src/components/chat/useThreadFind.ts @@ -3,9 +3,11 @@ import type { OrchestrationV2SearchThreadResult, ScopedThreadRef } from "@t3tool import { scopedThreadKey } from "@t3tools/client-runtime/environment"; import { useEffect, useEffectEvent, useRef, useState } from "react"; import { orchestrationEnvironment } from "~/state/orchestration"; +import { useRenderedAppearance } from "~/hooks/useTheme"; import { useThreadProjection } from "~/state/entities"; import { useEnvironmentQuery } from "~/state/query"; import { useDebouncedValue } from "~/state/queries"; +import type { ThemeAppearance } from "~/themePalette"; import { type ThreadFindMatch, type ThreadFindStart, stepThreadFindIndex } from "./threadFind"; import { CLOSED_THREAD_FIND, @@ -40,6 +42,11 @@ export function useThreadFind({ const isOpen = useThreadFindOpen(thread, enabled); const stored = useThreadFindStore(); const state = isOpen ? stored : CLOSED_THREAD_FIND; + const theme = useRenderedAppearance(); + const requestId = + state.localSelection && state.localSelection.theme !== theme + ? state.navigationId + : state.requestId; const setState = (update: (previous: ThreadFindState) => Partial) => useThreadFindStore.setState((previous) => previous.threadKey === threadKey ? update(previous) : previous, @@ -49,10 +56,11 @@ export function useThreadFind({ isOpen ? thread : null, state.query, state.offset, - state.requestId, + requestId, state.start, skills, progressive, + theme, ); const status: "loading" | "error" | null = remote.error ? "error" @@ -63,6 +71,7 @@ export function useThreadFind({ state.localSelection, remote.data, remote.navigationId, + theme, ); const count = remote.data?.totalMatches ?? 0; const activeIndex = localSelection?.activeIndex ?? remote.data?.activeIndex ?? 0; @@ -95,7 +104,12 @@ export function useThreadFind({ const step = (delta: number) => { if (count === 0 || counting) return; setState((previous) => { - const local = rebaseLocalSelection(previous.localSelection, remote.data, remote.navigationId); + const local = rebaseLocalSelection( + previous.localSelection, + remote.data, + remote.navigationId, + theme, + ); const pending = previous.navigationId !== (local?.navigationId ?? remote.navigationId); const selected = local?.match ?? remote.data?.match; const nextIndex = stepThreadFindIndex( @@ -125,6 +139,7 @@ export function useThreadFind({ ...previous, navigationId: nextNavigationId, localSelection: { + theme, base: remote.data, baseNavigationId: remote.navigationId, activeIndex: nextIndex, @@ -258,8 +273,9 @@ function rebaseLocalSelection( selection: ThreadFindLocalSelection | null, data: OrchestrationV2SearchThreadResult | null, navigationId: number, + theme: ThemeAppearance, ) { - if (!selection || !data) return null; + if (!selection || !data || selection.theme !== theme) return null; if (selection.base === data && selection.baseNavigationId === navigationId) return selection; if (navigationId >= selection.navigationId) return null; const entry = data.navigation?.find((entry) => entry.entryId === selection.match.entryId); @@ -276,6 +292,7 @@ function useServerResults( start: ThreadFindStart | undefined, skills: readonly InlineSkill[], progressive: boolean, + theme: ThemeAppearance, ) { const skillLabels = skills.map(({ name, displayName }) => ({ name, displayName })); const normalizedQuery = query.trim(); @@ -289,6 +306,7 @@ function useServerResults( input: { threadId, query: debouncedQuery, + theme, ...(start ? { start } : {}), ...(offset !== 0 ? { offset } : {}), skills: skillLabels, @@ -307,7 +325,7 @@ function useServerResults( } const result = useEnvironmentQuery(atom); const key = thread - ? JSON.stringify([thread.environmentId, thread.threadId, normalizedQuery, skillLabels]) + ? JSON.stringify([thread.environmentId, thread.threadId, normalizedQuery, skillLabels, theme]) : null; const [previous, setPrevious] = useState({ key, diff --git a/apps/web/src/markdown-links.ts b/apps/web/src/markdown-links.ts index b661af7c7e2fa..c3273b1fca025 100644 --- a/apps/web/src/markdown-links.ts +++ b/apps/web/src/markdown-links.ts @@ -4,8 +4,7 @@ import { inlineCodeFilePathCandidate, isRelativeFilePath, normalizeMarkdownLinkDestination, - parseMarkdownFileLink, - resolveMarkdownFileLinkTarget, + resolveMarkdownFileLink, } from "@t3tools/shared/markdownLinks"; import { parseFileUrlHref, splitFilePathPosition } from "@t3tools/shared/fileLinks"; @@ -76,31 +75,25 @@ export function resolveMarkdownFileLinkMeta( cwd?: string, baseDir: string | undefined = cwd, ): MarkdownFileLinkMeta | null { - const targetPath = resolveMarkdownFileLinkTarget(href, cwd, baseDir); - if (!targetPath) return null; - const source = href ? parseMarkdownFileLink(href) : null; - return { - ...buildFileLinkMetaFromTarget(targetPath, cwd), - ...(source?.endLine !== undefined ? { endLine: source.endLine } : {}), - workspaceLookupPath: - source !== null && - !isAbsolutePath(source.path) && - baseDir !== undefined && - workspaceRelativeFilePath(baseDir, cwd) === "." - ? source.path - : null, - }; -} - -function buildFileLinkMetaFromTarget(targetPath: string, cwd?: string) { - const { path, line, column } = splitFilePathPosition(targetPath); + const resolved = resolveMarkdownFileLink(href, cwd, baseDir); + if (!resolved) return null; + const { + sourcePath, + targetPath, + position: { path, ...lines }, + } = resolved; return { filePath: path, targetPath, displayPath: formatWorkspaceRelativePath(targetPath, cwd), workspaceRelativePath: workspaceRelativeFilePath(path, cwd), basename: fileBasename(path), - ...(line !== undefined ? { line } : {}), - ...(column !== undefined ? { column } : {}), + ...lines, + workspaceLookupPath: + !isAbsolutePath(sourcePath) && + baseDir !== undefined && + workspaceRelativeFilePath(baseDir, cwd) === "." + ? sourcePath + : null, }; } diff --git a/packages/client-runtime/src/markdownImages.ts b/packages/client-runtime/src/markdownImages.ts index 2d3de97dede1c..76383f08d30ac 100644 --- a/packages/client-runtime/src/markdownImages.ts +++ b/packages/client-runtime/src/markdownImages.ts @@ -1,73 +1,13 @@ import { - isNetworkPath, - isWindowsAbsolutePath, - workspaceRelativeFilePath, -} from "@t3tools/shared/path"; - -import { - markdownDestinationHostPath, normalizeMarkdownLinkDestination, splitMarkdownLinkSearchAndHash, } from "@t3tools/shared/markdownLinks"; -const DIRECT_IMAGE_SOURCE_PATTERN = /^(?:https?:|data:|blob:|\/\/)/i; -const URI_SCHEME_PATTERN = /^[A-Za-z][A-Za-z0-9+.-]*:/; - -export type MarkdownImageSource = - | { readonly _tag: "Direct"; readonly uri: string } - | { readonly _tag: "WorkspaceFile"; readonly path: string; readonly relative?: true } - | { readonly _tag: "Blocked" }; +export { + classifyMarkdownImageSource, + type MarkdownImageSource, +} from "@t3tools/shared/markdownLinks"; export function markdownImageSourceFragment(source: string): string { return splitMarkdownLinkSearchAndHash(normalizeMarkdownLinkDestination(source)).hash; } - -function joinWorkspacePath(workspaceRoot: string, relativePath: string): string { - const separator = isWindowsAbsolutePath(workspaceRoot) ? "\\" : "/"; - const root = workspaceRoot.replace(/[\\/]+$/, ""); - const path = relativePath.replace(/[\\/]/g, separator).replace(/^[\\/]+/, ""); - return `${root}${separator}${path}`; -} - -/** Rendering is not a click, so a network path loads only from the project's own share. */ -function hostFileSource( - path: string, - workspaceRoot: string | null | undefined, -): MarkdownImageSource { - return isNetworkPath(path) && workspaceRelativeFilePath(path, workspaceRoot) === null - ? { _tag: "Blocked" } - : { _tag: "WorkspaceFile", path }; -} - -/** - * Filesystem paths belong to the environment host and must never reach a - * browser or native image component without first becoming a signed asset URL. - */ -export function classifyMarkdownImageSource( - value: string | null | undefined, - workspaceRoot?: string | null, -): MarkdownImageSource { - if (value === null || value === undefined) return { _tag: "Blocked" }; - - const source = normalizeMarkdownLinkDestination(value); - if (source.length === 0 || source.startsWith("#") || source.startsWith("?")) { - return { _tag: "Blocked" }; - } - if (DIRECT_IMAGE_SOURCE_PATTERN.test(source)) { - return { _tag: "Direct", uri: source }; - } - - const path = markdownDestinationHostPath(source); - if (path === null) return { _tag: "Blocked" }; - if (/^file:/i.test(source)) return hostFileSource(path, workspaceRoot); - if (path.length === 0) return { _tag: "Blocked" }; - if (path.startsWith("/") || isWindowsAbsolutePath(path)) { - return hostFileSource(path, workspaceRoot); - } - if (URI_SCHEME_PATTERN.test(path) || path.startsWith("~/") || path.startsWith("~\\")) { - return { _tag: "Blocked" }; - } - if (!workspaceRoot) return { _tag: "Blocked" }; - - return { _tag: "WorkspaceFile", path: joinWorkspacePath(workspaceRoot, path), relative: true }; -} diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts index f59ac95c5cffb..33242f8dcdeac 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -4473,6 +4473,7 @@ export class OrchestrationGetWorkflowScriptError extends Schema.TaggedError, +): boolean { + return source._tag === "WorkspaceFile" && mediaKind === null; +} + export function isMarkdownFileLinkLabel(label: string, href: string): boolean { const destination = parseMarkdownFileLink(href); if (!destination) return false; @@ -494,10 +560,35 @@ export function resolveMarkdownFileLinkTarget( cwd?: string, baseDir: string | undefined = cwd, ): string | null { - if (!href) return null; - const target = parseMarkdownFileLink(href); - if (!target) return null; + return resolveMarkdownFileLink(href, cwd, baseDir)?.targetPath ?? null; +} + +/** Resolves the displayed position and the editor target, which opens at the start line. */ +export function resolveMarkdownFileLink( + href: string | undefined, + cwd?: string, + baseDir: string | undefined = cwd, +): { sourcePath: string; targetPath: string; position: FilePathPosition } | null { + const source = href ? parseMarkdownFileLink(href) : null; + if (!source) return null; + const targetPath = resolveParsedFileLinkTarget(source, cwd, baseDir); + if (!targetPath) return null; + return { + sourcePath: source.path, + targetPath, + position: { + ...splitFilePathPosition(targetPath), + ...(source.endLine !== undefined ? { endLine: source.endLine } : {}), + }, + }; +} + +function resolveParsedFileLinkTarget( + target: FilePathPosition, + cwd: string | undefined, + baseDir: string | undefined, +): string | null { const pathWithPosition = formatFilePathPosition(target); if (!isRelativeFilePath(pathWithPosition)) { // Opening a network path makes Windows sign in to its host with the user's diff --git a/packages/shared/src/markdownPipeline.ts b/packages/shared/src/markdownPipeline.ts index 728187e43ba94..53b49a03762a3 100644 --- a/packages/shared/src/markdownPipeline.ts +++ b/packages/shared/src/markdownPipeline.ts @@ -840,36 +840,61 @@ const imageSourceProcessor = unified() .use(remarkRehype, { allowDangerousHtml: true }) .use(CHAT_MARKDOWN_REHYPE_PLUGINS); +export type ChatMarkdownImageProperties = { + readonly src?: unknown; + readonly dataLocalSrc?: unknown; + readonly dataDarkSrc?: unknown; + readonly dataLightSrc?: unknown; +}; + +/** Keep the authored path for file links and normalize Windows separators for classification. */ +export function chatMarkdownImageSource( + properties?: ChatMarkdownImageProperties, + theme?: "dark" | "light", +) { + const themeSrc = + theme === undefined + ? undefined + : properties?.[theme === "dark" ? "dataDarkSrc" : "dataLightSrc"]; + const localSrc = typeof themeSrc === "string" ? undefined : properties?.dataLocalSrc; + const source = + typeof themeSrc === "string" + ? themeSrc + : typeof localSrc === "string" + ? localSrc + : properties?.src; + if (typeof source !== "string") return null; + const authoredSrc = normalizeMarkdownLinkDestination(source); + return { + authoredSrc, + classifiedSrc: typeof localSrc === "string" ? authoredSrc.replaceAll("\\", "/") : authoredSrc, + }; +} + interface ImageSourceNode { readonly type: string; readonly tagName?: string; - readonly properties?: { - readonly src?: unknown; - readonly dataLocalSrc?: unknown; - readonly dataDarkSrc?: unknown; - readonly dataLightSrc?: unknown; - }; + readonly properties?: ChatMarkdownImageProperties; readonly children?: ReadonlyArray; } /** - * The sources of the images chat markdown shows, read as ChatMarkdown's `img` renderer reads - * them. Code, comments, and plain links show no image, so they add none. + * Collect the fallback and every theme variant so images are available to all viewers. */ export function chatMarkdownImageSources(markdown: string): Array { const sources: Array = []; const visit = (node: ImageSourceNode) => { if (node.type === "element" && node.tagName === "img") { - const { src, dataLocalSrc, dataDarkSrc, dataLightSrc } = node.properties ?? {}; - // The sanitizer drops a Windows drive path from `src`; the renderer reads it from here. - if (typeof dataLocalSrc === "string") { - sources.push(normalizeMarkdownLinkDestination(dataLocalSrc).replaceAll("\\", "/")); - } else if (typeof src === "string") { - sources.push(normalizeMarkdownLinkDestination(src)); - } - // A `` shows one of these instead, by the viewer's theme. - for (const variant of [dataDarkSrc, dataLightSrc]) { - if (typeof variant === "string") sources.push(normalizeMarkdownLinkDestination(variant)); + const properties = node.properties; + const fallback = chatMarkdownImageSource(properties); + if (fallback) sources.push(fallback.classifiedSrc); + for (const [theme, variant] of [ + ["dark", properties?.dataDarkSrc], + ["light", properties?.dataLightSrc], + ] as const) { + if (typeof variant !== "string") continue; + const source = chatMarkdownImageSource(properties, theme); + if (source) sources.push(source.classifiedSrc); } } node.children?.forEach(visit); diff --git a/packages/shared/src/threadFindText.test.ts b/packages/shared/src/threadFindText.test.ts index 663ba33840db3..489e8e39ddf0f 100644 --- a/packages/shared/src/threadFindText.test.ts +++ b/packages/shared/src/threadFindText.test.ts @@ -148,6 +148,50 @@ it("keeps fence paths literal and indexes file-chip labels in user messages", () ).toEqual(["file.ts · L42"]); }); +it.each([ + { + source: "user", + cwd: "/workspace/repo", + text: "See [src/notes.ts](src/notes.ts#L42-L64) and [src/notes.ts](src/notes.ts#L42-L70)", + expected: ["See notes.ts · L42–64 and notes.ts · L42–70"], + }, + { + source: "assistant", + cwd: "/workspace/repo", + text: "[Read notes](src/notes.ts:42-64) and `test/notes.ts:42-64`", + expected: ["Read notes notes.ts · repo/src · L42–64 and notes.ts · repo/test · L42–64"], + }, + { + source: "assistant", + cwd: undefined, + text: [ + "[notes.ts](file:///tmp/notes.ts#L42-64) [relative](src/notes.ts#L42-L64)", + "[web](https://example.com/notes.ts#L42-L64) [reverse](/tmp/notes.ts#L64-L42)", + "`port:42-64`", + "\n```text\n/tmp/notes.ts:42-64\n```", + ].join(" "), + expected: [ + "notes.ts · L42–64 relative web reverse notes.ts · L64 port:42-64", + "/tmp/notes.ts:42-64\n", + ], + }, + { + source: "plan", + cwd: String.raw`\\server\share\repo`, + text: "[notes.ts](file://server/share/repo/notes.ts#L42-L64) [other](file://other/share/notes.ts#L42-L64)", + expected: ["Proposed plan", "notes.ts · L42–64 other"], + }, +] as const)( + "indexes the displayed file range in $source text", + ({ source, cwd, text, expected }) => { + const segments = + source === "plan" + ? searchablePlanSegments(text, cwd) + : searchableMessageSegments({ role: source, text, streaming: false }, cwd); + expect(segments).toEqual(expected); + }, +); + it("indexes nested disclosure summaries and bodies in rendered order", () => { expect( assistantSegments( @@ -188,3 +232,12 @@ it("indexes insight bodies without hidden fences and keeps user and plan text li expect(searchablePlanSegments(text).join("\n")).toContain("★ Insight"); expect(assistantSegments(`\`\`\`text\n${text}\n\`\`\``)?.join("\n")).toContain("★ Insight"); }); + +it("indexes image destinations rendered as file chips", () => { + expect( + assistantSegments( + "![note](src/notes.ts#L42-L64) ![screenshot](src/screenshot.png#L42-L64)", + "/workspace/repo", + ), + ).toEqual(["notes.ts · L42–64 "]); +}); diff --git a/packages/shared/src/threadFindText.ts b/packages/shared/src/threadFindText.ts index fd0f7ec505cca..fc2b446f40985 100644 --- a/packages/shared/src/threadFindText.ts +++ b/packages/shared/src/threadFindText.ts @@ -8,18 +8,17 @@ import { renderCodexInlineDirectivesAsMarkdown, } from "./codexMarkdownDirectives.ts"; import { codexArtifactTemplatePresentationLabel } from "./codexArtifactTemplates.ts"; +import { buildFileLinkParentSuffixByPath, fileLinkLabel } from "./fileLinks.ts"; import { - buildFileLinkParentSuffixByPath, - splitFilePathPosition, - fileLinkLabel, -} from "./fileLinks.ts"; -import { + classifyMarkdownImageSource, isMarkdownFileLinkLabel, extractMarkdownLinkHrefs, extractInlineCodeSpans, inlineCodeFilePathCandidate, - resolveMarkdownFileLinkTarget, + resolveMarkdownFileLink, + shouldRenderMarkdownImageAsFileLink, } from "./markdownLinks.ts"; +import { mediaKindFromPath } from "./mediaPreview.ts"; import { upgradeLegacyContextMessage } from "./composerContextLegacy.ts"; import { isAttachmentOnlyBootstrapPrompt, @@ -38,7 +37,9 @@ import { CHAT_MARKDOWN_REMARK_PLUGINS, CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS, CHAT_USER_MARKDOWN_REMARK_PLUGINS, + chatMarkdownImageSource, decodeMarkdownLinkEscapes, + type ChatMarkdownImageProperties, } from "./markdownPipeline.ts"; // Inline wrappers (including Shiki token spans) must not split a search phrase. @@ -103,9 +104,8 @@ interface TextTree { readonly type: string; readonly tagName?: string; readonly value?: string; - readonly properties?: { + readonly properties?: ChatMarkdownImageProperties & { readonly href?: unknown; - readonly src?: unknown; readonly dataInlineCode?: unknown; }; readonly children?: ReadonlyArray; @@ -113,11 +113,21 @@ interface TextTree { function markdownThreadFindText( markdown: string, - userMessage = false, - cwd?: string, - skills: readonly InlineSkill[] = [], - lineBreaks = false, - renderInsights = false, + { + userMessage = false, + cwd, + skills = [], + lineBreaks = false, + renderInsights = false, + theme, + }: { + userMessage?: boolean; + cwd: string | undefined; + skills?: readonly InlineSkill[]; + lineBreaks?: boolean; + renderInsights?: boolean; + theme: "dark" | "light" | undefined; + }, ): string[] { const processor = userMessage ? userProcessor @@ -136,8 +146,8 @@ function markdownThreadFindText( ), ...extractInlineCodeSpans(markdown).flatMap((span) => inlineCodeFilePathCandidate(span) ?? []), ].flatMap((href) => { - const target = resolveMarkdownFileLinkTarget(href, cwd); - return target ? [splitFilePathPosition(target).path] : []; + const resolved = resolveMarkdownFileLink(href, cwd); + return resolved ? [resolved.position.path] : []; }); const parentSuffixes = buildFileLinkParentSuffixByPath(paths); const segments: string[] = []; @@ -164,6 +174,19 @@ function markdownThreadFindText( let candidate: string | null = null; if (node.tagName === "a" && typeof href === "string") { candidate = href; + } else if (node.tagName === "img") { + const source = chatMarkdownImageSource(node.properties, theme); + if (source) { + const { authoredSrc, classifiedSrc } = source; + if ( + shouldRenderMarkdownImageAsFileLink( + classifyMarkdownImageSource(classifiedSrc, cwd), + mediaKindFromPath(classifiedSrc), + ) + ) { + candidate = authoredSrc; + } + } } else if ( node.tagName === "code" && !inPre && @@ -173,14 +196,13 @@ function markdownThreadFindText( (node.children ?? []).map((child) => child.value ?? "").join(""), ); } - const target = candidate ? resolveMarkdownFileLinkTarget(candidate, cwd) : null; - if (target) { + const resolved = candidate ? resolveMarkdownFileLink(candidate, cwd) : null; + if (candidate && resolved) { const labelText = (node: TextTree): string => node.value ?? (node.children ?? []).map(labelText).join(""); const label = labelText(node); - if (node.tagName === "a" && candidate && !isMarkdownFileLinkLabel(label, candidate)) - text += `${label} `; - text += fileLinkLabel(splitFilePathPosition(target), parentSuffixes); + if (node.tagName === "a" && !isMarkdownFileLinkLabel(label, candidate)) text += `${label} `; + text += fileLinkLabel(resolved.position, parentSuffixes); return; } } @@ -222,10 +244,14 @@ function markdownThreadFindText( } /** Plans render `$skill` tokens literally (no skill chips), so they are indexed as written. */ -export function searchablePlanSegments(markdown: string, cwd?: string): readonly string[] { +export function searchablePlanSegments( + markdown: string, + cwd?: string, + theme?: "dark" | "light", +): readonly string[] { return [ proposedPlanTitle(markdown) ?? "Proposed plan", - ...markdownThreadFindText(stripDisplayedPlanMarkdown(markdown), false, cwd, []), + ...markdownThreadFindText(stripDisplayedPlanMarkdown(markdown), { cwd, theme }), ]; } @@ -233,20 +259,20 @@ export function searchableMessageSegments( message: Pick, cwd?: string, skills: readonly InlineSkill[] = [], + theme?: "dark" | "light", ): readonly string[] | null { if (message.role === "user") { // Clients hide this prompt, so find must not match text nobody can see. if (isAttachmentOnlyBootstrapPrompt(message.text)) return []; const text = message.context ? message.text : upgradeLegacyContextMessage(message.text).text; - return markdownThreadFindText(text, true, cwd, skills); + return markdownThreadFindText(text, { userMessage: true, cwd, skills, theme }); } if (message.role !== "assistant") return null; - return markdownThreadFindText( - message.text || (message.streaming ? "" : "(empty response)"), - false, + return markdownThreadFindText(message.text || (message.streaming ? "" : "(empty response)"), { cwd, skills, - shouldPreserveAssistantLineBreaks(message.text), - true, - ); + lineBreaks: shouldPreserveAssistantLineBreaks(message.text), + renderInsights: true, + theme, + }); } diff --git a/scripts/scenarios/thread-find-matches-file-line-range.e2e.ts b/scripts/scenarios/thread-find-matches-file-line-range.e2e.ts new file mode 100644 index 0000000000000..abc5eeb6d4648 --- /dev/null +++ b/scripts/scenarios/thread-find-matches-file-line-range.e2e.ts @@ -0,0 +1,38 @@ +import { expect } from "e2e"; + +import { test, WEB } from "./t3.ts"; + +test( + "Find in thread matches the displayed line range of a file link", + WEB, + async ({ t3, app, screen, browser }) => { + const project = await t3.project("demo", { "src/notes.ts": "// Notes\n".repeat(64) }); + const thread = await t3.thread({ + project, + title: "File review", + messages: ["See [src/notes.ts](src/notes.ts#L42-L64)"], + }); + await t3.open(thread); + await screen.getByRole("button", /^Agent See/).tap(); + await browser + .locator("[data-user-message-body]") + .getByText("notes.ts · L42–64", { exact: true }) + .waitFor(); + + await browser.keyboard.press("Control+f"); + await screen.getByRole("searchbox", "Find in thread").fill("L42–64"); + try { + await expect + .poll( + () => + browser.evaluate( + 'document.querySelector("[data-thread-find-bar] span[aria-hidden]")?.textContent ?? ""', + ), + { message: "Find in thread counts the displayed line range as a match" }, + ) + .toBe("1/1"); + } finally { + await app.screenshot("file-range-find-result"); + } + }, +); From b68d29b2f75812f147e09db5cdd4f12c32b4ff19 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 19 Nov 2026 12:32:43 -0800 Subject: [PATCH 56/97] fix(server): storage cleanup removes clean detached worktrees whose commits are on a branch (#34967) --- apps/server/src/storageCleanup.test.ts | 30 ++++++++++++++++++++++-- apps/server/src/storageCleanup.ts | 32 +++++++++++++++++++++++++- 2 files changed, 59 insertions(+), 3 deletions(-) diff --git a/apps/server/src/storageCleanup.test.ts b/apps/server/src/storageCleanup.test.ts index 42e1df142e8f7..42548c948a83a 100644 --- a/apps/server/src/storageCleanup.test.ts +++ b/apps/server/src/storageCleanup.test.ts @@ -3261,8 +3261,6 @@ describe("storage cleanup reports and local file policies", () => { const { service, fs, repo, worktree, command, fullStatusCalls, threadBranches } = yield* cleanupFixture(); const changed = { outcome: "kept", reason: "Repository or branch changed" }; - yield* command(worktree, ["checkout", "--detach"]); - expect((yield* service.runNow).entries[0]).toMatchObject(changed); yield* command(worktree, ["switch", "--orphan", "other"]); expect((yield* service.runNow).entries[0]).toMatchObject(changed); yield* command(worktree, ["tag", "feature", "feature"]); @@ -3293,6 +3291,34 @@ describe("storage cleanup reports and local file policies", () => { }), ), ); + it.live("removes a clean detached worktree only when every commit is on a branch", () => + runCleanupTest( + Effect.gen(function* () { + const { service, fs, worktree, command } = yield* cleanupFixture(); + yield* command(worktree, ["checkout", "--detach"]); + yield* fs.writeFileString(`${worktree}/tracked.txt`, "unpushed\n"); + yield* command(worktree, ["commit", "-am", "unpushed"]); + expect((yield* service.runNow).entries[0]).toMatchObject({ outcome: "kept" }); + yield* command(worktree, ["checkout", "--detach", "main"]); + yield* command(worktree, ["-c", "sequence.editor=echo break >>", "rebase", "-i", "--root"]); + expect((yield* service.runNow).entries[0]).toMatchObject({ outcome: "kept" }); + yield* command(worktree, ["rebase", "--abort"]); + yield* command(worktree, ["checkout", "-b", "topic", "main"]); + yield* command(worktree, ["commit", "--allow-empty", "-m", "topic"]); + yield* command(worktree, ["checkout", "--detach", "main"]); + yield* fs.writeFileString(`${worktree}/tracked.txt`, "autostashed\n"); + yield* command(worktree, ["merge", "--autostash", "--no-ff", "--no-commit", "topic"]); + expect((yield* service.runNow).entries[0]).toMatchObject({ outcome: "kept" }); + yield* command(worktree, ["merge", "--abort"]); + expect(yield* fs.readFileString(`${worktree}/tracked.txt`)).toBe("autostashed\n"); + yield* command(worktree, ["checkout", "--", "tracked.txt"]); + yield* command(worktree, ["bisect", "start"]); + expect((yield* service.runNow).entries[0]).toMatchObject({ outcome: "kept" }); + yield* command(worktree, ["bisect", "reset"]); + expect((yield* service.runNow).entries[0]).toMatchObject({ outcome: "removed" }); + }), + ), + ); it.live.each([ ["any-local-files", ".env", "kept"], ["uncommitted-changes", ".env", "removed"], diff --git a/apps/server/src/storageCleanup.ts b/apps/server/src/storageCleanup.ts index ff5f003a9d21e..cbb7574befe7d 100644 --- a/apps/server/src/storageCleanup.ts +++ b/apps/server/src/storageCleanup.ts @@ -729,7 +729,37 @@ const make = Effect.gen(function* () { // Detached HEAD exits 1; full refs avoid shortening when a tag shares the branch name. const head = yield* read(["symbolic-ref", "--quiet", "HEAD"], 1); if (head === null) return true; - const ref = head.exitCode === 0 ? head.stdout.trim() : ""; + // Removal keeps branches but drops a detached HEAD, so only commits held elsewhere are safe. + if (head.exitCode !== 0) { + // A paused rebase, merge or bisect would lose its progress (and any autostash) on removal. + const operations = yield* read([ + "rev-parse", + "--git-path", + "rebase-merge", + "--git-path", + "rebase-apply", + "--git-path", + "MERGE_HEAD", + "--git-path", + "MERGE_AUTOSTASH", + "--git-path", + "BISECT_LOG", + ]); + if (operations === null) return true; + for (const state of operations.stdout.trim().split(/\r?\n/)) { + if (yield* fs.exists(path.resolve(cwd, state))) return true; + } + const unreachable = yield* read([ + "rev-list", + "--max-count=1", + "HEAD", + "--not", + "--branches", + "--remotes", + ]); + return unreachable === null || unreachable.stdout.trim() !== ""; + } + const ref = head.stdout.trim(); const name = ref.startsWith("refs/heads/") ? ref.slice("refs/heads/".length).trim() : null; return name !== branch; }); From e7b61491a3a93c2562c95d60c281c81c71c00688 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 19 Nov 2026 12:33:41 -0800 Subject: [PATCH 57/97] fix(server): a delivered handoff of a failed run is not re-sent to later fresh sessions (#39281) --- .../orchestration-v2/ProviderTurnStartService.ts | 15 +++++++++++++-- .../testkit/ProviderSwitch.integration.test.ts | 3 ++- 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts index 3a9313ac45475..8c2c4eb3bea04 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts @@ -549,9 +549,20 @@ export const layer: Layer.Layer< projection.runs.some( (source) => source.id === handoff.targetRunId && - (source.status === "failed" || + // A settled delivery retires history of this thread: the session that took it + // holds it, and a fresh session starts from a full summary of the thread. That + // summary lacks another thread's history (a fork source, a merge-back). + (((source.status === "failed" || source.status === "interrupted" || - source.status === "cancelled" || + source.status === "cancelled") && + !( + (handoff.delivery?.status === "injected" || + handoff.delivery?.status === "inline") && + handoff.fromProviderThreadIds.length > 0 && + handoff.fromProviderThreadIds.every((id) => + projection.providerThreads.some((candidate) => candidate.id === id), + ) + )) || (source.status === "completed" && handoff.delivery === undefined && // Compaction and /goal turns defer history to the next turn. diff --git a/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts b/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts index c2826eb6a1aae..8b9fc1087a574 100644 --- a/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts +++ b/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts @@ -2212,7 +2212,8 @@ describe("orchestration v2 provider switching", () => { ["completed", "failed", "completed", "completed"], ); const run4NativeThreadId = (yield* Ref.get(capturedTurns)).at(-1)?.nativeThreadId; - assert.equal( + // Run 3's summary already covers run 2's handoff, so run 4's fresh session must not get it again. + assert.notEqual( projection.contextHandoffs.find( (handoff) => handoff.targetRunId === projection.runs[1]?.id, )?.delivery?.nativeThreadId, From 56cd65316495164fd27bef6594554e75f1a03e18 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 19 Nov 2026 12:37:56 -0800 Subject: [PATCH 58/97] fix(mobile): a thread's goal pill can be cleared or resumed (#39283) Co-authored-by: ravdeep kainth Co-authored-by: voida6 --- .../features/threads/NewTaskDraftScreen.tsx | 1 + .../features/threads/ThreadDetailScreen.tsx | 48 ++++++++++++++++++- .../features/threads/ThreadRouteScreen.tsx | 1 + .../threads/floating-working-control.tsx | 47 ++++++++++-------- .../threads/floating-working-status.ts | 7 ++- apps/mobile/src/i18n/translations/de.json | 4 ++ apps/mobile/src/i18n/translations/en.json | 4 ++ apps/mobile/src/i18n/translations/es.json | 4 ++ apps/mobile/src/i18n/translations/fr.json | 4 ++ apps/mobile/src/i18n/translations/ja.json | 4 ++ apps/mobile/src/i18n/translations/ko.json | 4 ++ apps/mobile/src/i18n/translations/pt-BR.json | 4 ++ apps/mobile/src/i18n/translations/ru.json | 4 ++ apps/mobile/src/i18n/translations/sv.json | 4 ++ apps/mobile/src/i18n/translations/zh.json | 4 ++ apps/mobile/src/state/thread-outbox-model.ts | 2 + .../src/state/thread-task-permissions.test.ts | 32 +++++++++++++ .../src/state/threadOutboxDelivery.test.ts | 24 ++++++++++ apps/mobile/src/state/threadOutboxDelivery.ts | 8 ++++ .../src/state/use-thread-composer-state.ts | 45 +++++++++++++++++ 20 files changed, 234 insertions(+), 21 deletions(-) diff --git a/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx b/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx index a7d32c8788c85..65135ade77956 100644 --- a/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx +++ b/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx @@ -1086,6 +1086,7 @@ export function NewTaskDraftScreen(props: { onResumeQueue={null} onSendMessage={handleStart} offersSideChat={false} + onSendCommand={async () => null} onReconnectEnvironment={() => onReconnectEnvironment(selectedProject.environmentId)} canSwitchThreadProvider onRespondToApproval={async () => {}} diff --git a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx index cf8adb7ac3581..7df9f595d8553 100644 --- a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx +++ b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx @@ -193,7 +193,11 @@ import { FLOATING_WORKING_CONTROL_COVERAGE, FloatingWorkingControl, } from "./floating-working-control"; -import { connectionFloatingStatus, type FloatingWorkingStatus } from "./floating-working-status"; +import { + connectionFloatingStatus, + type FloatingStatusAction, + type FloatingWorkingStatus, +} from "./floating-working-status"; import type { ThreadStatusLineModel } from "./thread-context-divider"; import { derivePendingUserInputMaxHeight, @@ -311,6 +315,8 @@ export interface ThreadDetailScreenProps { ) => Promise, onWillEnqueue?: () => void, ) => Promise; + /** Queues a standalone text command, such as `/goal clear`, without touching the draft. */ + readonly onSendCommand: (text: string) => Promise; readonly onReconnectEnvironment: () => void; readonly canSwitchThreadProvider: boolean; readonly onRespondToApproval: ApprovalResponder; @@ -716,6 +722,21 @@ function ThreadDetailBody( ); } }; + const [goalCommandPending, setGoalCommandPending] = useState(false); + const runGoalCommand = async (command: string) => { + if (goalCommandPending || !props.canOperateThread) return; + setGoalCommandPending(true); + // No `finally`: React Compiler cannot lower it. + try { + await props.onSendCommand(command); + } catch (error) { + Dialog.alert( + gt("Could not update goal"), + error instanceof Error ? error.message : gt("Try again."), + ); + } + setGoalCommandPending(false); + }; const pendingBackgroundWork = presentPendingBackgroundWork( props.selectedThread.pendingBackgroundTasks, messages, @@ -860,10 +881,35 @@ function ThreadDetailBody( } if (props.selectedThread.goal !== null && contentPresentationKind === "ready") { const goal = presentProviderGoal(props.selectedThread.goal, false, messages); + const goalDriver = props.serverConfig?.providers.find( + (provider) => provider.instanceId === props.selectedThread.modelSelection.instanceId, + )?.driver; + const goalAction = ( + label: string, + accessibilityLabel: string, + command: string, + ): FloatingStatusAction => ({ + label, + accessibilityLabel, + disabled: !props.canOperateThread || goalCommandPending, + onPress: () => void runGoalCommand(command), + }); + // The server rejects Antigravity goal controls and Claude resume. Resume would stop + // unrelated work, so it waits for the thread to go idle. + const goalActions = + goalDriver === "antigravity" + ? [] + : [ + ...(goal.canResume && goalDriver !== "claudeAgent" && !props.activeThreadBusy + ? [goalAction(gt("Resume"), gt("Resume goal"), "/goal resume")] + : []), + goalAction(gt("Clear"), gt("Clear goal"), "/goal clear"), + ]; return { kind: "goal", label: goal.title, accessibilityLabel: `${goal.title}: ${goal.objective}`, + actions: goalActions, }; } if (extensionStatus !== null && contentPresentationKind === "ready") { diff --git a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx index 26ade22fe09c5..9d9cddd644e36 100644 --- a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx +++ b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx @@ -1125,6 +1125,7 @@ function ThreadRouteContent( onResumeQueue={composer.canResume ? handleResumeQueue : null} onSendMessage={composer.onSendMessage} offersSideChat={composer.sideChatUnavailableReason === null} + onSendCommand={composer.onSendCommand} onReconnectEnvironment={handleReconnectEnvironment} canSwitchThreadProvider={composer.canSwitchThreadProvider} onRespondToApproval={requests.onRespondToApproval} diff --git a/apps/mobile/src/features/threads/floating-working-control.tsx b/apps/mobile/src/features/threads/floating-working-control.tsx index c9e4bb9b82476..993d7999baf8b 100644 --- a/apps/mobile/src/features/threads/floating-working-control.tsx +++ b/apps/mobile/src/features/threads/floating-working-control.tsx @@ -1,7 +1,7 @@ import type { SubagentPillSegment } from "@t3tools/client-runtime/state/thread-subagents"; import { GlassContainer, GlassView } from "expo-glass-effect"; import { useGT } from "gt-react-native"; -import { type ReactNode, useEffect, useRef, useState } from "react"; +import { Fragment, type ReactNode, useEffect, useRef, useState } from "react"; import { type LayoutChangeEvent, Pressable, useWindowDimensions, View } from "react-native"; import Animated, { Easing, @@ -23,7 +23,7 @@ import { ControlPill } from "../../components/ui/ControlPill"; import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../../native/native-glass"; import { BrowserPreviewButton } from "../browser/browser-preview-button"; import { DevicePreviewButton } from "../devices/device-preview-button"; -import type { FloatingWorkingStatus } from "./floating-working-status"; +import type { FloatingStatusAction, FloatingWorkingStatus } from "./floating-working-status"; import { ShimmeringWorkContent } from "./thread-work-log"; const CONTROL_HEIGHT = 38.5; @@ -83,7 +83,12 @@ export function FloatingWorkingControl(props: { const extensionStatus = props.extensionStatus ?? null; const extensionOnly = props.status?.kind === "extension"; const useGlass = NATIVE_LIQUID_GLASS_SUPPORTED && !extensionOnly; - const action = props.status?.kind === "stop" ? props.status.action : null; + const actions: ReadonlyArray = + props.status?.kind === "goal" + ? props.status.actions + : props.status?.kind === "stop" && props.status.action !== null + ? [props.status.action] + : []; const [agentsWidth, setAgentsWidth] = useState(0); const hasQueue = props.queuedCount > 0; const hasPreview = props.devicePreview !== null || props.browserPreview !== null; @@ -96,7 +101,7 @@ export function FloatingWorkingControl(props: { 0, Math.min(overlayWidth, windowWidth) - reservedWidth - - (action !== null ? actionWidth : 0) - + (actions.length > 0 ? actionWidth : 0) - (hasQueue ? queueWidth : 0) - (hasAgents ? agentsWidth : 0) - (hasPreview ? previewWidth : 0), @@ -167,7 +172,7 @@ export function FloatingWorkingControl(props: { const capsuleInteractive = statusInteractive || extensionStatus !== null || - action !== null || + actions.length > 0 || hasQueue || hasAgents || hasPreview; @@ -215,24 +220,28 @@ export function FloatingWorkingControl(props: { ) : null} - {action !== null ? ( + {actions.length > 0 ? ( setActionWidth(settleWidth(event.nativeEvent.layout.width))} className="h-11 flex-row items-center" > - - - - {action.label} - - + {actions.map((action) => ( + + + + + {action.label} + + + + ))} ) : null} {hasPreview ? ( diff --git a/apps/mobile/src/features/threads/floating-working-status.ts b/apps/mobile/src/features/threads/floating-working-status.ts index f699276ae2d86..35b3578b63e18 100644 --- a/apps/mobile/src/features/threads/floating-working-status.ts +++ b/apps/mobile/src/features/threads/floating-working-status.ts @@ -23,7 +23,12 @@ export type FloatingWorkingStatus = readonly unresponsive: boolean; readonly action: FloatingStatusAction | null; } - | { readonly kind: "goal"; readonly label: string; readonly accessibilityLabel: string } + | { + readonly kind: "goal"; + readonly label: string; + readonly accessibilityLabel: string; + readonly actions: ReadonlyArray; + } | { readonly kind: "extension"; readonly label: string; readonly onPress: () => void } | { readonly kind: "preparing"; readonly label: string } | { diff --git a/apps/mobile/src/i18n/translations/de.json b/apps/mobile/src/i18n/translations/de.json index f5a0b37879c52..084c9bb22d63b 100644 --- a/apps/mobile/src/i18n/translations/de.json +++ b/apps/mobile/src/i18n/translations/de.json @@ -4375,6 +4375,7 @@ "f360accf1ccac178": "Runde gestoppt; der Agentenprozess läuft weiter", "967f83de030790dd": "{count, plural, =0 {Er wird mit anderen arbeitenden Threads geteilt. Stoppe diese, um ihn freizugeben.} one {Er wird mit {count} arbeitenden Thread geteilt. Stoppe diesen, um ihn freizugeben.} other {Er wird mit {count} arbeitenden Threads geteilt. Stoppe diese, um ihn freizugeben.}}", "5536ab75119ee3f9": "Thread konnte nicht aktualisiert werden", + "04c7bba52daa6f53": "Ziel konnte nicht aktualisiert werden", "f5f145b33e2a9380": "Wird gestoppt...", "e734a8e4a58a3835": "Stoppen", "0ce0ab7586e91607": "Hintergrundarbeit stoppen", @@ -4397,6 +4398,9 @@ "a20b495b9e6f82b9": "Wird gestartet…", "7917e738e8c3fd41": "Genehmigungsanfrage von {title} öffnen", "54c8b8a3c6e6046b": "Frage von {title} öffnen", + "715be2d41b9f1b72": "Ziel fortsetzen", + "5d0c71caa8f328b0": "Löschen", + "efe8657d62633cd4": "Ziel löschen", "cebceafe7ddc7d5d": "Feedback zur Genehmigung", "0830bd81f19bb753": "Sende Feedback zur Genehmigung ohne Anhänge oder zusätzlichen Kontext.", "d15878f290283f53": "Nachricht konnte nicht bearbeitet werden", diff --git a/apps/mobile/src/i18n/translations/en.json b/apps/mobile/src/i18n/translations/en.json index 43344b92f04ec..e4258c6dec547 100644 --- a/apps/mobile/src/i18n/translations/en.json +++ b/apps/mobile/src/i18n/translations/en.json @@ -4376,6 +4376,7 @@ "f360accf1ccac178": "Turn stopped; the agent process kept running", "967f83de030790dd": "{count, plural, =0 {It is shared with other working threads. Stop those to free it.} one {It is shared with {count} working thread. Stop those to free it.} other {It is shared with {count} working threads. Stop those to free it.}}", "5536ab75119ee3f9": "Could not update thread", + "04c7bba52daa6f53": "Could not update goal", "f5f145b33e2a9380": "Stopping...", "e734a8e4a58a3835": "Stop", "0ce0ab7586e91607": "Stop background work", @@ -4398,6 +4399,9 @@ "a20b495b9e6f82b9": "Starting…", "7917e738e8c3fd41": "Open approval from {title}", "54c8b8a3c6e6046b": "Open question from {title}", + "715be2d41b9f1b72": "Resume goal", + "5d0c71caa8f328b0": "Clear", + "efe8657d62633cd4": "Clear goal", "cebceafe7ddc7d5d": "Approval feedback", "0830bd81f19bb753": "Send approval feedback without attachments or added context.", "d15878f290283f53": "Could not edit message", diff --git a/apps/mobile/src/i18n/translations/es.json b/apps/mobile/src/i18n/translations/es.json index ffa0249acb7c5..9723fc5471f3b 100644 --- a/apps/mobile/src/i18n/translations/es.json +++ b/apps/mobile/src/i18n/translations/es.json @@ -4368,6 +4368,7 @@ "f360accf1ccac178": "Turno detenido; el proceso del agente siguió ejecutándose", "967f83de030790dd": "{count, plural, =0 {Se comparte con otros hilos en curso. Detenlos para liberarlo.} one {Se comparte con {count} hilo en curso. Detenlo para liberarlo.} other {Se comparte con {count} hilos en curso. Detenlos para liberarlo.}}", "5536ab75119ee3f9": "No se pudo actualizar el hilo", + "04c7bba52daa6f53": "No se pudo actualizar el objetivo", "f5f145b33e2a9380": "Deteniendo...", "e734a8e4a58a3835": "Detener", "0ce0ab7586e91607": "Detener el trabajo en segundo plano", @@ -4390,6 +4391,9 @@ "a20b495b9e6f82b9": "Iniciando…", "7917e738e8c3fd41": "Abrir la aprobación de {title}", "54c8b8a3c6e6046b": "Abrir la pregunta de {title}", + "715be2d41b9f1b72": "Reanudar objetivo", + "5d0c71caa8f328b0": "Borrar", + "efe8657d62633cd4": "Borrar objetivo", "cebceafe7ddc7d5d": "Comentarios de la aprobación", "0830bd81f19bb753": "Envía los comentarios de aprobación sin adjuntos ni contexto añadido.", "d15878f290283f53": "No se pudo editar el mensaje", diff --git a/apps/mobile/src/i18n/translations/fr.json b/apps/mobile/src/i18n/translations/fr.json index 76b6c1fee0d68..795b4bc67312d 100644 --- a/apps/mobile/src/i18n/translations/fr.json +++ b/apps/mobile/src/i18n/translations/fr.json @@ -4369,6 +4369,7 @@ "f360accf1ccac178": "Tour arrêté ; le processus de l’agent continue de tourner", "967f83de030790dd": "{count, plural, =0 {Il est partagé avec d’autres fils en cours. Arrêtez-les pour le libérer.} one {Il est partagé avec {count} fil en cours. Arrêtez-le pour le libérer.} other {Il est partagé avec {count} fils en cours. Arrêtez-les pour le libérer.}}", "5536ab75119ee3f9": "Impossible de mettre à jour le fil", + "04c7bba52daa6f53": "Impossible de mettre à jour l’objectif", "f5f145b33e2a9380": "Arrêt...", "e734a8e4a58a3835": "Arrêter", "0ce0ab7586e91607": "Arrêter le travail en arrière-plan", @@ -4391,6 +4392,9 @@ "a20b495b9e6f82b9": "Démarrage…", "7917e738e8c3fd41": "Ouvrir l’approbation de {title}", "54c8b8a3c6e6046b": "Ouvrir la question de {title}", + "715be2d41b9f1b72": "Reprendre l’objectif", + "5d0c71caa8f328b0": "Effacer", + "efe8657d62633cd4": "Effacer l’objectif", "cebceafe7ddc7d5d": "Retour sur l’approbation", "0830bd81f19bb753": "Envoyez votre réponse à l’approbation sans pièces jointes ni contexte ajouté.", "d15878f290283f53": "Impossible de modifier le message", diff --git a/apps/mobile/src/i18n/translations/ja.json b/apps/mobile/src/i18n/translations/ja.json index 274edf167b42e..97f21ae2fe472 100644 --- a/apps/mobile/src/i18n/translations/ja.json +++ b/apps/mobile/src/i18n/translations/ja.json @@ -4350,6 +4350,7 @@ "f360accf1ccac178": "ターンは停止しましたが、エージェントのプロセスは実行されたままです", "967f83de030790dd": "{count, plural, =0 {作業中の他のスレッドと共有されています。解放するにはそれらを停止してください。} other {作業中の {count} 個のスレッドと共有されています。解放するにはそれらを停止してください。}}", "5536ab75119ee3f9": "スレッドを更新できませんでした", + "04c7bba52daa6f53": "目標を更新できませんでした", "f5f145b33e2a9380": "停止しています...", "e734a8e4a58a3835": "停止", "0ce0ab7586e91607": "バックグラウンドの作業を停止", @@ -4372,6 +4373,9 @@ "a20b495b9e6f82b9": "開始しています…", "7917e738e8c3fd41": "{title} からの承認を開く", "54c8b8a3c6e6046b": "{title} からの質問を開く", + "715be2d41b9f1b72": "目標を再開", + "5d0c71caa8f328b0": "クリア", + "efe8657d62633cd4": "目標をクリア", "cebceafe7ddc7d5d": "承認へのフィードバック", "0830bd81f19bb753": "承認のフィードバックは、添付ファイルや追加のコンテキストなしで送信してください。", "d15878f290283f53": "メッセージを編集できませんでした", diff --git a/apps/mobile/src/i18n/translations/ko.json b/apps/mobile/src/i18n/translations/ko.json index d0d37ca80f4e9..2d95884bfc32c 100644 --- a/apps/mobile/src/i18n/translations/ko.json +++ b/apps/mobile/src/i18n/translations/ko.json @@ -4355,6 +4355,7 @@ "f360accf1ccac178": "턴이 중지되었지만 에이전트 프로세스가 계속 실행 중입니다", "967f83de030790dd": "{count, plural, =0 {다른 작업 중인 스레드와 공유되어 있습니다. 해제하려면 해당 스레드를 중지하세요.} other {작업 중인 스레드 {count}개와 공유되어 있습니다. 해제하려면 해당 스레드를 중지하세요.}}", "5536ab75119ee3f9": "스레드를 업데이트할 수 없습니다", + "04c7bba52daa6f53": "목표를 업데이트할 수 없습니다", "f5f145b33e2a9380": "중지하는 중...", "e734a8e4a58a3835": "중지", "0ce0ab7586e91607": "백그라운드 작업 중지", @@ -4377,6 +4378,9 @@ "a20b495b9e6f82b9": "시작하는 중…", "7917e738e8c3fd41": "{title}의 승인 요청 열기", "54c8b8a3c6e6046b": "{title}의 질문 열기", + "715be2d41b9f1b72": "목표 재개", + "5d0c71caa8f328b0": "지우기", + "efe8657d62633cd4": "목표 지우기", "cebceafe7ddc7d5d": "승인 피드백", "0830bd81f19bb753": "첨부 파일이나 추가 컨텍스트 없이 승인 피드백을 보내세요.", "d15878f290283f53": "메시지를 편집할 수 없습니다", diff --git a/apps/mobile/src/i18n/translations/pt-BR.json b/apps/mobile/src/i18n/translations/pt-BR.json index ec401f9fa194a..412808cc9d686 100644 --- a/apps/mobile/src/i18n/translations/pt-BR.json +++ b/apps/mobile/src/i18n/translations/pt-BR.json @@ -4369,6 +4369,7 @@ "f360accf1ccac178": "Turno parado; o processo do agente continuou em execução", "967f83de030790dd": "{count, plural, =0 {Ele é compartilhado com outras threads em andamento. Pare-as para liberá-lo.} one {Ele é compartilhado com {count} thread em andamento. Pare-a para liberá-lo.} other {Ele é compartilhado com {count} threads em andamento. Pare-as para liberá-lo.}}", "5536ab75119ee3f9": "Não foi possível atualizar a thread", + "04c7bba52daa6f53": "Não foi possível atualizar a meta", "f5f145b33e2a9380": "Parando...", "e734a8e4a58a3835": "Parar", "0ce0ab7586e91607": "Parar trabalho em segundo plano", @@ -4391,6 +4392,9 @@ "a20b495b9e6f82b9": "Iniciando…", "7917e738e8c3fd41": "Abrir aprovação de {title}", "54c8b8a3c6e6046b": "Abrir pergunta de {title}", + "715be2d41b9f1b72": "Retomar meta", + "5d0c71caa8f328b0": "Limpar", + "efe8657d62633cd4": "Limpar meta", "cebceafe7ddc7d5d": "Feedback da aprovação", "0830bd81f19bb753": "Envie o feedback da aprovação sem anexos nem contexto adicional.", "d15878f290283f53": "Não foi possível editar a mensagem", diff --git a/apps/mobile/src/i18n/translations/ru.json b/apps/mobile/src/i18n/translations/ru.json index 44db80a8f6808..b76e105104a8a 100644 --- a/apps/mobile/src/i18n/translations/ru.json +++ b/apps/mobile/src/i18n/translations/ru.json @@ -4447,6 +4447,7 @@ "f360accf1ccac178": "Ход остановлен; процесс агента продолжает работать", "967f83de030790dd": "{count, plural, =0 {Он используется другими работающими тредами. Остановите их, чтобы освободить его.} one {Он используется {count} работающим тредом. Остановите его, чтобы освободить.} few {Он используется {count} работающими тредами. Остановите их, чтобы освободить его.} many {Он используется {count} работающими тредами. Остановите их, чтобы освободить его.} other {Он используется {count} работающего треда. Остановите их, чтобы освободить его.}}", "5536ab75119ee3f9": "Не удалось обновить тред", + "04c7bba52daa6f53": "Не удалось обновить цель", "f5f145b33e2a9380": "Остановка...", "e734a8e4a58a3835": "Остановить", "0ce0ab7586e91607": "Остановить фоновую работу", @@ -4469,6 +4470,9 @@ "a20b495b9e6f82b9": "Запуск…", "7917e738e8c3fd41": "Открыть запрос подтверждения из {title}", "54c8b8a3c6e6046b": "Открыть вопрос из {title}", + "715be2d41b9f1b72": "Возобновить цель", + "5d0c71caa8f328b0": "Очистить", + "efe8657d62633cd4": "Очистить цель", "cebceafe7ddc7d5d": "Отзыв на подтверждение", "0830bd81f19bb753": "Отправьте отзыв на подтверждение без вложений и добавленного контекста.", "d15878f290283f53": "Не удалось изменить сообщение", diff --git a/apps/mobile/src/i18n/translations/sv.json b/apps/mobile/src/i18n/translations/sv.json index e62b0c05509d9..8629e708c09fe 100644 --- a/apps/mobile/src/i18n/translations/sv.json +++ b/apps/mobile/src/i18n/translations/sv.json @@ -4375,6 +4375,7 @@ "f360accf1ccac178": "Omgången stoppades; agentprocessen fortsatte att köras", "967f83de030790dd": "{count, plural, =0 {Den delas med andra arbetande trådar. Stoppa dem för att frigöra den.} one {Den delas med {count} arbetande tråd. Stoppa den för att frigöra den.} other {Den delas med {count} arbetande trådar. Stoppa dem för att frigöra den.}}", "5536ab75119ee3f9": "Kunde inte uppdatera tråden", + "04c7bba52daa6f53": "Det gick inte att uppdatera målet", "f5f145b33e2a9380": "Stoppar...", "e734a8e4a58a3835": "Stoppa", "0ce0ab7586e91607": "Stoppa bakgrundsarbete", @@ -4397,6 +4398,9 @@ "a20b495b9e6f82b9": "Startar…", "7917e738e8c3fd41": "Öppna godkännande från {title}", "54c8b8a3c6e6046b": "Öppna fråga från {title}", + "715be2d41b9f1b72": "Återuppta mål", + "5d0c71caa8f328b0": "Rensa", + "efe8657d62633cd4": "Rensa mål", "cebceafe7ddc7d5d": "Feedback på godkännande", "0830bd81f19bb753": "Skicka feedback om godkännandet utan bilagor eller tillagd kontext.", "d15878f290283f53": "Kunde inte redigera meddelandet", diff --git a/apps/mobile/src/i18n/translations/zh.json b/apps/mobile/src/i18n/translations/zh.json index f70973a639e22..45e032bebe433 100644 --- a/apps/mobile/src/i18n/translations/zh.json +++ b/apps/mobile/src/i18n/translations/zh.json @@ -4358,6 +4358,7 @@ "f360accf1ccac178": "这一轮已停止,但智能体进程仍在运行", "967f83de030790dd": "{count, plural, =0 {它被其他正在工作的会话共用。停止那些会话即可释放。} other {它被 {count} 个正在工作的会话共用。停止那些会话即可释放。}}", "5536ab75119ee3f9": "无法更新会话", + "04c7bba52daa6f53": "无法更新目标", "f5f145b33e2a9380": "正在停止…", "e734a8e4a58a3835": "停止", "0ce0ab7586e91607": "停止后台工作", @@ -4380,6 +4381,9 @@ "a20b495b9e6f82b9": "正在启动…", "7917e738e8c3fd41": "打开来自 {title} 的批准请求", "54c8b8a3c6e6046b": "打开来自 {title} 的问题", + "715be2d41b9f1b72": "恢复目标", + "5d0c71caa8f328b0": "清除", + "efe8657d62633cd4": "清除目标", "cebceafe7ddc7d5d": "批准反馈", "0830bd81f19bb753": "发送审批反馈时请不要带附件或额外上下文。", "d15878f290283f53": "无法编辑消息", diff --git a/apps/mobile/src/state/thread-outbox-model.ts b/apps/mobile/src/state/thread-outbox-model.ts index 2ab60eec8c2db..e0305b547d011 100644 --- a/apps/mobile/src/state/thread-outbox-model.ts +++ b/apps/mobile/src/state/thread-outbox-model.ts @@ -56,6 +56,7 @@ export const QueuedThreadMessageSchema = Schema.Struct({ messageId: MessageId, commandId: CommandId, text: Schema.String, + restoreToDraft: Schema.optional(Schema.Boolean), context: Schema.optional(OrchestrationMessageContext), attachments: Schema.Array(DraftComposerAttachmentSchema), modelSelection: Schema.optional(ModelSelection), @@ -88,6 +89,7 @@ export interface QueuedThreadMessage { readonly messageId: MessageId; readonly commandId: CommandId; readonly text: string; + readonly restoreToDraft?: boolean; readonly context?: OrchestrationMessageContext; readonly attachments: ReadonlyArray; readonly modelSelection?: ModelSelectionType; diff --git a/apps/mobile/src/state/thread-task-permissions.test.ts b/apps/mobile/src/state/thread-task-permissions.test.ts index 57c8e5bfe9cc0..b2b83204b2f67 100644 --- a/apps/mobile/src/state/thread-task-permissions.test.ts +++ b/apps/mobile/src/state/thread-task-permissions.test.ts @@ -560,6 +560,38 @@ describe("mobile task permissions", () => { ); }); + it("queues a goal command with the thread's settings and leaves the draft alone", async () => { + state.grantedEnvironments.add("secondary"); + state.draft.modelSelection = { + instanceId: ProviderInstanceId.make("claudeAgent"), + model: "claude-sonnet-5-5", + }; + Object.assign(state.draft, { runtimeMode: "approval-required" }); + const composer = useThreadComposerState(NO_SIDE_CHATS); + expect(await composer.onSendCommand("/goal clear")).toBe("message"); + expect(state.enqueue).toHaveBeenCalledExactlyOnceWith( + expect.objectContaining({ + environmentId: "secondary", + threadId: "thread", + text: "/goal clear", + restoreToDraft: false, + attachments: [], + modelSelection: state.thread.modelSelection, + runtimeMode: state.thread.runtimeMode, + }), + ); + expect(state.clearDraft).not.toHaveBeenCalled(); + expect(state.draft.text).toBe("Keep my draft"); + }); + + it("rechecks the operate grant before queueing a command", async () => { + state.grantedEnvironments.add("secondary"); + const composer = useThreadComposerState(NO_SIDE_CHATS); + state.grantedEnvironments.delete("secondary"); + expect(await composer.onSendCommand("/goal clear")).toBeNull(); + expect(state.enqueue).not.toHaveBeenCalled(); + }); + it("rechecks the target environment before an approval response", async () => { state.grantedEnvironments.add("secondary"); const requests = useSelectedThreadRequests(); diff --git a/apps/mobile/src/state/threadOutboxDelivery.test.ts b/apps/mobile/src/state/threadOutboxDelivery.test.ts index e77ce11e2c724..51691aca707ea 100644 --- a/apps/mobile/src/state/threadOutboxDelivery.test.ts +++ b/apps/mobile/src/state/threadOutboxDelivery.test.ts @@ -939,6 +939,30 @@ describe("thread outbox recovery rollback", () => { }), ); + it.effect("keeps the draft unchanged when a standalone goal command is rejected", () => + Effect.gen(function* () { + const message: QueuedThreadMessage = { + ...queuedMessage({ messageId: "goal-rejected", text: "/goal clear" }), + restoreToDraft: false, + modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.6-sol" }, + runtimeMode: "full-access", + }; + const threadKey = `${message.environmentId}:${message.threadId}`; + appAtomRegistry.set(composerDrafts.composerDraftsAtom, { + [threadKey]: { text: "Keep my draft", attachments: [], runtimeMode: "approval-required" }, + }); + const draft = composerDrafts.getComposerDraftSnapshot(threadKey); + yield* Effect.promise(() => harness.manager.enqueue(message)); + expect(yield* restoreRejectedQueuedMessage(message, "rejected")).toBe("restored"); + expect(composerDrafts.getComposerDraftSnapshot(threadKey)).toEqual(draft); + expect(remainingMessages()).toEqual([]); + expect(appAtomRegistry.get(threadComposerErrorsAtom)[threadKey]).toEqual({ + message: "rejected", + messageId: message.messageId, + }); + }), + ); + it.effect("does not record a creation outcome for a rejected follow-up message", () => Effect.gen(function* () { const message = queuedMessage({ messageId: "message-followup-restore", text: "follow up" }); diff --git a/apps/mobile/src/state/threadOutboxDelivery.ts b/apps/mobile/src/state/threadOutboxDelivery.ts index 1e12bd5d96c89..1d2b3555e29b6 100644 --- a/apps/mobile/src/state/threadOutboxDelivery.ts +++ b/apps/mobile/src/state/threadOutboxDelivery.ts @@ -478,6 +478,14 @@ export const restoreRejectedQueuedMessage = Effect.fn("ThreadOutbox.restoreRejec return "deferred" as const; } const revision = threadOutboxRevision(queuedMessage.messageId); + if (queuedMessage.restoreToDraft === false) { + const removed = yield* storage("remove-unsendable", queuedMessage.messageId, () => + removeThreadOutboxMessage(queuedMessage, revision, () => !editing()), + ); + if (!removed) return "deferred" as const; + setThreadComposerError(threadKey, message, queuedMessage.messageId); + return "restored" as const; + } yield* storage("load-drafts", queuedMessage.messageId, () => waitForComposerDraftsLoaded()); if (editing()) return "deferred" as const; const originalDraft = getComposerDraftSnapshot(draftKey); diff --git a/apps/mobile/src/state/use-thread-composer-state.ts b/apps/mobile/src/state/use-thread-composer-state.ts index 69ec0af369956..48e7fc02b5b32 100644 --- a/apps/mobile/src/state/use-thread-composer-state.ts +++ b/apps/mobile/src/state/use-thread-composer-state.ts @@ -979,6 +979,50 @@ export function useThreadComposerState(input: { return null; })(); + /** Queues a standalone text command such as `/goal clear` and leaves the composer draft alone. */ + const onSendCommand = async (text: string) => { + if ( + !selectedThreadShell || + selectedThreadCreation !== null || + (selectedEnvironmentRuntime?.connectionState === "connected" && + !readEnvironmentScope(selectedThreadShell.environmentId, AuthOrchestrationOperateScope)) + ) { + return null; + } + const thread = selectedThreadShell; + // Goal commands belong to the thread itself, not the model or modes picked in the draft. + const modelSelection = thread.modelSelection; + const serverConfig = selectedEnvironmentRuntime?.serverConfig; + if ( + selectedEnvironmentRuntime?.connectionState === "connected" && + isModelSelectionUnavailable(serverConfig, modelSelection, thread.projectId) + ) { + const { title, detail } = describeUnavailableModelSelection( + serverConfig, + modelSelection, + thread.projectId, + ); + Dialog.alert(title, detail); + return null; + } + const metadata = makeQueuedMessageMetadata(); + const messageId = MessageId.make(metadata.messageId); + await enqueueThreadOutboxMessage({ + environmentId: thread.environmentId, + threadId: thread.id, + messageId, + commandId: CommandId.make(metadata.commandId), + text, + restoreToDraft: false, + attachments: [], + modelSelection, + runtimeMode: thread.runtimeMode, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + createdAt: metadata.createdAt, + }); + return messageId; + }; + const onChangeDraftMessage = (value: string) => { if (!selectedThreadShell) { return; @@ -1052,6 +1096,7 @@ export function useThreadComposerState(input: { onNativePasteText, onRemoveDraftImage, onSendMessage, + onSendCommand, sideChatUnavailableReason, }; } From b5481adcd8af677c85e4b461093759ec1ccab6fd Mon Sep 17 00:00:00 2001 From: Bin Jamshid Date: Fri, 20 Nov 2026 00:38:14 +0400 Subject: [PATCH 59/97] fix(web,mobile): scheduled tasks from Settings start from the project's default branch (#32841) Co-authored-by: Ajraba04 <143622128+Ajraba04@users.noreply.github.com> Co-authored-by: maria-rcks Co-authored-by: Julius Marminge --- .../settings/ScheduledTaskPickerScreens.tsx | 7 +++- ...SettingsScheduledTasksRouteScreen.test.tsx | 3 ++ .../SettingsScheduledTasksRouteScreen.tsx | 25 ++++++++++-- .../settings/scheduledTaskDraft.test.ts | 38 +++++++++++++++++++ .../features/settings/scheduledTaskDraft.ts | 4 +- .../settings/ScheduledTasksSettings.tsx | 28 +++++++++++--- .../scheduledTasksSettings.logic.test.ts | 5 +++ .../settings/scheduledTasksSettings.logic.ts | 2 +- packages/client-runtime/package.json | 4 ++ .../src/scheduledTaskWorktree.test.ts | 18 +++++++++ .../src/scheduledTaskWorktree.ts | 17 +++++++++ 11 files changed, 138 insertions(+), 13 deletions(-) create mode 100644 packages/client-runtime/src/scheduledTaskWorktree.test.ts create mode 100644 packages/client-runtime/src/scheduledTaskWorktree.ts diff --git a/apps/mobile/src/features/settings/ScheduledTaskPickerScreens.tsx b/apps/mobile/src/features/settings/ScheduledTaskPickerScreens.tsx index d37c8c68a81f1..f07ffea096ec8 100644 --- a/apps/mobile/src/features/settings/ScheduledTaskPickerScreens.tsx +++ b/apps/mobile/src/features/settings/ScheduledTaskPickerScreens.tsx @@ -2,6 +2,7 @@ import { msg, T, useGT, useMessages } from "gt-react-native"; import { NativeScrollView } from "../../native/NativeScrollViewMarker"; import { LegendList } from "@legendapp/list/react-native"; import { useNavigation } from "@react-navigation/native"; +import { scheduledTaskWorktreeBaseRef } from "@t3tools/client-runtime/scheduled-task-worktree"; import { isListedThreadLineage } from "@t3tools/contracts"; import * as Haptics from "expo-haptics"; import { useMemo, useState } from "react"; @@ -153,7 +154,11 @@ export function ScheduledTaskBranchPickerRouteScreen() { title={gt("Base branch")} project={project} branches={visibleBranches} - selectedBranchName={editor.draft.baseRef} + selectedBranchName={ + editor.draft.baseRef.trim() || debouncedQuery.trim() || branches.data === null + ? editor.draft.baseRef + : scheduledTaskWorktreeBaseRef("", branches.refs) + } query={query} onQueryChange={setQuery} loading={ diff --git a/apps/mobile/src/features/settings/SettingsScheduledTasksRouteScreen.test.tsx b/apps/mobile/src/features/settings/SettingsScheduledTasksRouteScreen.test.tsx index b92c1ec725b47..f0f28492a2a41 100644 --- a/apps/mobile/src/features/settings/SettingsScheduledTasksRouteScreen.test.tsx +++ b/apps/mobile/src/features/settings/SettingsScheduledTasksRouteScreen.test.tsx @@ -132,6 +132,9 @@ vi.mock("../../state/query", () => ({ useEnvironmentQuery: () => ({ data: { tasks: mocks.tasks, threads: [] } }), })); vi.mock("../../state/use-atom-command", () => ({ useAtomCommand: () => mocks.upsert })); +vi.mock("../../state/queries", () => ({ + usePaginatedBranches: () => ({ refs: [], data: null, error: null }), +})); import { appAtomRegistry } from "../../state/atom-registry"; import { editDraft } from "./scheduledTaskDraft"; diff --git a/apps/mobile/src/features/settings/SettingsScheduledTasksRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsScheduledTasksRouteScreen.tsx index 077f983ac0f2e..94594fa97a8c9 100644 --- a/apps/mobile/src/features/settings/SettingsScheduledTasksRouteScreen.tsx +++ b/apps/mobile/src/features/settings/SettingsScheduledTasksRouteScreen.tsx @@ -39,6 +39,7 @@ import { WEBHOOK_FILTER_OPS, type WebhookFilterDraft, } from "@t3tools/client-runtime/scheduled-task-webhook"; +import { scheduledTaskWorktreeBaseRef } from "@t3tools/client-runtime/scheduled-task-worktree"; import { scheduleTimeZoneLabel } from "@t3tools/client-runtime/scheduled-task-time-zone"; import type { MessageResolver } from "../../i18n/messages"; import { useRef, useState, type ReactNode } from "react"; @@ -66,6 +67,7 @@ import { buildModelOptions } from "../../lib/modelOptions"; import { withImplicitFastModeSelection } from "../../lib/providerOptions"; import { useProjects, useEnvironmentServerConfig } from "../../state/entities"; import { useEnvironmentQuery } from "../../state/query"; +import { usePaginatedBranches } from "../../state/queries"; import { serverEnvironment } from "../../state/server"; import { useAtomCommand } from "../../state/use-atom-command"; import { resolveNewTaskBranchLabel } from "../threads/new-task-context-presentation"; @@ -745,6 +747,21 @@ function TaskForm({ project.id === draft.task?.projectId), ) .sort((left, right) => Number(right.pinnedAt != null) - Number(left.pinnedAt != null)); + const automaticBaseRef = draft.workspace === "worktree" && !draft.baseRef.trim(); + const automaticBaseRefCwd = automaticBaseRef + ? (projects.find((project) => project.id === draft.projectId)?.workspaceRoot ?? null) + : null; + const automaticBaseRefs = usePaginatedBranches({ + environmentId, + cwd: automaticBaseRefCwd, + query: "", + }); + const worktreeBaseRef = scheduledTaskWorktreeBaseRef(draft.baseRef, automaticBaseRefs.refs); + // Until the project's refs load, the automatic base would save as `main`. A failed lookup falls back to it. + const automaticBaseRefLoading = + automaticBaseRefCwd !== null && + automaticBaseRefs.data === null && + automaticBaseRefs.error === null; const config = useEnvironmentServerConfig(environmentId); const destinationLabel = useScheduledTaskDestinationLabel(environmentId, draft.threadId); const boundThread = useScheduledTaskThread(environmentId, draft.threadId); @@ -793,7 +810,8 @@ function TaskForm({ saving || dictationPending || taskMissing || - environmentUnavailable + environmentUnavailable || + automaticBaseRefLoading ) return; // Preserve signatures edited on other clients by sending the task's current value. @@ -874,7 +892,7 @@ function TaskForm({ ? { type: "existing_worktree", worktreePath: draft.checkoutPath.trim() } : { type: "worktree", - baseRef: draft.baseRef.trim() || "main", + baseRef: worktreeBaseRef, startFromOrigin: draft.startFromOrigin, }, // Tasks have no mode picker; a mode above the administrator's ceiling is refused. @@ -1101,7 +1119,7 @@ function TaskForm({ label={gt("Base branch")} value={resolveNewTaskBranchLabel( { - branchName: draft.baseRef, + branchName: automaticBaseRefLoading ? null : worktreeBaseRef, startFromOrigin: draft.startFromOrigin, workspaceMode: "worktree", }, @@ -1460,6 +1478,7 @@ function TaskForm({ dictationPending || taskMissing || environmentUnavailable || + automaticBaseRefLoading || // The server refuses an enabled webhook task under this policy. (draft.enabled && draft.schedule.mode === "webhook" && webhookDenial !== undefined) } diff --git a/apps/mobile/src/features/settings/scheduledTaskDraft.test.ts b/apps/mobile/src/features/settings/scheduledTaskDraft.test.ts index 7359403a67dce..c4284fac14c43 100644 --- a/apps/mobile/src/features/settings/scheduledTaskDraft.test.ts +++ b/apps/mobile/src/features/settings/scheduledTaskDraft.test.ts @@ -5,8 +5,12 @@ import { ProviderDriverKind, ProviderInstanceId, ProjectId, + ScheduledTaskId, + type ScheduledTask, } from "@t3tools/contracts"; import { + createDraft, + editDraft, scheduledTaskDefaultModel, DEFAULT_SCHEDULE, scheduleDraftForTask, @@ -207,3 +211,37 @@ it("rejects dedupe keys without valid request placeholders", () => { scheduleFromDraft({ ...DEFAULT_SCHEDULE, mode: "webhook", coalesceKey: "{{body.bad" }), ).toBeNull(); }); + +describe("scheduled task worktree base", () => { + const rootTask = { + id: ScheduledTaskId.make("task"), + title: "Review issues", + prompt: "Review open issues", + enabled: true, + schedule: { type: "interval", everyMs: 60_000 }, + projectId: ProjectId.make("project"), + threadId: null, + workspaceStrategy: { type: "root" }, + modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" }, + runtimeMode: "full-access", + interactionMode: "default", + createdBy: "user", + creationSource: "mobile", + createdAt: "2026-09-17T00:00:00.000Z", + updatedAt: "2026-09-17T00:00:00.000Z", + nextRunAt: null, + lastRunAt: null, + lastRunStatus: "never", + lastRunError: null, + runCount: 0, + } satisfies ScheduledTask; + + it("leaves the base automatic for new tasks and tasks without a worktree", () => { + expect(createDraft(ProjectId.make("project"), null).baseRef).toBe(""); + expect(editDraft(rootTask).baseRef).toBe(""); + expect( + editDraft({ ...rootTask, workspaceStrategy: { type: "worktree", baseRef: "release" } }) + .baseRef, + ).toBe("release"); + }); +}); diff --git a/apps/mobile/src/features/settings/scheduledTaskDraft.ts b/apps/mobile/src/features/settings/scheduledTaskDraft.ts index 1ede30d84072b..5bacd4be83c81 100644 --- a/apps/mobile/src/features/settings/scheduledTaskDraft.ts +++ b/apps/mobile/src/features/settings/scheduledTaskDraft.ts @@ -301,7 +301,7 @@ export function createDraft( schedule: DEFAULT_SCHEDULE, threadMode: "new_thread", workspace: "worktree", - baseRef: "main", + baseRef: "", checkoutPath: "", enabled: true, startFromOrigin: true, @@ -321,7 +321,7 @@ export function editDraft(task: ScheduledTask): ScheduledTaskDraft { schedule: scheduleDraftForTask(task), threadMode: scheduledTaskThreadMode(task), workspace: task.workspaceStrategy.type, - baseRef: task.workspaceStrategy.type === "worktree" ? task.workspaceStrategy.baseRef : "main", + baseRef: task.workspaceStrategy.type === "worktree" ? task.workspaceStrategy.baseRef : "", checkoutPath: task.workspaceStrategy.type === "existing_worktree" ? task.workspaceStrategy.worktreePath diff --git a/apps/web/src/components/settings/ScheduledTasksSettings.tsx b/apps/web/src/components/settings/ScheduledTasksSettings.tsx index 4988ba93fdd23..39670ed266666 100644 --- a/apps/web/src/components/settings/ScheduledTasksSettings.tsx +++ b/apps/web/src/components/settings/ScheduledTasksSettings.tsx @@ -37,6 +37,7 @@ import { type WebhookFilterDraft, } from "@t3tools/client-runtime/scheduled-task-webhook"; import { scheduleTimeZoneLabel } from "@t3tools/client-runtime/scheduled-task-time-zone"; +import { scheduledTaskWorktreeBaseRef } from "@t3tools/client-runtime/scheduled-task-worktree"; import { MAX_WEBHOOK_DELIVERY_AGE_MINUTES, MAX_WEBHOOK_FILTERS, @@ -76,7 +77,7 @@ import { import { buildThreadRouteParams } from "../../threadRoutes"; import { scopeThreadRef } from "@t3tools/client-runtime/environment"; import { environmentAtomList, environmentIdsKey } from "../../state/environmentAtomList"; -import { useThreadSearch } from "../../state/queries"; +import { usePaginatedBranches, useThreadSearch } from "../../state/queries"; import { formatEnvironmentQueryError, useEnvironmentQuery } from "../../state/query"; import { EMPTY_SERVER_PROVIDERS, serverEnvironment } from "../../state/server"; import { threadFamilies } from "../../state/threads"; @@ -195,7 +196,7 @@ const EMPTY_DRAFT: DraftState = { threadId: "", threadMode: "new_thread", workspaceMode: "worktree", - baseRef: "main", + baseRef: "", startFromOrigin: true, existingWorktreePath: "", modelKey: "", @@ -1530,6 +1531,19 @@ function ScheduledTaskEditorForm({ : task; const selectedProjectId = draft.projectId || projects[0]?.id || ""; const selectedProject = projects.find((project) => project.id === selectedProjectId); + const automaticBaseRef = draft.workspaceMode === "worktree" && !draft.baseRef.trim(); + const automaticBaseRefs = usePaginatedBranches({ + environmentId, + cwd: automaticBaseRef ? (selectedProject?.workspaceRoot ?? null) : null, + query: "", + }); + const worktreeBaseRef = scheduledTaskWorktreeBaseRef(draft.baseRef, automaticBaseRefs.refs); + // Until the project's refs load, the automatic base would save as `main`. A failed lookup falls back to it. + const automaticBaseRefLoading = + automaticBaseRef && + selectedProject !== undefined && + automaticBaseRefs.data === null && + automaticBaseRefs.error === null; const instanceEntries = providerInstanceEntriesFor( providers, settings, @@ -1581,7 +1595,8 @@ function ScheduledTaskEditorForm({ saving || editingTaskMissing || !connected || - tasksQuery.data === null + tasksQuery.data === null || + automaticBaseRefLoading ) return; const selection = activeSelection; @@ -1653,7 +1668,7 @@ function ScheduledTaskEditorForm({ ? { type: "existing_worktree", worktreePath: draft.existingWorktreePath.trim() } : { type: "worktree", - baseRef: draft.baseRef.trim() || "main", + baseRef: worktreeBaseRef, startFromOrigin: draft.startFromOrigin, }; const input: ScheduledTaskUpsertInput = { @@ -1722,7 +1737,7 @@ function ScheduledTaskEditorForm({ projectId: defaultScheduledTaskProjectId(projectsOn(next.environmentId), scope), modelKey: "", baseModelSelection: null, - baseRef: "main", + baseRef: "", startFromOrigin: true, existingWorktreePath: "", })); @@ -1881,7 +1896,7 @@ function ScheduledTaskEditorForm({ id="scheduled-task-base-ref" environmentId={environmentId} cwd={selectedProject?.workspaceRoot ?? null} - value={draft.baseRef} + value={automaticBaseRefLoading ? "" : worktreeBaseRef} onValueChange={(baseRef) => setDraft((current) => ({ ...current, baseRef }))} startFromOrigin={draft.startFromOrigin} onStartFromOriginChange={(startFromOrigin) => @@ -2331,6 +2346,7 @@ function ScheduledTaskEditorForm({ editingTaskMissing || !connected || !tasksQuery.data || + automaticBaseRefLoading || (draft.enabled && draft.scheduleMode === "webhook" && webhookDenial !== undefined) } onClick={() => void submit()} diff --git a/apps/web/src/components/settings/scheduledTasksSettings.logic.test.ts b/apps/web/src/components/settings/scheduledTasksSettings.logic.test.ts index 295ce0aae0bd6..d01b47078dbe2 100644 --- a/apps/web/src/components/settings/scheduledTasksSettings.logic.test.ts +++ b/apps/web/src/components/settings/scheduledTasksSettings.logic.test.ts @@ -171,6 +171,11 @@ describe("editing scheduled task branch settings", () => { expect(draft.baseRef).toBe("release"); expect(draft.startFromOrigin).toBe(false); }); + + it("leaves the base automatic when a task without a worktree switches to one", () => { + const draft = taskToDraft({ ...legacyTask, workspaceStrategy: { type: "root" } }); + expect(draft.baseRef).toBe(""); + }); }); describe("fixed-time scheduled tasks", () => { diff --git a/apps/web/src/components/settings/scheduledTasksSettings.logic.ts b/apps/web/src/components/settings/scheduledTasksSettings.logic.ts index df227cfe32ea2..e66ea42743aa9 100644 --- a/apps/web/src/components/settings/scheduledTasksSettings.logic.ts +++ b/apps/web/src/components/settings/scheduledTasksSettings.logic.ts @@ -332,7 +332,7 @@ export function taskToDraft(task: ScheduledTask): DraftState { threadId: task.threadId ?? "", threadMode: scheduledTaskThreadMode(task), workspaceMode: task.workspaceStrategy.type, - baseRef: task.workspaceStrategy.type === "worktree" ? task.workspaceStrategy.baseRef : "main", + baseRef: task.workspaceStrategy.type === "worktree" ? task.workspaceStrategy.baseRef : "", startFromOrigin: task.workspaceStrategy.type === "worktree" ? (task.workspaceStrategy.startFromOrigin ?? false) diff --git a/packages/client-runtime/package.json b/packages/client-runtime/package.json index c09deef7e4b39..900dfad694aba 100644 --- a/packages/client-runtime/package.json +++ b/packages/client-runtime/package.json @@ -111,6 +111,10 @@ "types": "./src/scheduledTaskTimeZone.ts", "default": "./src/scheduledTaskTimeZone.ts" }, + "./scheduled-task-worktree": { + "types": "./src/scheduledTaskWorktree.ts", + "default": "./src/scheduledTaskWorktree.ts" + }, "./connection": { "types": "./src/connection/index.ts", "default": "./src/connection/index.ts" diff --git a/packages/client-runtime/src/scheduledTaskWorktree.test.ts b/packages/client-runtime/src/scheduledTaskWorktree.test.ts new file mode 100644 index 0000000000000..c5b044b3fdf2b --- /dev/null +++ b/packages/client-runtime/src/scheduledTaskWorktree.test.ts @@ -0,0 +1,18 @@ +import { expect, it } from "vite-plus/test"; + +import { scheduledTaskWorktreeBaseRef } from "./scheduledTaskWorktree.ts"; + +const ref = (name: string, isDefault = false) => ({ name, isDefault }); + +it("keeps a picked base and otherwise uses the project's default branch", () => { + expect(scheduledTaskWorktreeBaseRef(" release ", [ref("master", true)])).toBe("release"); + expect(scheduledTaskWorktreeBaseRef("", [ref("feature"), ref("master", true)])).toBe("master"); + expect(scheduledTaskWorktreeBaseRef(" ", [ref("origin/develop", true)])).toBe("origin/develop"); +}); + +it("falls back to main, then master, when no ref is marked default", () => { + expect(scheduledTaskWorktreeBaseRef("", [ref("feature"), ref("master")])).toBe("master"); + expect(scheduledTaskWorktreeBaseRef("", [ref("origin/master")])).toBe("origin/master"); + expect(scheduledTaskWorktreeBaseRef("", [ref("master"), ref("main")])).toBe("main"); + expect(scheduledTaskWorktreeBaseRef("", [])).toBe("main"); +}); diff --git a/packages/client-runtime/src/scheduledTaskWorktree.ts b/packages/client-runtime/src/scheduledTaskWorktree.ts new file mode 100644 index 0000000000000..2baa220570ce7 --- /dev/null +++ b/packages/client-runtime/src/scheduledTaskWorktree.ts @@ -0,0 +1,17 @@ +import type { VcsRef } from "@t3tools/contracts"; + +/** An empty base is automatic: the project's default branch, else `main` or `master`. */ +export function scheduledTaskWorktreeBaseRef( + baseRef: string, + refs: ReadonlyArray>, +): string { + const picked = baseRef.trim(); + if (picked) return picked; + const defaultRef = refs.find((ref) => ref.isDefault); + if (defaultRef) return defaultRef.name; + for (const name of ["main", "master"]) { + const match = refs.find((ref) => ref.name === name || ref.name === `origin/${name}`); + if (match) return match.name; + } + return "main"; +} From 4b697be8491ea615d198d06c67513f9dfa29b2a3 Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Thu, 19 Nov 2026 21:39:17 +0100 Subject: [PATCH 60/97] fix(web): keep deleted ACP sessions out of pending listings (#39331) Co-authored-by: Julius Marminge --- ...pSessionManagementSection.browser.test.tsx | 33 ++++ .../settings/AcpSessionManagementSection.tsx | 12 +- ...fresh-keeps-deleted-session-removed.e2e.ts | 142 ++++++++++++++++++ 3 files changed, 186 insertions(+), 1 deletion(-) create mode 100644 scripts/scenarios/acp-refresh-keeps-deleted-session-removed.e2e.ts diff --git a/apps/web/src/components/settings/AcpSessionManagementSection.browser.test.tsx b/apps/web/src/components/settings/AcpSessionManagementSection.browser.test.tsx index 5277c93f491d5..d0b1292cca7cc 100644 --- a/apps/web/src/components/settings/AcpSessionManagementSection.browser.test.tsx +++ b/apps/web/src/components/settings/AcpSessionManagementSection.browser.test.tsx @@ -186,6 +186,39 @@ it("rechecks task access after confirming deletion", async () => { expect(commands.delete).not.toHaveBeenCalled(); }); +it("keeps a deleted ACP session out of a pending page only", async () => { + setup(); + commands.list.mockResolvedValueOnce({ + _tag: "Success", + value: { sessions: [session], nextCursor: "page-2" }, + }); + let finishPage!: (value: unknown) => void; + commands.list.mockReturnValueOnce( + new Promise((resolve) => { + finishPage = resolve; + }), + ); + const otherSession = { ...session, sessionId: `${session.sessionId}0` }; + await using screen = await renderSection(); + const deletedRow = screen.getByText(session.sessionId, { exact: true }); + await screen.click("List sessions"); + await screen.click("Load more"); + await screen.click("Delete"); + await expect.element(deletedRow).not.toBeInTheDocument(); + + await act(async () => + finishPage({ + _tag: "Success", + value: { sessions: [session, otherSession], nextCursor: null }, + }), + ); + await expect.element(screen.getByText(otherSession.sessionId, { exact: true })).toBeVisible(); + await expect.element(deletedRow).not.toBeInTheDocument(); + + await screen.click("Refresh"); + await expect.element(deletedRow).toBeVisible(); +}); + it.each(["Save", "Disable"])("keeps other provider edits through a %s refetch", async (action) => { setup(); const providers: AcpRegistryConfigurableProvider[] = ["google", "other"].map((providerId) => ({ diff --git a/apps/web/src/components/settings/AcpSessionManagementSection.tsx b/apps/web/src/components/settings/AcpSessionManagementSection.tsx index 9e00116390678..063c57d1681f8 100644 --- a/apps/web/src/components/settings/AcpSessionManagementSection.tsx +++ b/apps/web/src/components/settings/AcpSessionManagementSection.tsx @@ -120,10 +120,12 @@ function InstanceSessionManagement( const canRead = useEnvironmentScope(props.environmentId, AuthOrchestrationReadScope); const { projectId } = props; const projectGeneration = useRef(0); + const deletionsDuringList = useRef | null>(null); // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Late continuations must not act on a replaced project scope. useLayoutEffect(() => { return () => { projectGeneration.current += 1; + deletionsDuringList.current = null; }; // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Retiring a project invalidates its pending operations even when the instance stays mounted. }, [projectId]); @@ -191,6 +193,8 @@ function InstanceSessionManagement( const loadSessions = async (cursor?: string) => { const generation = projectGeneration.current; if (projectId === null || loading) return; + const deletedSessionIds = new Set(); + deletionsDuringList.current = deletedSessionIds; setLoading(true); const result = await listSessions({ environmentId: props.environmentId, @@ -201,10 +205,15 @@ function InstanceSessionManagement( }, }); if (generation !== projectGeneration.current) return; + deletionsDuringList.current = null; setLoading(false); if (result._tag === "Success") { + // A pending list can return a snapshot taken before a deletion completed. + const listedSessions = result.value.sessions.filter( + (session) => !deletedSessionIds.has(session.sessionId), + ); setSessions((current) => - cursor === undefined ? result.value.sessions : [...current, ...result.value.sessions], + cursor === undefined ? listedSessions : [...current, ...listedSessions], ); setNextCursor(result.value.nextCursor); return; @@ -276,6 +285,7 @@ function InstanceSessionManagement( if (generation !== projectGeneration.current) return; setDeletingSessionId(null); if (result._tag === "Success") { + deletionsDuringList.current?.add(session.sessionId); setSessions((current) => current.filter((candidate) => candidate.sessionId !== session.sessionId), ); diff --git a/scripts/scenarios/acp-refresh-keeps-deleted-session-removed.e2e.ts b/scripts/scenarios/acp-refresh-keeps-deleted-session-removed.e2e.ts new file mode 100644 index 0000000000000..5be5c909eedcd --- /dev/null +++ b/scripts/scenarios/acp-refresh-keeps-deleted-session-removed.e2e.ts @@ -0,0 +1,142 @@ +// @effect-diagnostics nodeBuiltinImport:off -- The scenario supplies a local ACP agent with a gated list. +import * as NodeHttp from "node:http"; +import * as NodePath from "node:path"; + +import { ProviderDriverKind, ProviderInstanceId } from "@t3tools/contracts"; +import { expect } from "e2e"; +import * as Effect from "effect/Effect"; + +import { T3_HOME } from "../e2e.config.ts"; +import { rpcClient, runPromise, test, WEB } from "./t3.ts"; + +const SESSION_TITLE = "Native draft to delete"; +const ACP = ` +import { createInterface } from "node:readline"; + +const [origin] = process.argv.slice(2); +const reply = (message) => process.stdout.write(JSON.stringify({ jsonrpc: "2.0", ...message }) + "\\n"); +const handle = async ({ method, params }) => { + if (method === "initialize") { + return { + protocolVersion: 1, + agentInfo: { name: "session-scenario", version: "1.0.0" }, + agentCapabilities: { sessionCapabilities: { list: {}, delete: {} } }, + authMethods: [], + }; + } + if (method === "session/new") return { sessionId: "health-probe" }; + if (method === "session/list") { + const response = await fetch(origin + "/list"); + const { present, title } = await response.json(); + return { sessions: present ? [{ sessionId: "native-draft", cwd: params.cwd, title }] : [] }; + } + if (method === "session/delete") { + if (params.sessionId === "native-draft") await fetch(origin + "/delete"); + return {}; + } + return undefined; +}; +// A gated session/list must not block the session/delete that arrives while it waits. +createInterface({ input: process.stdin }).on("line", (line) => { + const request = JSON.parse(line); + if (request.id === undefined) return; + void handle(request).then((result) => + reply( + result === undefined + ? { id: request.id, error: { code: -32601, message: "Method not found" } } + : { id: request.id, result }, + ), + ); +}); +`; + +test( + "Refreshing native ACP sessions does not bring back a session deleted during the refresh", + WEB, + async ({ t3, app, screen }) => { + const instanceId = ProviderInstanceId.make("scenario-session-agent"); + const snapshotTaken = Promise.withResolvers(); + const releaseSnapshot = Promise.withResolvers(); + let present = true; + let holdNextList = false; + const state = NodeHttp.createServer((request, response) => { + if (request.url === "/list") { + const snapshot = JSON.stringify({ present, title: SESSION_TITLE }); + const reply = () => + response.writeHead(200, { "Content-Type": "application/json" }).end(snapshot); + if (holdNextList) { + holdNextList = false; + snapshotTaken.resolve(); + void releaseSnapshot.promise.then(reply); + } else { + reply(); + } + } else if (request.url === "/delete") { + present = false; + response.writeHead(204).end(); + } else { + response.writeHead(404).end(); + } + }); + + try { + await new Promise((resolve) => state.listen(0, "127.0.0.1", resolve)); + const address = state.address(); + if (address === null || typeof address === "string") throw new Error("No fixture port"); + const project = await t3.project("demo", { "session-agent.mjs": ACP }); + await runPromise( + Effect.gen(function* () { + const client = yield* rpcClient(T3_HOME, app.baseUrl ?? ""); + yield* client["server.updateSettings"]({ + patch: {}, + providerInstanceMutation: { + operation: "upsert", + instanceId, + instance: { + driver: ProviderDriverKind.make("acpRegistry"), + displayName: "Session scenario agent", + enabled: true, + config: { + source: "local", + commandPath: process.execPath, + commandArgs: [ + NodePath.join(project, "session-agent.mjs"), + `http://127.0.0.1:${address.port}`, + ], + }, + }, + }, + }); + }).pipe(Effect.scoped), + ); + await t3.open(`/settings/providers?instanceId=${instanceId}`); + await screen.getByRole("button", "List sessions", { exact: true }).tap({ timeout: 60_000 }); + const entry = screen.getByText(SESSION_TITLE, { exact: true }); + await entry.waitFor(); + + holdNextList = true; + await screen.getByRole("button", "Refresh", { exact: true }).tap(); + await snapshotTaken.promise; + const remove = screen.getByRole("button", "Delete", { exact: true }); + const loading = screen.getByRole("button", "Loading", { exact: true }); + if (!(await remove.isVisible()) || !(await remove.isEnabled())) { + releaseSnapshot.resolve(); + await loading.waitFor({ state: "hidden" }); + } + await remove.tap(); + const confirm = screen.getByRole("alertdialog"); + await confirm.getByRole("button", "Confirm", { exact: true }).tap(); + await entry.waitFor({ state: "hidden" }); + expect(await loading.isVisible(), "The refresh is still pending after deletion").toBe(true); + + releaseSnapshot.resolve(); + await loading.waitFor({ state: "hidden" }); + await app.screenshot("after-deletion-and-refresh"); + expect(await entry.isVisible(), "The deleted native session stays off the list").toBe(false); + } finally { + releaseSnapshot.resolve(); + state.close(); + state.closeAllConnections(); + } + }, +); From 9d0d00656f5e3eab26b98690678aa1c1b4a16081 Mon Sep 17 00:00:00 2001 From: Helmi Pradita <50313181+helmipradita@users.noreply.github.com> Date: Fri, 20 Nov 2026 03:39:28 +0700 Subject: [PATCH 61/97] fix(server): keep Antigravity thread cwd in workspace by omitting attachmentsDir from additionalDirectories (#37997) Co-authored-by: Julius Marminge --- .../Adapters/AntigravityAdapterV2.test.ts | 17 +++++++++++++---- .../Adapters/AntigravityAdapterV2.ts | 1 - 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts index 5aed140fde08c..21022a97f36d5 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts @@ -585,17 +585,26 @@ describe("AntigravityAdapterV2 client file system", () => { runtimePolicy, }); yield* session.ensureThread({ threadId, modelSelection, runtimePolicy }); - const initialize = (yield* fileSystem.readFileString(requestLog)) + const requests = (yield* fileSystem.readFileString(requestLog)) .trim() .split("\n") .map( (line) => JSON.parse(line) as { method?: string; - params?: { clientCapabilities?: { fs?: unknown }; clientInfo?: { name?: string } }; + params?: { + clientCapabilities?: { fs?: unknown }; + clientInfo?: { name?: string }; + additionalDirectories?: unknown; + }; }, - ) - .find((request) => request.method === "initialize"); + ); + const initialize = requests.find((request) => request.method === "initialize"); + // agy runs shell commands from its lexicographically first root, so attachments + // must reach it through client reads, never as an extra workspace root. + assert.isUndefined( + requests.find((request) => request.method === "session/new")?.params?.additionalDirectories, + ); assert.deepEqual(initialize?.params?.clientCapabilities?.fs, { readTextFile: true, writeTextFile: false, diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts index 6f25f207fcc33..e07e64185d276 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts @@ -156,7 +156,6 @@ export function makeAntigravityAcpAdapterFlavor( ...input, clientFileReads: true, sessionSystemPromptAppend: PULL_REQUEST_LINKING_INSTRUCTIONS, - additionalDirectories: [options.host.paths.attachmentsDir], }), ) .pipe(Effect.provideService(Scope.Scope, scope)); From 3cd98dcbaed2052851c66bc355c23bf8767a558b Mon Sep 17 00:00:00 2001 From: Ali-Al1 <11404482+Ali-Al1@users.noreply.github.com> Date: Thu, 19 Nov 2026 20:40:17 +0000 Subject: [PATCH 62/97] fix(server): a secret card closes after the steering restart that supersedes it (#34634) Co-authored-by: Julius Marminge --- .../OrchestratorMcpService.activity.test.ts | 89 ++++++ apps/server/src/mcp/OrchestratorMcpService.ts | 7 + .../src/orchestration-v2/Orchestrator.ts | 30 +- .../SecretRequestRecord.test.ts | 292 ++++++++++++++++++ 4 files changed, 412 insertions(+), 6 deletions(-) create mode 100644 apps/server/src/orchestration-v2/SecretRequestRecord.test.ts diff --git a/apps/server/src/mcp/OrchestratorMcpService.activity.test.ts b/apps/server/src/mcp/OrchestratorMcpService.activity.test.ts index 4a7b08fbd870b..03c2a911cebf7 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.activity.test.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.activity.test.ts @@ -7,6 +7,7 @@ import { ProjectId, ProviderDriverKind, ProviderInstanceId, + RunAttemptId, RunId, ScheduledTaskId, SECRET_REQUEST_UNSAVED_NOTE, @@ -1202,3 +1203,91 @@ it("requestSecret returns the unsaved note for a declined, cancelled or timed-ou { status: "timed_out", note: SECRET_REQUEST_UNSAVED_NOTE.timed_out }, ]); }); + +it("requestSecret cancels its card when a steering restart supersedes the request", async () => { + const originalRoot = NodeId.make("node-mcp-secret-root-original"); + const steeredRoot = NodeId.make("node-mcp-secret-root-steered"); + const dispatched: Array<{ + readonly type: string; + readonly turnItemId?: TurnItemId; + readonly nodeId?: NodeId; + readonly secretStatus?: string; + }> = []; + let steered = false; + const projection = () => { + const card = dispatched.find( + (command) => command.type === "secret_request.record" && command.secretStatus === "pending", + ); + return { + thread: baseThread({ + threadId: parentThreadId, + title: "Parent", + instanceId: parentInstanceId, + model: "gpt-5.4", + }), + runs: [ + { + ...makeRun({ id: activeRunId, ordinal: 1, status: "running" }), + rootNodeId: steered ? steeredRoot : originalRoot, + activeAttemptId: RunAttemptId.make("attempt-mcp-secret-original"), + }, + ], + visibleTurnItems: [], + turnItems: + card === undefined + ? [] + : [{ type: "secret_request", id: card.turnItemId, secretStatus: "pending" }], + providerTurns: [], + runtimeRequests: [], + messages: [], + contextTransfers: [], + subagents: [], + updatedAt: now, + } as unknown as OrchestrationV2ThreadProjection; + }; + const layer = layerOrchestratorService.pipe( + Layer.provide( + Layer.mergeAll( + Layer.mock(ThreadManagementService.ThreadManagementService)({ + getThreadRecords: () => Effect.sync(projection), + getThreadShell: () => + Effect.sync(() => projection().thread as unknown as OrchestrationV2ThreadShell), + dispatch: (command) => + Effect.sync(() => { + dispatched.push(command as (typeof dispatched)[number]); + // The user steers right after the card opens, replacing the run's root. + if (command.type === "secret_request.record" && command.secretStatus === "pending") { + steered = true; + } + return undefined as never; + }), + } satisfies Partial), + ServerSettings.layerTest(), + Layer.mock(ProviderRegistry.ProviderRegistry)({ + getProviders: Effect.succeed([]), + } satisfies Partial), + Layer.mock(ProjectService.ProjectService)({}), + Layer.mock(SecretRequests.SecretRequests)({}), + Layer.mock(RemoteDelegation.RemoteDelegation)({}), + Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), + Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({}), + NodeCrypto.layer, + ), + ), + ); + + await Effect.gen(function* () { + const service = yield* OrchestratorMcpService.OrchestratorMcpService; + const result = yield* service.requestSecret(makeScope(), { + label: "Booking details", + reason: "To check the passenger in.", + timeoutMs: 60_000, + }); + // The wait ended the moment its attempt was superseded instead of blocking + // the agent's turn until the timeout, and the card closed with it. + expect(result).toEqual({ status: "cancelled", note: SECRET_REQUEST_UNSAVED_NOTE.cancelled }); + const records = dispatched.filter((command) => command.type === "secret_request.record"); + expect(records.map((command) => command.secretStatus)).toEqual(["pending", "cancelled"]); + expect(records.every((command) => command.nodeId === originalRoot)).toBe(true); + }).pipe(Effect.provide(layer), Effect.runPromise); +}); diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts index 74599bbade796..c9009d6597671 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.ts @@ -2588,6 +2588,13 @@ const make = Effect.gen(function* () { yield* record("cancelled"); return "cancelled" as const; } + // A steering restart replaced the run's root, so this request belonged to + // the superseded attempt: its card can never be answered into that attempt, + // and the call must stop blocking the agent's turn. + if (current.rootNodeId !== nodeId) { + yield* record("cancelled"); + return "cancelled" as const; + } yield* Effect.sleep(Duration.millis(SECRET_REQUEST_POLL_INTERVAL_MS)); } }).pipe( diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index b8e6a869dd17d..0a3424735a670 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -10791,14 +10791,23 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ), ); const run = projection.runs.find((candidate) => candidate.id === command.runId); - if (run === undefined || run.rootNodeId !== command.nodeId) { + if (run === undefined) { return yield* new OrchestratorDispatchError({ commandId: command.commandId, commandType: command.type, - cause: `Node ${command.nodeId} is not the root of run ${command.runId}.`, + cause: `Run ${command.runId} was not found.`, }); } const existing = projection.turnItems.find((item) => item.id === command.turnItemId); + // Only a new card needs its run's current root. A steer restarts the run + // under a new root, and the card asked before it must still close. + if (existing === undefined && run.rootNodeId !== command.nodeId) { + return yield* new OrchestratorDispatchError({ + commandId: command.commandId, + commandType: command.type, + cause: `Node ${command.nodeId} is not the root of run ${command.runId}.`, + }); + } if (existing !== undefined && existing.type !== "secret_request") { return yield* new OrchestratorDispatchError({ commandId: command.commandId, @@ -10813,6 +10822,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio cause: `Secret request ${command.turnItemId} belongs to another run.`, }); } + const nodeId = existing?.nodeId ?? command.nodeId; const now = yield* DateTime.now; const unchanged = existing !== undefined && @@ -10824,9 +10834,17 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio id: command.turnItemId, threadId: command.threadId, runId: command.runId, - nodeId: command.nodeId, - providerThreadId: run.providerThreadId, - providerTurnId: providerTurnForRun(projection, run)?.id ?? null, + nodeId, + // An update keeps where the card was asked, even after a restart. + ...(existing === undefined + ? { + providerThreadId: run.providerThreadId, + providerTurnId: providerTurnForRun(projection, run)?.id ?? null, + } + : { + providerThreadId: existing.providerThreadId, + providerTurnId: existing.providerTurnId, + }), nativeItemRef: null, parentItemId: null, ordinal: existing?.ordinal ?? (yield* nextTurnItemOrdinal(projection)), @@ -10870,7 +10888,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio type: "turn-item.updated", threadId: command.threadId, runId: command.runId, - nodeId: command.nodeId, + nodeId, providerInstanceId: run.providerInstanceId, occurredAt: now, payload: turnItem, diff --git a/apps/server/src/orchestration-v2/SecretRequestRecord.test.ts b/apps/server/src/orchestration-v2/SecretRequestRecord.test.ts new file mode 100644 index 0000000000000..2860b279c836a --- /dev/null +++ b/apps/server/src/orchestration-v2/SecretRequestRecord.test.ts @@ -0,0 +1,292 @@ +import { assert, it } from "@effect/vitest"; +import { + CommandId, + EventId, + MessageId, + NodeId, + ProjectId, + ProviderDriverKind, + ProviderInstanceId, + ProviderSessionId, + ProviderThreadId, + ProviderTurnId, + RunAttemptId, + RunId, + ThreadId, + TurnItemId, +} from "@t3tools/contracts"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as SqlitePersistence from "../persistence/Sqlite.ts"; +import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts"; +import * as EffectOutbox from "./EffectOutbox.ts"; +import * as Orchestrator from "./Orchestrator.ts"; +import * as ProjectionStore from "./ProjectionStore.ts"; +import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts"; +import * as ProviderReplayHarness from "./testkit/ProviderReplayHarness.ts"; +import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; + +const instanceId = ProviderInstanceId.make("codex"); +const modelSelection = { instanceId, model: "gpt-5.1-codex" }; +const adapter = { + instanceId, + driver: ProviderDriverKind.make("codex"), + getCapabilities: () => Effect.succeed(CodexProviderCapabilitiesV2), + planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" as const }), + openSession: () => Effect.die("No provider process needed for record controls"), +} as ProviderAdapter.ProviderAdapterV2["Service"]; +const layerDatabase = SqlitePersistence.layerMemory; +const layerTest = Layer.mergeAll( + layerDatabase, + ProjectionStore.layer.pipe(Layer.provide(layerDatabase)), + EffectOutbox.layer.pipe(Layer.provide(layerDatabase)), + ProviderReplayHarness.layerWithRegistry( + { name: "secret-request-record" }, + ProviderAdapterRegistry.layerFromAdapters([adapter]), + { databaseLayer: layerDatabase, runEffectWorker: false }, + ), +); + +const projectId = ProjectId.make("project:secret-request-record"); +const threadId = ThreadId.make("thread:secret-request-record"); +const sessionId = ProviderSessionId.make("session:secret-request-record"); +const providerThreadId = ProviderThreadId.make("provider-thread:secret-request-record"); +const runId = RunId.make("run:secret-request-record"); +const firstAttemptId = RunAttemptId.make("attempt:secret-request-record:1"); +const steeredAttemptId = RunAttemptId.make("attempt:secret-request-record:2"); +const originalRoot = NodeId.make("node:secret-request-record:original"); +const steeredRoot = NodeId.make("node:secret-request-record:steered"); +const originalTurnId = ProviderTurnId.make("provider-turn:secret-request-record:original"); +const messageId = MessageId.make("message:secret-request-record"); +const cardId = TurnItemId.make("turn-item:secret-request:secret-request-record"); +const staleCardId = TurnItemId.make("turn-item:secret-request:secret-request-record:stale"); +const now = DateTime.makeUnsafe("2026-11-11T20:00:00.000Z"); + +/** + * A pending secret card must stay closable after a steering restart replaces the + * run's root node: the call that opened it only ever carries the card's own node, + * so rejecting that node wedges the card open forever. + */ +it.effect("closes a secret card recorded under an earlier root after a steering restart", () => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const projections = yield* ProjectionStore.ProjectionStoreV2; + yield* orchestrator.dispatch({ + type: "thread.create", + commandId: CommandId.make("create-secret-request-record"), + threadId, + projectId, + title: "Secret request record", + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + createdBy: "user", + creationSource: "web", + }); + yield* projections.apply({ + id: EventId.make("secret-request-record:session"), + type: "provider-session.attached", + threadId, + occurredAt: now, + payload: { + id: sessionId, + driver: adapter.driver, + providerInstanceId: instanceId, + status: "ready", + cwd: "/repo", + model: modelSelection.model, + capabilities: CodexProviderCapabilitiesV2, + createdAt: now, + updatedAt: now, + lastError: null, + }, + }); + yield* projections.apply({ + id: EventId.make("secret-request-record:provider-thread"), + type: "provider-thread.updated", + threadId, + occurredAt: now, + payload: { + id: providerThreadId, + driver: adapter.driver, + providerInstanceId: instanceId, + providerSessionId: sessionId, + appThreadId: threadId, + ownerNodeId: null, + nativeThreadRef: { driver: adapter.driver, nativeId: "native-thread", strength: "strong" }, + nativeConversationHeadRef: null, + status: "idle", + firstRunOrdinal: 1, + lastRunOrdinal: 1, + handoffIds: [], + forkedFrom: null, + createdAt: now, + updatedAt: now, + }, + }); + yield* projections.apply({ + id: EventId.make("secret-request-record:run"), + type: "run.created", + threadId, + occurredAt: now, + payload: { + id: runId, + threadId, + ordinal: 1, + providerInstanceId: instanceId, + modelSelection, + providerThreadId, + userMessageId: messageId, + rootNodeId: originalRoot, + activeAttemptId: firstAttemptId, + status: "running", + requestedAt: now, + startedAt: now, + completedAt: null, + checkpointId: null, + contextHandoffId: null, + }, + }); + yield* projections.apply({ + id: EventId.make("secret-request-record:attempt-1"), + type: "run-attempt.created", + threadId, + occurredAt: now, + payload: { + id: firstAttemptId, + runId, + attemptOrdinal: 1, + rootNodeId: originalRoot, + providerInstanceId: instanceId, + providerThreadId, + providerTurnId: null, + reason: "initial", + status: "running", + startedAt: now, + completedAt: null, + }, + }); + + // The first attempt reached the provider; the card is asked on that turn. + yield* projections.apply({ + id: EventId.make("secret-request-record:turn"), + type: "provider-turn.updated", + threadId, + occurredAt: now, + payload: { + id: originalTurnId, + providerThreadId, + nodeId: originalRoot, + runAttemptId: firstAttemptId, + nativeTurnRef: null, + ordinal: 1, + status: "running", + startedAt: now, + completedAt: null, + }, + }); + + const record = (commandId: string, nodeId: NodeId, turnItemId: TurnItemId) => + orchestrator.dispatch({ + type: "secret_request.record", + commandId: CommandId.make(commandId), + threadId, + runId, + nodeId, + turnItemId, + label: "Booking details", + reason: "To check the passenger in.", + secretStatus: "pending" as const, + }); + const readCard = (id: TurnItemId) => + projections + .getThreadRecords(threadId, ["turnItems"], { + turnItemTypes: ["secret_request"], + messageRoles: [], + }) + .pipe( + Effect.map((records) => { + const item = records.turnItems.find((candidate) => candidate.id === id); + return item?.type === "secret_request" ? item : undefined; + }), + ); + + yield* record("secret-request-record:open", originalRoot, cardId); + const opened = yield* readCard(cardId); + assert.equal(opened?.secretStatus, "pending"); + assert.equal(opened?.providerTurnId, originalTurnId); + + // The user steers while the card waits: the run's root moves to a new attempt. + yield* projections.apply({ + id: EventId.make("secret-request-record:run-steered"), + type: "run.updated", + threadId, + occurredAt: now, + payload: { + id: runId, + threadId, + ordinal: 1, + providerInstanceId: instanceId, + modelSelection, + providerThreadId, + userMessageId: messageId, + rootNodeId: steeredRoot, + activeAttemptId: steeredAttemptId, + status: "starting", + requestedAt: now, + startedAt: now, + completedAt: null, + checkpointId: null, + contextHandoffId: null, + }, + }); + yield* projections.apply({ + id: EventId.make("secret-request-record:attempt-2"), + type: "run-attempt.created", + threadId, + occurredAt: now, + payload: { + id: steeredAttemptId, + runId, + attemptOrdinal: 2, + rootNodeId: steeredRoot, + providerInstanceId: instanceId, + providerThreadId, + providerTurnId: null, + reason: "steering_restart", + status: "pending", + startedAt: null, + completedAt: null, + }, + }); + + // The waiting call only carries the card's own node; closing must still work. + yield* orchestrator.dispatch({ + type: "secret_request.record", + commandId: CommandId.make("secret-request-record:close"), + threadId, + runId, + nodeId: originalRoot, + turnItemId: cardId, + label: "Booking details", + reason: "To check the passenger in.", + secretStatus: "cancelled" as const, + }); + const cancelled = yield* readCard(cardId); + assert.equal(cancelled?.secretStatus, "cancelled"); + assert.equal(cancelled?.status, "cancelled"); + // Closing through the card's own node keeps the identity it was asked with, + // even though the run's active attempt has no provider turn of its own. + assert.equal(cancelled?.nodeId, originalRoot); + assert.equal(cancelled?.providerTurnId, originalTurnId); + + // A new card may not be opened under the stale root. + const stale = yield* Effect.flip( + record("secret-request-record:stale-open", originalRoot, staleCardId), + ); + assert.match(String((stale as { cause?: unknown }).cause ?? ""), /is not the root of run/); + }).pipe(Effect.provide(layerTest)), +); From 40c1e861eec7ff9936b582a2ffb6225265041fd1 Mon Sep 17 00:00:00 2001 From: screen Date: Thu, 19 Nov 2026 19:25:46 +0400 Subject: [PATCH 63/97] fix(web): keep sidebar update control readable when narrow (cherry picked from commit f0b4502be23f4961668eff044386e4b59bf78533) --- .../sidebar/SidebarUpdateCapsule.tsx | 42 +++++++++++-------- .../components/sidebar/SidebarUpdatePill.tsx | 2 +- 2 files changed, 26 insertions(+), 18 deletions(-) diff --git a/apps/web/src/components/sidebar/SidebarUpdateCapsule.tsx b/apps/web/src/components/sidebar/SidebarUpdateCapsule.tsx index ab75793f85b5c..d59d33927915a 100644 --- a/apps/web/src/components/sidebar/SidebarUpdateCapsule.tsx +++ b/apps/web/src/components/sidebar/SidebarUpdateCapsule.tsx @@ -90,6 +90,10 @@ export function SidebarUpdateCapsule({ const updateServer = useServerUpdate(); const failed = machines.some(({ status }) => status === "failed"); const settled = !hasActiveMachine && run.localVersion === null; + const restartSeconds = + run.phase === "countdown" && run.restartAt !== null + ? Math.max(0, Math.ceil((run.restartAt - now) / 1000)) + : null; const actionLabel = view.action === "later" ? gt("Later") : view.action === "retry" ? gt("Retry") : gt("Dismiss"); @@ -103,7 +107,7 @@ export function SidebarUpdateCapsule({
} /> - {/* w-0 keeps the label out of the capsule's minimum width, so a shared footer row - can squeeze the label but never push the action past the sidebar edge. */} - + {view.label} {view.slow ? ( {view.slow.elapsed} @@ -130,16 +132,22 @@ export function SidebarUpdateCapsule({ {view.action !== null ? ( - ) : ( - - {icon} - - )} + ) : null} + + {restartSeconds !== null ? `${restartSeconds}s` : icon} +
@@ -183,16 +191,16 @@ export function SidebarUpdateCapsule({ ) : null}
))} - {settled && failed ? ( + {view.action !== null ? (
- {view.action === "retry" ? ( - + {settled && failed && view.action !== "dismiss" ? ( + ) : null} -
) : null} diff --git a/apps/web/src/components/sidebar/SidebarUpdatePill.tsx b/apps/web/src/components/sidebar/SidebarUpdatePill.tsx index ce45fe8bf73a4..71fce36f3ed43 100644 --- a/apps/web/src/components/sidebar/SidebarUpdatePill.tsx +++ b/apps/web/src/components/sidebar/SidebarUpdatePill.tsx @@ -441,7 +441,7 @@ function SidebarUpdateControl() { ? { status: "downloading", percent: state.downloadPercent } : { status: "waiting" }; return ( - + Date: Thu, 19 Nov 2026 19:45:07 +0400 Subject: [PATCH 64/97] fix(web): localize compact restart countdown (cherry picked from commit e5dc6ef974cf8c1d2f429e4922a34eb5f29bce4d) --- apps/web/src/components/sidebar/SidebarUpdateCapsule.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/web/src/components/sidebar/SidebarUpdateCapsule.tsx b/apps/web/src/components/sidebar/SidebarUpdateCapsule.tsx index d59d33927915a..d789cea9fd070 100644 --- a/apps/web/src/components/sidebar/SidebarUpdateCapsule.tsx +++ b/apps/web/src/components/sidebar/SidebarUpdateCapsule.tsx @@ -146,7 +146,7 @@ export function SidebarUpdateCapsule({ "rounded-full text-xs font-medium tabular-nums ring-1 ring-current/22 ring-inset", )} > - {restartSeconds !== null ? `${restartSeconds}s` : icon} + {restartSeconds !== null ? m(msg("{seconds}s", { seconds: restartSeconds })) : icon} From 98af8803fe6b21b05320786479836b50735fb0aa Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 19 Nov 2026 18:08:51 +0000 Subject: [PATCH 65/97] refactor(web): share restart countdown seconds in update capsule Co-Authored-By: Claude Opus 5.5 --- .../sidebar/SidebarUpdateCapsule.tsx | 20 +++++++++---------- 1 file changed, 9 insertions(+), 11 deletions(-) diff --git a/apps/web/src/components/sidebar/SidebarUpdateCapsule.tsx b/apps/web/src/components/sidebar/SidebarUpdateCapsule.tsx index d789cea9fd070..2e6cbe19390cc 100644 --- a/apps/web/src/components/sidebar/SidebarUpdateCapsule.tsx +++ b/apps/web/src/components/sidebar/SidebarUpdateCapsule.tsx @@ -46,19 +46,20 @@ function useUpdateRunMachineViews(run: UpdateEverythingRun): ReadonlyArray status === "failed"); const settled = !hasActiveMachine && run.localVersion === null; - const restartSeconds = - run.phase === "countdown" && run.restartAt !== null - ? Math.max(0, Math.ceil((run.restartAt - now) / 1000)) - : null; + const restartSeconds = restartSecondsLeft(run, now); const actionLabel = view.action === "later" ? gt("Later") : view.action === "retry" ? gt("Retry") : gt("Dismiss"); From 02c5270a116f8317e5c0917a37b17c58c6251461 Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Thu, 19 Nov 2026 21:42:45 +0100 Subject: [PATCH 66/97] fix(web): keep SSH connection checks pending until they finish (#39328) Co-authored-by: Julius Marminge --- .../settings/DeviceSourcesSettings.tsx | 28 ++++-- .../settings/useHostConnectionChecks.ts | 9 +- ...vice-host-test-keeps-pending-status.e2e.ts | 97 +++++++++++++++++++ 3 files changed, 120 insertions(+), 14 deletions(-) create mode 100644 scripts/scenarios/device-host-test-keeps-pending-status.e2e.ts diff --git a/apps/web/src/components/settings/DeviceSourcesSettings.tsx b/apps/web/src/components/settings/DeviceSourcesSettings.tsx index 5102d9ffdbf8d..98a88b7e5aaba 100644 --- a/apps/web/src/components/settings/DeviceSourcesSettings.tsx +++ b/apps/web/src/components/settings/DeviceSourcesSettings.tsx @@ -33,7 +33,11 @@ import { Spinner } from "../ui/spinner"; import { toastManager } from "../ui/toast"; import { incompleteListings } from "../device/DeviceSetup"; import { DeviceHostEditor } from "./DeviceHostEditor"; -import { updateDeviceHosts, groupDeviceHosts } from "./deviceHostsSettings.logic"; +import { + updateDeviceHosts, + groupDeviceHosts, + type DeviceHostGroup, +} from "./deviceHostsSettings.logic"; import { EasDeviceHostEditor } from "./EasDeviceHostEditor"; import { easSessionLimits, @@ -320,17 +324,20 @@ export function DeviceSourcesSettings(props: { gt("Simlock host not removed everywhere"), ); - const [testing, setTesting] = useState>(new Set()); - const testSsh = async (host: SshDeviceHostConfig) => { - setTesting((current) => new Set(current).add(host.id)); - const checked = await testConnection(host).finally(() => - setTesting((current) => { + const [testingHosts, setTestingHosts] = useState>(new Set()); + const testSsh = async ({ host, members }: DeviceHostGroup) => { + const check = testConnection(host); + if (!check) return; + // Every member's id, so the row that remains after an environment drops out stays pending. + const ids = members.map((member) => member.host.id); + setTestingHosts((current) => new Set([...current, ...ids])); + const checked = await check.finally(() => + setTestingHosts((current) => { const next = new Set(current); - next.delete(host.id); + for (const id of ids) next.delete(id); return next; }), ); - if (!checked) return; const failed = targets.filter((target) => checked[target.environmentId]?.status === "failed"); toastManager.add({ type: failed.length ? "error" : "success", @@ -435,6 +442,7 @@ export function DeviceSourcesSettings(props: { for (const group of sshGroups) { const host = group.host; const holders = new Set(group.members.map((member) => member.environmentId)); + const testing = group.members.some((member) => testingHosts.has(member.host.id)); rows.push({ key: `ssh:${host.id}:${group.members.map((member) => member.environmentId).join(",")}`, shared: true, @@ -447,7 +455,7 @@ export function DeviceSourcesSettings(props: { ); if (!held) return { environmentId: member.environmentId, label: member.label, added: false }; - const status = testing.has(host.id) + const status = testing ? ({ tone: "pending", label: gt("Testing connection") } as const) : hostStatus(member.state, held.host.id, m); return { @@ -472,7 +480,7 @@ export function DeviceSourcesSettings(props: { () => setEditing({ kind: "ssh", host, original: host, ...(grouped ? {} : { only: holders }) }), () => void saveSsh(host, true, host, holders), - void testSsh(host)}> + void testSsh(group)}> Test connection , ), diff --git a/apps/web/src/components/settings/useHostConnectionChecks.ts b/apps/web/src/components/settings/useHostConnectionChecks.ts index 4765477036a38..11b804444a44c 100644 --- a/apps/web/src/components/settings/useHostConnectionChecks.ts +++ b/apps/web/src/components/settings/useHostConnectionChecks.ts @@ -18,13 +18,13 @@ export function useHostConnectionChecks(targets: ReadonlyArray>>({}); const running = useRef(new Set()); - const testConnection = async (host: SshDeviceHostConfig) => { + const testConnection = (host: SshDeviceHostConfig) => { const key = deviceHostConnectionKey(host); if (running.current.has(key)) return; running.current.add(key); setChecks((current) => ({ ...current, [key]: {} })); const results: Record = {}; - await checkDeviceHostConnections( + return checkDeviceHostConnections( targets, host, async (environmentId, input) => { @@ -42,8 +42,9 @@ export function useHostConnectionChecks(targets: ReadonlyArray running.current.delete(key)); - return results; + ) + .then(() => results) + .finally(() => running.current.delete(key)); }; return { checks, testConnection }; } diff --git a/scripts/scenarios/device-host-test-keeps-pending-status.e2e.ts b/scripts/scenarios/device-host-test-keeps-pending-status.e2e.ts new file mode 100644 index 0000000000000..8f4b09d77dd96 --- /dev/null +++ b/scripts/scenarios/device-host-test-keeps-pending-status.e2e.ts @@ -0,0 +1,97 @@ +/// +import { expect } from "e2e"; +import * as Effect from "effect/Effect"; + +import { T3_HOME } from "../e2e.config.ts"; +import { environmentId, rpcClient, runPromise, test, WEB } from "./t3.ts"; + +declare global { + interface Window { + deviceHostProbeGate?: { readonly started: Promise; readonly release: () => void }; + } +} + +test( + "A second SSH connection check keeps the pending status visible", + WEB, + async ({ t3, app, browser, screen }) => { + const origin = app.baseUrl ?? ""; + const environment = await runPromise(environmentId(origin)); + await t3.project("demo"); + await runPromise( + Effect.gen(function* () { + const client = yield* rpcClient(T3_HOME, origin); + yield* client["server.updateSettings"]({ + patch: { + enableDeviceSupport: true, + deviceHosts: [ + { kind: "ssh", id: "slow-host", label: "Slow host", target: "127.0.0.1", port: 1 }, + ], + }, + }); + }).pipe(Effect.scoped), + ); + + // Delay just the explicit probe at the transport boundary until after the UI sample. + await browser.addInitScript(() => { + const held: Array<() => void> = []; + const started = Promise.withResolvers(); + let delaying = true; + const send = WebSocket.prototype.send; + WebSocket.prototype.send = function (this: WebSocket, data) { + if (!delaying || typeof data !== "string") return send.call(this, data); + const parsed = JSON.parse(data); + const messages = [parsed].flat(); + const isProbe = (message: { _tag?: string; tag?: string }) => + message?._tag === "Request" && message.tag === "device.testHost"; + if (!messages.some(isProbe)) return send.call(this, data); + const probes = messages.filter(isProbe); + const other = messages.filter((message) => !isProbe(message)); + if (other.length) send.call(this, JSON.stringify(other)); + held.push(() => send.call(this, Array.isArray(parsed) ? JSON.stringify(probes) : data)); + started.resolve(); + }; + window.deviceHostProbeGate = { + started: started.promise, + release: () => { + delaying = false; + for (const release of held.splice(0)) release(); + }, + }; + }); + + await t3.open(`/settings/devices?machine=${encodeURIComponent(environment)}#device-sources`); + const more = browser.locator("#device-sources").getByRole("button", "More", { exact: true }); + const testConnection = screen.getByRole("menuitem", "Test connection", { exact: true }); + const pending = screen.getByText("Testing connection", { exact: true }); + try { + await more.tap(); + await testConnection.tap(); + await pending.waitFor(); + await browser.evaluate(async () => { + await window.deviceHostProbeGate!.started; + return null; + }); + if (await more.isEnabled()) { + await more.tap(); + await screen.getByRole("menu").waitFor(); + if ((await testConnection.isVisible()) && (await testConnection.isEnabled())) { + await testConnection.tap(); + await testConnection.waitFor({ state: "hidden" }); + } else { + await browser.keyboard.press("Escape"); + } + } + + await app.screenshot("second-connection-check"); + expect(await pending.isVisible(), "The SSH connection check still shows as pending").toBe( + true, + ); + } finally { + await browser.evaluate(() => { + window.deviceHostProbeGate?.release(); + return null; + }); + } + }, +); From b5bef4d9391117ad0d95b3a8f91a63200861ed54 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 19 Nov 2026 12:43:01 -0800 Subject: [PATCH 67/97] fix(server): /logout in chat needs providers:manage (#39027) --- apps/server/src/auth/RpcAuthorization.test.ts | 78 +++++++++++++++++++ apps/server/src/auth/RpcAuthorization.ts | 35 ++++++++- apps/server/src/mcp/toolkits/core.test.ts | 39 ++++++++-- .../src/mcp/toolkits/thread/handlers.ts | 21 ++++- .../src/orchestration-v2/CommandPolicy.ts | 11 +++ .../ProviderTurnStartService.test.ts | 28 ++++++- .../ProviderTurnStartService.ts | 4 + .../ThreadLaunchService.test.ts | 11 ++- .../ThreadMessageIntake.test.ts | 72 ++++++++++++++++- .../orchestration-v2/ThreadMessageIntake.ts | 51 +++++++++++- .../src/provider/ProviderAuthService.test.ts | 41 +++++++++- .../src/provider/ProviderAuthService.ts | 14 +++- apps/server/src/ws.ts | 6 ++ docs/user/providers-antigravity.md | 2 + 14 files changed, 391 insertions(+), 22 deletions(-) diff --git a/apps/server/src/auth/RpcAuthorization.test.ts b/apps/server/src/auth/RpcAuthorization.test.ts index 8afe47e715a9f..1d38610692965 100644 --- a/apps/server/src/auth/RpcAuthorization.test.ts +++ b/apps/server/src/auth/RpcAuthorization.test.ts @@ -17,6 +17,10 @@ import { AuthSourceControlWriteScope, AuthTerminalReadScope, AuthTerminalOperateScope, + CommandId, + MessageId, + ORCHESTRATION_V2_WS_METHODS, + RunId, WS_METHODS, WsRpcGroup, } from "@t3tools/contracts"; @@ -606,3 +610,77 @@ it.effect("denies manual cleanup before the handler without settings permission" expect(handled).toBe(false); }), ); + +it.effect("requires provider management to send /logout through chat", () => + Effect.gen(function* () { + const group = WsRpcGroup.omit( + ...[...WsRpcGroup.requests.keys()].filter( + ( + tag, + ): tag is Exclude< + keyof typeof RPC_REQUIRED_SCOPES, + typeof ORCHESTRATION_V2_WS_METHODS.dispatchCommand + > => tag !== ORCHESTRATION_V2_WS_METHODS.dispatchCommand, + ), + ); + const handled: string[] = []; + const handler = group.toLayerHandler(ORCHESTRATION_V2_WS_METHODS.dispatchCommand, (command) => + Effect.sync(() => { + handled.push(command.commandId); + return { sequence: 1 }; + }), + ); + const message = (commandId: string, text: string) => ({ + type: "message.dispatch" as const, + createdBy: "user" as const, + creationSource: "web" as const, + commandId: CommandId.make(commandId), + threadId: ThreadId.make("thread"), + messageId: MessageId.make(commandId), + text, + attachments: [], + dispatchMode: { type: "start_immediately" as const }, + }); + const edit = (commandId: string) => ({ + type: "queued-run.edit" as const, + commandId: CommandId.make(commandId), + threadId: ThreadId.make("thread"), + runId: RunId.make("run"), + text: "/logout", + }); + // With an attachment, `/logout` reaches the provider as a prompt, not a sign-out. + const attachments = [ + { type: "image" as const, id: "shot", name: "shot.png", mimeType: "image/png", sizeBytes: 1 }, + ]; + const operator = yield* RpcTest.makeClient(group).pipe( + Effect.provide(Layer.merge(handler, RpcAuthorization.layer([AuthOrchestrationOperateScope]))), + ); + const dispatch = operator[ORCHESTRATION_V2_WS_METHODS.dispatchCommand]; + yield* dispatch(message("hello", "hello")); + yield* dispatch({ ...message("attached", "/logout"), attachments }); + yield* dispatch({ ...edit("attached-edit"), attachments }); + // This edit keeps the queued attachments; message intake decides it. + yield* dispatch(edit("kept-attachments-edit")); + for (const command of [message("logout", " /LOGOUT "), { ...edit("edit"), attachments: [] }]) { + expect(yield* dispatch(command).pipe(Effect.flip)).toMatchObject({ + requiredPermission: AuthProvidersManageScope, + }); + } + const manager = yield* RpcTest.makeClient(group).pipe( + Effect.provide( + Layer.merge( + handler, + RpcAuthorization.layer([AuthOrchestrationOperateScope, AuthProvidersManageScope]), + ), + ), + ); + yield* manager[ORCHESTRATION_V2_WS_METHODS.dispatchCommand](message("manager", "/logout")); + expect(handled).toEqual([ + "hello", + "attached", + "attached-edit", + "kept-attachments-edit", + "manager", + ]); + }).pipe(Effect.scoped), +); diff --git a/apps/server/src/auth/RpcAuthorization.ts b/apps/server/src/auth/RpcAuthorization.ts index 2e73a401caaff..859beb21d354a 100644 --- a/apps/server/src/auth/RpcAuthorization.ts +++ b/apps/server/src/auth/RpcAuthorization.ts @@ -24,6 +24,8 @@ import { AuthRelayWriteScope, AuthTerminalOperateScope, ORCHESTRATION_V2_WS_METHODS, + type OrchestrationV2Command, + type OrchestrationV2ThreadLaunchInput, AuthTerminalReadScope, type AuthEnvironmentScope, EnvironmentAuthorizationError, @@ -35,6 +37,7 @@ import * as Effect from "effect/Effect"; import * as Schema from "effect/Schema"; import * as Layer from "effect/Layer"; import type * as RpcGroup from "effect/rpc/RpcGroup"; +import { isProviderSignOutPrompt } from "../orchestration-v2/CommandPolicy.ts"; type WsRpcMethod = RpcGroup.Rpcs["_tag"]; @@ -265,6 +268,32 @@ const requiredScopesForSettingsUpdate = (payload: unknown) => { const decodeProjectMutation = Schema.decodeUnknownSync(ProjectMutation); const decodeAssetCreateUrlInput = Schema.decodeUnknownSync(AssetCreateUrlInput); +/** + * A queued edit that omits `attachments` keeps the queued ones, which a payload cannot show; + * ThreadMessageIntake.dispatchCommand decides that case. + */ +const sendsProviderSignOutPrompt = (method: string, payload: unknown): boolean => { + if (method === ORCHESTRATION_V2_WS_METHODS.launchThread) { + const message = (payload as OrchestrationV2ThreadLaunchInput).initialMessage; + return message !== undefined && isProviderSignOutPrompt(message); + } + if (method !== ORCHESTRATION_V2_WS_METHODS.dispatchCommand) return false; + const command = payload as OrchestrationV2Command; + switch (command.type) { + case "message.dispatch": + return isProviderSignOutPrompt(command); + case "queued-run.edit": + return ( + command.attachments !== undefined && + isProviderSignOutPrompt({ text: command.text, attachments: command.attachments }) + ); + case "delegated_task.request": + return isProviderSignOutPrompt({ text: command.task, attachments: [] }); + default: + return false; + } +}; + const requiredScopesForRpcCall = ( method: string, payload: unknown, @@ -297,8 +326,10 @@ const requiredScopesForRpcCall = ( return requiredScopesForProjectMutation(decodeProjectMutation(payload)); } const guarded = clientRpcRequiredScopes(method, payload); - if (guarded.length > 0) return guarded; - return [requiredScopeForRpcMethod(method)]; + const scopes = guarded.length > 0 ? guarded : [requiredScopeForRpcMethod(method)]; + return sendsProviderSignOutPrompt(method, payload) + ? [...scopes, AuthProvidersManageScope] + : scopes; }; /** diff --git a/apps/server/src/mcp/toolkits/core.test.ts b/apps/server/src/mcp/toolkits/core.test.ts index af2501b295c56..daadff0e09d54 100644 --- a/apps/server/src/mcp/toolkits/core.test.ts +++ b/apps/server/src/mcp/toolkits/core.test.ts @@ -473,7 +473,10 @@ it.effect("records only failed calls of tools that hand off no work", () => { }); // A thread read whose runs or messages are bounded by nothing but the thread. -const historyReads = (reads: Array) => { +const historyReads = ( + reads: Array, + queued?: { readonly attachments: ReadonlyArray; readonly dispatched: Array }, +) => { const record = ( fields: ReadonlyArray, filter: ProjectionStore.ProjectionRecordFilter | undefined, @@ -499,9 +502,20 @@ const historyReads = (reads: Array) => { getProjectThreadRecords: (_target, fields, filter) => Effect.sync(() => record(fields, filter)).pipe(Effect.as(projection as never)), getThreadRecords: (_id, fields, filter) => - Effect.sync(() => record(fields, filter)).pipe(Effect.as(projection as never)), - getMessagesById: () => Effect.succeed(new Map()), - dispatch: () => Effect.succeed({ sequence: 1 } as never), + Effect.sync(() => record(fields, filter)).pipe( + Effect.as({ + ...projection, + runs: + queued === undefined + ? projection.runs + : [{ id: "run:queued", status: "queued", userMessageId: "message:queued" }], + } as never), + ), + getMessagesById: () => + Effect.succeed(new Map(queued === undefined ? [] : [["message:queued", queued]]) as never), + hasReceipt: () => Effect.succeed(false), + dispatch: (command) => + Effect.sync(() => queued?.dispatched.push(command)).pipe(Effect.as({ sequence: 1 } as never)), }); }; @@ -532,6 +546,8 @@ it.effect("t3_queue list and read load only the queued runs and their messages", it.effect("handoff analytics read only the caller's active run and its message", () => { const reads: Array = []; + const attachments = [{ type: "image", id: "shot", name: "shot.png" }]; + const dispatched: Array = []; const recorded = Deferred.makeUnsafe(); return Effect.gen(function* () { const server = yield* McpServer.McpServer; @@ -546,12 +562,25 @@ it.effect("handoff analytics read only the caller's active run and its message", ); yield* Deferred.await(recorded); expect(reads).toEqual([]); + // The edit keeps the queued image, so `/logout` stays an ordinary prompt and is not refused. + const attached = yield* server + .callTool({ + name: "t3_queue", + arguments: { action: "edit", queuedRunId: "run:queued", text: " /LOGOUT " }, + }) + .pipe( + Effect.provideService(McpInvocationContext.McpInvocationContext, scope), + Effect.provideService(McpSchema.McpServerClient, client), + ); + expect(attached.isError).not.toBe(true); + expect(dispatched).toMatchObject([{ text: "Edited" }, { text: " /LOGOUT ", attachments }]); + expect(dispatched[0]).not.toHaveProperty("attachments"); }).pipe( Effect.provide( layerThreadToolkit.pipe( Layer.provideMerge(McpHttpServer.layerInProcessMcpServer), Layer.provide(NodeCrypto.layer), - Layer.provide(historyReads(reads)), + Layer.provide(historyReads(reads, { attachments, dispatched })), Layer.provide( Layer.succeed( AnalyticsService.AnalyticsService, diff --git a/apps/server/src/mcp/toolkits/thread/handlers.ts b/apps/server/src/mcp/toolkits/thread/handlers.ts index 972174638e10f..190cbe3eac2b1 100644 --- a/apps/server/src/mcp/toolkits/thread/handlers.ts +++ b/apps/server/src/mcp/toolkits/thread/handlers.ts @@ -21,6 +21,7 @@ import { unavailable, } from "../../threadAccess.ts"; import type * as ThreadManagement from "../../../orchestration-v2/ThreadManagementService.ts"; +import * as ThreadMessageIntake from "../../../orchestration-v2/ThreadMessageIntake.ts"; import * as ThreadSearch from "../../../orchestration-v2/ThreadSearch.ts"; import * as ScheduledTasks from "../../../scheduledTasks/ScheduledTaskService.ts"; import { queuedRunsInDeliveryOrder } from "../../../orchestration-v2/QueuedRunOrder.ts"; @@ -324,12 +325,26 @@ export const layer = McpToolAccess.toLayer(ThreadToolkit, { switch (input.action) { case "edit": { const text = yield* required(input.text, "text"); - return yield* dispatch(input.threadId, (common) => ({ - ...common, + const { threads, projection } = yield* readThread(input.threadId); + // An agent must not turn a person's queued message into a provider sign-out. + const command = yield* ThreadMessageIntake.withQueuedAttachmentsOnSignOutText({ type: "queued-run.edit", + commandId: yield* newCommandId(), + threadId: projection.thread.id, runId, text, - })); + }).pipe( + Effect.mapError((error) => + error._tag === "EnvironmentAuthorizationError" + ? new OrchestratorMcpFailure({ + code: "invalid_request", + message: "A queued message cannot be edited into a provider sign-out.", + }) + : dispatchFailure(error), + ), + ); + const result = yield* threads.dispatch(command).pipe(Effect.mapError(dispatchFailure)); + return { sequence: result.sequence }; } case "reorder": { const beforeRunId = yield* required(input.beforeRunId, "beforeRunId"); diff --git a/apps/server/src/orchestration-v2/CommandPolicy.ts b/apps/server/src/orchestration-v2/CommandPolicy.ts index 0191163e8bc75..451ca978b9e51 100644 --- a/apps/server/src/orchestration-v2/CommandPolicy.ts +++ b/apps/server/src/orchestration-v2/CommandPolicy.ts @@ -59,6 +59,17 @@ type MessageDispatchMode = Extract< { readonly type: "message.dispatch" } >["dispatchMode"]; +/** + * A message that signs a provider account out at turn start, as `providerAuthLogout` does. + * With attachments the same text is an ordinary prompt. + */ +export function isProviderSignOutPrompt(message: { + readonly text: string; + readonly attachments: ReadonlyArray; +}): boolean { + return message.attachments.length === 0 && message.text.trim().toLowerCase() === "/logout"; +} + export function isNativeMaintenanceCommand(message: { readonly text: string; readonly attachments: ReadonlyArray; diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts index f83fa70ca6bae..e4edafd70942b 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts @@ -467,6 +467,8 @@ function makeLocalCommandHarness(input: { readonly fileSystem?: FileSystem.FileSystem; readonly previousNativeSession?: boolean; readonly previousMessages?: ReadonlyArray; + readonly createdBy?: "agent" | "system"; + readonly scheduledTaskId?: ScheduledTaskId; readonly logoutFailure?: string; readonly openFailure?: unknown; readonly ensureThreadFailure?: unknown; @@ -565,8 +567,9 @@ function makeLocalCommandHarness(input: { text: input.text, attachments: [], streaming: false, - createdBy: "user", - creationSource: "web", + createdBy: input.createdBy ?? "user", + creationSource: input.createdBy === undefined ? "web" : "mcp", + ...(input.scheduledTaskId === undefined ? {} : { scheduledTaskId: input.scheduledTaskId }), createdAt: now, updatedAt: now, }; @@ -3301,6 +3304,7 @@ effectIt.effect.each(["not_loaded", "error"] as const)( instanceId: harness.oldInstanceId, text: "/logout", hasAttachments: false, + sentByPerson: true, }); expect(harness.open).not.toHaveBeenCalled(); expect(harness.startRootRun).not.toHaveBeenCalled(); @@ -3324,6 +3328,26 @@ effectIt.effect.each(["not_loaded", "error"] as const)( }), ); +effectIt.effect.each([ + { name: "an agent", createdBy: "agent" as const }, + // A scheduled delivery keeps its task author's createdBy. + { name: "a scheduled task", scheduledTaskId: ScheduledTaskId.make("task") }, +])("does not let $name sign a provider out", ({ name: _name, ...sender }) => + Effect.gen(function* () { + const harness = makeLocalCommandHarness({ + text: "/logout", + ...sender, + previousNativeSession: true, + }); + + yield* harness.start; + + expect(harness.tryHandlePromptCommand).toHaveBeenCalledExactlyOnceWith( + expect.objectContaining({ sentByPerson: false }), + ); + }), +); + for (const previousMessages of [[], ["/compact", " /COMPACT "]]) { effectIt.effect( `rejects compaction without conversation context after ${previousMessages.length} prior compactions`, diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts index 8c2c4eb3bea04..fded9011c9137 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts @@ -741,6 +741,10 @@ export const layer: Layer.Layer< records: providerMessage.context?.records ?? [], }), hasAttachments: false, + // A scheduled delivery keeps its task author's createdBy. + sentByPerson: + providerMessage.createdBy === "user" && + providerMessage.scheduledTaskId === undefined, }), ); if (isEmptyCompaction || authResult?._tag === "Failure" || authResult?.success) { diff --git a/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts b/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts index 9f40a5a176923..cabd1dce197a8 100644 --- a/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts +++ b/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts @@ -77,6 +77,9 @@ import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAda const projectId = ProjectId.make("project:launch-test"); const otherProjectId = ProjectId.make("project:launch-other"); const encodeThreadProjection = Schema.encodeEffect(OrchestrationV2ThreadProjectionJson); +const dispatchIntakeCommand = ( + command: Parameters[0], +) => ThreadMessageIntake.dispatchCommand(command, { managesProviders: true }); const modelSelection = { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.1-codex", @@ -2672,7 +2675,7 @@ it.effect("shared intake preserves durable attachment bytes after a lost launch }).pipe(Effect.flip); assert.equal(missingProject._tag, "ThreadLaunchError"); assert.equal((yield* claimedFiles).length, 1); - const missingThread = yield* ThreadMessageIntake.dispatchCommand({ + const missingThread = yield* dispatchIntakeCommand({ type: "message.dispatch", commandId: CommandId.make("intake-no-thread"), threadId: ThreadId.make("missing-thread"), @@ -2686,7 +2689,7 @@ it.effect("shared intake preserves durable attachment bytes after a lost launch assert.equal(missingThread._tag, "OrchestratorProjectionError"); assert.equal((yield* claimedFiles).length, 1); - const dispatch = ThreadMessageIntake.dispatchCommand({ + const dispatch = dispatchIntakeCommand({ type: "message.dispatch", commandId: CommandId.make("intake-dispatch"), threadId: input.threadId, @@ -2722,7 +2725,7 @@ it.effect("shared intake preserves durable attachment bytes after a lost launch }); assert.isNotNull(filePath); yield* fs.writeFile(filePath, new Uint8Array([5, 6, 7, 8])); - const edit = ThreadMessageIntake.dispatchCommand({ + const edit = dispatchIntakeCommand({ type: "queued-run.edit", commandId: CommandId.make("intake-edit"), threadId: input.threadId, @@ -2748,7 +2751,7 @@ it.effect("shared intake preserves durable attachment bytes after a lost launch assert.deepEqual(yield* fs.readFile(durableFilePath), new Uint8Array([5, 6, 7, 8])); assert.deepEqual(yield* fs.readFile(filePath), new Uint8Array([5, 6, 7, 8])); const beforeRejectedEdit = (yield* claimedFiles).length; - const rejectedEdit = yield* ThreadMessageIntake.dispatchCommand({ + const rejectedEdit = yield* dispatchIntakeCommand({ type: "queued-run.edit", commandId: CommandId.make("intake-edit-rejected"), threadId: input.threadId, diff --git a/apps/server/src/orchestration-v2/ThreadMessageIntake.test.ts b/apps/server/src/orchestration-v2/ThreadMessageIntake.test.ts index a92cdd22aa515..81fc56150d7fd 100644 --- a/apps/server/src/orchestration-v2/ThreadMessageIntake.test.ts +++ b/apps/server/src/orchestration-v2/ThreadMessageIntake.test.ts @@ -34,7 +34,10 @@ import { OrchestratorDispatchError, } from "./Orchestrator.ts"; import * as ThreadManagementService from "./ThreadManagementService.ts"; -import { dispatchCommand } from "./ThreadMessageIntake.ts"; +import * as ThreadMessageIntake from "./ThreadMessageIntake.ts"; + +const dispatchCommand = (command: OrchestrationV2Command, sender = { managesProviders: true }) => + ThreadMessageIntake.dispatchCommand(command, sender); const layerIntakeTest = ServerConfig.layerTest(process.cwd(), { prefix: "t3-question-intake-", @@ -475,3 +478,70 @@ it.effect("refuses a queued edit that keeps a file another edit already deleted" expect(captured).toHaveLength(2); }).pipe(Effect.provide(layerIntakeTest)), ); + +it.effect("a queued /logout edit without provider management must keep an attachment", () => + Effect.gen(function* () { + const threadId = ThreadId.make("thread-sign-out-edit"); + const image = { + type: "image" as const, + id: ChatAttachmentId.make(createAttachmentId(threadId)!), + name: "shot.png", + mimeType: "image/png", + sizeBytes: 3, + }; + const config = yield* ServerConfig.ServerConfig; + NodeFS.writeFileSync( + NodePath.join(config.attachmentsDir, `${image.id}.png`), + new Uint8Array([1, 2, 3]), + ); + const captured: OrchestrationV2ServerCommand[] = []; + // The edit omits `attachments`, as an older client's does, so the queued ones stay. + const edit = (run: string, managesProviders: boolean) => + dispatchCommand( + { + type: "queued-run.edit", + commandId: CommandId.make(`edit-${run}-${managesProviders}`), + threadId, + runId: RunId.make(run), + text: " /LOGOUT ", + }, + { managesProviders }, + ).pipe( + Effect.provide( + Layer.mock(ThreadManagementService.ThreadManagementService)({ + dispatch: layerFailingDispatchHandler(captured), + hasReceipt: (commandId) => Effect.succeed(commandId === "edit-replayed-false"), + getThreadRecords: () => + Effect.succeed({ + runs: ["attached", "bare"].map((id) => ({ + id: RunId.make(id), + status: "queued", + userMessageId: MessageId.make(id), + })), + } as never), + getMessagesById: (_threadId, [id]) => + Effect.succeed( + new Map([[id, { attachments: id === "attached" ? [image] : [] }]]) as never, + ), + }), + ), + Effect.flip, + ); + + expect((yield* edit("bare", false))._tag).toBe("EnvironmentAuthorizationError"); + expect((yield* edit("started", false))._tag).toBe("EnvironmentAuthorizationError"); + expect(captured).toEqual([]); + yield* edit("attached", false); + yield* edit("bare", true); + // A retry of an accepted edit reaches its receipt after its run left the queue. + yield* edit("replayed", false); + // The kept files are pinned, so an edit racing this one cannot strip them afterwards. + expect(captured).toMatchObject([ + { runId: "attached", attachments: [image] }, + { runId: "bare" }, + { runId: "replayed" }, + ]); + expect(captured[1]).not.toHaveProperty("attachments"); + expect(captured[2]).not.toHaveProperty("attachments"); + }).pipe(Effect.provide(layerIntakeTest)), +); diff --git a/apps/server/src/orchestration-v2/ThreadMessageIntake.ts b/apps/server/src/orchestration-v2/ThreadMessageIntake.ts index 6e9fd503baec5..5d9ec263b0b0d 100644 --- a/apps/server/src/orchestration-v2/ThreadMessageIntake.ts +++ b/apps/server/src/orchestration-v2/ThreadMessageIntake.ts @@ -1,14 +1,20 @@ import { remapComposerContextAttachments } from "@t3tools/shared/composerContextReferences"; import { appendUserInputAttachmentPaths } from "../provider/userInputAttachments.ts"; -import type { ChatAttachment, OrchestrationV2Command } from "@t3tools/contracts"; +import { + AuthProvidersManageScope, + type ChatAttachment, + type OrchestrationV2Command, +} from "@t3tools/contracts"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Schema from "effect/Schema"; import { resolveAttachmentPath } from "../attachmentStore.ts"; +import { rpcAuthorizationError } from "../auth/RpcAuthorization.ts"; import * as ServerConfig from "../config.ts"; import * as Orchestrator from "./Orchestrator.ts"; import * as AttachmentClaims from "./AttachmentClaims.ts"; +import { isProviderSignOutPrompt } from "./CommandPolicy.ts"; import * as ThreadLaunch from "./ThreadLaunchService.ts"; import * as ThreadManagement from "./ThreadManagementService.ts"; @@ -85,11 +91,52 @@ const withGuestAttachments = Effect.fn("ThreadMessageIntake.withGuestAttachments return { ...command, attachments: message?.attachments ?? [] }; }); +/** + * For a caller without `providers:manage`. An edit that omits `attachments` keeps the queued + * ones, so `/logout` signs out only when the queued message has none. The edit goes on with + * the files read here, so an edit racing this one cannot strip them afterwards. + */ +export const withQueuedAttachmentsOnSignOutText = Effect.fn( + "ThreadMessageIntake.withQueuedAttachmentsOnSignOutText", +)(function* (command: Extract) { + if ( + command.attachments !== undefined || + !isProviderSignOutPrompt({ text: command.text, attachments: [] }) + ) { + return command; + } + const threads = yield* ThreadManagement.ThreadManagementService; + // A retry of an accepted edit replays its receipt, even after its run left the queue. + if (yield* threads.hasReceipt(command.commandId)) return command; + const { runs } = yield* threads.getThreadRecords(command.threadId, ["runs"], { + runIds: [command.runId], + }); + const queuedRun = runs.find((run) => run.id === command.runId && run.status === "queued"); + const attachments = + queuedRun === undefined + ? [] + : ((yield* threads.getMessagesById(command.threadId, [queuedRun.userMessageId])).get( + queuedRun.userMessageId, + )?.attachments ?? []); + if (attachments.length === 0) return yield* rpcAuthorizationError(AuthProvidersManageScope); + return { ...command, attachments }; +}); + +/** + * `sender.managesProviders` is whether the caller holds `providers:manage`. RPC authorization + * has already checked every command whose payload shows a provider sign-out; a queued edit + * that keeps its attachments is the one case decided here. + */ export const dispatchCommand = Effect.fn("ThreadMessageIntake.dispatchCommand")(function* ( incoming: OrchestrationV2Command, + sender: { readonly managesProviders: boolean }, ) { const command = - incoming.type === "message.dispatch" ? yield* withGuestAttachments(incoming) : incoming; + incoming.type === "message.dispatch" + ? yield* withGuestAttachments(incoming) + : incoming.type === "queued-run.edit" && !sender.managesProviders + ? yield* withQueuedAttachmentsOnSignOutText(incoming) + : incoming; const threads = yield* ThreadManagement.ThreadManagementService; if (command.type === "runtime-request.respond" && command.attachmentsByQuestionId) { const config = yield* ServerConfig.ServerConfig; diff --git a/apps/server/src/provider/ProviderAuthService.test.ts b/apps/server/src/provider/ProviderAuthService.test.ts index 603df5e7e4bcd..0186f79fac768 100644 --- a/apps/server/src/provider/ProviderAuthService.test.ts +++ b/apps/server/src/provider/ProviderAuthService.test.ts @@ -679,6 +679,32 @@ describe("ProviderAuthService", () => { }), ); + it.effect("refuses a chat sign-out that no person sent", () => + Effect.gen(function* () { + const { service, actions } = yield* makeHarness({}); + const error = yield* Effect.flip( + service.tryHandlePromptCommand({ + instanceId, + text: "/logout", + hasAttachments: false, + sentByPerson: false, + }), + ); + + assert.strictEqual(error.operation, "logout"); + assert.deepStrictEqual(actions, []); + // Any other prompt still goes to the provider. + assert.isFalse( + yield* service.tryHandlePromptCommand({ + instanceId, + text: "hello", + hasAttachments: false, + sentByPerson: false, + }), + ); + }), + ); + it.effect("does not log out or consume the command when stopping a session fails", () => Effect.gen(function* () { const { service, actions, released } = yield* makeHarness({ @@ -687,7 +713,12 @@ describe("ProviderAuthService", () => { stopError: true, }); const error = yield* Effect.flip( - service.tryHandlePromptCommand({ instanceId, text: "/logout", hasAttachments: false }), + service.tryHandlePromptCommand({ + instanceId, + text: "/logout", + hasAttachments: false, + sentByPerson: true, + }), ); assert.instanceOf(error, ProviderSetupError); @@ -722,7 +753,12 @@ it.effect("queued logout prompts resolve the current controller after provider r yield* Deferred.await(entered); observeLookup = true; const queued = yield* harness.service - .tryHandlePromptCommand({ instanceId, text: "/logout", hasAttachments: false }) + .tryHandlePromptCommand({ + instanceId, + text: "/logout", + hasAttachments: false, + sentByPerson: true, + }) .pipe(Effect.forkChild); yield* Deferred.await(lookup); let replacementLoggedOut = false; @@ -787,6 +823,7 @@ it.effect.each(["start", "logout", "prompt"] as const)( instanceId, text: "/logout", hasAttachments: false, + sentByPerson: true, }); const running = yield* operation.pipe(Effect.forkChild); yield* Deferred.await(checked); diff --git a/apps/server/src/provider/ProviderAuthService.ts b/apps/server/src/provider/ProviderAuthService.ts index b09a60ffc1be0..625a4ae77c683 100644 --- a/apps/server/src/provider/ProviderAuthService.ts +++ b/apps/server/src/provider/ProviderAuthService.ts @@ -62,7 +62,12 @@ export class ProviderAuthService extends Context.Service< ownerSessionId: string, ) => Stream.Stream; readonly tryHandlePromptCommand: ( - input: ProviderAuthTarget & { readonly text: string; readonly hasAttachments: boolean }, + input: ProviderAuthTarget & { + readonly text: string; + readonly hasAttachments: boolean; + /** False for agent, system and scheduled messages: no RPC scope check covered them. */ + readonly sentByPerson: boolean; + }, ) => Effect.Effect; } >()("t3/provider/ProviderAuthService") {} @@ -306,6 +311,13 @@ export const makeProviderAuthService = Effect.gen(function* () { if (!instance?.auth?.isLogoutPrompt?.(input.text, input.hasAttachments)) { return false; } + if (!input.sentByPerson) { + return yield* new ProviderSetupError({ + instanceId: input.instanceId, + operation: "logout", + detail: "Only a person can sign out of a provider from chat. Sign out in Settings.", + }); + } return yield* credentialChanges.withPermit( Effect.gen(function* () { const auth = yield* getController(input.instanceId, "logout"); diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index 63d45c48816e4..9408127f5a2b3 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -31,6 +31,7 @@ import { AuthAccessStreamError, type AuthAccessStreamEvent, AuthOrchestrationOperateScope, + AuthProvidersManageScope, type AuthEnvironmentScope, type ScheduledTaskListResult, AuthSessionId, @@ -2018,6 +2019,10 @@ export const layerWsRpc = ( creationSource: "creationSource" in command ? command.creationSource : "web", }), + { + managesProviders: + currentSession.scopes.includes(AuthProvidersManageScope), + }, ) ).pipe(Effect.provide(intakeContext)), ) @@ -2027,6 +2032,7 @@ export const layerWsRpc = ( ), Effect.map((result) => ({ sequence: result.sequence })), Effect.mapError((cause) => { + if (cause._tag === "EnvironmentAuthorizationError") return cause; const detail = userFacingDispatchErrorMessage(cause); return new OrchestrationV2DispatchCommandError({ commandId: command.commandId, diff --git a/docs/user/providers-antigravity.md b/docs/user/providers-antigravity.md index 8935439c0a63d..db2a06661c8e7 100644 --- a/docs/user/providers-antigravity.md +++ b/docs/user/providers-antigravity.md @@ -142,6 +142,8 @@ runtimes are shared on the environment. All three keep thread history and workspace files. Sending `/logout` by itself in a thread signs out its instance, including stopping that instance's other sessions. +That needs a client allowed to manage providers, and it has to be your own message: +`/logout` from an agent or a scheduled task is refused. Sign out, then sign in again to replace an account. Before removing a managed runtime, disable its instances and cancel any active From f8d7f4891385cdf178271a1fd0dc8c5842b483a6 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 19 Nov 2026 12:43:13 -0800 Subject: [PATCH 68/97] fix(ssh): desktop SSH reaches hosts with a one-time code through a signed-in ControlMaster (#30616) --- docs/user/remote-access.md | 12 ++++ packages/ssh/src/command.ts | 36 +++++++++++- packages/ssh/src/tunnel.test.ts | 77 ++++++++++++++++++++++++++ packages/ssh/src/tunnel.ts | 97 +++++++++++++++++++++++++++------ 4 files changed, 203 insertions(+), 19 deletions(-) diff --git a/docs/user/remote-access.md b/docs/user/remote-access.md index 7a6731d9ebe10..8a8e87fe0ba57 100644 --- a/docs/user/remote-access.md +++ b/docs/user/remote-access.md @@ -259,6 +259,18 @@ check with: ssh user@example.com 'sh -lc "command -v claude codex"' ``` +T3 Code cannot answer a second sign-in prompt such as a Duo code. On macOS and +Linux it can reuse a connection you signed in to in a terminal instead: turn on +connection sharing for the host in `~/.ssh/config`, run `ssh `, then +connect. When that connection closes, sign in again in a terminal and retry. + +```sshconfig +Host + ControlMaster auto + ControlPath ~/.ssh/cm-%C + ControlPersist 8h +``` + If SSH reconnecting fails after an app update, retry the launch once. Removing the connection stops a server that T3 Code launched; a server that was already running is left alone. diff --git a/packages/ssh/src/command.ts b/packages/ssh/src/command.ts index 8a225ab05a15d..4d1534bf96b43 100644 --- a/packages/ssh/src/command.ts +++ b/packages/ssh/src/command.ts @@ -43,7 +43,7 @@ export interface RunSshCommandOptions extends SshAuthOptions { readonly keepErrorOutputTail?: boolean; } -export function parseSshResolveOutput(alias: string, stdout: string): DesktopSshEnvironmentTarget { +function parseSshConfigOutput(stdout: string): Map { const values = new Map(); for (const line of stdout.split(/\r?\n/u)) { const trimmed = line.trim(); @@ -56,6 +56,11 @@ export function parseSshResolveOutput(alias: string, stdout: string): DesktopSsh } values.set(key, rest.join(" ").trim()); } + return values; +} + +export function parseSshResolveOutput(alias: string, stdout: string): DesktopSshEnvironmentTarget { + const values = parseSshConfigOutput(stdout); const hostname = values.get("hostname")?.trim() || alias; const username = values.get("user")?.trim() || null; @@ -123,6 +128,12 @@ export function baseSshArgs( ]; } +// `-F none` keeps the user's configured forwards out of T3's requests, and ProxyCommand=false +// fails closed instead of dialing the host directly once the master is gone. +export function controlMasterArgs(controlPath: string): string[] { + return ["-F", "none", "-o", `ControlPath=${controlPath}`, "-o", "ProxyCommand=false"]; +} + export function getLastNonEmptyOutputLine(stdout: string): string | null { return ( stdout @@ -442,3 +453,26 @@ export const resolveSshTarget = Effect.fn("ssh/command.resolveSshTarget")(functi ), ); }); + +/** The control path of the user's signed-in ControlMaster for `target`, or null when none is live. */ +export const findLiveControlPath = Effect.fn("ssh/command.findLiveControlPath")(function* ( + target: DesktopSshEnvironmentTarget, +): Effect.fn.Return< + string | null, + never, + ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path +> { + const resolved = yield* runSshCommand(target, { preHostArgs: ["-G"] }).pipe(Effect.option); + const controlPath = Option.isSome(resolved) + ? parseSshConfigOutput(resolved.value.stdout).get("controlpath") + : undefined; + if (controlPath === undefined || controlPath === "none") { + return null; + } + return yield* runSshCommand(target, { + preHostArgs: [...controlMasterArgs(controlPath), "-O", "check"], + }).pipe( + Effect.as(controlPath), + Effect.orElseSucceed(() => null), + ); +}); diff --git a/packages/ssh/src/tunnel.test.ts b/packages/ssh/src/tunnel.test.ts index ca7b4ce85ac51..6c8ffd5a6151c 100644 --- a/packages/ssh/src/tunnel.test.ts +++ b/packages/ssh/src/tunnel.test.ts @@ -1187,6 +1187,83 @@ describe("ssh tunnel scripts", () => { }), ); + it.effect.each([ + { name: "rides a live ControlMaster", masterLive: true }, + { name: "keeps the auth failure without a live ControlMaster", masterLive: false }, + ])("when the tunnel cannot sign in again, $name", ({ masterLive }) => + Effect.gen(function* () { + const denied = "julius@devbox: Permission denied (publickey,keyboard-interactive).\n"; + const openedForwards: Array = []; + const cancelledForwards: Array = []; + const spawner = ChildProcessSpawner.make((command) => + Effect.sync(() => { + const args = commandArgs(command); + const forward = args.includes("-L") ? args[args.indexOf("-L") + 1] : undefined; + const muxCommand = args.includes("-O") ? args[args.indexOf("-O") + 1] : undefined; + const failed = (stderr: string) => ({ + ...makeSuccessfulProcess(""), + exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(255)), + stderr: Stream.make(new TextEncoder().encode(stderr)), + }); + if (args.includes("-G")) { + return makeSuccessfulProcess("hostname devbox\ncontrolpath /tmp/t3-cm\n"); + } + if (muxCommand === "check") { + return masterLive + ? makeSuccessfulProcess("") + : failed("Control socket connect: ENOENT\n"); + } + if (muxCommand === "cancel") { + cancelledForwards.push(forward); + return makeSuccessfulProcess(""); + } + if (forward !== undefined) { + // Only the signed-in master can pass the host's one-time-code prompt. + if (!masterLive || args.includes("ControlPath=none")) return failed(denied); + openedForwards.push(forward); + return muxCommand === "forward" + ? makeSuccessfulProcess("") + : makeRunningProcess(() => undefined); + } + return makeSuccessfulProcess('{"remotePort":3773}\n'); + }), + ); + const layer = Layer.mergeAll( + NodeServices.layer, + NodeCrypto.layer, + Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner), + Layer.succeed( + HttpClient.HttpClient, + HttpClient.make((request) => + openedForwards.length > 0 ? testHttpClient.execute(request) : Effect.never, + ), + ), + Layer.succeed(NetService.NetService, testNetService), + SshAuth.SshPasswordPrompt.disabledLayer, + SshTunnel.SshEnvironmentManager.layer({ resolveCliRunner: Effect.succeed(ARCHIVE) }), + ); + const target = { alias: "devbox", hostname: "devbox", username: null, port: null }; + yield* Effect.gen(function* () { + const manager = yield* SshTunnel.SshEnvironmentManager; + const result = yield* Effect.result(manager.ensureEnvironment(target)); + if (!masterLive) { + assert.isTrue(Result.isFailure(result)); + if (Result.isFailure(result)) { + assert.instanceOf(result.failure, SshCommandError); + assert.include(result.failure.message, "Permission denied"); + } + assert.deepEqual(openedForwards, []); + return; + } + assert.equal(Result.isFailure(result) ? result.failure.message : "connected", "connected"); + assert.lengthOf(openedForwards, 1); + yield* manager.disconnectEnvironment(target); + // The master keeps a forward after the client that asked for it exits. + assert.deepEqual(cancelledForwards, openedForwards); + }).pipe(Effect.provide(layer), Effect.scoped); + }), + ); + it.live("concurrent launches on one remote home record the server that owns it", () => // The second row's server never publishes server-runtime.json. Effect.forEach([1_500, null, "wrapper"] as const, (variant) => diff --git a/packages/ssh/src/tunnel.ts b/packages/ssh/src/tunnel.ts index 522fb23625286..a4b865385f81e 100644 --- a/packages/ssh/src/tunnel.ts +++ b/packages/ssh/src/tunnel.ts @@ -32,6 +32,8 @@ import * as SshAuth from "./auth.ts"; import { baseSshArgs, buildSshHostSpecEffect, + controlMasterArgs, + findLiveControlPath, getLastNonEmptyOutputLine, remoteStateKey, resolveSshCommand, @@ -1471,6 +1473,8 @@ const startSshTunnel = Effect.fn("ssh/tunnel.startSshTunnel")(function* (input: readonly httpBaseUrl: string; readonly wsBaseUrl: string; readonly authOptions: SshAuth.SshAuthOptions; + /** Forward through this live ControlMaster instead of signing in again. */ + readonly controlPath: string | null; readonly remoteServerKind: "external" | "managed" | null; readonly scope: Scope.Closeable; }): Effect.fn.Return< @@ -1503,7 +1507,7 @@ const startSshTunnel = Effect.fn("ssh/tunnel.startSshTunnel")(function* (input: }), ), ); - const args = [ + const directArgs = [ ...baseSshArgs(input.resolvedTarget, { batchMode: input.authOptions.batchMode ?? "no", }), @@ -1526,10 +1530,56 @@ const startSshTunnel = Effect.fn("ssh/tunnel.startSshTunnel")(function* (input: "--", hostSpec, ]; + const { controlPath, scope } = input; + // The master's own GatewayPorts would otherwise decide the bind address. + const controlMasterForward = `127.0.0.1:${input.localPort}:127.0.0.1:${input.remotePort}`; + const { args, stdin } = + controlPath === null + ? { args: directArgs, stdin: { stream: Stream.empty, endOnDone: true } } + : { + // A mux client with -N exits once the master takes the forward, so hold a session + // open on stdin to keep a process whose exit means the tunnel is gone. + args: [ + ...baseSshArgs(input.resolvedTarget, { batchMode: "yes" }), + ...controlMasterArgs(controlPath), + "-o", + "ExitOnForwardFailure=yes", + "-o", + "ControlMaster=no", + "-T", + "-L", + controlMasterForward, + "--", + hostSpec, + "sh -c 'exec cat >/dev/null'", + ], + stdin: "pipe" as const, + }; const sshCommand = yield* resolveSshCommand; const tunnelCommand = [sshCommand, ...args]; const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const { scope } = input; + if (controlPath !== null) { + const fileSystemService = yield* FileSystem.FileSystem; + const pathService = yield* Path.Path; + // The master keeps a forward after the mux client that asked for it exits. + yield* Scope.addFinalizer( + scope, + runSshCommand(input.resolvedTarget, { + preHostArgs: [ + ...controlMasterArgs(controlPath), + "-O", + "cancel", + "-L", + controlMasterForward, + ], + }).pipe( + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), + Effect.provideService(FileSystem.FileSystem, fileSystemService), + Effect.provideService(Path.Path, pathService), + Effect.ignore, + ), + ); + } yield* Effect.logDebug("ssh.tunnel.spawn.start", { ...sshTargetLogFields(input.resolvedTarget), command: tunnelCommand, @@ -1543,10 +1593,7 @@ const startSshTunnel = Effect.fn("ssh/tunnel.startSshTunnel")(function* (input: ChildProcess.make(sshCommand, args, { env: childEnvironment, extendEnv: true, - stdin: { - stream: Stream.empty, - endOnDone: true, - }, + stdin, }), ) .pipe( @@ -1908,18 +1955,32 @@ const makeSshEnvironmentManager = Effect.fn("ssh/tunnel.SshEnvironmentManager.ma const tunnelEntry = yield* runWithSshAuth({ key: input.key, target: input.resolvedTarget, - operation: (authOptions) => - startSshTunnel({ - key: input.key, - resolvedTarget: input.resolvedTarget, - remotePort, - localPort, - httpBaseUrl, - wsBaseUrl, - authOptions, - remoteServerKind: remoteLaunch.remoteServerKind, - scope: entryScope, - }), + operation: (authOptions) => { + const start = (controlPath: string | null) => + startSshTunnel({ + key: input.key, + resolvedTarget: input.resolvedTarget, + remotePort, + localPort, + httpBaseUrl, + wsBaseUrl, + authOptions, + controlPath, + remoteServerKind: remoteLaunch.remoteServerKind, + scope: entryScope, + }); + // A fresh login cannot answer a second factor such as Duo, but the user's signed-in + // ControlMaster already has. Without one, the auth failure goes on to the password prompt. + return start(null).pipe( + Effect.catchIf(SshAuth.isSshAuthFailure, (error) => + findLiveControlPath(input.resolvedTarget).pipe( + Effect.flatMap((controlPath) => + controlPath === null ? Effect.fail(error) : start(controlPath), + ), + ), + ), + ); + }, }).pipe( Effect.onExit((exit) => Exit.isSuccess(exit) ? Effect.void : Scope.close(entryScope, Exit.void).pipe(Effect.ignore), From 34a7ab3641d39dd4eb5e863f2d6f38bc09b9bcbf Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 19 Nov 2026 12:43:35 -0800 Subject: [PATCH 69/97] fix(pi): T3 tools are callable by Pi's own mcp__t3_code__ names (#26845) --- .../orchestrator-mcp-server.md | 9 +- .../src/server/mcpBridge.testkit.ts | 57 ++++++++ .../src/server/mcpExtensionSource.test.ts | 122 ++++++++++++++++-- .../src/server/mcpExtensionSource.ts | 50 +++++-- 4 files changed, 212 insertions(+), 26 deletions(-) diff --git a/docs/orchestration-v2/orchestrator-mcp-server.md b/docs/orchestration-v2/orchestrator-mcp-server.md index 6c1150fbfc023..5f48ed4a2c14f 100644 --- a/docs/orchestration-v2/orchestrator-mcp-server.md +++ b/docs/orchestration-v2/orchestrator-mcp-server.md @@ -167,9 +167,12 @@ T3_MCP_BEARER_TOKEN= ``` The extension preserves public names under `mcp__t3-code__` for saved loadouts -and tool selectors. Modern Pi also receives hidden `mcp__t3_code__` aliases, -which reserve the normalized namespace against configured MCP servers without -adding declarations or search results. On Pi 0.99+, +and tool selectors. Modern Pi also receives `mcp__t3_code__` aliases, Pi's own +name for the server, which reserve it against configured MCP servers. They are +`model-only` and hide their own declarations, so the model can call them without +added declarations, search results, or codemode entries. An alias follows its +public tool: dropped when that tool is excluded, and off while a direct one is +off. Pi's `hidden` exposure would make them unreachable. On Pi 0.99+, `orchestrator_capabilities`, `delegate_task`, and `task_status` remain directly available; optional tools are discovered through Pi's builtin `tool_search`. On older Pi or without builtin search, all tools remain directly available. diff --git a/packages/provider-pi/src/server/mcpBridge.testkit.ts b/packages/provider-pi/src/server/mcpBridge.testkit.ts index 98ef74bb862cc..759c8346ba037 100644 --- a/packages/provider-pi/src/server/mcpBridge.testkit.ts +++ b/packages/provider-pi/src/server/mcpBridge.testkit.ts @@ -13,6 +13,12 @@ interface RegisteredTool { readonly exposure?: string; readonly promptSnippet?: string; readonly promptGuidelines?: ReadonlyArray; + readonly prepareLoadout?: (loadout: { + readonly declared: ReadonlyArray; + readonly callable: ReadonlyArray; + readonly registered: ReadonlyArray; + readonly getExposure: (name: string) => string; + }) => { readonly hiddenDeclarations?: ReadonlyArray } | undefined; readonly execute: ( id: string, args: Record, @@ -40,12 +46,20 @@ type AgentStartHook = ( }, ) => Promise<{ systemPrompt: string } | undefined>; +function activatesOnRegistration(tool: RegisteredTool) { + return ( + tool.exposure === undefined || tool.exposure === "direct" || tool.exposure === "model-only" + ); +} + export async function loadMcpBridge( options: { readonly modern?: boolean; readonly result?: unknown; readonly toolSearchAvailable?: boolean; readonly toolSearchDisabled?: boolean; + // Pi activates direct and model-only tools when they are registered. + readonly activatesOnRegistration?: boolean; readonly allowsTool?: (name: string) => boolean; readonly runtimeMode?: string; readonly inputSchema?: Record; @@ -131,8 +145,17 @@ export async function loadMcpBridge( registerTool: (tool: RegisteredTool) => { if (options.allowsTool && !options.allowsTool(tool.name)) return; const index = tools.findIndex((current) => current.name === tool.name); + const previous = index === -1 ? undefined : tools[index]; if (index === -1) tools.push(tool); else tools[index] = tool; + if ( + options.activatesOnRegistration && + activatesOnRegistration(tool) && + (previous === undefined || !activatesOnRegistration(previous)) && + !activeTools.includes(tool.name) + ) { + activeTools = [...activeTools, tool.name]; + } }, getActiveTools: () => activeTools, setActiveTools: (names: string[]) => { @@ -155,9 +178,43 @@ export async function loadMcpBridge( : {}), }, }); + const exposureOf = (name: string) => + tools.find((tool) => tool.name === name)?.exposure ?? "direct"; + // Pi resolves model tool calls against the active, non-hidden tools only. + const modelTools = () => + tools.filter((tool) => activeTools.includes(tool.name) && exposureOf(tool.name) !== "hidden"); + // Pi's ctx.executeTool() catalog, which codemode scripts search and list. + const callableTools = () => + tools.filter( + (tool) => + ["codemode", "deferred"].includes(exposureOf(tool.name)) || + (exposureOf(tool.name) === "direct" && activeTools.includes(tool.name)), + ); + const declaredTools = () => { + const active = modelTools(); + const loadout = { + declared: active, + callable: callableTools(), + registered: tools, + getExposure: exposureOf, + }; + const hidden = new Set( + active.flatMap((tool) => tool.prepareLoadout?.(loadout)?.hiddenDeclarations ?? []), + ); + return active.map((tool) => tool.name).filter((name) => !hidden.has(name)); + }; return { handlers, tools, + declaredTools, + callableTools: () => callableTools().map((tool) => tool.name), + callModelTool: async (name: string, args: Record) => { + const tool = modelTools().find((candidate) => candidate.name === name); + if (tool === undefined) { + return { content: [{ type: "text", text: `Tool ${name} not found` }], isError: true }; + } + return tool.execute("model-call", args); + }, setBridgeSourcePath: (path: string) => { bridgeSourcePath = path; }, diff --git a/packages/provider-pi/src/server/mcpExtensionSource.test.ts b/packages/provider-pi/src/server/mcpExtensionSource.test.ts index 63556422bf41a..7506f155ab229 100644 --- a/packages/provider-pi/src/server/mcpExtensionSource.test.ts +++ b/packages/provider-pi/src/server/mcpExtensionSource.test.ts @@ -183,7 +183,11 @@ describe("Pi MCP tool exposure", () => { }; it("keeps orchestration direct and optional bridge tools discoverable on modern Pi", async () => { - const bridge = await loadMcpBridge({ modern: true, toolSearchAvailable: true }); + const bridge = await loadMcpBridge({ + modern: true, + toolSearchAvailable: true, + activatesOnRegistration: true, + }); await bridge.handlers.get("session_start")!({ systemPrompt: "" }, discoveryContext); const start = bridge.handlers.get("before_agent_start"); assert.isDefined(start); @@ -191,10 +195,27 @@ describe("Pi MCP tool exposure", () => { assert.include(prompt?.systemPrompt ?? "", "orchestrator_capabilities"); assert.equal(bridge.servers.length, 0); assert.equal(bridge.tools.length, 8); - assert.deepEqual(bridge.getActiveTools(), ["read", "tool_search"]); + const aliases = [ + "mcp__t3_code__orchestrator_capabilities", + "mcp__t3_code__delegate_task", + "mcp__t3_code__task_status", + "mcp__t3_code__preview_snapshot", + ]; + const publicDirect = [ + "mcp__t3-code__orchestrator_capabilities", + "mcp__t3-code__delegate_task", + "mcp__t3-code__task_status", + ]; + assert.sameMembers(bridge.getActiveTools(), [ + "read", + "tool_search", + ...publicDirect, + ...aliases, + ]); + assert.deepEqual(bridge.declaredTools(), publicDirect); assert.deepEqual( bridge.tools - .filter((tool) => tool.exposure !== "hidden") + .filter((tool) => tool.name.startsWith("mcp__t3-code__")) .map((tool) => [tool.name, tool.exposure]), [ ["mcp__t3-code__orchestrator_capabilities", "direct"], @@ -204,13 +225,10 @@ describe("Pi MCP tool exposure", () => { ], ); assert.deepEqual( - bridge.tools.filter((tool) => tool.exposure === "hidden").map((tool) => tool.name), - [ - "mcp__t3_code__orchestrator_capabilities", - "mcp__t3_code__delegate_task", - "mcp__t3_code__task_status", - "mcp__t3_code__preview_snapshot", - ], + bridge.tools + .filter((tool) => tool.name.startsWith("mcp__t3_code__")) + .map((tool) => [tool.name, tool.exposure]), + aliases.map((name) => [name, "model-only"]), ); const result = await bridge.tools .find((tool) => tool.name === "mcp__t3-code__preview_snapshot")! @@ -224,9 +242,11 @@ describe("Pi MCP tool exposure", () => { modern: true, toolSearchAvailable: true, allowsTool: (name) => name !== "mcp__t3-code__delegate_task", + activatesOnRegistration: true, }); const event = { systemPrompt: "" }; await bridge.handlers.get("session_start")!(event, discoveryContext); + assert.notInclude(bridge.getActiveTools(), "mcp__t3_code__delegate_task"); const gatewayContext = { model: { api: "openai-completions" }, ui: { notify: assert.fail } }; await bridge.handlers.get("model_select")!(event, gatewayContext); bridge.restoreActiveTools(["read", "mcp__t3-code__task_status"]); @@ -237,6 +257,9 @@ describe("Pi MCP tool exposure", () => { "tool_search", "mcp__t3-code__orchestrator_capabilities", "mcp__t3-code__preview_snapshot", + "mcp__t3_code__orchestrator_capabilities", + "mcp__t3_code__task_status", + "mcp__t3_code__preview_snapshot", ]); await bridge.handlers.get("model_select")!(event, discoveryContext); assert.equal( @@ -246,6 +269,74 @@ describe("Pi MCP tool exposure", () => { assert.include(bridge.getActiveTools(), "mcp__t3-code__preview_snapshot"); }); + it("keeps Pi's canonical MCP tool names callable by the model without declaring them twice", async () => { + const bridge = await loadMcpBridge({ + modern: true, + toolSearchAvailable: true, + activatesOnRegistration: true, + }); + const canonicalNames = [ + "mcp__t3_code__orchestrator_capabilities", + "mcp__t3_code__delegate_task", + "mcp__t3_code__task_status", + "mcp__t3_code__preview_snapshot", + ]; + const unreachableCanonicalNames = async () => { + const unreachable: string[] = []; + for (const name of canonicalNames) { + const result = await bridge.callModelTool(name, {}); + if (result.isError === true) unreachable.push(name); + } + return unreachable; + }; + const declaredCanonicalNames = () => + bridge.declaredTools().filter((name) => name.startsWith("mcp__t3_code__")); + const event = { systemPrompt: "" }; + + await bridge.handlers.get("session_start")!(event, discoveryContext); + assert.deepEqual( + await unreachableCanonicalNames(), + [], + "model calls to these names fail with Tool not found after session start", + ); + assert.deepEqual(declaredCanonicalNames(), [], "declared twice after session start"); + assert.equal(bridge.requests.at(-1)?.method, "tools/call"); + + bridge.restoreActiveTools([ + "read", + "mcp__t3-code__orchestrator_capabilities", + "mcp__t3-code__delegate_task", + "mcp__t3-code__task_status", + ]); + await bridge.handlers.get("session_tree")!(event, discoveryContext); + assert.deepEqual( + await unreachableCanonicalNames(), + [], + "model calls to these names fail with Tool not found after an older tree loadout", + ); + assert.deepEqual(declaredCanonicalNames(), [], "declared twice after an older tree loadout"); + assert.isFalse( + bridge.callableTools().some((name) => name.startsWith("mcp__t3_code__")), + "aliases duplicate the codemode catalog", + ); + + const requestCount = bridge.requests.length; + bridge.restoreActiveTools( + bridge.getActiveTools().filter((name) => name !== "mcp__t3-code__delegate_task"), + ); + const late = await bridge.callModelTool("mcp__t3_code__delegate_task", {}); + assert.isTrue(late.isError, "an alias runs after its public tool was switched off"); + assert.equal(bridge.requests.length, requestCount); + + bridge.restoreActiveTools(["read", "mcp__t3-code__task_status"]); + await bridge.handlers.get("session_tree")!(event, discoveryContext); + assert.deepEqual( + await unreachableCanonicalNames(), + ["mcp__t3_code__orchestrator_capabilities", "mcp__t3_code__delegate_task"], + "an alias stays callable while its direct public tool is off", + ); + }); + it.each(["legacy Pi", "disabled tool search"])( "keeps tool execution available with %s", async (mode) => { @@ -258,11 +349,16 @@ describe("Pi MCP tool exposure", () => { const start = bridge.handlers.get("session_start"); await start!({ systemPrompt: "Pi system prompt" }, discoveryContext); } - assert.equal(bridge.tools.filter((tool) => tool.exposure !== "hidden").length, 4); + const publicTools = bridge.tools.filter((tool) => tool.name.startsWith("mcp__t3-code__")); + assert.equal(publicTools.length, 4); assert.isTrue( + publicTools.every((tool) => tool.exposure === undefined || tool.exposure === "direct"), + ); + assert.deepEqual( bridge.tools - .filter((tool) => tool.exposure !== "hidden") - .every((tool) => tool.exposure === undefined || tool.exposure === "direct"), + .filter((tool) => tool.name.startsWith("mcp__t3_code__")) + .map((tool) => tool.exposure), + mode === "legacy Pi" ? [] : ["model-only", "model-only", "model-only", "model-only"], ); const tool = bridge.tools.find((tool) => tool.name === "mcp__t3-code__preview_snapshot"); assert.isDefined(tool); diff --git a/packages/provider-pi/src/server/mcpExtensionSource.ts b/packages/provider-pi/src/server/mcpExtensionSource.ts index 2e7844a23ac94..e934ce60e6ba6 100644 --- a/packages/provider-pi/src/server/mcpExtensionSource.ts +++ b/packages/provider-pi/src/server/mcpExtensionSource.ts @@ -397,31 +397,52 @@ export default async function t3McpExtension(pi: ExtensionAPI) { // bridge as the credential owner: mcp.json overrides native registrations. const supportsExposure = "registerMcpServer" in pi && typeof pi.registerMcpServer === "function"; const directTools = new Set(["orchestrator_capabilities", "delegate_task", "task_status"]); + const ALIAS_PREFIX = "mcp__t3_code__"; let deferOptionalTools = supportsExposure; + const isDeferred = (name: string) => deferOptionalTools && !directTools.has(name); + // An alias follows its public tool: gone when --exclude-tools removed it, + // off while a direct one is off. + const followsPublicTool = ( + name: string, + registered: ReadonlySet, + active: ReadonlyArray, + ) => + registered.has("mcp__t3-code__" + name) && + (isDeferred(name) || active.includes("mcp__t3-code__" + name)); let catalog: ReadonlyArray = []; const client = createMcpClient(endpoint, token); let started: Promise | undefined; const registerTools = () => { - // Preserve public names for saved loadouts and tool selectors. Hidden - // canonical names reserve ownership against Pi's configured MCP servers. - const prefixes = supportsExposure ? ["mcp__t3-code__", "mcp__t3_code__"] : ["mcp__t3-code__"]; + // Preserve public names for saved loadouts and tool selectors. The alias, + // Pi's own MCP name for T3, reserves it against Pi's configured MCP servers. + // model-only keeps it out of codemode; it hides its own declaration. + const prefixes = supportsExposure ? ["mcp__t3-code__", ALIAS_PREFIX] : ["mcp__t3-code__"]; readOnlyMcpTools.clear(); for (const tool of catalog) { const name = tool.name; for (const prefix of prefixes) { - if (tool.annotations?.readOnlyHint === true) readOnlyMcpTools.add(\`\${prefix}\${name}\`); - const exposure = prefix === "mcp__t3_code__" ? "hidden" : - deferOptionalTools && !directTools.has(name) ? "deferred" : "direct"; + const toolName = \`\${prefix}\${name}\`; + if (tool.annotations?.readOnlyHint === true) readOnlyMcpTools.add(toolName); + const isAlias = prefix === ALIAS_PREFIX; + const exposure = isAlias ? "model-only" : isDeferred(name) ? "deferred" : "direct"; pi.registerTool({ - name: \`\${prefix}\${name}\`, + name: toolName, label: name, description: tool.description ?? name, parameters: jsonSchemaToTypebox(tool.inputSchema), ...(supportsExposure ? { outputSchema: mcpOutputSchema(tool) } : {}), ...(supportsExposure ? { exposure } : {}), + ...(isAlias ? { prepareLoadout: () => ({ hiddenDeclarations: [toolName] }) } : {}), async execute(_toolCallId, params, signal) { + // Another extension may switch the public tool off after reconciliation. + if ( + isAlias && + !followsPublicTool(name, new Set(pi.getAllTools().map((tool) => tool.name)), pi.getActiveTools()) + ) { + return { content: [{ type: "text", text: \`Tool \${toolName} not found\` }], details: {}, isError: true }; + } const result = await client.callTool( name, (params ?? {}) as Record, @@ -470,7 +491,6 @@ export default async function t3McpExtension(pi: ExtensionAPI) { const exposureChanged = deferOptionalTools !== hasToolSearch; deferOptionalTools = hasToolSearch; if (exposureChanged) registerTools(); - const active = pi.getActiveTools(); // Completion gateways can silently drop calls to undeclared tools named // in history or guidance. Eagerly load T3 schemas, including after tree // restores, while retaining deferred exposure for Pi's allowlist rules. @@ -479,8 +499,18 @@ export default async function t3McpExtension(pi: ExtensionAPI) { ...(hasToolSearch ? ["tool_search"] : []), ...(ctx.model?.api === "openai-completions" ? catalog.map((tool) => "mcp__t3-code__" + tool.name) : []), ]; - const missing = required.filter((name) => !active.includes(name)); - if (missing.length > 0) pi.setActiveTools([...active, ...missing]); + const current = pi.getActiveTools(); + const missing = required.filter((name) => !current.includes(name)); + if (missing.length > 0) pi.setActiveTools([...current, ...missing]); + // An alias is callable only while active. + const registered = new Set(pi.getAllTools().map((tool) => tool.name)); + const loaded = pi.getActiveTools(); + const aliases = catalog + .filter((tool) => registered.has(ALIAS_PREFIX + tool.name) && followsPublicTool(tool.name, registered, loaded)) + .map((tool) => ALIAS_PREFIX + tool.name); + const kept = loaded.filter((name) => !name.startsWith(ALIAS_PREFIX) || aliases.includes(name)); + const added = aliases.filter((name) => !loaded.includes(name)); + if (added.length > 0 || kept.length !== loaded.length) pi.setActiveTools([...kept, ...added]); }; // Tree navigation restores its saved loadout after session_start. From f9e45e436317417bea136f3461662a0f51ea10b9 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 19 Nov 2026 12:44:04 -0800 Subject: [PATCH 70/97] fix(server): agents on hosts without swap are OOM-killed instead of throttled for hours (#39287) --- apps/server/src/process/agentScope.test.ts | 15 ++++++++++--- apps/server/src/process/agentScope.ts | 25 ++++++++++++++-------- 2 files changed, 28 insertions(+), 12 deletions(-) diff --git a/apps/server/src/process/agentScope.test.ts b/apps/server/src/process/agentScope.test.ts index 49674354b2532..033d83bc5f5c0 100644 --- a/apps/server/src/process/agentScope.test.ts +++ b/apps/server/src/process/agentScope.test.ts @@ -21,7 +21,7 @@ import * as ProviderProcesses from "./providerProcesses.ts"; import { classifyScope, make, ownedAgentSlice, type ScopeState } from "./agentScope.ts"; const GiB = 1024 ** 3; -const memory = vi.hoisted(() => ({ total: 16 * 1024 ** 3 })); +const memory = vi.hoisted(() => ({ total: 16 * 1024 ** 3, swapKb: 2 * 1024 ** 2 })); vi.mock("node:os", async (importOriginal) => ({ ...(await importOriginal()), totalmem: () => memory.total, @@ -133,7 +133,9 @@ const withFakeSystemd = ( Effect.provideService(FileSystem.FileSystem, { ...fileSystem, readFileString: (path, encoding) => - fileSystem.readFileString(path.replace("/sys/fs/cgroup", cgroupRoot), encoding), + path === "/proc/meminfo" + ? Effect.sync(() => `MemTotal: 16384 kB\nSwapTotal: ${memory.swapKb} kB\n`) + : fileSystem.readFileString(path.replace("/sys/fs/cgroup", cgroupRoot), encoding), writeFileString: (path, data, options) => fileSystem.writeFileString(path.replace("/sys/fs/cgroup", cgroupRoot), data, options), }), @@ -331,8 +333,9 @@ describe("AgentScope service", () => { ), ); - it.effect("follows a live memory change at the next launch", () => { + it.effect("follows a live memory or swap change at the next launch", () => { memory.total = 16 * GiB; + memory.swapKb = 2 * 1024 ** 2; return withFakeSystemd(({ scope, calls, failingVerbs }) => Effect.gen(function* () { const launch = scope.wrap({ command: "agent", args: [], name: "t", threadId: "a" }); @@ -361,6 +364,12 @@ describe("AgentScope service", () => { grown, grown, ]); + + // Without swap, MemoryHigh only throttles; MemoryMax must OOM-kill the runaway. + memory.swapKb = 0; + yield* launch; + expect(memoryLimits().at(-1)).toEqual(["MemoryHigh=infinity", `MemoryMax=${18 * GiB}`]); + memory.swapKb = 2 * 1024 ** 2; }), ); }); diff --git a/apps/server/src/process/agentScope.ts b/apps/server/src/process/agentScope.ts index 1e52e680b6f8d..4bbb7d159cf0b 100644 --- a/apps/server/src/process/agentScope.ts +++ b/apps/server/src/process/agentScope.ts @@ -36,14 +36,13 @@ export function ownedAgentSlice(stateDir: string): string { const GiB = 1024 ** 3; /** - * Agents together leave about 6 GB free before they are throttled and 4 GB - * before the kernel kills one, so the server, sshd, and tailscaled keep - * working. Small machines still give agents at least half of RAM before - * throttling and three quarters before a kill. + * Agents leave about 6 GB free before throttling and 4 GB before an OOM kill (at + * least half and three quarters of RAM go to agents) so the server and sshd keep + * working. Without swap, MemoryHigh stalls every agent and never reaches the kill. */ -function agentSliceMemoryLimits(totalBytes: number) { +function agentSliceMemoryLimits(totalBytes: number, hasSwap: boolean) { return { - high: Math.max(totalBytes - 6 * GiB, Math.floor(totalBytes / 2)), + high: hasSwap ? Math.max(totalBytes - 6 * GiB, Math.floor(totalBytes / 2)) : "infinity", max: Math.max(totalBytes - 4 * GiB, Math.floor(totalBytes * 0.75)), }; } @@ -204,13 +203,20 @@ export const make = Effect.gen(function* () { }); // VMs and containers can resize RAM live, so each launch re-checks the total // the limits came from. A failed update is retried by the next launch. + // An unreadable meminfo keeps the throttle, as before swap was checked. + const readHasSwap = fileSystem.readFileString("/proc/meminfo").pipe( + Effect.map((text) => /^SwapTotal:\s*0 kB$/m.exec(text) === null), + Effect.orElseSucceed(() => true), + ); let appliedTotal: number | undefined; + let appliedHasSwap: boolean | undefined; const memoryLimitsLock = yield* Semaphore.make(1); const applyMemoryLimits = memoryLimitsLock.withPermits(1)( Effect.gen(function* () { const total = NodeOS.totalmem(); - if (total === appliedTotal) return; - const limits = agentSliceMemoryLimits(total); + const hasSwap = yield* readHasSwap; + if (total === appliedTotal && hasSwap === appliedHasSwap) return; + const limits = agentSliceMemoryLimits(total, hasSwap); const applied = yield* setProperties(AGENT_SLICE, [ `MemoryHigh=${limits.high}`, `MemoryMax=${limits.max}`, @@ -225,13 +231,14 @@ export const make = Effect.gen(function* () { }); } appliedTotal = total; + appliedHasSwap = hasSwap; }), ); yield* applyMemoryLimits; yield* setProperties(AGENTS_PARENT_SLICE, AGENTS_PARENT_PROPERTIES); yield* Effect.logInfo("Agent scopes are on", { slice: AGENT_SLICE, - ...agentSliceMemoryLimits(NodeOS.totalmem()), + ...agentSliceMemoryLimits(NodeOS.totalmem(), yield* readHasSwap), oomPolicy: supportsOomPolicy, }); return { From c4419dadd91249d9eeff4a26c1098517e71736f0 Mon Sep 17 00:00:00 2001 From: Bilal Bakr <62337003+Bil0000@users.noreply.github.com> Date: Thu, 19 Nov 2026 23:47:58 +0300 Subject: [PATCH 71/97] fix(server): threads stay in Working when Claude or OpenCode marks a background wait between turns (#38638) Co-authored-by: Claude Opus 5.5 Co-authored-by: Julius Marminge --- apps/server/src/mcp/toolkits/core.test.ts | 40 +++++ .../src/mcp/toolkits/orchestrator/handlers.ts | 3 +- .../Adapters/OpenCode2AdapterV2.test.ts | 145 ++++++++++++++++++ .../src/server/v2/adapter.ts | 101 ++++++++++-- 4 files changed, 276 insertions(+), 13 deletions(-) diff --git a/apps/server/src/mcp/toolkits/core.test.ts b/apps/server/src/mcp/toolkits/core.test.ts index daadff0e09d54..bdd48dda82817 100644 --- a/apps/server/src/mcp/toolkits/core.test.ts +++ b/apps/server/src/mcp/toolkits/core.test.ts @@ -1291,6 +1291,46 @@ it.effect.each(["t3_thread_interrupt", "t3_workflow_stop"])( ), ); +it.effect( + "t3_background_wait marks work from a turn Claude started before T3 started its run", + () => + Effect.gen(function* () { + const server = yield* McpServer.McpServer; + const result = yield* server + .callTool({ name: "t3_background_wait", arguments: { taskIds: ["checks"] } }) + .pipe( + Effect.provideService(McpInvocationContext.McpInvocationContext, scope), + Effect.provideService(McpSchema.McpServerClient, client), + ); + expect(result.structuredContent).toEqual({ matched: ["checks"], unmatched: [] }); + }).pipe( + Effect.provide( + layerOrchestratorToolkit.pipe( + Layer.provideMerge(McpHttpServer.layerInProcessMcpServer), + Layer.provide(NodeCrypto.layer), + Layer.provide( + Layer.mock(ThreadManagement.ThreadManagementService)({ + getThreadShell: (id) => + Effect.succeed(McpToolAccessTestkit.liveThreadShell(id, { activeRunId: null })), + awaitBackgroundTasks: ({ taskIds }) => + Effect.succeed({ matched: taskIds, unmatched: [] }), + }), + ), + Layer.provide(ServerSettings.layerTest()), + Layer.provide(Layer.mock(ProviderRegistry.ProviderRegistry)({})), + Layer.provide(Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({})), + Layer.provide(Layer.mock(ScheduledTaskService.ScheduledTaskService)({})), + Layer.provide(Layer.mock(ProjectService.ProjectService)({})), + Layer.provide(Layer.mock(SecretRequests.SecretRequests)({})), + Layer.provide(Layer.mock(RemoteDelegation.RemoteDelegation)({})), + Layer.provide(Layer.mock(PeerForwarding.PeerForwarding)({})), + Layer.provide(Layer.mock(PeerLinkRequests.PeerLinkRequests)({})), + Layer.provide(Layer.mock(PeerLinks.PeerLinks)({})), + ), + ), + ), +); + it.effect("discovers workflow stop targets and requires orchestration capability", () => { const threadId = ThreadId.make("workflow-parent"); const shell = McpToolAccessTestkit.liveThreadShell(threadId); diff --git a/apps/server/src/mcp/toolkits/orchestrator/handlers.ts b/apps/server/src/mcp/toolkits/orchestrator/handlers.ts index dfa1ad58545ee..d90a118be468e 100644 --- a/apps/server/src/mcp/toolkits/orchestrator/handlers.ts +++ b/apps/server/src/mcp/toolkits/orchestrator/handlers.ts @@ -61,7 +61,8 @@ const handlers = { ); }), ), - t3_background_wait: McpToolAccess.actsAsCaller((input) => + // Claude can start a turn by itself before T3 starts its run, so a live-run check would refuse the mark. + t3_background_wait: McpToolAccess.readsAsCaller((input) => Effect.gen(function* () { const { scope, threads } = yield* readCaller(); const caller = yield* McpInvocationContext.requireThreadScope(scope, "t3_background_wait"); diff --git a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts index 3b82ff9a69754..5dbaf3628b11d 100644 --- a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts @@ -2342,6 +2342,151 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { }), ); + it.effect.each(["running", "exited", "timeout", "held", "sync"] as const)( + "marks a shell OpenCode started on its own before T3 runs the wake, shell %s", + (shell) => + Effect.gen(function* () { + const shellID = "sh_wake"; + const tool = { sessionID: SESSION, assistantMessageID: "msg_wake", id: "call-wake-shell" }; + const offers: Array = []; + const shellReport = (state: string, extra: Record = {}) => + event("session.inbox.enqueued", { + inboxID: "msg_shell_report", + sessionID: SESSION, + item: { + type: "synthetic", + payload: { + text: `done`, + description: "vp test", + metadata: { source: "shell", shellID, state, ...extra }, + }, + delivery: "steer", + }, + }); + const { runtime, thread } = yield* resumed([ + ...backgroundLaunch(CHILD), + event("session.execution.succeeded", { sessionID: SESSION }), + event("session.execution.succeeded", { sessionID: CHILD }), + childReport("msg_report", "CHILD_OK"), + event("session.execution.started", { sessionID: SESSION }), + event("session.tool.input.started", { ...tool, name: "shell" }), + event("session.tool.called", { + ...tool, + name: "shell", + input: { command: "vp test", background: true }, + executed: false, + }), + event( + "session.tool.success", + { + ...tool, + content: [{ type: "text", text: "Launched" }], + // A foreground shell's result already carries its exit. + metadata: shell === "sync" ? { shellID, exit: 0 } : { shellID }, + executed: false, + }, + undefined, + 2, + ), + event("shell.created", { + info: { + id: shellID, + status: "running", + command: "vp test", + cwd: WORK, + shell: "bash", + file: "/tmp/sh_wake.log", + metadata: { sessionID: SESSION }, + time: { started: 1 }, + }, + }), + ...(shell === "held" ? [shellReport("completed")] : []), + event("session.execution.succeeded", { sessionID: SESSION }), + ...(shell === "exited" + ? [ + event("shell.exited", { id: shellID, exit: 7, status: "exited" }), + shellReport("error"), + ] + : []), + ...(shell === "timeout" + ? [ + event("shell.exited", { id: shellID, status: "timeout" }), + shellReport("completed", { timeout: true }), + ] + : []), + // Routed once the held execution ended, so its update proves the launch reached the adapter. + event("session.model.selected", { + sessionID: SESSION, + model: { providerID: "opencode", id: "big-pickle", variant: "thinking" }, + }), + ...Array.from({ length: shell === "held" ? 2 : shell === "sync" ? 0 : 1 }, () => [ + out("shell.output", ""), + reply("shell.output", { + location: { directory: WORK }, + data: { output: "", cursor: 0, size: 0, truncated: false }, + }), + ]).flat(), + ]).pipe( + Effect.provideService(ProviderContinuationRequests.ProviderContinuationRequests, { + offer: (request) => + Effect.sync(() => { + offers.push(request); + }), + take: Effect.never, + }), + ); + // One reader: the runtime's event queue hands each event to only one taker. + const launchSeen = yield* Deferred.make(); + const marked = yield* Deferred.make(); + const settled = + yield* Deferred.make(); + yield* runtime.events.pipe( + Stream.tap((e) => + e.type === "turn_item.updated" && + e.turnItem.type === "command_execution" && + e.turnItem.status !== "running" + ? Deferred.succeed(settled, e.turnItem) + : e.type !== "provider_thread.updated" + ? Effect.void + : Effect.gen(function* () { + const variant = + e.providerThread.nativeMetadata?.modelSelection?.options?.[0]?.value; + if (variant === "thinking") yield* Deferred.succeed(launchSeen, undefined); + const listed = e.providerThread.pendingBackgroundTasks?.find( + (task) => task.taskId === shellID, + ); + // The first roster that lists the shell must hold the thread already. + if (listed !== undefined) yield* Deferred.succeed(marked, listed.awaited); + }), + ), + Stream.runDrain, + Effect.forkScoped, + ); + yield* runtime.startTurn(withLineage(thread)); + yield* Deferred.await(launchSeen); + assert.deepEqual( + yield* runtime.awaitBackgroundTasks!({ + providerThread: thread, + taskIds: [shellID], + awaited: true, + }), + { matched: shell === "running" ? [shellID] : [] }, + ); + if (shell === "sync") return; + yield* runtime.startTurn(continuationTurn(thread, offers[0]!)); + if (shell === "running") return assert.isTrue(yield* Deferred.await(marked)); + // A shell that ended before the wake ran never holds the thread. + assert.deepInclude( + yield* Deferred.await(settled), + shell === "exited" + ? { status: "failed", exitCode: 7 } + : { status: shell === "timeout" ? "failed" : "completed" }, + ); + const listed = yield* Deferred.poll(marked); + if (Option.isSome(listed)) assert.notStrictEqual(yield* listed.value, true); + }), + ); + it.effect("clears the caller's pending work when a called session's held wake runs", () => Effect.gen(function* () { const OTHER = "ses_other00000000000000000000"; diff --git a/packages/provider-opencode/src/server/v2/adapter.ts b/packages/provider-opencode/src/server/v2/adapter.ts index 862144b12fa4f..9815a3caa96bf 100644 --- a/packages/provider-opencode/src/server/v2/adapter.ts +++ b/packages/provider-opencode/src/server/v2/adapter.ts @@ -313,6 +313,12 @@ interface Wake { readonly after: string | undefined; readonly first: string | undefined; readonly children: Set; + readonly awaited: Set; + /** Held shell launches whose end report arrived first; the report already cleared their status. */ + readonly ended: Map< + string, + { readonly status: "completed" | "failed" | "interrupted"; readonly exit?: number } + >; } interface OpenBlock { @@ -1011,6 +1017,38 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr } >(); + // A held wake routes its shell launches only when T3 starts its run, so marks wait on the wake. + const heldLaunch = (state: ThreadState, taskId: string) => + sessionsOf(state) + .flatMap((session) => session.wakes) + .find((wake) => + wake.events.some( + (event) => + event.type === "session.tool.success" && + stringField(event.data.metadata, "shellID") === taskId && + event.data.metadata?.["exit"] === undefined && + event.data.metadata?.["signal"] === undefined && + event.data.metadata?.["timeout"] !== true, + ), + ); + const wakeLaunchingShell = (state: ThreadState, taskId: string) => { + const wake = heldLaunch(state, taskId); + return wake === undefined || + wake.ended.has(taskId) || + (shellInfo.get(taskId)?.status ?? "running") !== "running" || + // An end report held with the launch replays after it. + wake.events.some( + (event) => + event.type === "session.inbox.enqueued" && + event.data.item.type === "synthetic" && + stringField(event.data.item.payload.metadata, "source") === "shell" && + stringField(event.data.item.payload.metadata, "shellID") === taskId, + ) + ? undefined + : wake; + }; + let replaying: Wake | undefined; + const owesWork = (state: ThreadState) => [...shells.values()].some((shell) => shell.state === state && shell.running) || [...state.imageJobs.values()].some((job) => job.status === "running") || @@ -1966,7 +2004,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr awaited: state.providerThread.pendingBackgroundTasks?.some( (task) => task.taskId === info.id && task.awaited === true, - ) === true, + ) === true || wakeLaunchingShell(state, info.id)?.awaited.has(info.id) === true, running: true, output: "", cursor: 0, @@ -2863,25 +2901,30 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr toolId: event.data.id, tool, command: stringField(tool.input, "command") ?? "Shell command", + ...(replaying?.awaited.has(shellId) === true ? { awaited: true } : {}), running: true, output: "", cursor: 0, }); - yield* readShellOutput(shellId).pipe(Effect.ignore({ log: true })); const known = shellInfo.get(shellId); + const ended = replaying?.ended.get(shellId); const tracked = shells.get(shellId)!; - tracked.running = known === undefined || known.status === "running"; + tracked.running = + ended === undefined && (known === undefined || known.status === "running"); + yield* readShellOutput(shellId, !tracked.running).pipe(Effect.ignore({ log: true })); yield* emitShell( shellId, tracked.running ? "running" - : known?.status === "killed" - ? "interrupted" - : known?.exit === 0 - ? "completed" - : "failed", - known?.exit, + : (ended?.status ?? + (known?.status === "killed" + ? "interrupted" + : known?.exit === 0 + ? "completed" + : "failed")), + ended?.exit ?? known?.exit, ); + if (ended !== undefined) shells.delete(shellId); yield* syncRosterAncestors(state); return; } @@ -3009,6 +3052,8 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr after: delivered.at(-1)?.inboxId, first: leading ?? delivered[0]?.inboxId, children: new Set(), + awaited: new Set(), + ended: new Map(), }; state.wakes.push(wake); yield* Effect.logInfo("OpenCode started a turn on its own; asking for a continuation.", { @@ -3119,6 +3164,27 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr outcome: reportOutcome(stringField(payload.metadata, "state")), }, }); + if (id !== undefined && shell === undefined) { + const outcome = reportOutcome(stringField(payload.metadata, "state")); + const known = shellInfo.get(id); + const exit = known?.exit; + // A known exit outranks the report, which says "completed" for a timeout. + heldLaunch(state, id)?.ended.set(id, { + status: + known !== undefined && known.status !== "running" + ? known.status === "killed" + ? "interrupted" + : exit === 0 + ? "completed" + : "failed" + : outcome === "failed" + ? "failed" + : outcome === "cancelled" + ? "interrupted" + : "completed", + ...(exit === undefined ? {} : { exit }), + }); + } if (id !== undefined && shell?.stopping !== true) { if (shell?.running === true && shell.state === state) { yield* readShellOutput(id, true).pipe(Effect.ignore({ log: true })); @@ -4424,7 +4490,10 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr const replay = Effect.fnUntraced(function* (wake: Wake) { wake.dropped = true; - for (const event of wake.events) yield* route(event, sessionOfEvent(event), true); + replaying = wake; + yield* Effect.forEach(wake.events, (event) => route(event, sessionOfEvent(event), true), { + discard: true, + }).pipe(Effect.ensuring(Effect.sync(() => (replaying = undefined)))); }); const discardWakes = (caller: ThreadState, wakes: ReadonlyArray) => { @@ -5153,11 +5222,19 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr const sessions = sessionsOf(state); const matched = [...new Set(taskIds)].filter((taskId) => { const shell = shells.get(taskId); - return shell !== undefined && shell.running && sessions.includes(shell.state); + return shell === undefined + ? wakeLaunchingShell(state, taskId) !== undefined + : shell.running && sessions.includes(shell.state); }); if (matched.length === 0) return { matched }; for (const taskId of matched) { - const shell = shells.get(taskId)!; + const shell = shells.get(taskId); + if (shell === undefined) { + const held = wakeLaunchingShell(state, taskId)!.awaited; + if (awaited) held.add(taskId); + else held.delete(taskId); + continue; + } shell.awaited = awaited; yield* syncRosterAncestors(shell.state); } From b111b6310ab55011e3500172377a770123c7b655 Mon Sep 17 00:00:00 2001 From: Bilal Bakr <62337003+Bil0000@users.noreply.github.com> Date: Thu, 19 Nov 2026 23:51:43 +0300 Subject: [PATCH 72/97] fix(web): collapse extra linked issues in thread details (#39232) --- .../components/chat/ThreadDetailsControl.tsx | 34 ++++++++++++++- .../chat/ThreadDetailsIssueRows.tsx | 41 ++++++++++++------ .../chat/ThreadDetailsPrRow.browser.test.tsx | 42 ++++++++++++------- .../components/chat/ThreadDetailsPrRows.tsx | 32 ++++---------- 4 files changed, 96 insertions(+), 53 deletions(-) diff --git a/apps/web/src/components/chat/ThreadDetailsControl.tsx b/apps/web/src/components/chat/ThreadDetailsControl.tsx index b2f1ce0cfe12e..576ac3ff719a6 100644 --- a/apps/web/src/components/chat/ThreadDetailsControl.tsx +++ b/apps/web/src/components/chat/ThreadDetailsControl.tsx @@ -1,5 +1,6 @@ import { mergeProps } from "@base-ui/react/merge-props"; import { useRender } from "@base-ui/react/use-render"; +import { T, Var } from "gt-react"; import type { ComponentProps } from "react"; import { cn } from "~/lib/utils"; @@ -15,7 +16,7 @@ import { THREAD_DETAILS_PANEL_SELECT_LABEL_CLASS, THREAD_DETAILS_PANEL_SELECT_ICON_CLASS, } from "./threadDetailsPanelStyles"; -import { ChevronDownIcon } from "lucide-react"; +import { ChevronDownIcon, ChevronUpIcon } from "lucide-react"; const parts = { row: THREAD_DETAILS_PANEL_ROW_CLASS, @@ -107,3 +108,34 @@ export function ThreadDetailsControl({ } return control; } + +export function ThreadDetailsMoreButton({ + expanded, + remaining, + onToggle, +}: { + expanded: boolean; + remaining: number; + onToggle: () => void; +}) { + const Icon = expanded ? ChevronUpIcon : ChevronDownIcon; + return ( + + + {expanded ? ( + Show less + ) : ( + + Show {remaining} more + + )} + + ); +} diff --git a/apps/web/src/components/chat/ThreadDetailsIssueRows.tsx b/apps/web/src/components/chat/ThreadDetailsIssueRows.tsx index da3eb6e22994b..5726d1edeca14 100644 --- a/apps/web/src/components/chat/ThreadDetailsIssueRows.tsx +++ b/apps/web/src/components/chat/ThreadDetailsIssueRows.tsx @@ -1,7 +1,8 @@ import { threadIssueKeyOf, type ScopedThreadRef, type ThreadIssueLink } from "@t3tools/contracts"; +import { scopedThreadKey } from "@t3tools/client-runtime/environment"; import { useGT } from "gt-react"; import { MessageSquareIcon } from "lucide-react"; -import type { MouseEvent } from "react"; +import { useState, type MouseEvent } from "react"; import { cn } from "~/lib/utils"; import { useRightPanelStore } from "~/rightPanelStore"; @@ -19,7 +20,7 @@ import { PullRequestRowLines, } from "../pullRequest/PullRequestListRow"; import { PullRequestActorLabel } from "../pullRequest/pullRequestPresentation"; -import { ThreadDetailsControl } from "./ThreadDetailsControl"; +import { ThreadDetailsControl, ThreadDetailsMoreButton } from "./ThreadDetailsControl"; import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; function LinkedIssueRow({ @@ -156,14 +157,30 @@ export function ThreadDetailsIssueRows({ mountScope?: "thread-details" | "linked-items" | "sidebar-tooltip"; onOpen?: () => void; }) { - return links.map((link) => ( - - )); + const [expandedThread, setExpandedThread] = useState(null); + const threadKey = scopedThreadKey(threadRef); + const expanded = expandedThread === threadKey; + const hasMore = compact && links.length > 1; + const visibleLinks = hasMore && !expanded ? links.slice(0, 1) : links; + return ( + <> + {visibleLinks.map((link) => ( + + ))} + {hasMore ? ( + setExpandedThread(expanded ? null : threadKey)} + /> + ) : null} + + ); } diff --git a/apps/web/src/components/chat/ThreadDetailsPrRow.browser.test.tsx b/apps/web/src/components/chat/ThreadDetailsPrRow.browser.test.tsx index fd3d0cc702d4c..b17067affb96f 100644 --- a/apps/web/src/components/chat/ThreadDetailsPrRow.browser.test.tsx +++ b/apps/web/src/components/chat/ThreadDetailsPrRow.browser.test.tsx @@ -8,6 +8,7 @@ import { ThreadId, type PullRequestCheck, type ScopedThreadRef, + type ThreadIssueLink, } from "@t3tools/contracts"; import { DraftId } from "~/composerDraftStore"; import { AsyncResult } from "effect/reactivity"; @@ -387,29 +388,34 @@ it("names a linked pull request row by its kind, number and title, not its URL", expect(exposedNumbers).toHaveLength(0); }); -it("names a linked issue row by its kind, number and title, not its URL", async () => { +it("names the first linked issue and reveals more issues on demand", async () => { await using screen = await setup(); + const issue: ThreadIssueLink = { + tracker: IssueTrackerKind.make("github"), + host: "github.com", + scope: "owner/repo", + key: "123", + projectId: ProjectId.make("repository"), + url: "https://github.com/owner/repo/issues/123", + source: "manual", + linkedAt: "2026-10-30T00:00:00.000Z", + displayKey: "#123", + title: "Sidebar flickers on resize", + }; await act(async () => { await screen.rerender( , ); }); @@ -433,6 +439,12 @@ it("names a linked issue row by its kind, number and title, not its URL", async row.dispatchEvent(externalClick); }); expect(externalClick.defaultPrevented).toBe(false); + const extra = screen.getByRole("link", { name: "Issue #124: Tab list jumps" }); + await expect.element(extra).not.toBeInTheDocument(); + await screen.getByRole("button", { name: "Show 1 more" }).click(); + await expect.element(extra).toBeVisible(); + await screen.getByRole("button", { name: "Show less" }).click(); + await expect.element(extra).not.toBeInTheDocument(); }); it("keeps Ready pending when refreshed detail becomes mergeable before the action settles", async () => { diff --git a/apps/web/src/components/chat/ThreadDetailsPrRows.tsx b/apps/web/src/components/chat/ThreadDetailsPrRows.tsx index 51b167a427b52..6a3132df72603 100644 --- a/apps/web/src/components/chat/ThreadDetailsPrRows.tsx +++ b/apps/web/src/components/chat/ThreadDetailsPrRows.tsx @@ -1,5 +1,5 @@ import { pipe } from "effect/Function"; -import { ThreadDetailsControl } from "./ThreadDetailsControl"; +import { ThreadDetailsMoreButton } from "./ThreadDetailsControl"; import type { EnvironmentId, ScopedThreadRef, @@ -13,8 +13,7 @@ import { threadPullRequestKeyOf, visibleThreadPullRequests, } from "@t3tools/client-runtime/thread-pull-requests"; -import { T, useMessages, Var } from "gt-react"; -import { ChevronDownIcon, ChevronUpIcon } from "lucide-react"; +import { useMessages } from "gt-react"; import { useState, type ComponentProps, type MouseEvent as ReactMouseEvent } from "react"; import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients"; @@ -136,28 +135,11 @@ function ThreadDetailsPrRows({ ))} ) : null} - setExpanded(!expanded)} - part="row" - tone="muted" - className="w-full active:scale-100" - > - {/* Chevrons, not plus and minus: the plus already means "add" in this card. */} - {expanded ? ( - - ) : ( - - )} - {expanded ? ( - Show less - ) : ( - - Show {rest.length} more - - )} - + setExpanded(!expanded)} + /> ); } From cae24a6f0ef6c65be44a457940494e0d4f0c3b97 Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Thu, 19 Nov 2026 12:54:13 -0800 Subject: [PATCH 73/97] fix(release): update feed check waits for a just-published nightly (#39192) Co-authored-by: Claude Opus 5.5 --- .github/scripts/check-nightly-release.cjs | 34 +++++++++++++------ .../scripts/check-nightly-release.test.cjs | 16 ++++++++- docs/operations/release.md | 5 +-- 3 files changed, 42 insertions(+), 13 deletions(-) diff --git a/.github/scripts/check-nightly-release.cjs b/.github/scripts/check-nightly-release.cjs index a9502b26c8c81..4d2d039696322 100644 --- a/.github/scripts/check-nightly-release.cjs +++ b/.github/scripts/check-nightly-release.cjs @@ -124,7 +124,12 @@ async function resolveLatestNightlyCommit({ github, context, core }) { // The two places a nightly install looks for an update: the `update-feed` pointer, and // releases.atom, which holds the 10 newest git tags of any kind. Older installs take the first // nightly in the feed. Reports what each names beside the newest published nightly. -async function readNightlyUpdateFeed({ github, context, fetch = globalThis.fetch }) { +async function readNightlyUpdateFeed({ + github, + context, + fetch = globalThis.fetch, + sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)), +}) { const latest = await findLatestNightly({ github, context }); if (!latest) return {}; @@ -150,19 +155,28 @@ async function readNightlyUpdateFeed({ github, context, fetch = globalThis.fetch // An unreadable feed leaves `feedTags` unset, so the pointer is still repaired. An error page // can answer HTTP 200, so only an Atom document counts as read. - let feedTags; - try { - const feed = await fetch(`${base}/releases.atom`, { signal: signal() }); - const body = feed.ok ? await feed.text() : ""; - if (/]/.test(body)) { - feedTags = Array.from(body.matchAll(/href="[^"]*\/releases\/tag\/([^"]+)"/g), (match) => + const readFeed = async () => { + try { + const feed = await fetch(`${base}/releases.atom`, { signal: signal() }); + const body = feed.ok ? await feed.text() : ""; + if (!/]/.test(body)) return {}; + const feedTags = Array.from(body.matchAll(/href="[^"]*\/releases\/tag\/([^"]+)"/g), (match) => decodeURIComponent(match[1]), ); + const feedNightly = feedTags.find((tag) => /^v?\d+\.\d+\.\d+-nightly\./.test(tag)); + return { feedTags, feedNightly }; + } catch { + return {}; } - } catch {} - const feedNightly = feedTags?.find((tag) => /^v?\d+\.\d+\.\d+-nightly\./.test(tag)); + }; + // The feed can lag a release published seconds ago, so read it again before calling it hidden. + let feed = await readFeed(); + for (let retry = 0; retry < 3 && feed.feedTags && feed.feedNightly !== latest.tagName; retry++) { + await sleep(30_000); + feed = await readFeed(); + } - return { tag: latest.tagName, pointerTag, feedNightly, feedTags }; + return { tag: latest.tagName, pointerTag, ...feed }; } module.exports = { diff --git a/.github/scripts/check-nightly-release.test.cjs b/.github/scripts/check-nightly-release.test.cjs index 2f3d385755ca6..82decf82747da 100644 --- a/.github/scripts/check-nightly-release.test.cjs +++ b/.github/scripts/check-nightly-release.test.cjs @@ -247,19 +247,33 @@ const atomFeed = (tags) => new Response(`${tags.map(atomEntry).join("")} url === "https://github.com/example/app/releases.atom" - ? feed + ? (feeds.length > 1 ? feeds.shift() : feeds[0]).clone() : url === "https://github.com/example/app/releases/download/update-feed/nightly.json" ? pointer : assert.fail(`unexpected fetch ${url}`); + options.sleeps = []; + options.sleep = async (ms) => void options.sleeps.push(ms); return options; } +test("update feed check waits for a nightly published moments ago to reach the feed", async () => { + const options = updateFeedFixture({ + feed: [atomFeed([OLDER]), atomFeed([NEWEST, OLDER])], + pointer: Response.json({ tag_name: NEWEST }), + }); + const { feedNightly } = await readNightlyUpdateFeed(options); + assert.equal(feedNightly, NEWEST); + assert.deepEqual(options.sleeps, [30_000]); +}); + const missing = () => new Response("Not Found", { status: 404 }); // HTTP 200, then the connection drops before the body arrives. const brokenBody = () => diff --git a/docs/operations/release.md b/docs/operations/release.md index 4e98e516e46be..831c70cf27763 100644 --- a/docs/operations/release.md +++ b/docs/operations/release.md @@ -484,8 +484,9 @@ A nightly install finds the newest nightly in up to three places. The release workflow's `Check the update feed` job runs on every scheduled tick, unless `PAUSE_NIGHTLY` is set, and after every nightly. It waits in the same queue as nightlies and previews. It rewrites a missing or outdated pointer. Its last step fails when the first nightly -in the feed is not the newest one. A feed it could not read is only a warning: that says nothing -about the tags, and the next tick reads it again. +in the feed is not the newest one. The feed can lag a release published seconds earlier, so the +job first reads it up to three more times, 30 seconds apart. A feed it could not read is only a +warning: that says nothing about the tags, and the next tick reads it again. When that step fails, installs that read only the feed cannot reach the newest nightly. If the feed still names an older nightly first, installs from `4603` up to the first build with the From cdeacd547afac554a12bbdc7eb122a7bcec4c395 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 19 Nov 2026 13:20:20 -0800 Subject: [PATCH 74/97] perf(server): turn start reads a long thread's restart-note history once (#39241) --- .../ProviderTurnStartService.ts | 56 ++++---- .../RestartBackgroundNote.test.ts | 12 +- .../orchestration-v2/RestartBackgroundNote.ts | 135 ++++++++++++------ 3 files changed, 126 insertions(+), 77 deletions(-) diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts index fded9011c9137..8add83f213c8e 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts @@ -1005,15 +1005,16 @@ export const layer: Layer.Layer< const restartCancelledWork = pendingRestartCancelledBackgroundWork({ runs: projection.runs, providerTurns: projection.providerTurns, - compactionMessageIds: new Set( - projection.messages - .filter( - (candidate) => - isCompactionCommandMessage(candidate) || - (goalDriver && parseGoalCommand(candidate) !== null), - ) - .map((candidate) => candidate.id), - ), + compactionMessageIds: () => + new Set( + projection.messages + .filter( + (candidate) => + isCompactionCommandMessage(candidate) || + (goalDriver && parseGoalCommand(candidate) !== null), + ) + .map((candidate) => candidate.id), + ), run, attempts: projection.attempts, }); @@ -1213,27 +1214,26 @@ export const layer: Layer.Layer< // History delivery (inline or injected) is text only, so missed images ride on prompts // until a later run's is accepted. Compaction and /goal starts carry none. A missed run's // own accepted attempt predates its unsent steering input, so it does not count. - const lastPromptOrdinal = Math.max( - 0, - ...acceptedAttempts.flatMap((attempt) => { - if (missedRunIds.has(attempt.runId)) return []; - const source = projection.runs.find((candidate) => candidate.id === attempt.runId); - const message = projection.messages.find( - (candidate) => candidate.id === source?.userMessageId, - ); - return source === undefined || - (message !== undefined && - (isCompactionCommandMessage(message) || - (goalDriver && parseGoalCommand(message) !== null))) - ? [] - : [source.ordinal]; - }), - ); + const runsById = new Map(projection.runs.map((source) => [source.id, source])); + const messagesById = new Map(projection.messages.map((message) => [message.id, message])); + let lastPromptOrdinal = 0; + for (const attempt of acceptedAttempts) { + if (missedRunIds.has(attempt.runId)) continue; + const source = runsById.get(attempt.runId); + if (source === undefined) continue; + const message = messagesById.get(source.userMessageId); + if ( + message !== undefined && + (isCompactionCommandMessage(message) || + (goalDriver && parseGoalCommand(message) !== null)) + ) + continue; + lastPromptOrdinal = Math.max(lastPromptOrdinal, source.ordinal); + } const attachments = missedHistory.flatMap((item) => item.type === "user_message" && - missedRuns.some( - (source) => source.id === item.runId && source.ordinal > lastPromptOrdinal, - ) + item.runId !== null && + (runsById.get(item.runId)?.ordinal ?? 0) > lastPromptOrdinal ? item.attachments : [], ); diff --git a/apps/server/src/orchestration-v2/RestartBackgroundNote.test.ts b/apps/server/src/orchestration-v2/RestartBackgroundNote.test.ts index 25e844f9c1dba..b5b3a033789dd 100644 --- a/apps/server/src/orchestration-v2/RestartBackgroundNote.test.ts +++ b/apps/server/src/orchestration-v2/RestartBackgroundNote.test.ts @@ -52,7 +52,7 @@ it("keeps the note for the provider thread that lost the work across a provider pendingRestartCancelledBackgroundWork({ runs, providerTurns: runs.filter((source) => source.id !== target.id).map(turnFor), - compactionMessageIds: new Set(), + compactionMessageIds: () => new Set(), run: target, attempts: [{ id: target.activeAttemptId!, runId: target.id }], }); @@ -77,7 +77,7 @@ it("delivers a resumed queued run's note even after a higher-ordinal run", () => pendingRestartCancelledBackgroundWork({ runs, providerTurns: [resumed, ranFirst].map(turnFor), - compactionMessageIds: new Set(), + compactionMessageIds: () => new Set(), run: next, attempts: [{ id: next.activeAttemptId!, runId: next.id }], }), @@ -198,7 +198,7 @@ it("does not repeat the note when a steer restarts the run on a new attempt", () ] : []), ], - compactionMessageIds: new Set(), + compactionMessageIds: () => new Set(), run: steered, attempts: runAttemptIds.map((id) => ({ id, runId: steered.id })), }); @@ -225,7 +225,7 @@ it("counts a prompted mid-turn or chained continuation as delivering the note", pendingRestartCancelledBackgroundWork({ runs: [cut, continuation, later], providerTurns: [cutTurn, ...(delivered ? [turnFor(continuation)] : [])], - compactionMessageIds: new Set(), + compactionMessageIds: () => new Set(), run: later, attempts: [{ id: later.activeAttemptId!, runId: later.id }], }); @@ -249,7 +249,7 @@ it("counts a prompted mid-turn or chained continuation as delivering the note", pendingRestartCancelledBackgroundWork({ runs: [cut, unstarted, later], providerTurns: turns, - compactionMessageIds: new Set(), + compactionMessageIds: () => new Set(), run: later, attempts: [{ id: later.activeAttemptId!, runId: later.id }], }), @@ -270,7 +270,7 @@ it("counts a prompted mid-turn or chained continuation as delivering the note", pendingRestartCancelledBackgroundWork({ runs: [cut, steered, later], providerTurns: turns, - compactionMessageIds: new Set(), + compactionMessageIds: () => new Set(), run: later, attempts, }), diff --git a/apps/server/src/orchestration-v2/RestartBackgroundNote.ts b/apps/server/src/orchestration-v2/RestartBackgroundNote.ts index efee98938d413..ae7dba05c106a 100644 --- a/apps/server/src/orchestration-v2/RestartBackgroundNote.ts +++ b/apps/server/src/orchestration-v2/RestartBackgroundNote.ts @@ -151,6 +151,15 @@ type ProviderTurnState = Pick< export function isRestartNoteSource( source: Pick, providerTurns: ReadonlyArray>, +): boolean { + return isNoteSource(source, (attemptId) => + providerTurns.some((turn) => turn.runAttemptId === attemptId && turn.status === "cancelled"), + ); +} + +function isNoteSource( + source: Pick, + attemptCancelled: (attemptId: OrchestrationV2Run["activeAttemptId"]) => boolean, ): boolean { return ( // Failed and interrupted turns never continue; recovery-cancelled waiting runs still qualify. @@ -158,9 +167,7 @@ export function isRestartNoteSource( source.status === "waiting" || source.status === "cancelled") && (source.restartCancelledBackgroundWork?.length ?? 0) > 0 && - !providerTurns.some( - (turn) => turn.runAttemptId === source.activeAttemptId && turn.status === "cancelled", - ) + !attemptCancelled(source.activeAttemptId) ); } @@ -326,6 +333,28 @@ export function isRestartContinuationSource( : source.status === "cancelled"; } +/** Built once per call so long threads are read a bounded number of times, not once per run. */ +function continuationLookup( + runs: ReadonlyArray, + providerTurns: ReadonlyArray>, + attempts: ReadonlyArray, +) { + const runsById = new Map(); + for (const run of runs) if (!runsById.has(run.id)) runsById.set(run.id, run); + const completedAttempts = new Set(); + const cancelledAttempts = new Set(); + for (const turn of providerTurns) { + if (turn.status === "completed") completedAttempts.add(turn.runAttemptId); + else if (turn.status === "cancelled") cancelledAttempts.add(turn.runAttemptId); + } + const completedRuns = new Set(); + for (const attempt of attempts) + if (completedAttempts.has(attempt.id)) completedRuns.add(attempt.runId); + return { runsById, completedAttempts, cancelledAttempts, completedRuns }; +} + +type ContinuationLookup = ReturnType; + /** Running does not prove prompt acceptance; carry continuation notes until a completed turn proves delivery. */ export function restartContinuationNote( source: OrchestrationV2Run, @@ -333,12 +362,13 @@ export function restartContinuationNote( providerTurns: ReadonlyArray>, attempts: ReadonlyArray, ): { readonly work: ReadonlyArray; readonly settled: boolean } { - const completedAttempts = new Set( - providerTurns.filter((turn) => turn.status === "completed").map((turn) => turn.runAttemptId), - ); - const completedRuns = new Set( - attempts.filter((attempt) => completedAttempts.has(attempt.id)).map((attempt) => attempt.runId), - ); + return continuationNote(source, continuationLookup(runs, providerTurns, attempts)); +} + +function continuationNote( + source: OrchestrationV2Run, + { runsById, completedAttempts, cancelledAttempts, completedRuns }: ContinuationLookup, +): { readonly work: ReadonlyArray; readonly settled: boolean } { let current = source; let work = current.restartCancelledBackgroundWork ?? []; const visited = new Set([current.id]); @@ -347,13 +377,16 @@ export function restartContinuationNote( !completedRuns.has(current.id) && !(current.activeAttemptId !== null && completedAttempts.has(current.activeAttemptId)) ) { - const previous = runs.find((candidate) => candidate.id === current.restartContinuationOfRunId); + const previous = runsById.get(current.restartContinuationOfRunId); if (previous === undefined || visited.has(previous.id)) break; visited.add(previous.id); current = previous; work = mergeRestartCancelledBackgroundWork(current.restartCancelledBackgroundWork ?? [], work); } - return { work, settled: isRestartNoteSource(current, providerTurns) }; + return { + work, + settled: isNoteSource(current, (attemptId) => cancelledAttempts.has(attemptId)), + }; } export function isRestartNoteContinuation( @@ -361,22 +394,30 @@ export function isRestartNoteContinuation( runs: ReadonlyArray, providerTurns: ReadonlyArray>, attempts: ReadonlyArray, +): boolean { + return ( + run.restartContinuationOfRunId !== undefined && + isNoteContinuation(run, continuationLookup(runs, providerTurns, attempts)) + ); +} + +function isNoteContinuation( + run: Pick, + lookup: ContinuationLookup, ): boolean { const source = run.restartContinuationOfRunId === undefined ? undefined - : runs.find((candidate) => candidate.id === run.restartContinuationOfRunId); - return ( - source !== undefined && - restartContinuationNote(source, runs, providerTurns, attempts).work.length > 0 - ); + : lookup.runsById.get(run.restartContinuationOfRunId); + return source !== undefined && continuationNote(source, lookup).work.length > 0; } /** Derive delivery from later completed turns on the same provider thread, excluding compactions, resumes, and rolled-back runs. */ export function pendingRestartCancelledBackgroundWork(input: { readonly runs: ReadonlyArray; readonly providerTurns: ReadonlyArray; - readonly compactionMessageIds: ReadonlySet; + /** Called only when an earlier run on the provider thread carries restart-note work. */ + readonly compactionMessageIds: () => ReadonlySet; readonly run: Pick< OrchestrationV2Run, | "id" @@ -390,33 +431,24 @@ export function pendingRestartCancelledBackgroundWork(input: { readonly attempts: ReadonlyArray; }): ReadonlyArray { - const isCompaction = (run: typeof input.run) => input.compactionMessageIds.has(run.userMessageId); - if ( - input.run.providerThreadId === null || - input.run.restartContinuationOfRunId !== undefined || - isCompaction(input.run) - ) + if (input.run.providerThreadId === null || input.run.restartContinuationOfRunId !== undefined) return []; const providerThreadId = input.run.providerThreadId; + const sameThread = input.runs.filter((run) => run.providerThreadId === providerThreadId); + const sources = sameThread.filter( + (source) => + (source.restartCancelledBackgroundWork?.length ?? 0) > 0 && runRanAfter(input.run, source), + ); + // Threads whose server never restarted carry no notes; skip every other lookup for them. + if (sources.length === 0) return []; + const compactionMessageIds = input.compactionMessageIds(); + const isCompaction = (run: typeof input.run) => compactionMessageIds.has(run.userMessageId); + if (isCompaction(input.run)) return []; const deliveredAttemptIds = new Set( input.providerTurns .filter((turn) => turn.providerThreadId === providerThreadId && turn.status === "completed") .map((turn) => turn.runAttemptId), ); - const sameThread = input.runs.filter((run) => run.providerThreadId === providerThreadId); - const prompted = sameThread.filter( - (candidate) => - candidate.id !== input.run.id && - candidate.activeAttemptId !== null && - candidate.status !== "rolled_back" && - (deliveredAttemptIds.has(candidate.activeAttemptId) || - input.attempts.some( - (attempt) => attempt.runId === candidate.id && deliveredAttemptIds.has(attempt.id), - )) && - !isCompaction(candidate) && - (candidate.restartContinuationOfRunId === undefined || - isRestartNoteContinuation(candidate, input.runs, input.providerTurns, input.attempts)), - ); // Earlier attempts may already have delivered the note; a steer's replacement attempt must not repeat it. const alreadyDelivered = input.attempts.some( (attempt) => @@ -425,13 +457,30 @@ export function pendingRestartCancelledBackgroundWork(input: { deliveredAttemptIds.has(attempt.id), ); if (alreadyDelivered) return []; - return sameThread - .filter( - (source) => - runRanAfter(input.run, source) && - (source.restartCancelledBackgroundWork?.length ?? 0) > 0 && - !prompted.some((later) => runRanAfter(later, source)), + const deliveredRunIds = new Set(); + for (const attempt of input.attempts) + if (deliveredAttemptIds.has(attempt.id)) deliveredRunIds.add(attempt.runId); + let lookup: ContinuationLookup | undefined; + // runRanAfter is a total order, so a source precedes some prompted run iff it precedes the latest one. + let latestPrompted: OrchestrationV2Run | undefined; + for (const candidate of sameThread) { + if ( + candidate.id !== input.run.id && + candidate.activeAttemptId !== null && + candidate.status !== "rolled_back" && + (deliveredAttemptIds.has(candidate.activeAttemptId) || deliveredRunIds.has(candidate.id)) && + !isCompaction(candidate) && + (candidate.restartContinuationOfRunId === undefined || + isNoteContinuation( + candidate, + (lookup ??= continuationLookup(input.runs, input.providerTurns, input.attempts)), + )) && + (latestPrompted === undefined || runRanAfter(candidate, latestPrompted)) ) + latestPrompted = candidate; + } + return sources + .filter((source) => latestPrompted === undefined || !runRanAfter(latestPrompted, source)) .reduce>( (work, source) => mergeRestartCancelledBackgroundWork(work, source.restartCancelledBackgroundWork ?? []), From 296f9131f72cdc65fab7852e4b2d7709dcce0f7b Mon Sep 17 00:00:00 2001 From: Ernest0N Date: Fri, 20 Nov 2026 01:21:34 +0400 Subject: [PATCH 75/97] fix(web): Cmd+W closes the browser tab when the page has focus (#39340) Co-authored-by: Julius Marminge --- apps/web/src/components/ChatView.tsx | 17 ++++++++++++++--- .../ReopenClosedViewShortcut.browser.test.tsx | 12 ++++++++---- .../src/components/ReopenClosedViewShortcut.tsx | 1 + 3 files changed, 23 insertions(+), 7 deletions(-) diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index e6f0fc79ecb62..1e1646e3123e6 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -2832,15 +2832,26 @@ export default function ChatView(props: ChatViewProps) { }, }); + const closeActiveRightPanelSurfaceStable = useStableCallback(() => { + if (activeRightPanelSurface) closeRightPanelSurface(activeRightPanelSurface); + }); + // A focused desktop browser page forwards these chords as menu actions. - // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- subscribes to desktop bridge menu actions that toggle the right panel + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- subscribes to desktop bridge menu actions that toggle or close the right panel useEffect(() => { - if (embedded) return; + if (embedded || backgroundThread) return; return window.desktopBridge?.onMenuAction((action) => { if (action === "rightPanel.toggle") toggleRightPanelStable(); else if (action === "rightPanel.toggleMaximized") toggleRightPanelMaximizedStable(); + else if (action === "rightPanel.close") closeActiveRightPanelSurfaceStable(); }); - }, [embedded, toggleRightPanelStable, toggleRightPanelMaximizedStable]); + }, [ + embedded, + backgroundThread, + toggleRightPanelStable, + toggleRightPanelMaximizedStable, + closeActiveRightPanelSurfaceStable, + ]); usePasteToFocusComposer(embedded ? null : activeThreadId, composerRef); // A delegated task is a remote thread's subagent. diff --git a/apps/web/src/components/ReopenClosedViewShortcut.browser.test.tsx b/apps/web/src/components/ReopenClosedViewShortcut.browser.test.tsx index dd12cedfbdefd..0830d218945ab 100644 --- a/apps/web/src/components/ReopenClosedViewShortcut.browser.test.tsx +++ b/apps/web/src/components/ReopenClosedViewShortcut.browser.test.tsx @@ -265,14 +265,18 @@ describe("root reopen shortcut", () => { expect(useClosedViewStore.getState().entries).toEqual([]); }, ); - it("forwards address-bar focus and zoom from a focused desktop page", async () => { + it("forwards address-bar focus, zoom, and panel close from a focused desktop page", async () => { setup(); await using _shortcut = await renderShortcut(); expect(state.setShortcuts).toHaveBeenLastCalledWith( expect.arrayContaining( - ["preview.focusUrl", "preview.zoomIn", "preview.zoomOut", "preview.resetZoom"].map( - (command) => expect.objectContaining({ command }), - ), + [ + "preview.focusUrl", + "preview.zoomIn", + "preview.zoomOut", + "preview.resetZoom", + "rightPanel.close", + ].map((command) => expect.objectContaining({ command })), ), ); }); diff --git a/apps/web/src/components/ReopenClosedViewShortcut.tsx b/apps/web/src/components/ReopenClosedViewShortcut.tsx index 5723ff357d3d7..8c4e7d7c5a80c 100644 --- a/apps/web/src/components/ReopenClosedViewShortcut.tsx +++ b/apps/web/src/components/ReopenClosedViewShortcut.tsx @@ -54,6 +54,7 @@ const PREVIEW_FORWARDED_COMMANDS = [ "sidebar.toggle", "rightPanel.toggle", "rightPanel.toggleMaximized", + "rightPanel.close", "preview.focusUrl", "preview.zoomIn", "preview.zoomOut", From b0b2c4f952d3a12a886e915ad8ffe7e82ebc1fb4 Mon Sep 17 00:00:00 2001 From: Bilal Bakr <62337003+Bil0000@users.noreply.github.com> Date: Fri, 20 Nov 2026 00:33:15 +0300 Subject: [PATCH 76/97] fix(server): agents can tell another agent's message from the user's (#39306) Co-authored-by: Julius Marminge --- .../ProviderTurnControlService.test.ts | 11 +++- .../ProviderTurnControlService.ts | 12 ++-- .../ProviderTurnStartService.ts | 12 ++-- .../SteeringCompletion.integration.test.ts | 19 ++++++- .../codex_transcript.ndjson | 6 +- .../contracts/src/orchestrationV2.test.ts | 56 ++++++++++++++++++- packages/contracts/src/orchestrationV2.ts | 32 +++++++++++ .../provider-core/src/server/handoffBudget.ts | 3 + 8 files changed, 133 insertions(+), 18 deletions(-) diff --git a/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts b/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts index 10cc4b10b7130..df80f2ded5836 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts @@ -379,7 +379,7 @@ it.effect( }), ); -it.effect("steers a running turn with the thread's MCP app model context", () => +it.effect("steers a running turn with its sender and the thread's MCP app model context", () => Effect.gen(function* () { const now = yield* DateTime.now; const threadId = ThreadId.make("thread:steer-app-context"); @@ -413,8 +413,9 @@ it.effect("steers a running turn with the thread's MCP app model context", () => id: MessageId.make("message:steer-app-context"), text: "What did the app report?", attachments: [], - createdBy: "user", - creationSource: "web", + createdBy: "agent", + creationSource: "mcp", + senderThreadId: ThreadId.make("thread:steer-sender"), } as unknown as NonNullable< ProjectionStore.ProjectionProviderControlContext["message"] >, @@ -454,6 +455,10 @@ it.effect("steers a running turn with the thread's MCP app model context", () => }).pipe(Effect.provide(layerControl)); assert.equal(steered.length, 1); + assert.equal( + steered[0]!.message.text, + '[T3 Code: the agent in T3 thread "thread:steer-sender" sent this message, not the user.]\n\nWhat did the app report?', + ); assert.deepEqual("appContext" in steered[0]! ? steered[0].appContext : undefined, [ { key: "mcp_app_turn-item_call-1", text: "Pressed: blue" }, ]); diff --git a/apps/server/src/orchestration-v2/ProviderTurnControlService.ts b/apps/server/src/orchestration-v2/ProviderTurnControlService.ts index 25df164788e76..088b4d386d177 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnControlService.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnControlService.ts @@ -8,6 +8,7 @@ import { ProviderTurnId, RunAttemptId, ThreadId, + withMessageSenderNote, } from "@t3tools/contracts"; import type * as DateTime from "effect/DateTime"; import * as Context from "effect/Context"; @@ -463,10 +464,13 @@ export const layer: Layer.Layer< ...(appContext.length === 0 ? {} : { appContext }), message: { messageId: message.id, - text: projectComposerContextForProvider({ - text: message.text, - records: message.context?.records ?? [], - }), + text: withMessageSenderNote( + message, + projectComposerContextForProvider({ + text: message.text, + records: message.context?.records ?? [], + }), + ), attachments: message.attachments, createdBy: message.createdBy, creationSource: message.creationSource, diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts index 8add83f213c8e..d423d0c2ea675 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts @@ -5,6 +5,7 @@ import { CommandId, PROVIDER_SEND_TURN_MAX_INPUT_CHARS, latestProviderTurnForAttempt, + withMessageSenderNote, type OrchestrationV2DomainEvent, type OrchestrationV2ContextHandoff, type OrchestrationV2ExecutionNode, @@ -985,10 +986,13 @@ export const layer: Layer.Layer< }); let effectiveHandoffs = handoffs; let resumeFellBack = false; - const userText = projectComposerContextForProvider({ - text: providerMessage.text, - records: providerMessage.context?.records ?? [], - }); + const userText = withMessageSenderNote( + providerMessage, + projectComposerContextForProvider({ + text: providerMessage.text, + records: providerMessage.context?.records ?? [], + }), + ); // Native goal commands go verbatim; handoff history waits a turn. const goalDriver = session.driver === "codex" || diff --git a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts index ca794563234d7..ebe5e7215bcbd 100644 --- a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts +++ b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts @@ -2427,7 +2427,9 @@ it.effect("steers a promoted scheduled delivery with the thread's current select yield* worker.drain(); const projection = yield* orchestrator.getThreadProjection(threadId); - assert.deepEqual(steered, ["scheduled"]); + assert.deepEqual(steered, [ + '[T3 Code: scheduled task "task:scheduled" sent this prompt, not the user typing in this chat.]\n\nscheduled', + ]); assert.deepEqual(projection.thread.modelSelection, composerSelection); }).pipe(Effect.provide(layer)); }), @@ -3180,7 +3182,16 @@ it.effect("starts a restart that stops the running turn ahead of an older held q const { queue, started: startedTexts } = yield* read(threadId); assert.deepEqual( { queue, started: startedTexts }, - { queue: ["queued"], started: ["first", "second", "do this instead"] }, + { + queue: ["queued"], + started: [ + "first", + ...["second", "do this instead"].map( + (text) => + `[T3 Code: this message came through T3 Code's tools, not from the user typing in this chat.]\n\n${text}`, + ), + ], + }, ); }).pipe(Effect.provide(layer)); }), @@ -3300,7 +3311,9 @@ it.effect("replays an accepted steer after its target turn completes", () => .pipe(Effect.flip); assert.equal(fresh._tag, "ThreadManagementNoSteerableRunError"); yield* worker.drain(); - assert.deepEqual(steered, [input.text]); + assert.deepEqual(steered, [ + `[T3 Code: this message came through T3 Code's tools, not from the user typing in this chat.]\n\n${input.text}`, + ]); assert.lengthOf(started, 1); }).pipe( Effect.provide( diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/delegated_task_status/codex_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/delegated_task_status/codex_transcript.ndjson index 95427ba136636..e40c278285055 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/delegated_task_status/codex_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/delegated_task_status/codex_transcript.ndjson @@ -21,7 +21,7 @@ {"type":"emit_inbound","label":"thread/name/updated","frame":{"method":"thread/name/updated","params":{"threadId":"019f1000-0000-7000-8000-000000000003","threadName":"Replay fixture: delegated_task_status"}}} {"type":"expect_outbound","label":"config/read","frame":{"id":8,"method":"config/read","params":{"cwd":"","includeLayers":false}}} {"type":"emit_inbound","label":"config/read","frame":{"id":8,"result":{"config":{},"origins":{}}}} -{"type":"expect_outbound","label":"child.original.turn/start","frame":{"id":9,"method":"turn/start","params":{"approvalPolicy":"never","cwd":"","input":[{"text":"Inspect the delegated API boundary and return the result.","type":"text"}],"model":"gpt-5.4","sandboxPolicy":{"type":"dangerFullAccess"},"threadId":"019f1000-0000-7000-8000-000000000003","approvalsReviewer":"user","summary":"auto","collaborationMode":{"mode":"default","settings":{"model":"gpt-5.4"}}}}} +{"type":"expect_outbound","label":"child.original.turn/start","frame":{"id":9,"method":"turn/start","params":{"approvalPolicy":"never","cwd":"","input":[{"text":"[T3 Code: the agent in T3 thread \"thread:mcp-orchestrator-parent\" sent this message, not the user.]\n\nInspect the delegated API boundary and return the result.","type":"text"}],"model":"gpt-5.4","sandboxPolicy":{"type":"dangerFullAccess"},"threadId":"019f1000-0000-7000-8000-000000000003","approvalsReviewer":"user","summary":"auto","collaborationMode":{"mode":"default","settings":{"model":"gpt-5.4"}}}}} {"type":"emit_inbound","label":"child.thread/started","frame":{"method":"thread/started","params":{"thread":{"id":"019f1000-0000-7000-8000-000000000003","forkedFromId":null,"preview":"","ephemeral":false,"modelProvider":"openai","createdAt":1776739468,"updatedAt":1776739468,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/delegated-task-status-child.jsonl","cwd":"/home/replay-user/t3code","cliVersion":"0.120.0","source":"vscode","agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"turns":[]}}}} {"type":"emit_inbound","label":"child.original.turn/start","frame":{"id":9,"result":{"turn":{"id":"019f1000-0000-7000-8000-000000000004","items":[],"status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"child.original.thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"019f1000-0000-7000-8000-000000000003","status":{"type":"active","activeFlags":[]}}}} @@ -33,7 +33,7 @@ {"type":"emit_inbound","label":"child.original.turn/completed","frame":{"method":"turn/completed","params":{"threadId":"019f1000-0000-7000-8000-000000000003","turn":{"id":"019f1000-0000-7000-8000-000000000004","items":[],"status":"completed","error":null,"startedAt":1776739468,"completedAt":1776739469,"durationMs":1000}}}} {"type":"expect_outbound","label":"config/read","frame":{"id":10,"method":"config/read","params":{"cwd":"","includeLayers":false}}} {"type":"emit_inbound","label":"config/read","frame":{"id":10,"result":{"config":{},"origins":{}}}} -{"type":"expect_outbound","label":"child.running.turn/start","frame":{"id":11,"method":"turn/start","params":{"approvalPolicy":"never","cwd":"","input":[{"text":"Remain active until the parent cancels this delegated task.","type":"text"}],"model":"gpt-5.4","sandboxPolicy":{"type":"dangerFullAccess"},"threadId":"019f1000-0000-7000-8000-000000000003","approvalsReviewer":"user","summary":"auto","collaborationMode":{"mode":"default","settings":{"model":"gpt-5.4"}}}}} +{"type":"expect_outbound","label":"child.running.turn/start","frame":{"id":11,"method":"turn/start","params":{"approvalPolicy":"never","cwd":"","input":[{"text":"[T3 Code: the agent in T3 thread \"thread:mcp-orchestrator-parent\" sent this message, not the user.]\n\nRemain active until the parent cancels this delegated task.","type":"text"}],"model":"gpt-5.4","sandboxPolicy":{"type":"dangerFullAccess"},"threadId":"019f1000-0000-7000-8000-000000000003","approvalsReviewer":"user","summary":"auto","collaborationMode":{"mode":"default","settings":{"model":"gpt-5.4"}}}}} {"type":"emit_inbound","label":"child.running.turn/start","frame":{"id":11,"result":{"turn":{"id":"019f1000-0000-7000-8000-000000000005","items":[],"status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"child.running.thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"019f1000-0000-7000-8000-000000000003","status":{"type":"active","activeFlags":[]}}}} {"type":"emit_inbound","label":"child.running.turn/started","frame":{"method":"turn/started","params":{"threadId":"019f1000-0000-7000-8000-000000000003","turn":{"id":"019f1000-0000-7000-8000-000000000005","items":[],"status":"inProgress","error":null,"startedAt":1776739470,"completedAt":null,"durationMs":null}}}} @@ -43,7 +43,7 @@ {"type":"emit_inbound","label":"child.running.turn/completed","frame":{"method":"turn/completed","params":{"threadId":"019f1000-0000-7000-8000-000000000003","turn":{"id":"019f1000-0000-7000-8000-000000000005","items":[],"status":"interrupted","error":null,"startedAt":1776739470,"completedAt":1776739471,"durationMs":1000}}}} {"type":"expect_outbound","label":"config/read","frame":{"id":13,"method":"config/read","params":{"cwd":"","includeLayers":false}}} {"type":"emit_inbound","label":"config/read","frame":{"id":13,"result":{"config":{},"origins":{}}}} -{"type":"expect_outbound","label":"child.queued.turn/start","frame":{"id":14,"method":"turn/start","params":{"approvalPolicy":"never","cwd":"","input":[{"text":"Complete the queued follow-up and return the final result.","type":"text"}],"model":"gpt-5.4","sandboxPolicy":{"type":"dangerFullAccess"},"threadId":"019f1000-0000-7000-8000-000000000003","approvalsReviewer":"user","summary":"auto","collaborationMode":{"mode":"default","settings":{"model":"gpt-5.4"}}}}} +{"type":"expect_outbound","label":"child.queued.turn/start","frame":{"id":14,"method":"turn/start","params":{"approvalPolicy":"never","cwd":"","input":[{"text":"[T3 Code: the agent in T3 thread \"thread:mcp-orchestrator-parent\" sent this message, not the user.]\n\nComplete the queued follow-up and return the final result.","type":"text"}],"model":"gpt-5.4","sandboxPolicy":{"type":"dangerFullAccess"},"threadId":"019f1000-0000-7000-8000-000000000003","approvalsReviewer":"user","summary":"auto","collaborationMode":{"mode":"default","settings":{"model":"gpt-5.4"}}}}} {"type":"emit_inbound","label":"child.queued.turn/start","frame":{"id":14,"result":{"turn":{"id":"019f1000-0000-7000-8000-000000000006","items":[],"status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"child.queued.thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"019f1000-0000-7000-8000-000000000003","status":{"type":"active","activeFlags":[]}}}} {"type":"emit_inbound","label":"child.queued.turn/started","frame":{"method":"turn/started","params":{"threadId":"019f1000-0000-7000-8000-000000000003","turn":{"id":"019f1000-0000-7000-8000-000000000006","items":[],"status":"inProgress","error":null,"startedAt":1776739472,"completedAt":null,"durationMs":null}}}} diff --git a/packages/contracts/src/orchestrationV2.test.ts b/packages/contracts/src/orchestrationV2.test.ts index 76f78f536d7c5..bacf812ab8057 100644 --- a/packages/contracts/src/orchestrationV2.test.ts +++ b/packages/contracts/src/orchestrationV2.test.ts @@ -2,7 +2,14 @@ import { describe, expect, it } from "@effect/vitest"; import * as DateTime from "effect/DateTime"; import * as Schema from "effect/Schema"; -import { NodeId, RunAttemptId, TrimmedNonEmptyString } from "./index.ts"; +import { + EnvironmentId, + NodeId, + RunAttemptId, + ScheduledTaskId, + ThreadId, + TrimmedNonEmptyString, +} from "./index.ts"; import { latestProviderTurnForAttempt, OrchestrationV2CheckpointFileSummary, @@ -16,6 +23,7 @@ import { OrchestrationV2ThreadHistoryPage, OrchestrationV2TurnItem, OrchestrationV2TurnItemJson, + withMessageSenderNote, } from "./orchestrationV2.ts"; const now = DateTime.makeUnsafe("2026-04-20T00:00:00.000Z"); @@ -650,3 +658,49 @@ describe("latestProviderTurnForAttempt", () => { expect(latestProviderTurnForAttempt(turns, null)).toBeUndefined(); }); }); + +describe("withMessageSenderNote", () => { + const thread = { + createdBy: "agent", + creationSource: "mcp", + senderThreadId: ThreadId.make("t"), + } as const; + it.each([ + [thread, "Hi", '[T3 Code: the agent in T3 thread "t" sent this message, not the user.]\n\nHi'], + [thread, "", '[T3 Code: the agent in T3 thread "t" sent this message, not the user.]'], + [thread, " /git/review staged", " /git/review staged"], + [thread, "$deploy ship it", "$deploy ship it"], + [ + thread, + "$25 left", + '[T3 Code: the agent in T3 thread "t" sent this message, not the user.]\n\n$25 left', + ], + [ + { + createdBy: "agent", + creationSource: "mcp", + linkedSender: { + environmentId: EnvironmentId.make("e"), + threadId: ThreadId.make("r"), + title: "x", + }, + }, + "Hi", + '[T3 Code: the agent in T3 thread "r" on linked environment "e" sent this message, not the user.]\n\nHi', + ], + [ + { createdBy: "user", creationSource: "web", scheduledTaskId: ScheduledTaskId.make("s") }, + "Hi", + '[T3 Code: scheduled task "s" sent this prompt, not the user typing in this chat.]\n\nHi', + ], + [ + { createdBy: "agent", creationSource: "mcp" }, + "Hi", + "[T3 Code: this message came through T3 Code's tools, not from the user typing in this chat.]\n\nHi", + ], + [{ createdBy: "user", creationSource: "web" }, "Hi", "Hi"], + [{ createdBy: "agent", creationSource: "server" }, "Hi", "Hi"], + ] as const)("labels %j's message %j for the provider", (message, text, expected) => { + expect(withMessageSenderNote(message, text)).toBe(expected); + }); +}); diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts index 33242f8dcdeac..573607abc7e97 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -602,6 +602,38 @@ export function isCompactionCommandMessage(message: CompactionMessageFields): bo ); } +const LEADING_COMMAND = /^\s*(?:\/|\p{Sc}[a-zA-Z0-9:_-]*[a-zA-Z])/u; + +/** + * Who sent a message, in a line the model reads before its text, or the text unchanged when a + * person typed it. Providers parse slash commands and skill mentions such as `$deploy` from the + * start of a prompt, so those stay as sent. + */ +export function withMessageSenderNote( + message: { + readonly createdBy: OrchestrationV2Actor; + readonly creationSource: OrchestrationV2CreationSource; + readonly scheduledTaskId?: ScheduledTaskId | undefined; + readonly senderThreadId?: ThreadId | undefined; + readonly linkedSender?: OrchestrationV2LinkedSender | undefined; + }, + text: string, +): string { + const agent = message.createdBy === "agent"; + const note = + agent && message.linkedSender !== undefined + ? `[T3 Code: the agent in T3 thread ${JSON.stringify(message.linkedSender.threadId)} on linked environment ${JSON.stringify(message.linkedSender.environmentId)} sent this message, not the user.]` + : agent && message.senderThreadId !== undefined + ? `[T3 Code: the agent in T3 thread ${JSON.stringify(message.senderThreadId)} sent this message, not the user.]` + : message.scheduledTaskId !== undefined + ? `[T3 Code: scheduled task ${JSON.stringify(message.scheduledTaskId)} sent this prompt, not the user typing in this chat.]` + : agent && message.creationSource === "mcp" + ? "[T3 Code: this message came through T3 Code's tools, not from the user typing in this chat.]" + : undefined; + if (note === undefined || LEADING_COMMAND.test(text)) return text; + return text === "" ? note : `${note}\n\n${text}`; +} + export type OrchestrationV2GoalCommand = | { readonly type: "show" } | { readonly type: "clear" } diff --git a/packages/provider-core/src/server/handoffBudget.ts b/packages/provider-core/src/server/handoffBudget.ts index 18bd5fb1fd284..ddf9b692c337c 100644 --- a/packages/provider-core/src/server/handoffBudget.ts +++ b/packages/provider-core/src/server/handoffBudget.ts @@ -8,6 +8,7 @@ import type { OrchestrationV2ProviderThread, OrchestrationV2TurnItem, } from "@t3tools/contracts"; +import { withMessageSenderNote } from "@t3tools/contracts"; import * as Config from "effect/Config"; @@ -137,6 +138,8 @@ export function historicalMessage( let text: string; switch (item.type) { case "user_message": + text = withMessageSenderNote(item, item.text); + break; case "assistant_message": text = item.text; break; From 6455fc1a74c752a732f1458718f67f6fd083914b Mon Sep 17 00:00:00 2001 From: Mike Olson Date: Thu, 19 Nov 2026 16:42:31 -0500 Subject: [PATCH 77/97] fix(mobile): Composer says why Send is disabled after an attachment upload fails (#38395) Co-authored-by: Julius Marminge --- .../src/components/ComposerAttachmentStrip.tsx | 7 +++++++ .../src/features/threads/ThreadComposer.tsx | 17 +++++++++++++++++ 2 files changed, 24 insertions(+) diff --git a/apps/mobile/src/components/ComposerAttachmentStrip.tsx b/apps/mobile/src/components/ComposerAttachmentStrip.tsx index 767a689568131..ba7d9790c4120 100644 --- a/apps/mobile/src/components/ComposerAttachmentStrip.tsx +++ b/apps/mobile/src/components/ComposerAttachmentStrip.tsx @@ -66,6 +66,13 @@ export function ComposerAttachmentThumbnail(props: ComposerAttachmentThumbnailPr return ( + {upload?.status === "failed" ? ( + + ) : null} {upload && upload.status !== "ready" ? ( {isExpanded ? editingAttachments : null} + {attachmentBlockReason !== null ? ( + + + + {attachmentBlockReason} + + + ) : null} { compactEditor.onRowLayout(event); From 2c2191789ae7f07b8b2d485f138b4dc7fefce9da Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 19 Nov 2026 13:43:27 -0800 Subject: [PATCH 78/97] fix(mobile): SVG text with font-variation-settings no longer crashes Android (#39334) --- patches/react-native-svg@15.16.1.patch | 82 ++++++++++++++++++++++++++ pnpm-lock.yaml | 12 ++-- 2 files changed, 88 insertions(+), 6 deletions(-) diff --git a/patches/react-native-svg@15.16.1.patch b/patches/react-native-svg@15.16.1.patch index 5431d95cfc4e9..69c2888efd40d 100644 --- a/patches/react-native-svg@15.16.1.patch +++ b/patches/react-native-svg@15.16.1.patch @@ -38,3 +38,85 @@ index 8c796236f9f4b58717ac3fbab65e33d11ba032f2..d886e13d2cd1390a396716ecf4a37920 markerTransform.preRotate(degrees); boolean useStrokeWidth = "strokeWidth".equals(mMarkerUnits); +diff --git a/android/src/main/java/com/horcrux/svg/TSpanView.java b/android/src/main/java/com/horcrux/svg/TSpanView.java +index b6e0a3892eb5416b1badf447d4f8c4e4baef828c..4660fb4b7b49ec44e78fb413a543dd5f9f93ed6a 100644 +--- a/android/src/main/java/com/horcrux/svg/TSpanView.java ++++ b/android/src/main/java/com/horcrux/svg/TSpanView.java +@@ -21,6 +21,7 @@ import static com.horcrux.svg.TextProperties.TextPathMidLine; + import static com.horcrux.svg.TextProperties.TextPathSide; + + import android.annotation.SuppressLint; ++import android.annotation.TargetApi; + import android.content.res.AssetManager; + import android.graphics.Canvas; + import android.graphics.Matrix; +@@ -290,6 +291,33 @@ class TSpanView extends TextView { + static final String additionalLigatures = "'hlig', 'cala', "; + static final String fontWeightTag = "'wght' "; + ++ static String fontVariationSettings(int weight, String extra) { ++ String weightAxis = fontWeightTag + weight; ++ return extra == null || extra.trim().isEmpty() ? weightAxis : weightAxis + ", " + extra; ++ } ++ ++ // Android throws IllegalArgumentException on settings it cannot parse, which would crash the ++ // draw; fall back to the weight axis alone. ++ @TargetApi(Build.VERSION_CODES.O) ++ private static void setPaintFontVariationSettings(Paint paint, FontData font) { ++ try { ++ paint.setFontVariationSettings( ++ fontVariationSettings(font.absoluteFontWeight, font.fontVariationSettings)); ++ } catch (IllegalArgumentException e) { ++ paint.setFontVariationSettings(fontWeightTag + font.absoluteFontWeight); ++ } ++ } ++ ++ @TargetApi(Build.VERSION_CODES.O) ++ private static void setBuilderFontVariationSettings( ++ Typeface.Builder builder, int weight, String extra) { ++ try { ++ builder.setFontVariationSettings(fontVariationSettings(weight, extra)); ++ } catch (IllegalArgumentException e) { ++ builder.setFontVariationSettings(fontWeightTag + weight); ++ } ++ } ++ + private void applySpacingAndFeatures(Paint paint, FontData font) { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { + double letterSpacing = font.letterSpacing; +@@ -307,8 +335,7 @@ class TSpanView extends TextView { + } + + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { +- paint.setFontVariationSettings( +- fontWeightTag + font.absoluteFontWeight + font.fontVariationSettings); ++ setPaintFontVariationSettings(paint, font); + } + } + } +@@ -487,8 +514,7 @@ class TSpanView extends TextView { + } + + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { +- paint.setFontVariationSettings( +- fontWeightTag + font.absoluteFontWeight + font.fontVariationSettings); ++ setPaintFontVariationSettings(paint, font); + } + } + // OpenType.js font data +@@ -1147,13 +1173,13 @@ class TSpanView extends TextView { + String ttfpath = FONTS + fontFamily + TTF; + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { + Typeface.Builder builder = new Typeface.Builder(assets, otfpath); +- builder.setFontVariationSettings("'wght' " + weight + font.fontVariationSettings); ++ setBuilderFontVariationSettings(builder, weight, font.fontVariationSettings); + builder.setWeight(weight); + builder.setItalic(isItalic); + typeface = builder.build(); + if (typeface == null) { + builder = new Typeface.Builder(assets, ttfpath); +- builder.setFontVariationSettings("'wght' " + weight + font.fontVariationSettings); ++ setBuilderFontVariationSettings(builder, weight, font.fontVariationSettings); + builder.setWeight(weight); + builder.setItalic(isItalic); + typeface = builder.build(); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 54437f3d0434c..08a6a213597b0 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -396,7 +396,7 @@ patchedDependencies: react-native-keyboard-controller@1.23.0: 1c7c80317ef050e08d4aabe034a0813d03b497dff2dc8b37fb5f4a6e3b20fddb react-native-pdf-jsi@6.1.0: d29e6b69813548de641a09db705dd94823d3f96832821ae9c3f6a196dd15cb68 react-native-reanimated@4.7.1: 95ee26e5fcab5f50bc4b4c47b3f7e6278a0b20850205efb9f6ee7e70a22d2b59 - react-native-svg@15.16.1: 110f9243ffad03654ce40dd1cdb09f01af16b8fa2ccb2b2cd3d62e682c180399 + react-native-svg@15.16.1: 7f94d240fc19418233c96f9a637dfd248846446657476c204f3614fd2847900e react-native-webview@14.0.1: 71009983c76818bd5e73d4ca597f76efd04101600c84cd4b4c5d920781c048ae importers: @@ -623,7 +623,7 @@ importers: version: link:../../packages/shared '@tabler/icons-react-native': specifier: ^3.44.0 - version: 3.44.0(react-native-svg@15.16.1(patch_hash=110f9243ffad03654ce40dd1cdb09f01af16b8fa2ccb2b2cd3d62e682c180399)(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0))(react@19.3.0) + version: 3.44.0(react-native-svg@15.16.1(patch_hash=7f94d240fc19418233c96f9a637dfd248846446657476c204f3614fd2847900e)(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0))(react@19.3.0) clsx: specifier: ^2.1.1 version: 2.1.1 @@ -791,7 +791,7 @@ importers: version: file:apps/mobile/deps/react-native-screens-5.0.0-t3.61.tgz(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0) react-native-svg: specifier: 15.16.1 - version: 15.16.1(patch_hash=110f9243ffad03654ce40dd1cdb09f01af16b8fa2ccb2b2cd3d62e682c180399)(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0) + version: 15.16.1(patch_hash=7f94d240fc19418233c96f9a637dfd248846446657476c204f3614fd2847900e)(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0) react-native-webview: specifier: 14.0.1 version: 14.0.1(patch_hash=71009983c76818bd5e73d4ca597f76efd04101600c84cd4b4c5d920781c048ae)(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0) @@ -16972,11 +16972,11 @@ snapshots: '@t3tools/mobile-terminal-native@file:apps/mobile/modules/t3-terminal': {} - '@tabler/icons-react-native@3.44.0(react-native-svg@15.16.1(patch_hash=110f9243ffad03654ce40dd1cdb09f01af16b8fa2ccb2b2cd3d62e682c180399)(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0))(react@19.3.0)': + '@tabler/icons-react-native@3.44.0(react-native-svg@15.16.1(patch_hash=7f94d240fc19418233c96f9a637dfd248846446657476c204f3614fd2847900e)(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0))(react@19.3.0)': dependencies: '@tabler/icons': 3.44.0 react: 19.3.0 - react-native-svg: 15.16.1(patch_hash=110f9243ffad03654ce40dd1cdb09f01af16b8fa2ccb2b2cd3d62e682c180399)(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0) + react-native-svg: 15.16.1(patch_hash=7f94d240fc19418233c96f9a637dfd248846446657476c204f3614fd2847900e)(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0) '@tabler/icons@3.44.0': {} @@ -22604,7 +22604,7 @@ snapshots: react-native: 0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6) warn-once: 0.1.1 - react-native-svg@15.16.1(patch_hash=110f9243ffad03654ce40dd1cdb09f01af16b8fa2ccb2b2cd3d62e682c180399)(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0): + react-native-svg@15.16.1(patch_hash=7f94d240fc19418233c96f9a637dfd248846446657476c204f3614fd2847900e)(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0): dependencies: css-select: 5.2.2 css-tree: 1.1.3 From babc83baf1cdf850182f20f53abad59ae3820a85 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 19 Nov 2026 13:43:52 -0800 Subject: [PATCH 79/97] fix(web): PR viewer renders GitHub :emoji: shortcodes (#39315) --- .../pull-requests/PullRequestMarkdown.tsx | 28 +- .../pullRequestAutolinks.test.ts | 23 +- .../pull-requests/pullRequestAutolinks.ts | 72 +- .../pullRequest/PullRequestSummaryTab.tsx | 2 +- .../pullRequestMarkdown.logic.test.ts | 30 +- .../pullRequest/pullRequestMarkdown.logic.ts | 33 +- .../client-runtime/src/githubEmojiAliases.ts | 1917 +++++++++++++++++ .../client-runtime/src/pullRequestMarkdown.ts | 37 + third-party-licenses.config.json | 12 + 9 files changed, 2109 insertions(+), 45 deletions(-) create mode 100644 packages/client-runtime/src/githubEmojiAliases.ts diff --git a/apps/mobile/src/features/pull-requests/PullRequestMarkdown.tsx b/apps/mobile/src/features/pull-requests/PullRequestMarkdown.tsx index 05fe4b444a6ef..3654cfd87bb42 100644 --- a/apps/mobile/src/features/pull-requests/PullRequestMarkdown.tsx +++ b/apps/mobile/src/features/pull-requests/PullRequestMarkdown.tsx @@ -22,7 +22,7 @@ import { sourceControlClients, type ReferenceAutolink, } from "@t3tools/client-runtime/source-control-clients"; -import { linkReferenceAutolinks } from "./pullRequestAutolinks"; +import { nativePullRequestMarkdown } from "./pullRequestAutolinks"; import { useOpenPullRequest } from "../../native/useOpenPullRequest"; import { SelectableMarkdownText } from "../../native/SelectableMarkdownText"; @@ -43,6 +43,7 @@ const AutolinksContext = createContext<((text: string) => ReadonlyArray(null); export function PullRequestMarkdownRepository(props: { @@ -69,11 +70,13 @@ export function PullRequestMarkdownRepository(props: { : null; return ( - - - {props.children} - - + + + + {props.children} + + + ); } @@ -160,18 +163,21 @@ function PullRequestBodySegmentView(props: { readonly onTaskListUndone: () => void; }) { const { segment, onTaskListChange } = props; + const autolinks = useContext(AutolinksContext); + const githubEmoji = useContext(GithubEmojiContext); if (segment.kind === "markdown") { + const prose = nativePullRequestMarkdown(segment.text, autolinks, githubEmoji); return ( { const offset = markdownTaskMarkerOffset( - segment.text, + prose.markdown, event.index, event.text, event.checked, @@ -179,7 +185,7 @@ function PullRequestBodySegmentView(props: { const kept = offset !== null && onTaskListChange({ - markerOffset: segment.sourceOffset + offset, + markerOffset: segment.sourceOffset + prose.sourceOffset(offset), checked: event.checked, }); if (!kept) props.onTaskListUndone(); @@ -218,12 +224,10 @@ function PullRequestMarkdownContent(props: { readonly onTaskListItemPress?: SelectableMarkdownTextProps["onTaskListItemPress"]; }) { const hostLineBreaks = useContext(LineBreaksContext); - const autolinks = useContext(AutolinksContext); const mediaContext = useContext(PullRequestMediaContext); const changeRequestUrl = useContext(ChangeRequestUrlContext); const resolveMediaUrl = (href: string) => changeRequestUrl ? resolveChangeRequestMediaUrl(href, changeRequestUrl) : href; - const markdown = linkReferenceAutolinks(props.markdown, autolinks); const openPullRequest = useOpenPullRequest(); const openLink = (href: string) => { void openPullRequest(href); @@ -236,7 +240,7 @@ function PullRequestMarkdownContent(props: { return ( { +describe("nativePullRequestMarkdown", () => { it("links the host's references in prose", () => { - expect(linkReferenceAutolinks("Closes #123, see @julius", github)).toBe( + expect(nativePullRequestMarkdown("Closes #123, see @julius", github, false).markdown).toBe( "Closes [#123](https://github.com/team/repo/issues/123), see [@julius](https://github.com/julius)", ); }); @@ -18,12 +18,12 @@ describe("linkReferenceAutolinks", () => { it("leaves code, links, images, escapes and definitions alone", () => { const text = "`#123 @person abc1234`\n\n```\n#123\n```\n\n[#123](https://example.com) ![#123](image.png) https://example.com/#123 user@example.com \\#123 1234567\n\n[ref]: https://example.com/#123"; - expect(linkReferenceAutolinks(text, github)).toBe(text); + expect(nativePullRequestMarkdown(text, github, false).markdown).toBe(text); }); it("does not nest links inside HTML anchors or code", () => { const text = 'See
#12 and #13, then #14.'; - expect(linkReferenceAutolinks(text, github)).toBe( + expect(nativePullRequestMarkdown(text, github, false).markdown).toBe( 'See #12 and #13, then [#14](https://github.com/team/repo/issues/14).', ); }); @@ -33,6 +33,17 @@ describe("linkReferenceAutolinks", () => { provider: "forgejo", url: "https://codeberg.org/acme/web/pulls/7", }); - expect(linkReferenceAutolinks("Closes #123", forgejo)).toBe("Closes #123"); + expect(nativePullRequestMarkdown("Closes #123", forgejo, false).markdown).toBe("Closes #123"); + }); + + it("expands GitHub emoji aliases in prose and link labels, mapping offsets back", () => { + const text = + "- [ ] Ship :tada: #1 `:tada:`\n- [ ] [:+1: docs](https://x.dev/:tada:) https://x.dev/:tada: :asterisk:"; + const native = nativePullRequestMarkdown(text, github, true); + expect(native.markdown).toBe( + "- [ ] Ship 🎉 [#1](https://github.com/team/repo/issues/1) `:tada:`\n- [ ] [👍 docs](https://x.dev/:tada:) https://x.dev/:tada: \\*️⃣", + ); + const marker = native.markdown.lastIndexOf("[ ]"); + expect(native.sourceOffset(marker)).toBe(text.lastIndexOf("[ ]")); }); }); diff --git a/apps/mobile/src/features/pull-requests/pullRequestAutolinks.ts b/apps/mobile/src/features/pull-requests/pullRequestAutolinks.ts index d46b2b11a665c..91268c797e808 100644 --- a/apps/mobile/src/features/pull-requests/pullRequestAutolinks.ts +++ b/apps/mobile/src/features/pull-requests/pullRequestAutolinks.ts @@ -1,3 +1,4 @@ +import { githubEmojiAliases } from "@t3tools/client-runtime/pull-request-markdown"; import type { ReferenceAutolink } from "@t3tools/client-runtime/source-control-clients"; import remarkGfm from "remark-gfm"; import remarkParse from "remark-parse"; @@ -26,29 +27,54 @@ const UNLINKED_TYPES = new Set([ "definition", ]); +const unchanged = (offset: number) => offset; + /** - * Rewrites the references `autolinks` finds in the markdown's prose as markdown links, because the - * native renderer takes markdown text. Text is searched as written, escapes included. + * Rewrites the references `autolinks` finds in the markdown's prose as markdown links, and GitHub's + * `:alias:` emoji as the emoji, because the native renderer takes markdown text. Text is searched + * as written, escapes included. `sourceOffset` maps an offset in the result back to `markdown`. */ -export function linkReferenceAutolinks( +export function nativePullRequestMarkdown( markdown: string, autolinks: ((text: string) => ReadonlyArray) | null, -): string { - if (autolinks === null) return markdown; + githubEmoji: boolean, +): { readonly markdown: string; readonly sourceOffset: (offset: number) => number } { + if (autolinks === null && !githubEmoji) return { markdown, sourceOffset: unchanged }; const edits: { start: number; end: number; value: string }[] = []; - const visit = (node: MarkdownNode) => { + const visit = (node: MarkdownNode, inLink: boolean) => { + // Only a bracketed label is prose; an autolink's text is its destination. + const labelled = markdown[node.position?.start.offset ?? -1] === "["; + if (node.type === "link" && labelled && !inLink) { + node.children?.forEach((child) => visit(child, true)); + return; + } if (UNLINKED_TYPES.has(node.type)) return; if (node.type === "text") { const start = node.position?.start.offset; const end = node.position?.end.offset; if (start === undefined || end === undefined) return; - for (const link of autolinks(markdown.slice(start, end))) { - edits.push({ + const text = markdown.slice(start, end); + const found: { start: number; end: number; value: string }[] = []; + for (const link of inLink ? [] : (autolinks?.(text) ?? [])) { + found.push({ start: start + link.index, end: start + link.index + link.text.length, value: `[${link.label}](${link.url})`, }); } + for (const alias of githubEmoji ? githubEmojiAliases(text) : []) { + // Keycap emoji start with `*`, which the native parser would read as emphasis. + const value = alias.emoji.replaceAll("*", "\\*"); + found.push({ + start: start + alias.index, + end: start + alias.index + alias.text.length, + value, + }); + } + found.sort((left, right) => left.start - right.start); + for (const edit of found) { + if (edit.start >= (edits.at(-1)?.end ?? 0)) edits.push(edit); + } } else if (node.children !== undefined) { let protectedHtmlDepth = 0; for (const child of node.children) { @@ -59,15 +85,31 @@ export function linkReferenceAutolinks( for (const match of tag.matchAll(/<(\/)?(?:a|code|pre|script|style)(?=[\s>])[^>]*>/giu)) { protectedHtmlDepth = Math.max(0, protectedHtmlDepth + (match[1] ? -1 : 1)); } - } else if (protectedHtmlDepth === 0) visit(child); + } else if (protectedHtmlDepth === 0) visit(child, inLink); } } }; - visit(parser.parse(markdown)); - let linked = markdown; - for (let index = edits.length - 1; index >= 0; index--) { - const edit = edits[index]!; - linked = linked.slice(0, edit.start) + edit.value + linked.slice(edit.end); + visit(parser.parse(markdown), false); + if (edits.length === 0) return { markdown, sourceOffset: unchanged }; + let rewritten = ""; + let cursor = 0; + // Where each edit ends in the result, and how far `markdown` is ahead from there on. + const shifts: { end: number; delta: number }[] = []; + for (const edit of edits) { + rewritten += markdown.slice(cursor, edit.start) + edit.value; + cursor = edit.end; + shifts.push({ end: rewritten.length, delta: edit.end - rewritten.length }); } - return linked; + rewritten += markdown.slice(cursor); + return { + markdown: rewritten, + sourceOffset(offset) { + let delta = 0; + for (const shift of shifts) { + if (shift.end > offset) break; + delta = shift.delta; + } + return offset + delta; + }, + }; } diff --git a/apps/web/src/components/pullRequest/PullRequestSummaryTab.tsx b/apps/web/src/components/pullRequest/PullRequestSummaryTab.tsx index 0e8a530c5bebb..5078a67759dec 100644 --- a/apps/web/src/components/pullRequest/PullRequestSummaryTab.tsx +++ b/apps/web/src/components/pullRequest/PullRequestSummaryTab.tsx @@ -342,7 +342,7 @@ function CollapsedComment({ className="mt-2 block w-full truncate text-left text-xs text-muted-foreground hover:text-foreground" onClick={() => statusTriggerRef.current?.focus({ preventScroll: true })} > - {pullRequestCommentPreview(body)} + {pullRequestCommentPreview(body, detail.provider)} ) : null} diff --git a/apps/web/src/components/pullRequest/pullRequestMarkdown.logic.test.ts b/apps/web/src/components/pullRequest/pullRequestMarkdown.logic.test.ts index c78617f221c1e..1655427b2d4e9 100644 --- a/apps/web/src/components/pullRequest/pullRequestMarkdown.logic.test.ts +++ b/apps/web/src/components/pullRequest/pullRequestMarkdown.logic.test.ts @@ -3,7 +3,11 @@ import remarkParse from "remark-parse"; import { unified } from "unified"; import { describe, expect, it } from "vite-plus/test"; -import { pullRequestCommentPreview, remarkPullRequestAutolinks } from "./pullRequestMarkdown.logic"; +import { + pullRequestCommentPreview, + pullRequestMarkdownPlugins, + remarkPullRequestAutolinks, +} from "./pullRequestMarkdown.logic"; type Node = { type: string; @@ -45,6 +49,24 @@ describe("remarkPullRequestAutolinks", () => { }); }); +describe("pullRequestMarkdownPlugins", () => { + it("renders GitHub emoji shortcodes in prose and leaves code literal", () => { + const processor = unified() + .use(remarkParse) + .use( + pullRequestMarkdownPlugins({ + provider: "github", + url: "https://github.com/team/repo/pull/8", + }), + ); + const tree = processor.runSync(processor.parse("Ship it :tada: :+1: `:tada:`")) as Node; + const text = (node: Node): string => + (node.type === "inlineCode" ? `\`${node.value}\`` : (node.value ?? "")) + + (node.children ?? []).map(text).join(""); + expect(text(tree)).toBe("Ship it 🎉 👍 `:tada:`"); + }); +}); + describe("pullRequestCommentPreview", () => { it.each([ ["\n> [!WARNING]\n**Guard** [this](https://example.com).", "Guard this."], @@ -68,7 +90,9 @@ describe("pullRequestCommentPreview", () => { "Review :codex-file-citation{purpose='output'} safely.", ], [":codex-followup[Prepare **print** version]", ":codex-followup[Prepare **print** version]"], - ])("extracts readable text from %s", (body, expected) => { - expect(pullRequestCommentPreview(body)).toBe(expected); + ["Approved :thumbsup: `:warning:`", "Approved 👍 :warning:"], + ["Approved :thumbsup:", "Approved :thumbsup:", "gitlab"], + ])("extracts readable text from %s", (body, expected, provider = "github") => { + expect(pullRequestCommentPreview(body, provider)).toBe(expected); }); }); diff --git a/apps/web/src/components/pullRequest/pullRequestMarkdown.logic.ts b/apps/web/src/components/pullRequest/pullRequestMarkdown.logic.ts index 40dc1473660de..21f3574838e06 100644 --- a/apps/web/src/components/pullRequest/pullRequestMarkdown.logic.ts +++ b/apps/web/src/components/pullRequest/pullRequestMarkdown.logic.ts @@ -1,5 +1,6 @@ import { changeRequestReferenceAutolinker, + expandGithubEmojiAliases, resolveChangeRequestMediaUrl, } from "@t3tools/client-runtime/pull-request-markdown"; import { @@ -78,6 +79,16 @@ function remarkChangeRequestMediaUrls(options: { readonly changeRequestUrl: stri return (tree: MarkdownNode) => visit(tree); } +/** GitHub renders `:alias:` emoji in prose; code keeps them, being `inlineCode`/`code`, not `text`. */ +function remarkGithubEmoji() { + const visit = (node: MarkdownNode): void => { + if (node.type === "text" && node.value !== undefined) + node.value = expandGithubEmojiAliases(node.value); + node.children?.forEach(visit); + }; + return (tree: MarkdownNode) => visit(tree); +} + const NO_PLUGINS: PluggableList = []; const markdownPlugins = new Map(); @@ -97,18 +108,23 @@ export function pullRequestMarkdownPlugins( if (plugins === undefined) { const autolinks = changeRequestReferenceAutolinker(changeRequest); plugins = [[remarkChangeRequestMediaUrls, { changeRequestUrl: repositoryUrl }]]; + if (changeRequest.provider === "github") plugins.push(remarkGithubEmoji); if (autolinks) plugins.push([remarkPullRequestAutolinks, { autolinks }]); markdownPlugins.set(key, plugins); } return plugins; } -const commentPreviewProcessor = unified() - .use(remarkParse) - .use(CHAT_MARKDOWN_REMARK_PLUGINS) - .use(remarkRehype, { allowDangerousHtml: true }) - .use(CHAT_MARKDOWN_REHYPE_PLUGINS) - .freeze(); +const commentPreviewProcessor = (plugins: PluggableList) => + unified() + .use(remarkParse) + .use(CHAT_MARKDOWN_REMARK_PLUGINS) + .use(plugins) + .use(remarkRehype, { allowDangerousHtml: true }) + .use(CHAT_MARKDOWN_REHYPE_PLUGINS) + .freeze(); +const commentPreview = commentPreviewProcessor(NO_PLUGINS); +const githubCommentPreview = commentPreviewProcessor([remarkGithubEmoji]); const PREVIEW_BLOCK_TAGS = new Set([ "blockquote", @@ -147,7 +163,8 @@ function commentPreviewText(node: Nodes): string { return node.type === "element" && PREVIEW_BLOCK_TAGS.has(node.tagName) ? ` ${text} ` : text; } -export function pullRequestCommentPreview(body: string): string { - const tree = commentPreviewProcessor.runSync(commentPreviewProcessor.parse(body), body); +export function pullRequestCommentPreview(body: string, provider: string): string { + const processor = provider === "github" ? githubCommentPreview : commentPreview; + const tree = processor.runSync(processor.parse(body), body); return commentPreviewText(tree).replace(/\s+/gu, " ").trim(); } diff --git a/packages/client-runtime/src/githubEmojiAliases.ts b/packages/client-runtime/src/githubEmojiAliases.ts new file mode 100644 index 0000000000000..fe43c554fecf2 --- /dev/null +++ b/packages/client-runtime/src/githubEmojiAliases.ts @@ -0,0 +1,1917 @@ +// GitHub's `:alias:` emoji, one `alias emoji` pair per line, from github/gemoji db/emoji.json at +// fadaeaf1f1a9be82b321316a6c5502e43138b2f6 (MIT, Copyright (c) 2019 GitHub, Inc.). +export const GITHUB_EMOJI_ALIASES = ` +grinning 😀 +smiley 😃 +smile 😄 +grin 😁 +laughing 😆 +satisfied 😆 +sweat_smile 😅 +rofl 🤣 +joy 😂 +slightly_smiling_face 🙂 +upside_down_face 🙃 +melting_face 🫠 +wink 😉 +blush 😊 +innocent 😇 +smiling_face_with_three_hearts 🥰 +heart_eyes 😍 +star_struck 🤩 +kissing_heart 😘 +kissing 😗 +relaxed ☺️ +kissing_closed_eyes 😚 +kissing_smiling_eyes 😙 +smiling_face_with_tear 🥲 +yum 😋 +stuck_out_tongue 😛 +stuck_out_tongue_winking_eye 😜 +zany_face 🤪 +stuck_out_tongue_closed_eyes 😝 +money_mouth_face 🤑 +hugs 🤗 +hand_over_mouth 🤭 +face_with_open_eyes_and_hand_over_mouth 🫢 +face_with_peeking_eye 🫣 +shushing_face 🤫 +thinking 🤔 +saluting_face 🫡 +zipper_mouth_face 🤐 +raised_eyebrow 🤨 +neutral_face 😐 +expressionless 😑 +no_mouth 😶 +dotted_line_face 🫥 +face_in_clouds 😶‍🌫️ +smirk 😏 +unamused 😒 +roll_eyes 🙄 +grimacing 😬 +face_exhaling 😮‍💨 +lying_face 🤥 +shaking_face 🫨 +relieved 😌 +pensive 😔 +sleepy 😪 +drooling_face 🤤 +sleeping 😴 +mask 😷 +face_with_thermometer 🤒 +face_with_head_bandage 🤕 +nauseated_face 🤢 +vomiting_face 🤮 +sneezing_face 🤧 +hot_face 🥵 +cold_face 🥶 +woozy_face 🥴 +dizzy_face 😵 +face_with_spiral_eyes 😵‍💫 +exploding_head 🤯 +cowboy_hat_face 🤠 +partying_face 🥳 +disguised_face 🥸 +sunglasses 😎 +nerd_face 🤓 +monocle_face 🧐 +confused 😕 +face_with_diagonal_mouth 🫤 +worried 😟 +slightly_frowning_face 🙁 +frowning_face ☹️ +open_mouth 😮 +hushed 😯 +astonished 😲 +flushed 😳 +pleading_face 🥺 +face_holding_back_tears 🥹 +frowning 😦 +anguished 😧 +fearful 😨 +cold_sweat 😰 +disappointed_relieved 😥 +cry 😢 +sob 😭 +scream 😱 +confounded 😖 +persevere 😣 +disappointed 😞 +sweat 😓 +weary 😩 +tired_face 😫 +yawning_face 🥱 +triumph 😤 +rage 😡 +pout 😡 +angry 😠 +cursing_face 🤬 +smiling_imp 😈 +imp 👿 +skull 💀 +skull_and_crossbones ☠️ +hankey 💩 +poop 💩 +shit 💩 +clown_face 🤡 +japanese_ogre 👹 +japanese_goblin 👺 +ghost 👻 +alien 👽 +space_invader 👾 +robot 🤖 +smiley_cat 😺 +smile_cat 😸 +joy_cat 😹 +heart_eyes_cat 😻 +smirk_cat 😼 +kissing_cat 😽 +scream_cat 🙀 +crying_cat_face 😿 +pouting_cat 😾 +see_no_evil 🙈 +hear_no_evil 🙉 +speak_no_evil 🙊 +love_letter 💌 +cupid 💘 +gift_heart 💝 +sparkling_heart 💖 +heartpulse 💗 +heartbeat 💓 +revolving_hearts 💞 +two_hearts 💕 +heart_decoration 💟 +heavy_heart_exclamation ❣️ +broken_heart 💔 +heart_on_fire ❤️‍🔥 +mending_heart ❤️‍🩹 +heart ❤️ +pink_heart 🩷 +orange_heart 🧡 +yellow_heart 💛 +green_heart 💚 +blue_heart 💙 +light_blue_heart 🩵 +purple_heart 💜 +brown_heart 🤎 +black_heart 🖤 +grey_heart 🩶 +white_heart 🤍 +kiss 💋 +100 💯 +anger 💢 +boom 💥 +collision 💥 +dizzy 💫 +sweat_drops 💦 +dash 💨 +hole 🕳️ +speech_balloon 💬 +eye_speech_bubble 👁️‍🗨️ +left_speech_bubble 🗨️ +right_anger_bubble 🗯️ +thought_balloon 💭 +zzz 💤 +wave 👋 +raised_back_of_hand 🤚 +raised_hand_with_fingers_splayed 🖐️ +hand ✋ +raised_hand ✋ +vulcan_salute 🖖 +rightwards_hand 🫱 +leftwards_hand 🫲 +palm_down_hand 🫳 +palm_up_hand 🫴 +leftwards_pushing_hand 🫷 +rightwards_pushing_hand 🫸 +ok_hand 👌 +pinched_fingers 🤌 +pinching_hand 🤏 +v ✌️ +crossed_fingers 🤞 +hand_with_index_finger_and_thumb_crossed 🫰 +love_you_gesture 🤟 +metal 🤘 +call_me_hand 🤙 +point_left 👈 +point_right 👉 +point_up_2 👆 +middle_finger 🖕 +fu 🖕 +point_down 👇 +point_up ☝️ +index_pointing_at_the_viewer 🫵 ++1 👍 +thumbsup 👍 +-1 👎 +thumbsdown 👎 +fist_raised ✊ +fist ✊ +fist_oncoming 👊 +facepunch 👊 +punch 👊 +fist_left 🤛 +fist_right 🤜 +clap 👏 +raised_hands 🙌 +heart_hands 🫶 +open_hands 👐 +palms_up_together 🤲 +handshake 🤝 +pray 🙏 +writing_hand ✍️ +nail_care 💅 +selfie 🤳 +muscle 💪 +mechanical_arm 🦾 +mechanical_leg 🦿 +leg 🦵 +foot 🦶 +ear 👂 +ear_with_hearing_aid 🦻 +nose 👃 +brain 🧠 +anatomical_heart 🫀 +lungs 🫁 +tooth 🦷 +bone 🦴 +eyes 👀 +eye 👁️ +tongue 👅 +lips 👄 +biting_lip 🫦 +baby 👶 +child 🧒 +boy 👦 +girl 👧 +adult 🧑 +blond_haired_person 👱 +man 👨 +bearded_person 🧔 +man_beard 🧔‍♂️ +woman_beard 🧔‍♀️ +red_haired_man 👨‍🦰 +curly_haired_man 👨‍🦱 +white_haired_man 👨‍🦳 +bald_man 👨‍🦲 +woman 👩 +red_haired_woman 👩‍🦰 +person_red_hair 🧑‍🦰 +curly_haired_woman 👩‍🦱 +person_curly_hair 🧑‍🦱 +white_haired_woman 👩‍🦳 +person_white_hair 🧑‍🦳 +bald_woman 👩‍🦲 +person_bald 🧑‍🦲 +blond_haired_woman 👱‍♀️ +blonde_woman 👱‍♀️ +blond_haired_man 👱‍♂️ +older_adult 🧓 +older_man 👴 +older_woman 👵 +frowning_person 🙍 +frowning_man 🙍‍♂️ +frowning_woman 🙍‍♀️ +pouting_face 🙎 +pouting_man 🙎‍♂️ +pouting_woman 🙎‍♀️ +no_good 🙅 +no_good_man 🙅‍♂️ +ng_man 🙅‍♂️ +no_good_woman 🙅‍♀️ +ng_woman 🙅‍♀️ +ok_person 🙆 +ok_man 🙆‍♂️ +ok_woman 🙆‍♀️ +tipping_hand_person 💁 +information_desk_person 💁 +tipping_hand_man 💁‍♂️ +sassy_man 💁‍♂️ +tipping_hand_woman 💁‍♀️ +sassy_woman 💁‍♀️ +raising_hand 🙋 +raising_hand_man 🙋‍♂️ +raising_hand_woman 🙋‍♀️ +deaf_person 🧏 +deaf_man 🧏‍♂️ +deaf_woman 🧏‍♀️ +bow 🙇 +bowing_man 🙇‍♂️ +bowing_woman 🙇‍♀️ +facepalm 🤦 +man_facepalming 🤦‍♂️ +woman_facepalming 🤦‍♀️ +shrug 🤷 +man_shrugging 🤷‍♂️ +woman_shrugging 🤷‍♀️ +health_worker 🧑‍⚕️ +man_health_worker 👨‍⚕️ +woman_health_worker 👩‍⚕️ +student 🧑‍🎓 +man_student 👨‍🎓 +woman_student 👩‍🎓 +teacher 🧑‍🏫 +man_teacher 👨‍🏫 +woman_teacher 👩‍🏫 +judge 🧑‍⚖️ +man_judge 👨‍⚖️ +woman_judge 👩‍⚖️ +farmer 🧑‍🌾 +man_farmer 👨‍🌾 +woman_farmer 👩‍🌾 +cook 🧑‍🍳 +man_cook 👨‍🍳 +woman_cook 👩‍🍳 +mechanic 🧑‍🔧 +man_mechanic 👨‍🔧 +woman_mechanic 👩‍🔧 +factory_worker 🧑‍🏭 +man_factory_worker 👨‍🏭 +woman_factory_worker 👩‍🏭 +office_worker 🧑‍💼 +man_office_worker 👨‍💼 +woman_office_worker 👩‍💼 +scientist 🧑‍🔬 +man_scientist 👨‍🔬 +woman_scientist 👩‍🔬 +technologist 🧑‍💻 +man_technologist 👨‍💻 +woman_technologist 👩‍💻 +singer 🧑‍🎤 +man_singer 👨‍🎤 +woman_singer 👩‍🎤 +artist 🧑‍🎨 +man_artist 👨‍🎨 +woman_artist 👩‍🎨 +pilot 🧑‍✈️ +man_pilot 👨‍✈️ +woman_pilot 👩‍✈️ +astronaut 🧑‍🚀 +man_astronaut 👨‍🚀 +woman_astronaut 👩‍🚀 +firefighter 🧑‍🚒 +man_firefighter 👨‍🚒 +woman_firefighter 👩‍🚒 +police_officer 👮 +cop 👮 +policeman 👮‍♂️ +policewoman 👮‍♀️ +detective 🕵️ +male_detective 🕵️‍♂️ +female_detective 🕵️‍♀️ +guard 💂 +guardsman 💂‍♂️ +guardswoman 💂‍♀️ +ninja 🥷 +construction_worker 👷 +construction_worker_man 👷‍♂️ +construction_worker_woman 👷‍♀️ +person_with_crown 🫅 +prince 🤴 +princess 👸 +person_with_turban 👳 +man_with_turban 👳‍♂️ +woman_with_turban 👳‍♀️ +man_with_gua_pi_mao 👲 +woman_with_headscarf 🧕 +person_in_tuxedo 🤵 +man_in_tuxedo 🤵‍♂️ +woman_in_tuxedo 🤵‍♀️ +person_with_veil 👰 +man_with_veil 👰‍♂️ +woman_with_veil 👰‍♀️ +bride_with_veil 👰‍♀️ +pregnant_woman 🤰 +pregnant_man 🫃 +pregnant_person 🫄 +breast_feeding 🤱 +woman_feeding_baby 👩‍🍼 +man_feeding_baby 👨‍🍼 +person_feeding_baby 🧑‍🍼 +angel 👼 +santa 🎅 +mrs_claus 🤶 +mx_claus 🧑‍🎄 +superhero 🦸 +superhero_man 🦸‍♂️ +superhero_woman 🦸‍♀️ +supervillain 🦹 +supervillain_man 🦹‍♂️ +supervillain_woman 🦹‍♀️ +mage 🧙 +mage_man 🧙‍♂️ +mage_woman 🧙‍♀️ +fairy 🧚 +fairy_man 🧚‍♂️ +fairy_woman 🧚‍♀️ +vampire 🧛 +vampire_man 🧛‍♂️ +vampire_woman 🧛‍♀️ +merperson 🧜 +merman 🧜‍♂️ +mermaid 🧜‍♀️ +elf 🧝 +elf_man 🧝‍♂️ +elf_woman 🧝‍♀️ +genie 🧞 +genie_man 🧞‍♂️ +genie_woman 🧞‍♀️ +zombie 🧟 +zombie_man 🧟‍♂️ +zombie_woman 🧟‍♀️ +troll 🧌 +massage 💆 +massage_man 💆‍♂️ +massage_woman 💆‍♀️ +haircut 💇 +haircut_man 💇‍♂️ +haircut_woman 💇‍♀️ +walking 🚶 +walking_man 🚶‍♂️ +walking_woman 🚶‍♀️ +standing_person 🧍 +standing_man 🧍‍♂️ +standing_woman 🧍‍♀️ +kneeling_person 🧎 +kneeling_man 🧎‍♂️ +kneeling_woman 🧎‍♀️ +person_with_probing_cane 🧑‍🦯 +man_with_probing_cane 👨‍🦯 +woman_with_probing_cane 👩‍🦯 +person_in_motorized_wheelchair 🧑‍🦼 +man_in_motorized_wheelchair 👨‍🦼 +woman_in_motorized_wheelchair 👩‍🦼 +person_in_manual_wheelchair 🧑‍🦽 +man_in_manual_wheelchair 👨‍🦽 +woman_in_manual_wheelchair 👩‍🦽 +runner 🏃 +running 🏃 +running_man 🏃‍♂️ +running_woman 🏃‍♀️ +woman_dancing 💃 +dancer 💃 +man_dancing 🕺 +business_suit_levitating 🕴️ +dancers 👯 +dancing_men 👯‍♂️ +dancing_women 👯‍♀️ +sauna_person 🧖 +sauna_man 🧖‍♂️ +sauna_woman 🧖‍♀️ +climbing 🧗 +climbing_man 🧗‍♂️ +climbing_woman 🧗‍♀️ +person_fencing 🤺 +horse_racing 🏇 +skier ⛷️ +snowboarder 🏂 +golfing 🏌️ +golfing_man 🏌️‍♂️ +golfing_woman 🏌️‍♀️ +surfer 🏄 +surfing_man 🏄‍♂️ +surfing_woman 🏄‍♀️ +rowboat 🚣 +rowing_man 🚣‍♂️ +rowing_woman 🚣‍♀️ +swimmer 🏊 +swimming_man 🏊‍♂️ +swimming_woman 🏊‍♀️ +bouncing_ball_person ⛹️ +bouncing_ball_man ⛹️‍♂️ +basketball_man ⛹️‍♂️ +bouncing_ball_woman ⛹️‍♀️ +basketball_woman ⛹️‍♀️ +weight_lifting 🏋️ +weight_lifting_man 🏋️‍♂️ +weight_lifting_woman 🏋️‍♀️ +bicyclist 🚴 +biking_man 🚴‍♂️ +biking_woman 🚴‍♀️ +mountain_bicyclist 🚵 +mountain_biking_man 🚵‍♂️ +mountain_biking_woman 🚵‍♀️ +cartwheeling 🤸 +man_cartwheeling 🤸‍♂️ +woman_cartwheeling 🤸‍♀️ +wrestling 🤼 +men_wrestling 🤼‍♂️ +women_wrestling 🤼‍♀️ +water_polo 🤽 +man_playing_water_polo 🤽‍♂️ +woman_playing_water_polo 🤽‍♀️ +handball_person 🤾 +man_playing_handball 🤾‍♂️ +woman_playing_handball 🤾‍♀️ +juggling_person 🤹 +man_juggling 🤹‍♂️ +woman_juggling 🤹‍♀️ +lotus_position 🧘 +lotus_position_man 🧘‍♂️ +lotus_position_woman 🧘‍♀️ +bath 🛀 +sleeping_bed 🛌 +people_holding_hands 🧑‍🤝‍🧑 +two_women_holding_hands 👭 +couple 👫 +two_men_holding_hands 👬 +couplekiss 💏 +couplekiss_man_woman 👩‍❤️‍💋‍👨 +couplekiss_man_man 👨‍❤️‍💋‍👨 +couplekiss_woman_woman 👩‍❤️‍💋‍👩 +couple_with_heart 💑 +couple_with_heart_woman_man 👩‍❤️‍👨 +couple_with_heart_man_man 👨‍❤️‍👨 +couple_with_heart_woman_woman 👩‍❤️‍👩 +family 👪 +family_man_woman_boy 👨‍👩‍👦 +family_man_woman_girl 👨‍👩‍👧 +family_man_woman_girl_boy 👨‍👩‍👧‍👦 +family_man_woman_boy_boy 👨‍👩‍👦‍👦 +family_man_woman_girl_girl 👨‍👩‍👧‍👧 +family_man_man_boy 👨‍👨‍👦 +family_man_man_girl 👨‍👨‍👧 +family_man_man_girl_boy 👨‍👨‍👧‍👦 +family_man_man_boy_boy 👨‍👨‍👦‍👦 +family_man_man_girl_girl 👨‍👨‍👧‍👧 +family_woman_woman_boy 👩‍👩‍👦 +family_woman_woman_girl 👩‍👩‍👧 +family_woman_woman_girl_boy 👩‍👩‍👧‍👦 +family_woman_woman_boy_boy 👩‍👩‍👦‍👦 +family_woman_woman_girl_girl 👩‍👩‍👧‍👧 +family_man_boy 👨‍👦 +family_man_boy_boy 👨‍👦‍👦 +family_man_girl 👨‍👧 +family_man_girl_boy 👨‍👧‍👦 +family_man_girl_girl 👨‍👧‍👧 +family_woman_boy 👩‍👦 +family_woman_boy_boy 👩‍👦‍👦 +family_woman_girl 👩‍👧 +family_woman_girl_boy 👩‍👧‍👦 +family_woman_girl_girl 👩‍👧‍👧 +speaking_head 🗣️ +bust_in_silhouette 👤 +busts_in_silhouette 👥 +people_hugging 🫂 +footprints 👣 +monkey_face 🐵 +monkey 🐒 +gorilla 🦍 +orangutan 🦧 +dog 🐶 +dog2 🐕 +guide_dog 🦮 +service_dog 🐕‍🦺 +poodle 🐩 +wolf 🐺 +fox_face 🦊 +raccoon 🦝 +cat 🐱 +cat2 🐈 +black_cat 🐈‍⬛ +lion 🦁 +tiger 🐯 +tiger2 🐅 +leopard 🐆 +horse 🐴 +moose 🫎 +donkey 🫏 +racehorse 🐎 +unicorn 🦄 +zebra 🦓 +deer 🦌 +bison 🦬 +cow 🐮 +ox 🐂 +water_buffalo 🐃 +cow2 🐄 +pig 🐷 +pig2 🐖 +boar 🐗 +pig_nose 🐽 +ram 🐏 +sheep 🐑 +goat 🐐 +dromedary_camel 🐪 +camel 🐫 +llama 🦙 +giraffe 🦒 +elephant 🐘 +mammoth 🦣 +rhinoceros 🦏 +hippopotamus 🦛 +mouse 🐭 +mouse2 🐁 +rat 🐀 +hamster 🐹 +rabbit 🐰 +rabbit2 🐇 +chipmunk 🐿️ +beaver 🦫 +hedgehog 🦔 +bat 🦇 +bear 🐻 +polar_bear 🐻‍❄️ +koala 🐨 +panda_face 🐼 +sloth 🦥 +otter 🦦 +skunk 🦨 +kangaroo 🦘 +badger 🦡 +feet 🐾 +paw_prints 🐾 +turkey 🦃 +chicken 🐔 +rooster 🐓 +hatching_chick 🐣 +baby_chick 🐤 +hatched_chick 🐥 +bird 🐦 +penguin 🐧 +dove 🕊️ +eagle 🦅 +duck 🦆 +swan 🦢 +owl 🦉 +dodo 🦤 +feather 🪶 +flamingo 🦩 +peacock 🦚 +parrot 🦜 +wing 🪽 +black_bird 🐦‍⬛ +goose 🪿 +frog 🐸 +crocodile 🐊 +turtle 🐢 +lizard 🦎 +snake 🐍 +dragon_face 🐲 +dragon 🐉 +sauropod 🦕 +t-rex 🦖 +whale 🐳 +whale2 🐋 +dolphin 🐬 +flipper 🐬 +seal 🦭 +fish 🐟 +tropical_fish 🐠 +blowfish 🐡 +shark 🦈 +octopus 🐙 +shell 🐚 +coral 🪸 +jellyfish 🪼 +snail 🐌 +butterfly 🦋 +bug 🐛 +ant 🐜 +bee 🐝 +honeybee 🐝 +beetle 🪲 +lady_beetle 🐞 +cricket 🦗 +cockroach 🪳 +spider 🕷️ +spider_web 🕸️ +scorpion 🦂 +mosquito 🦟 +fly 🪰 +worm 🪱 +microbe 🦠 +bouquet 💐 +cherry_blossom 🌸 +white_flower 💮 +lotus 🪷 +rosette 🏵️ +rose 🌹 +wilted_flower 🥀 +hibiscus 🌺 +sunflower 🌻 +blossom 🌼 +tulip 🌷 +hyacinth 🪻 +seedling 🌱 +potted_plant 🪴 +evergreen_tree 🌲 +deciduous_tree 🌳 +palm_tree 🌴 +cactus 🌵 +ear_of_rice 🌾 +herb 🌿 +shamrock ☘️ +four_leaf_clover 🍀 +maple_leaf 🍁 +fallen_leaf 🍂 +leaves 🍃 +empty_nest 🪹 +nest_with_eggs 🪺 +mushroom 🍄 +grapes 🍇 +melon 🍈 +watermelon 🍉 +tangerine 🍊 +orange 🍊 +mandarin 🍊 +lemon 🍋 +banana 🍌 +pineapple 🍍 +mango 🥭 +apple 🍎 +green_apple 🍏 +pear 🍐 +peach 🍑 +cherries 🍒 +strawberry 🍓 +blueberries 🫐 +kiwi_fruit 🥝 +tomato 🍅 +olive 🫒 +coconut 🥥 +avocado 🥑 +eggplant 🍆 +potato 🥔 +carrot 🥕 +corn 🌽 +hot_pepper 🌶️ +bell_pepper 🫑 +cucumber 🥒 +leafy_green 🥬 +broccoli 🥦 +garlic 🧄 +onion 🧅 +peanuts 🥜 +beans 🫘 +chestnut 🌰 +ginger_root 🫚 +pea_pod 🫛 +bread 🍞 +croissant 🥐 +baguette_bread 🥖 +flatbread 🫓 +pretzel 🥨 +bagel 🥯 +pancakes 🥞 +waffle 🧇 +cheese 🧀 +meat_on_bone 🍖 +poultry_leg 🍗 +cut_of_meat 🥩 +bacon 🥓 +hamburger 🍔 +fries 🍟 +pizza 🍕 +hotdog 🌭 +sandwich 🥪 +taco 🌮 +burrito 🌯 +tamale 🫔 +stuffed_flatbread 🥙 +falafel 🧆 +egg 🥚 +fried_egg 🍳 +shallow_pan_of_food 🥘 +stew 🍲 +fondue 🫕 +bowl_with_spoon 🥣 +green_salad 🥗 +popcorn 🍿 +butter 🧈 +salt 🧂 +canned_food 🥫 +bento 🍱 +rice_cracker 🍘 +rice_ball 🍙 +rice 🍚 +curry 🍛 +ramen 🍜 +spaghetti 🍝 +sweet_potato 🍠 +oden 🍢 +sushi 🍣 +fried_shrimp 🍤 +fish_cake 🍥 +moon_cake 🥮 +dango 🍡 +dumpling 🥟 +fortune_cookie 🥠 +takeout_box 🥡 +crab 🦀 +lobster 🦞 +shrimp 🦐 +squid 🦑 +oyster 🦪 +icecream 🍦 +shaved_ice 🍧 +ice_cream 🍨 +doughnut 🍩 +cookie 🍪 +birthday 🎂 +cake 🍰 +cupcake 🧁 +pie 🥧 +chocolate_bar 🍫 +candy 🍬 +lollipop 🍭 +custard 🍮 +honey_pot 🍯 +baby_bottle 🍼 +milk_glass 🥛 +coffee ☕ +teapot 🫖 +tea 🍵 +sake 🍶 +champagne 🍾 +wine_glass 🍷 +cocktail 🍸 +tropical_drink 🍹 +beer 🍺 +beers 🍻 +clinking_glasses 🥂 +tumbler_glass 🥃 +pouring_liquid 🫗 +cup_with_straw 🥤 +bubble_tea 🧋 +beverage_box 🧃 +mate 🧉 +ice_cube 🧊 +chopsticks 🥢 +plate_with_cutlery 🍽️ +fork_and_knife 🍴 +spoon 🥄 +hocho 🔪 +knife 🔪 +jar 🫙 +amphora 🏺 +earth_africa 🌍 +earth_americas 🌎 +earth_asia 🌏 +globe_with_meridians 🌐 +world_map 🗺️ +japan 🗾 +compass 🧭 +mountain_snow 🏔️ +mountain ⛰️ +volcano 🌋 +mount_fuji 🗻 +camping 🏕️ +beach_umbrella 🏖️ +desert 🏜️ +desert_island 🏝️ +national_park 🏞️ +stadium 🏟️ +classical_building 🏛️ +building_construction 🏗️ +bricks 🧱 +rock 🪨 +wood 🪵 +hut 🛖 +houses 🏘️ +derelict_house 🏚️ +house 🏠 +house_with_garden 🏡 +office 🏢 +post_office 🏣 +european_post_office 🏤 +hospital 🏥 +bank 🏦 +hotel 🏨 +love_hotel 🏩 +convenience_store 🏪 +school 🏫 +department_store 🏬 +factory 🏭 +japanese_castle 🏯 +european_castle 🏰 +wedding 💒 +tokyo_tower 🗼 +statue_of_liberty 🗽 +church ⛪ +mosque 🕌 +hindu_temple 🛕 +synagogue 🕍 +shinto_shrine ⛩️ +kaaba 🕋 +fountain ⛲ +tent ⛺ +foggy 🌁 +night_with_stars 🌃 +cityscape 🏙️ +sunrise_over_mountains 🌄 +sunrise 🌅 +city_sunset 🌆 +city_sunrise 🌇 +bridge_at_night 🌉 +hotsprings ♨️ +carousel_horse 🎠 +playground_slide 🛝 +ferris_wheel 🎡 +roller_coaster 🎢 +barber 💈 +circus_tent 🎪 +steam_locomotive 🚂 +railway_car 🚃 +bullettrain_side 🚄 +bullettrain_front 🚅 +train2 🚆 +metro 🚇 +light_rail 🚈 +station 🚉 +tram 🚊 +monorail 🚝 +mountain_railway 🚞 +train 🚋 +bus 🚌 +oncoming_bus 🚍 +trolleybus 🚎 +minibus 🚐 +ambulance 🚑 +fire_engine 🚒 +police_car 🚓 +oncoming_police_car 🚔 +taxi 🚕 +oncoming_taxi 🚖 +car 🚗 +red_car 🚗 +oncoming_automobile 🚘 +blue_car 🚙 +pickup_truck 🛻 +truck 🚚 +articulated_lorry 🚛 +tractor 🚜 +racing_car 🏎️ +motorcycle 🏍️ +motor_scooter 🛵 +manual_wheelchair 🦽 +motorized_wheelchair 🦼 +auto_rickshaw 🛺 +bike 🚲 +kick_scooter 🛴 +skateboard 🛹 +roller_skate 🛼 +busstop 🚏 +motorway 🛣️ +railway_track 🛤️ +oil_drum 🛢️ +fuelpump ⛽ +wheel 🛞 +rotating_light 🚨 +traffic_light 🚥 +vertical_traffic_light 🚦 +stop_sign 🛑 +construction 🚧 +anchor ⚓ +ring_buoy 🛟 +boat ⛵ +sailboat ⛵ +canoe 🛶 +speedboat 🚤 +passenger_ship 🛳️ +ferry ⛴️ +motor_boat 🛥️ +ship 🚢 +airplane ✈️ +small_airplane 🛩️ +flight_departure 🛫 +flight_arrival 🛬 +parachute 🪂 +seat 💺 +helicopter 🚁 +suspension_railway 🚟 +mountain_cableway 🚠 +aerial_tramway 🚡 +artificial_satellite 🛰️ +rocket 🚀 +flying_saucer 🛸 +bellhop_bell 🛎️ +luggage 🧳 +hourglass ⌛ +hourglass_flowing_sand ⏳ +watch ⌚ +alarm_clock ⏰ +stopwatch ⏱️ +timer_clock ⏲️ +mantelpiece_clock 🕰️ +clock12 🕛 +clock1230 🕧 +clock1 🕐 +clock130 🕜 +clock2 🕑 +clock230 🕝 +clock3 🕒 +clock330 🕞 +clock4 🕓 +clock430 🕟 +clock5 🕔 +clock530 🕠 +clock6 🕕 +clock630 🕡 +clock7 🕖 +clock730 🕢 +clock8 🕗 +clock830 🕣 +clock9 🕘 +clock930 🕤 +clock10 🕙 +clock1030 🕥 +clock11 🕚 +clock1130 🕦 +new_moon 🌑 +waxing_crescent_moon 🌒 +first_quarter_moon 🌓 +moon 🌔 +waxing_gibbous_moon 🌔 +full_moon 🌕 +waning_gibbous_moon 🌖 +last_quarter_moon 🌗 +waning_crescent_moon 🌘 +crescent_moon 🌙 +new_moon_with_face 🌚 +first_quarter_moon_with_face 🌛 +last_quarter_moon_with_face 🌜 +thermometer 🌡️ +sunny ☀️ +full_moon_with_face 🌝 +sun_with_face 🌞 +ringed_planet 🪐 +star ⭐ +star2 🌟 +stars 🌠 +milky_way 🌌 +cloud ☁️ +partly_sunny ⛅ +cloud_with_lightning_and_rain ⛈️ +sun_behind_small_cloud 🌤️ +sun_behind_large_cloud 🌥️ +sun_behind_rain_cloud 🌦️ +cloud_with_rain 🌧️ +cloud_with_snow 🌨️ +cloud_with_lightning 🌩️ +tornado 🌪️ +fog 🌫️ +wind_face 🌬️ +cyclone 🌀 +rainbow 🌈 +closed_umbrella 🌂 +open_umbrella ☂️ +umbrella ☔ +parasol_on_ground ⛱️ +zap ⚡ +snowflake ❄️ +snowman_with_snow ☃️ +snowman ⛄ +comet ☄️ +fire 🔥 +droplet 💧 +ocean 🌊 +jack_o_lantern 🎃 +christmas_tree 🎄 +fireworks 🎆 +sparkler 🎇 +firecracker 🧨 +sparkles ✨ +balloon 🎈 +tada 🎉 +confetti_ball 🎊 +tanabata_tree 🎋 +bamboo 🎍 +dolls 🎎 +flags 🎏 +wind_chime 🎐 +rice_scene 🎑 +red_envelope 🧧 +ribbon 🎀 +gift 🎁 +reminder_ribbon 🎗️ +tickets 🎟️ +ticket 🎫 +medal_military 🎖️ +trophy 🏆 +medal_sports 🏅 +1st_place_medal 🥇 +2nd_place_medal 🥈 +3rd_place_medal 🥉 +soccer ⚽ +baseball ⚾ +softball 🥎 +basketball 🏀 +volleyball 🏐 +football 🏈 +rugby_football 🏉 +tennis 🎾 +flying_disc 🥏 +bowling 🎳 +cricket_game 🏏 +field_hockey 🏑 +ice_hockey 🏒 +lacrosse 🥍 +ping_pong 🏓 +badminton 🏸 +boxing_glove 🥊 +martial_arts_uniform 🥋 +goal_net 🥅 +golf ⛳ +ice_skate ⛸️ +fishing_pole_and_fish 🎣 +diving_mask 🤿 +running_shirt_with_sash 🎽 +ski 🎿 +sled 🛷 +curling_stone 🥌 +dart 🎯 +yo_yo 🪀 +kite 🪁 +gun 🔫 +8ball 🎱 +crystal_ball 🔮 +magic_wand 🪄 +video_game 🎮 +joystick 🕹️ +slot_machine 🎰 +game_die 🎲 +jigsaw 🧩 +teddy_bear 🧸 +pinata 🪅 +mirror_ball 🪩 +nesting_dolls 🪆 +spades ♠️ +hearts ♥️ +diamonds ♦️ +clubs ♣️ +chess_pawn ♟️ +black_joker 🃏 +mahjong 🀄 +flower_playing_cards 🎴 +performing_arts 🎭 +framed_picture 🖼️ +art 🎨 +thread 🧵 +sewing_needle 🪡 +yarn 🧶 +knot 🪢 +eyeglasses 👓 +dark_sunglasses 🕶️ +goggles 🥽 +lab_coat 🥼 +safety_vest 🦺 +necktie 👔 +shirt 👕 +tshirt 👕 +jeans 👖 +scarf 🧣 +gloves 🧤 +coat 🧥 +socks 🧦 +dress 👗 +kimono 👘 +sari 🥻 +one_piece_swimsuit 🩱 +swim_brief 🩲 +shorts 🩳 +bikini 👙 +womans_clothes 👚 +folding_hand_fan 🪭 +purse 👛 +handbag 👜 +pouch 👝 +shopping 🛍️ +school_satchel 🎒 +thong_sandal 🩴 +mans_shoe 👞 +shoe 👞 +athletic_shoe 👟 +hiking_boot 🥾 +flat_shoe 🥿 +high_heel 👠 +sandal 👡 +ballet_shoes 🩰 +boot 👢 +hair_pick 🪮 +crown 👑 +womans_hat 👒 +tophat 🎩 +mortar_board 🎓 +billed_cap 🧢 +military_helmet 🪖 +rescue_worker_helmet ⛑️ +prayer_beads 📿 +lipstick 💄 +ring 💍 +gem 💎 +mute 🔇 +speaker 🔈 +sound 🔉 +loud_sound 🔊 +loudspeaker 📢 +mega 📣 +postal_horn 📯 +bell 🔔 +no_bell 🔕 +musical_score 🎼 +musical_note 🎵 +notes 🎶 +studio_microphone 🎙️ +level_slider 🎚️ +control_knobs 🎛️ +microphone 🎤 +headphones 🎧 +radio 📻 +saxophone 🎷 +accordion 🪗 +guitar 🎸 +musical_keyboard 🎹 +trumpet 🎺 +violin 🎻 +banjo 🪕 +drum 🥁 +long_drum 🪘 +maracas 🪇 +flute 🪈 +iphone 📱 +calling 📲 +phone ☎️ +telephone ☎️ +telephone_receiver 📞 +pager 📟 +fax 📠 +battery 🔋 +low_battery 🪫 +electric_plug 🔌 +computer 💻 +desktop_computer 🖥️ +printer 🖨️ +keyboard ⌨️ +computer_mouse 🖱️ +trackball 🖲️ +minidisc 💽 +floppy_disk 💾 +cd 💿 +dvd 📀 +abacus 🧮 +movie_camera 🎥 +film_strip 🎞️ +film_projector 📽️ +clapper 🎬 +tv 📺 +camera 📷 +camera_flash 📸 +video_camera 📹 +vhs 📼 +mag 🔍 +mag_right 🔎 +candle 🕯️ +bulb 💡 +flashlight 🔦 +izakaya_lantern 🏮 +lantern 🏮 +diya_lamp 🪔 +notebook_with_decorative_cover 📔 +closed_book 📕 +book 📖 +open_book 📖 +green_book 📗 +blue_book 📘 +orange_book 📙 +books 📚 +notebook 📓 +ledger 📒 +page_with_curl 📃 +scroll 📜 +page_facing_up 📄 +newspaper 📰 +newspaper_roll 🗞️ +bookmark_tabs 📑 +bookmark 🔖 +label 🏷️ +moneybag 💰 +coin 🪙 +yen 💴 +dollar 💵 +euro 💶 +pound 💷 +money_with_wings 💸 +credit_card 💳 +receipt 🧾 +chart 💹 +envelope ✉️ +email 📧 +e-mail 📧 +incoming_envelope 📨 +envelope_with_arrow 📩 +outbox_tray 📤 +inbox_tray 📥 +package 📦 +mailbox 📫 +mailbox_closed 📪 +mailbox_with_mail 📬 +mailbox_with_no_mail 📭 +postbox 📮 +ballot_box 🗳️ +pencil2 ✏️ +black_nib ✒️ +fountain_pen 🖋️ +pen 🖊️ +paintbrush 🖌️ +crayon 🖍️ +memo 📝 +pencil 📝 +briefcase 💼 +file_folder 📁 +open_file_folder 📂 +card_index_dividers 🗂️ +date 📅 +calendar 📆 +spiral_notepad 🗒️ +spiral_calendar 🗓️ +card_index 📇 +chart_with_upwards_trend 📈 +chart_with_downwards_trend 📉 +bar_chart 📊 +clipboard 📋 +pushpin 📌 +round_pushpin 📍 +paperclip 📎 +paperclips 🖇️ +straight_ruler 📏 +triangular_ruler 📐 +scissors ✂️ +card_file_box 🗃️ +file_cabinet 🗄️ +wastebasket 🗑️ +lock 🔒 +unlock 🔓 +lock_with_ink_pen 🔏 +closed_lock_with_key 🔐 +key 🔑 +old_key 🗝️ +hammer 🔨 +axe 🪓 +pick ⛏️ +hammer_and_pick ⚒️ +hammer_and_wrench 🛠️ +dagger 🗡️ +crossed_swords ⚔️ +bomb 💣 +boomerang 🪃 +bow_and_arrow 🏹 +shield 🛡️ +carpentry_saw 🪚 +wrench 🔧 +screwdriver 🪛 +nut_and_bolt 🔩 +gear ⚙️ +clamp 🗜️ +balance_scale ⚖️ +probing_cane 🦯 +link 🔗 +chains ⛓️ +hook 🪝 +toolbox 🧰 +magnet 🧲 +ladder 🪜 +alembic ⚗️ +test_tube 🧪 +petri_dish 🧫 +dna 🧬 +microscope 🔬 +telescope 🔭 +satellite 📡 +syringe 💉 +drop_of_blood 🩸 +pill 💊 +adhesive_bandage 🩹 +crutch 🩼 +stethoscope 🩺 +x_ray 🩻 +door 🚪 +elevator 🛗 +mirror 🪞 +window 🪟 +bed 🛏️ +couch_and_lamp 🛋️ +chair 🪑 +toilet 🚽 +plunger 🪠 +shower 🚿 +bathtub 🛁 +mouse_trap 🪤 +razor 🪒 +lotion_bottle 🧴 +safety_pin 🧷 +broom 🧹 +basket 🧺 +roll_of_paper 🧻 +bucket 🪣 +soap 🧼 +bubbles 🫧 +toothbrush 🪥 +sponge 🧽 +fire_extinguisher 🧯 +shopping_cart 🛒 +smoking 🚬 +coffin ⚰️ +headstone 🪦 +funeral_urn ⚱️ +nazar_amulet 🧿 +hamsa 🪬 +moyai 🗿 +placard 🪧 +identification_card 🪪 +atm 🏧 +put_litter_in_its_place 🚮 +potable_water 🚰 +wheelchair ♿ +mens 🚹 +womens 🚺 +restroom 🚻 +baby_symbol 🚼 +wc 🚾 +passport_control 🛂 +customs 🛃 +baggage_claim 🛄 +left_luggage 🛅 +warning ⚠️ +children_crossing 🚸 +no_entry ⛔ +no_entry_sign 🚫 +no_bicycles 🚳 +no_smoking 🚭 +do_not_litter 🚯 +non-potable_water 🚱 +no_pedestrians 🚷 +no_mobile_phones 📵 +underage 🔞 +radioactive ☢️ +biohazard ☣️ +arrow_up ⬆️ +arrow_upper_right ↗️ +arrow_right ➡️ +arrow_lower_right ↘️ +arrow_down ⬇️ +arrow_lower_left ↙️ +arrow_left ⬅️ +arrow_upper_left ↖️ +arrow_up_down ↕️ +left_right_arrow ↔️ +leftwards_arrow_with_hook ↩️ +arrow_right_hook ↪️ +arrow_heading_up ⤴️ +arrow_heading_down ⤵️ +arrows_clockwise 🔃 +arrows_counterclockwise 🔄 +back 🔙 +end 🔚 +on 🔛 +soon 🔜 +top 🔝 +place_of_worship 🛐 +atom_symbol ⚛️ +om 🕉️ +star_of_david ✡️ +wheel_of_dharma ☸️ +yin_yang ☯️ +latin_cross ✝️ +orthodox_cross ☦️ +star_and_crescent ☪️ +peace_symbol ☮️ +menorah 🕎 +six_pointed_star 🔯 +khanda 🪯 +aries ♈ +taurus ♉ +gemini ♊ +cancer ♋ +leo ♌ +virgo ♍ +libra ♎ +scorpius ♏ +sagittarius ♐ +capricorn ♑ +aquarius ♒ +pisces ♓ +ophiuchus ⛎ +twisted_rightwards_arrows 🔀 +repeat 🔁 +repeat_one 🔂 +arrow_forward ▶️ +fast_forward ⏩ +next_track_button ⏭️ +play_or_pause_button ⏯️ +arrow_backward ◀️ +rewind ⏪ +previous_track_button ⏮️ +arrow_up_small 🔼 +arrow_double_up ⏫ +arrow_down_small 🔽 +arrow_double_down ⏬ +pause_button ⏸️ +stop_button ⏹️ +record_button ⏺️ +eject_button ⏏️ +cinema 🎦 +low_brightness 🔅 +high_brightness 🔆 +signal_strength 📶 +wireless 🛜 +vibration_mode 📳 +mobile_phone_off 📴 +female_sign ♀️ +male_sign ♂️ +transgender_symbol ⚧️ +heavy_multiplication_x ✖️ +heavy_plus_sign ➕ +heavy_minus_sign ➖ +heavy_division_sign ➗ +heavy_equals_sign 🟰 +infinity ♾️ +bangbang ‼️ +interrobang ⁉️ +question ❓ +grey_question ❔ +grey_exclamation ❕ +exclamation ❗ +heavy_exclamation_mark ❗ +wavy_dash 〰️ +currency_exchange 💱 +heavy_dollar_sign 💲 +medical_symbol ⚕️ +recycle ♻️ +fleur_de_lis ⚜️ +trident 🔱 +name_badge 📛 +beginner 🔰 +o ⭕ +white_check_mark ✅ +ballot_box_with_check ☑️ +heavy_check_mark ✔️ +x ❌ +negative_squared_cross_mark ❎ +curly_loop ➰ +loop ➿ +part_alternation_mark 〽️ +eight_spoked_asterisk ✳️ +eight_pointed_black_star ✴️ +sparkle ❇️ +copyright ©️ +registered ®️ +tm ™️ +hash #️⃣ +asterisk *️⃣ +zero 0️⃣ +one 1️⃣ +two 2️⃣ +three 3️⃣ +four 4️⃣ +five 5️⃣ +six 6️⃣ +seven 7️⃣ +eight 8️⃣ +nine 9️⃣ +keycap_ten 🔟 +capital_abcd 🔠 +abcd 🔡 +1234 🔢 +symbols 🔣 +abc 🔤 +a 🅰️ +ab 🆎 +b 🅱️ +cl 🆑 +cool 🆒 +free 🆓 +information_source ℹ️ +id 🆔 +m Ⓜ️ +new 🆕 +ng 🆖 +o2 🅾️ +ok 🆗 +parking 🅿️ +sos 🆘 +up 🆙 +vs 🆚 +koko 🈁 +sa 🈂️ +u6708 🈷️ +u6709 🈶 +u6307 🈯 +ideograph_advantage 🉐 +u5272 🈹 +u7121 🈚 +u7981 🈲 +accept 🉑 +u7533 🈸 +u5408 🈴 +u7a7a 🈳 +congratulations ㊗️ +secret ㊙️ +u55b6 🈺 +u6e80 🈵 +red_circle 🔴 +orange_circle 🟠 +yellow_circle 🟡 +green_circle 🟢 +large_blue_circle 🔵 +purple_circle 🟣 +brown_circle 🟤 +black_circle ⚫ +white_circle ⚪ +red_square 🟥 +orange_square 🟧 +yellow_square 🟨 +green_square 🟩 +blue_square 🟦 +purple_square 🟪 +brown_square 🟫 +black_large_square ⬛ +white_large_square ⬜ +black_medium_square ◼️ +white_medium_square ◻️ +black_medium_small_square ◾ +white_medium_small_square ◽ +black_small_square ▪️ +white_small_square ▫️ +large_orange_diamond 🔶 +large_blue_diamond 🔷 +small_orange_diamond 🔸 +small_blue_diamond 🔹 +small_red_triangle 🔺 +small_red_triangle_down 🔻 +diamond_shape_with_a_dot_inside 💠 +radio_button 🔘 +white_square_button 🔳 +black_square_button 🔲 +checkered_flag 🏁 +triangular_flag_on_post 🚩 +crossed_flags 🎌 +black_flag 🏴 +white_flag 🏳️ +rainbow_flag 🏳️‍🌈 +transgender_flag 🏳️‍⚧️ +pirate_flag 🏴‍☠️ +ascension_island 🇦🇨 +andorra 🇦🇩 +united_arab_emirates 🇦🇪 +afghanistan 🇦🇫 +antigua_barbuda 🇦🇬 +anguilla 🇦🇮 +albania 🇦🇱 +armenia 🇦🇲 +angola 🇦🇴 +antarctica 🇦🇶 +argentina 🇦🇷 +american_samoa 🇦🇸 +austria 🇦🇹 +australia 🇦🇺 +aruba 🇦🇼 +aland_islands 🇦🇽 +azerbaijan 🇦🇿 +bosnia_herzegovina 🇧🇦 +barbados 🇧🇧 +bangladesh 🇧🇩 +belgium 🇧🇪 +burkina_faso 🇧🇫 +bulgaria 🇧🇬 +bahrain 🇧🇭 +burundi 🇧🇮 +benin 🇧🇯 +st_barthelemy 🇧🇱 +bermuda 🇧🇲 +brunei 🇧🇳 +bolivia 🇧🇴 +caribbean_netherlands 🇧🇶 +brazil 🇧🇷 +bahamas 🇧🇸 +bhutan 🇧🇹 +bouvet_island 🇧🇻 +botswana 🇧🇼 +belarus 🇧🇾 +belize 🇧🇿 +canada 🇨🇦 +cocos_islands 🇨🇨 +congo_kinshasa 🇨🇩 +central_african_republic 🇨🇫 +congo_brazzaville 🇨🇬 +switzerland 🇨🇭 +cote_divoire 🇨🇮 +cook_islands 🇨🇰 +chile 🇨🇱 +cameroon 🇨🇲 +cn 🇨🇳 +colombia 🇨🇴 +clipperton_island 🇨🇵 +costa_rica 🇨🇷 +cuba 🇨🇺 +cape_verde 🇨🇻 +curacao 🇨🇼 +christmas_island 🇨🇽 +cyprus 🇨🇾 +czech_republic 🇨🇿 +de 🇩🇪 +diego_garcia 🇩🇬 +djibouti 🇩🇯 +denmark 🇩🇰 +dominica 🇩🇲 +dominican_republic 🇩🇴 +algeria 🇩🇿 +ceuta_melilla 🇪🇦 +ecuador 🇪🇨 +estonia 🇪🇪 +egypt 🇪🇬 +western_sahara 🇪🇭 +eritrea 🇪🇷 +es 🇪🇸 +ethiopia 🇪🇹 +eu 🇪🇺 +european_union 🇪🇺 +finland 🇫🇮 +fiji 🇫🇯 +falkland_islands 🇫🇰 +micronesia 🇫🇲 +faroe_islands 🇫🇴 +fr 🇫🇷 +gabon 🇬🇦 +gb 🇬🇧 +uk 🇬🇧 +grenada 🇬🇩 +georgia 🇬🇪 +french_guiana 🇬🇫 +guernsey 🇬🇬 +ghana 🇬🇭 +gibraltar 🇬🇮 +greenland 🇬🇱 +gambia 🇬🇲 +guinea 🇬🇳 +guadeloupe 🇬🇵 +equatorial_guinea 🇬🇶 +greece 🇬🇷 +south_georgia_south_sandwich_islands 🇬🇸 +guatemala 🇬🇹 +guam 🇬🇺 +guinea_bissau 🇬🇼 +guyana 🇬🇾 +hong_kong 🇭🇰 +heard_mcdonald_islands 🇭🇲 +honduras 🇭🇳 +croatia 🇭🇷 +haiti 🇭🇹 +hungary 🇭🇺 +canary_islands 🇮🇨 +indonesia 🇮🇩 +ireland 🇮🇪 +israel 🇮🇱 +isle_of_man 🇮🇲 +india 🇮🇳 +british_indian_ocean_territory 🇮🇴 +iraq 🇮🇶 +iran 🇮🇷 +iceland 🇮🇸 +it 🇮🇹 +jersey 🇯🇪 +jamaica 🇯🇲 +jordan 🇯🇴 +jp 🇯🇵 +kenya 🇰🇪 +kyrgyzstan 🇰🇬 +cambodia 🇰🇭 +kiribati 🇰🇮 +comoros 🇰🇲 +st_kitts_nevis 🇰🇳 +north_korea 🇰🇵 +kr 🇰🇷 +kuwait 🇰🇼 +cayman_islands 🇰🇾 +kazakhstan 🇰🇿 +laos 🇱🇦 +lebanon 🇱🇧 +st_lucia 🇱🇨 +liechtenstein 🇱🇮 +sri_lanka 🇱🇰 +liberia 🇱🇷 +lesotho 🇱🇸 +lithuania 🇱🇹 +luxembourg 🇱🇺 +latvia 🇱🇻 +libya 🇱🇾 +morocco 🇲🇦 +monaco 🇲🇨 +moldova 🇲🇩 +montenegro 🇲🇪 +st_martin 🇲🇫 +madagascar 🇲🇬 +marshall_islands 🇲🇭 +macedonia 🇲🇰 +mali 🇲🇱 +myanmar 🇲🇲 +mongolia 🇲🇳 +macau 🇲🇴 +northern_mariana_islands 🇲🇵 +martinique 🇲🇶 +mauritania 🇲🇷 +montserrat 🇲🇸 +malta 🇲🇹 +mauritius 🇲🇺 +maldives 🇲🇻 +malawi 🇲🇼 +mexico 🇲🇽 +malaysia 🇲🇾 +mozambique 🇲🇿 +namibia 🇳🇦 +new_caledonia 🇳🇨 +niger 🇳🇪 +norfolk_island 🇳🇫 +nigeria 🇳🇬 +nicaragua 🇳🇮 +netherlands 🇳🇱 +norway 🇳🇴 +nepal 🇳🇵 +nauru 🇳🇷 +niue 🇳🇺 +new_zealand 🇳🇿 +oman 🇴🇲 +panama 🇵🇦 +peru 🇵🇪 +french_polynesia 🇵🇫 +papua_new_guinea 🇵🇬 +philippines 🇵🇭 +pakistan 🇵🇰 +poland 🇵🇱 +st_pierre_miquelon 🇵🇲 +pitcairn_islands 🇵🇳 +puerto_rico 🇵🇷 +palestinian_territories 🇵🇸 +portugal 🇵🇹 +palau 🇵🇼 +paraguay 🇵🇾 +qatar 🇶🇦 +reunion 🇷🇪 +romania 🇷🇴 +serbia 🇷🇸 +ru 🇷🇺 +rwanda 🇷🇼 +saudi_arabia 🇸🇦 +solomon_islands 🇸🇧 +seychelles 🇸🇨 +sudan 🇸🇩 +sweden 🇸🇪 +singapore 🇸🇬 +st_helena 🇸🇭 +slovenia 🇸🇮 +svalbard_jan_mayen 🇸🇯 +slovakia 🇸🇰 +sierra_leone 🇸🇱 +san_marino 🇸🇲 +senegal 🇸🇳 +somalia 🇸🇴 +suriname 🇸🇷 +south_sudan 🇸🇸 +sao_tome_principe 🇸🇹 +el_salvador 🇸🇻 +sint_maarten 🇸🇽 +syria 🇸🇾 +swaziland 🇸🇿 +tristan_da_cunha 🇹🇦 +turks_caicos_islands 🇹🇨 +chad 🇹🇩 +french_southern_territories 🇹🇫 +togo 🇹🇬 +thailand 🇹🇭 +tajikistan 🇹🇯 +tokelau 🇹🇰 +timor_leste 🇹🇱 +turkmenistan 🇹🇲 +tunisia 🇹🇳 +tonga 🇹🇴 +tr 🇹🇷 +trinidad_tobago 🇹🇹 +tuvalu 🇹🇻 +taiwan 🇹🇼 +tanzania 🇹🇿 +ukraine 🇺🇦 +uganda 🇺🇬 +us_outlying_islands 🇺🇲 +united_nations 🇺🇳 +us 🇺🇸 +uruguay 🇺🇾 +uzbekistan 🇺🇿 +vatican_city 🇻🇦 +st_vincent_grenadines 🇻🇨 +venezuela 🇻🇪 +british_virgin_islands 🇻🇬 +us_virgin_islands 🇻🇮 +vietnam 🇻🇳 +vanuatu 🇻🇺 +wallis_futuna 🇼🇫 +samoa 🇼🇸 +kosovo 🇽🇰 +yemen 🇾🇪 +mayotte 🇾🇹 +south_africa 🇿🇦 +zambia 🇿🇲 +zimbabwe 🇿🇼 +england 🏴󠁧󠁢󠁥󠁮󠁧󠁿 +scotland 🏴󠁧󠁢󠁳󠁣󠁴󠁿 +wales 🏴󠁧󠁢󠁷󠁬󠁳󠁿 +`; diff --git a/packages/client-runtime/src/pullRequestMarkdown.ts b/packages/client-runtime/src/pullRequestMarkdown.ts index 8ad710325a50c..688235c544fdb 100644 --- a/packages/client-runtime/src/pullRequestMarkdown.ts +++ b/packages/client-runtime/src/pullRequestMarkdown.ts @@ -3,6 +3,7 @@ import remarkGfm from "remark-gfm"; import remarkParse from "remark-parse"; import { unified } from "unified"; +import { GITHUB_EMOJI_ALIASES } from "./githubEmojiAliases.ts"; import { sourceControlClients, type ReferenceAutolink } from "./sourceControlClients.ts"; /** `id` is positional on purpose: the same attachment can be embedded twice in one body. */ @@ -369,3 +370,39 @@ export function resolveChangeRequestMediaUrl(url: string, changeRequestUrl: stri return url; } } + +let githubEmojiByAlias: ReadonlyMap | undefined; +const githubEmojiAlias = /:([a-z\d_+-]+)(?=:)/gu; + +/** GitHub's `:alias:` emoji in `text`; a colon closes one alias only, so `:tada:tada:` has one. */ +export function githubEmojiAliases( + text: string, +): ReadonlyArray<{ readonly index: number; readonly text: string; readonly emoji: string }> { + githubEmojiByAlias ??= new Map( + GITHUB_EMOJI_ALIASES.trim() + .split("\n") + .map((line) => { + const space = line.indexOf(" "); + return [line.slice(0, space), line.slice(space + 1)] as const; + }), + ); + const found: { index: number; text: string; emoji: string }[] = []; + let end = 0; + for (const match of text.matchAll(githubEmojiAlias)) { + const emoji = githubEmojiByAlias.get(match[1]!); + if (emoji === undefined || match.index < end) continue; + end = match.index + match[0].length + 1; + found.push({ index: match.index, text: `${match[0]}:`, emoji }); + } + return found; +} + +export function expandGithubEmojiAliases(text: string): string { + let expanded = ""; + let start = 0; + for (const alias of githubEmojiAliases(text)) { + expanded += text.slice(start, alias.index) + alias.emoji; + start = alias.index + alias.text.length; + } + return start === 0 ? text : expanded + text.slice(start); +} diff --git a/third-party-licenses.config.json b/third-party-licenses.config.json index 66eed772bebbf..2cfb7324d9eae 100644 --- a/third-party-licenses.config.json +++ b/third-party-licenses.config.json @@ -1,5 +1,17 @@ { "customNotices": [ + { + "bundles": ["desktop", "mobile", "web"], + "license": "MIT", + "name": "GitHub gemoji alias data", + "sourceUrl": "https://github.com/github/gemoji/blob/fadaeaf1f1a9be82b321316a6c5502e43138b2f6/db/emoji.json", + "generatedNotices": [ + { + "licenseId": "MIT", + "copyrights": ["Copyright (c) 2019 GitHub, Inc."] + } + ] + }, { "name": "opencode Office viewers", "bundles": ["web"], From 66b8a94f8d10e6ef123c134852c94642c4f1324c Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 19 Nov 2026 13:46:42 -0800 Subject: [PATCH 80/97] perf(server): finalizing a delegated task no longer reads the child's whole turn history (#39325) --- .../src/orchestration-v2/Orchestrator.ts | 164 +++++++++++++----- .../orchestration-v2/ProjectionStore.test.ts | 86 +++++++-- .../src/orchestration-v2/ProjectionStore.ts | 96 ++++++++++ .../ProviderTurnControlService.test.ts | 1 + .../orchestration-v2/delegatedTaskMessage.ts | 9 + apps/server/src/persistence/Migrations.ts | 2 + .../101_DelegatedTaskReadIndexes.ts | 22 +++ .../reconcileV2PreviewMigration.test.ts | 2 + .../src/server/subagentProjection.ts | 2 +- 9 files changed, 333 insertions(+), 51 deletions(-) create mode 100644 apps/server/src/orchestration-v2/delegatedTaskMessage.ts create mode 100644 apps/server/src/persistence/Migrations/101_DelegatedTaskReadIndexes.ts diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 0a3424735a670..059671b306fa9 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -201,6 +201,7 @@ import { subagentResultForRun, delegatedTaskProgress, delegatedTaskReportRuns, + monitorUpdateRunIds, subagentThreadTitle, } from "@t3tools/provider-core/server/subagentProjection"; import { @@ -1286,6 +1287,41 @@ function runForSourcePoint( } } +const DELEGATED_CHILD_RUN_WINDOW = 20; + +type DelegatedChildControls = ProjectionRecords< + "runs" | "messages" | "subagents" | "providerThreads" +> & { + /** Set when `runs` holds only what ran since this run, plus older unfinished and task runs. */ + readonly runsFloor?: OrchestrationV2Run | undefined; +}; + +function ranSince(run: OrchestrationV2Run, floor: OrchestrationV2Run): boolean { + return run.id === floor.id || runRanAfter(run, floor); +} + +/** The walk back to a report is exact when it stops at a run that ran since the floor. */ +function reportRunsRead( + controls: DelegatedChildControls, + run: OrchestrationV2Run, + reportRuns: ReadonlyArray, +): boolean { + const floor = controls.runsFloor; + if (floor === undefined || run.status !== "completed") return true; + const oldest = reportRuns.at(-1) ?? run; + if (!ranSince(oldest, floor)) return false; + const monitorRuns = monitorUpdateRunIds(controls.messages); + return controls.runs.some( + (candidate) => + candidate.id !== run.id && + candidate.startedAt !== null && + candidate.status !== "rolled_back" && + !monitorRuns.has(candidate.id) && + runRanAfter(oldest, candidate) && + ranSince(candidate, floor), + ); +} + function providerThreadForRun( projection: Pick, run: OrchestrationV2Run, @@ -14621,23 +14657,24 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio // A finished delegate otherwise keeps its provider process until the idle timeout. Callers hold // the parent lock; the child lock orders this after any follow-up that started a run meanwhile. const releaseFinishedDelegateSessions = Effect.fn("Orchestrator.releaseFinishedDelegateSessions")( - function* (childThreadId: ThreadId, resultRunId: RunId) { + function* (childThreadId: ThreadId, resultRunId: RunId, taskId: NodeId) { yield* threadDispatch.withLock( childThreadId, Effect.gen(function* () { - const child = yield* projectionStore.getThreadRecords( - childThreadId, - ["runs", "messages", "subagents", "providerThreads", "providerSessions"], - { messageRoles: ["user"] }, - ); + const { controls: child, progress } = yield* readDelegatedChildControls(childThreadId, [ + taskId, + ]); // Unawaited background tasks still allow a result but die with the process; the idle // timer keeps their process pinned. if ( - delegatedTaskProgress(child).state !== "result_available" || + progress.state !== "result_available" || child.providerThreads.some((thread) => (thread.pendingBackgroundTasks ?? []).length > 0) ) return; - for (const session of child.providerSessions) { + const { providerSessions } = yield* projectionStore.getThreadRecords(childThreadId, [ + "providerSessions", + ]); + for (const session of providerSessions) { // Shared processes unload their threads themselves; only a per-thread process lingers. if ( session.status === "stopped" || @@ -14663,15 +14700,39 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ), ); + const readAllDelegatedChildControls = (childThreadId: ThreadId) => + projectionStore.getThreadRecords( + childThreadId, + ["runs", "messages", "subagents", "providerThreads"], + { messageRoles: ["user"], delegatedTaskMessagesOnly: true }, + ); + + const readDelegatedChildControls = Effect.fn("Orchestrator.readDelegatedChildControls")( + function* (childThreadId: ThreadId, taskIds: ReadonlyArray) { + const controls: DelegatedChildControls = yield* projectionStore.getDelegatedChildControls( + childThreadId, + { taskIds, windowSize: DELEGATED_CHILD_RUN_WINDOW }, + ); + const progress = delegatedTaskProgress(controls); + // The latest result may have ended before the runs read above; then read them all. + if ( + controls.runsFloor !== undefined && + (progress.resultRun === undefined || !ranSince(progress.resultRun, controls.runsFloor)) + ) { + const all = yield* readAllDelegatedChildControls(childThreadId); + return { controls: all, progress: delegatedTaskProgress(all) }; + } + return { controls, progress }; + }, + ); + /** * Callers must hold the parent thread's dispatch lock: wake-policy updates the same * subagent row with full-row payloads, so unserialized writers clobber policy or terminal status. */ const finalizeAppOwnedSubagentTask = Effect.fn("Orchestrator.finalizeAppOwnedSubagentTask")( function* ( - childControls: ProjectionRecords< - "runs" | "messages" | "subagents" | "providerThreads" | "providerTurns" | "attempts" - >, + childControls: DelegatedChildControls, options: { readonly settledContinuationOf?: RunId; readonly syncRunId?: RunId; @@ -14776,23 +14837,45 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio } // A run queued behind the report can end the task without saying anything. - const reportRuns = delegatedTaskReportRuns(childControls, { ...childRun, status: outcome }); + const reportFrom = { ...childRun, status: outcome }; + let reportRuns = delegatedTaskReportRuns(childControls, reportFrom); + if (!reportRunsRead(childControls, reportFrom, reportRuns)) { + reportRuns = delegatedTaskReportRuns( + yield* readAllDelegatedChildControls(childThreadId), + reportFrom, + ); + } const resultRunIds = [childRun.id, ...reportRuns.map((run) => run.id)]; const childResult = yield* projectionStore.getThreadRecords( childThreadId, - ["messages", "turnItems"], + ["messages", "turnItems", "providerTurns", "attempts"], { messageRoles: ["assistant"], messageRunIds: resultRunIds, turnItemRunIds: resultRunIds, turnItemTypes: ["assistant_message", "error", "system_notice"], + providerTurnAttemptIds: [childRun, ...reportRuns].flatMap( + (run) => run.activeAttemptId ?? [], + ), + attemptIds: childRun.activeAttemptId === null ? [] : [childRun.activeAttemptId], }, ); + // A steered run's attempt can point at a provider turn that another attempt started. + const attemptTurnId = childResult.attempts[0]?.providerTurnId; + const steeredTurns = + attemptTurnId == null || + childResult.providerTurns.some((turn) => turn.runAttemptId === childRun.activeAttemptId) + ? [] + : (yield* projectionStore.getThreadRecords(childThreadId, ["providerTurns"], { + providerTurnIds: [attemptTurnId], + })).providerTurns; const childProjection = { ...childControls, runs: reportRuns, messages: childResult.messages, turnItems: childResult.turnItems, + providerTurns: [...childResult.providerTurns, ...steeredTurns], + attempts: childResult.attempts, }; const parentThreadId = childControls.thread.lineage.parentThreadId; // The task's node and turn item share its id. @@ -14957,7 +15040,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio }, ]; yield* writeSystemEvents(completionEvents, [], { updateDelegatedCompletionOnly: true }); - yield* releaseFinishedDelegateSessions(childThreadId, childRun.id); + yield* releaseFinishedDelegateSessions(childThreadId, childRun.id, task.id); if (completionPlan.offer && completionPlan.parentRun !== undefined) { yield* offerDelegatedCompletionDelivery(parentThreadId, completionPlan.parentRun.id); @@ -14978,41 +15061,41 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio childThreadId: ThreadId, options?: { readonly settledContinuationOf?: RunId; readonly syncRunId?: RunId }, ) { - const childControls = yield* projectionStore.getThreadRecords( - childThreadId, - ["runs", "messages", "subagents", "providerThreads", "providerTurns", "attempts"], - { messageRoles: ["user"] }, - ); - const parentThreadId = childControls.thread.lineage.parentThreadId; + const child = yield* projectionStore.getThreadRecords(childThreadId, ["contextTransfers"]); + const parentThreadId = child.thread.lineage.parentThreadId; + const forkedFrom = child.thread.forkedFrom; if ( - childControls.thread.lineage.relationshipToParent !== "subagent" || + child.thread.lineage.relationshipToParent !== "subagent" || parentThreadId === null || - childControls.thread.forkedFrom?.type !== "node" + forkedFrom?.type !== "node" ) return; - const progress = delegatedTaskProgress(childControls); // Each task of this child names it, so the parent's other tasks stay unread. const parent = yield* projectionStore.getThreadRecords(parentThreadId, ["subagents"], { subagentChildThreadIds: [childThreadId], }); - const { contextTransfers } = yield* projectionStore.getThreadRecords(childThreadId, [ - "contextTransfers", - ]); - for (const task of parent.subagents) { + const resultSent = child.contextTransfers.some( + (transfer) => + transfer.type === "subagent_result" && + transfer.sourceThreadId === childThreadId && + transfer.targetThreadId === parentThreadId, + ); + const openTasks = parent.subagents.filter( + (task) => + task.origin === "app_owned" && + task.childThreadId === childThreadId && + !(task.result !== null && resultSent), + ); + const { controls: childControls, progress } = yield* readDelegatedChildControls( + childThreadId, + openTasks.map((task) => task.id), + ); + for (const task of openTasks) { // A cancelled task does not wait for the work its cancel is stopping. const cancelled = task.cancelledRunId !== undefined; if ( - task.origin !== "app_owned" || - task.childThreadId !== childThreadId || - (task.id === childControls.thread.forkedFrom.nodeId && - (cancelled ? progress.state === "working" : progress.state !== "result_available")) || - (task.result !== null && - contextTransfers.some( - (transfer) => - transfer.type === "subagent_result" && - transfer.sourceThreadId === childThreadId && - transfer.targetThreadId === parentThreadId, - )) + task.id === forkedFrom.nodeId && + (cancelled ? progress.state === "working" : progress.state !== "result_available") ) continue; yield* finalizeAppOwnedSubagentTask(childControls, { @@ -15025,7 +15108,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio // Only the run a cancelled task settled from ends with it. The row read above has no // such run yet when this call settled the task, from the same result run. const { resultRun } = progress; - const resultTaskId = resultRun?.delegatedTaskId ?? childControls.thread.forkedFrom.nodeId; + const resultTaskId = resultRun?.delegatedTaskId ?? forkedFrom.nodeId; const resultTask = parent.subagents.find((task) => task.id === resultTaskId); const taskCancelled = resultTask?.cancelledRunId !== undefined && resultTask.cancelledRunId === resultRun?.id; @@ -15064,7 +15147,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio run = previousRunId === undefined ? undefined - : childControls.runs.find((candidate) => candidate.id === previousRunId); + : (childControls.runs.find((candidate) => candidate.id === previousRunId) ?? + (yield* projectionStore.getRun(childThreadId, previousRunId))); } for (const request of pendingQuestions) { if ( diff --git a/apps/server/src/orchestration-v2/ProjectionStore.test.ts b/apps/server/src/orchestration-v2/ProjectionStore.test.ts index 5a1baf63d997a..dabe53aeae46f 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.test.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.test.ts @@ -1385,6 +1385,7 @@ it.effect("record reads filter notification sources without dropping matching me ["monitor", "user", "monitor"], ["system", "user", "system"], ["assistant-monitor", "assistant", "monitor"], + ["wake", "user", "wake"], ] as const) { yield* store.apply({ id: EventId.make(`notification-filter:${id}`), @@ -1406,13 +1407,21 @@ it.effect("record reads filter notification sources without dropping matching me updatedAt: now, ...(kind === null ? {} - : { - notification: { - source: { kind }, - outcome: "updated", - summary: "Background notification", - }, - }), + : kind === "wake" + ? { + delegatedCompletion: { + parentRunId: RunId.make("run:wake-parent"), + generation: 1, + taskIds: [], + }, + } + : { + notification: { + source: { kind }, + outcome: "updated", + summary: "Background notification", + }, + }), }, }); } @@ -1424,11 +1433,19 @@ it.effect("record reads filter notification sources without dropping matching me matching.messages.map((message) => [message.id, message.text]), [["monitor", "Complete body for monitor"]], ); + const delegatedTaskMessages = yield* store.getThreadRecords(threadId, ["messages"], { + messageRoles: ["user"], + delegatedTaskMessagesOnly: true, + }); + assert.deepEqual( + delegatedTaskMessages.messages.map((message) => message.id), + ["monitor", "wake"], + ); const { statements, tracer } = traceSqlStatements(); const userMessages = yield* store .getThreadRecords(threadId, ["messages"], { messageRoles: ["user"] }) .pipe(Effect.withTracer(tracer)); - assert.lengthOf(userMessages.messages, 3); + assert.lengthOf(userMessages.messages, 4); const ordinalLookup = statements.find((statement) => statement.includes("MIN(ordinal)")); // User-only reads must seek the message-ordinal index instead of scanning every turn item. yield* assertReadsThroughMessageOrdinalIndex(ordinalLookup, ["thread_id=?", "=?"]); @@ -1442,7 +1459,7 @@ it.effect("record reads filter notification sources without dropping matching me .pipe(Effect.withTracer(withItems.tracer)); assert.deepEqual(ordered.messages, userMessages.messages); assert.isFalse(withItems.statements.some((statement) => statement.includes("MIN(ordinal)"))); - assert.lengthOf((yield* store.getThreadRecords(threadId, ["messages"])).messages, 4); + assert.lengthOf((yield* store.getThreadRecords(threadId, ["messages"])).messages, 5); assert.lengthOf( (yield* store.getThreadRecords(threadId, ["messages"], { monitorNotificationsOnly: true, @@ -1453,7 +1470,56 @@ it.effect("record reads filter notification sources without dropping matching me (yield* store.getThreadRecords(threadId, ["messages"], { monitorNotificationsOnly: false, })).messages, - 4, + 5, + ); + }).pipe(Effect.provide(layerTest)), +); + +it.effect("reads a delegated child's recent, unfinished and task runs without its history", () => + Effect.gen(function* () { + const store = yield* ProjectionStore.ProjectionStoreV2; + const threadId = yield* addRolledBackRecoveryCandidate("delegated-child-runs"); + const first = (yield* store.getThreadRecords(threadId, ["runs"])).runs[0]!; + const at = (minutes: number) => DateTime.add(first.requestedAt, { minutes: minutes + 60 }); + const id = (ordinal: number) => RunId.make(`run:delegated-child-runs:${ordinal}`); + const unstartedCancel = { status: "cancelled", startedAt: null } as const; + for (const [ordinal, patch] of [ + [3, { status: "running", completedAt: null }], + // Unstarted cancelled runs are outside the window's index: one ends after the floor. + [4, { ...unstartedCancel, completedAt: at(20) }], + [5, { ...unstartedCancel, completedAt: at(1) }], + ...[2, 6, 7, 8, 9, 10, 11, 12].map((ordinal) => [ordinal, {}] as const), + ] as const) { + yield* store.apply({ + id: EventId.make(`event:delegated-child-runs:${ordinal}`), + type: "run.created", + threadId, + runId: id(ordinal), + occurredAt: first.requestedAt, + payload: { + ...first, + id: id(ordinal), + ordinal, + status: "completed", + startedAt: at(ordinal), + completedAt: at(ordinal), + delegatedTaskId: NodeId.make(`node:delegated-child-runs:task:${ordinal}`), + ...patch, + }, + }); + } + const taskIds = [NodeId.make("node:delegated-child-runs:task:2")]; + const bounded = yield* store.getDelegatedChildControls(threadId, { taskIds, windowSize: 3 }); + assert.equal(bounded.runsFloor?.id, id(11)); + assert.deepEqual( + bounded.runs.map((run) => run.id), + [2, 3, 4, 11, 12].map(id), + ); + const whole = yield* store.getDelegatedChildControls(threadId, { taskIds, windowSize: 100 }); + assert.isUndefined(whole.runsFloor); + assert.deepEqual( + whole.runs.map((run) => run.id), + (yield* store.getThreadRecords(threadId, ["runs"])).runs.map((run) => run.id), ); }).pipe(Effect.provide(layerTest)), ); diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index 7824fce056c4f..930639b5d6bbe 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -103,6 +103,7 @@ import type * as Statement from "effect/sql/Statement"; import { MCP_APP_OUTPUT_KEY } from "@t3tools/shared/mcpApp"; import { threadHtmlRenderAttachmentIds } from "../attachmentStore.ts"; +import { DELEGATED_TASK_MESSAGE_CONDITION } from "./delegatedTaskMessage.ts"; import { DEFERRED_COMMAND_MESSAGE_CONDITION, JAVASCRIPT_TRIM_WHITESPACE, @@ -375,6 +376,8 @@ export interface ProjectionRecordFilter { readonly attemptIds?: ReadonlyArray; readonly messageRoles?: ReadonlyArray; readonly monitorNotificationsOnly?: boolean; + /** User messages that are monitor notifications or delegated-completion wakes, through their partial index. */ + readonly delegatedTaskMessagesOnly?: true; readonly turnItemRunId?: RunId; readonly messageIds?: ReadonlyArray; readonly messageRunIds?: ReadonlyArray; @@ -816,6 +819,20 @@ export interface ProjectionStoreV2Shape { threadId: ThreadId, runId: RunId, ) => Effect.Effect; + /** + * One snapshot: the `windowSize` runs that ended last, unfinished runs, the runs of `taskIds` and + * their wakes. `runsFloor` is set when older runs were left out; every run that ran after it is + * in `runs`. + */ + readonly getDelegatedChildControls: ( + threadId: ThreadId, + input: { readonly taskIds: ReadonlyArray; readonly windowSize: number }, + ) => Effect.Effect< + ProjectionRecords<"runs" | "messages" | "subagents" | "providerThreads"> & { + readonly runsFloor: OrchestrationV2Run | undefined; + }, + ProjectionStoreV2Error + >; readonly canStartQueuedRun: ( threadId: ThreadId, ) => Effect.Effect; @@ -4437,6 +4454,7 @@ export const layer: Layer.Layer = ${filter?.messageIds === undefined ? sql`` : sql`AND message_id IN (SELECT value FROM json_each(${encodeIdList(filter.messageIds)}))`} ${filter?.messageRoles === undefined ? sql`` : sql`AND role IN (SELECT value FROM json_each(${encodeIdList(filter.messageRoles)}))`} ${filter?.monitorNotificationsOnly === true ? sql`AND json_extract(payload_json, '$.notification.source.kind') = 'monitor'` : sql``} + ${filter?.delegatedTaskMessagesOnly === true ? sql`AND ${sql.literal(DELEGATED_TASK_MESSAGE_CONDITION)}` : sql``} ${filter?.messageRunIds === undefined ? sql`` : sql`AND run_id IN (SELECT value FROM json_each(${encodeIdList(filter.messageRunIds)}))`} ORDER BY created_at ASC, message_id ASC ` @@ -6475,6 +6493,83 @@ export const layer: Layer.Layer = ) .pipe(Effect.mapError(controlReadError(threadId))); + const getDelegatedChildControls: ProjectionStoreV2Shape["getDelegatedChildControls"] = ( + threadId, + { taskIds, windowSize }, + ) => + sql + .withTransaction( + Effect.gen(function* () { + const records = yield* getThreadRecords( + threadId, + ["messages", "subagents", "providerThreads"], + { messageRoles: ["user"], delegatedTaskMessagesOnly: true }, + ); + // Spells migration 84's order and predicate so the window walks that index. + const windowRows = yield* sql` + SELECT payload_json, completed_at FROM orchestration_v2_projection_runs + WHERE thread_id = ${threadId} + AND status <> 'queued' + AND NOT (status = 'cancelled' AND json_extract(payload_json, '$.startedAt') IS NULL) + ORDER BY (completed_at IS NULL) DESC, completed_at DESC, ordinal DESC, run_id DESC + LIMIT ${windowSize} + `; + const window = yield* decodeRows(decodeRunPayload, threadId)(windowRows); + const last = window.length < windowSize ? undefined : window.at(-1); + const floorCompletedAt = windowRows.at(-1)?.completed_at ?? null; + // A window ending in unfinished runs bounds nothing, so read the whole thread. + const floor = floorCompletedAt === null ? undefined : last; + const rest = yield* ( + last !== undefined && floor === undefined + ? sql` + SELECT payload_json FROM orchestration_v2_projection_runs + WHERE thread_id = ${threadId}` + : sql` + SELECT payload_json FROM orchestration_v2_projection_runs + WHERE thread_id = ${threadId} + AND status IN ('preparing', 'queued', 'starting', 'running', 'waiting') + UNION + SELECT payload_json FROM orchestration_v2_projection_runs + WHERE thread_id = ${threadId} AND json_valid(payload_json) + AND json_extract(payload_json, '$.delegatedTaskId') IS NOT NULL + AND json_extract(payload_json, '$.delegatedTaskId') + IN (SELECT value FROM json_each(${encodeIdList(taskIds)})) + UNION + -- Unstarted cancelled runs are outside the window's index. + SELECT payload_json FROM orchestration_v2_projection_runs + WHERE thread_id = ${threadId} AND status = 'cancelled' + ${floor === undefined ? sql`` : sql`AND (completed_at IS NULL OR completed_at >= ${floorCompletedAt})`}` + ).pipe(Effect.flatMap(decodeRows(decodeRunPayload, threadId))); + const runs = new Map([...window, ...rest].map((run) => [run.id, run])); + const requested = new Set(); + for (;;) { + const wakeRunIds = [ + ...new Set( + records.messages.flatMap((message) => + message.runId !== null && + message.delegatedCompletion !== undefined && + runs.has(message.delegatedCompletion.parentRunId) && + !runs.has(message.runId) && + !requested.has(message.runId) + ? [message.runId] + : [], + ), + ), + ]; + if (wakeRunIds.length === 0) break; + for (const id of wakeRunIds) requested.add(id); + const wakes = yield* getThreadRecords(threadId, ["runs"], { runIds: wakeRunIds }); + for (const run of wakes.runs) runs.set(run.id, run); + } + return { + ...records, + runs: [...runs.values()].toSorted((a, b) => a.ordinal - b.ordinal), + runsFloor: floor, + }; + }), + ) + .pipe(Effect.mapError(controlReadError(threadId))); + const getRun: ProjectionStoreV2Shape["getRun"] = (threadId, runId) => sql .withTransaction( @@ -9669,6 +9764,7 @@ export const layer: Layer.Layer = getCheckpointCaptureContext: readOnReader(getCheckpointCaptureContext), getCheckpointRollbackContext: readOnReader(getCheckpointRollbackContext), getRunMessage: readOnReader(getRunMessage), + getDelegatedChildControls: readOnReader(getDelegatedChildControls), getRun: readOnReader(getRun), canStartQueuedRun: readOnReader(canStartQueuedRun), getHeldQueuedRuns: readOnReader(getHeldQueuedRuns), diff --git a/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts b/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts index df80f2ded5836..51c38efa8a41a 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts @@ -187,6 +187,7 @@ function layerProjectionStore( getCheckpointRollbackContext: () => Effect.die("unused rollback context"), getCheckpointCaptureContext: () => Effect.die("not used"), getRunMessage: () => Effect.die("not used"), + getDelegatedChildControls: () => Effect.die("not used"), getRun: () => Effect.die("not used"), isNodeStored: () => Effect.die("not used"), canStartQueuedRun: () => Effect.die("not used"), diff --git a/apps/server/src/orchestration-v2/delegatedTaskMessage.ts b/apps/server/src/orchestration-v2/delegatedTaskMessage.ts new file mode 100644 index 0000000000000..df98b47dc3791 --- /dev/null +++ b/apps/server/src/orchestration-v2/delegatedTaskMessage.ts @@ -0,0 +1,9 @@ +/** + * A user message that marks its run as a monitor update or a delegated-completion wake: what + * `delegatedTaskProgress` and `delegatedTaskRuns` read. The partial index on it is only used when + * the read spells this text the same way. + */ +export const DELEGATED_TASK_MESSAGE_CONDITION = `role = 'user' AND json_valid(payload_json) AND ( + json_extract(payload_json, '$.notification.source.kind') = 'monitor' + OR json_extract(payload_json, '$.delegatedCompletion') IS NOT NULL +)`; diff --git a/apps/server/src/persistence/Migrations.ts b/apps/server/src/persistence/Migrations.ts index dcf435b670ca5..c3fc7aacef055 100644 --- a/apps/server/src/persistence/Migrations.ts +++ b/apps/server/src/persistence/Migrations.ts @@ -108,6 +108,7 @@ import Migration0097 from "./Migrations/097_IssueTrackerBindings.ts"; import Migration0098 from "./Migrations/098_ActiveShellIndexIndexes.ts"; import Migration0099 from "./Migrations/099_BackgroundRecoveryIndexes.ts"; import Migration0100 from "./Migrations/100_TurnStartReadIndexes.ts"; +import Migration0101 from "./Migrations/101_DelegatedTaskReadIndexes.ts"; const migrationEntries = [ [1, "OrchestrationEvents", Migration0001], @@ -211,6 +212,7 @@ const migrationEntries = [ [98, "ActiveShellIndexIndexes", Migration0098], [99, "BackgroundRecoveryIndexes", Migration0099], [100, "TurnStartReadIndexes", Migration0100], + [101, "DelegatedTaskReadIndexes", Migration0101], ] as const; export const migrationManifest = migrationEntries.map(([id, name]) => [id, name] as const); diff --git a/apps/server/src/persistence/Migrations/101_DelegatedTaskReadIndexes.ts b/apps/server/src/persistence/Migrations/101_DelegatedTaskReadIndexes.ts new file mode 100644 index 0000000000000..e057296dafab2 --- /dev/null +++ b/apps/server/src/persistence/Migrations/101_DelegatedTaskReadIndexes.ts @@ -0,0 +1,22 @@ +import * as Effect from "effect/Effect"; +import * as SqlClient from "effect/sql/SqlClient"; + +import { DELEGATED_TASK_MESSAGE_CONDITION } from "../../orchestration-v2/delegatedTaskMessage.ts"; + +export default Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + + // Finalizing a delegated task finds its tasks' runs and the child's wakes without reading the + // child's history. ProjectionStore.getDelegatedChildControls and the delegatedTaskMessagesOnly read + // must spell the same expressions. + yield* sql` + CREATE INDEX IF NOT EXISTS orchestration_v2_projection_runs_delegated_task_idx + ON orchestration_v2_projection_runs(thread_id, json_extract(payload_json, '$.delegatedTaskId')) + WHERE json_valid(payload_json) AND json_extract(payload_json, '$.delegatedTaskId') IS NOT NULL + `; + yield* sql.unsafe(` + CREATE INDEX IF NOT EXISTS orchestration_v2_projection_messages_delegated_task_idx + ON orchestration_v2_projection_messages(thread_id, created_at, message_id) + WHERE ${DELEGATED_TASK_MESSAGE_CONDITION} + `); +}); diff --git a/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts b/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts index 982ea60a2b340..b9feabbf89b88 100644 --- a/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts +++ b/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts @@ -80,6 +80,7 @@ describe("V2 preview upgrade", () => { [98, "ActiveShellIndexIndexes"], [99, "BackgroundRecoveryIndexes"], [100, "TurnStartReadIndexes"], + [101, "DelegatedTaskReadIndexes"], ]); assert.deepStrictEqual(yield* runMigrations(), []); assert.deepStrictEqual(yield* sql`SELECT * FROM orchestration_v2_legacy_imports`, imports); @@ -203,6 +204,7 @@ describe("V2 preview upgrade", () => { [98, "ActiveShellIndexIndexes"], [99, "BackgroundRecoveryIndexes"], [100, "TurnStartReadIndexes"], + [101, "DelegatedTaskReadIndexes"], ]); }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))), ); diff --git a/packages/provider-core/src/server/subagentProjection.ts b/packages/provider-core/src/server/subagentProjection.ts index 88b124bf5fb79..e0ac009f5731a 100644 --- a/packages/provider-core/src/server/subagentProjection.ts +++ b/packages/provider-core/src/server/subagentProjection.ts @@ -206,7 +206,7 @@ function stopNotice( type MonitorNotice = Pick; /** Runs that only acknowledge a monitor update are never a task's work. */ -function monitorUpdateRunIds(messages: ReadonlyArray) { +export function monitorUpdateRunIds(messages: ReadonlyArray) { return new Set( messages .filter( From 210996207d3c9327c1dcbb12cd958abdfa72e5ae Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 19 Nov 2026 14:09:09 -0800 Subject: [PATCH 81/97] feat(mobile): pull request files follow the same review order as web (#26760) --- .../pull-requests/PullRequestFiles.tsx | 39 +------- .../pull-requests/pullRequestDiffPages.ts | 6 +- .../pullRequestFileSections.test.ts | 22 +++++ .../pull-requests/pullRequestFileSections.ts | 37 ++++++++ .../web/src/components/diffs/DiffFileTree.tsx | 2 +- .../diffs/diffFileTree.logic.test.ts | 26 +---- .../components/diffs/diffFileTree.logic.ts | 43 --------- .../pullRequest/PullRequestCodeTab.tsx | 11 +-- packages/client-runtime/package.json | 4 + .../client-runtime/src/diffFileOrder.test.ts | 56 +++++++++-- .../client-runtime/src/diffFileOrder.ts | 94 +++++++++++++++---- 11 files changed, 198 insertions(+), 142 deletions(-) create mode 100644 apps/mobile/src/features/pull-requests/pullRequestFileSections.test.ts create mode 100644 apps/mobile/src/features/pull-requests/pullRequestFileSections.ts rename apps/web/src/components/pullRequest/pullRequestFileOrder.logic.test.ts => packages/client-runtime/src/diffFileOrder.test.ts (75%) rename apps/web/src/components/pullRequest/pullRequestFileOrder.logic.ts => packages/client-runtime/src/diffFileOrder.ts (68%) diff --git a/apps/mobile/src/features/pull-requests/PullRequestFiles.tsx b/apps/mobile/src/features/pull-requests/PullRequestFiles.tsx index b16313d8b8897..601f6e5c20b5a 100644 --- a/apps/mobile/src/features/pull-requests/PullRequestFiles.tsx +++ b/apps/mobile/src/features/pull-requests/PullRequestFiles.tsx @@ -32,6 +32,7 @@ import { import { usePullRequestFileFilter } from "./usePullRequestFileFilter"; import { usePullRequestFilesViewed } from "./usePullRequestFilesViewed"; import { requestPullRequestFileJump } from "./pullRequestFileJump"; +import { fileDirectory, groupByDirectory } from "./pullRequestFileSections"; import type { MessageResolver } from "../../i18n/messages"; const BREAKDOWN_LABELS = { @@ -42,11 +43,6 @@ const BREAKDOWN_LABELS = { docs: msg("Docs", { $context: "kind of changed file" }), } satisfies Record, string>; -function fileDirectory(path: string) { - const separator = path.lastIndexOf("/"); - return separator < 0 ? "" : path.slice(0, separator); -} - function useChangedFiles(params: PullRequestDiffParams) { const detail = useEnvironmentQuery(composerPullRequests.detail(pullRequestTarget(params))); // A commit's diff is part of the pull request, so the PR's file counts and viewed state don't apply. @@ -375,39 +371,6 @@ export function usePullRequestFilesSection(params: PullRequestParams) { }; } -type SheetItem = - | { - readonly kind: "directory"; - readonly key: string; - readonly directory: string; - readonly collapsed: boolean; - } - | { readonly kind: "file"; readonly key: string; readonly file: ReviewRenderableFile }; - -function groupByDirectory( - files: ReadonlyArray, - collapsed: ReadonlySet, -) { - const sorted = files - .map((file) => ({ file, directory: fileDirectory(file.path) })) - .sort( - (a, b) => a.directory.localeCompare(b.directory) || a.file.path.localeCompare(b.file.path), - ); - const items: SheetItem[] = []; - sorted.forEach(({ file, directory }, index) => { - if (directory !== sorted[index - 1]?.directory) { - items.push({ - kind: "directory", - key: `directory:${directory}`, - directory, - collapsed: collapsed.has(directory), - }); - } - if (!collapsed.has(directory)) items.push({ kind: "file", key: file.id, file }); - }); - return items; -} - function DirectoryRow(props: { readonly directory: string; readonly collapsed: boolean; diff --git a/apps/mobile/src/features/pull-requests/pullRequestDiffPages.ts b/apps/mobile/src/features/pull-requests/pullRequestDiffPages.ts index f4f33896e8bb4..914ee50df3c85 100644 --- a/apps/mobile/src/features/pull-requests/pullRequestDiffPages.ts +++ b/apps/mobile/src/features/pull-requests/pullRequestDiffPages.ts @@ -1,3 +1,4 @@ +import { orderDiffFilesForReview } from "@t3tools/client-runtime/diff-file-order"; import type { ChangeRequestTerminology } from "@t3tools/client-runtime/source-control-clients"; import { changeRequestTermKind } from "../../lib/changeRequestTerm"; import type { PullRequestDiffResult } from "@t3tools/contracts"; @@ -118,7 +119,10 @@ export function combinePullRequestDiffPages( cache.set(page.result, value); return value; }); - const files = parsed.flatMap((page) => (page.kind === "files" ? page.files : [])); + const files = orderDiffFilesForReview( + parsed.flatMap((page) => (page.kind === "files" ? page.files : [])), + (file) => file.path, + ); if (files.length === 0) return parsed[0] ?? { kind: "empty" }; return { kind: "files", diff --git a/apps/mobile/src/features/pull-requests/pullRequestFileSections.test.ts b/apps/mobile/src/features/pull-requests/pullRequestFileSections.test.ts new file mode 100644 index 0000000000000..0fcc778b91942 --- /dev/null +++ b/apps/mobile/src/features/pull-requests/pullRequestFileSections.test.ts @@ -0,0 +1,22 @@ +import { describe, expect, it } from "vite-plus/test"; +import { buildReviewParsedDiff } from "../review/reviewModel"; +import { groupByDirectory } from "./pullRequestFileSections"; + +function patch(path: string) { + return `diff --git a/${path} b/${path}\n--- a/${path}\n+++ b/${path}\n@@ -1 +1 @@\n-old\n+new\n`; +} + +describe("groupByDirectory", () => { + it("keeps review order when a parent directory resumes after a subdirectory", () => { + const parsed = buildReviewParsedDiff( + ["src/a.ts", "src/lib/b.ts", "src/z.ts"].map(patch).join("\n"), + "pr", + ); + if (parsed.kind !== "files") throw new Error("Expected files"); + const items = groupByDirectory(parsed.files, new Set()); + expect( + items.map((item) => (item.kind === "directory" ? `${item.directory}/` : item.file.path)), + ).toEqual(["src/", "src/a.ts", "src/lib/", "src/lib/b.ts", "src/", "src/z.ts"]); + expect(new Set(items.map((item) => item.key)).size).toBe(items.length); + }); +}); diff --git a/apps/mobile/src/features/pull-requests/pullRequestFileSections.ts b/apps/mobile/src/features/pull-requests/pullRequestFileSections.ts new file mode 100644 index 0000000000000..8ae0ca4c844db --- /dev/null +++ b/apps/mobile/src/features/pull-requests/pullRequestFileSections.ts @@ -0,0 +1,37 @@ +import type { ReviewRenderableFile } from "../review/reviewModel"; + +export function fileDirectory(path: string) { + const separator = path.lastIndexOf("/"); + return separator < 0 ? "" : path.slice(0, separator); +} + +type SheetItem = + | { + readonly kind: "directory"; + readonly key: string; + readonly directory: string; + readonly collapsed: boolean; + } + | { readonly kind: "file"; readonly key: string; readonly file: ReviewRenderableFile }; + +export function groupByDirectory( + files: ReadonlyArray, + collapsed: ReadonlySet, +) { + // Keep the shared review order: a directory gets a new header each time it resumes after a subdirectory. + const items: SheetItem[] = []; + files.forEach((file, index) => { + const directory = fileDirectory(file.path); + const previous = files[index - 1]; + if (!previous || directory !== fileDirectory(previous.path)) { + items.push({ + kind: "directory", + key: `directory:${directory}:${index}`, + directory, + collapsed: collapsed.has(directory), + }); + } + if (!collapsed.has(directory)) items.push({ kind: "file", key: file.id, file }); + }); + return items; +} diff --git a/apps/web/src/components/diffs/DiffFileTree.tsx b/apps/web/src/components/diffs/DiffFileTree.tsx index e59cf38f4c66c..ce48a468f66ec 100644 --- a/apps/web/src/components/diffs/DiffFileTree.tsx +++ b/apps/web/src/components/diffs/DiffFileTree.tsx @@ -21,9 +21,9 @@ import { compareDiffFileTreeEntries, collectDirectoryPaths, diffFileTreeModel, - diffFileTreePositions, type DiffFileTreeEntry, } from "./diffFileTree.logic"; +import { diffFileTreePositions } from "@t3tools/client-runtime/diff-file-order"; export type { DiffFileTreeEntry } from "./diffFileTree.logic"; diff --git a/apps/web/src/components/diffs/diffFileTree.logic.test.ts b/apps/web/src/components/diffs/diffFileTree.logic.test.ts index dea4b9981c8a6..757ab3f83de42 100644 --- a/apps/web/src/components/diffs/diffFileTree.logic.test.ts +++ b/apps/web/src/components/diffs/diffFileTree.logic.test.ts @@ -1,11 +1,7 @@ import type { FileDiffMetadata } from "@pierre/diffs"; import { describe, expect, it } from "vite-plus/test"; -import { - buildDiffFileTreeUpdates, - diffFileTreeEntries, - orderDiffFilesLikeTree, -} from "./diffFileTree.logic"; +import { buildDiffFileTreeUpdates, diffFileTreeEntries } from "./diffFileTree.logic"; function file(type: FileDiffMetadata["type"], name: string, prevName = name): FileDiffMetadata { return { type, name, prevName } as FileDiffMetadata; @@ -28,26 +24,6 @@ describe("diffFileTreeEntries", () => { }); }); -describe("orderDiffFilesLikeTree", () => { - it("pulls a test listed last into its directory, keeping the first-seen order", () => { - expect( - orderDiffFilesLikeTree([ - file("change", "server/device/Host.ts"), - file("change", "web/settings.ts"), - file("change", "server/ws.ts"), - file("change", "server/device/Host.test.ts"), - file("change", "web/settings.test.ts"), - ]).map((entry) => entry.name), - ).toEqual([ - "server/device/Host.ts", - "server/device/Host.test.ts", - "server/ws.ts", - "web/settings.ts", - "web/settings.test.ts", - ]); - }); -}); - describe("buildDiffFileTreeUpdates", () => { it("adds a new file's directories before the file", () => { expect(buildDiffFileTreeUpdates(["README.md"], ["README.md", "src/lib/a.ts"])).toEqual([ diff --git a/apps/web/src/components/diffs/diffFileTree.logic.ts b/apps/web/src/components/diffs/diffFileTree.logic.ts index 41d2a5e676e70..b819133d75da9 100644 --- a/apps/web/src/components/diffs/diffFileTree.logic.ts +++ b/apps/web/src/components/diffs/diffFileTree.logic.ts @@ -85,49 +85,6 @@ export function collectDirectoryPaths(paths: ReadonlyArray): ReadonlyArr return [...directories]; } -export function diffFileTreePositions(paths: ReadonlyArray): ReadonlyMap { - const positions = new Map(); - paths.forEach((path, index) => { - positions.set(path, index); - let directory = ""; - for (const segment of path.split("/").slice(0, -1)) { - directory += `${segment}/`; - if (!positions.has(directory)) positions.set(directory, index); - } - }); - return positions; -} - -// A flat list in tree order: each directory stays contiguous, siblings ranked as -// compareDiffFileTreeEntries ranks them, so the list never disagrees with the tree. -export function orderDiffFilesLikeTree( - files: ReadonlyArray, -): ReadonlyArray { - const paths = files.map(resolveFileDiffPath); - const positions = diffFileTreePositions(paths); - const keys = paths.map((path) => { - const key: number[] = []; - let directory = ""; - for (const segment of path.split("/").slice(0, -1)) { - directory += `${segment}/`; - key.push(positions.get(directory)!); - } - key.push(positions.get(path)!); - return key; - }); - return files - .map((file, index) => ({ file, key: keys[index]! })) - .toSorted((left, right) => { - const length = Math.min(left.key.length, right.key.length); - for (let index = 0; index < length; index++) { - const difference = left.key[index]! - right.key[index]!; - if (difference !== 0) return difference; - } - return left.key.length - right.key.length; - }) - .map(({ file }) => file); -} - export function compareDiffFileTreeEntries( getPositions: () => ReadonlyMap, ): FileTreeSortComparator { diff --git a/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx b/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx index a1c3404f25085..c847e55738405 100644 --- a/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx +++ b/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx @@ -81,8 +81,8 @@ import { } from "@t3tools/client-runtime/pull-request-editing"; import { fileDiffRows } from "@t3tools/client-runtime/review-guide-tour"; import { isTestChangedFile } from "@t3tools/shared/changedFileKind"; +import { orderDiffFilesForReview } from "@t3tools/client-runtime/diff-file-order"; import { isWorkspaceImagePreviewPath } from "@t3tools/shared/mediaPreview"; -import { orderDiffFiles } from "./pullRequestFileOrder.logic"; import { buildFileDiffIdentityKey, buildFileDiffRenderKey, @@ -116,7 +116,7 @@ import { DiffFileTree } from "../diffs/DiffFileTree"; import { FileExplorerPane } from "../files/FileExplorerPane"; import { useCodeViewFileReveal } from "../diffs/useCodeViewFileReveal"; import { useHideTestFiles } from "../diffs/useHideTestFiles"; -import { diffFileTreeEntries, orderDiffFilesLikeTree } from "../diffs/diffFileTree.logic"; +import { diffFileTreeEntries } from "../diffs/diffFileTree.logic"; import { StyledDiffCodeView } from "../diffs/StyledDiffCodeView"; import { Button } from "../ui/button"; import { Checkbox } from "../ui/checkbox"; @@ -261,10 +261,9 @@ function diffModel( }); const model: DiffModel = { parsedSlices, - loadedFiles: orderDiffFilesLikeTree( - parsedSlices.flatMap((parsed) => - parsed?.kind === "files" ? orderDiffFiles(parsed.files) : [], - ), + loadedFiles: orderDiffFilesForReview( + parsedSlices.flatMap((parsed) => (parsed?.kind === "files" ? parsed.files : [])), + resolveFileDiffPath, ), sourceFileStats: new Map( parsedSlices.flatMap((parsed) => diff --git a/packages/client-runtime/package.json b/packages/client-runtime/package.json index 900dfad694aba..003abc03ac65f 100644 --- a/packages/client-runtime/package.json +++ b/packages/client-runtime/package.json @@ -59,6 +59,10 @@ "types": "./src/imageAttachmentSize.ts", "default": "./src/imageAttachmentSize.ts" }, + "./diff-file-order": { + "types": "./src/diffFileOrder.ts", + "default": "./src/diffFileOrder.ts" + }, "./handoff": { "types": "./src/handoff.ts", "default": "./src/handoff.ts" diff --git a/apps/web/src/components/pullRequest/pullRequestFileOrder.logic.test.ts b/packages/client-runtime/src/diffFileOrder.test.ts similarity index 75% rename from apps/web/src/components/pullRequest/pullRequestFileOrder.logic.test.ts rename to packages/client-runtime/src/diffFileOrder.test.ts index 0626e463d751a..c00579ac63f16 100644 --- a/apps/web/src/components/pullRequest/pullRequestFileOrder.logic.test.ts +++ b/packages/client-runtime/src/diffFileOrder.test.ts @@ -1,17 +1,22 @@ -import type { FileDiffMetadata } from "@pierre/diffs"; import { describe, expect, it } from "vite-plus/test"; -import { orderDiffFiles } from "./pullRequestFileOrder.logic"; +import { orderDiffFilesForReview } from "./diffFileOrder.ts"; -function file(name: string, additionLines: ReadonlyArray = []): FileDiffMetadata { - return { name, hunks: [], additionLines, deletionLines: [] } as unknown as FileDiffMetadata; +interface TestFile { + readonly name: string; + readonly additionLines: ReadonlyArray; + readonly deletionLines: ReadonlyArray; } -function order(files: ReadonlyArray): Array { - return orderDiffFiles(files).map((entry) => entry.name); +function file(name: string, additionLines: ReadonlyArray = []): TestFile { + return { name, additionLines, deletionLines: [] }; } -describe("orderDiffFiles", () => { +function order(files: ReadonlyArray): Array { + return orderDiffFilesForReview(files, (entry) => entry.name).map((entry) => entry.name); +} + +describe("orderDiffFilesForReview", () => { it("places source before tests and generated files across path conventions", () => { const source = ["src/app.ts", "src/dist.ts", "src/testing.ts"]; const tests = [ @@ -33,7 +38,42 @@ describe("orderDiffFiles", () => { ]; expect( order([...generated, ...tests, ...source].toReversed().map((path) => file(path))), - ).toEqual([...source, ...tests, ...generated]); + ).toEqual([ + ...source, + ...tests.slice(0, 3), + // Generated files under src/ stay in src/ so the list matches the tree. + "src/__snapshots__/app.ts", + "src/api.generated.ts", + "src/app.test.ts.snap", + ...tests.slice(3), + ...generated.slice(0, 5), + ]); + }); + + it("keeps both entries of a path that changed type, such as a file replaced by a symlink", () => { + const deleted = { ...file("AGENTS.md"), additionLines: [], deletionLines: ["# Agents"] }; + const added = file("AGENTS.md", ["CLAUDE.md"]); + expect( + orderDiffFilesForReview([file("CLAUDE.md"), deleted, added], (entry) => entry.name), + ).toEqual([deleted, added, file("CLAUDE.md")]); + }); + + it("pulls a test listed last into its directory, keeping the first-seen order", () => { + expect( + order([ + file("server/device/Host.ts"), + file("web/settings.ts"), + file("server/ws.ts"), + file("server/device/Host.test.ts"), + file("web/settings.test.ts"), + ]), + ).toEqual([ + "server/device/Host.ts", + "server/device/Host.test.ts", + "server/ws.ts", + "web/settings.ts", + "web/settings.test.ts", + ]); }); it("resolves a specifier that climbs out of the importer's directory", () => { diff --git a/apps/web/src/components/pullRequest/pullRequestFileOrder.logic.ts b/packages/client-runtime/src/diffFileOrder.ts similarity index 68% rename from apps/web/src/components/pullRequest/pullRequestFileOrder.logic.ts rename to packages/client-runtime/src/diffFileOrder.ts index 41ee82ebdf85e..0fbe3c057eaff 100644 --- a/apps/web/src/components/pullRequest/pullRequestFileOrder.logic.ts +++ b/packages/client-runtime/src/diffFileOrder.ts @@ -1,8 +1,9 @@ -import type { FileDiffMetadata } from "@pierre/diffs"; - -import { resolveFileDiffPath } from "~/lib/diffRendering"; +interface OrderableDiffFile { + readonly additionLines: ReadonlyArray; + readonly deletionLines: ReadonlyArray; +} -export type DiffFileTier = "source" | "test" | "generated"; +type DiffFileTier = "source" | "test" | "generated"; const GENERATED_FILE_NAMES = new Set([ "pnpm-lock.yaml", @@ -139,11 +140,16 @@ function testedSourcePosition(path: string, sourcePositions: ReadonlyMap, -): ReadonlyArray { - const byPath = new Map(); - for (const file of files) byPath.set(resolveFileDiffPath(file), file); +function orderByImportsAndTier( + files: ReadonlyArray, + pathOf: (file: F) => string, +): ReadonlyArray { + // A type change (file to symlink) is a delete and an add under one path; keep both. + const byPath = new Map(); + for (const file of files) { + const path = pathOf(file); + byPath.set(path, [...(byPath.get(path) ?? []), file]); + } const tiers = new Map(); for (const path of byPath.keys()) tiers.set(path, diffFileTier(path)); @@ -161,16 +167,10 @@ export function orderDiffFiles( const imports = new Map>(); for (const path of sourcePaths) { - const file = byPath.get(path)!; - imports.set( - path, - importedPaths( - path, - [...file.additionLines, ...file.deletionLines], - byModulePath, - byModuleName, - ), - ); + const lines = byPath + .get(path)! + .flatMap((file) => [...file.additionLines, ...file.deletionLines]); + imports.set(path, importedPaths(path, lines, byModulePath, byModuleName)); } const orderedSource = orderByImports(sourcePaths, imports); @@ -192,5 +192,59 @@ export function orderDiffFiles( .filter((path) => tiers.get(path) === "generated") .sort((left, right) => left.localeCompare(right)); - return [...orderedSource, ...orderedTests, ...orderedGenerated].map((path) => byPath.get(path)!); + return [...orderedSource, ...orderedTests, ...orderedGenerated].flatMap((path) => + byPath.get(path)!, + ); +} + +/** Where each file, and each directory (with a trailing slash), first appears in `paths`. */ +export function diffFileTreePositions(paths: ReadonlyArray): ReadonlyMap { + const positions = new Map(); + paths.forEach((path, index) => { + positions.set(path, index); + let directory = ""; + for (const segment of path.split("/").slice(0, -1)) { + directory += `${segment}/`; + if (!positions.has(directory)) positions.set(directory, index); + } + }); + return positions; +} + +function orderLikeTree(files: ReadonlyArray, pathOf: (file: F) => string): ReadonlyArray { + const paths = files.map(pathOf); + const positions = diffFileTreePositions(paths); + const keys = paths.map((path) => { + const key: number[] = []; + let directory = ""; + for (const segment of path.split("/").slice(0, -1)) { + directory += `${segment}/`; + key.push(positions.get(directory)!); + } + key.push(positions.get(path)!); + return key; + }); + return files + .map((file, index) => ({ file, key: keys[index]! })) + .sort((left, right) => { + const length = Math.min(left.key.length, right.key.length); + for (let index = 0; index < length; index++) { + const difference = left.key[index]! - right.key[index]!; + if (difference !== 0) return difference; + } + return left.key.length - right.key.length; + }) + .map(({ file }) => file); +} + +/** + * Review order shared by every client: dependencies before dependents, tests after their source, + * generated files last, then regrouped so each directory stays contiguous and a file tree built + * from `diffFileTreePositions` lists files in the same order. + */ +export function orderDiffFilesForReview( + files: ReadonlyArray, + pathOf: (file: F) => string, +): ReadonlyArray { + return orderLikeTree(orderByImportsAndTier(files, pathOf), pathOf); } From 6b6950adfe2ea03b31894829ac8bfb369c9c35a2 Mon Sep 17 00:00:00 2001 From: Victor Date: Thu, 19 Nov 2026 16:22:44 -0600 Subject: [PATCH 82/97] fix(mobile): Android diff word highlights sit on the changed characters (#33568) Co-authored-by: Julius Marminge --- .../t3reviewdiff/ReviewDiffCanvasDrawing.kt | 177 ++++++++++-------- .../modules/t3reviewdiff/T3ReviewDiffView.kt | 5 +- .../t3reviewdiff/ReviewDiffGeometryTest.kt | 82 ++++++++ 3 files changed, 188 insertions(+), 76 deletions(-) diff --git a/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/ReviewDiffCanvasDrawing.kt b/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/ReviewDiffCanvasDrawing.kt index 2f1e4d9fd4a43..d86861018c77d 100644 --- a/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/ReviewDiffCanvasDrawing.kt +++ b/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/ReviewDiffCanvasDrawing.kt @@ -221,6 +221,7 @@ internal class ReviewDiffCanvasDrawing(context: Context) { private var measuredContentWidth = 0 private var asciiCharacterWidth = 0f private var asciiFixedPitch = false + private var wordDiffLefts = FloatArray(0) fun tokensChangeWidth( previous: Map>, @@ -332,14 +333,58 @@ internal class ReviewDiffCanvasDrawing(context: Context) { configureMonospacePaint(theme.hunkText, style.hunkFontSizePx, style.hunkFontWeight) return textPaint.measureText(row.text.ifEmpty { row.content }) } - val runs = if (tokens.isNullOrEmpty()) listOf(DiffToken(row.content, null, 0)) else tokens - var width = 0f - // Match drawCode's run boundaries and fonts, including fallback glyphs and tabs. - for (run in runs) { - configureCodePaint(run.color ?: theme.text, run.fontStyle, style) - width += textPaint.measureText(run.content) + val lines = CodeWrapLayout.NONE.lines(row) + return forEachCodePiece(row, tokens, style, lines) { text, start, end, _, _, _, _ -> + textPaint.measureText(text, start, end) } - return width + } + + /** Row width, highlights and drawCode share these drawText pieces so their positions agree. */ + private inline fun forEachCodePiece( + row: DiffRow, + tokens: List?, + style: DiffStyle, + lines: CodeLines, + piece: ( + text: String, + start: Int, + end: Int, + tokenStart: Int, + x: Float, + line: Int, + note: Boolean + ) -> Float + ): Float { + val noteStart = row.noteStart ?: Int.MAX_VALUE + var line = 0 + var x = 0f + var tokenStart = 0 + val runCount = if (tokens.isNullOrEmpty()) 1 else tokens.size + for (index in 0 until runCount) { + val run = tokens?.getOrNull(index) + val text = run?.content ?: row.content + var start = 0 + while (start < text.length) { + while (line + 1 < lines.starts.size && lines.starts[line + 1] <= tokenStart + start) { + line += 1 + x = 0f + } + val note = tokenStart + start >= noteStart + var end = min(text.length, lines.end(line, Int.MAX_VALUE) - tokenStart) + if (!note) end = min(end, noteStart - tokenStart) + if (start == 0 || tokenStart + start == noteStart) { + configureCodePaint( + if (note) theme.warningText else run?.color ?: theme.text, + run?.fontStyle ?: 0, + style, + ) + } + x += piece(text, start, end, tokenStart, x, line, note) + start = end + } + tokenStart += text.length + } + return x } fun lineNumberColor(change: String): Int = when (change) { @@ -368,34 +413,55 @@ internal class ReviewDiffCanvasDrawing(context: Context) { fun drawWordDiffRanges( canvas: Canvas, row: DiffRow, + tokens: List?, codeX: Float, top: Int, bottom: Int, - lines: CodeLines + lines: CodeLines, + style: DiffStyle ) { - if (lines.nativeLayout != null) return - if (row.wordDiffRanges.isEmpty() || (row.change != "add" && row.change != "delete")) return + val changed = row.change == "add" || row.change == "delete" + if (lines.nativeLayout != null || row.wordDiffRanges.isEmpty() || !changed) return val color = if (row.change == "add") theme.addBar else theme.deleteBar backgroundPaint.color = withAlpha(color, 71) - val characterWidth = textPaint.measureText("M") + configureCodePaint(theme.text, 0, style) val fontHeight = textPaint.fontMetrics.run { descent - ascent } val highlightHeight = max(4f * density, min(bottom - top - 4f * density, fontHeight)) val highlightTop = (top + bottom - highlightHeight) / 2f - row.wordDiffRanges.forEach { range -> - lines.starts.forEachIndexed { line, lineStart -> - val start = max(range.start, lineStart) - val end = min(range.end, lines.end(line, Int.MAX_VALUE)) - if (end <= start) return@forEachIndexed - val left = codeX + (start - lineStart) * characterWidth - val right = max(left + 2f * density, left + (end - start) * characterWidth) - val lineTop = highlightTop + line * lines.height - canvas.drawRoundRect( - RectF(left, lineTop, right, lineTop + highlightHeight), - 3f * density, - 3f * density, - backgroundPaint, - ) + if (wordDiffLefts.size < row.wordDiffRanges.size) { + wordDiffLefts = FloatArray(row.wordDiffRanges.size) + } + val lefts = wordDiffLefts + val lastEnd = row.wordDiffRanges.maxOf { it.end } + forEachCodePiece(row, tokens, style, lines) { text, start, end, tokenStart, x, line, _ -> + val pieceX = codeX + x + val advance = textPaint.measureText(text, start, end) + + // Inside a piece an edge keeps its kerning and clusters, as drawText shapes the whole piece; + // the piece's end is where drawCode starts the next one. + fun edge(at: Int) = if (at == end) { + pieceX + advance + } else { + pieceX + textPaint.getRunAdvance(text, start, end, start, end, false, at) + } + row.wordDiffRanges.forEachIndexed { index, range -> + val left = max(range.start, lines.starts[line]) - tokenStart + val right = min(range.end, lines.end(line, Int.MAX_VALUE)) - tokenStart + if (right <= left) return@forEachIndexed + if (left in start until end) lefts[index] = edge(left) + if (right in start + 1..end) { + val lineTop = highlightTop + line * lines.height + val rightX = max(lefts[index] + 2f * density, edge(right)) + canvas.drawRoundRect( + RectF(lefts[index], lineTop, rightX, lineTop + highlightHeight), + 3f * density, + 3f * density, + backgroundPaint, + ) + } } + if (tokenStart + end >= lastEnd) return + advance } } @@ -417,35 +483,19 @@ internal class ReviewDiffCanvasDrawing(context: Context) { canvas.restore() return } - val runs = if (tokens.isNullOrEmpty()) listOf(DiffToken(row.content, null, 0)) else tokens - var line = 0 - var x = codeX - var column = 0 - splitAtNote(runs, row.noteStart).forEach { (run, note) -> - configureCodePaint( - if (note) theme.warningText else run.color ?: theme.text, - run.fontStyle, - style, - ) - var start = 0 - while (start < run.content.length) { - while (line + 1 < lines.starts.size && lines.starts[line + 1] <= column + start) { - line += 1 - x = codeX - } - val end = min(run.content.length, lines.end(line, Int.MAX_VALUE) - column) - val lineBaseline = baseline + line * lines.height - if (lineBaseline + textPaint.fontMetrics.descent >= canvas.clipBounds.top && - lineBaseline + textPaint.fontMetrics.ascent <= canvas.clipBounds.bottom - ) { - val segmentWidth = textPaint.measureText(run.content, start, end) - fillNote(canvas, note, x, x + segmentWidth, lineBaseline) - canvas.drawText(run.content, start, end, x, lineBaseline, textPaint) - x += segmentWidth - } - start = end + forEachCodePiece(row, tokens, style, lines) { text, start, end, _, x, line, note -> + val lineBaseline = baseline + line * lines.height + if (lineBaseline + textPaint.fontMetrics.descent >= canvas.clipBounds.top && + lineBaseline + textPaint.fontMetrics.ascent <= canvas.clipBounds.bottom + ) { + val left = codeX + x + val segmentWidth = textPaint.measureText(text, start, end) + fillNote(canvas, note, left, left + segmentWidth, lineBaseline) + canvas.drawText(text, start, end, left, lineBaseline, textPaint) + segmentWidth + } else { + 0f } - column += run.content.length } } @@ -553,24 +603,3 @@ private object ReviewDiffTypefaces { else -> regular } } - -/** Splits color runs where a cut line's note starts; the flag marks the note's runs. */ -private fun splitAtNote(runs: List, noteStart: Int?): List> { - if (noteStart == null) return runs.map { it to false } - return buildList { - var offset = 0 - for (run in runs) { - val end = offset + run.content.length - when { - end <= noteStart -> add(run to false) - offset >= noteStart -> add(run to true) - else -> { - val cut = noteStart - offset - add(run.copy(content = run.content.substring(0, cut)) to false) - add(run.copy(content = run.content.substring(cut)) to true) - } - } - offset = end - } - } -} diff --git a/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/T3ReviewDiffView.kt b/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/T3ReviewDiffView.kt index 91bb6719ed8fa..8b0a84a952caf 100644 --- a/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/T3ReviewDiffView.kt +++ b/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/T3ReviewDiffView.kt @@ -1329,9 +1329,10 @@ private class DiffCanvasView(context: Context) : View(context) { val firstLineBottom = top + lines.firstHeight(style.rowHeightPx.toInt()) drawScrollableCode(canvas, top, bottom) { codeX -> drawing.configureCodePaint(theme.text, 0, style) - drawing.drawWordDiffRanges(canvas, row, codeX, top, firstLineBottom, lines) val baseline = lines.baseline(top, firstLineBottom, textPaint) - drawing.drawCode(canvas, row, tokensByRowId[row.id], codeX, baseline, style, lines) + val tokens = tokensByRowId[row.id] + drawing.drawWordDiffRanges(canvas, row, tokens, codeX, top, firstLineBottom, lines, style) + drawing.drawCode(canvas, row, tokens, codeX, baseline, style, lines) } drawLineNumber(canvas, row, top, firstLineBottom) diff --git a/apps/mobile/modules/t3-review-diff/tests/android/src/test/kotlin/expo/modules/t3reviewdiff/ReviewDiffGeometryTest.kt b/apps/mobile/modules/t3-review-diff/tests/android/src/test/kotlin/expo/modules/t3reviewdiff/ReviewDiffGeometryTest.kt index beac68f8e5357..f2992979bf522 100644 --- a/apps/mobile/modules/t3-review-diff/tests/android/src/test/kotlin/expo/modules/t3reviewdiff/ReviewDiffGeometryTest.kt +++ b/apps/mobile/modules/t3-review-diff/tests/android/src/test/kotlin/expo/modules/t3reviewdiff/ReviewDiffGeometryTest.kt @@ -1,6 +1,12 @@ package expo.modules.t3reviewdiff +import android.graphics.Bitmap +import android.graphics.Canvas import android.graphics.Color +import android.graphics.Paint +import android.graphics.RectF +import android.text.StaticLayout +import android.text.TextPaint import android.view.View import kotlin.math.ceil import expo.modules.kotlin.AppContext @@ -177,6 +183,82 @@ class ReviewDiffGeometryTest { } } + @Test + fun unwrappedWordDiffHighlightsCoverTheTextDrawCodeDraws() { + val drawing = ReviewDiffCanvasDrawing(RuntimeEnvironment.getApplication()) + val boxes = mutableListOf() + val texts = mutableMapOf() + val paints = mutableMapOf() + val bitmap = Bitmap.createBitmap(1000, 60, Bitmap.Config.ARGB_8888) + val canvas = object : Canvas(bitmap) { + override fun drawRoundRect(rect: RectF, rx: Float, ry: Float, paint: Paint) { + boxes += RectF(rect) + } + + override fun drawText( + text: String, + start: Int, + end: Int, + x: Float, + y: Float, + paint: Paint + ) { + texts[text.substring(start, end)] = x + paints[text.substring(start, end)] = TextPaint(paint) + } + } + + // The framework's caret position in the piece drawCode drew, kerning included. + fun caret(piece: String, offset: Int): Float { + val layout = StaticLayout.Builder.obtain(piece, 0, piece.length, paints.getValue(piece), 1000) + return texts.getValue(piece) + layout.build().getPrimaryHorizontal(offset) + } + val lines = CodeLines(intArrayOf(0), 0) + for (weight in listOf("medium", "regular")) { + val style = DiffStyle.defaults(1f).copy(codeFontWeight = weight, codeFontSizePx = 17f) + for (prefix in listOf("if ", "说明 ", "😀 ")) { + val tokens = listOf( + DiffToken(prefix, Color.RED, 2), + DiffToken("go ", Color.BLUE, 0), + DiffToken("1.27.3", Color.GREEN, 0), + DiffToken(";", Color.BLUE, 0), + DiffToken(" LTP.", Color.BLUE, 0), + DiffToken(" AV", Color.GREEN, 0), + DiffToken("LP.", Color.BLUE, 0), + ) + val content = tokens.joinToString("") { it.content } + val start = content.indexOf("1.27.3") + val kerned = content.indexOf("TP") + val crossing = content.indexOf("VLP") + val row = row("line", content).copy( + wordDiffRanges = listOf( + DiffWordDiffRange(start, start + "1.27.3".length), + DiffWordDiffRange(kerned, kerned + 2), + DiffWordDiffRange(crossing, crossing + 3), + ), + ) + boxes.clear() + texts.clear() + paints.clear() + drawing.configureCodePaint(Color.BLACK, 0, style) + drawing.drawWordDiffRanges(canvas, row, tokens, 10f, 0, 40, lines, style) + drawing.drawCode(canvas, row, tokens, 10f, 28f, style, lines) + assertEquals(3, boxes.size) + val (box, kernedBox, crossingBox) = boxes + val case = "weight=$weight prefix=$prefix" + assertEquals("$case left", requireNotNull(texts["1.27.3"]), box.left, 0.5f) + assertEquals("$case right", requireNotNull(texts[";"]), box.right, 0.5f) + val unkerned = texts.getValue(" LTP.") + paints.getValue(" LTP.").measureText(" L") + if (weight == "medium") assertTrue("$case L and T kern", caret(" LTP.", 2) < unkerned - 1f) + assertEquals("$case kerned left", caret(" LTP.", 2), kernedBox.left, 0.5f) + assertEquals("$case kerned right", caret(" LTP.", 4), kernedBox.right, 0.5f) + assertEquals("$case crossing left", caret(" AV", 2), crossingBox.left, 0.5f) + assertEquals("$case crossing right", caret("LP.", 2), crossingBox.right, 0.5f) + } + } + bitmap.recycle() + } + @Test fun lazyAsciiHeightAndLineStartsMatchTheExistingLayoutAtEveryBoundary() { val drawing = ReviewDiffCanvasDrawing(RuntimeEnvironment.getApplication()) From 57db750b8f379d6656ad774b11bb6039094ca873 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 19 Nov 2026 14:46:32 -0800 Subject: [PATCH 83/97] fix(server): Copilot subagent thinking and replies reach the subagent thread (#38896) --- .../Adapters/AcpAdapterV2.test.ts | 15 +++++++++++++-- .../src/server/copilotAcp.ts | 11 +++++++++-- 2 files changed, 22 insertions(+), 4 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts index cc56b4c29abdf..c3d54f06719fa 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts @@ -4222,6 +4222,17 @@ describe("AcpAdapterV2", () => { }), ), ); + // Copilot 1.0.114 names the subagent only by agentId, on the delta and the chunk. + const agentChunk = (text: string, agentId: string) => + raw("assistant.message_delta", { deltaContent: text }, agentId).pipe( + Effect.andThen( + update({ + sessionUpdate: "agent_message_chunk", + content: { type: "text", text }, + _meta: { "github.com/copilot": { agentId } }, + }), + ), + ); const launch = (toolCallId: string, description: string, mode: string) => update({ sessionUpdate: "tool_call", @@ -4259,10 +4270,10 @@ describe("AcpAdapterV2", () => { _meta: { "github.com/copilot": { agentId: "agent-a" } }, }); yield* chunk("`a.txt` says", "task-a"); - yield* chunk("`b.txt` has", "task-b"); + yield* agentChunk("`b.txt` has", "agent-b"); yield* chunk(" hello.", "task-a"); yield* chunk("a.txt b.txt", "task-bg"); - yield* chunk(" three lines.", "task-b"); + yield* agentChunk(" three lines.", "agent-b"); for (const [task, agent, text] of [ ["task-a", "agent-a", "`a.txt` says hello."], ["task-b", "agent-b", "`b.txt` has three lines."], diff --git a/packages/provider-acp-registry/src/server/copilotAcp.ts b/packages/provider-acp-registry/src/server/copilotAcp.ts index 44723c79dc1d5..6594e5036cb02 100644 --- a/packages/provider-acp-registry/src/server/copilotAcp.ts +++ b/packages/provider-acp-registry/src/server/copilotAcp.ts @@ -109,12 +109,19 @@ export function makeCopilotSubagentRouting() { const registerExtensions = (context: AcpAdapterV2ExtensionContext) => context.runtime.handleExtNotification(COPILOT_SESSION_EVENT, CopilotSessionEvent, (event) => { const data = event.data ?? {}; - const task = typeof data.parentToolCallId === "string" ? data.parentToolCallId : undefined; switch (event.type) { case "assistant.message_delta": case "assistant.reasoning_delta": { if (typeof data.deltaContent !== "string") return Effect.void; - session(event.sessionId).delta = { + const current = session(event.sessionId); + // Copilot 1.0.114+ names a subagent's deltas only by agentId, without parentToolCallId. + const task = + typeof data.parentToolCallId === "string" + ? data.parentToolCallId + : event.agentId === undefined + ? undefined + : current.taskByAgentId.get(event.agentId); + current.delta = { kind: event.type, text: data.deltaContent, ...(task === undefined ? {} : { task }), From cb391b5b5741553ef136d93486a3f6cf89d0c026 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 19 Nov 2026 14:54:21 -0800 Subject: [PATCH 84/97] fix(server): agent activity publish keeps retrying after a network drop (#39402) --- .../src/relay/AgentAwarenessRelay.test.ts | 47 +++++++++++++++++-- apps/server/src/relay/AgentAwarenessRelay.ts | 16 +++++-- 2 files changed, 55 insertions(+), 8 deletions(-) diff --git a/apps/server/src/relay/AgentAwarenessRelay.test.ts b/apps/server/src/relay/AgentAwarenessRelay.test.ts index 5cde458a1cd30..da3b0f30a99cb 100644 --- a/apps/server/src/relay/AgentAwarenessRelay.test.ts +++ b/apps/server/src/relay/AgentAwarenessRelay.test.ts @@ -291,9 +291,13 @@ const makeTestRelay = Effect.fnUntraced(function* ( authorization: new Headers(init?.headers).get("authorization"), state: payload.state, }); - return Promise.resolve( - options.respond?.(publications.length) ?? Response.json({ ok: true, deliveries: [] }), - ); + try { + return Promise.resolve( + options.respond?.(publications.length) ?? Response.json({ ok: true, deliveries: [] }), + ); + } catch (error) { + return Promise.reject(error); + } }, { preconnect: () => {} }, ); @@ -972,6 +976,43 @@ describe("AgentAwarenessRelay", () => { }), ); + it.effect("delivers a completion once the network returns after the retry budget runs out", () => + Effect.gen(function* () { + let networkUp = true; + const delivered: Array = []; + const { relay, currentShell, publications } = yield* makeTestRelay({ + respond: (attempt) => { + if (!networkUp) throw new TypeError("fetch failed: getaddrinfo EAI_AGAIN"); + delivered.push(publications[attempt - 1]?.state?.phase ?? null); + return Response.json({ ok: true, deliveries: [] }); + }, + }); + yield* relay.publishThread(THREAD_ID); + networkUp = false; + yield* Ref.set(currentShell, shell({ status: "completed" })); + yield* relay.publishThread(THREAD_ID); + yield* TestClock.adjust("5 seconds"); + yield* relay.drain; + for (const delay of [ + "1 second", + "2 seconds", + "4 seconds", + "8 seconds", + "16 seconds", + ] as const) { + yield* TestClock.adjust(delay); + yield* relay.drain; + } + assert.equal(publications.length, 7); + assert.deepEqual(delivered, ["running"]); + + networkUp = true; + yield* TestClock.adjust("10 minutes"); + yield* relay.drain; + assert.deepEqual(delivered, ["running", "completed"]); + }), + ); + it.effect("keeps settled live work until its awaited monitor finishes", () => Effect.gen(function* () { const { relay, currentShell, publications } = yield* makeTestRelay(); diff --git a/apps/server/src/relay/AgentAwarenessRelay.ts b/apps/server/src/relay/AgentAwarenessRelay.ts index 75e84e7bb8c96..c9f38ed345ae9 100644 --- a/apps/server/src/relay/AgentAwarenessRelay.ts +++ b/apps/server/src/relay/AgentAwarenessRelay.ts @@ -205,6 +205,8 @@ function resolveAgentActivityPublishingStartupState(input: { const RELAY_AGENT_ACTIVITY_DETAIL_MAX_LENGTH = 160; const REDACTED_RELAY_AGENT_FAILURE_DETAIL = "The agent run failed."; const RELAY_AGENT_ACTIVITY_RETRY_DELAYS_MS = [1_000, 2_000, 4_000, 8_000, 16_000] as const; +// Nothing else re-queues a thread when the network returns, so a lost terminal state is retried until it lands. +const RELAY_AGENT_ACTIVITY_STEADY_RETRY_DELAY_MS = 60_000; function sanitizeRelayAgentActivityState( state: RelayAgentActivityState | null, @@ -820,11 +822,15 @@ export const make = Effect.gen(function* () { schedulePublishRetry = Effect.fnUntraced(function* (threadId: ThreadId) { const attempts = publishRetries.get(threadId)?.attempts ?? 0; - const delayMs = RELAY_AGENT_ACTIVITY_RETRY_DELAYS_MS[attempts]; - if (delayMs === undefined) { - // Retain exhausted budgets until activity or success resets them; old timers must not restart retries. - yield* Effect.logWarning("agent activity publish retry budget exhausted", { threadId }); - return; + const delayMs = + RELAY_AGENT_ACTIVITY_RETRY_DELAYS_MS[attempts] ?? RELAY_AGENT_ACTIVITY_STEADY_RETRY_DELAY_MS; + if (attempts === RELAY_AGENT_ACTIVITY_RETRY_DELAYS_MS.length) { + yield* Effect.logWarning( + "agent activity publish retry budget exhausted; retrying every minute", + { + threadId, + }, + ); } const retry = { attempts: attempts + 1, From 2bba2564cafd651a1ca36de1b2b8492ad9124498 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 19 Nov 2026 15:03:47 -0800 Subject: [PATCH 85/97] perf(server): thread shell item counts no longer sum every run the thread has had (#39391) --- .../orchestration-v2/ProjectionStore.test.ts | 4 + .../src/orchestration-v2/ProjectionStore.ts | 50 ++++---- apps/server/src/persistence/Migrations.ts | 2 + .../Migrations/102_ThreadItemCounts.test.ts | 89 ++++++++++++++ .../Migrations/102_ThreadItemCounts.ts | 112 ++++++++++++++++++ .../reconcileV2PreviewMigration.test.ts | 2 + 6 files changed, 235 insertions(+), 24 deletions(-) create mode 100644 apps/server/src/persistence/Migrations/102_ThreadItemCounts.test.ts create mode 100644 apps/server/src/persistence/Migrations/102_ThreadItemCounts.ts diff --git a/apps/server/src/orchestration-v2/ProjectionStore.test.ts b/apps/server/src/orchestration-v2/ProjectionStore.test.ts index dabe53aeae46f..79478def6dfd1 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.test.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.test.ts @@ -7178,6 +7178,10 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => { if (/^SEARCH (r|run) /.test(detail)) { assert.include(detail, "COVERING INDEX", detail); } + // A thread's item count reads one count row per hidden run, not one per run it had. + if (detail.startsWith("SEARCH counts ")) { + assert.include(detail, "run_key=?", detail); + } if (detail.includes("orchestration_v2_projection_turn_items")) { // Only held input is read from the sparse index; transcript history stays unread. assert.include( diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index 930639b5d6bbe..a8d06679c801a 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -8565,30 +8565,32 @@ export const layer: Layer.Layer = const selectShellItemCounts = (threadIds: ReadonlyArray) => sql` - SELECT counts.thread_id, - SUM(CASE WHEN counts.run_key = '' OR r.status <> 'rolled_back' - THEN counts.item_count - CASE - WHEN r.status IN ('queued', 'cancelled') THEN ( - SELECT COUNT(*) - FROM orchestration_v2_projection_turn_items held - INDEXED BY orchestration_v2_projection_turn_items_queued_input_idx - WHERE held.run_id = counts.run_key - AND held.type = 'user_message' - AND json_valid(held.payload_json) - AND json_extract(held.payload_json, '$.inputIntent') = 'queued_turn' - ) - ELSE 0 - END - ELSE 0 END) AS item_count, - SUM(CASE WHEN counts.run_key = '' THEN counts.item_count ELSE 0 END) - AS runless_item_count - FROM orchestration_v2_projection_turn_item_counts counts - -- The primary key would load each run's whole row just for its status. - LEFT JOIN orchestration_v2_projection_runs r - INDEXED BY orchestration_v2_projection_runs_run_status_idx - ON r.run_id = counts.run_key - WHERE counts.thread_id IN (SELECT value FROM json_each(${encodeIdList(threadIds)})) - GROUP BY counts.thread_id + -- Only the thread's hidden runs are visited, so settled history costs nothing here. + SELECT totals.thread_id, + totals.item_count - COALESCE(( + SELECT SUM(CASE WHEN r.status = 'rolled_back' THEN counts.item_count ELSE ( + SELECT COUNT(*) + FROM orchestration_v2_projection_turn_items held + INDEXED BY orchestration_v2_projection_turn_items_queued_input_idx + WHERE held.run_id = counts.run_key + AND held.type = 'user_message' + AND json_valid(held.payload_json) + AND json_extract(held.payload_json, '$.inputIntent') = 'queued_turn' + ) END) + FROM orchestration_v2_projection_runs r + INDEXED BY orchestration_v2_projection_runs_hidden_items_idx + JOIN orchestration_v2_projection_turn_item_counts counts + ON counts.thread_id = r.thread_id AND counts.run_key = r.run_id + WHERE r.thread_id = totals.thread_id + AND r.status IN ('rolled_back', 'queued', 'cancelled') + ), 0) AS item_count, + COALESCE(( + SELECT runless.item_count + FROM orchestration_v2_projection_turn_item_counts runless + WHERE runless.thread_id = totals.thread_id AND runless.run_key = '' + ), 0) AS runless_item_count + FROM orchestration_v2_projection_thread_item_counts totals + WHERE totals.thread_id IN (SELECT value FROM json_each(${encodeIdList(threadIds)})) `; const selectShellProviderThreadRows = (threadIds?: ReadonlyArray) => diff --git a/apps/server/src/persistence/Migrations.ts b/apps/server/src/persistence/Migrations.ts index c3fc7aacef055..6f0b74e029606 100644 --- a/apps/server/src/persistence/Migrations.ts +++ b/apps/server/src/persistence/Migrations.ts @@ -109,6 +109,7 @@ import Migration0098 from "./Migrations/098_ActiveShellIndexIndexes.ts"; import Migration0099 from "./Migrations/099_BackgroundRecoveryIndexes.ts"; import Migration0100 from "./Migrations/100_TurnStartReadIndexes.ts"; import Migration0101 from "./Migrations/101_DelegatedTaskReadIndexes.ts"; +import Migration0102 from "./Migrations/102_ThreadItemCounts.ts"; const migrationEntries = [ [1, "OrchestrationEvents", Migration0001], @@ -213,6 +214,7 @@ const migrationEntries = [ [99, "BackgroundRecoveryIndexes", Migration0099], [100, "TurnStartReadIndexes", Migration0100], [101, "DelegatedTaskReadIndexes", Migration0101], + [102, "ThreadItemCounts", Migration0102], ] as const; export const migrationManifest = migrationEntries.map(([id, name]) => [id, name] as const); diff --git a/apps/server/src/persistence/Migrations/102_ThreadItemCounts.test.ts b/apps/server/src/persistence/Migrations/102_ThreadItemCounts.test.ts new file mode 100644 index 0000000000000..678186e55b81c --- /dev/null +++ b/apps/server/src/persistence/Migrations/102_ThreadItemCounts.test.ts @@ -0,0 +1,89 @@ +import { assert, it } from "@effect/vitest"; +import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient"; +import * as Effect from "effect/Effect"; +import * as SqlClient from "effect/sql/SqlClient"; + +import { runMigrations } from "../Migrations.ts"; + +const layer = it.layer(NodeSqliteClient.layer({ filename: ":memory:" })); + +layer("102_ThreadItemCounts", (it) => { + it.effect("matches a recount of items without a run or with an existing run", () => + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + yield* runMigrations({ toMigrationInclusive: 101 }); + const upsertItem = (id: string, threadId: string, runId: string | null) => sql` + INSERT INTO orchestration_v2_projection_turn_items ( + turn_item_id, thread_id, run_id, ordinal, type, status, updated_at, payload_json + ) + VALUES ( + ${id}, ${threadId}, ${runId}, 1, 'assistant_message', 'completed', + '2026-11-19T00:00:00.000Z', '{}' + ) + ON CONFLICT(turn_item_id) DO UPDATE SET thread_id = excluded.thread_id, run_id = excluded.run_id + `; + const insertRun = (runId: string, threadId: string) => sql` + INSERT INTO orchestration_v2_projection_runs ( + run_id, thread_id, ordinal, provider, status, requested_at, payload_json + ) + VALUES ( + ${runId}, ${threadId}, + (SELECT COUNT(*) FROM orchestration_v2_projection_runs WHERE thread_id = ${threadId}), + 'codex', 'completed', '2026-11-19T00:00:00.000Z', '{}' + ) + `; + const totals = () => sql<{ readonly thread_id: string; readonly item_count: number }>` + SELECT thread_id, item_count FROM orchestration_v2_projection_thread_item_counts + ORDER BY thread_id + `; + const recount = () => sql<{ readonly thread_id: string; readonly item_count: number }>` + SELECT item.thread_id, COUNT(*) AS item_count + FROM orchestration_v2_projection_turn_items item + WHERE item.run_id IS NULL + OR EXISTS (SELECT 1 FROM orchestration_v2_projection_runs run WHERE run.run_id = item.run_id) + GROUP BY item.thread_id + ORDER BY item.thread_id + `; + const assertTotals = (expected: ReadonlyArray) => + Effect.gen(function* () { + const actual = yield* totals(); + assert.deepEqual(actual, yield* recount()); + assert.deepEqual( + actual.map((row) => [row.thread_id, row.item_count]), + expected.map(([threadId, count]) => [threadId, count]), + ); + }); + + yield* insertRun("run-1", "thread-1"); + yield* upsertItem("runless", "thread-1", null); + yield* upsertItem("run-1:a", "thread-1", "run-1"); + yield* upsertItem("late:a", "thread-1", "run-late"); + yield* runMigrations(); + yield* assertTotals([["thread-1", 2]]); + + yield* upsertItem("run-1:b", "thread-1", "run-1"); + yield* upsertItem("late:b", "thread-2", "run-late"); + yield* assertTotals([["thread-1", 3]]); + + yield* insertRun("run-late", "thread-1"); + yield* assertTotals([ + ["thread-1", 4], + ["thread-2", 1], + ]); + + yield* upsertItem("run-1:b", "thread-2", null); + yield* upsertItem("late:a", "thread-1", "run-missing"); + yield* assertTotals([ + ["thread-1", 2], + ["thread-2", 2], + ]); + + yield* sql`DELETE FROM orchestration_v2_projection_runs WHERE run_id = 'run-late'`; + yield* sql`DELETE FROM orchestration_v2_projection_turn_items WHERE turn_item_id = 'run-1:b'`; + yield* assertTotals([["thread-1", 2]]); + + yield* sql`DELETE FROM orchestration_v2_projection_turn_items WHERE thread_id = 'thread-1'`; + yield* assertTotals([]); + }), + ); +}); diff --git a/apps/server/src/persistence/Migrations/102_ThreadItemCounts.ts b/apps/server/src/persistence/Migrations/102_ThreadItemCounts.ts new file mode 100644 index 0000000000000..5cbfee859cd45 --- /dev/null +++ b/apps/server/src/persistence/Migrations/102_ThreadItemCounts.ts @@ -0,0 +1,112 @@ +import * as Effect from "effect/Effect"; +import * as SqlClient from "effect/sql/SqlClient"; + +/** + * One total per thread beside 085's per-run counts, so a shell read does not sum every run the + * thread has had. It holds the items without a run or with an existing run, the rows the shell + * read used to sum; the read still applies the run status rules. Triggers keep it exact. + */ +export default Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + + yield* sql` + CREATE TABLE orchestration_v2_projection_thread_item_counts ( + thread_id TEXT PRIMARY KEY, + item_count INTEGER NOT NULL + ) WITHOUT ROWID + `; + yield* sql` + INSERT INTO orchestration_v2_projection_thread_item_counts (thread_id, item_count) + SELECT counts.thread_id, SUM(counts.item_count) + FROM orchestration_v2_projection_turn_item_counts counts + WHERE counts.run_key = '' + OR EXISTS (SELECT 1 FROM orchestration_v2_projection_runs WHERE run_id = counts.run_key) + GROUP BY counts.thread_id + `; + + // The shell read subtracts only these runs. ProjectionStore.selectShellItemCounts must spell + // the same predicate for SQLite to use this partial index. + yield* sql` + CREATE INDEX IF NOT EXISTS orchestration_v2_projection_runs_hidden_items_idx + ON orchestration_v2_projection_runs(thread_id, status, run_id) + WHERE status IN ('rolled_back', 'queued', 'cancelled') + `; + + // 085's triggers upsert per-run counts, so an item write fires the insert or the update here. + yield* sql` + CREATE TRIGGER orchestration_v2_thread_item_counts_count_insert + AFTER INSERT ON orchestration_v2_projection_turn_item_counts + WHEN new.run_key = '' + OR EXISTS (SELECT 1 FROM orchestration_v2_projection_runs WHERE run_id = new.run_key) + BEGIN + INSERT INTO orchestration_v2_projection_thread_item_counts (thread_id, item_count) + VALUES (new.thread_id, new.item_count) + ON CONFLICT (thread_id) DO UPDATE SET item_count = item_count + excluded.item_count; + END + `; + yield* sql` + CREATE TRIGGER orchestration_v2_thread_item_counts_count_update + AFTER UPDATE ON orchestration_v2_projection_turn_item_counts + BEGIN + UPDATE orchestration_v2_projection_thread_item_counts + SET item_count = item_count - old.item_count + WHERE thread_id = old.thread_id + AND (old.run_key = '' + OR EXISTS (SELECT 1 FROM orchestration_v2_projection_runs WHERE run_id = old.run_key)); + INSERT INTO orchestration_v2_projection_thread_item_counts (thread_id, item_count) + SELECT new.thread_id, new.item_count + WHERE new.run_key = '' + OR EXISTS (SELECT 1 FROM orchestration_v2_projection_runs WHERE run_id = new.run_key) + ON CONFLICT (thread_id) DO UPDATE SET item_count = item_count + excluded.item_count; + DELETE FROM orchestration_v2_projection_thread_item_counts + WHERE thread_id = old.thread_id AND item_count <= 0; + END + `; + yield* sql` + CREATE TRIGGER orchestration_v2_thread_item_counts_count_delete + AFTER DELETE ON orchestration_v2_projection_turn_item_counts + WHEN old.run_key = '' + OR EXISTS (SELECT 1 FROM orchestration_v2_projection_runs WHERE run_id = old.run_key) + BEGIN + UPDATE orchestration_v2_projection_thread_item_counts + SET item_count = item_count - old.item_count + WHERE thread_id = old.thread_id; + DELETE FROM orchestration_v2_projection_thread_item_counts + WHERE thread_id = old.thread_id AND item_count <= 0; + END + `; + + // Items can be written before their run; they count from when it exists. + yield* sql` + CREATE TRIGGER orchestration_v2_thread_item_counts_run_insert + AFTER INSERT ON orchestration_v2_projection_runs + BEGIN + INSERT INTO orchestration_v2_projection_thread_item_counts (thread_id, item_count) + SELECT thread_id, COUNT(*) + FROM orchestration_v2_projection_turn_items + WHERE run_id = new.run_id + GROUP BY thread_id + ON CONFLICT (thread_id) DO UPDATE SET item_count = item_count + excluded.item_count; + END + `; + yield* sql` + CREATE TRIGGER orchestration_v2_thread_item_counts_run_delete + AFTER DELETE ON orchestration_v2_projection_runs + BEGIN + UPDATE orchestration_v2_projection_thread_item_counts + SET item_count = item_count - ( + SELECT COUNT(*) + FROM orchestration_v2_projection_turn_items item + WHERE item.run_id = old.run_id + AND item.thread_id = orchestration_v2_projection_thread_item_counts.thread_id + ) + WHERE thread_id IN ( + SELECT thread_id FROM orchestration_v2_projection_turn_items WHERE run_id = old.run_id + ); + DELETE FROM orchestration_v2_projection_thread_item_counts + WHERE item_count <= 0 AND thread_id IN ( + SELECT thread_id FROM orchestration_v2_projection_turn_items WHERE run_id = old.run_id + ); + END + `; +}); diff --git a/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts b/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts index b9feabbf89b88..1703789b6b479 100644 --- a/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts +++ b/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts @@ -81,6 +81,7 @@ describe("V2 preview upgrade", () => { [99, "BackgroundRecoveryIndexes"], [100, "TurnStartReadIndexes"], [101, "DelegatedTaskReadIndexes"], + [102, "ThreadItemCounts"], ]); assert.deepStrictEqual(yield* runMigrations(), []); assert.deepStrictEqual(yield* sql`SELECT * FROM orchestration_v2_legacy_imports`, imports); @@ -205,6 +206,7 @@ describe("V2 preview upgrade", () => { [99, "BackgroundRecoveryIndexes"], [100, "TurnStartReadIndexes"], [101, "DelegatedTaskReadIndexes"], + [102, "ThreadItemCounts"], ]); }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))), ); From 420d1b59003f5340624786e5e3c9e06d57db55b7 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 19 Nov 2026 15:09:06 -0800 Subject: [PATCH 86/97] feat(desktop): forward another environment's ports to this machine (#39393) Co-authored-by: Claude Opus 5.5 --- apps/desktop/src/ipc/channels.ts | 5 + apps/desktop/src/ipc/methods/preview.ts | 51 ++++ apps/desktop/src/preload.ts | 16 ++ .../src/preview/LoopbackTunnel.test.ts | 239 +++++++++++++++- apps/desktop/src/preview/LoopbackTunnel.ts | 254 +++++++++++++++++- apps/web/src/components/CommandPalette.tsx | 22 +- .../CommandPalettePortForwardItems.tsx | 215 +++++++++++++++ .../components/chat/ThreadServersPanel.tsx | 172 +++++++++--- apps/web/src/i18n/translations/de.json | 51 +++- apps/web/src/i18n/translations/en.json | 53 +++- apps/web/src/i18n/translations/es.json | 53 +++- apps/web/src/i18n/translations/fr.json | 53 +++- apps/web/src/i18n/translations/ja.json | 53 +++- apps/web/src/i18n/translations/ko.json | 51 +++- apps/web/src/i18n/translations/pt-BR.json | 51 +++- apps/web/src/i18n/translations/ru.json | 51 +++- apps/web/src/i18n/translations/sv.json | 53 +++- apps/web/src/i18n/translations/zh.json | 53 +++- apps/web/src/state/portForwards.ts | 152 +++++++++++ docs/user/remote-access.md | 17 ++ packages/client-runtime/src/state/session.ts | 1 + packages/contracts/src/ipc.ts | 25 +- 22 files changed, 1527 insertions(+), 164 deletions(-) create mode 100644 apps/web/src/components/CommandPalettePortForwardItems.tsx create mode 100644 apps/web/src/state/portForwards.ts diff --git a/apps/desktop/src/ipc/channels.ts b/apps/desktop/src/ipc/channels.ts index bb708a6ab7c88..4a99d52b0e79d 100644 --- a/apps/desktop/src/ipc/channels.ts +++ b/apps/desktop/src/ipc/channels.ts @@ -128,6 +128,11 @@ export const PREVIEW_OPEN_LINK_CHANNEL = "desktop:preview-open-link"; export const PREVIEW_FIND_RESULT_CHANNEL = "desktop:preview-find-result"; export const PREVIEW_TUNNEL_ACCESS_REQUEST_CHANNEL = "desktop:preview-tunnel-access-request"; export const PREVIEW_TUNNEL_ACCESS_RESOLVE_CHANNEL = "desktop:preview-tunnel-access-resolve"; +export const PORT_FORWARD_START_CHANNEL = "desktop:port-forward-start"; +export const PORT_FORWARD_STOP_CHANNEL = "desktop:port-forward-stop"; +export const PORT_FORWARD_LIST_CHANNEL = "desktop:port-forward-list"; +export const PORT_FORWARD_CHANGE_CHANNEL = "desktop:port-forward-change"; +export const PORT_FORWARD_SHARES_LOOPBACK_CHANNEL = "desktop:port-forward-shares-loopback"; export const MAC_PERMISSION_HELPER_CHANNEL = "desktop:mac-permission-helper"; diff --git a/apps/desktop/src/ipc/methods/preview.ts b/apps/desktop/src/ipc/methods/preview.ts index f06c26014f40e..9dc0465c1e55a 100644 --- a/apps/desktop/src/ipc/methods/preview.ts +++ b/apps/desktop/src/ipc/methods/preview.ts @@ -23,6 +23,9 @@ import { DesktopPreviewCreateTabInputSchema, DesktopPreviewTabInputSchema, DesktopPreviewTunnelAccessResolutionInputSchema, + DesktopPortForwardInputSchema, + DesktopPortForwardSchema, + DesktopSharesLoopbackInputSchema, DesktopPreviewWebviewConfigSchema, PreviewAnnotationSubmissionResultSchema, PreviewCaptureFailure, @@ -66,6 +69,10 @@ export const installPreviewEventForwarding = Effect.fn( yield* manager.subscribeFindResults((event) => electronWindow.sendAll(IpcChannels.PREVIEW_FIND_RESULT_CHANNEL, event), ); + const tunnel = yield* LoopbackTunnel.LoopbackTunnel; + yield* tunnel.subscribeForwards((forwards) => + electronWindow.sendAll(IpcChannels.PORT_FORWARD_CHANGE_CHANNEL, forwards), + ); }); const setForwardedShortcuts = DesktopIpc.makeIpcMethod({ @@ -379,6 +386,46 @@ const resolveTunnelAccess = DesktopIpc.makeIpcMethod({ }), }); +const forwardPort = DesktopIpc.makeIpcMethod({ + channel: IpcChannels.PORT_FORWARD_START_CHANNEL, + payload: DesktopPortForwardInputSchema, + result: DesktopPortForwardSchema, + handler: Effect.fn("desktop.ipc.preview.forwardPort")(function* (input) { + const tunnel = yield* LoopbackTunnel.LoopbackTunnel; + return yield* tunnel.forward(input); + }), +}); + +const stopPortForward = DesktopIpc.makeIpcMethod({ + channel: IpcChannels.PORT_FORWARD_STOP_CHANNEL, + payload: DesktopPortForwardInputSchema, + result: Schema.Void, + handler: Effect.fn("desktop.ipc.preview.stopPortForward")(function* (input) { + const tunnel = yield* LoopbackTunnel.LoopbackTunnel; + yield* tunnel.stopForward(input); + }), +}); + +const listPortForwards = DesktopIpc.makeIpcMethod({ + channel: IpcChannels.PORT_FORWARD_LIST_CHANNEL, + payload: Schema.Void, + result: Schema.Array(DesktopPortForwardSchema), + handler: Effect.fn("desktop.ipc.preview.listPortForwards")(function* () { + const tunnel = yield* LoopbackTunnel.LoopbackTunnel; + return yield* tunnel.forwards; + }), +}); + +const sharesLoopback = DesktopIpc.makeIpcMethod({ + channel: IpcChannels.PORT_FORWARD_SHARES_LOOPBACK_CHANNEL, + payload: DesktopSharesLoopbackInputSchema, + result: Schema.Boolean, + handler: Effect.fn("desktop.ipc.preview.sharesLoopback")(function* ({ environmentId }) { + const tunnel = yield* LoopbackTunnel.LoopbackTunnel; + return yield* tunnel.sharesLoopback(environmentId); + }), +}); + export const listBrowserImportSources = DesktopIpc.makeIpcMethod({ channel: IpcChannels.PREVIEW_IMPORT_SOURCES_CHANNEL, payload: Schema.Void, @@ -523,6 +570,10 @@ export const methods = [ clearCache, getPreviewConfig, resolveTunnelAccess, + forwardPort, + stopPortForward, + listPortForwards, + sharesLoopback, setAnnotationTheme, setAnnotationSendEnabled, pickElement, diff --git a/apps/desktop/src/preload.ts b/apps/desktop/src/preload.ts index b413656a15241..280c5ad6c6716 100644 --- a/apps/desktop/src/preload.ts +++ b/apps/desktop/src/preload.ts @@ -449,6 +449,22 @@ contextBridge.exposeInMainWorld("desktopBridge", { }, resolveTunnelAccess: (requestId, url) => ipcRenderer.invoke(IpcChannels.PREVIEW_TUNNEL_ACCESS_RESOLVE_CHANNEL, { requestId, url }), + forwardPort: (environmentId, remotePort) => + ipcRenderer.invoke(IpcChannels.PORT_FORWARD_START_CHANNEL, { environmentId, remotePort }), + stopPortForward: (environmentId, remotePort) => + ipcRenderer.invoke(IpcChannels.PORT_FORWARD_STOP_CHANNEL, { environmentId, remotePort }), + listPortForwards: () => ipcRenderer.invoke(IpcChannels.PORT_FORWARD_LIST_CHANNEL), + sharesLoopback: (environmentId) => + ipcRenderer.invoke(IpcChannels.PORT_FORWARD_SHARES_LOOPBACK_CHANNEL, { environmentId }), + onPortForwards: (listener) => { + const wrappedListener = (_event: Electron.IpcRendererEvent, forwards: unknown) => { + if (!Array.isArray(forwards)) return; + listener(forwards); + }; + ipcRenderer.on(IpcChannels.PORT_FORWARD_CHANGE_CHANNEL, wrappedListener); + return () => + ipcRenderer.removeListener(IpcChannels.PORT_FORWARD_CHANGE_CHANNEL, wrappedListener); + }, setAnnotationTheme: (theme) => ipcRenderer.invoke(IpcChannels.PREVIEW_SET_ANNOTATION_THEME_CHANNEL, { theme }), setAnnotationSendEnabled: (tabId, enabled) => diff --git a/apps/desktop/src/preview/LoopbackTunnel.test.ts b/apps/desktop/src/preview/LoopbackTunnel.test.ts index fb193e768e8d2..fe83817c0d5e8 100644 --- a/apps/desktop/src/preview/LoopbackTunnel.test.ts +++ b/apps/desktop/src/preview/LoopbackTunnel.test.ts @@ -1,5 +1,6 @@ import * as NodeFileSystem from "@effect/platform-node/NodeFileSystem"; import * as NodeWS from "@effect/platform-node/NodeWS"; +import { EnvironmentId } from "@t3tools/contracts"; import * as HostProcess from "@t3tools/shared/HostProcess"; import { expect, it } from "@effect/vitest"; import * as NodeNet from "node:net"; @@ -8,6 +9,8 @@ import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Queue from "effect/Queue"; +import * as Result from "effect/Result"; +import * as SecureRandom from "effect/crypto/SecureRandom"; import * as ElectronWindow from "../electron/ElectronWindow.ts"; import * as LoopbackTunnel from "./LoopbackTunnel.ts"; @@ -74,9 +77,10 @@ const unusedPort = Effect.promise( }), ); -/** Routes a stand-in session through the tunnel and returns its SOCKS listener port. */ -const routeThroughTunnel = ( - tunnelUrl: string | null, +/** The tunnel service, with every access request answered with `tunnelUrl`. */ +const makeTunnel = ( + /** A function answers each access request with its current value. */ + tunnelUrl: string | null | (() => string | null), host?: Layer.Layer | Layer.Layer, ) => Effect.gen(function* () { @@ -96,6 +100,7 @@ const routeThroughTunnel = ( currentMainOrFirst: Effect.succeedSome(window as unknown as Electron.BrowserWindow), }), NodeFileSystem.layer, + SecureRandom.layerWebCrypto, host ?? Layer.empty, ), ), @@ -103,10 +108,25 @@ const routeThroughTunnel = ( ); const tunnel = Context.get(services, LoopbackTunnel.LoopbackTunnel); yield* Queue.take(accessRequests).pipe( - Effect.flatMap((requestId) => tunnel.resolveAccess({ requestId, url: tunnelUrl })), + Effect.flatMap((requestId) => + tunnel.resolveAccess({ + requestId, + url: typeof tunnelUrl === "function" ? tunnelUrl() : tunnelUrl, + }), + ), Effect.forever, Effect.forkScoped, ); + return tunnel; + }); + +/** Routes a stand-in session through the tunnel and returns its SOCKS listener port. */ +const routeThroughTunnel = ( + tunnelUrl: string | null, + host?: Layer.Layer | Layer.Layer, +) => + Effect.gen(function* () { + const tunnel = yield* makeTunnel(tunnelUrl, host); let proxyRules = ""; const session = { setProxy: async (config: Electron.ProxyConfig) => { @@ -284,3 +304,214 @@ it.effect("connects straight to the environment's own forwarded origin port", () expect(received).toEqual([7, 8]); }), ); + +/** Connects to a local port, sends `bytes`, and resolves with the first chunk back. */ +const exchange = (port: number, bytes: Uint8Array) => + Effect.promise( + () => + new Promise((resolve, reject) => { + const socket = NodeNet.connect(port, "127.0.0.1", () => socket.write(bytes)); + socket.once("data", (chunk) => { + resolve([...chunk]); + socket.destroy(); + }); + socket.on("error", reject); + }), + ); + +const refusesConnections = (port: number) => + Effect.promise( + () => + new Promise((resolve) => { + const socket = NodeNet.connect(port, "127.0.0.1", () => { + socket.destroy(); + resolve(false); + }); + socket.on("error", () => resolve(true)); + }), + ); + +it.effect("forwards a port over the tunnel on the same local port until stopped", () => + Effect.gen(function* () { + const endpoint = yield* listenEndpoint; + const remotePort = yield* unusedPort; + const tunnel = yield* makeTunnel( + `ws://127.0.0.1:${addressPort(endpoint.server)}/api/preview/tunnel?wsTicket=t`, + ); + const announced: number[][] = []; + yield* tunnel.subscribeForwards((forwards) => + Effect.sync(() => announced.push(forwards.map((forward) => forward.localPort))), + ); + const environmentId = EnvironmentId.make("remote"); + const forward = yield* tunnel.forward({ environmentId, remotePort }); + expect(forward).toEqual({ environmentId, remotePort, localPort: remotePort }); + + expect(yield* exchange(remotePort, Uint8Array.of(4, 5))).toEqual([0xee, 4, 5]); + // The first request is the same-machine probe. + expect(endpoint.requests.at(-1)).toBe(`/api/preview/tunnel?wsTicket=t&port=${remotePort}`); + + yield* tunnel.stopForward({ environmentId, remotePort }); + expect(yield* refusesConnections(remotePort)).toBe(true); + expect(yield* tunnel.forwards).toEqual([]); + expect(announced).toEqual([[remotePort], []]); + }), +); + +it.effect("moves a forward to a free port when its own is taken here", () => + Effect.gen(function* () { + const decoy = yield* listenDecoy; + const endpoint = yield* listenEndpoint; + const remotePort = addressPort(decoy.server); + const tunnel = yield* makeTunnel( + `ws://127.0.0.1:${addressPort(endpoint.server)}/api/preview/tunnel`, + ); + const forward = yield* tunnel.forward({ + environmentId: EnvironmentId.make("remote"), + remotePort, + }); + expect(forward.localPort).not.toBe(remotePort); + + expect(yield* exchange(forward.localPort, Uint8Array.of(6))).toEqual([0xee, 6]); + expect(endpoint.requests.at(-1)).toBe(`/api/preview/tunnel?port=${remotePort}`); + expect(decoy.connections()).toBe(0); + }), +); + +/** An environment on this machine: each tunnel connection dials the requested local port. */ +const listenSameMachineEndpoint = Effect.acquireRelease( + Effect.promise( + () => + new Promise((resolve) => { + const server: NodeWS.WebSocketServer = new NodeWS.WebSocketServer( + { port: 0, host: "127.0.0.1" }, + () => resolve(server), + ); + server.on("connection", (socket: NodeWS.WebSocket, request: { url?: string }) => { + const port = Number(new URL(request.url ?? "", "ws://x").searchParams.get("port")); + const local = NodeNet.connect(port, "127.0.0.1"); + local.on("data", (chunk) => socket.send(chunk)); + local.on("error", () => socket.close()); + socket.on("message", (data: Buffer) => local.write(data)); + socket.on("close", () => local.destroy()); + }); + }), + ), + closeServer, +); + +it.effect("refuses to forward from an environment that shares this machine's loopback", () => + Effect.gen(function* () { + const endpoint = yield* listenSameMachineEndpoint; + const remotePort = yield* unusedPort; + const tunnel = yield* makeTunnel(`ws://127.0.0.1:${addressPort(endpoint)}/api/preview/tunnel`); + const error = yield* tunnel + .forward({ environmentId: EnvironmentId.make("remote"), remotePort }) + .pipe(Effect.flip); + expect(error._tag).toBe("LoopbackTunnelSameMachineError"); + expect(yield* refusesConnections(remotePort)).toBe(true); + expect(yield* tunnel.forwards).toEqual([]); + }), +); + +it.effect( + "forwards nothing while the environment is out of reach, then forwards once it is back", + () => + Effect.gen(function* () { + const endpoint = yield* listenEndpoint; + const remotePort = yield* unusedPort; + let access: string | null = null; + const tunnel = yield* makeTunnel(() => access); + const environmentId = EnvironmentId.make("remote"); + + const unavailable = yield* tunnel.forward({ environmentId, remotePort }).pipe(Effect.flip); + expect(unavailable._tag).toBe("LoopbackTunnelUnavailableError"); + expect(yield* refusesConnections(remotePort)).toBe(true); + expect(yield* tunnel.forwards).toEqual([]); + + access = `ws://127.0.0.1:${addressPort(endpoint.server)}/api/preview/tunnel`; + const forward = yield* tunnel.forward({ environmentId, remotePort }); + expect(yield* exchange(forward.localPort, Uint8Array.of(9))).toEqual([0xee, 9]); + }), +); + +/** The environment's tunnel route refusing every port with a 502, as for a port nothing listens on. */ +const listenRefusingEndpoint = (headers: Record) => + Effect.acquireRelease( + Effect.promise( + () => + new Promise((resolve) => { + const server: NodeWS.WebSocketServer = new NodeWS.WebSocketServer( + { + port: 0, + host: "127.0.0.1", + verifyClient: (_info, done) => done(false, 502, "Bad Gateway", headers), + }, + () => resolve(server), + ); + }), + ), + closeServer, + ); + +it.effect.each([ + { case: "the environment reports nothing on the probe port", refused: true }, + { case: "the tunnel fails for another reason", refused: false }, +])("decides a forward's machine only on proof: $case", ({ refused }) => + Effect.gen(function* () { + const endpoint = yield* listenRefusingEndpoint( + refused ? { "x-t3-tunnel-port-refused": "1" } : {}, + ); + const remotePort = yield* unusedPort; + const tunnel = yield* makeTunnel(`ws://127.0.0.1:${addressPort(endpoint)}/api/preview/tunnel`); + const result = yield* tunnel + .forward({ environmentId: EnvironmentId.make("remote"), remotePort }) + .pipe(Effect.result); + if (refused) { + expect(Result.isSuccess(result)).toBe(true); + } else { + expect(Result.isFailure(result) && result.failure._tag).toBe( + "LoopbackTunnelUnavailableError", + ); + expect(yield* refusesConnections(remotePort)).toBe(true); + } + }), +); + +it.effect("closes connections beyond a forward's limit without tunnelling them", () => + Effect.gen(function* () { + const endpoint = yield* listenEndpoint; + const tunnel = yield* makeTunnel( + `ws://127.0.0.1:${addressPort(endpoint.server)}/api/preview/tunnel`, + ); + const forward = yield* tunnel.forward({ + environmentId: EnvironmentId.make("remote"), + remotePort: yield* unusedPort, + }); + const open = () => + Effect.acquireRelease( + Effect.promise( + () => + new Promise((resolve) => { + const socket = NodeNet.connect(forward.localPort, "127.0.0.1", () => { + socket.once("data", () => resolve(socket)); + socket.write(Uint8Array.of(1)); + }); + }), + ), + (socket) => Effect.sync(() => socket.destroy()), + ); + yield* Effect.forEach(Array.from({ length: 64 }), open, { concurrency: "unbounded" }); + const tunnelled = endpoint.requests.length; + const closed = yield* Effect.promise( + () => + new Promise((resolve) => { + const socket = NodeNet.connect(forward.localPort, "127.0.0.1"); + socket.on("close", () => resolve(true)); + socket.on("data", () => resolve(false)); + socket.write(Uint8Array.of(2)); + }), + ); + expect(closed).toBe(true); + expect(endpoint.requests.length).toBe(tunnelled); + }), +); diff --git a/apps/desktop/src/preview/LoopbackTunnel.ts b/apps/desktop/src/preview/LoopbackTunnel.ts index 6eff2dd70b345..1e06993fa54f0 100644 --- a/apps/desktop/src/preview/LoopbackTunnel.ts +++ b/apps/desktop/src/preview/LoopbackTunnel.ts @@ -1,21 +1,28 @@ // Renders another environment's localhost pages in a local webview: the partition's loopback // traffic goes to a SOCKS5 listener here, and each connection rides one WebSocket to the -// environment's /api/preview/tunnel. The page keeps its localhost origin. +// environment's /api/preview/tunnel. The page keeps its localhost origin. Forwarded ports take +// the same route from a plain listener, for any client on this machine. import * as NodeSocket from "@effect/platform-node/NodeSocket"; import * as NodeSocketServer from "@effect/platform-node/NodeSocketServer"; import * as NodeWS from "@effect/platform-node/NodeWS"; -import type { DesktopPreviewTunnelAccessRequest } from "@t3tools/contracts"; +import type { + DesktopPortForward, + DesktopPreviewTunnelAccessRequest, + EnvironmentId, +} from "@t3tools/contracts"; import * as HostProcess from "@t3tools/shared/HostProcess"; import type { NonEmptyReadonlyArray } from "effect/Array"; import * as Context from "effect/Context"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as NetAddress from "effect/net/NetAddress"; import * as Option from "effect/Option"; import * as Result from "effect/Result"; import * as Schema from "effect/Schema"; +import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Scope from "effect/Scope"; import * as Semaphore from "effect/Semaphore"; import * as Socket from "effect/socket/Socket"; @@ -24,6 +31,8 @@ import * as ElectronWindow from "../electron/ElectronWindow.ts"; import { PREVIEW_TUNNEL_ACCESS_REQUEST_CHANNEL } from "../ipc/channels.ts"; const ACCESS_TIMEOUT = "15 seconds"; +const PROBE_TIMEOUT = "3 seconds"; +const MAX_FORWARD_CONNECTIONS = 64; const CONNECT_TIMEOUT = "10 seconds"; const REPLY_SUCCEEDED = 0; @@ -127,9 +136,13 @@ const isTunnelEndpoint = (tunnelUrl: string, port: number) => { }; /** Opens a connection to the destination; `ws` pauses its socket, so a slow page slows the tunnel. */ +/** Set by the environment's /api/preview/tunnel when it reached the port and nothing listens. */ +const PORT_REFUSED_HEADER = "x-t3-tunnel-port-refused"; + const dialDestination = Effect.fn("LoopbackTunnel.dialDestination")(function* ( tunnelUrl: string, port: number, + onPortRefused?: () => void, ) { if (isTunnelEndpoint(tunnelUrl, port)) { const endpoint = yield* NodeSocket.makeNet({ @@ -141,10 +154,18 @@ const dialDestination = Effect.fn("LoopbackTunnel.dialDestination")(function* ( const url = new URL(tunnelUrl); url.searchParams.set("port", String(port)); const tunnel = yield* Effect.acquireRelease( - Effect.sync(() => + Effect.sync(() => { // Closing before the handshake finishes emits an error after Socket's listeners are gone. - new NodeWS.WebSocket(url).on("error", () => undefined), - ), + const tunnel = new NodeWS.WebSocket(url).on("error", () => undefined); + if (onPortRefused) { + tunnel.on("unexpected-response", (_request, response) => { + if (response.headers[PORT_REFUSED_HEADER] !== undefined) onPortRefused(); + // Handled here, so `ws` leaves aborting the handshake to us. + tunnel.terminate(); + }); + } + return tunnel; + }), (tunnel) => Effect.sync(() => tunnel.close()), ); const socket = yield* Socket.fromWebSocket(Effect.succeed(tunnel), { @@ -224,6 +245,33 @@ export class LoopbackTunnelRouteError extends Schema.TaggedError()( + "LoopbackTunnelForwardError", + { environmentId: Schema.String, port: Schema.Number, cause: Schema.Defect() }, +) { + override get message(): string { + return `Failed to forward port ${this.port} of environment "${this.environmentId}".`; + } +} + +export class LoopbackTunnelUnavailableError extends Schema.TaggedError()( + "LoopbackTunnelUnavailableError", + { environmentId: Schema.String }, +) { + override get message(): string { + return `Environment "${this.environmentId}" can't be reached through the tunnel right now.`; + } +} + +export class LoopbackTunnelSameMachineError extends Schema.TaggedError()( + "LoopbackTunnelSameMachineError", + { environmentId: Schema.String, port: Schema.Number }, +) { + override get message(): string { + return `This environment runs on this computer, so localhost:${this.port} already reaches it.`; + } +} + export class LoopbackTunnel extends Context.Service< LoopbackTunnel, { @@ -237,6 +285,26 @@ export class LoopbackTunnel extends Context.Service< readonly requestId: string; readonly url: string | null; }) => Effect.Effect; + /** Listens on this machine's loopback, on the same port when it is free. */ + readonly forward: (input: { + readonly environmentId: EnvironmentId; + readonly remotePort: number; + }) => Effect.Effect< + DesktopPortForward, + LoopbackTunnelForwardError | LoopbackTunnelSameMachineError | LoopbackTunnelUnavailableError + >; + readonly stopForward: (input: { + readonly environmentId: EnvironmentId; + readonly remotePort: number; + }) => Effect.Effect; + readonly forwards: Effect.Effect>; + /** Whether the environment's loopback is this machine's, so forwarding would only loop. */ + readonly sharesLoopback: ( + environmentId: EnvironmentId, + ) => Effect.Effect; + readonly subscribeForwards: ( + listener: (forwards: ReadonlyArray) => Effect.Effect, + ) => Effect.Effect; } >()("@t3tools/desktop/preview/LoopbackTunnel") {} @@ -245,8 +313,17 @@ const make = Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; const platform = yield* HostProcess.Platform; const userId = yield* HostProcess.UserId; + const random = yield* SecureRandom.SecureRandom; const listenerScope = yield* Effect.scope; const routing = yield* Semaphore.make(1); + const forwarding = yield* Semaphore.make(1); + const forwarded = new Map< + string, + { readonly forward: DesktopPortForward; readonly scope: Scope.Closeable } + >(); + const forwardListeners = new Set< + (forwards: ReadonlyArray) => Effect.Effect + >(); const pending = new Map>(); const listenerPorts = new Map(); const routed = new WeakSet(); @@ -318,6 +395,163 @@ const make = Effect.gen(function* () { (effect) => Effect.ignoreCause(effect), ); + /** Serves one connection to a forwarded port; closes it when the environment is out of reach. */ + const serveForward = (environmentId: string, port: number) => { + let active = 0; + return Effect.fn("LoopbackTunnel.serveForward")( + function* (socket: Socket.Socket) { + // Acquiring the socket ties it to this scope, so returning early closes it. + const pull = yield* Socket.readerBytes(socket); + const writer = yield* socket.writer; + // Closed at once, so a page hammering the port can't queue tunnels and access requests. + if (active >= MAX_FORWARD_CONNECTIONS) return; + active++; + yield* Effect.addFinalizer(() => Effect.sync(() => active--)); + if (!(yield* isOwnConnection())) return; + const tunnelUrl = yield* requestAccess(environmentId); + if (tunnelUrl === null) return; + const destination = yield* dialDestination(tunnelUrl, port); + return yield* Effect.raceFirst( + pump(pull, destination.writer.writeAll), + pump(destination.pull, writer.writeAll), + ); + }, + Effect.scoped, + (effect) => Effect.ignoreCause(effect), + ); + }; + + /** + * Whether the environment's loopback is this machine's, by tunnelling a nonce to a local probe. + * A forward there would accept the environment's own dials and loop through the tunnel. + */ + const sharesLoopback = Effect.fn("LoopbackTunnel.sharesLoopback")(function* ( + environmentId: string, + ) { + const tunnelUrl = yield* requestAccess(environmentId); + // Without access the answer is unknown, not "another machine": a forward could loop later. + if (tunnelUrl === null) return yield* new LoopbackTunnelUnavailableError({ environmentId }); + return yield* probeLoopback(environmentId, tunnelUrl); + }); + + /** + * True only when the nonce reaches this machine's probe; false only on proof the environment + * was reached and nothing listens on the probe port there. Anything else is unknown. + */ + const probeLoopback = Effect.fn("LoopbackTunnel.probeLoopback")( + function* (environmentId: string, tunnelUrl: string) { + const unavailable = new LoopbackTunnelUnavailableError({ environmentId }); + const nonce = new TextEncoder().encode(yield* random.uuidV4()); + const arrived = yield* Deferred.make(); + const probe = yield* NodeSocketServer.make({ port: 0, host: "127.0.0.1" }); + yield* probe + .run( + Effect.fnUntraced( + function* (socket: Socket.Socket) { + const pull = yield* Socket.readerBytes(socket); + let received = Buffer.alloc(0); + while (received.length < nonce.length) { + received = Buffer.concat([received, ...(yield* pull)]); + } + if (received.subarray(0, nonce.length).equals(nonce)) { + yield* Deferred.succeed(arrived, undefined); + } + }, + Effect.scoped, + (effect) => Effect.ignoreCause(effect), + ), + ) + .pipe(Effect.forkScoped); + let portRefused = false; + const destination = yield* dialDestination( + tunnelUrl, + (probe.address as NetAddress.InetAddress).port, + () => { + portRefused = true; + }, + ).pipe(Effect.option); + if (Option.isNone(destination)) { + if (portRefused) return false; + return yield* unavailable; + } + yield* destination.value.writer.write(nonce); + // An answer or a close means a service on another machine took the connection. + const answer = yield* Effect.raceFirst( + Deferred.await(arrived).pipe(Effect.as(true)), + destination.value.pull.pipe(Effect.as(false)), + ).pipe(Effect.timeoutOption(PROBE_TIMEOUT)); + if (Option.isNone(answer)) return yield* unavailable; + return answer.value; + }, + Effect.scoped, + (effect, environmentId) => + effect.pipe( + Effect.mapError((error) => + error._tag === "LoopbackTunnelUnavailableError" + ? error + : new LoopbackTunnelUnavailableError({ environmentId }), + ), + ), + ); + + const forwardKey = (environmentId: string, port: number) => `${environmentId}:${port}`; + const currentForwards = () => [...forwarded.values()].map(({ forward }) => forward); + const announceForwards = Effect.suspend(() => { + const forwards = currentForwards(); + return Effect.forEach([...forwardListeners], (listener) => listener(forwards), { + discard: true, + }); + }); + + const forward: LoopbackTunnel["Service"]["forward"] = Effect.fn("LoopbackTunnel.forward")( + function* ({ environmentId, remotePort }) { + const existing = forwarded.get(forwardKey(environmentId, remotePort)); + if (existing) return existing.forward; + if (yield* sharesLoopback(environmentId)) { + return yield* new LoopbackTunnelSameMachineError({ environmentId, port: remotePort }); + } + const scope = yield* Scope.fork(listenerScope); + const bind = (port: number) => + NodeSocketServer.make({ port, host: "127.0.0.1" }).pipe(Scope.provide(scope)); + const server = yield* bind(remotePort).pipe( + // Taken here, or privileged: any free port still reaches the environment's. + Effect.catch(() => bind(0)), + Effect.onError(() => Scope.close(scope, Exit.void)), + Effect.mapError( + (cause) => new LoopbackTunnelForwardError({ environmentId, port: remotePort, cause }), + ), + ); + yield* server.run(serveForward(environmentId, remotePort)).pipe(Effect.forkIn(scope)); + const forward = { + environmentId, + remotePort, + localPort: (server.address as NetAddress.InetAddress).port, + }; + forwarded.set(forwardKey(environmentId, remotePort), { forward, scope }); + yield* announceForwards; + return forward; + }, + forwarding.withPermits(1), + ); + + const stopForward: LoopbackTunnel["Service"]["stopForward"] = Effect.fn( + "LoopbackTunnel.stopForward", + )(function* ({ environmentId, remotePort }) { + const key = forwardKey(environmentId, remotePort); + const existing = forwarded.get(key); + if (!existing) return; + forwarded.delete(key); + // Closing the scope also ends the connections it carries. + yield* Scope.close(existing.scope, Exit.void); + yield* announceForwards; + }, forwarding.withPermits(1)); + + const subscribeForwards: LoopbackTunnel["Service"]["subscribeForwards"] = (listener) => + Effect.acquireRelease( + Effect.sync(() => forwardListeners.add(listener)), + () => Effect.sync(() => forwardListeners.delete(listener)), + ).pipe(Effect.asVoid); + const listen = Effect.fn("LoopbackTunnel.listen")(function* (environmentId: string) { const existing = listenerPorts.get(environmentId); if (existing !== undefined) return existing; @@ -375,7 +609,15 @@ const make = Effect.gen(function* () { return answer ? Deferred.succeed(answer, url).pipe(Effect.asVoid) : Effect.void; }; - return LoopbackTunnel.of({ route, resolveAccess }); + return LoopbackTunnel.of({ + route, + resolveAccess, + forward, + stopForward, + forwards: Effect.sync(currentForwards), + sharesLoopback, + subscribeForwards, + }); }); export const layer = Layer.effect(LoopbackTunnel, make); diff --git a/apps/web/src/components/CommandPalette.tsx b/apps/web/src/components/CommandPalette.tsx index 1eb1a9bcba599..3349902aeea05 100644 --- a/apps/web/src/components/CommandPalette.tsx +++ b/apps/web/src/components/CommandPalette.tsx @@ -255,6 +255,10 @@ import { } from "./CommandPaletteAddProject"; import { useCommandPaletteThreadItems } from "./CommandPaletteThreadItems"; import { useCommandPaletteThemeItems } from "./CommandPaletteThemeItems"; +import { + PORT_FORWARD_GROUP_PREFIX, + useCommandPalettePortForwardItem, +} from "./CommandPalettePortForwardItems"; import { CommandPaletteVirtualizedResults, scrollCommandPaletteRowIntoView, @@ -547,6 +551,10 @@ function OpenCommandPaletteDialog(props: { const keybindings = useAtomValue(primaryServerKeybindingsAtom); const providersByEnvironment = useEnvironmentProviders(); const { changeThemeItem, changeAppearanceItem, themeEditorItem } = useCommandPaletteThemeItems(); + const portForwardItem = useCommandPalettePortForwardItem({ + activeThread: activeThread ?? null, + query: deferredQuery, + }); const currentView = viewStack.at(-1)?.view ?? null; const threadSearchQuery = currentView === null && !isActionsOnly ? deferredQuery : ""; const [browseGeneration, setBrowseGeneration] = useState(0); @@ -1425,6 +1433,8 @@ function OpenCommandPaletteDialog(props: { }); } + if (portForwardItem) actionItems.push(portForwardItem); + const promptLinkTarget = paletteRouteTarget ? paletteRouteTarget.kind === "server" ? paletteRouteTarget.threadRef @@ -1884,11 +1894,13 @@ function OpenCommandPaletteDialog(props: { items: projectThreadItems.length > 0 ? projectThreadItems : [addProjectAction], }, ] - : currentView?.groups[0]?.value === "themes" - ? changeThemeItem.groups - : currentView?.groups[0]?.value === "appearance" - ? changeAppearanceItem.groups - : (currentView?.groups ?? rootGroups); + : currentView?.groups[0]?.value.startsWith(PORT_FORWARD_GROUP_PREFIX) && portForwardItem + ? portForwardItem.groups + : currentView?.groups[0]?.value === "themes" + ? changeThemeItem.groups + : currentView?.groups[0]?.value === "appearance" + ? changeAppearanceItem.groups + : (currentView?.groups ?? rootGroups); const isLinkedThreadSearch = linkedThreadSearch?.linkedThreads !== undefined && deferredQuery === linkedThreadSearch.query; diff --git a/apps/web/src/components/CommandPalettePortForwardItems.tsx b/apps/web/src/components/CommandPalettePortForwardItems.tsx new file mode 100644 index 0000000000000..2a03b19d300c1 --- /dev/null +++ b/apps/web/src/components/CommandPalettePortForwardItems.tsx @@ -0,0 +1,215 @@ +import { + AuthTerminalOperateScope, + type DesktopPortForward, + type EnvironmentId, + type ThreadId, +} from "@t3tools/contracts"; +import { useAtomValue } from "@effect/atom-react"; +import { useGT } from "gt-react"; +import { CableIcon, ClipboardCopyIcon, ExternalLinkIcon, SquareIcon } from "lucide-react"; + +import { writeTextToClipboard } from "../hooks/useCopyToClipboard"; +import { readLocalApi } from "../localApi"; +import { useThreadDiscoveredPorts } from "../portDiscoveryState"; +import { useEnvironments } from "../state/environments"; +import { + canForwardPorts, + findPortForward, + forwardedUrl, + forwardPort, + forwardLocalitiesAtom, + stopPortForward, + usePortForwards, +} from "../state/portForwards"; +import { environmentIdsKey } from "../state/environmentAtomList"; +import { useEnvironmentsWithScope } from "../state/session"; +import { + ADDON_ICON_CLASS, + ITEM_ICON_CLASS, + type CommandPaletteActionItem, + type CommandPaletteGroup, + type CommandPaletteSubmenuItem, +} from "./CommandPalette.logic"; +import { toastManager } from "./ui/toast"; + +/** Prefix of this submenu's group values; the palette rebuilds them live while it is open. */ +export const PORT_FORWARD_GROUP_PREFIX = "port-forwards:"; + +const parsePort = (query: string) => { + const trimmed = query.trim(); + if (!/^\d{1,5}$/.test(trimmed)) return null; + const port = Number(trimmed); + return port >= 1 && port <= 65_535 ? port : null; +}; + +/** "Forwarded ports": each forward with its actions, then ports to forward from the thread or the query. */ +export function useCommandPalettePortForwardItem(input: { + readonly activeThread: { + readonly environmentId: EnvironmentId; + readonly id: ThreadId; + } | null; + readonly query: string; +}): CommandPaletteSubmenuItem | null { + const gt = useGT(); + const forwards = usePortForwards(); + const { environments } = useEnvironments(); + const reachable = environments.filter( + (environment) => + environment.connection.phase === "connected" && canForwardPorts(environment.entry.target), + ); + const tunnelling = useEnvironmentsWithScope(reachable, AuthTerminalOperateScope); + const tunnelled = reachable.filter((environment) => tunnelling.has(environment.environmentId)); + const localities = useAtomValue( + forwardLocalitiesAtom(environmentIdsKey(tunnelled.map(({ environmentId }) => environmentId))), + ); + const sources = tunnelled.filter((_, index) => localities[index] === "remote"); + // Only a forwardable thread's servers are listed, so other clients never subscribe to them. + const threadEnvironmentId = sources.some( + (environment) => environment.environmentId === input.activeThread?.environmentId, + ) + ? (input.activeThread?.environmentId ?? null) + : null; + const threadServers = useThreadDiscoveredPorts({ + environmentId: threadEnvironmentId, + threadId: threadEnvironmentId === null ? null : (input.activeThread?.id ?? null), + }); + if (forwards.length === 0 && sources.length === 0) return null; + + const labelOf = (environmentId: EnvironmentId) => + environments.find((environment) => environment.environmentId === environmentId)?.label ?? + environmentId; + + const start = async (environmentId: EnvironmentId, remotePort: number) => { + const forward = await forwardPort(environmentId, remotePort); + toastManager.add({ + type: "success", + title: gt("Forwarded port {port}", { port: remotePort }), + description: gt("Apps on this machine reach it at localhost:{port}.", { + port: forward.localPort, + }), + }); + }; + + const forwardedItem = (forward: DesktopPortForward): CommandPaletteSubmenuItem => { + const address = `localhost:${forward.localPort}`; + const environment = labelOf(forward.environmentId); + return { + kind: "submenu", + value: `port-forward:${forward.environmentId}:${forward.remotePort}`, + title: address, + description: gt("Port {port} on {environment}", { port: forward.remotePort, environment }), + searchTerms: [address, String(forward.remotePort), environment, "forwarded port"], + icon: , + addonIcon: , + groups: [ + { + value: "port-forward-actions", + label: address, + items: [ + { + kind: "action", + value: "port-forward:open", + title: gt("Open in browser"), + searchTerms: ["open", "browser"], + icon: , + run: async () => { + await readLocalApi()?.shell.openExternal(forwardedUrl(forward)); + }, + }, + { + kind: "action", + value: "port-forward:copy", + title: gt("Copy address"), + searchTerms: ["copy", "address", "url"], + icon: , + run: async () => { + await writeTextToClipboard(forwardedUrl(forward)); + }, + }, + { + kind: "action", + value: "port-forward:stop", + title: gt("Stop forwarding"), + searchTerms: ["stop", "remove", "close"], + icon: , + run: () => stopPortForward(forward.environmentId, forward.remotePort), + }, + ], + }, + ], + }; + }; + + const startItems: CommandPaletteActionItem[] = []; + for (const server of threadServers) { + const environmentId = threadEnvironmentId; + if (environmentId === null) break; + if (findPortForward(forwards, environmentId, server.port)) continue; + startItems.push({ + kind: "action", + value: `port-forward:start:${environmentId}:${server.port}`, + title: gt("Forward localhost:{port}", { port: server.port }), + description: [labelOf(environmentId), server.processName].filter(Boolean).join(" · "), + searchTerms: [String(server.port), server.processName ?? "", "forward"], + icon: , + run: () => start(environmentId, server.port), + }); + } + const typedPort = parsePort(input.query); + if (typedPort !== null) { + for (const environment of sources) { + if (findPortForward(forwards, environment.environmentId, typedPort)) continue; + if ( + startItems.some((item) => item.value.endsWith(`:${environment.environmentId}:${typedPort}`)) + ) + continue; + startItems.push({ + kind: "action", + value: `port-forward:start:${environment.environmentId}:${typedPort}`, + title: gt("Forward port {port} from {environment}", { + port: typedPort, + environment: environment.label, + }), + searchTerms: [String(typedPort), "forward"], + icon: , + run: () => start(environment.environmentId, typedPort), + }); + } + } + + const groups: CommandPaletteGroup[] = []; + if (forwards.length > 0) { + groups.push({ + value: `${PORT_FORWARD_GROUP_PREFIX}forwarded`, + label: gt("Forwarded"), + items: forwards.map(forwardedItem), + }); + } + if (startItems.length === 0 && sources.length > 0) { + startItems.push({ + kind: "action", + value: "port-forward:hint", + title: gt("Type a port number to forward it"), + searchTerms: [], + icon: , + disabled: true, + run: async () => {}, + }); + } + // Always present, so the open submenu keeps a group to be recognized by. + groups.push({ + value: `${PORT_FORWARD_GROUP_PREFIX}start`, + label: startItems.length > 0 ? gt("Forward a port") : "", + items: startItems, + }); + + return { + kind: "submenu", + value: "action:port-forwards", + title: gt("Forwarded ports"), + searchTerms: ["forward port", "port forwarding", "forwarded ports", "ports", "tunnel"], + icon: , + addonIcon: , + groups, + }; +} diff --git a/apps/web/src/components/chat/ThreadServersPanel.tsx b/apps/web/src/components/chat/ThreadServersPanel.tsx index 10bfb11aa835a..b392a78f21b9a 100644 --- a/apps/web/src/components/chat/ThreadServersPanel.tsx +++ b/apps/web/src/components/chat/ThreadServersPanel.tsx @@ -3,6 +3,7 @@ import { thrownErrorMessage } from "@t3tools/client-runtime/errors"; import { scopeThreadRef } from "@t3tools/client-runtime/environment"; import { AuthPreviewOperateScope, + AuthTerminalOperateScope, type DiscoveredLocalServer, type EnvironmentId, type ThreadId, @@ -13,7 +14,7 @@ import { } from "@t3tools/client-runtime/state/runtime"; import { T, useGT, Var } from "gt-react"; import { m } from "~/i18n/messages"; -import { GlobeIcon, SquareIcon, ChevronDownIcon, ChevronUpIcon } from "lucide-react"; +import { CableIcon, GlobeIcon, SquareIcon, ChevronDownIcon, ChevronUpIcon } from "lucide-react"; import { type MouseEvent, useState } from "react"; import { resolveExternalServerUrl } from "../../browser/browserTargetResolver"; @@ -21,6 +22,15 @@ import { readLocalApi } from "../../localApi"; import { cn, isMacPlatform } from "../../lib/utils"; import { useThreadDiscoveredPorts } from "../../portDiscoveryState"; import { useEnvironment } from "../../state/environments"; +import { + canForwardPorts, + findPortForward, + forwardedUrl, + forwardPort, + stopPortForward, + useForwardLocality, + usePortForwards, +} from "../../state/portForwards"; import { previewEnvironment } from "../../state/preview"; import { useEnvironmentScope } from "../../state/session"; import { useAtomCommand } from "../../state/use-atom-command"; @@ -53,14 +63,21 @@ function ThreadServersList(props: ThreadServersPanelProps) { const canStop = useAtomValue( previewEnvironment.stopLocalServer.permissionAtom(props.environmentId), ); - const supportsStop = - useEnvironment(props.environmentId)?.serverConfig?.environment.capabilities.localServerStop === - true; + const environment = useEnvironment(props.environmentId); + const supportsStop = environment?.serverConfig?.environment.capabilities.localServerStop === true; + const forwards = usePortForwards(); + const forwardable = + useEnvironmentScope(props.environmentId, AuthTerminalOperateScope) && + environment?.connection.phase === "connected" && + canForwardPorts(environment.entry.target); + const locality = useForwardLocality(forwardable ? props.environmentId : null); + const canForward = locality === "remote"; const openPreview = useAtomCommand(previewEnvironment.open, { reportFailure: false }); const stopServer = useAtomCommand(previewEnvironment.stopLocalServer, { label: "thread server stop", }); const [stoppingKey, setStoppingKey] = useState(null); + const [forwardingPort, setForwardingPort] = useState(null); const [visibleCount, setVisibleCount] = useState(SERVER_PAGE_COUNT); if (servers.length === 0) return null; @@ -83,7 +100,19 @@ function ThreadServersList(props: ThreadServersPanelProps) { // Like links: modified and middle clicks go to the system browser. if (event.metaKey || event.ctrlKey || event.button === 1) { event.preventDefault(); - const url = resolveExternalServerUrl(props.environmentId, server.url); + // This machine's browser reaches another environment's loopback only through a forward. + // Starting a forward runs the probe; only a confirmed local environment opens directly. + const url = + forwardable && locality !== "local" + ? await forwardPort(props.environmentId, server.port).then( + (forward) => forwardedUrl(forward, server.url), + (error: unknown) => { + reportFailure(gt("Could not forward port {port}", { port: server.port }), error); + return null; + }, + ) + : resolveExternalServerUrl(props.environmentId, server.url); + if (url === null) return; await readLocalApi() ?.shell.openExternal(url) .catch((error: unknown) => reportFailure(gt("Unable to open in browser"), error)); @@ -108,6 +137,19 @@ function ThreadServersList(props: ThreadServersPanelProps) { } }; + const toggleForward = async (server: DiscoveredLocalServer, forwarded: boolean) => { + if (forwardingPort !== null) return; + setForwardingPort(server.port); + await ( + forwarded + ? stopPortForward(props.environmentId, server.port) + : forwardPort(props.environmentId, server.port) + ).catch((error: unknown) => + reportFailure(gt("Could not forward port {port}", { port: server.port }), error), + ); + setForwardingPort(null); + }; + return ( { const key = serverKey(server); const stoppable = canStop && supportsStop && server.pid !== null; + const forward = findPortForward(forwards, props.environmentId, server.port); + const actionCount = Number(stoppable) + Number(canForward); return (
  • {/* The end padding keeps text clear of the stop button. */} - + localhost:{server.port} {[ + // First, so the narrow panel truncates the less useful parts. + forward + ? gt("Forwarded to :{port}", { + $context: "a remote dev server reachable on this machine's port", + port: forward.localPort, + }) + : null, server.terminal === null ? gt("Agent", { $context: "who started a dev server" }) : gt("Terminal", { $context: "who started a dev server" }), @@ -162,32 +219,83 @@ function ThreadServersList(props: ThreadServersPanelProps) { - {stoppable ? ( -
    - - void stop(server)} - /> - } - > - {stoppingKey === key ? ( - - ) : ( - - )} - - - Stop server - - + {actionCount > 0 ? ( +
    + {canForward ? ( + + void toggleForward(server, forward !== undefined)} + /> + } + > + {forwardingPort === server.port ? ( + + ) : ( + + )} + + + {forward ? ( + + Forwarded to localhost:{forward.localPort} on this machine. + Click to stop. + + ) : ( + Forward to this machine, for any app here + )} + + + ) : null} + {stoppable ? ( + + void stop(server)} + /> + } + > + {stoppingKey === key ? ( + + ) : ( + + )} + + + Stop server + + + ) : null}
    ) : null}
  • diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index 22f9bcf953f2b..661098ee35afc 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -1840,6 +1840,18 @@ "480646ceb98c7163": "Schließen", "32fc9124998ebc18": "Lokal", "1c4158d741eec5da": "{label} (lokal)", + "a12a4958ca6b924b": "Port {port} weitergeleitet", + "0f14a51b016f825d": "Apps auf diesem Rechner erreichen ihn unter localhost:{port}.", + "4bdb9a086e77ee6d": "Port {port} auf {environment}", + "7a462e32dba47f4c": "Im Browser öffnen", + "4b8087450e97c995": "Adresse kopieren", + "c170720e67d01733": "Weiterleitung beenden", + "1e5c6d1c33667b17": "localhost:{port} weiterleiten", + "e76f45b6a412a0b6": "Port {port} von {environment} weiterleiten", + "ecf3b95b3d9e6e74": "Weitergeleitet", + "b3123e5b8602a134": "Gib eine Portnummer ein, um sie weiterzuleiten", + "1bdeef9819b4a055": "Port weiterleiten", + "de8a46b66f8ec455": "Weitergeleitete Ports", "f844c41fac2d339c": "Aktuell", "69154433587763c0": "Keine passenden Aktionen.", "90c3a382ecefa0ce": "Keine passenden Befehle, Projekte oder Threads.", @@ -2975,6 +2987,10 @@ "314cdccee9c14774": "Dieser Server unterstützt keine Registry-Abfragen. Aktualisiere ihn, bevor du den Kanal wechselst.", "22da1d00403ab2fd": "Die npm-Registry dieser Umgebung konnte nicht geprüft werden. Prüfe die Verbindung und die Registry-Einstellungen.", "2fc0f7a698c95c90": "Verbinde dich mit einem Server, um nach Releases zu suchen.", + "922269f8691aa3ba": "Es ließ sich nicht feststellen, ob diese Umgebung auf diesem Computer läuft.", + "35cade9cc8a01363": "Portweiterleitung braucht die Desktop-App.", + "9e303e0a794898d4": "Diese Umgebung läuft auf diesem Computer, daher erreicht localhost:{port} sie bereits.", + "2d49965e0e27e23b": "Diese Umgebung ist gerade nicht erreichbar. Versuche es erneut, sobald sie wieder verbunden ist.", "7280baf7517dad1c": "Refs konnten nicht geladen werden.", "567c0fed6ab8efc1": "Diese Verbindung kann keine Host-Dateien durchsuchen.", "5189720b9436f98c": "Die Suche ist auf {count} Zeichen begrenzt.", @@ -4024,6 +4040,15 @@ } ], "e58a1d884fa1d8f2": "Thread-Details", + "43c5fbd02c6f330a": "Weniger anzeigen", + "de45b075b016cb14": [ + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " weitere anzeigen" + ], "02d9667ff2c8e0b8": "Issue {key}: {title}", "4276743ee60a3c62": "{count, plural, one {{count} Kommentar} other {{count} Kommentare}}", "42f634397f3960aa": "In Thread-Details anzeigen", @@ -4063,15 +4088,6 @@ ], "159ddd0d146a0f22": "Beobachtet: Der Agent wird geweckt, wenn Checks fertig sind, jemand kommentiert oder der Branch Konflikte hat. Klicke zum Beenden.", "1cbc8b5db51b4c77": "Mergen", - "43c5fbd02c6f330a": "Weniger anzeigen", - "de45b075b016cb14": [ - { - "i": 1, - "k": "_gt_value_1", - "v": "v" - }, - " weitere anzeigen" - ], "a3d040c4ef4fc6e9": "Über dem Tempo", "b16fdf56b16d99c9": "Im Tempo", "90f977e97ae8b6c6": "Unter dem Tempo", @@ -4086,6 +4102,7 @@ "66be4fb43249bbd2": "{used} von {max} Tokens", "ee3ae58c8b38a425": "{left} % übrig", "ebb26f93fb83a71b": "{label}: {left} % übrig", + "1b16346722b65812": "{timeLeft} % des Zeitfensters übrig", "728c6cc1431e76c8": "Wird in {duration} zurückgesetzt · {time}", "e16b0b9b490c8bc7": "{label}: {value}", "ba67d0a9ff5dabf0": "Die Zwischenablage-API ist beim Kopieren der Admin-Anfrage nicht verfügbar.", @@ -4179,12 +4196,16 @@ ], "3237699bd13dd4bb": "Subagent stoppen", "075398ac562d74b0": "Agentensitzung trennen", + "1d2025060ba3d1c3": "Port {port} konnte nicht weitergeleitet werden", "086ecbb6f4c2e959": "Kann nicht im Browser geöffnet werden", "51052c00ab1ac8cc": "Vorschau kann nicht geöffnet werden", "0ccd37739f9cf2b6": "Server konnte nicht gestoppt werden", "a610a81c4061bb4c": "Server", + "253bc8b5e99002dc": "Weitergeleitet an :{port}", "bd1ca8ccb6d0b87c": "Agent", "e25e045607262b40": "Terminal", + "194a9791a83d3f79": "Weiterleitung von localhost:{port} beenden", + "95bbbac2f2e17273": "localhost:{port} an diesen Rechner weiterleiten", "95b263aa683271cc": "localhost:{port} stoppen", "f94866e17faddc05": [ "Im Browser-Panel öffnen. ", @@ -4195,6 +4216,16 @@ }, " für deinen Browser." ], + "781fba367a220012": [ + "An localhost:", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " auf diesem Rechner weitergeleitet. Klicke zum Beenden." + ], + "92347683e33e9f02": "An diesen Rechner weiterleiten, für jede App hier", "3c7763243445b28d": "Server stoppen", "991cc9fb37606c91": "(leere Antwort)", "36e4b8d2db087296": "Ab dieser Antwort forken", @@ -5932,7 +5963,6 @@ "a74538a7917c1c96": "Video abspielen", "11a5a4d340e6397d": "Original öffnen", "1b74242b0d303272": "Video herunterladen", - "7a462e32dba47f4c": "Im Browser öffnen", "f9ca1e61d515445e": "Nutzdaten der Data-URL fehlen.", "1b547c297573369c": "Dieses eingebettete Medium konnte nicht decodiert werden.", "84f7c359e5f050b1": "Die Datei konnte nicht abgerufen werden (HTTP {status}).", @@ -11860,7 +11890,6 @@ "0bd938825ffcf992": "+{percent} % des Kontingents", "09c0e00d7fb55402": "Reset-Guthaben wird verwendet…", "4df3ff1be768a7ab": "{name}: {remaining} % übrig", - "1b16346722b65812": "{timeLeft} % des Zeitfensters übrig", "7aaaff1c6484f25c": "Segment", "8bcab2ef61de6518": "0-$-Limit", "a16b48709357a5a7": "Nutzung verwalten", diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index 442486e2decb0..a873be091b0c9 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -1841,6 +1841,18 @@ "480646ceb98c7163": "Close", "32fc9124998ebc18": "Local", "1c4158d741eec5da": "{label} (Local)", + "a12a4958ca6b924b": "Forwarded port {port}", + "0f14a51b016f825d": "Apps on this machine reach it at localhost:{port}.", + "4bdb9a086e77ee6d": "Port {port} on {environment}", + "7a462e32dba47f4c": "Open in browser", + "4b8087450e97c995": "Copy address", + "c170720e67d01733": "Stop forwarding", + "1e5c6d1c33667b17": "Forward localhost:{port}", + "e76f45b6a412a0b6": "Forward port {port} from {environment}", + "ecf3b95b3d9e6e74": "Forwarded", + "b3123e5b8602a134": "Type a port number to forward it", + "1bdeef9819b4a055": "Forward a port", + "de8a46b66f8ec455": "Forwarded ports", "f844c41fac2d339c": "Current", "69154433587763c0": "No matching actions.", "90c3a382ecefa0ce": "No matching commands, projects, or threads.", @@ -2974,6 +2986,10 @@ "314cdccee9c14774": "This server does not support registry lookups. Update it before switching tracks.", "22da1d00403ab2fd": "Could not check this environment's npm registry. Check the connection and registry settings.", "2fc0f7a698c95c90": "Connect to a server to check releases.", + "922269f8691aa3ba": "Could not tell whether this environment runs on this computer.", + "35cade9cc8a01363": "Port forwarding needs the desktop app.", + "9e303e0a794898d4": "This environment runs on this computer, so localhost:{port} already reaches it.", + "2d49965e0e27e23b": "This environment can't be reached right now. Try again once it reconnects.", "7280baf7517dad1c": "Failed to load refs.", "567c0fed6ab8efc1": "This connection cannot search host files.", "5189720b9436f98c": "Search is limited to {count} characters.", @@ -4022,6 +4038,16 @@ } ], "e58a1d884fa1d8f2": "Thread details", + "43c5fbd02c6f330a": "Show less", + "de45b075b016cb14": [ + "Show ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " more" + ], "02d9667ff2c8e0b8": "Issue {key}: {title}", "4276743ee60a3c62": "{count, plural, one {{count} comment} other {{count} comments}}", "42f634397f3960aa": "Show in thread details", @@ -4061,16 +4087,6 @@ ], "159ddd0d146a0f22": "Watching: the agent wakes when checks finish, someone comments, or the branch conflicts. Click to stop.", "1cbc8b5db51b4c77": "Merge", - "43c5fbd02c6f330a": "Show less", - "de45b075b016cb14": [ - "Show ", - { - "i": 1, - "k": "_gt_value_1", - "v": "v" - }, - " more" - ], "a3d040c4ef4fc6e9": "Ahead of pace", "b16fdf56b16d99c9": "On pace", "90f977e97ae8b6c6": "Under pace", @@ -4085,6 +4101,7 @@ "66be4fb43249bbd2": "{used} of {max} tokens", "ee3ae58c8b38a425": "{left}% left", "ebb26f93fb83a71b": "{label}: {left}% left", + "1b16346722b65812": "{timeLeft}% of the window left", "728c6cc1431e76c8": "Resets in {duration} · {time}", "e16b0b9b490c8bc7": "{label}: {value}", "ba67d0a9ff5dabf0": "Clipboard API is unavailable while copying admin request.", @@ -4178,12 +4195,16 @@ ], "3237699bd13dd4bb": "Stop subagent", "075398ac562d74b0": "Disconnect agent session", + "1d2025060ba3d1c3": "Could not forward port {port}", "086ecbb6f4c2e959": "Unable to open in browser", "51052c00ab1ac8cc": "Unable to open preview", "0ccd37739f9cf2b6": "Could not stop server", "a610a81c4061bb4c": "Servers", + "253bc8b5e99002dc": "Forwarded to :{port}", "bd1ca8ccb6d0b87c": "Agent", "e25e045607262b40": "Terminal", + "194a9791a83d3f79": "Stop forwarding localhost:{port}", + "95bbbac2f2e17273": "Forward localhost:{port} to this machine", "95b263aa683271cc": "Stop localhost:{port}", "f94866e17faddc05": [ "Open in the browser panel. ", @@ -4194,6 +4215,16 @@ }, " for your browser." ], + "781fba367a220012": [ + "Forwarded to localhost:", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " on this machine. Click to stop." + ], + "92347683e33e9f02": "Forward to this machine, for any app here", "3c7763243445b28d": "Stop server", "991cc9fb37606c91": "(empty response)", "36e4b8d2db087296": "Fork from this response", @@ -5933,7 +5964,6 @@ "a74538a7917c1c96": "Play video", "11a5a4d340e6397d": "Open original", "1b74242b0d303272": "Download video", - "7a462e32dba47f4c": "Open in browser", "f9ca1e61d515445e": "Missing data URL payload.", "1b547c297573369c": "This inline media could not be decoded.", "84f7c359e5f050b1": "The file could not be fetched (HTTP {status}).", @@ -11868,7 +11898,6 @@ "0bd938825ffcf992": "+{percent}% of pool", "09c0e00d7fb55402": "Using reset credit…", "4df3ff1be768a7ab": "{name}: {remaining}% left", - "1b16346722b65812": "{timeLeft}% of the window left", "7aaaff1c6484f25c": "Segment", "8bcab2ef61de6518": "$0 cap", "a16b48709357a5a7": "Manage usage", diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index 87c7e9a861a93..3e730353316fe 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -1841,6 +1841,18 @@ "480646ceb98c7163": "Cerrar", "32fc9124998ebc18": "Local", "1c4158d741eec5da": "{label} (local)", + "a12a4958ca6b924b": "Puerto {port} reenviado", + "0f14a51b016f825d": "Las apps de este equipo lo alcanzan en localhost:{port}.", + "4bdb9a086e77ee6d": "Puerto {port} en {environment}", + "7a462e32dba47f4c": "Abrir en el navegador", + "4b8087450e97c995": "Copiar dirección", + "c170720e67d01733": "Dejar de reenviar", + "1e5c6d1c33667b17": "Reenviar localhost:{port}", + "e76f45b6a412a0b6": "Reenviar el puerto {port} desde {environment}", + "ecf3b95b3d9e6e74": "Reenviados", + "b3123e5b8602a134": "Escribe un número de puerto para reenviarlo", + "1bdeef9819b4a055": "Reenviar un puerto", + "de8a46b66f8ec455": "Puertos reenviados", "f844c41fac2d339c": "Actual", "69154433587763c0": "No hay acciones que coincidan.", "90c3a382ecefa0ce": "No hay comandos, proyectos ni hilos que coincidan.", @@ -2974,6 +2986,10 @@ "314cdccee9c14774": "Este servidor no permite consultas al registro. Actualízalo antes de cambiar de canal.", "22da1d00403ab2fd": "No se pudo comprobar el registro npm de este entorno. Revisa la conexión y los ajustes del registro.", "2fc0f7a698c95c90": "Conéctate a un servidor para comprobar las versiones.", + "922269f8691aa3ba": "No se pudo saber si este entorno se ejecuta en este equipo.", + "35cade9cc8a01363": "El reenvío de puertos necesita la app de escritorio.", + "9e303e0a794898d4": "Este entorno se ejecuta en este equipo, así que localhost:{port} ya lo alcanza.", + "2d49965e0e27e23b": "No se puede acceder a este entorno ahora. Inténtalo de nuevo cuando se vuelva a conectar.", "7280baf7517dad1c": "No se pudieron cargar las refs.", "567c0fed6ab8efc1": "Esta conexión no puede buscar archivos del host.", "5189720b9436f98c": "La búsqueda está limitada a {count} caracteres.", @@ -4020,6 +4036,16 @@ } ], "e58a1d884fa1d8f2": "Detalles del hilo", + "43c5fbd02c6f330a": "Mostrar menos", + "de45b075b016cb14": [ + "Mostrar ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " más" + ], "02d9667ff2c8e0b8": "Issue {key}: {title}", "4276743ee60a3c62": "{count, plural, one {{count} comentario} other {{count} comentarios}}", "42f634397f3960aa": "Mostrar en los detalles del hilo", @@ -4059,16 +4085,6 @@ ], "159ddd0d146a0f22": "Siguiendo: el agente se activa cuando terminan las comprobaciones, alguien comenta o la rama tiene conflictos. Haz clic para dejar de seguir.", "1cbc8b5db51b4c77": "Fusionar", - "43c5fbd02c6f330a": "Mostrar menos", - "de45b075b016cb14": [ - "Mostrar ", - { - "i": 1, - "k": "_gt_value_1", - "v": "v" - }, - " más" - ], "a3d040c4ef4fc6e9": "Por encima del ritmo", "b16fdf56b16d99c9": "Al ritmo", "90f977e97ae8b6c6": "Por debajo del ritmo", @@ -4083,6 +4099,7 @@ "66be4fb43249bbd2": "{used} de {max} tokens", "ee3ae58c8b38a425": "{left} % restante", "ebb26f93fb83a71b": "{label}: {left} % restante", + "1b16346722b65812": "Queda un {timeLeft}% de la ventana", "728c6cc1431e76c8": "Se restablece en {duration} · {time}", "e16b0b9b490c8bc7": "{label}: {value}", "ba67d0a9ff5dabf0": "La API del portapapeles no está disponible al copiar la solicitud de administrador.", @@ -4176,12 +4193,16 @@ ], "3237699bd13dd4bb": "Detener subagente", "075398ac562d74b0": "Desconectar la sesión del agente", + "1d2025060ba3d1c3": "No se pudo reenviar el puerto {port}", "086ecbb6f4c2e959": "No se puede abrir en el navegador", "51052c00ab1ac8cc": "No se puede abrir la vista previa", "0ccd37739f9cf2b6": "No se pudo detener el servidor", "a610a81c4061bb4c": "Servidores", + "253bc8b5e99002dc": "Reenviado a :{port}", "bd1ca8ccb6d0b87c": "Agente", "e25e045607262b40": "Terminal", + "194a9791a83d3f79": "Dejar de reenviar localhost:{port}", + "95bbbac2f2e17273": "Reenviar localhost:{port} a este equipo", "95b263aa683271cc": "Detener localhost:{port}", "f94866e17faddc05": [ "Abrir en el panel del navegador. ", @@ -4192,6 +4213,16 @@ }, " para tu navegador." ], + "781fba367a220012": [ + "Reenviado a localhost:", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " en este equipo. Haz clic para detenerlo." + ], + "92347683e33e9f02": "Reenviar a este equipo, para cualquier app aquí", "3c7763243445b28d": "Detener servidor", "991cc9fb37606c91": "(respuesta vacía)", "36e4b8d2db087296": "Bifurcar desde esta respuesta", @@ -5931,7 +5962,6 @@ "a74538a7917c1c96": "Reproducir vídeo", "11a5a4d340e6397d": "Abrir original", "1b74242b0d303272": "Descargar vídeo", - "7a462e32dba47f4c": "Abrir en el navegador", "f9ca1e61d515445e": "Falta el contenido de la URL de datos.", "1b547c297573369c": "No se pudo decodificar este contenido en línea.", "84f7c359e5f050b1": "No se pudo obtener el archivo (HTTP {status}).", @@ -11853,7 +11883,6 @@ "0bd938825ffcf992": "+{percent}% del total", "09c0e00d7fb55402": "Usando el crédito de restablecimiento…", "4df3ff1be768a7ab": "{name}: queda un {remaining}%", - "1b16346722b65812": "Queda un {timeLeft}% de la ventana", "7aaaff1c6484f25c": "Segmento", "8bcab2ef61de6518": "Límite de 0 $", "a16b48709357a5a7": "Gestionar uso", diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index a3a16e772103e..24dba2e932684 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -1841,6 +1841,18 @@ "480646ceb98c7163": "Fermer", "32fc9124998ebc18": "Local", "1c4158d741eec5da": "{label} (local)", + "a12a4958ca6b924b": "Port {port} redirigé", + "0f14a51b016f825d": "Les apps de cette machine l’atteignent sur localhost:{port}.", + "4bdb9a086e77ee6d": "Port {port} sur {environment}", + "7a462e32dba47f4c": "Ouvrir dans le navigateur", + "4b8087450e97c995": "Copier l’adresse", + "c170720e67d01733": "Arrêter la redirection", + "1e5c6d1c33667b17": "Rediriger localhost:{port}", + "e76f45b6a412a0b6": "Rediriger le port {port} depuis {environment}", + "ecf3b95b3d9e6e74": "Redirigés", + "b3123e5b8602a134": "Saisis un numéro de port pour le rediriger", + "1bdeef9819b4a055": "Rediriger un port", + "de8a46b66f8ec455": "Ports redirigés", "f844c41fac2d339c": "Actuel", "69154433587763c0": "Aucune action correspondante.", "90c3a382ecefa0ce": "Aucune commande, aucun projet ni aucun fil correspondant.", @@ -2974,6 +2986,10 @@ "314cdccee9c14774": "Ce serveur ne prend pas en charge les recherches dans le registre. Mettez-le à jour avant de changer de canal.", "22da1d00403ab2fd": "Impossible de vérifier le registre npm de cet environnement. Vérifiez la connexion et les paramètres du registre.", "2fc0f7a698c95c90": "Connectez-vous à un serveur pour vérifier les versions.", + "922269f8691aa3ba": "Impossible de savoir si cet environnement tourne sur cet ordinateur.", + "35cade9cc8a01363": "La redirection de ports nécessite l’app de bureau.", + "9e303e0a794898d4": "Cet environnement tourne sur cet ordinateur, donc localhost:{port} l’atteint déjà.", + "2d49965e0e27e23b": "Cet environnement est injoignable pour le moment. Réessaie une fois qu’il est reconnecté.", "7280baf7517dad1c": "Échec du chargement des refs.", "567c0fed6ab8efc1": "Cette connexion ne peut pas rechercher dans les fichiers de l’hôte.", "5189720b9436f98c": "La recherche est limitée à {count} caractères.", @@ -4021,6 +4037,16 @@ } ], "e58a1d884fa1d8f2": "Détails du fil", + "43c5fbd02c6f330a": "Afficher moins", + "de45b075b016cb14": [ + "Afficher ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " de plus" + ], "02d9667ff2c8e0b8": "Ticket {key} : {title}", "4276743ee60a3c62": "{count, plural, one {{count} commentaire} other {{count} commentaires}}", "42f634397f3960aa": "Afficher dans les détails du fil", @@ -4060,16 +4086,6 @@ ], "159ddd0d146a0f22": "Surveillance : l’agent se réveille quand les checks se terminent, que quelqu’un commente ou que la branche entre en conflit. Cliquez pour arrêter.", "1cbc8b5db51b4c77": "Fusionner", - "43c5fbd02c6f330a": "Afficher moins", - "de45b075b016cb14": [ - "Afficher ", - { - "i": 1, - "k": "_gt_value_1", - "v": "v" - }, - " de plus" - ], "a3d040c4ef4fc6e9": "En avance sur le rythme", "b16fdf56b16d99c9": "Dans le rythme", "90f977e97ae8b6c6": "En dessous du rythme", @@ -4084,6 +4100,7 @@ "66be4fb43249bbd2": "{used} tokens sur {max}", "ee3ae58c8b38a425": "{left} % restant", "ebb26f93fb83a71b": "{label} : {left} % restant", + "1b16346722b65812": "{timeLeft} % de la fenêtre restant", "728c6cc1431e76c8": "Réinitialisation dans {duration} · {time}", "e16b0b9b490c8bc7": "{label} : {value}", "ba67d0a9ff5dabf0": "L’API Presse-papiers n’est pas disponible pour copier la demande à l’administrateur.", @@ -4177,12 +4194,16 @@ ], "3237699bd13dd4bb": "Arrêter le sous-agent", "075398ac562d74b0": "Déconnecter la session de l’agent", + "1d2025060ba3d1c3": "Impossible de rediriger le port {port}", "086ecbb6f4c2e959": "Impossible d’ouvrir dans le navigateur", "51052c00ab1ac8cc": "Impossible d’ouvrir l’aperçu", "0ccd37739f9cf2b6": "Impossible d’arrêter le serveur", "a610a81c4061bb4c": "Serveurs", + "253bc8b5e99002dc": "Redirigé vers :{port}", "bd1ca8ccb6d0b87c": "Agent", "e25e045607262b40": "Terminal", + "194a9791a83d3f79": "Arrêter de rediriger localhost:{port}", + "95bbbac2f2e17273": "Rediriger localhost:{port} vers cette machine", "95b263aa683271cc": "Arrêter localhost:{port}", "f94866e17faddc05": [ "Ouvrir dans le panneau du navigateur. ", @@ -4193,6 +4214,16 @@ }, " pour votre navigateur." ], + "781fba367a220012": [ + "Redirigé vers localhost:", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " sur cette machine. Clique pour arrêter." + ], + "92347683e33e9f02": "Rediriger vers cette machine, pour toute app ici", "3c7763243445b28d": "Arrêter le serveur", "991cc9fb37606c91": "(réponse vide)", "36e4b8d2db087296": "Créer un fork depuis cette réponse", @@ -5932,7 +5963,6 @@ "a74538a7917c1c96": "Lire la vidéo", "11a5a4d340e6397d": "Ouvrir l’original", "1b74242b0d303272": "Télécharger la vidéo", - "7a462e32dba47f4c": "Ouvrir dans le navigateur", "f9ca1e61d515445e": "Contenu de la data URL manquant.", "1b547c297573369c": "Impossible de décoder ce média intégré.", "84f7c359e5f050b1": "Impossible de récupérer le fichier (HTTP {status}).", @@ -11858,7 +11888,6 @@ "0bd938825ffcf992": "+{percent} % du quota", "09c0e00d7fb55402": "Utilisation du crédit de réinitialisation…", "4df3ff1be768a7ab": "{name} : {remaining} % restant", - "1b16346722b65812": "{timeLeft} % de la fenêtre restant", "7aaaff1c6484f25c": "Segment", "8bcab2ef61de6518": "Plafond de 0 $", "a16b48709357a5a7": "Gérer l’utilisation", diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index 8459e9cf87854..e88cc490a8590 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -1839,6 +1839,18 @@ "480646ceb98c7163": "閉じる", "32fc9124998ebc18": "ローカル", "1c4158d741eec5da": "{label} (ローカル)", + "a12a4958ca6b924b": "ポート {port} を転送しました", + "0f14a51b016f825d": "このマシンのアプリから localhost:{port} でアクセスできます。", + "4bdb9a086e77ee6d": "{environment} のポート {port}", + "7a462e32dba47f4c": "ブラウザーで開く", + "4b8087450e97c995": "アドレスをコピー", + "c170720e67d01733": "転送を停止", + "1e5c6d1c33667b17": "localhost:{port} を転送", + "e76f45b6a412a0b6": "{environment} からポート {port} を転送", + "ecf3b95b3d9e6e74": "転送中", + "b3123e5b8602a134": "転送するポート番号を入力", + "1bdeef9819b4a055": "ポートを転送", + "de8a46b66f8ec455": "転送中のポート", "f844c41fac2d339c": "現在", "69154433587763c0": "一致するアクションはありません。", "90c3a382ecefa0ce": "一致するコマンド、プロジェクト、スレッドはありません。", @@ -2972,6 +2984,10 @@ "314cdccee9c14774": "このサーバーはレジストリの検索をサポートしていません。トラックを切り替える前に更新してください。", "22da1d00403ab2fd": "この環境の npm レジストリを確認できませんでした。接続とレジストリの設定を確認してください。", "2fc0f7a698c95c90": "リリースを確認するにはサーバーに接続してください。", + "922269f8691aa3ba": "この環境がこのコンピューターで動いているか判断できませんでした。", + "35cade9cc8a01363": "ポート転送にはデスクトップアプリが必要です。", + "9e303e0a794898d4": "この環境はこのコンピューターで動いているため、localhost:{port} で既にアクセスできます。", + "2d49965e0e27e23b": "現在この環境に接続できません。再接続されてからもう一度お試しください。", "7280baf7517dad1c": "ref を読み込めませんでした。", "567c0fed6ab8efc1": "この接続ではホストのファイルを検索できません。", "5189720b9436f98c": "検索は {count} 文字までです。", @@ -4011,6 +4027,16 @@ } ], "e58a1d884fa1d8f2": "スレッドの詳細", + "43c5fbd02c6f330a": "表示を減らす", + "de45b075b016cb14": [ + "さらに ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " 件を表示" + ], "02d9667ff2c8e0b8": "Issue {key}: {title}", "4276743ee60a3c62": "{count, plural, other {{count} 件のコメント}}", "42f634397f3960aa": "スレッドの詳細に表示", @@ -4050,16 +4076,6 @@ ], "159ddd0d146a0f22": "監視中: チェックの完了、コメントの追加、ブランチの競合が発生するとエージェントが起動します。クリックすると停止します。", "1cbc8b5db51b4c77": "マージ", - "43c5fbd02c6f330a": "表示を減らす", - "de45b075b016cb14": [ - "さらに ", - { - "i": 1, - "k": "_gt_value_1", - "v": "v" - }, - " 件を表示" - ], "a3d040c4ef4fc6e9": "ペースより速い", "b16fdf56b16d99c9": "ペースどおり", "90f977e97ae8b6c6": "ペースより遅い", @@ -4074,6 +4090,7 @@ "66be4fb43249bbd2": "{used} / {max} トークン", "ee3ae58c8b38a425": "残り {left}%", "ebb26f93fb83a71b": "{label}: 残り {left}%", + "1b16346722b65812": "期間の残り {timeLeft}%", "728c6cc1431e76c8": "{duration} 後にリセット · {time}", "e16b0b9b490c8bc7": "{label}: {value}", "ba67d0a9ff5dabf0": "管理者へのリクエストをコピーする際にクリップボード API を利用できませんでした。", @@ -4167,12 +4184,16 @@ ], "3237699bd13dd4bb": "サブエージェントを停止", "075398ac562d74b0": "エージェントのセッションを切断", + "1d2025060ba3d1c3": "ポート {port} を転送できませんでした", "086ecbb6f4c2e959": "ブラウザーで開けません", "51052c00ab1ac8cc": "プレビューを開けません", "0ccd37739f9cf2b6": "サーバーを停止できませんでした", "a610a81c4061bb4c": "サーバー", + "253bc8b5e99002dc": ":{port} に転送中", "bd1ca8ccb6d0b87c": "エージェント", "e25e045607262b40": "ターミナル", + "194a9791a83d3f79": "localhost:{port} の転送を停止", + "95bbbac2f2e17273": "localhost:{port} をこのマシンに転送", "95b263aa683271cc": "localhost:{port} を停止", "f94866e17faddc05": [ "ブラウザーパネルで開きます。", @@ -4183,6 +4204,16 @@ }, " で自分のブラウザーで開きます。" ], + "781fba367a220012": [ + "このマシンの localhost:", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " に転送中です。クリックで停止します。" + ], + "92347683e33e9f02": "このマシンに転送し、ここのどのアプリからも使えるようにする", "3c7763243445b28d": "サーバーを停止", "991cc9fb37606c91": "(空のレスポンス)", "36e4b8d2db087296": "この応答からフォーク", @@ -5913,7 +5944,6 @@ "a74538a7917c1c96": "動画を再生", "11a5a4d340e6397d": "元のファイルを開く", "1b74242b0d303272": "動画をダウンロード", - "7a462e32dba47f4c": "ブラウザーで開く", "f9ca1e61d515445e": "データ URL のペイロードがありません。", "1b547c297573369c": "このインラインメディアをデコードできませんでした。", "84f7c359e5f050b1": "ファイルを取得できませんでした (HTTP {status})。", @@ -11808,7 +11838,6 @@ "0bd938825ffcf992": "プールの +{percent}%", "09c0e00d7fb55402": "リセットクレジットを使用しています…", "4df3ff1be768a7ab": "{name}: 残り {remaining}%", - "1b16346722b65812": "期間の残り {timeLeft}%", "7aaaff1c6484f25c": "セグメント", "8bcab2ef61de6518": "上限 $0", "a16b48709357a5a7": "使用量を管理", diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index c523c5dc7b1fc..c80d5dc373208 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -1841,6 +1841,18 @@ "480646ceb98c7163": "닫기", "32fc9124998ebc18": "로컬", "1c4158d741eec5da": "{label}(로컬)", + "a12a4958ca6b924b": "포트 {port}을(를) 포워딩했습니다", + "0f14a51b016f825d": "이 컴퓨터의 앱에서 localhost:{port}로 접속할 수 있습니다.", + "4bdb9a086e77ee6d": "{environment}의 포트 {port}", + "7a462e32dba47f4c": "브라우저에서 열기", + "4b8087450e97c995": "주소 복사", + "c170720e67d01733": "포워딩 중지", + "1e5c6d1c33667b17": "localhost:{port} 포워딩", + "e76f45b6a412a0b6": "{environment}에서 포트 {port} 포워딩", + "ecf3b95b3d9e6e74": "포워딩됨", + "b3123e5b8602a134": "포워딩할 포트 번호를 입력하세요", + "1bdeef9819b4a055": "포트 포워딩", + "de8a46b66f8ec455": "포워딩된 포트", "f844c41fac2d339c": "현재", "69154433587763c0": "일치하는 작업이 없습니다.", "90c3a382ecefa0ce": "일치하는 명령, 프로젝트, 스레드가 없습니다.", @@ -2973,6 +2985,10 @@ "314cdccee9c14774": "이 서버는 레지스트리 조회를 지원하지 않습니다. 트랙을 전환하기 전에 업데이트하세요.", "22da1d00403ab2fd": "이 환경의 npm 레지스트리를 확인할 수 없습니다. 연결 및 레지스트리 설정을 확인하세요.", "2fc0f7a698c95c90": "릴리스를 확인하려면 서버에 연결하세요.", + "922269f8691aa3ba": "이 환경이 이 컴퓨터에서 실행 중인지 확인할 수 없습니다.", + "35cade9cc8a01363": "포트 포워딩은 데스크톱 앱이 필요합니다.", + "9e303e0a794898d4": "이 환경은 이 컴퓨터에서 실행 중이므로 localhost:{port}로 이미 접속할 수 있습니다.", + "2d49965e0e27e23b": "지금은 이 환경에 연결할 수 없습니다. 다시 연결되면 다시 시도하세요.", "7280baf7517dad1c": "참조를 불러오지 못했습니다.", "567c0fed6ab8efc1": "이 연결로는 호스트 파일을 검색할 수 없습니다.", "5189720b9436f98c": "검색어는 {count}자로 제한됩니다.", @@ -4009,6 +4025,15 @@ } ], "e58a1d884fa1d8f2": "스레드 세부 정보", + "43c5fbd02c6f330a": "간략히 보기", + "de45b075b016cb14": [ + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + "개 더 보기" + ], "02d9667ff2c8e0b8": "이슈 {key}: {title}", "4276743ee60a3c62": "{count, plural, other {댓글 {count}개}}", "42f634397f3960aa": "스레드 세부 정보에 표시", @@ -4048,15 +4073,6 @@ ], "159ddd0d146a0f22": "지켜보는 중: 검사가 끝나거나, 누군가 댓글을 달거나, 브랜치가 충돌하면 에이전트가 깨어납니다. 클릭하여 중지하세요.", "1cbc8b5db51b4c77": "병합", - "43c5fbd02c6f330a": "간략히 보기", - "de45b075b016cb14": [ - { - "i": 1, - "k": "_gt_value_1", - "v": "v" - }, - "개 더 보기" - ], "a3d040c4ef4fc6e9": "예상보다 빠름", "b16fdf56b16d99c9": "예상대로", "90f977e97ae8b6c6": "예상보다 느림", @@ -4071,6 +4087,7 @@ "66be4fb43249bbd2": "토큰 {max}개 중 {used}개", "ee3ae58c8b38a425": "{left}% 남음", "ebb26f93fb83a71b": "{label}: {left}% 남음", + "1b16346722b65812": "기간 {timeLeft}% 남음", "728c6cc1431e76c8": "{duration} 후 초기화 · {time}", "e16b0b9b490c8bc7": "{label}: {value}", "ba67d0a9ff5dabf0": "관리자 요청을 복사하는 중 클립보드 API를 사용할 수 없습니다.", @@ -4164,12 +4181,16 @@ ], "3237699bd13dd4bb": "서브에이전트 중지", "075398ac562d74b0": "에이전트 세션 연결 끊기", + "1d2025060ba3d1c3": "포트 {port}을(를) 포워딩할 수 없습니다", "086ecbb6f4c2e959": "브라우저에서 열 수 없습니다", "51052c00ab1ac8cc": "미리 보기를 열 수 없습니다", "0ccd37739f9cf2b6": "서버를 중지할 수 없습니다", "a610a81c4061bb4c": "서버", + "253bc8b5e99002dc": ":{port}로 포워딩됨", "bd1ca8ccb6d0b87c": "에이전트", "e25e045607262b40": "터미널", + "194a9791a83d3f79": "localhost:{port} 포워딩 중지", + "95bbbac2f2e17273": "localhost:{port}을(를) 이 컴퓨터로 포워딩", "95b263aa683271cc": "localhost:{port} 중지", "f94866e17faddc05": [ "브라우저 패널에서 엽니다. ", @@ -4180,6 +4201,16 @@ }, "하면 내 브라우저에서 엽니다." ], + "781fba367a220012": [ + "이 컴퓨터의 localhost:", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + "(으)로 포워딩 중입니다. 클릭하면 중지합니다." + ], + "92347683e33e9f02": "이 컴퓨터로 포워딩해 여기 있는 모든 앱에서 사용", "3c7763243445b28d": "서버 중지", "991cc9fb37606c91": "(빈 응답)", "36e4b8d2db087296": "이 응답에서 포크", @@ -5911,7 +5942,6 @@ "a74538a7917c1c96": "동영상 재생", "11a5a4d340e6397d": "원본 열기", "1b74242b0d303272": "동영상 다운로드", - "7a462e32dba47f4c": "브라우저에서 열기", "f9ca1e61d515445e": "데이터 URL 페이로드가 없습니다.", "1b547c297573369c": "이 인라인 미디어를 디코딩할 수 없습니다.", "84f7c359e5f050b1": "파일을 가져올 수 없습니다(HTTP {status}).", @@ -11805,7 +11835,6 @@ "0bd938825ffcf992": "풀의 +{percent}%", "09c0e00d7fb55402": "초기화 크레딧 사용 중…", "4df3ff1be768a7ab": "{name}: {remaining}% 남음", - "1b16346722b65812": "기간 {timeLeft}% 남음", "7aaaff1c6484f25c": "구간", "8bcab2ef61de6518": "$0 한도", "a16b48709357a5a7": "사용량 관리", diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index bd34cd96c3d8b..a2a2daa2b7ccc 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -1841,6 +1841,18 @@ "480646ceb98c7163": "Fechar", "32fc9124998ebc18": "Local", "1c4158d741eec5da": "{label} (local)", + "a12a4958ca6b924b": "Porta {port} encaminhada", + "0f14a51b016f825d": "Os apps desta máquina a acessam em localhost:{port}.", + "4bdb9a086e77ee6d": "Porta {port} em {environment}", + "7a462e32dba47f4c": "Abrir no navegador", + "4b8087450e97c995": "Copiar endereço", + "c170720e67d01733": "Parar de encaminhar", + "1e5c6d1c33667b17": "Encaminhar localhost:{port}", + "e76f45b6a412a0b6": "Encaminhar a porta {port} de {environment}", + "ecf3b95b3d9e6e74": "Encaminhadas", + "b3123e5b8602a134": "Digite um número de porta para encaminhá-la", + "1bdeef9819b4a055": "Encaminhar uma porta", + "de8a46b66f8ec455": "Portas encaminhadas", "f844c41fac2d339c": "Atual", "69154433587763c0": "Nenhuma ação correspondente.", "90c3a382ecefa0ce": "Nenhum comando, projeto ou thread correspondente.", @@ -2974,6 +2986,10 @@ "314cdccee9c14774": "Este servidor não permite consultas ao registro. Atualize-o antes de trocar de canal.", "22da1d00403ab2fd": "Não foi possível verificar o registro npm deste ambiente. Verifique a conexão e as configurações do registro.", "2fc0f7a698c95c90": "Conecte-se a um servidor para verificar as versões.", + "922269f8691aa3ba": "Não foi possível saber se este ambiente roda neste computador.", + "35cade9cc8a01363": "O encaminhamento de portas precisa do app para desktop.", + "9e303e0a794898d4": "Este ambiente roda neste computador, então localhost:{port} já o alcança.", + "2d49965e0e27e23b": "Não é possível acessar este ambiente agora. Tente novamente quando ele se reconectar.", "7280baf7517dad1c": "Falha ao carregar as refs.", "567c0fed6ab8efc1": "Esta conexão não pode pesquisar arquivos do host.", "5189720b9436f98c": "A pesquisa é limitada a {count} caracteres.", @@ -4021,6 +4037,15 @@ } ], "e58a1d884fa1d8f2": "Detalhes da thread", + "43c5fbd02c6f330a": "Mostrar menos", + "de45b075b016cb14": [ + "Mostrar mais ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + } + ], "02d9667ff2c8e0b8": "Issue {key}: {title}", "4276743ee60a3c62": "{count, plural, one {{count} comentário} other {{count} comentários}}", "42f634397f3960aa": "Mostrar nos detalhes da thread", @@ -4060,15 +4085,6 @@ ], "159ddd0d146a0f22": "Acompanhando: o agente é ativado quando as verificações terminam, alguém comenta ou o branch entra em conflito. Clique para parar.", "1cbc8b5db51b4c77": "Mesclar", - "43c5fbd02c6f330a": "Mostrar menos", - "de45b075b016cb14": [ - "Mostrar mais ", - { - "i": 1, - "k": "_gt_value_1", - "v": "v" - } - ], "a3d040c4ef4fc6e9": "Acima do ritmo", "b16fdf56b16d99c9": "No ritmo", "90f977e97ae8b6c6": "Abaixo do ritmo", @@ -4083,6 +4099,7 @@ "66be4fb43249bbd2": "{used} de {max} tokens", "ee3ae58c8b38a425": "{left}% restante", "ebb26f93fb83a71b": "{label}: {left}% restante", + "1b16346722b65812": "{timeLeft}% da janela restante", "728c6cc1431e76c8": "Renova em {duration} · {time}", "e16b0b9b490c8bc7": "{label}: {value}", "ba67d0a9ff5dabf0": "A API da área de transferência não está disponível ao copiar o pedido para o administrador.", @@ -4176,12 +4193,16 @@ ], "3237699bd13dd4bb": "Parar subagente", "075398ac562d74b0": "Desconectar a sessão do agente", + "1d2025060ba3d1c3": "Não foi possível encaminhar a porta {port}", "086ecbb6f4c2e959": "Não foi possível abrir no navegador", "51052c00ab1ac8cc": "Não foi possível abrir a pré-visualização", "0ccd37739f9cf2b6": "Não foi possível parar o servidor", "a610a81c4061bb4c": "Servidores", + "253bc8b5e99002dc": "Encaminhada para :{port}", "bd1ca8ccb6d0b87c": "Agente", "e25e045607262b40": "Terminal", + "194a9791a83d3f79": "Parar de encaminhar localhost:{port}", + "95bbbac2f2e17273": "Encaminhar localhost:{port} para esta máquina", "95b263aa683271cc": "Parar localhost:{port}", "f94866e17faddc05": [ "Abrir no painel do navegador. ", @@ -4192,6 +4213,16 @@ }, " para o seu navegador." ], + "781fba367a220012": [ + "Encaminhada para localhost:", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " nesta máquina. Clique para parar." + ], + "92347683e33e9f02": "Encaminhar para esta máquina, para qualquer app aqui", "3c7763243445b28d": "Parar servidor", "991cc9fb37606c91": "(resposta vazia)", "36e4b8d2db087296": "Criar fork a partir desta resposta", @@ -5931,7 +5962,6 @@ "a74538a7917c1c96": "Reproduzir vídeo", "11a5a4d340e6397d": "Abrir original", "1b74242b0d303272": "Baixar vídeo", - "7a462e32dba47f4c": "Abrir no navegador", "f9ca1e61d515445e": "Falta o conteúdo da data URL.", "1b547c297573369c": "Não foi possível decodificar esta mídia em linha.", "84f7c359e5f050b1": "Não foi possível buscar o arquivo (HTTP {status}).", @@ -11857,7 +11887,6 @@ "0bd938825ffcf992": "+{percent}% do total", "09c0e00d7fb55402": "Usando crédito de redefinição…", "4df3ff1be768a7ab": "{name}: {remaining}% restante", - "1b16346722b65812": "{timeLeft}% da janela restante", "7aaaff1c6484f25c": "Segmento", "8bcab2ef61de6518": "Limite de $0", "a16b48709357a5a7": "Gerenciar uso", diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index 4242d78d5f3c5..852b80217f746 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -1841,6 +1841,18 @@ "480646ceb98c7163": "Закрыть", "32fc9124998ebc18": "Локально", "1c4158d741eec5da": "{label} (локально)", + "a12a4958ca6b924b": "Порт {port} перенаправлен", + "0f14a51b016f825d": "Приложения на этом компьютере открывают его по адресу localhost:{port}.", + "4bdb9a086e77ee6d": "Порт {port} в {environment}", + "7a462e32dba47f4c": "Открыть в браузере", + "4b8087450e97c995": "Копировать адрес", + "c170720e67d01733": "Остановить перенаправление", + "1e5c6d1c33667b17": "Перенаправить localhost:{port}", + "e76f45b6a412a0b6": "Перенаправить порт {port} из {environment}", + "ecf3b95b3d9e6e74": "Перенаправленные", + "b3123e5b8602a134": "Введите номер порта, чтобы перенаправить его", + "1bdeef9819b4a055": "Перенаправить порт", + "de8a46b66f8ec455": "Перенаправленные порты", "f844c41fac2d339c": "Текущий", "69154433587763c0": "Нет подходящих действий.", "90c3a382ecefa0ce": "Нет подходящих команд, проектов или тредов.", @@ -2974,6 +2986,10 @@ "314cdccee9c14774": "Этот сервер не поддерживает запросы к реестру. Обновите его перед сменой канала.", "22da1d00403ab2fd": "Не удалось проверить реестр npm этого окружения. Проверьте подключение и настройки реестра.", "2fc0f7a698c95c90": "Подключитесь к серверу, чтобы проверить выпуски.", + "922269f8691aa3ba": "Не удалось определить, работает ли это окружение на этом компьютере.", + "35cade9cc8a01363": "Для перенаправления портов нужно приложение для компьютера.", + "9e303e0a794898d4": "Это окружение работает на этом компьютере, поэтому localhost:{port} уже ведёт к нему.", + "2d49965e0e27e23b": "Сейчас это окружение недоступно. Попробуйте снова, когда оно переподключится.", "7280baf7517dad1c": "Не удалось загрузить ссылки.", "567c0fed6ab8efc1": "Это подключение не может искать файлы на хосте.", "5189720b9436f98c": "Поиск ограничен {count} символами.", @@ -4021,6 +4037,15 @@ } ], "e58a1d884fa1d8f2": "Сведения о треде", + "43c5fbd02c6f330a": "Показать меньше", + "de45b075b016cb14": [ + "Показать ещё ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + } + ], "02d9667ff2c8e0b8": "Issue {key}: {title}", "4276743ee60a3c62": "{count, plural, one {{count} комментарий} few {{count} комментария} many {{count} комментариев} other {{count} комментария}}", "42f634397f3960aa": "Показывать в сведениях о треде", @@ -4060,15 +4085,6 @@ ], "159ddd0d146a0f22": "Отслеживается: агент проснётся, когда завершатся проверки, кто-то оставит комментарий или в ветке появится конфликт. Нажмите, чтобы прекратить.", "1cbc8b5db51b4c77": "Слить", - "43c5fbd02c6f330a": "Показать меньше", - "de45b075b016cb14": [ - "Показать ещё ", - { - "i": 1, - "k": "_gt_value_1", - "v": "v" - } - ], "a3d040c4ef4fc6e9": "Быстрее темпа", "b16fdf56b16d99c9": "В темпе", "90f977e97ae8b6c6": "Медленнее темпа", @@ -4083,6 +4099,7 @@ "66be4fb43249bbd2": "{used} из {max} токенов", "ee3ae58c8b38a425": "Осталось {left}%", "ebb26f93fb83a71b": "{label}: осталось {left}%", + "1b16346722b65812": "От окна осталось {timeLeft}%", "728c6cc1431e76c8": "Сброс через {duration} · {time}", "e16b0b9b490c8bc7": "{label}: {value}", "ba67d0a9ff5dabf0": "API буфера обмена недоступен при копировании запроса администратору.", @@ -4176,12 +4193,16 @@ ], "3237699bd13dd4bb": "Остановить субагента", "075398ac562d74b0": "Отключить сеанс агента", + "1d2025060ba3d1c3": "Не удалось перенаправить порт {port}", "086ecbb6f4c2e959": "Не удалось открыть в браузере", "51052c00ab1ac8cc": "Не удалось открыть предпросмотр", "0ccd37739f9cf2b6": "Не удалось остановить сервер", "a610a81c4061bb4c": "Серверы", + "253bc8b5e99002dc": "Перенаправлен на :{port}", "bd1ca8ccb6d0b87c": "Агент", "e25e045607262b40": "Терминал", + "194a9791a83d3f79": "Остановить перенаправление localhost:{port}", + "95bbbac2f2e17273": "Перенаправить localhost:{port} на этот компьютер", "95b263aa683271cc": "Остановить localhost:{port}", "f94866e17faddc05": [ "Открыть в панели браузера. ", @@ -4192,6 +4213,16 @@ }, " — в вашем браузере." ], + "781fba367a220012": [ + "Перенаправлен на localhost:", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " на этом компьютере. Нажмите, чтобы остановить." + ], + "92347683e33e9f02": "Перенаправить на этот компьютер для любых приложений", "3c7763243445b28d": "Остановить сервер", "991cc9fb37606c91": "(пустой ответ)", "36e4b8d2db087296": "Ответвить от этого ответа", @@ -5931,7 +5962,6 @@ "a74538a7917c1c96": "Воспроизвести видео", "11a5a4d340e6397d": "Открыть оригинал", "1b74242b0d303272": "Скачать видео", - "7a462e32dba47f4c": "Открыть в браузере", "f9ca1e61d515445e": "Нет данных data URL.", "1b547c297573369c": "Не удалось декодировать это встроенное медиа.", "84f7c359e5f050b1": "Не удалось получить файл (HTTP {status}).", @@ -11858,7 +11888,6 @@ "0bd938825ffcf992": "+{percent}% пула", "09c0e00d7fb55402": "Использование кредита на сброс…", "4df3ff1be768a7ab": "{name}: осталось {remaining}%", - "1b16346722b65812": "От окна осталось {timeLeft}%", "7aaaff1c6484f25c": "Сегмент", "8bcab2ef61de6518": "Лимит $0", "a16b48709357a5a7": "Управление использованием", diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index d3d7bec015020..f8c06f7408c75 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -1841,6 +1841,18 @@ "480646ceb98c7163": "Stäng", "32fc9124998ebc18": "Lokal", "1c4158d741eec5da": "{label} (lokal)", + "a12a4958ca6b924b": "Port {port} vidarebefordrad", + "0f14a51b016f825d": "Appar på den här datorn når den på localhost:{port}.", + "4bdb9a086e77ee6d": "Port {port} på {environment}", + "7a462e32dba47f4c": "Öppna i webbläsaren", + "4b8087450e97c995": "Kopiera adress", + "c170720e67d01733": "Sluta vidarebefordra", + "1e5c6d1c33667b17": "Vidarebefordra localhost:{port}", + "e76f45b6a412a0b6": "Vidarebefordra port {port} från {environment}", + "ecf3b95b3d9e6e74": "Vidarebefordrade", + "b3123e5b8602a134": "Skriv ett portnummer för att vidarebefordra det", + "1bdeef9819b4a055": "Vidarebefordra en port", + "de8a46b66f8ec455": "Vidarebefordrade portar", "f844c41fac2d339c": "Aktuellt", "69154433587763c0": "Inga matchande åtgärder.", "90c3a382ecefa0ce": "Inga matchande kommandon, projekt eller trådar.", @@ -2974,6 +2986,10 @@ "314cdccee9c14774": "Den här servern stöder inte registeruppslag. Uppdatera den innan du byter spår.", "22da1d00403ab2fd": "Kunde inte kontrollera den här miljöns npm-register. Kontrollera anslutningen och registerinställningarna.", "2fc0f7a698c95c90": "Anslut till en server för att söka efter versioner.", + "922269f8691aa3ba": "Det gick inte att avgöra om den här miljön körs på den här datorn.", + "35cade9cc8a01363": "Portvidarebefordring kräver skrivbordsappen.", + "9e303e0a794898d4": "Den här miljön körs på den här datorn, så localhost:{port} når den redan.", + "2d49965e0e27e23b": "Den här miljön går inte att nå just nu. Försök igen när den har anslutit igen.", "7280baf7517dad1c": "Det gick inte att läsa in refs.", "567c0fed6ab8efc1": "Den här anslutningen kan inte söka i värdens filer.", "5189720b9436f98c": "Sökningen är begränsad till {count} tecken.", @@ -4021,6 +4037,16 @@ } ], "e58a1d884fa1d8f2": "Tråddetaljer", + "43c5fbd02c6f330a": "Visa mindre", + "de45b075b016cb14": [ + "Visa ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " till" + ], "02d9667ff2c8e0b8": "Ärende {key}: {title}", "4276743ee60a3c62": "{count, plural, one {{count} kommentar} other {{count} kommentarer}}", "42f634397f3960aa": "Visa i tråddetaljer", @@ -4060,16 +4086,6 @@ ], "159ddd0d146a0f22": "Bevakar: agenten vaknar när kontrollerna är klara, någon kommenterar eller grenen får konflikter. Klicka för att sluta.", "1cbc8b5db51b4c77": "Merga", - "43c5fbd02c6f330a": "Visa mindre", - "de45b075b016cb14": [ - "Visa ", - { - "i": 1, - "k": "_gt_value_1", - "v": "v" - }, - " till" - ], "a3d040c4ef4fc6e9": "Före takten", "b16fdf56b16d99c9": "I takt", "90f977e97ae8b6c6": "Under takten", @@ -4084,6 +4100,7 @@ "66be4fb43249bbd2": "{used} av {max} token", "ee3ae58c8b38a425": "{left} % kvar", "ebb26f93fb83a71b": "{label}: {left} % kvar", + "1b16346722b65812": "{timeLeft} % av fönstret kvar", "728c6cc1431e76c8": "Återställs om {duration} · {time}", "e16b0b9b490c8bc7": "{label}: {value}", "ba67d0a9ff5dabf0": "Urklipps-API:t är inte tillgängligt vid kopiering av administratörsbegäran.", @@ -4177,12 +4194,16 @@ ], "3237699bd13dd4bb": "Stoppa subagent", "075398ac562d74b0": "Koppla från agentsession", + "1d2025060ba3d1c3": "Kunde inte vidarebefordra port {port}", "086ecbb6f4c2e959": "Det gick inte att öppna i webbläsaren", "51052c00ab1ac8cc": "Det gick inte att öppna förhandsvisningen", "0ccd37739f9cf2b6": "Kunde inte stoppa servern", "a610a81c4061bb4c": "Servrar", + "253bc8b5e99002dc": "Vidarebefordrad till :{port}", "bd1ca8ccb6d0b87c": "Agent", "e25e045607262b40": "Terminal", + "194a9791a83d3f79": "Sluta vidarebefordra localhost:{port}", + "95bbbac2f2e17273": "Vidarebefordra localhost:{port} till den här datorn", "95b263aa683271cc": "Stoppa localhost:{port}", "f94866e17faddc05": [ "Öppna i webbläsarpanelen. ", @@ -4193,6 +4214,16 @@ }, " för din webbläsare." ], + "781fba367a220012": [ + "Vidarebefordrad till localhost:", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " på den här datorn. Klicka för att stoppa." + ], + "92347683e33e9f02": "Vidarebefordra till den här datorn, för alla appar här", "3c7763243445b28d": "Stoppa server", "991cc9fb37606c91": "(tomt svar)", "36e4b8d2db087296": "Forka från det här svaret", @@ -5932,7 +5963,6 @@ "a74538a7917c1c96": "Spela upp video", "11a5a4d340e6397d": "Öppna original", "1b74242b0d303272": "Ladda ned video", - "7a462e32dba47f4c": "Öppna i webbläsaren", "f9ca1e61d515445e": "Data-URL:ens innehåll saknas.", "1b547c297573369c": "Det här inbäddade mediet kunde inte avkodas.", "84f7c359e5f050b1": "Filen kunde inte hämtas (HTTP {status}).", @@ -11866,7 +11896,6 @@ "0bd938825ffcf992": "+{percent} % av poolen", "09c0e00d7fb55402": "Använder återställningskredit…", "4df3ff1be768a7ab": "{name}: {remaining} % kvar", - "1b16346722b65812": "{timeLeft} % av fönstret kvar", "7aaaff1c6484f25c": "Segment", "8bcab2ef61de6518": "Tak på 0 $", "a16b48709357a5a7": "Hantera användning", diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index 5923adef292f5..74245c4e54300 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -1842,6 +1842,18 @@ "480646ceb98c7163": "关闭", "32fc9124998ebc18": "本地", "1c4158d741eec5da": "{label}(本地)", + "a12a4958ca6b924b": "已转发端口 {port}", + "0f14a51b016f825d": "本机上的应用可通过 localhost:{port} 访问它。", + "4bdb9a086e77ee6d": "{environment} 上的端口 {port}", + "7a462e32dba47f4c": "在浏览器中打开", + "4b8087450e97c995": "复制地址", + "c170720e67d01733": "停止转发", + "1e5c6d1c33667b17": "转发 localhost:{port}", + "e76f45b6a412a0b6": "从 {environment} 转发端口 {port}", + "ecf3b95b3d9e6e74": "已转发", + "b3123e5b8602a134": "输入端口号以转发", + "1bdeef9819b4a055": "转发端口", + "de8a46b66f8ec455": "已转发的端口", "f844c41fac2d339c": "当前", "69154433587763c0": "没有匹配的操作。", "90c3a382ecefa0ce": "没有匹配的命令、项目或会话。", @@ -2978,6 +2990,10 @@ "314cdccee9c14774": "此服务器不支持查询仓库。请先更新,再切换通道。", "22da1d00403ab2fd": "无法检查此环境的 npm 仓库。请检查连接和仓库设置。", "2fc0f7a698c95c90": "连接一个服务器以检查版本。", + "922269f8691aa3ba": "无法判断此环境是否运行在这台计算机上。", + "35cade9cc8a01363": "端口转发需要桌面应用。", + "9e303e0a794898d4": "此环境运行在这台计算机上,localhost:{port} 已经可以访问它。", + "2d49965e0e27e23b": "目前无法访问此环境。请在它重新连接后再试。", "7280baf7517dad1c": "无法加载引用。", "567c0fed6ab8efc1": "此连接无法搜索主机文件。", "5189720b9436f98c": "搜索最多 {count} 个字符。", @@ -4026,6 +4042,16 @@ } ], "e58a1d884fa1d8f2": "会话详情", + "43c5fbd02c6f330a": "收起", + "de45b075b016cb14": [ + "再显示 ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " 个" + ], "02d9667ff2c8e0b8": "issue {key}:{title}", "4276743ee60a3c62": "{count, plural, other {{count} 条评论}}", "42f634397f3960aa": "在会话详情中显示", @@ -4066,16 +4092,6 @@ ], "159ddd0d146a0f22": "关注中:检查完成、有人评论或分支出现冲突时,智能体会被唤醒。点击停止关注。", "1cbc8b5db51b4c77": "合并", - "43c5fbd02c6f330a": "收起", - "de45b075b016cb14": [ - "再显示 ", - { - "i": 1, - "k": "_gt_value_1", - "v": "v" - }, - " 个" - ], "a3d040c4ef4fc6e9": "用量消耗偏快", "b16fdf56b16d99c9": "用量消耗适中", "90f977e97ae8b6c6": "用量消耗偏慢", @@ -4090,6 +4106,7 @@ "66be4fb43249bbd2": "{used} / {max} token", "ee3ae58c8b38a425": "剩余 {left}%", "ebb26f93fb83a71b": "{label}:剩余 {left}%", + "1b16346722b65812": "窗口剩余 {timeLeft}%", "728c6cc1431e76c8": "{duration} 后重置 · {time}", "e16b0b9b490c8bc7": "{label}:{value}", "ba67d0a9ff5dabf0": "复制管理员请求时剪贴板 API 不可用。", @@ -4183,12 +4200,16 @@ ], "3237699bd13dd4bb": "停止子智能体", "075398ac562d74b0": "断开智能体会话", + "1d2025060ba3d1c3": "无法转发端口 {port}", "086ecbb6f4c2e959": "无法在浏览器中打开", "51052c00ab1ac8cc": "无法打开预览", "0ccd37739f9cf2b6": "无法停止服务器", "a610a81c4061bb4c": "服务器", + "253bc8b5e99002dc": "已转发到 :{port}", "bd1ca8ccb6d0b87c": "智能体", "e25e045607262b40": "终端", + "194a9791a83d3f79": "停止转发 localhost:{port}", + "95bbbac2f2e17273": "将 localhost:{port} 转发到本机", "95b263aa683271cc": "停止 localhost:{port}", "f94866e17faddc05": [ "在浏览器面板中打开。", @@ -4199,6 +4220,16 @@ }, " 以在你的浏览器中打开。" ], + "781fba367a220012": [ + "已转发到本机的 localhost:", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + "。点击停止。" + ], + "92347683e33e9f02": "转发到本机,供这里的任何应用使用", "3c7763243445b28d": "停止服务器", "991cc9fb37606c91": "(空响应)", "36e4b8d2db087296": "从这条回复分叉", @@ -5938,7 +5969,6 @@ "a74538a7917c1c96": "播放视频", "11a5a4d340e6397d": "打开原始链接", "1b74242b0d303272": "下载视频", - "7a462e32dba47f4c": "在浏览器中打开", "f9ca1e61d515445e": "缺少 data URL 数据。", "1b547c297573369c": "无法解码此内嵌媒体。", "84f7c359e5f050b1": "无法获取该文件(HTTP {status})。", @@ -11883,7 +11913,6 @@ "0bd938825ffcf992": "+{percent}%(按共享池总额度计算)", "09c0e00d7fb55402": "正在使用重置额度…", "4df3ff1be768a7ab": "{name}:剩余 {remaining}%", - "1b16346722b65812": "窗口剩余 {timeLeft}%", "7aaaff1c6484f25c": "分段", "8bcab2ef61de6518": "上限 $0", "a16b48709357a5a7": "管理用量", diff --git a/apps/web/src/state/portForwards.ts b/apps/web/src/state/portForwards.ts new file mode 100644 index 0000000000000..3a0c767791bfb --- /dev/null +++ b/apps/web/src/state/portForwards.ts @@ -0,0 +1,152 @@ +import { useAtomValue } from "@effect/atom-react"; +import type { DesktopPortForward, EnvironmentId } from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; +import * as Queue from "effect/Queue"; +import * as Schema from "effect/Schema"; +import * as Stream from "effect/Stream"; +import * as AsyncResult from "effect/reactivity/AsyncResult"; +import { Atom } from "effect/reactivity"; +import { msg } from "gt-react"; + +import type { ConnectionTarget } from "@t3tools/client-runtime/connection"; + +import { tunnelsEnvironmentLoopback } from "../browser/browserTargetResolver"; +import { m } from "../i18n/messages"; +import { environmentAtomList } from "./environmentAtomList"; +import { environmentSession } from "./session"; + +const EMPTY_FORWARDS: ReadonlyArray = []; + +const previewBridge = () => + typeof window === "undefined" ? undefined : window.desktopBridge?.preview; + +/** Ports of other environments the desktop app forwards to this machine; empty elsewhere. */ +const portForwardsAtom = Atom.make( + Stream.callback>((queue) => + Effect.gen(function* () { + const bridge = previewBridge(); + if (!bridge) return yield* Effect.never; + let changed = false; + yield* Effect.acquireRelease( + Effect.sync(() => + bridge.onPortForwards((forwards) => { + changed = true; + Queue.offerUnsafe(queue, forwards); + }), + ), + (unsubscribe) => Effect.sync(unsubscribe), + ); + const initial = yield* Effect.promise(() => bridge.listPortForwards()); + if (!changed) Queue.offerUnsafe(queue, initial); + return yield* Effect.never; + }), + ), + { initialValue: EMPTY_FORWARDS }, +).pipe(Atom.keepAlive, Atom.withLabel("desktop:port-forwards")); + +export function usePortForwards(): ReadonlyArray { + return AsyncResult.getOrElse(useAtomValue(portForwardsAtom), () => EMPTY_FORWARDS); +} + +/** Only the desktop app forwards, and only from environments it reaches through the tunnel. */ +export const canForwardPorts = (target: ConnectionTarget | undefined): boolean => + previewBridge() !== undefined && tunnelsEnvironmentLoopback(target); + +/** + * Whether the environment runs on another machine. A saved route can still lead back to this + * computer (its own Tailscale address, a relay), where a forward would only loop. + */ +export type ForwardLocality = "remote" | "local" | "pending" | "unknown"; + +class PortForwardLocalityError extends Schema.TaggedError()( + "PortForwardLocalityError", + { environmentId: Schema.String, cause: Schema.Defect() }, +) { + override get message(): string { + return m(msg("Could not tell whether this environment runs on this computer.")); + } +} + +const localityResultAtom = Atom.family((environmentId: EnvironmentId) => + Atom.make((get) => { + // Each established connection probes anew, so a failed probe never outlives a reconnect. + const connection = AsyncResult.getOrElse( + get(environmentSession.transportSessionAtom(environmentId)), + () => Option.none(), + ); + const bridge = previewBridge(); + if (Option.isNone(connection) || bridge === undefined) return Effect.never; + return Effect.tryPromise({ + try: () => bridge.sharesLoopback(environmentId), + catch: (cause) => new PortForwardLocalityError({ environmentId, cause }), + }).pipe(Effect.map((shares): ForwardLocality => (shares ? "local" : "remote"))); + }).pipe( + Atom.setIdleTTL(10 * 60_000), + Atom.withLabel(`desktop:port-forward-locality-probe:${environmentId}`), + ), +); + +const localityAtom = Atom.family((environmentId: EnvironmentId) => + Atom.make((get): ForwardLocality => { + const result = get(localityResultAtom(environmentId)); + if (AsyncResult.isSuccess(result)) return result.value; + return AsyncResult.isFailure(result) ? "unknown" : "pending"; + }).pipe(Atom.withLabel(`desktop:port-forward-locality:${environmentId}`)), +); + +const NO_LOCALITY = Atom.make("unknown").pipe( + Atom.withLabel("desktop:port-forward-locality:none"), +); + +/** Pass `null` for an environment the desktop doesn't tunnel to; that one never probes. */ +export function useForwardLocality(environmentId: EnvironmentId | null): ForwardLocality { + return useAtomValue(environmentId === null ? NO_LOCALITY : localityAtom(environmentId)); +} + +export const forwardLocalitiesAtom = environmentAtomList( + "desktop:port-forward-localities", + localityAtom, +); + +export const findPortForward = ( + forwards: ReadonlyArray, + environmentId: EnvironmentId, + remotePort: number, +) => + forwards.find( + (forward) => forward.environmentId === environmentId && forward.remotePort === remotePort, + ); + +export function forwardPort(environmentId: EnvironmentId, remotePort: number) { + const bridge = previewBridge(); + if (!bridge) return Promise.reject(new Error(m(msg("Port forwarding needs the desktop app.")))); + return bridge.forwardPort(environmentId, remotePort).catch((error: unknown) => { + // Electron flattens main-process errors into "Error invoking remote method '…': Tag: text". + const raw = error instanceof Error ? error.message : String(error); + throw new Error( + raw.includes("LoopbackTunnelSameMachineError") + ? m( + msg("This environment runs on this computer, so localhost:{port} already reaches it.", { + port: remotePort, + }), + ) + : raw.includes("LoopbackTunnelUnavailableError") + ? m(msg("This environment can't be reached right now. Try again once it reconnects.")) + : raw.replace(/^Error invoking remote method '[^']*':\s*(\w+Error:\s*)?/u, ""), + { cause: error }, + ); + }); +} + +export function stopPortForward(environmentId: EnvironmentId, remotePort: number) { + return previewBridge()?.stopPortForward(environmentId, remotePort) ?? Promise.resolve(); +} + +/** `url` with its host and port moved to the forward's end on this machine. */ +export function forwardedUrl(forward: DesktopPortForward, url?: string): string { + const local = new URL(url ?? "http://localhost/"); + local.hostname = "localhost"; + local.port = String(forward.localPort); + return local.toString(); +} diff --git a/docs/user/remote-access.md b/docs/user/remote-access.md index 8a8e87fe0ba57..17c6e36df1576 100644 --- a/docs/user/remote-access.md +++ b/docs/user/remote-access.md @@ -303,6 +303,23 @@ do. These tabs ignore your system proxy settings, so they can't reach a host you connect to only through a proxy or over HTTPS with a privately issued certificate. The web app keeps streaming. +The desktop app can also forward a port on the host to your computer, so any +app there, such as your own browser, `curl`, or a database client, reaches it +at `localhost`. Use the forward button on a server in the thread's **Servers** +list, or **Forwarded ports** in the command palette, where you can also type +any port number and stop forwards. A forward keeps the host's port number +unless that port is taken on your computer, in which case it uses a free one +and shows it. Forwards end when you stop them or quit the app. ⌘-click +(Ctrl-click on Windows and Linux) on a remote server forwards it and opens it +in your browser. + +A forwarded port behaves like a server running on your computer: anything on +your computer can reach it, including web pages open in your browser, so a +forwarded service is exposed the same way a local dev server is. Forwards +listen only on your computer's loopback, never on your network. On Linux they +accept only apps running as your user; on macOS and Windows, other users signed +in to the same computer can reach them too. + On iPhone, iPad, and Android, a tab showing one of the host's `localhost` pages has **Open on this device** in its menu. So does a long press on a `localhost` link in a chat. It opens the page in the phone's own browser view, at the same diff --git a/packages/client-runtime/src/state/session.ts b/packages/client-runtime/src/state/session.ts index 6fdec4bd91580..e6066910d36f4 100644 --- a/packages/client-runtime/src/state/session.ts +++ b/packages/client-runtime/src/state/session.ts @@ -271,6 +271,7 @@ function makeEnvironmentSessionAtoms( preparedConnectionValueAtom, sessionStateAtom, sessionStateValueAtom, + transportSessionAtom, }; } diff --git a/packages/contracts/src/ipc.ts b/packages/contracts/src/ipc.ts index a9dbc8b81de98..77a523c03608f 100644 --- a/packages/contracts/src/ipc.ts +++ b/packages/contracts/src/ipc.ts @@ -2,7 +2,7 @@ import * as Schema from "effect/Schema"; import type { PreviewCaptureFailureEncoded } from "./previewCapture.ts"; import { SnapShotSource } from "./chatAttachment.ts"; -import { EnvironmentId, TrimmedNonEmptyString } from "./baseSchemas.ts"; +import { EnvironmentId, PortSchema, TrimmedNonEmptyString } from "./baseSchemas.ts"; import { BrowserProfileId } from "./browserProfile.ts"; import type { BrowserImportResult, @@ -1002,6 +1002,22 @@ export const DesktopPreviewTunnelAccessResolutionInputSchema = Schema.Struct({ url: Schema.NullOr(Schema.String), }); +/** A loopback port of another environment, reachable on this machine's 127.0.0.1. */ +export const DesktopPortForwardSchema = Schema.Struct({ + environmentId: EnvironmentId, + remotePort: PortSchema, + /** The same as `remotePort` unless that port was taken here. */ + localPort: PortSchema, +}); +export type DesktopPortForward = typeof DesktopPortForwardSchema.Type; + +export const DesktopSharesLoopbackInputSchema = Schema.Struct({ environmentId: EnvironmentId }); + +export const DesktopPortForwardInputSchema = Schema.Struct({ + environmentId: EnvironmentId, + remotePort: PortSchema, +}); + export const DesktopPreviewClearDataInputSchema = Schema.Struct({ environmentId: EnvironmentId, /** Omit to clear every profile; otherwise only this profile's partition. */ @@ -1324,6 +1340,13 @@ export interface DesktopPreviewBridge { listener: (request: DesktopPreviewTunnelAccessRequest) => void, ) => () => void; resolveTunnelAccess: (requestId: string, url: string | null) => Promise; + /** Forwards an environment's loopback port to this machine until stopped or the app quits. */ + forwardPort: (environmentId: EnvironmentId, remotePort: number) => Promise; + stopPortForward: (environmentId: EnvironmentId, remotePort: number) => Promise; + listPortForwards: () => Promise>; + /** Whether the environment runs on this machine, where its ports need no forward. */ + sharesLoopback: (environmentId: EnvironmentId) => Promise; + onPortForwards: (listener: (forwards: ReadonlyArray) => void) => () => void; listBrowserImportSources: () => Promise>; importBrowserCookies: (input: { readonly environmentId: EnvironmentId; From 71e1bb2dcc07cbea4f73ada217b536c193d42405 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 19 Nov 2026 15:18:32 -0800 Subject: [PATCH 87/97] fix(server): Antigravity sign-in names a runtime crash instead of blaming Google (#28355) --- .../src/provider/AntigravityAuth.test.ts | 20 +++++++++++++++++++ apps/server/src/provider/AntigravityAuth.ts | 11 ++++++++++ 2 files changed, 31 insertions(+) diff --git a/apps/server/src/provider/AntigravityAuth.test.ts b/apps/server/src/provider/AntigravityAuth.test.ts index 936cfcb6bc06f..48cb3f1912da3 100644 --- a/apps/server/src/provider/AntigravityAuth.test.ts +++ b/apps/server/src/provider/AntigravityAuth.test.ts @@ -264,6 +264,26 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("AntigravityAuth" }), ); + it.effect("says Antigravity exited when its process dies during sign-in", () => + Effect.gen(function* () { + const harness = yield* makeHarness({ interactive: false }); + yield* harness.auth.controller.start(owner); + yield* Deferred.await(harness.authenticateCalled); + yield* Deferred.fail( + harness.authenticated, + new AcpErrors.AcpProcessExitedError({ + signal: "SIGILL", + stderr: `runtime crashed ${callbackUrl}`, + }), + ); + const failed = yield* phase(harness.auth, "failed"); + assert.include(failed.message ?? "", "exited"); + assert.include(failed.message ?? "", "SIGILL"); + assert.notInclude(failed.message ?? "", "Google sign-in failed"); + assert.notInclude(failed.message ?? "", "runtime crashed"); + }), + ); + it.effect("tells the user when the agent cannot reach Google", () => Effect.gen(function* () { const harness = yield* makeHarness({ interactive: false }); diff --git a/apps/server/src/provider/AntigravityAuth.ts b/apps/server/src/provider/AntigravityAuth.ts index fcaf41275de12..6e471dad4dc1a 100644 --- a/apps/server/src/provider/AntigravityAuth.ts +++ b/apps/server/src/provider/AntigravityAuth.ts @@ -47,6 +47,7 @@ const UNREACHABLE_MESSAGE = const FORWARDING_FAILED_MESSAGE = "Could not deliver the sign-in response. Start sign-in again."; const isSetupError = Schema.is(ProviderSetupError); const isAcpRequestError = Schema.is(AcpErrors.AcpRequestError); +const isAcpProcessExitedError = Schema.is(AcpErrors.AcpProcessExitedError); interface AuthSnapshot { readonly ownerSessionId: string | null; @@ -120,6 +121,16 @@ function safeAuthFailure(cause: Cause.Cause, usesBrowser: boolean): str if (isSetupError(error.value)) { return error.value.detail; } + if (isAcpProcessExitedError(error.value)) { + const { code, signal } = error.value; + const reason = + signal !== undefined + ? ` after signal ${signal}` + : code !== undefined + ? ` with code ${code}` + : ""; + return `Antigravity exited unexpectedly${reason}. Start sign-in again.`; + } if (isAcpRequestError(error.value)) { if (error.value.errorMessage.includes("SUBSCRIPTION_REQUIRED")) { return "Google requires an eligible Antigravity subscription for this account."; From 0a159c9fba55f2699b6f36d19f7318046063e3f9 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 19 Nov 2026 15:28:40 -0800 Subject: [PATCH 88/97] fix(server): agent messages queued behind /compact keep send order (#39417) --- .../src/orchestration-v2/Orchestrator.ts | 22 ++++ .../SteeringCompletion.integration.test.ts | 123 ++++++++++++++++++ 2 files changed, 145 insertions(+) diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 059671b306fa9..73cf6e9782a22 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -7439,6 +7439,28 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ) { dispatchMode = { type: "queue_after_active" }; } + // An agent's automatic send must not overtake an earlier agent message still queued + // (e.g. behind /compact), or the agent receives them out of send order. + if ( + command.deliveryIntent === "auto" && + command.createdBy === "agent" && + (dispatchMode.type === "steer_active" || dispatchMode.type === "restart_active") + ) { + const queuedRuns = projection.runs.filter( + (run) => run.status === "queued" && run.queueHeld !== true, + ); + if (queuedRuns.length > 0) { + const queuedMessages = yield* projectionStore + .getMessagesById( + command.threadId, + queuedRuns.map((run) => run.userMessageId), + ) + .pipe(mapDispatchError(command)); + if ([...queuedMessages.values()].some((message) => message.createdBy === "agent")) { + dispatchMode = { type: "queue_after_active" }; + } + } + } // An explicit restart that Stop reached has only its start left, so it // queues behind the stopping run like any other start. if ( diff --git a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts index ebe5e7215bcbd..cc14fde257da8 100644 --- a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts +++ b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts @@ -1717,6 +1717,129 @@ it.effect("queues a steer until the turn ends when the provider cannot steer it" }), ); +// regression: #39404 a later agent message steers ahead of one queued behind /compact +it.effect("delivers agent messages queued behind /compact before a later one steers", () => + Effect.gen(function* () { + const { events, started, steered, layer, startFirstTurn } = yield* nextTurnSelectionHarness( + "agent-order-after-compact", + ); + yield* Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; + const threadId = yield* startFirstTurn; + const nextRunning = Effect.fn("nextRunning")(function* () { + return yield* orchestrator.streamDomainEvents.pipe( + Stream.filter( + (event) => event.type === "provider-turn.updated" && event.payload.status === "running", + ), + Stream.take(1), + Stream.runDrain, + Effect.forkScoped, + ); + }); + const lock = (yield* ThreadCommandExecutor.ThreadCommandExecutor).withLock( + threadId, + Effect.void, + ); + const finishTurn = Effect.fn("finishTurn")(function* (index: number) { + const turnInput = started[index]!; + const turn = (yield* orchestrator.getThreadProjection(threadId)).providerTurns.find( + (candidate) => candidate.runAttemptId === turnInput.attemptId, + )!; + const settled = yield* orchestrator.streamDomainEvents.pipe( + Stream.filter( + (event) => + event.type === "run.updated" && + event.payload.id === turnInput.runId && + (event.payload.status === "waiting" || event.payload.status === "completed"), + ), + Stream.take(1), + Stream.runDrain, + Effect.forkScoped, + ); + yield* Queue.offer(events, { + type: "provider_turn.updated", + driver, + providerTurn: { ...turn, status: "completed", completedAt: yield* DateTime.now }, + }); + yield* Queue.offer(events, { + type: "turn.terminal", + driver, + providerThreadId: turn.providerThreadId, + providerTurnId: turn.id, + runOrdinal: turnInput.runOrdinal, + status: "completed", + failure: null, + threadDisposition: "reusable", + }); + yield* Fiber.join(settled); + yield* worker.drain(); + yield* orchestrator.resumeQueuedRuns; + yield* worker.drain(); + }); + yield* finishTurn(0); + const compactRunning = yield* nextRunning(); + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make("compact"), + threadId, + messageId: MessageId.make("message:compact"), + text: "/compact", + attachments: [], + dispatchMode: { type: "start_immediately" }, + createdBy: "user", + creationSource: "web", + }); + yield* worker.drain(); + yield* Fiber.join(compactRunning); + yield* lock; + const sendFromAgent = (codeword: string) => + Effect.gen(function* () { + const active = (yield* orchestrator.getThreadProjection(threadId)).runs.find( + (run) => run.status === "running", + )!; + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make(`send-${codeword}`), + threadId, + messageId: MessageId.make(`message:${codeword}`), + text: codeword, + attachments: [], + dispatchMode: { type: "steer_active", targetRunId: active.id }, + deliveryIntent: "auto", + createdBy: "agent", + creationSource: "mcp", + senderThreadId: ThreadId.make("thread:orchestrator"), + }); + yield* worker.drain(); + }); + yield* sendFromAgent("ALPHA"); + yield* sendFromAgent("BRAVO"); + const queued = (yield* orchestrator.getThreadProjection(threadId)).runs.filter( + (run) => run.status === "queued", + ); + assert.lengthOf(queued, 2); + assert.deepEqual(steered, []); + + const alphaRunning = yield* nextRunning(); + yield* finishTurn(1); + yield* Fiber.join(alphaRunning); + yield* lock; + assert.deepEqual( + started.map((turn) => turn.message.text.split("\n").at(-1)), + ["first", "/compact", "ALPHA"], + ); + + yield* sendFromAgent("CHARLIE"); + const delivered = [...steered, ...started.slice(3).map((turn) => turn.message.text)] + .map((text) => text.split("\n").at(-1)) + .filter((text) => text === "BRAVO" || text === "CHARLIE"); + // Whatever reaches the agent so far does so in send order: CHARLIE never before BRAVO. + assert.deepEqual(delivered, ["BRAVO", "CHARLIE"].slice(0, delivered.length)); + }).pipe(Effect.provide(layer)); + }), +); + // regression: #33454 a steer that restarts a completion wake run left its cohort claimed forever const restartCompletionWake = Effect.fn("restartCompletionWake")(function* ( harness: Pick< From 5283f33ca9d3515058a5686ea9a4e40a57ef23da Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 19 Nov 2026 15:30:09 -0800 Subject: [PATCH 89/97] fix(server): Antigravity limits read the 1.5.x CLI's stored sign-in (#38957) --- .../provider/antigravityUsageLimits.test.ts | 108 ++++++++- .../src/provider/antigravityUsageLimits.ts | 219 ++++++++++++++---- 2 files changed, 286 insertions(+), 41 deletions(-) diff --git a/apps/server/src/provider/antigravityUsageLimits.test.ts b/apps/server/src/provider/antigravityUsageLimits.test.ts index 9defd9df90dce..6582fc2458577 100644 --- a/apps/server/src/provider/antigravityUsageLimits.test.ts +++ b/apps/server/src/provider/antigravityUsageLimits.test.ts @@ -1,5 +1,6 @@ import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; +import * as HostProcess from "@t3tools/shared/HostProcess"; import * as Layer from "effect/Layer"; import { describe, expect, it } from "@effect/vitest"; import * as Context from "effect/Context"; @@ -10,7 +11,11 @@ import * as Path from "effect/Path"; import * as TestClock from "effect/testing/TestClock"; import { FetchHttpClient, HttpClient, HttpClientResponse } from "effect/http"; -import { makeAntigravityUsageProbe } from "./antigravityUsageLimits.ts"; +import { + decodeGoKeyringSecret, + makeAntigravityUsageProbe, + readWindowsCliCredential, +} from "./antigravityUsageLimits.ts"; const summary = { groups: [ @@ -66,6 +71,9 @@ const fixture = Effect.fn("AntigravityUsageTest.fixture")(function* ( userInfoAt?: number; missingToken?: boolean; authMethod?: "oauth-personal" | "oauth-business" | "gemini-api-key"; + keyringSecret?: string; + /** Reads the OS keyring instead of `keyringSecret`. */ + nativeKeyring?: boolean; } = {}, ) { const fs = yield* FileSystem.FileSystem; @@ -111,7 +119,7 @@ const fixture = Effect.fn("AntigravityUsageTest.fixture")(function* ( : Response.json({}, { status: 403 }), ); } - expect(JSON.parse(body)).toEqual({ project: "project-id" }); + expect(JSON.parse(body)).toEqual(options.missingToken ? {} : { project: "project-id" }); expect(request.headers["user-agent"]).toMatch(/^antigravity\/hub\/2\.24\.0 /); return HttpClientResponse.fromWeb( request, @@ -132,6 +140,7 @@ const fixture = Effect.fn("AntigravityUsageTest.fixture")(function* ( const usage = yield* makeAntigravityUsageProbe({ profileDirectory, authMethod: options.authMethod ?? "oauth-personal", + ...(options.nativeKeyring ? {} : { readKeyringSecret: Effect.succeed(options.keyringSecret) }), }).pipe(Effect.provideService(HttpClient.HttpClient, http)); return { ...usage, requests, writeToken, tokenPath }; }); @@ -654,6 +663,101 @@ describe("Antigravity subscription limits", () => { }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); + it.effect("reads the native CLI's stored sign-in when acp_token.json is absent", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const { probe, tokenPath } = yield* fixture({ missingToken: true }); + // The 1.5.x CLI never writes acp_token.json; without a keyring it stores this file instead. + yield* fs.writeFileString( + path.join(path.dirname(tokenPath), "antigravity-oauth-token"), + JSON.stringify({ + token: { + access_token: "access-token", + token_type: "Bearer", + refresh_token: "refresh-a", + expiry: "2099-01-01T00:00:00Z", + expires_in: 3600, + }, + auth_method: "consumer", + id_token_email: "someone@example.com", + }), + ); + const limits = yield* probe; + expect(limits.unavailable?.message).not.toBe( + "Sign in with Google to see Antigravity limits.", + ); + expect(limits.unavailable?.reason).not.toBe("unsupported"); + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), + ); + + it.effect("reads the native CLI's keyring sign-in and reports when it has expired", () => + Effect.gen(function* () { + yield* TestClock.setTime(DateTime.toEpochMillis(DateTime.makeUnsafe("2026-10-09T12:00:00Z"))); + const keyringSecret = (expiry: string) => + JSON.stringify({ token: { access_token: "access-token", refresh_token: "r", expiry } }); + const signedIn = yield* fixture({ + missingToken: true, + userId: "google-user-1", + keyringSecret: keyringSecret("2026-10-09T14:00:00.123456789+01:00"), + }); + const limits = yield* signedIn.probe; + expect(limits.unavailable).toBeUndefined(); + expect(limits.windows).toHaveLength(4); + expect(signedIn.requests.some((request) => request.url.endsWith("/token"))).toBe(false); + + const expired = yield* fixture({ + missingToken: true, + keyringSecret: keyringSecret("2026-10-09T12:00:30Z"), + }); + expect((yield* expired.probe).unavailable?.reason).toBe("probeFailed"); + expect(expired.requests).toEqual([]); + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), + ); + + it.effect.runIf(HostProcess.Platform.defaultValue() === "win32")( + "reads go-keyring's Windows credential target without changing it", + (ctx) => + Effect.gen(function* () { + // Never overwrite a real sign-in on a developer's machine. + if (readWindowsCliCredential(HostProcess.Architecture.defaultValue())) return ctx.skip(); + yield* TestClock.setTime( + DateTime.toEpochMillis(DateTime.makeUnsafe("2026-10-09T12:00:00Z")), + ); + const { AsyncEntry } = yield* Effect.promise(() => import("@napi-rs/keyring")); + // go-keyring writes the UTF-8 JSON at `:`. + const target = AsyncEntry.withTarget("gemini:antigravity", "gemini", "antigravity"); + const stored = new TextEncoder().encode( + JSON.stringify({ + token: { access_token: "access-token", expiry: "2026-10-09T14:00:00Z" }, + }), + ); + yield* Effect.acquireRelease( + Effect.promise(() => target.setSecret(stored)), + () => Effect.promise(() => target.deleteCredential()), + ); + const { probe } = yield* fixture({ missingToken: true, nativeKeyring: true }); + const limits = yield* probe; + expect(limits.unavailable).toBeUndefined(); + expect(limits.windows).toHaveLength(4); + expect(readWindowsCliCredential(HostProcess.Architecture.defaultValue())).toEqual( + Buffer.from(stored), + ); + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), + ); + + it("decodes go-keyring's macOS encodings", () => { + const value = '{"token":{}}'; + const bytes = (text: string) => new TextEncoder().encode(text); + expect(decodeGoKeyringSecret(bytes(value))).toBe(value); + expect( + decodeGoKeyringSecret(bytes(`go-keyring-base64:${Buffer.from(value).toString("base64")}`)), + ).toBe(value); + expect( + decodeGoKeyringSecret(bytes(`go-keyring-encoded:${Buffer.from(value).toString("hex")}`)), + ).toBe(value); + }); + it.effect("does not make network requests for API keys or missing sign-ins", () => Effect.gen(function* () { for (const options of [{ authMethod: "gemini-api-key" as const }, { missingToken: true }]) { diff --git a/apps/server/src/provider/antigravityUsageLimits.ts b/apps/server/src/provider/antigravityUsageLimits.ts index ede0e5c47d20e..77ac75c7a2f52 100644 --- a/apps/server/src/provider/antigravityUsageLimits.ts +++ b/apps/server/src/provider/antigravityUsageLimits.ts @@ -1,3 +1,5 @@ +import * as NodeModule from "node:module"; + import type { AntigravitySettings, ServerProviderUsageWindow } from "@t3tools/contracts"; import * as HostProcess from "@t3tools/shared/HostProcess"; import * as Clock from "effect/Clock"; @@ -38,6 +40,15 @@ const TokenFile = Schema.Struct({ refresh_token: Schema.NonEmptyString, project_id: Schema.optional(Schema.String), }); +// The 1.5.x CLI never writes acp_token.json: it keeps its sign-in in the OS keyring, or in +// antigravity-oauth-token without one. It stores no OAuth client, so T3 cannot refresh it. +const CliToken = Schema.Struct({ + token: Schema.Struct({ + access_token: Schema.NonEmptyString, + refresh_token: Schema.optional(Schema.String), + expiry: Schema.optional(Schema.String), + }), +}); const TokenResponse = Schema.Struct({ access_token: Schema.NonEmptyString, expires_in: Schema.Number.check(Schema.isGreaterThan(0)), @@ -78,6 +89,7 @@ const Models = Schema.Struct({ }); const decodeTokenFile = Schema.decodeEffect(Schema.fromJsonString(TokenFile)); +const decodeCliToken = Schema.decodeEffect(Schema.fromJsonString(CliToken)); const decodeTokenResponse = Schema.decodeUnknownEffect(TokenResponse); const decodeUserInfo = Schema.decodeUnknownEffect(UserInfo); const decodeSummary = Schema.decodeUnknownEffect(Summary); @@ -132,6 +144,104 @@ const sha256 = Effect.fnUntraced(function* (text: string) { return Array.from(digest, (byte) => byte.toString(16).padStart(2, "0")).join(""); }); +/** go-keyring stores UTF-8, which it prefixes and encodes on macOS. */ +export function decodeGoKeyringSecret(secret: ArrayLike): string { + // The binding resolves a plain number array at runtime despite its Uint8Array type. + const text = new TextDecoder().decode(Uint8Array.from(secret)); + if (text.startsWith("go-keyring-base64:")) { + return Buffer.from(text.slice("go-keyring-base64:".length), "base64").toString("utf8"); + } + if (text.startsWith("go-keyring-encoded:")) { + return Buffer.from(text.slice("go-keyring-encoded:".length), "hex").toString("utf8"); + } + return text; +} + +class AntigravityKeyringError extends Schema.TaggedError()( + "AntigravityKeyringError", + { cause: Schema.Defect() }, +) { + override get message(): string { + return "Could not read the Antigravity sign-in from the system keyring."; + } +} + +// A single-executable server resolves packages on disk only through `require`. +const requireExternal = NodeModule.createRequire(import.meta.url); + +/** + * go-keyring's Windows target is `gemini:antigravity`; @napi-rs/keyring reads `antigravity.gemini`, + * and its `withTarget` overwrites the target with an empty secret before reading. + */ +export function readWindowsCliCredential( + architecture: NodeJS.Architecture, +): Uint8Array | undefined { + // CREDENTIALW offsets and the pointers below are 64-bit. + if (architecture !== "x64" && architecture !== "arm64") { + throw new Error(`no credential access on ${architecture}`); + } + const { DataType, load, open } = requireExternal("ffi-rs") as typeof import("ffi-rs"); + open({ library: "t3-advapi32", path: "advapi32.dll" }); + open({ library: "t3-kernel32", path: "kernel32.dll" }); + const copy = (into: Buffer, from: bigint) => + load({ + library: "t3-kernel32", + funcName: "RtlMoveMemory", + retType: DataType.Void, + paramsType: [DataType.U8Array, DataType.BigInt, DataType.BigInt], + paramsValue: [into, from, BigInt(into.length)], + }); + const out = Buffer.alloc(8); + const read = load({ + library: "t3-advapi32", + funcName: "CredReadW", + retType: DataType.I32, + // CRED_TYPE_GENERIC + paramsType: [DataType.WString, DataType.U32, DataType.U32, DataType.U8Array], + paramsValue: ["gemini:antigravity", 1, 0, out], + errno: true as const, + }); + if (read.value === 0) { + // ERROR_NOT_FOUND + if (read.errnoCode === 1168) return undefined; + throw new Error(`CredReadW failed with Windows error ${read.errnoCode}`); + } + const credential = out.readBigUInt64LE(); + try { + // CredentialBlobSize is a DWORD at 32 and CredentialBlob a pointer at 40. + const header = Buffer.alloc(48); + copy(header, credential); + const size = header.readUInt32LE(32); + if (size === 0) return undefined; + const blob = Buffer.alloc(size); + copy(blob, header.readBigUInt64LE(40)); + return blob; + } finally { + load({ + library: "t3-advapi32", + funcName: "CredFree", + retType: DataType.Void, + paramsType: [DataType.BigInt], + paramsValue: [credential], + }); + } +} + +// Loaded lazily: a native binding that fails to load must not take the provider down. +const readCliKeyringSecret = (platform: NodeJS.Platform, architecture: NodeJS.Architecture) => + Effect.tryPromise({ + try: async () => { + const secret = + platform === "win32" + ? readWindowsCliCredential(architecture) + : await new ( + requireExternal("@napi-rs/keyring") as typeof import("@napi-rs/keyring") + ).AsyncEntry("gemini", "antigravity").getSecret(); + return secret ? decodeGoKeyringSecret(secret) : undefined; + }, + catch: (cause) => new AntigravityKeyringError({ cause }), + }); + /** Keys an account by its Google ID, which matches across machines and hubs; refresh tokens do not. */ export const antigravityAccountFingerprint = (userInfo: unknown) => decodeUserInfo(userInfo).pipe(Effect.flatMap((info) => sha256(`google-account\0${info.id}`))); @@ -210,6 +320,7 @@ function modelWindows(models: typeof Models.Type) { export const makeAntigravityUsageProbe = Effect.fn("makeAntigravityUsageProbe")(function* (input: { readonly profileDirectory: string; readonly authMethod: AntigravitySettings["authMethod"]; + readonly readKeyringSecret?: Effect.Effect; }) { const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; @@ -218,6 +329,12 @@ export const makeAntigravityUsageProbe = Effect.fn("makeAntigravityUsageProbe")( const platform = yield* HostProcess.Platform; const architecture = yield* HostProcess.Architecture; const tokenPath = path.join(input.profileDirectory, "antigravity-acp", "acp_token.json"); + const cliTokenPath = path.join( + input.profileDirectory, + "antigravity-acp", + "antigravity-oauth-token", + ); + const readKeyringSecret = input.readKeyringSecret ?? readCliKeyringSecret(platform, architecture); let cached: | { fingerprint: string; account: string; accessToken: string; expiresAt: number } | undefined; @@ -236,54 +353,80 @@ export const makeAntigravityUsageProbe = Effect.fn("makeAntigravityUsageProbe")( if (input.authMethod !== "oauth-personal" && input.authMethod !== "oauth-business") { return makeUnavailableUsageLimits({ checkedAt, reason: "unsupported" }); } - if (!(yield* fs.exists(tokenPath))) { - cached = undefined; - return makeUnavailableUsageLimits({ - checkedAt, - reason: "unsupported", - message: "Sign in with Google to see Antigravity limits.", - }); - } - const token = yield* fs.readFileString(tokenPath).pipe(Effect.flatMap(decodeTokenFile)); - const fingerprint = yield* sha256( - `${token.client_id}\0${token.refresh_token}\0${token.project_id ?? ""}`, - ); const now = yield* Clock.currentTimeMillis; let accessToken: string; let account: string; - if (cached?.fingerprint !== fingerprint || cached.expiresAt <= now + 60_000) { + let projectId: string | undefined; + if (!(yield* fs.exists(tokenPath))) { cached = undefined; - const refreshed = yield* request( - HttpClientRequest.post("https://oauth2.googleapis.com/token").pipe( - HttpClientRequest.bodyUrlParams({ - client_id: token.client_id, - client_secret: token.client_secret, - refresh_token: token.refresh_token, - grant_type: "refresh_token", - }), - ), - ).pipe(Effect.flatMap(decodeTokenResponse)); - accessToken = refreshed.access_token; - // Use Google account IDs to merge accounts across environments; refresh tokens differ per machine. + const stored = (yield* fs.exists(cliTokenPath)) + ? yield* fs.readFileString(cliTokenPath) + : yield* readKeyringSecret; + if (stored === undefined) { + return makeUnavailableUsageLimits({ + checkedAt, + reason: "unsupported", + message: "Sign in with Google to see Antigravity limits.", + }); + } + const { token } = yield* decodeCliToken(stored); + if (!(Date.parse(token.expiry ?? "") > now + 60_000)) { + return makeUnavailableUsageLimits({ + checkedAt, + reason: "probeFailed", + message: + "Antigravity's saved sign-in has expired. Start an Antigravity turn to renew it, then refresh limits.", + }); + } + accessToken = token.access_token; account = yield* request( HttpClientRequest.get("https://www.googleapis.com/oauth2/v2/userinfo").pipe( HttpClientRequest.setHeaders({ Authorization: `Bearer ${accessToken}` }), ), ).pipe( Effect.flatMap(antigravityAccountFingerprint), - Effect.orElseSucceed(() => fingerprint), + Effect.catch(() => sha256(`antigravity-cli\0${token.refresh_token || accessToken}`)), ); - if (generation === startedGeneration) { - cached = { - fingerprint, - account, - accessToken, - expiresAt: now + refreshed.expires_in * 1000, - }; - } } else { - accessToken = cached.accessToken; - account = cached.account; + const token = yield* fs.readFileString(tokenPath).pipe(Effect.flatMap(decodeTokenFile)); + projectId = token.project_id; + const fingerprint = yield* sha256( + `${token.client_id}\0${token.refresh_token}\0${token.project_id ?? ""}`, + ); + if (cached?.fingerprint !== fingerprint || cached.expiresAt <= now + 60_000) { + cached = undefined; + const refreshed = yield* request( + HttpClientRequest.post("https://oauth2.googleapis.com/token").pipe( + HttpClientRequest.bodyUrlParams({ + client_id: token.client_id, + client_secret: token.client_secret, + refresh_token: token.refresh_token, + grant_type: "refresh_token", + }), + ), + ).pipe(Effect.flatMap(decodeTokenResponse)); + accessToken = refreshed.access_token; + // Use Google account IDs to merge accounts across environments; refresh tokens differ per machine. + account = yield* request( + HttpClientRequest.get("https://www.googleapis.com/oauth2/v2/userinfo").pipe( + HttpClientRequest.setHeaders({ Authorization: `Bearer ${accessToken}` }), + ), + ).pipe( + Effect.flatMap(antigravityAccountFingerprint), + Effect.orElseSucceed(() => fingerprint), + ); + if (generation === startedGeneration) { + cached = { + fingerprint, + account, + accessToken, + expiresAt: now + refreshed.expires_in * 1000, + }; + } + } else { + accessToken = cached.accessToken; + account = cached.account; + } } const endpoints = ENDPOINTS[input.authMethod]; // Merge endpoints because quota groups differ; the metered host's reading of a bucket wins. @@ -306,9 +449,7 @@ export const makeAntigravityUsageProbe = Effect.fn("makeAntigravityUsageProbe")( Authorization: `Bearer ${accessToken}`, "User-Agent": antigravityUserAgent(platform, architecture), }), - HttpClientRequest.bodyJsonUnsafe( - token.project_id ? { project: token.project_id } : {}, - ), + HttpClientRequest.bodyJsonUnsafe(projectId ? { project: projectId } : {}), ), ).pipe( Effect.flatMap((response) => parse(response, requestedAt)), From 06eda8e36eb41d799bc4aec163148b596e4e4bbb Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 19 Nov 2026 15:35:47 -0800 Subject: [PATCH 90/97] fix(server): Codex stdio MCP servers receive T3CODE_THREAD_ID (#39414) --- .../Adapters/CodexAdapterV2.test.ts | 120 ++++++++++++++---- .../Adapters/CodexAdapterV2.ts | 64 +++++++++- .../codex_transcript.ndjson | 26 ++-- .../codex_transcript.ndjson | 18 +-- .../codex_transcript.ndjson | 56 ++++---- .../message_steering/codex_transcript.ndjson | 22 ++-- .../multi_turn/codex_transcript.ndjson | 26 ++-- .../plan_questions/codex_transcript.ndjson | 18 +-- .../proposed_plan/codex_transcript.ndjson | 18 +-- .../codex_transcript.ndjson | 36 +++--- .../queued_turn/codex_transcript.ndjson | 26 ++-- .../fixtures/simple/codex_transcript.ndjson | 18 +-- .../fixtures/subagent/codex_transcript.ndjson | 18 +-- .../subagent_continue/codex_transcript.ndjson | 26 ++-- .../subagent_v2/codex_transcript.ndjson | 18 +-- .../codex_transcript.ndjson | 18 +-- .../codex_transcript.ndjson | 18 +-- .../codex_transcript.ndjson | 18 +-- .../codex_transcript.ndjson | 44 ++++--- .../codex_transcript.ndjson | 78 ++++++------ .../thread_rollback/codex_transcript.ndjson | 46 +++---- .../codex_transcript.ndjson | 58 +++++---- .../codex_transcript.ndjson | 62 ++++----- .../todo_list/codex_transcript.ndjson | 18 +-- .../codex_transcript.ndjson | 18 +-- .../codex_transcript.ndjson | 18 +-- .../codex_transcript.ndjson | 18 +-- .../turn_interrupt/codex_transcript.ndjson | 22 ++-- .../codex_transcript.ndjson | 26 ++-- .../web_search/codex_transcript.ndjson | 18 +-- .../effect-codex-app-server/src/replay.ts | 11 +- 31 files changed, 602 insertions(+), 399 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts index cf5439e3eb254..67189ae9d7dee 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts @@ -805,7 +805,9 @@ function codexReplayPreamble(input: { /** * Every turn/start follows a config/read, and a thread's first turn on a connection names it - * unless the transcript names it itself. Inserts those exchanges and shifts later client ids. + * unless the transcript names it itself. A thread start, resume or fork follows a config/read + * unless it retries a failed request or the transcript reads config itself. Inserts those + * exchanges and shifts later client ids. */ function withConfigReadBeforeTurnStart( entries: ReadonlyArray, @@ -815,6 +817,9 @@ function withConfigReadBeforeTurnStart( let offset = 0; let clientIds = new Map(); let namedThreads = new Set(); + let transcriptReads = 0; + let previousOutbound: { readonly method: string; readonly id: number } | undefined; + let failedMethod: string | undefined; for (const entry of entries) { const frame = entry.type === "runtime_exit" ? undefined : entry.frame; if (!Predicate.isObject(frame) || typeof frame.id !== "number") { @@ -829,8 +834,25 @@ function withConfigReadBeforeTurnStart( namedThreads = new Set(); } if (frame.method === "thread/name/set") namedThreads.add(params.threadId); + const exchanges: Array = []; + const isThreadRequest = + frame.method === "thread/start" || + frame.method === "thread/resume" || + frame.method === "thread/fork"; + if (frame.method === "config/read") transcriptReads += 1; + else if (isThreadRequest && transcriptReads > 0) transcriptReads -= 1; + else if ( + isThreadRequest && + failedMethod !== frame.method && + previousOutbound?.method !== "thread/unarchive" + ) { + exchanges.push([ + "config/read", + { ...(params.cwd === undefined ? {} : { cwd: params.cwd }), includeLayers: false }, + { config: {}, origins: {} }, + ]); + } if (frame.method === "turn/start") { - const exchanges: Array = []; if (!namedThreads.has(params.threadId)) { namedThreads.add(params.threadId); exchanges.push(["thread/name/set", { threadId: params.threadId, name: threadName }, {}]); @@ -840,23 +862,28 @@ function withConfigReadBeforeTurnStart( { cwd: params.cwd, includeLayers: false }, { config: {}, origins: {} }, ]); - for (const [method, requestParams, response] of exchanges) { - const id = frame.id + offset; - result.push( - { - type: "expect_outbound", - label: method, - frame: { id, method, params: requestParams }, - }, - { type: "emit_inbound", label: method, frame: { id, result: response } }, - ); - offset += 1; - } } + for (const [method, requestParams, response] of exchanges) { + const id = frame.id + offset; + result.push( + { + type: "expect_outbound", + label: method, + frame: { id, method, params: requestParams }, + }, + { type: "emit_inbound", label: method, frame: { id, result: response } }, + ); + offset += 1; + } + previousOutbound = { method: frame.method, id: frame.id }; + failedMethod = undefined; clientIds.set(frame.id, frame.id + offset); result.push(withReplayRequestId(entry, frame.id + offset)); continue; } + if (entry.type === "emit_inbound" && frame.id === previousOutbound?.id && "error" in frame) { + failedMethod = previousOutbound.method; + } const mapped = clientIds.get(frame.id); result.push( entry.type === "emit_inbound" && frame.method === undefined && mapped !== undefined @@ -947,8 +974,8 @@ describe("CodexAdapterV2 process exit", () => { Predicate.isObject(entry.frame) && "id" in entry.frame, ); - if (response?.type === "emit_inbound") { - yield* emit(response.frame); + if (response?.type === "emit_inbound" && Predicate.isObject(response.frame)) { + yield* emit({ ...response.frame, id: frame.id }); } }), ).pipe(Sink.ensuring(Deferred.succeed(outputEnded, undefined))), @@ -1193,10 +1220,25 @@ describe("CodexAdapterV2 session initialize", () => { makeCodexReplayTranscript({ scenario: "concurrent-initialize", entries: [ - ...replayPreamble("concurrent-first").slice(0, 5), + ...replayPreamble("concurrent-first").slice(0, 3), + ...[2, 3].flatMap((id): Array => [ + { + type: "expect_outbound", + label: "config/read", + frame: { id, method: "config/read", params: { includeLayers: false } }, + }, + { + type: "emit_inbound", + label: "config/read", + frame: { id, result: { config: {}, origins: {} } }, + }, + ]), + ...replayPreamble("concurrent-first") + .slice(3, 5) + .map((entry) => withReplayRequestId(entry, 4)), ...replayPreamble("concurrent-second") .slice(3, 5) - .map((entry) => withReplayRequestId(entry, 3)), + .map((entry) => withReplayRequestId(entry, 5)), ], }), (entry) => @@ -2384,7 +2426,7 @@ describe("CodexAdapterV2 post-settle continuation", () => { ), ); - it.effect("adds the session MCP server without replacing launch-argument servers", () => + it.effect("adds the session MCP server and gives stdio servers the thread id", () => Effect.gen(function* () { const scenario = "launch-mcp-servers"; yield* (yield* McpProviderSessions.McpProviderSessions).set({ @@ -2397,14 +2439,40 @@ describe("CodexAdapterV2 post-settle continuation", () => { browserToolsAvailable: true, }); const requests: Array = []; + const preamble = codexReplayPreamble({ + nativeThreadId: "launch-mcp-thread", + nativeTurnId: "unused", + prompt: "unused", + }); yield* makeCodexReplayHarness( makeCodexReplayTranscript({ scenario, - entries: codexReplayPreamble({ - nativeThreadId: "launch-mcp-thread", - nativeTurnId: "unused", - prompt: "unused", - }).slice(0, 5), + entries: [ + ...preamble.slice(0, 3), + { + type: "expect_outbound", + label: "config/read", + frame: { id: 2, method: "config/read", params: { includeLayers: false } }, + }, + { + type: "emit_inbound", + label: "config/read", + frame: { + id: 2, + result: { + config: { + mcp_servers: { + envprobe: { command: "python3", env: { FOO: "bar" } }, + remote: { url: "https://example.com/mcp" }, + "dotted.name": { command: "node" }, + }, + }, + origins: {}, + }, + }, + }, + ...preamble.slice(3, 5).map((entry) => withReplayRequestId(entry, 3)), + ], }), () => Effect.void, (method, params) => @@ -2421,6 +2489,7 @@ describe("CodexAdapterV2 post-settle continuation", () => { mcp_optional_startup_grace_ms: 10_000, "features.concurrent_reasoning_summaries": true, "shell_environment_policy.set.T3CODE_THREAD_ID": `thread-${scenario}`, + "mcp_servers.envprobe.env.T3CODE_THREAD_ID": `thread-${scenario}`, "mcp_servers.t3-code": { url: "http://127.0.0.1:43123/mcp", tool_timeout_sec: 3_900, @@ -4455,7 +4524,8 @@ describe("CodexAdapterV2 post-settle continuation", () => { "cause.method", failAt === 4 ? "thread/unarchive" : "thread/resume", ); - assert.nestedPropertyVal(error, "cause.requestId", String(failAt)); + // The thread start and the resume each read config first. + assert.nestedPropertyVal(error, "cause.requestId", String(failAt + 2)); return; } const resumed = yield* resume; diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts index 4474dd04273a0..c36c1772ae197 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts @@ -1507,9 +1507,25 @@ const CODEX_T3_MCP_TOOL_TIMEOUT_SEC = 65 * 60; const CODEX_T3_DIRECT_MCP_SERVER = "t3-code-direct"; const CODEX_DIRECT_ONLY_T3_TOOLS = ["t3_thread_wait", "delegate_task"]; +/** Names of the stdio MCP servers in a `config/read` config, the ones Codex starts per thread. */ +function codexStdioMcpServerNames(mcpServers: unknown): ReadonlyArray { + if (mcpServers === null || typeof mcpServers !== "object") return []; + return Object.entries(mcpServers) + .filter( + ([name, server]) => + // Codex splits config override keys on every dot. + !name.includes(".") && + server !== null && + typeof server === "object" && + typeof Reflect.get(server, "command") === "string", + ) + .map(([name]) => name); +} + function codexThreadRuntimeParams(input: { readonly threadId: ThreadId | null; readonly mcpSession: McpProviderSession.McpProviderSessionConfig | undefined; + readonly stdioMcpServers?: ReadonlyArray; readonly modelSelection?: { readonly model: string }; readonly runtimePolicy?: ProviderAdapter.ProviderAdapterV2RuntimePolicy; }): { @@ -1534,7 +1550,16 @@ function codexThreadRuntimeParams(input: { // One app-server serves many threads, so the id goes in per-thread shell config, not its env. ...(input.threadId === null ? {} - : { [`shell_environment_policy.set.${PortScanner.AGENT_THREAD_ENV}`]: input.threadId }), + : { + [`shell_environment_policy.set.${PortScanner.AGENT_THREAD_ENV}`]: input.threadId, + // Codex starts the user's stdio MCP servers per thread, outside the shell policy. + ...Object.fromEntries( + (input.stdioMcpServers ?? []).map((name) => [ + `mcp_servers.${name}.env.${PortScanner.AGENT_THREAD_ENV}`, + input.threadId, + ]), + ), + }), ...(t3Server === undefined ? {} : { @@ -2064,6 +2089,22 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( ); // A failed open is discarded, so the next turn spawns the updated binary. if (adapterOptions.compatibility !== undefined) yield* ensureInitialized; + // Read per thread: a workspace's project config can add its own servers. + const readStdioMcpServers = (cwd: string | null | undefined) => + ensureInitialized.pipe( + Effect.andThen( + client.request("config/read", { + ...(cwd == null ? {} : { cwd }), + includeLayers: false, + }), + ), + Effect.map((response) => codexStdioMcpServerNames(response.config.mcp_servers)), + Effect.catch(() => + Effect.logDebug("Codex config read failed.").pipe( + Effect.as>([]), + ), + ), + ); const now = yield* DateTime.now; const session = providerSession({ providerSessionId: input.providerSessionId, @@ -7795,13 +7836,17 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( ) => request.pipe( Effect.catchIf(isCodexThreadNotFoundError, () => - readMcpSession(providerThread.appThreadId).pipe( - Effect.flatMap((mcpSession) => + Effect.all([ + readMcpSession(providerThread.appThreadId), + readStdioMcpServers(undefined), + ]).pipe( + Effect.flatMap(([mcpSession, stdioMcpServers]) => resumeNativeThread(threadId, { excludeTurns: true, ...codexThreadRuntimeParams({ threadId: providerThread.appThreadId, mcpSession, + stdioMcpServers, }), }), ), @@ -7965,12 +8010,18 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( }), ensureThread: (threadInput) => ensureInitialized.pipe( - Effect.andThen(mcpSessions.read(threadInput.threadId)), - Effect.flatMap((mcpSession) => + Effect.andThen( + Effect.all([ + mcpSessions.read(threadInput.threadId), + readStdioMcpServers(threadInput.runtimePolicy.cwd), + ]), + ), + Effect.flatMap(([mcpSession, stdioMcpServers]) => client.request("thread/start", { ...codexThreadRuntimeParams({ threadId: threadInput.threadId, mcpSession, + stdioMcpServers, modelSelection: threadInput.modelSelection, runtimePolicy: threadInput.runtimePolicy, }), @@ -8008,6 +8059,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( ...codexThreadRuntimeParams({ threadId: appThreadId, mcpSession: yield* readMcpSession(appThreadId), + stdioMcpServers: yield* readStdioMcpServers(threadInput.runtimePolicy?.cwd), ...(threadInput.modelSelection === undefined ? {} : { modelSelection: threadInput.modelSelection }), @@ -8905,6 +8957,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( ...codexThreadRuntimeParams({ threadId: threadInput.providerThread.appThreadId, mcpSession: yield* readMcpSession(threadInput.providerThread.appThreadId), + stdioMcpServers: yield* readStdioMcpServers(undefined), }), }); } @@ -8953,6 +9006,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( ...codexThreadRuntimeParams({ threadId: threadInput.targetThreadId, mcpSession: yield* mcpSessions.read(threadInput.targetThreadId), + stdioMcpServers: yield* readStdioMcpServers(threadInput.runtimePolicy?.cwd), ...(threadInput.modelSelection === undefined ? {} : { modelSelection: threadInput.modelSelection }), diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/codex_model_reroute/codex_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/codex_model_reroute/codex_transcript.ndjson index aa14fb3b08d50..43f96d949175f 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/codex_model_reroute/codex_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/codex_model_reroute/codex_transcript.ndjson @@ -2,20 +2,22 @@ {"type":"expect_outbound","label":"initialize","frame":{"id":1,"method":"initialize","params":{"capabilities":{"experimentalApi":true,"optOutNotificationMethods":["turn/diff/updated"],"extensions":{"io.modelcontextprotocol/ui":{"mimeTypes":["text/html;profile=mcp-app"]}}},"clientInfo":{"name":"T3 Code","title":"T3 Code","version":"0.0.44"}}}} {"type":"emit_inbound","label":"initialize","frame":{"id":1,"result":{"userAgent":"t3code_desktop/0.156.1 (Debian 13.0.0; x86_64) unknown (t3code_desktop; 0.1.0)","codexHome":"/home/replay-user/.codex","platformFamily":"unix","platformOs":"linux"}}} {"type":"expect_outbound","label":"initialized","frame":{"method":"initialized"}} -{"type":"expect_outbound","label":"thread/start","frame":{"id":2,"method":"thread/start","params":{"config":{"tools.update_plan.enabled":true,"mcp_optional_startup_grace_ms":10000,"features.concurrent_reasoning_summaries":true},"cwd":"","model":"gpt-6-luna"}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":2,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":2,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"thread/start","frame":{"id":3,"method":"thread/start","params":{"config":{"tools.update_plan.enabled":true,"mcp_optional_startup_grace_ms":10000,"features.concurrent_reasoning_summaries":true},"cwd":"","model":"gpt-6-luna"}}} {"type":"emit_inbound","label":"configWarning","frame":{"method":"configWarning","params":{"summary":"Codex could not find bubblewrap on PATH. Install bubblewrap with your OS package manager. See the sandbox prerequisites: https://developers.openai.com/codex/concepts/sandboxing#prerequisites. Codex will use the bundled bubblewrap in the meantime.","details":null},"emittedAtMs":1790295480414}} {"type":"emit_inbound","label":"remoteControl/status/changed","frame":{"method":"remoteControl/status/changed","params":{"status":"disabled","serverName":"replay-host","installationId":"00000000-0000-4000-8000-000000000000","environmentId":null},"emittedAtMs":1790295480414}} -{"type":"emit_inbound","label":"thread/start","frame":{"id":2,"result":{"thread":{"id":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790295480,"updatedAt":1790295480,"recencyAt":1790295480,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-18-00-01a0d5ed-187d-70c2-b4b6-b6881a68de09.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]},"model":"gpt-6-luna","modelProvider":"openai","serviceTier":null,"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"],"instructionSources":["/home/replay-user/.codex/AGENTS.md","/home/replay-user/t3code/AGENTS.md"],"approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":{"id":":workspace","extends":null},"reasoningEffort":null,"multiAgentMode":"explicitRequestOnly"}}} -{"type":"expect_outbound","label":"thread/name/set","frame":{"id":3,"method":"thread/name/set","params":{"name":"Replay fixture: codex_model_reroute","threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09"}}} -{"type":"emit_inbound","label":"thread/name/set","frame":{"id":3,"result":{}}} +{"type":"emit_inbound","label":"thread/start","frame":{"id":3,"result":{"thread":{"id":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790295480,"updatedAt":1790295480,"recencyAt":1790295480,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-18-00-01a0d5ed-187d-70c2-b4b6-b6881a68de09.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]},"model":"gpt-6-luna","modelProvider":"openai","serviceTier":null,"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"],"instructionSources":["/home/replay-user/.codex/AGENTS.md","/home/replay-user/t3code/AGENTS.md"],"approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":{"id":":workspace","extends":null},"reasoningEffort":null,"multiAgentMode":"explicitRequestOnly"}}} +{"type":"expect_outbound","label":"thread/name/set","frame":{"id":4,"method":"thread/name/set","params":{"name":"Replay fixture: codex_model_reroute","threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09"}}} +{"type":"emit_inbound","label":"thread/name/set","frame":{"id":4,"result":{}}} {"type":"emit_inbound","label":"thread/name/updated","frame":{"method":"thread/name/updated","params":{"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","threadName":"Replay fixture: codex_model_reroute"}}} -{"type":"expect_outbound","label":"config/read","frame":{"id":4,"method":"config/read","params":{"cwd":"","includeLayers":false}}} -{"type":"emit_inbound","label":"config/read","frame":{"id":4,"result":{"config":{},"origins":{}}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":5,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Respond with exactly: first fixture turn complete","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"auto","threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":5,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":5,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":6,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Respond with exactly: first fixture turn complete","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"auto","threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} {"type":"emit_inbound","label":"thread/started","frame":{"method":"thread/started","params":{"thread":{"id":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790295480,"updatedAt":1790295480,"recencyAt":1790295480,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-18-00-01a0d5ed-187d-70c2-b4b6-b6881a68de09.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]}},"emittedAtMs":1790295480656}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","name":"codex_apps","status":"starting","error":null,"failureReason":null},"emittedAtMs":1790295480656}} {"type":"emit_inbound","label":"thread/settings/updated","frame":{"method":"thread/settings/updated","params":{"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","threadSettings":{"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","approvalPolicy":"never","approvalsReviewer":"user","sandboxPolicy":{"type":"dangerFullAccess"},"activePermissionProfile":null,"model":"gpt-6-luna","modelProvider":"openai","serviceTier":null,"effort":null,"summary":"detailed","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna","reasoning_effort":null,"developer_instructions":null}},"multiAgentMode":"explicitRequestOnly","personality":null}},"emittedAtMs":1790295480666}} -{"type":"emit_inbound","label":"turn/start","frame":{"id":5,"result":{"turn":{"id":"01a0d5ed-1957-7a22-8399-d0172af342fd","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} +{"type":"emit_inbound","label":"turn/start","frame":{"id":6,"result":{"turn":{"id":"01a0d5ed-1957-7a22-8399-d0172af342fd","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","status":{"type":"active","activeFlags":[]}},"emittedAtMs":1790295480718}} {"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","turn":{"id":"01a0d5ed-1957-7a22-8399-d0172af342fd","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1790295480,"completedAt":null,"durationMs":null}},"emittedAtMs":1790295480718}} {"type":"emit_inbound","label":"model/rerouted","frame":{"method":"model/rerouted","params":{"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","turnId":"01a0d5ed-1957-7a22-8399-d0172af342fd","fromModel":"gpt-6-luna","toModel":"gpt-6-astra","reason":"highRiskCyberActivity"}}} @@ -33,11 +35,11 @@ {"type":"emit_inbound","label":"thread/tokenUsage/updated","frame":{"method":"thread/tokenUsage/updated","params":{"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","turnId":"01a0d5ed-1957-7a22-8399-d0172af342fd","tokenUsage":{"total":{"totalTokens":21426,"inputTokens":21418,"cachedInputTokens":6912,"cacheWriteInputTokens":0,"outputTokens":8,"reasoningOutputTokens":0},"last":{"totalTokens":21426,"inputTokens":21418,"cachedInputTokens":6912,"cacheWriteInputTokens":0,"outputTokens":8,"reasoningOutputTokens":0},"modelContextWindow":258400}},"emittedAtMs":1790295485211}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","status":{"type":"idle"}},"emittedAtMs":1790295485220}} {"type":"emit_inbound","label":"turn/completed","frame":{"method":"turn/completed","params":{"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","turn":{"id":"01a0d5ed-1957-7a22-8399-d0172af342fd","items":[{"type":"agentMessage","id":"msg_06900ecb02a780a6016ab5bdbcd76887d0ba52ca8fee9da2e1","text":"first fixture turn complete","phase":"final_answer","memoryCitation":null,"delivery":null,"questions":null}],"itemsView":"summary","status":"completed","error":null,"startedAt":1790295480,"completedAt":1790295485,"durationMs":4550}},"emittedAtMs":1790295485220}} -{"type":"expect_outbound","label":"config/read","frame":{"id":6,"method":"config/read","params":{"cwd":"","includeLayers":false}}} -{"type":"emit_inbound","label":"config/read","frame":{"id":6,"result":{"config":{},"origins":{}}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":7,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Respond with exactly: second fixture turn complete","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"auto","threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":7,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":7,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":8,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Respond with exactly: second fixture turn complete","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"auto","threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","name":"xcodebuildmcp","status":"ready","error":null,"failureReason":null},"emittedAtMs":1790295485265}} -{"type":"emit_inbound","label":"turn/start","frame":{"id":7,"result":{"turn":{"id":"01a0d5ed-2b29-7353-a6d5-7745731173b7","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} +{"type":"emit_inbound","label":"turn/start","frame":{"id":8,"result":{"turn":{"id":"01a0d5ed-2b29-7353-a6d5-7745731173b7","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","status":{"type":"active","activeFlags":[]}},"emittedAtMs":1790295485286}} {"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","turn":{"id":"01a0d5ed-2b29-7353-a6d5-7745731173b7","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1790295485,"completedAt":null,"durationMs":null}},"emittedAtMs":1790295485286}} {"type":"emit_inbound","label":"item/started","frame":{"method":"item/started","params":{"item":{"type":"userMessage","id":"01a0d5ed-2bdf-7093-9e82-b961af1fe132","clientId":null,"content":[{"type":"text","text":"Respond with exactly: second fixture turn complete","text_elements":[]}]},"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","turnId":"01a0d5ed-2b29-7353-a6d5-7745731173b7","startedAtMs":1790295485409},"emittedAtMs":1790295485409}} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/command_output_streaming/codex_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/command_output_streaming/codex_transcript.ndjson index 954c6e4a48f26..dc4f9ed7eaa80 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/command_output_streaming/codex_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/command_output_streaming/codex_transcript.ndjson @@ -2,15 +2,17 @@ {"type":"expect_outbound","label":"initialize","frame":{"id":1,"method":"initialize","params":{"capabilities":{"experimentalApi":true,"optOutNotificationMethods":["turn/diff/updated"],"extensions":{"io.modelcontextprotocol/ui":{"mimeTypes":["text/html;profile=mcp-app"]}}},"clientInfo":{"name":"T3 Code","title":"T3 Code","version":"0.0.45"}}}} {"type":"emit_inbound","label":"initialize","frame":{"id":1,"result":{"userAgent":"T3 Code/0.157.0 (Mac OS 27.0.0; arm64) unknown (T3 Code; 0.0.45)","codexHome":"/home/replay-user/.codex","platformFamily":"unix","platformOs":"macos"}}} {"type":"expect_outbound","label":"initialized","frame":{"method":"initialized"}} -{"type":"expect_outbound","label":"thread/start","frame":{"id":2,"method":"thread/start","params":{"config":{"tools.update_plan.enabled":true,"mcp_optional_startup_grace_ms":10000,"features.concurrent_reasoning_summaries":true},"cwd":"","model":"gpt-6-luna"}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":2,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":2,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"thread/start","frame":{"id":3,"method":"thread/start","params":{"config":{"tools.update_plan.enabled":true,"mcp_optional_startup_grace_ms":10000,"features.concurrent_reasoning_summaries":true},"cwd":"","model":"gpt-6-luna"}}} {"type":"emit_inbound","label":"remoteControl/status/changed","frame":{"method":"remoteControl/status/changed","params":{"status":"disabled","serverName":"replay-host","installationId":"00000000-0000-4000-8000-000000000000","environmentId":null},"emittedAtMs":1791001627148}} -{"type":"emit_inbound","label":"thread/start","frame":{"id":2,"result":{"thread":{"id":"01a10004-0a27-7421-852d-0f7f99ace2d6","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/apps/server","runtimeWorkspaceRoots":["/home/replay-user/t3code/apps/server"]}],"extra":null,"sessionId":"01a10004-0a27-7421-852d-0f7f99ace2d6","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"cpa","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1791001627,"updatedAt":1791001627,"recencyAt":1791001627,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/10/03/rollout-2026-10-03T00-27-07-01a10004-0a27-7421-852d-0f7f99ace2d6.jsonl","cwd":"/home/replay-user/t3code/apps/server","cliVersion":"0.157.0","originator":"T3 Code","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]},"model":"gpt-6-luna","modelProvider":"cpa","serviceTier":"default","disabledPluginIds":[],"cwd":"/home/replay-user/t3code/apps/server","runtimeWorkspaceRoots":["/home/replay-user/t3code/apps/server"],"instructionSources":["/home/replay-user/.codex/AGENTS.md","/home/replay-user/t3code/AGENTS.md"],"approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"readOnly","networkAccess":false},"activePermissionProfile":{"id":":read-only","extends":null},"reasoningEffort":null,"multiAgentMode":"explicitRequestOnly"}}} -{"type":"expect_outbound","label":"thread/name/set","frame":{"id":3,"method":"thread/name/set","params":{"name":"Replay fixture: command_output_streaming","threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6"}}} -{"type":"emit_inbound","label":"thread/name/set","frame":{"id":3,"result":{}}} +{"type":"emit_inbound","label":"thread/start","frame":{"id":3,"result":{"thread":{"id":"01a10004-0a27-7421-852d-0f7f99ace2d6","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/apps/server","runtimeWorkspaceRoots":["/home/replay-user/t3code/apps/server"]}],"extra":null,"sessionId":"01a10004-0a27-7421-852d-0f7f99ace2d6","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"cpa","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1791001627,"updatedAt":1791001627,"recencyAt":1791001627,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/10/03/rollout-2026-10-03T00-27-07-01a10004-0a27-7421-852d-0f7f99ace2d6.jsonl","cwd":"/home/replay-user/t3code/apps/server","cliVersion":"0.157.0","originator":"T3 Code","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]},"model":"gpt-6-luna","modelProvider":"cpa","serviceTier":"default","disabledPluginIds":[],"cwd":"/home/replay-user/t3code/apps/server","runtimeWorkspaceRoots":["/home/replay-user/t3code/apps/server"],"instructionSources":["/home/replay-user/.codex/AGENTS.md","/home/replay-user/t3code/AGENTS.md"],"approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"readOnly","networkAccess":false},"activePermissionProfile":{"id":":read-only","extends":null},"reasoningEffort":null,"multiAgentMode":"explicitRequestOnly"}}} +{"type":"expect_outbound","label":"thread/name/set","frame":{"id":4,"method":"thread/name/set","params":{"name":"Replay fixture: command_output_streaming","threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6"}}} +{"type":"emit_inbound","label":"thread/name/set","frame":{"id":4,"result":{}}} {"type":"emit_inbound","label":"thread/name/updated","frame":{"method":"thread/name/updated","params":{"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","threadName":"Replay fixture: command_output_streaming"}}} -{"type":"expect_outbound","label":"config/read","frame":{"id":4,"method":"config/read","params":{"cwd":"","includeLayers":false}}} -{"type":"emit_inbound","label":"config/read","frame":{"id":4,"result":{"config":{},"origins":{}}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":5,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Run this exact shell command in the foreground and wait for it to finish: `for i in 1 2 3 4; do printf '\\033[32mstream line %s\\033[0m\\n' $i; sleep 1; done; printf 'progress 50%%\\rprogress 100%%\\n'`. Then respond exactly: command output fixture complete","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"networkAccess":false,"type":"workspaceWrite","writableRoots":[]},"summary":"auto","threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":5,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":5,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":6,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Run this exact shell command in the foreground and wait for it to finish: `for i in 1 2 3 4; do printf '\\033[32mstream line %s\\033[0m\\n' $i; sleep 1; done; printf 'progress 50%%\\rprogress 100%%\\n'`. Then respond exactly: command output fixture complete","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"networkAccess":false,"type":"workspaceWrite","writableRoots":[]},"summary":"auto","threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} {"type":"emit_inbound","label":"thread/started","frame":{"method":"thread/started","params":{"thread":{"id":"01a10004-0a27-7421-852d-0f7f99ace2d6","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/apps/server","runtimeWorkspaceRoots":["/home/replay-user/t3code/apps/server"]}],"extra":null,"sessionId":"01a10004-0a27-7421-852d-0f7f99ace2d6","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"cpa","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1791001627,"updatedAt":1791001627,"recencyAt":1791001627,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/10/03/rollout-2026-10-03T00-27-07-01a10004-0a27-7421-852d-0f7f99ace2d6.jsonl","cwd":"/home/replay-user/t3code/apps/server","cliVersion":"0.157.0","originator":"T3 Code","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]}},"emittedAtMs":1791001627410}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","name":"cua_repl","status":"starting","error":null,"failureReason":null},"emittedAtMs":1791001627411}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","name":"codex_apps","status":"starting","error":null,"failureReason":null},"emittedAtMs":1791001627411}} @@ -18,7 +20,7 @@ {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","name":"paper","status":"starting","error":null,"failureReason":null},"emittedAtMs":1791001627411}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","name":"node_repl","status":"starting","error":null,"failureReason":null},"emittedAtMs":1791001627411}} {"type":"emit_inbound","label":"thread/settings/updated","frame":{"method":"thread/settings/updated","params":{"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","threadSettings":{"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/apps/server","approvalPolicy":"never","approvalsReviewer":"user","sandboxPolicy":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":null,"model":"gpt-6-luna","modelProvider":"cpa","serviceTier":"default","effort":null,"summary":"detailed","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna","reasoning_effort":null,"developer_instructions":null}},"multiAgentMode":"explicitRequestOnly","personality":null}},"emittedAtMs":1791001627437}} -{"type":"emit_inbound","label":"turn/start","frame":{"id":5,"result":{"turn":{"id":"01a10004-0b1b-78f0-a41c-b253bded078e","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} +{"type":"emit_inbound","label":"turn/start","frame":{"id":6,"result":{"turn":{"id":"01a10004-0b1b-78f0-a41c-b253bded078e","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"account/updated","frame":{"method":"account/updated","params":{"authMode":"chatgpt","planType":"unknown"},"emittedAtMs":1791001627550}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","status":{"type":"active","activeFlags":[]}},"emittedAtMs":1791001627553}} {"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","turn":{"id":"01a10004-0b1b-78f0-a41c-b253bded078e","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1791001627,"completedAt":null,"durationMs":null}},"emittedAtMs":1791001627553}} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/delegated_task_status/codex_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/delegated_task_status/codex_transcript.ndjson index e40c278285055..0dd98394500b7 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/delegated_task_status/codex_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/delegated_task_status/codex_transcript.ndjson @@ -2,28 +2,32 @@ {"type":"expect_outbound","label":"initialize","frame":{"id":1,"method":"initialize","params":{"capabilities":{"experimentalApi":true,"optOutNotificationMethods":["turn/diff/updated"],"extensions":{"io.modelcontextprotocol/ui":{"mimeTypes":["text/html;profile=mcp-app"]}}},"clientInfo":{"name":"T3 Code","title":"T3 Code","version":"0.0.44"}}}} {"type":"emit_inbound","label":"initialize","frame":{"id":1,"result":{"userAgent":"t3code_desktop/0.120.0 (Mac OS 26.4.1; arm64) dumb (t3code_desktop; 0.1.0)","codexHome":"/home/replay-user/.codex","platformFamily":"unix","platformOs":"macos"}}} {"type":"expect_outbound","label":"initialized","frame":{"method":"initialized"}} -{"type":"expect_outbound","label":"parent.thread/start","frame":{"id":2,"method":"thread/start","params":{"config":{"tools.update_plan.enabled":true,"mcp_optional_startup_grace_ms":10000,"features.concurrent_reasoning_summaries":true}}}} -{"type":"emit_inbound","label":"parent.thread/start","frame":{"id":2,"result":{"thread":{"id":"019f1000-0000-7000-8000-000000000001","forkedFromId":null,"preview":"","ephemeral":false,"modelProvider":"openai","createdAt":1776739467,"updatedAt":1776739467,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/delegated-task-status-parent.jsonl","cwd":"/home/replay-user/t3code","cliVersion":"0.120.0","source":"vscode","agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"turns":[]},"model":"gpt-5.4","modelProvider":"openai","serviceTier":"fast","cwd":"/home/replay-user/t3code","approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"readOnlyAccess":{"type":"fullAccess"},"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"reasoningEffort":"xhigh"}}} -{"type":"expect_outbound","label":"thread/name/set","frame":{"id":3,"method":"thread/name/set","params":{"name":"Replay fixture: delegated_task_status","threadId":"019f1000-0000-7000-8000-000000000001"}}} -{"type":"emit_inbound","label":"thread/name/set","frame":{"id":3,"result":{}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":2,"method":"config/read","params":{"includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":2,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"parent.thread/start","frame":{"id":3,"method":"thread/start","params":{"config":{"tools.update_plan.enabled":true,"mcp_optional_startup_grace_ms":10000,"features.concurrent_reasoning_summaries":true}}}} +{"type":"emit_inbound","label":"parent.thread/start","frame":{"id":3,"result":{"thread":{"id":"019f1000-0000-7000-8000-000000000001","forkedFromId":null,"preview":"","ephemeral":false,"modelProvider":"openai","createdAt":1776739467,"updatedAt":1776739467,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/delegated-task-status-parent.jsonl","cwd":"/home/replay-user/t3code","cliVersion":"0.120.0","source":"vscode","agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"turns":[]},"model":"gpt-5.4","modelProvider":"openai","serviceTier":"fast","cwd":"/home/replay-user/t3code","approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"readOnlyAccess":{"type":"fullAccess"},"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"reasoningEffort":"xhigh"}}} +{"type":"expect_outbound","label":"thread/name/set","frame":{"id":4,"method":"thread/name/set","params":{"name":"Replay fixture: delegated_task_status","threadId":"019f1000-0000-7000-8000-000000000001"}}} +{"type":"emit_inbound","label":"thread/name/set","frame":{"id":4,"result":{}}} {"type":"emit_inbound","label":"thread/name/updated","frame":{"method":"thread/name/updated","params":{"threadId":"019f1000-0000-7000-8000-000000000001","threadName":"Replay fixture: delegated_task_status"}}} -{"type":"expect_outbound","label":"config/read","frame":{"id":4,"method":"config/read","params":{"cwd":"","includeLayers":false}}} -{"type":"emit_inbound","label":"config/read","frame":{"id":4,"result":{"config":{},"origins":{}}}} -{"type":"expect_outbound","label":"parent.turn/start","frame":{"id":5,"method":"turn/start","params":{"approvalPolicy":"never","cwd":"","input":[{"text":"Keep this parent turn active while orchestration tools are tested.","type":"text"}],"model":"gpt-5.4","sandboxPolicy":{"type":"dangerFullAccess"},"threadId":"019f1000-0000-7000-8000-000000000001","approvalsReviewer":"user","summary":"auto","collaborationMode":{"mode":"default","settings":{"model":"gpt-5.4"}}}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":5,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":5,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"parent.turn/start","frame":{"id":6,"method":"turn/start","params":{"approvalPolicy":"never","cwd":"","input":[{"text":"Keep this parent turn active while orchestration tools are tested.","type":"text"}],"model":"gpt-5.4","sandboxPolicy":{"type":"dangerFullAccess"},"threadId":"019f1000-0000-7000-8000-000000000001","approvalsReviewer":"user","summary":"auto","collaborationMode":{"mode":"default","settings":{"model":"gpt-5.4"}}}}} {"type":"emit_inbound","label":"parent.thread/started","frame":{"method":"thread/started","params":{"thread":{"id":"019f1000-0000-7000-8000-000000000001","forkedFromId":null,"preview":"","ephemeral":false,"modelProvider":"openai","createdAt":1776739467,"updatedAt":1776739467,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/delegated-task-status-parent.jsonl","cwd":"/home/replay-user/t3code","cliVersion":"0.120.0","source":"vscode","agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"turns":[]}}}} -{"type":"emit_inbound","label":"parent.turn/start","frame":{"id":5,"result":{"turn":{"id":"019f1000-0000-7000-8000-000000000002","items":[],"status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} +{"type":"emit_inbound","label":"parent.turn/start","frame":{"id":6,"result":{"turn":{"id":"019f1000-0000-7000-8000-000000000002","items":[],"status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"parent.thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"019f1000-0000-7000-8000-000000000001","status":{"type":"active","activeFlags":[]}}}} {"type":"emit_inbound","label":"parent.turn/started","frame":{"method":"turn/started","params":{"threadId":"019f1000-0000-7000-8000-000000000001","turn":{"id":"019f1000-0000-7000-8000-000000000002","items":[],"status":"inProgress","error":null,"startedAt":1776739467,"completedAt":null,"durationMs":null}}}} -{"type":"expect_outbound","label":"child.thread/start","frame":{"id":6,"method":"thread/start","params":{"config":{"tools.update_plan.enabled":true,"mcp_optional_startup_grace_ms":10000,"features.concurrent_reasoning_summaries":true},"threadSource":"subagent"}}} -{"type":"emit_inbound","label":"child.thread/start","frame":{"id":6,"result":{"thread":{"id":"019f1000-0000-7000-8000-000000000003","forkedFromId":null,"preview":"","ephemeral":false,"modelProvider":"openai","createdAt":1776739468,"updatedAt":1776739468,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/delegated-task-status-child.jsonl","cwd":"/home/replay-user/t3code","cliVersion":"0.120.0","source":"vscode","agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"turns":[]},"model":"gpt-5.4","modelProvider":"openai","serviceTier":"fast","cwd":"/home/replay-user/t3code","approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"readOnlyAccess":{"type":"fullAccess"},"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"reasoningEffort":"xhigh"}}} -{"type":"expect_outbound","label":"thread/name/set","frame":{"id":7,"method":"thread/name/set","params":{"name":"Replay fixture: delegated_task_status","threadId":"019f1000-0000-7000-8000-000000000003"}}} -{"type":"emit_inbound","label":"thread/name/set","frame":{"id":7,"result":{}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":7,"method":"config/read","params":{"includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":7,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"child.thread/start","frame":{"id":8,"method":"thread/start","params":{"config":{"tools.update_plan.enabled":true,"mcp_optional_startup_grace_ms":10000,"features.concurrent_reasoning_summaries":true},"threadSource":"subagent"}}} +{"type":"emit_inbound","label":"child.thread/start","frame":{"id":8,"result":{"thread":{"id":"019f1000-0000-7000-8000-000000000003","forkedFromId":null,"preview":"","ephemeral":false,"modelProvider":"openai","createdAt":1776739468,"updatedAt":1776739468,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/delegated-task-status-child.jsonl","cwd":"/home/replay-user/t3code","cliVersion":"0.120.0","source":"vscode","agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"turns":[]},"model":"gpt-5.4","modelProvider":"openai","serviceTier":"fast","cwd":"/home/replay-user/t3code","approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"readOnlyAccess":{"type":"fullAccess"},"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"reasoningEffort":"xhigh"}}} +{"type":"expect_outbound","label":"thread/name/set","frame":{"id":9,"method":"thread/name/set","params":{"name":"Replay fixture: delegated_task_status","threadId":"019f1000-0000-7000-8000-000000000003"}}} +{"type":"emit_inbound","label":"thread/name/set","frame":{"id":9,"result":{}}} {"type":"emit_inbound","label":"thread/name/updated","frame":{"method":"thread/name/updated","params":{"threadId":"019f1000-0000-7000-8000-000000000003","threadName":"Replay fixture: delegated_task_status"}}} -{"type":"expect_outbound","label":"config/read","frame":{"id":8,"method":"config/read","params":{"cwd":"","includeLayers":false}}} -{"type":"emit_inbound","label":"config/read","frame":{"id":8,"result":{"config":{},"origins":{}}}} -{"type":"expect_outbound","label":"child.original.turn/start","frame":{"id":9,"method":"turn/start","params":{"approvalPolicy":"never","cwd":"","input":[{"text":"[T3 Code: the agent in T3 thread \"thread:mcp-orchestrator-parent\" sent this message, not the user.]\n\nInspect the delegated API boundary and return the result.","type":"text"}],"model":"gpt-5.4","sandboxPolicy":{"type":"dangerFullAccess"},"threadId":"019f1000-0000-7000-8000-000000000003","approvalsReviewer":"user","summary":"auto","collaborationMode":{"mode":"default","settings":{"model":"gpt-5.4"}}}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":10,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":10,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"child.original.turn/start","frame":{"id":11,"method":"turn/start","params":{"approvalPolicy":"never","cwd":"","input":[{"text":"[T3 Code: the agent in T3 thread \"thread:mcp-orchestrator-parent\" sent this message, not the user.]\n\nInspect the delegated API boundary and return the result.","type":"text"}],"model":"gpt-5.4","sandboxPolicy":{"type":"dangerFullAccess"},"threadId":"019f1000-0000-7000-8000-000000000003","approvalsReviewer":"user","summary":"auto","collaborationMode":{"mode":"default","settings":{"model":"gpt-5.4"}}}}} {"type":"emit_inbound","label":"child.thread/started","frame":{"method":"thread/started","params":{"thread":{"id":"019f1000-0000-7000-8000-000000000003","forkedFromId":null,"preview":"","ephemeral":false,"modelProvider":"openai","createdAt":1776739468,"updatedAt":1776739468,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/delegated-task-status-child.jsonl","cwd":"/home/replay-user/t3code","cliVersion":"0.120.0","source":"vscode","agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"turns":[]}}}} -{"type":"emit_inbound","label":"child.original.turn/start","frame":{"id":9,"result":{"turn":{"id":"019f1000-0000-7000-8000-000000000004","items":[],"status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} +{"type":"emit_inbound","label":"child.original.turn/start","frame":{"id":11,"result":{"turn":{"id":"019f1000-0000-7000-8000-000000000004","items":[],"status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"child.original.thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"019f1000-0000-7000-8000-000000000003","status":{"type":"active","activeFlags":[]}}}} {"type":"emit_inbound","label":"child.original.turn/started","frame":{"method":"turn/started","params":{"threadId":"019f1000-0000-7000-8000-000000000003","turn":{"id":"019f1000-0000-7000-8000-000000000004","items":[],"status":"inProgress","error":null,"startedAt":1776739468,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"child.original.item/started","frame":{"method":"item/started","params":{"item":{"type":"agentMessage","id":"msg_delegated_task_status_original","text":"","phase":"final_answer","memoryCitation":null},"threadId":"019f1000-0000-7000-8000-000000000003","turnId":"019f1000-0000-7000-8000-000000000004"}}} @@ -31,20 +35,20 @@ {"type":"emit_inbound","label":"child.original.item/completed","frame":{"method":"item/completed","params":{"item":{"type":"agentMessage","id":"msg_delegated_task_status_original","text":"Delegated API boundary inspected.","phase":"final_answer","memoryCitation":null},"threadId":"019f1000-0000-7000-8000-000000000003","turnId":"019f1000-0000-7000-8000-000000000004"}}} {"type":"emit_inbound","label":"child.original.thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"019f1000-0000-7000-8000-000000000003","status":{"type":"idle"}}}} {"type":"emit_inbound","label":"child.original.turn/completed","frame":{"method":"turn/completed","params":{"threadId":"019f1000-0000-7000-8000-000000000003","turn":{"id":"019f1000-0000-7000-8000-000000000004","items":[],"status":"completed","error":null,"startedAt":1776739468,"completedAt":1776739469,"durationMs":1000}}}} -{"type":"expect_outbound","label":"config/read","frame":{"id":10,"method":"config/read","params":{"cwd":"","includeLayers":false}}} -{"type":"emit_inbound","label":"config/read","frame":{"id":10,"result":{"config":{},"origins":{}}}} -{"type":"expect_outbound","label":"child.running.turn/start","frame":{"id":11,"method":"turn/start","params":{"approvalPolicy":"never","cwd":"","input":[{"text":"[T3 Code: the agent in T3 thread \"thread:mcp-orchestrator-parent\" sent this message, not the user.]\n\nRemain active until the parent cancels this delegated task.","type":"text"}],"model":"gpt-5.4","sandboxPolicy":{"type":"dangerFullAccess"},"threadId":"019f1000-0000-7000-8000-000000000003","approvalsReviewer":"user","summary":"auto","collaborationMode":{"mode":"default","settings":{"model":"gpt-5.4"}}}}} -{"type":"emit_inbound","label":"child.running.turn/start","frame":{"id":11,"result":{"turn":{"id":"019f1000-0000-7000-8000-000000000005","items":[],"status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":12,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":12,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"child.running.turn/start","frame":{"id":13,"method":"turn/start","params":{"approvalPolicy":"never","cwd":"","input":[{"text":"[T3 Code: the agent in T3 thread \"thread:mcp-orchestrator-parent\" sent this message, not the user.]\n\nRemain active until the parent cancels this delegated task.","type":"text"}],"model":"gpt-5.4","sandboxPolicy":{"type":"dangerFullAccess"},"threadId":"019f1000-0000-7000-8000-000000000003","approvalsReviewer":"user","summary":"auto","collaborationMode":{"mode":"default","settings":{"model":"gpt-5.4"}}}}} +{"type":"emit_inbound","label":"child.running.turn/start","frame":{"id":13,"result":{"turn":{"id":"019f1000-0000-7000-8000-000000000005","items":[],"status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"child.running.thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"019f1000-0000-7000-8000-000000000003","status":{"type":"active","activeFlags":[]}}}} {"type":"emit_inbound","label":"child.running.turn/started","frame":{"method":"turn/started","params":{"threadId":"019f1000-0000-7000-8000-000000000003","turn":{"id":"019f1000-0000-7000-8000-000000000005","items":[],"status":"inProgress","error":null,"startedAt":1776739470,"completedAt":null,"durationMs":null}}}} -{"type":"expect_outbound","label":"child.running.turn/interrupt","frame":{"id":12,"method":"turn/interrupt","params":{"threadId":"019f1000-0000-7000-8000-000000000003","turnId":"019f1000-0000-7000-8000-000000000005"}}} -{"type":"emit_inbound","label":"child.running.turn/interrupt","frame":{"id":12,"result":{}}} +{"type":"expect_outbound","label":"child.running.turn/interrupt","frame":{"id":14,"method":"turn/interrupt","params":{"threadId":"019f1000-0000-7000-8000-000000000003","turnId":"019f1000-0000-7000-8000-000000000005"}}} +{"type":"emit_inbound","label":"child.running.turn/interrupt","frame":{"id":14,"result":{}}} {"type":"emit_inbound","label":"child.running.thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"019f1000-0000-7000-8000-000000000003","status":{"type":"idle"}}}} {"type":"emit_inbound","label":"child.running.turn/completed","frame":{"method":"turn/completed","params":{"threadId":"019f1000-0000-7000-8000-000000000003","turn":{"id":"019f1000-0000-7000-8000-000000000005","items":[],"status":"interrupted","error":null,"startedAt":1776739470,"completedAt":1776739471,"durationMs":1000}}}} -{"type":"expect_outbound","label":"config/read","frame":{"id":13,"method":"config/read","params":{"cwd":"","includeLayers":false}}} -{"type":"emit_inbound","label":"config/read","frame":{"id":13,"result":{"config":{},"origins":{}}}} -{"type":"expect_outbound","label":"child.queued.turn/start","frame":{"id":14,"method":"turn/start","params":{"approvalPolicy":"never","cwd":"","input":[{"text":"[T3 Code: the agent in T3 thread \"thread:mcp-orchestrator-parent\" sent this message, not the user.]\n\nComplete the queued follow-up and return the final result.","type":"text"}],"model":"gpt-5.4","sandboxPolicy":{"type":"dangerFullAccess"},"threadId":"019f1000-0000-7000-8000-000000000003","approvalsReviewer":"user","summary":"auto","collaborationMode":{"mode":"default","settings":{"model":"gpt-5.4"}}}}} -{"type":"emit_inbound","label":"child.queued.turn/start","frame":{"id":14,"result":{"turn":{"id":"019f1000-0000-7000-8000-000000000006","items":[],"status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":15,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":15,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"child.queued.turn/start","frame":{"id":16,"method":"turn/start","params":{"approvalPolicy":"never","cwd":"","input":[{"text":"[T3 Code: the agent in T3 thread \"thread:mcp-orchestrator-parent\" sent this message, not the user.]\n\nComplete the queued follow-up and return the final result.","type":"text"}],"model":"gpt-5.4","sandboxPolicy":{"type":"dangerFullAccess"},"threadId":"019f1000-0000-7000-8000-000000000003","approvalsReviewer":"user","summary":"auto","collaborationMode":{"mode":"default","settings":{"model":"gpt-5.4"}}}}} +{"type":"emit_inbound","label":"child.queued.turn/start","frame":{"id":16,"result":{"turn":{"id":"019f1000-0000-7000-8000-000000000006","items":[],"status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"child.queued.thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"019f1000-0000-7000-8000-000000000003","status":{"type":"active","activeFlags":[]}}}} {"type":"emit_inbound","label":"child.queued.turn/started","frame":{"method":"turn/started","params":{"threadId":"019f1000-0000-7000-8000-000000000003","turn":{"id":"019f1000-0000-7000-8000-000000000006","items":[],"status":"inProgress","error":null,"startedAt":1776739472,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"child.queued.item/started","frame":{"method":"item/started","params":{"item":{"type":"agentMessage","id":"msg_delegated_task_status_queued","text":"","phase":"final_answer","memoryCitation":null},"threadId":"019f1000-0000-7000-8000-000000000003","turnId":"019f1000-0000-7000-8000-000000000006"}}} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/message_steering/codex_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/message_steering/codex_transcript.ndjson index 04326cba7f59d..2afc2bf567e6e 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/message_steering/codex_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/message_steering/codex_transcript.ndjson @@ -2,24 +2,26 @@ {"type":"expect_outbound","label":"initialize","frame":{"id":1,"method":"initialize","params":{"capabilities":{"experimentalApi":true,"optOutNotificationMethods":["turn/diff/updated"],"extensions":{"io.modelcontextprotocol/ui":{"mimeTypes":["text/html;profile=mcp-app"]}}},"clientInfo":{"name":"T3 Code","title":"T3 Code","version":"0.0.44"}}}} {"type":"emit_inbound","label":"initialize","frame":{"id":1,"result":{"userAgent":"t3code_desktop/0.156.1 (Debian 13.0.0; x86_64) unknown (t3code_desktop; 0.1.0)","codexHome":"/home/replay-user/.codex","platformFamily":"unix","platformOs":"linux"}}} {"type":"expect_outbound","label":"initialized","frame":{"method":"initialized"}} -{"type":"expect_outbound","label":"thread/start","frame":{"id":2,"method":"thread/start","params":{"config":{"tools.update_plan.enabled":true,"mcp_optional_startup_grace_ms":10000,"features.concurrent_reasoning_summaries":true},"cwd":"","model":"gpt-6-luna"}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":2,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":2,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"thread/start","frame":{"id":3,"method":"thread/start","params":{"config":{"tools.update_plan.enabled":true,"mcp_optional_startup_grace_ms":10000,"features.concurrent_reasoning_summaries":true},"cwd":"","model":"gpt-6-luna"}}} {"type":"emit_inbound","label":"configWarning","frame":{"method":"configWarning","params":{"summary":"Codex could not find bubblewrap on PATH. Install bubblewrap with your OS package manager. See the sandbox prerequisites: https://developers.openai.com/codex/concepts/sandboxing#prerequisites. Codex will use the bundled bubblewrap in the meantime.","details":null},"emittedAtMs":1790295500250}} {"type":"emit_inbound","label":"remoteControl/status/changed","frame":{"method":"remoteControl/status/changed","params":{"status":"disabled","serverName":"replay-host","installationId":"00000000-0000-4000-8000-000000000000","environmentId":null},"emittedAtMs":1790295500250}} -{"type":"emit_inbound","label":"thread/start","frame":{"id":2,"result":{"thread":{"id":"01a0d5ed-65ea-7d42-b8e9-d06f045cfa86","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d5ed-65ea-7d42-b8e9-d06f045cfa86","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790295500,"updatedAt":1790295500,"recencyAt":1790295500,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-18-20-01a0d5ed-65ea-7d42-b8e9-d06f045cfa86.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]},"model":"gpt-6-luna","modelProvider":"openai","serviceTier":null,"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"],"instructionSources":["/home/replay-user/.codex/AGENTS.md","/home/replay-user/t3code/AGENTS.md"],"approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":{"id":":workspace","extends":null},"reasoningEffort":null,"multiAgentMode":"explicitRequestOnly"}}} -{"type":"expect_outbound","label":"thread/name/set","frame":{"id":3,"method":"thread/name/set","params":{"name":"Replay fixture: message_steering","threadId":"01a0d5ed-65ea-7d42-b8e9-d06f045cfa86"}}} -{"type":"emit_inbound","label":"thread/name/set","frame":{"id":3,"result":{}}} +{"type":"emit_inbound","label":"thread/start","frame":{"id":3,"result":{"thread":{"id":"01a0d5ed-65ea-7d42-b8e9-d06f045cfa86","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d5ed-65ea-7d42-b8e9-d06f045cfa86","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790295500,"updatedAt":1790295500,"recencyAt":1790295500,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-18-20-01a0d5ed-65ea-7d42-b8e9-d06f045cfa86.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]},"model":"gpt-6-luna","modelProvider":"openai","serviceTier":null,"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"],"instructionSources":["/home/replay-user/.codex/AGENTS.md","/home/replay-user/t3code/AGENTS.md"],"approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":{"id":":workspace","extends":null},"reasoningEffort":null,"multiAgentMode":"explicitRequestOnly"}}} +{"type":"expect_outbound","label":"thread/name/set","frame":{"id":4,"method":"thread/name/set","params":{"name":"Replay fixture: message_steering","threadId":"01a0d5ed-65ea-7d42-b8e9-d06f045cfa86"}}} +{"type":"emit_inbound","label":"thread/name/set","frame":{"id":4,"result":{}}} {"type":"emit_inbound","label":"thread/name/updated","frame":{"method":"thread/name/updated","params":{"threadId":"01a0d5ed-65ea-7d42-b8e9-d06f045cfa86","threadName":"Replay fixture: message_steering"}}} -{"type":"expect_outbound","label":"config/read","frame":{"id":4,"method":"config/read","params":{"cwd":"","includeLayers":false}}} -{"type":"emit_inbound","label":"config/read","frame":{"id":4,"result":{"config":{},"origins":{}}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":5,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Respond with exactly: steering fixture initial response","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"auto","threadId":"01a0d5ed-65ea-7d42-b8e9-d06f045cfa86","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":5,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":5,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":6,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Respond with exactly: steering fixture initial response","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"auto","threadId":"01a0d5ed-65ea-7d42-b8e9-d06f045cfa86","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} {"type":"emit_inbound","label":"thread/started","frame":{"method":"thread/started","params":{"thread":{"id":"01a0d5ed-65ea-7d42-b8e9-d06f045cfa86","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d5ed-65ea-7d42-b8e9-d06f045cfa86","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790295500,"updatedAt":1790295500,"recencyAt":1790295500,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-18-20-01a0d5ed-65ea-7d42-b8e9-d06f045cfa86.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]}},"emittedAtMs":1790295500547}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0d5ed-65ea-7d42-b8e9-d06f045cfa86","name":"codex_apps","status":"starting","error":null,"failureReason":null},"emittedAtMs":1790295500547}} {"type":"emit_inbound","label":"thread/settings/updated","frame":{"method":"thread/settings/updated","params":{"threadId":"01a0d5ed-65ea-7d42-b8e9-d06f045cfa86","threadSettings":{"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","approvalPolicy":"never","approvalsReviewer":"user","sandboxPolicy":{"type":"dangerFullAccess"},"activePermissionProfile":null,"model":"gpt-6-luna","modelProvider":"openai","serviceTier":null,"effort":null,"summary":"detailed","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna","reasoning_effort":null,"developer_instructions":null}},"multiAgentMode":"explicitRequestOnly","personality":null}},"emittedAtMs":1790295500567}} -{"type":"emit_inbound","label":"turn/start","frame":{"id":5,"result":{"turn":{"id":"01a0d5ed-670e-7032-9a87-707c736491a6","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} +{"type":"emit_inbound","label":"turn/start","frame":{"id":6,"result":{"turn":{"id":"01a0d5ed-670e-7032-9a87-707c736491a6","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d5ed-65ea-7d42-b8e9-d06f045cfa86","status":{"type":"active","activeFlags":[]}},"emittedAtMs":1790295500626}} {"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"01a0d5ed-65ea-7d42-b8e9-d06f045cfa86","turn":{"id":"01a0d5ed-670e-7032-9a87-707c736491a6","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1790295500,"completedAt":null,"durationMs":null}},"emittedAtMs":1790295500626}} -{"type":"expect_outbound","label":"turn/steer","frame":{"id":6,"method":"turn/steer","params":{"expectedTurnId":"01a0d5ed-670e-7032-9a87-707c736491a6","input":[{"text":"Actually, respond with exactly: steering fixture observed","type":"text"}],"threadId":"01a0d5ed-65ea-7d42-b8e9-d06f045cfa86"}}} -{"type":"emit_inbound","label":"turn/steer","frame":{"id":6,"result":{"turnId":"01a0d5ed-670e-7032-9a87-707c736491a6"}}} +{"type":"expect_outbound","label":"turn/steer","frame":{"id":7,"method":"turn/steer","params":{"expectedTurnId":"01a0d5ed-670e-7032-9a87-707c736491a6","input":[{"text":"Actually, respond with exactly: steering fixture observed","type":"text"}],"threadId":"01a0d5ed-65ea-7d42-b8e9-d06f045cfa86"}}} +{"type":"emit_inbound","label":"turn/steer","frame":{"id":7,"result":{"turnId":"01a0d5ed-670e-7032-9a87-707c736491a6"}}} {"type":"emit_inbound","label":"account/updated","frame":{"method":"account/updated","params":{"authMode":"chatgpt","planType":"unknown"},"emittedAtMs":1790295500936}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0d5ed-65ea-7d42-b8e9-d06f045cfa86","name":"xcodebuildmcp","status":"starting","error":null,"failureReason":null},"emittedAtMs":1790295501151}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0d5ed-65ea-7d42-b8e9-d06f045cfa86","name":"codex_apps","status":"ready","error":null,"failureReason":null},"emittedAtMs":1790295501388}} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/multi_turn/codex_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/multi_turn/codex_transcript.ndjson index 47194cff98a1d..58604e829fc67 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/multi_turn/codex_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/multi_turn/codex_transcript.ndjson @@ -2,20 +2,22 @@ {"type":"expect_outbound","label":"initialize","frame":{"id":1,"method":"initialize","params":{"capabilities":{"experimentalApi":true,"optOutNotificationMethods":["turn/diff/updated"],"extensions":{"io.modelcontextprotocol/ui":{"mimeTypes":["text/html;profile=mcp-app"]}}},"clientInfo":{"name":"T3 Code","title":"T3 Code","version":"0.0.44"}}}} {"type":"emit_inbound","label":"initialize","frame":{"id":1,"result":{"userAgent":"t3code_desktop/0.156.1 (Debian 13.0.0; x86_64) unknown (t3code_desktop; 0.1.0)","codexHome":"/home/replay-user/.codex","platformFamily":"unix","platformOs":"linux"}}} {"type":"expect_outbound","label":"initialized","frame":{"method":"initialized"}} -{"type":"expect_outbound","label":"thread/start","frame":{"id":2,"method":"thread/start","params":{"config":{"tools.update_plan.enabled":true,"mcp_optional_startup_grace_ms":10000,"features.concurrent_reasoning_summaries":true},"cwd":"","model":"gpt-6-luna"}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":2,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":2,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"thread/start","frame":{"id":3,"method":"thread/start","params":{"config":{"tools.update_plan.enabled":true,"mcp_optional_startup_grace_ms":10000,"features.concurrent_reasoning_summaries":true},"cwd":"","model":"gpt-6-luna"}}} {"type":"emit_inbound","label":"configWarning","frame":{"method":"configWarning","params":{"summary":"Codex could not find bubblewrap on PATH. Install bubblewrap with your OS package manager. See the sandbox prerequisites: https://developers.openai.com/codex/concepts/sandboxing#prerequisites. Codex will use the bundled bubblewrap in the meantime.","details":null},"emittedAtMs":1790295480414}} {"type":"emit_inbound","label":"remoteControl/status/changed","frame":{"method":"remoteControl/status/changed","params":{"status":"disabled","serverName":"replay-host","installationId":"00000000-0000-4000-8000-000000000000","environmentId":null},"emittedAtMs":1790295480414}} -{"type":"emit_inbound","label":"thread/start","frame":{"id":2,"result":{"thread":{"id":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790295480,"updatedAt":1790295480,"recencyAt":1790295480,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-18-00-01a0d5ed-187d-70c2-b4b6-b6881a68de09.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]},"model":"gpt-6-luna","modelProvider":"openai","serviceTier":null,"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"],"instructionSources":["/home/replay-user/.codex/AGENTS.md","/home/replay-user/t3code/AGENTS.md"],"approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":{"id":":workspace","extends":null},"reasoningEffort":null,"multiAgentMode":"explicitRequestOnly"}}} -{"type":"expect_outbound","label":"thread/name/set","frame":{"id":3,"method":"thread/name/set","params":{"name":"Replay fixture: multi_turn","threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09"}}} -{"type":"emit_inbound","label":"thread/name/set","frame":{"id":3,"result":{}}} +{"type":"emit_inbound","label":"thread/start","frame":{"id":3,"result":{"thread":{"id":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790295480,"updatedAt":1790295480,"recencyAt":1790295480,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-18-00-01a0d5ed-187d-70c2-b4b6-b6881a68de09.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]},"model":"gpt-6-luna","modelProvider":"openai","serviceTier":null,"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"],"instructionSources":["/home/replay-user/.codex/AGENTS.md","/home/replay-user/t3code/AGENTS.md"],"approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":{"id":":workspace","extends":null},"reasoningEffort":null,"multiAgentMode":"explicitRequestOnly"}}} +{"type":"expect_outbound","label":"thread/name/set","frame":{"id":4,"method":"thread/name/set","params":{"name":"Replay fixture: multi_turn","threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09"}}} +{"type":"emit_inbound","label":"thread/name/set","frame":{"id":4,"result":{}}} {"type":"emit_inbound","label":"thread/name/updated","frame":{"method":"thread/name/updated","params":{"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","threadName":"Replay fixture: multi_turn"}}} -{"type":"expect_outbound","label":"config/read","frame":{"id":4,"method":"config/read","params":{"cwd":"","includeLayers":false}}} -{"type":"emit_inbound","label":"config/read","frame":{"id":4,"result":{"config":{},"origins":{}}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":5,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Respond with exactly: first fixture turn complete","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"auto","threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":5,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":5,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":6,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Respond with exactly: first fixture turn complete","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"auto","threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} {"type":"emit_inbound","label":"thread/started","frame":{"method":"thread/started","params":{"thread":{"id":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790295480,"updatedAt":1790295480,"recencyAt":1790295480,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-18-00-01a0d5ed-187d-70c2-b4b6-b6881a68de09.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]}},"emittedAtMs":1790295480656}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","name":"codex_apps","status":"starting","error":null,"failureReason":null},"emittedAtMs":1790295480656}} {"type":"emit_inbound","label":"thread/settings/updated","frame":{"method":"thread/settings/updated","params":{"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","threadSettings":{"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","approvalPolicy":"never","approvalsReviewer":"user","sandboxPolicy":{"type":"dangerFullAccess"},"activePermissionProfile":null,"model":"gpt-6-luna","modelProvider":"openai","serviceTier":null,"effort":null,"summary":"detailed","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna","reasoning_effort":null,"developer_instructions":null}},"multiAgentMode":"explicitRequestOnly","personality":null}},"emittedAtMs":1790295480666}} -{"type":"emit_inbound","label":"turn/start","frame":{"id":5,"result":{"turn":{"id":"01a0d5ed-1957-7a22-8399-d0172af342fd","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} +{"type":"emit_inbound","label":"turn/start","frame":{"id":6,"result":{"turn":{"id":"01a0d5ed-1957-7a22-8399-d0172af342fd","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","status":{"type":"active","activeFlags":[]}},"emittedAtMs":1790295480718}} {"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","turn":{"id":"01a0d5ed-1957-7a22-8399-d0172af342fd","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1790295480,"completedAt":null,"durationMs":null}},"emittedAtMs":1790295480718}} {"type":"emit_inbound","label":"account/updated","frame":{"method":"account/updated","params":{"authMode":"chatgpt","planType":"unknown"},"emittedAtMs":1790295481015}} @@ -32,11 +34,11 @@ {"type":"emit_inbound","label":"thread/tokenUsage/updated","frame":{"method":"thread/tokenUsage/updated","params":{"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","turnId":"01a0d5ed-1957-7a22-8399-d0172af342fd","tokenUsage":{"total":{"totalTokens":21426,"inputTokens":21418,"cachedInputTokens":6912,"cacheWriteInputTokens":0,"outputTokens":8,"reasoningOutputTokens":0},"last":{"totalTokens":21426,"inputTokens":21418,"cachedInputTokens":6912,"cacheWriteInputTokens":0,"outputTokens":8,"reasoningOutputTokens":0},"modelContextWindow":258400}},"emittedAtMs":1790295485211}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","status":{"type":"idle"}},"emittedAtMs":1790295485220}} {"type":"emit_inbound","label":"turn/completed","frame":{"method":"turn/completed","params":{"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","turn":{"id":"01a0d5ed-1957-7a22-8399-d0172af342fd","items":[{"type":"agentMessage","id":"msg_06900ecb02a780a6016ab5bdbcd76887d0ba52ca8fee9da2e1","text":"first fixture turn complete","phase":"final_answer","memoryCitation":null,"delivery":null,"questions":null}],"itemsView":"summary","status":"completed","error":null,"startedAt":1790295480,"completedAt":1790295485,"durationMs":4550}},"emittedAtMs":1790295485220}} -{"type":"expect_outbound","label":"config/read","frame":{"id":6,"method":"config/read","params":{"cwd":"","includeLayers":false}}} -{"type":"emit_inbound","label":"config/read","frame":{"id":6,"result":{"config":{},"origins":{}}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":7,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Respond with exactly: second fixture turn complete","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"auto","threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":7,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":7,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":8,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Respond with exactly: second fixture turn complete","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"auto","threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","name":"xcodebuildmcp","status":"ready","error":null,"failureReason":null},"emittedAtMs":1790295485265}} -{"type":"emit_inbound","label":"turn/start","frame":{"id":7,"result":{"turn":{"id":"01a0d5ed-2b29-7353-a6d5-7745731173b7","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} +{"type":"emit_inbound","label":"turn/start","frame":{"id":8,"result":{"turn":{"id":"01a0d5ed-2b29-7353-a6d5-7745731173b7","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","status":{"type":"active","activeFlags":[]}},"emittedAtMs":1790295485286}} {"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","turn":{"id":"01a0d5ed-2b29-7353-a6d5-7745731173b7","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1790295485,"completedAt":null,"durationMs":null}},"emittedAtMs":1790295485286}} {"type":"emit_inbound","label":"item/started","frame":{"method":"item/started","params":{"item":{"type":"userMessage","id":"01a0d5ed-2bdf-7093-9e82-b961af1fe132","clientId":null,"content":[{"type":"text","text":"Respond with exactly: second fixture turn complete","text_elements":[]}]},"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","turnId":"01a0d5ed-2b29-7353-a6d5-7745731173b7","startedAtMs":1790295485409},"emittedAtMs":1790295485409}} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/plan_questions/codex_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/plan_questions/codex_transcript.ndjson index b44351ebb9ce3..6d359da0b323f 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/plan_questions/codex_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/plan_questions/codex_transcript.ndjson @@ -2,20 +2,22 @@ {"type":"expect_outbound","label":"initialize","frame":{"id":1,"method":"initialize","params":{"capabilities":{"experimentalApi":true,"optOutNotificationMethods":["turn/diff/updated"],"extensions":{"io.modelcontextprotocol/ui":{"mimeTypes":["text/html;profile=mcp-app"]}}},"clientInfo":{"name":"T3 Code","title":"T3 Code","version":"0.0.44"}}}} {"type":"emit_inbound","label":"initialize","frame":{"id":1,"result":{"userAgent":"t3code_desktop/0.156.1 (Debian 13.0.0; x86_64) unknown (t3code_desktop; 0.1.0)","codexHome":"/home/replay-user/.codex","platformFamily":"unix","platformOs":"linux"}}} {"type":"expect_outbound","label":"initialized","frame":{"method":"initialized"}} -{"type":"expect_outbound","label":"thread/start","frame":{"id":2,"method":"thread/start","params":{"config":{"tools.update_plan.enabled":true,"mcp_optional_startup_grace_ms":10000,"features.concurrent_reasoning_summaries":true},"cwd":"","model":"gpt-6-luna"}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":2,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":2,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"thread/start","frame":{"id":3,"method":"thread/start","params":{"config":{"tools.update_plan.enabled":true,"mcp_optional_startup_grace_ms":10000,"features.concurrent_reasoning_summaries":true},"cwd":"","model":"gpt-6-luna"}}} {"type":"emit_inbound","label":"configWarning","frame":{"method":"configWarning","params":{"summary":"Codex could not find bubblewrap on PATH. Install bubblewrap with your OS package manager. See the sandbox prerequisites: https://developers.openai.com/codex/concepts/sandboxing#prerequisites. Codex will use the bundled bubblewrap in the meantime.","details":null},"emittedAtMs":1790295620180}} {"type":"emit_inbound","label":"remoteControl/status/changed","frame":{"method":"remoteControl/status/changed","params":{"status":"disabled","serverName":"replay-host","installationId":"00000000-0000-4000-8000-000000000000","environmentId":null},"emittedAtMs":1790295620180}} -{"type":"emit_inbound","label":"thread/start","frame":{"id":2,"result":{"thread":{"id":"01a0d5ef-3a6a-75d0-9942-61b29ab82328","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d5ef-3a6a-75d0-9942-61b29ab82328","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790295620,"updatedAt":1790295620,"recencyAt":1790295620,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-20-20-01a0d5ef-3a6a-75d0-9942-61b29ab82328.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]},"model":"gpt-6-luna","modelProvider":"openai","serviceTier":null,"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"],"instructionSources":["/home/replay-user/.codex/AGENTS.md","/home/replay-user/t3code/AGENTS.md"],"approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":{"id":":workspace","extends":null},"reasoningEffort":null,"multiAgentMode":"explicitRequestOnly"}}} -{"type":"expect_outbound","label":"thread/name/set","frame":{"id":3,"method":"thread/name/set","params":{"name":"Replay fixture: plan_questions","threadId":"01a0d5ef-3a6a-75d0-9942-61b29ab82328"}}} -{"type":"emit_inbound","label":"thread/name/set","frame":{"id":3,"result":{}}} +{"type":"emit_inbound","label":"thread/start","frame":{"id":3,"result":{"thread":{"id":"01a0d5ef-3a6a-75d0-9942-61b29ab82328","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d5ef-3a6a-75d0-9942-61b29ab82328","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790295620,"updatedAt":1790295620,"recencyAt":1790295620,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-20-20-01a0d5ef-3a6a-75d0-9942-61b29ab82328.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]},"model":"gpt-6-luna","modelProvider":"openai","serviceTier":null,"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"],"instructionSources":["/home/replay-user/.codex/AGENTS.md","/home/replay-user/t3code/AGENTS.md"],"approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":{"id":":workspace","extends":null},"reasoningEffort":null,"multiAgentMode":"explicitRequestOnly"}}} +{"type":"expect_outbound","label":"thread/name/set","frame":{"id":4,"method":"thread/name/set","params":{"name":"Replay fixture: plan_questions","threadId":"01a0d5ef-3a6a-75d0-9942-61b29ab82328"}}} +{"type":"emit_inbound","label":"thread/name/set","frame":{"id":4,"result":{}}} {"type":"emit_inbound","label":"thread/name/updated","frame":{"method":"thread/name/updated","params":{"threadId":"01a0d5ef-3a6a-75d0-9942-61b29ab82328","threadName":"Replay fixture: plan_questions"}}} -{"type":"expect_outbound","label":"config/read","frame":{"id":4,"method":"config/read","params":{"cwd":"","includeLayers":false}}} -{"type":"emit_inbound","label":"config/read","frame":{"id":4,"result":{"config":{},"origins":{}}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":5,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Use request_user_input to ask one multiple-choice clarifying question about whether this fixture should prefer strict schemas or UI flexibility. After receiving the answer, respond exactly: plan questions fixture complete","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"networkAccess":false,"type":"readOnly"},"summary":"auto","threadId":"01a0d5ef-3a6a-75d0-9942-61b29ab82328","collaborationMode":{"mode":"plan","settings":{"model":"gpt-6-luna"}}}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":5,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":5,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":6,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Use request_user_input to ask one multiple-choice clarifying question about whether this fixture should prefer strict schemas or UI flexibility. After receiving the answer, respond exactly: plan questions fixture complete","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"networkAccess":false,"type":"readOnly"},"summary":"auto","threadId":"01a0d5ef-3a6a-75d0-9942-61b29ab82328","collaborationMode":{"mode":"plan","settings":{"model":"gpt-6-luna"}}}}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0d5ef-3a6a-75d0-9942-61b29ab82328","name":"codex_apps","status":"starting","error":null,"failureReason":null},"emittedAtMs":1790295620428}} {"type":"emit_inbound","label":"thread/started","frame":{"method":"thread/started","params":{"thread":{"id":"01a0d5ef-3a6a-75d0-9942-61b29ab82328","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d5ef-3a6a-75d0-9942-61b29ab82328","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790295620,"updatedAt":1790295620,"recencyAt":1790295620,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-20-20-01a0d5ef-3a6a-75d0-9942-61b29ab82328.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]}},"emittedAtMs":1790295620428}} {"type":"emit_inbound","label":"thread/settings/updated","frame":{"method":"thread/settings/updated","params":{"threadId":"01a0d5ef-3a6a-75d0-9942-61b29ab82328","threadSettings":{"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","approvalPolicy":"never","approvalsReviewer":"user","sandboxPolicy":{"type":"readOnly","networkAccess":false},"activePermissionProfile":null,"model":"gpt-6-luna","modelProvider":"openai","serviceTier":null,"effort":"medium","summary":"detailed","collaborationMode":{"mode":"plan","settings":{"model":"gpt-6-luna","reasoning_effort":"medium","developer_instructions":"You are in Plan mode. Prefer request_user_input for clarifying questions. When presenting a complete plan, wrap it in and ."}},"multiAgentMode":"explicitRequestOnly","personality":null}},"emittedAtMs":1790295620457}} -{"type":"emit_inbound","label":"turn/start","frame":{"id":5,"result":{"turn":{"id":"01a0d5ef-3b5a-7bb2-9cd2-da112b6b158f","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} +{"type":"emit_inbound","label":"turn/start","frame":{"id":6,"result":{"turn":{"id":"01a0d5ef-3b5a-7bb2-9cd2-da112b6b158f","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d5ef-3a6a-75d0-9942-61b29ab82328","status":{"type":"active","activeFlags":[]}},"emittedAtMs":1790295620520}} {"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"01a0d5ef-3a6a-75d0-9942-61b29ab82328","turn":{"id":"01a0d5ef-3b5a-7bb2-9cd2-da112b6b158f","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1790295620,"completedAt":null,"durationMs":null}},"emittedAtMs":1790295620520}} {"type":"emit_inbound","label":"account/updated","frame":{"method":"account/updated","params":{"authMode":"chatgpt","planType":"unknown"},"emittedAtMs":1790295620774}} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/proposed_plan/codex_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/proposed_plan/codex_transcript.ndjson index 01e59956ea15f..6c8caa4672e61 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/proposed_plan/codex_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/proposed_plan/codex_transcript.ndjson @@ -2,20 +2,22 @@ {"type":"expect_outbound","label":"initialize","frame":{"id":1,"method":"initialize","params":{"capabilities":{"experimentalApi":true,"optOutNotificationMethods":["turn/diff/updated"],"extensions":{"io.modelcontextprotocol/ui":{"mimeTypes":["text/html;profile=mcp-app"]}}},"clientInfo":{"name":"T3 Code","title":"T3 Code","version":"0.0.44"}}}} {"type":"emit_inbound","label":"initialize","frame":{"id":1,"result":{"userAgent":"t3code_desktop/0.156.1 (Debian 13.0.0; x86_64) unknown (t3code_desktop; 0.1.0)","codexHome":"/home/replay-user/.codex","platformFamily":"unix","platformOs":"linux"}}} {"type":"expect_outbound","label":"initialized","frame":{"method":"initialized"}} -{"type":"expect_outbound","label":"thread/start","frame":{"id":2,"method":"thread/start","params":{"config":{"tools.update_plan.enabled":true,"mcp_optional_startup_grace_ms":10000,"features.concurrent_reasoning_summaries":true},"cwd":"","model":"gpt-6-luna"}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":2,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":2,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"thread/start","frame":{"id":3,"method":"thread/start","params":{"config":{"tools.update_plan.enabled":true,"mcp_optional_startup_grace_ms":10000,"features.concurrent_reasoning_summaries":true},"cwd":"","model":"gpt-6-luna"}}} {"type":"emit_inbound","label":"configWarning","frame":{"method":"configWarning","params":{"summary":"Codex could not find bubblewrap on PATH. Install bubblewrap with your OS package manager. See the sandbox prerequisites: https://developers.openai.com/codex/concepts/sandboxing#prerequisites. Codex will use the bundled bubblewrap in the meantime.","details":null},"emittedAtMs":1790295608195}} {"type":"emit_inbound","label":"remoteControl/status/changed","frame":{"method":"remoteControl/status/changed","params":{"status":"disabled","serverName":"replay-host","installationId":"00000000-0000-4000-8000-000000000000","environmentId":null},"emittedAtMs":1790295608195}} -{"type":"emit_inbound","label":"thread/start","frame":{"id":2,"result":{"thread":{"id":"01a0d5ef-0ba3-7552-b090-7cfbb328e278","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d5ef-0ba3-7552-b090-7cfbb328e278","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790295608,"updatedAt":1790295608,"recencyAt":1790295608,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-20-08-01a0d5ef-0ba3-7552-b090-7cfbb328e278.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]},"model":"gpt-6-luna","modelProvider":"openai","serviceTier":null,"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"],"instructionSources":["/home/replay-user/.codex/AGENTS.md","/home/replay-user/t3code/AGENTS.md"],"approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":{"id":":workspace","extends":null},"reasoningEffort":null,"multiAgentMode":"explicitRequestOnly"}}} -{"type":"expect_outbound","label":"thread/name/set","frame":{"id":3,"method":"thread/name/set","params":{"name":"Replay fixture: proposed_plan","threadId":"01a0d5ef-0ba3-7552-b090-7cfbb328e278"}}} -{"type":"emit_inbound","label":"thread/name/set","frame":{"id":3,"result":{}}} +{"type":"emit_inbound","label":"thread/start","frame":{"id":3,"result":{"thread":{"id":"01a0d5ef-0ba3-7552-b090-7cfbb328e278","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d5ef-0ba3-7552-b090-7cfbb328e278","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790295608,"updatedAt":1790295608,"recencyAt":1790295608,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-20-08-01a0d5ef-0ba3-7552-b090-7cfbb328e278.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]},"model":"gpt-6-luna","modelProvider":"openai","serviceTier":null,"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"],"instructionSources":["/home/replay-user/.codex/AGENTS.md","/home/replay-user/t3code/AGENTS.md"],"approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":{"id":":workspace","extends":null},"reasoningEffort":null,"multiAgentMode":"explicitRequestOnly"}}} +{"type":"expect_outbound","label":"thread/name/set","frame":{"id":4,"method":"thread/name/set","params":{"name":"Replay fixture: proposed_plan","threadId":"01a0d5ef-0ba3-7552-b090-7cfbb328e278"}}} +{"type":"emit_inbound","label":"thread/name/set","frame":{"id":4,"result":{}}} {"type":"emit_inbound","label":"thread/name/updated","frame":{"method":"thread/name/updated","params":{"threadId":"01a0d5ef-0ba3-7552-b090-7cfbb328e278","threadName":"Replay fixture: proposed_plan"}}} -{"type":"expect_outbound","label":"config/read","frame":{"id":4,"method":"config/read","params":{"cwd":"","includeLayers":false}}} -{"type":"emit_inbound","label":"config/read","frame":{"id":4,"result":{"config":{},"origins":{}}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":5,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Create a short implementation plan for adding deterministic replay fixtures. Do not ask questions. Present the final plan in a proposed plan block.","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"networkAccess":false,"type":"readOnly"},"summary":"auto","threadId":"01a0d5ef-0ba3-7552-b090-7cfbb328e278","collaborationMode":{"mode":"plan","settings":{"model":"gpt-6-luna"}}}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":5,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":5,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":6,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Create a short implementation plan for adding deterministic replay fixtures. Do not ask questions. Present the final plan in a proposed plan block.","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"networkAccess":false,"type":"readOnly"},"summary":"auto","threadId":"01a0d5ef-0ba3-7552-b090-7cfbb328e278","collaborationMode":{"mode":"plan","settings":{"model":"gpt-6-luna"}}}}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0d5ef-0ba3-7552-b090-7cfbb328e278","name":"codex_apps","status":"starting","error":null,"failureReason":null},"emittedAtMs":1790295608443}} {"type":"emit_inbound","label":"thread/started","frame":{"method":"thread/started","params":{"thread":{"id":"01a0d5ef-0ba3-7552-b090-7cfbb328e278","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d5ef-0ba3-7552-b090-7cfbb328e278","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790295608,"updatedAt":1790295608,"recencyAt":1790295608,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-20-08-01a0d5ef-0ba3-7552-b090-7cfbb328e278.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]}},"emittedAtMs":1790295608443}} {"type":"emit_inbound","label":"thread/settings/updated","frame":{"method":"thread/settings/updated","params":{"threadId":"01a0d5ef-0ba3-7552-b090-7cfbb328e278","threadSettings":{"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","approvalPolicy":"never","approvalsReviewer":"user","sandboxPolicy":{"type":"readOnly","networkAccess":false},"activePermissionProfile":null,"model":"gpt-6-luna","modelProvider":"openai","serviceTier":null,"effort":"medium","summary":"detailed","collaborationMode":{"mode":"plan","settings":{"model":"gpt-6-luna","reasoning_effort":"medium","developer_instructions":"You are in Plan mode. Prefer request_user_input for clarifying questions. When presenting a complete plan, wrap it in and ."}},"multiAgentMode":"explicitRequestOnly","personality":null}},"emittedAtMs":1790295608464}} -{"type":"emit_inbound","label":"turn/start","frame":{"id":5,"result":{"turn":{"id":"01a0d5ef-0c85-7f41-ad02-13753158be02","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} +{"type":"emit_inbound","label":"turn/start","frame":{"id":6,"result":{"turn":{"id":"01a0d5ef-0c85-7f41-ad02-13753158be02","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d5ef-0ba3-7552-b090-7cfbb328e278","status":{"type":"active","activeFlags":[]}},"emittedAtMs":1790295608547}} {"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"01a0d5ef-0ba3-7552-b090-7cfbb328e278","turn":{"id":"01a0d5ef-0c85-7f41-ad02-13753158be02","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1790295608,"completedAt":null,"durationMs":null}},"emittedAtMs":1790295608548}} {"type":"emit_inbound","label":"account/updated","frame":{"method":"account/updated","params":{"authMode":"chatgpt","planType":"unknown"},"emittedAtMs":1790295608936}} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/provider_thread_resume/codex_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/provider_thread_resume/codex_transcript.ndjson index 38a7a83c45fc5..46da729181c58 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/provider_thread_resume/codex_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/provider_thread_resume/codex_transcript.ndjson @@ -2,20 +2,22 @@ {"type":"expect_outbound","label":"initialize","frame":{"id":1,"method":"initialize","params":{"capabilities":{"experimentalApi":true,"optOutNotificationMethods":["turn/diff/updated"],"extensions":{"io.modelcontextprotocol/ui":{"mimeTypes":["text/html;profile=mcp-app"]}}},"clientInfo":{"name":"T3 Code","title":"T3 Code","version":"0.0.44"}}}} {"type":"emit_inbound","label":"initialize","frame":{"id":1,"result":{"userAgent":"t3code_desktop/0.156.1 (Debian 13.0.0; x86_64) unknown (t3code_desktop; 0.1.0)","codexHome":"/home/replay-user/.codex","platformFamily":"unix","platformOs":"linux"}}} {"type":"expect_outbound","label":"initialized","frame":{"method":"initialized"}} -{"type":"expect_outbound","label":"thread/start","frame":{"id":2,"method":"thread/start","params":{"config":{"tools.update_plan.enabled":true,"mcp_optional_startup_grace_ms":10000,"features.concurrent_reasoning_summaries":true},"cwd":"","model":"gpt-6-luna"}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":2,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":2,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"thread/start","frame":{"id":3,"method":"thread/start","params":{"config":{"tools.update_plan.enabled":true,"mcp_optional_startup_grace_ms":10000,"features.concurrent_reasoning_summaries":true},"cwd":"","model":"gpt-6-luna"}}} {"type":"emit_inbound","label":"configWarning","frame":{"method":"configWarning","params":{"summary":"Codex could not find bubblewrap on PATH. Install bubblewrap with your OS package manager. See the sandbox prerequisites: https://developers.openai.com/codex/concepts/sandboxing#prerequisites. Codex will use the bundled bubblewrap in the meantime.","details":null},"emittedAtMs":1790295630509}} {"type":"emit_inbound","label":"remoteControl/status/changed","frame":{"method":"remoteControl/status/changed","params":{"status":"disabled","serverName":"replay-host","installationId":"00000000-0000-4000-8000-000000000000","environmentId":null},"emittedAtMs":1790295630509}} -{"type":"emit_inbound","label":"thread/start","frame":{"id":2,"result":{"thread":{"id":"01a0d5ef-62bd-7c20-861b-0528ff7d86bd","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d5ef-62bd-7c20-861b-0528ff7d86bd","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790295630,"updatedAt":1790295630,"recencyAt":1790295630,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-20-30-01a0d5ef-62bd-7c20-861b-0528ff7d86bd.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]},"model":"gpt-6-luna","modelProvider":"openai","serviceTier":null,"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"],"instructionSources":["/home/replay-user/.codex/AGENTS.md","/home/replay-user/t3code/AGENTS.md"],"approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":{"id":":workspace","extends":null},"reasoningEffort":null,"multiAgentMode":"explicitRequestOnly"}}} -{"type":"expect_outbound","label":"thread/name/set","frame":{"id":3,"method":"thread/name/set","params":{"name":"Replay fixture: provider_thread_resume","threadId":"01a0d5ef-62bd-7c20-861b-0528ff7d86bd"}}} -{"type":"emit_inbound","label":"thread/name/set","frame":{"id":3,"result":{}}} +{"type":"emit_inbound","label":"thread/start","frame":{"id":3,"result":{"thread":{"id":"01a0d5ef-62bd-7c20-861b-0528ff7d86bd","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d5ef-62bd-7c20-861b-0528ff7d86bd","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790295630,"updatedAt":1790295630,"recencyAt":1790295630,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-20-30-01a0d5ef-62bd-7c20-861b-0528ff7d86bd.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]},"model":"gpt-6-luna","modelProvider":"openai","serviceTier":null,"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"],"instructionSources":["/home/replay-user/.codex/AGENTS.md","/home/replay-user/t3code/AGENTS.md"],"approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":{"id":":workspace","extends":null},"reasoningEffort":null,"multiAgentMode":"explicitRequestOnly"}}} +{"type":"expect_outbound","label":"thread/name/set","frame":{"id":4,"method":"thread/name/set","params":{"name":"Replay fixture: provider_thread_resume","threadId":"01a0d5ef-62bd-7c20-861b-0528ff7d86bd"}}} +{"type":"emit_inbound","label":"thread/name/set","frame":{"id":4,"result":{}}} {"type":"emit_inbound","label":"thread/name/updated","frame":{"method":"thread/name/updated","params":{"threadId":"01a0d5ef-62bd-7c20-861b-0528ff7d86bd","threadName":"Replay fixture: provider_thread_resume"}}} -{"type":"expect_outbound","label":"config/read","frame":{"id":4,"method":"config/read","params":{"cwd":"","includeLayers":false}}} -{"type":"emit_inbound","label":"config/read","frame":{"id":4,"result":{"config":{},"origins":{}}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":5,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Respond with exactly: provider thread resume fixture first turn complete","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"auto","threadId":"01a0d5ef-62bd-7c20-861b-0528ff7d86bd","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":5,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":5,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":6,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Respond with exactly: provider thread resume fixture first turn complete","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"auto","threadId":"01a0d5ef-62bd-7c20-861b-0528ff7d86bd","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0d5ef-62bd-7c20-861b-0528ff7d86bd","name":"codex_apps","status":"starting","error":null,"failureReason":null},"emittedAtMs":1790295630711}} {"type":"emit_inbound","label":"thread/started","frame":{"method":"thread/started","params":{"thread":{"id":"01a0d5ef-62bd-7c20-861b-0528ff7d86bd","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d5ef-62bd-7c20-861b-0528ff7d86bd","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790295630,"updatedAt":1790295630,"recencyAt":1790295630,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-20-30-01a0d5ef-62bd-7c20-861b-0528ff7d86bd.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]}},"emittedAtMs":1790295630711}} {"type":"emit_inbound","label":"thread/settings/updated","frame":{"method":"thread/settings/updated","params":{"threadId":"01a0d5ef-62bd-7c20-861b-0528ff7d86bd","threadSettings":{"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","approvalPolicy":"never","approvalsReviewer":"user","sandboxPolicy":{"type":"dangerFullAccess"},"activePermissionProfile":null,"model":"gpt-6-luna","modelProvider":"openai","serviceTier":null,"effort":null,"summary":"detailed","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna","reasoning_effort":null,"developer_instructions":null}},"multiAgentMode":"explicitRequestOnly","personality":null}},"emittedAtMs":1790295630725}} -{"type":"emit_inbound","label":"turn/start","frame":{"id":5,"result":{"turn":{"id":"01a0d5ef-637e-7ba2-bf9a-5534a6f98a83","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} +{"type":"emit_inbound","label":"turn/start","frame":{"id":6,"result":{"turn":{"id":"01a0d5ef-637e-7ba2-bf9a-5534a6f98a83","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d5ef-62bd-7c20-861b-0528ff7d86bd","status":{"type":"active","activeFlags":[]}},"emittedAtMs":1790295630781}} {"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"01a0d5ef-62bd-7c20-861b-0528ff7d86bd","turn":{"id":"01a0d5ef-637e-7ba2-bf9a-5534a6f98a83","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1790295630,"completedAt":null,"durationMs":null}},"emittedAtMs":1790295630781}} {"type":"emit_inbound","label":"account/updated","frame":{"method":"account/updated","params":{"authMode":"chatgpt","planType":"unknown"},"emittedAtMs":1790295631109}} @@ -40,22 +42,24 @@ {"type":"expect_outbound","label":"initialize","frame":{"id":1,"method":"initialize","params":{"capabilities":{"experimentalApi":true,"optOutNotificationMethods":["turn/diff/updated"],"extensions":{"io.modelcontextprotocol/ui":{"mimeTypes":["text/html;profile=mcp-app"]}}},"clientInfo":{"name":"T3 Code","title":"T3 Code","version":"0.0.44"}}}} {"type":"emit_inbound","label":"initialize","frame":{"id":1,"result":{"userAgent":"t3code_desktop/0.156.1 (Debian 13.0.0; x86_64) unknown (t3code_desktop; 0.1.0)","codexHome":"/home/replay-user/.codex","platformFamily":"unix","platformOs":"linux"}}} {"type":"expect_outbound","label":"initialized","frame":{"method":"initialized"}} -{"type":"expect_outbound","label":"thread/resume","frame":{"id":2,"method":"thread/resume","params":{"config":{"tools.update_plan.enabled":true,"mcp_optional_startup_grace_ms":10000,"features.concurrent_reasoning_summaries":true},"cwd":"","excludeTurns":true,"model":"gpt-6-luna","threadId":"01a0d5ef-62bd-7c20-861b-0528ff7d86bd"}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":2,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":2,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"thread/resume","frame":{"id":3,"method":"thread/resume","params":{"config":{"tools.update_plan.enabled":true,"mcp_optional_startup_grace_ms":10000,"features.concurrent_reasoning_summaries":true},"cwd":"","excludeTurns":true,"model":"gpt-6-luna","threadId":"01a0d5ef-62bd-7c20-861b-0528ff7d86bd"}}} {"type":"emit_inbound","label":"configWarning","frame":{"method":"configWarning","params":{"summary":"Codex could not find bubblewrap on PATH. Install bubblewrap with your OS package manager. See the sandbox prerequisites: https://developers.openai.com/codex/concepts/sandboxing#prerequisites. Codex will use the bundled bubblewrap in the meantime.","details":null},"emittedAtMs":1790295635636}} {"type":"emit_inbound","label":"remoteControl/status/changed","frame":{"method":"remoteControl/status/changed","params":{"status":"disabled","serverName":"replay-host","installationId":"00000000-0000-4000-8000-000000000000","environmentId":null},"emittedAtMs":1790295635636}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0d5ef-62bd-7c20-861b-0528ff7d86bd","name":"codex_apps","status":"starting","error":null,"failureReason":null},"emittedAtMs":1790295635910}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d5ef-62bd-7c20-861b-0528ff7d86bd","status":{"type":"idle"}},"emittedAtMs":1790295635918}} -{"type":"emit_inbound","label":"thread/resume","frame":{"id":2,"result":{"thread":{"id":"01a0d5ef-62bd-7c20-861b-0528ff7d86bd","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d5ef-62bd-7c20-861b-0528ff7d86bd","forkedFromId":null,"parentThreadId":null,"preview":"Respond with exactly: provider thread resume fixture first turn complete","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790295630,"updatedAt":1790295635,"recencyAt":1790295630,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-20-30-01a0d5ef-62bd-7c20-861b-0528ff7d86bd.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":{"sha":"1563a64b41d5e7e2e640b46f52cee724913f8851","branch":"v2/codex-gpt6-luna-rerecord","originUrl":"https://github.com/pingdotgg/t3code.git"},"name":null,"daybreakEnabled":null,"turns":[]},"model":"gpt-6-luna","modelProvider":"openai","serviceTier":null,"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"],"instructionSources":["/home/replay-user/.codex/AGENTS.md","/home/replay-user/t3code/AGENTS.md"],"approvalPolicy":"never","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":{"id":":workspace","extends":null},"reasoningEffort":null,"collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna","reasoning_effort":null,"developer_instructions":null}},"multiAgentMode":"explicitRequestOnly","initialTurnsPage":null,"turnsBackwardsCursor":"{\"requestedThreadId\":\"01a0d5ef-62bd-7c20-861b-0528ff7d86bd\",\"rolloutOrdinal\":1,\"includeAnchor\":true,\"scope\":{\"kind\":\"turns\"}}","itemsBackwardsCursor":"{\"requestedThreadId\":\"01a0d5ef-62bd-7c20-861b-0528ff7d86bd\",\"rolloutOrdinal\":10,\"includeAnchor\":true,\"scope\":{\"kind\":\"itemsByCreatedAtOrdinal\"}}"}}} -{"type":"expect_outbound","label":"thread/name/set","frame":{"id":3,"method":"thread/name/set","params":{"name":"Replay fixture: provider_thread_resume","threadId":"01a0d5ef-62bd-7c20-861b-0528ff7d86bd"}}} -{"type":"emit_inbound","label":"thread/name/set","frame":{"id":3,"result":{}}} +{"type":"emit_inbound","label":"thread/resume","frame":{"id":3,"result":{"thread":{"id":"01a0d5ef-62bd-7c20-861b-0528ff7d86bd","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d5ef-62bd-7c20-861b-0528ff7d86bd","forkedFromId":null,"parentThreadId":null,"preview":"Respond with exactly: provider thread resume fixture first turn complete","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790295630,"updatedAt":1790295635,"recencyAt":1790295630,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-20-30-01a0d5ef-62bd-7c20-861b-0528ff7d86bd.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":{"sha":"1563a64b41d5e7e2e640b46f52cee724913f8851","branch":"v2/codex-gpt6-luna-rerecord","originUrl":"https://github.com/pingdotgg/t3code.git"},"name":null,"daybreakEnabled":null,"turns":[]},"model":"gpt-6-luna","modelProvider":"openai","serviceTier":null,"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"],"instructionSources":["/home/replay-user/.codex/AGENTS.md","/home/replay-user/t3code/AGENTS.md"],"approvalPolicy":"never","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":{"id":":workspace","extends":null},"reasoningEffort":null,"collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna","reasoning_effort":null,"developer_instructions":null}},"multiAgentMode":"explicitRequestOnly","initialTurnsPage":null,"turnsBackwardsCursor":"{\"requestedThreadId\":\"01a0d5ef-62bd-7c20-861b-0528ff7d86bd\",\"rolloutOrdinal\":1,\"includeAnchor\":true,\"scope\":{\"kind\":\"turns\"}}","itemsBackwardsCursor":"{\"requestedThreadId\":\"01a0d5ef-62bd-7c20-861b-0528ff7d86bd\",\"rolloutOrdinal\":10,\"includeAnchor\":true,\"scope\":{\"kind\":\"itemsByCreatedAtOrdinal\"}}"}}} +{"type":"expect_outbound","label":"thread/name/set","frame":{"id":4,"method":"thread/name/set","params":{"name":"Replay fixture: provider_thread_resume","threadId":"01a0d5ef-62bd-7c20-861b-0528ff7d86bd"}}} +{"type":"emit_inbound","label":"thread/name/set","frame":{"id":4,"result":{}}} {"type":"emit_inbound","label":"thread/name/updated","frame":{"method":"thread/name/updated","params":{"threadId":"01a0d5ef-62bd-7c20-861b-0528ff7d86bd","threadName":"Replay fixture: provider_thread_resume"}}} -{"type":"expect_outbound","label":"config/read","frame":{"id":4,"method":"config/read","params":{"cwd":"","includeLayers":false}}} -{"type":"emit_inbound","label":"config/read","frame":{"id":4,"result":{"config":{},"origins":{}}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":5,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Using the conversation history available in this resumed thread, first repeat the exact final answer you gave in the previous turn. Then on a new line write exactly: provider thread resume fixture second turn complete","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"auto","threadId":"01a0d5ef-62bd-7c20-861b-0528ff7d86bd","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":5,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":5,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":6,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Using the conversation history available in this resumed thread, first repeat the exact final answer you gave in the previous turn. Then on a new line write exactly: provider thread resume fixture second turn complete","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"auto","threadId":"01a0d5ef-62bd-7c20-861b-0528ff7d86bd","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} {"type":"emit_inbound","label":"thread/tokenUsage/updated","frame":{"method":"thread/tokenUsage/updated","params":{"threadId":"01a0d5ef-62bd-7c20-861b-0528ff7d86bd","turnId":"01a0d5ef-637e-7ba2-bf9a-5534a6f98a83","tokenUsage":{"total":{"totalTokens":21432,"inputTokens":21421,"cachedInputTokens":21248,"cacheWriteInputTokens":0,"outputTokens":11,"reasoningOutputTokens":0},"last":{"totalTokens":21432,"inputTokens":21421,"cachedInputTokens":21248,"cacheWriteInputTokens":0,"outputTokens":11,"reasoningOutputTokens":0},"modelContextWindow":258400}},"emittedAtMs":1790295635930}} {"type":"emit_inbound","label":"thread/goal/cleared","frame":{"method":"thread/goal/cleared","params":{"threadId":"01a0d5ef-62bd-7c20-861b-0528ff7d86bd"},"emittedAtMs":1790295635930}} {"type":"emit_inbound","label":"thread/settings/updated","frame":{"method":"thread/settings/updated","params":{"threadId":"01a0d5ef-62bd-7c20-861b-0528ff7d86bd","threadSettings":{"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","approvalPolicy":"never","approvalsReviewer":"user","sandboxPolicy":{"type":"dangerFullAccess"},"activePermissionProfile":null,"model":"gpt-6-luna","modelProvider":"openai","serviceTier":null,"effort":null,"summary":"detailed","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna","reasoning_effort":null,"developer_instructions":null}},"multiAgentMode":"explicitRequestOnly","personality":null}},"emittedAtMs":1790295635949}} -{"type":"emit_inbound","label":"turn/start","frame":{"id":5,"result":{"turn":{"id":"01a0d5ef-77e2-7e22-a198-4864f687b8b5","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} +{"type":"emit_inbound","label":"turn/start","frame":{"id":6,"result":{"turn":{"id":"01a0d5ef-77e2-7e22-a198-4864f687b8b5","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d5ef-62bd-7c20-861b-0528ff7d86bd","status":{"type":"active","activeFlags":[]}},"emittedAtMs":1790295635967}} {"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"01a0d5ef-62bd-7c20-861b-0528ff7d86bd","turn":{"id":"01a0d5ef-77e2-7e22-a198-4864f687b8b5","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1790295635,"completedAt":null,"durationMs":null}},"emittedAtMs":1790295635967}} {"type":"emit_inbound","label":"account/updated","frame":{"method":"account/updated","params":{"authMode":"chatgpt","planType":"unknown"},"emittedAtMs":1790295636362}} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/queued_turn/codex_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/queued_turn/codex_transcript.ndjson index 8dc7109ff264c..052b27087784b 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/queued_turn/codex_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/queued_turn/codex_transcript.ndjson @@ -2,20 +2,22 @@ {"type":"expect_outbound","label":"initialize","frame":{"id":1,"method":"initialize","params":{"capabilities":{"experimentalApi":true,"optOutNotificationMethods":["turn/diff/updated"],"extensions":{"io.modelcontextprotocol/ui":{"mimeTypes":["text/html;profile=mcp-app"]}}},"clientInfo":{"name":"T3 Code","title":"T3 Code","version":"0.0.44"}}}} {"type":"emit_inbound","label":"initialize","frame":{"id":1,"result":{"userAgent":"t3code_desktop/0.156.1 (Debian 13.0.0; x86_64) unknown (t3code_desktop; 0.1.0)","codexHome":"/home/replay-user/.codex","platformFamily":"unix","platformOs":"linux"}}} {"type":"expect_outbound","label":"initialized","frame":{"method":"initialized"}} -{"type":"expect_outbound","label":"thread/start","frame":{"id":2,"method":"thread/start","params":{"config":{"tools.update_plan.enabled":true,"mcp_optional_startup_grace_ms":10000,"features.concurrent_reasoning_summaries":true},"cwd":"","model":"gpt-6-luna"}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":2,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":2,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"thread/start","frame":{"id":3,"method":"thread/start","params":{"config":{"tools.update_plan.enabled":true,"mcp_optional_startup_grace_ms":10000,"features.concurrent_reasoning_summaries":true},"cwd":"","model":"gpt-6-luna"}}} {"type":"emit_inbound","label":"configWarning","frame":{"method":"configWarning","params":{"summary":"Codex could not find bubblewrap on PATH. Install bubblewrap with your OS package manager. See the sandbox prerequisites: https://developers.openai.com/codex/concepts/sandboxing#prerequisites. Codex will use the bundled bubblewrap in the meantime.","details":null},"emittedAtMs":1790295489278}} {"type":"emit_inbound","label":"remoteControl/status/changed","frame":{"method":"remoteControl/status/changed","params":{"status":"disabled","serverName":"replay-host","installationId":"00000000-0000-4000-8000-000000000000","environmentId":null},"emittedAtMs":1790295489278}} -{"type":"emit_inbound","label":"thread/start","frame":{"id":2,"result":{"thread":{"id":"01a0d5ed-3b1d-7b03-a1a3-075d3fa4bc67","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d5ed-3b1d-7b03-a1a3-075d3fa4bc67","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790295489,"updatedAt":1790295489,"recencyAt":1790295489,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-18-09-01a0d5ed-3b1d-7b03-a1a3-075d3fa4bc67.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]},"model":"gpt-6-luna","modelProvider":"openai","serviceTier":null,"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"],"instructionSources":["/home/replay-user/.codex/AGENTS.md","/home/replay-user/t3code/AGENTS.md"],"approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":{"id":":workspace","extends":null},"reasoningEffort":null,"multiAgentMode":"explicitRequestOnly"}}} -{"type":"expect_outbound","label":"thread/name/set","frame":{"id":3,"method":"thread/name/set","params":{"name":"Replay fixture: queued_turn","threadId":"01a0d5ed-3b1d-7b03-a1a3-075d3fa4bc67"}}} -{"type":"emit_inbound","label":"thread/name/set","frame":{"id":3,"result":{}}} +{"type":"emit_inbound","label":"thread/start","frame":{"id":3,"result":{"thread":{"id":"01a0d5ed-3b1d-7b03-a1a3-075d3fa4bc67","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d5ed-3b1d-7b03-a1a3-075d3fa4bc67","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790295489,"updatedAt":1790295489,"recencyAt":1790295489,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-18-09-01a0d5ed-3b1d-7b03-a1a3-075d3fa4bc67.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]},"model":"gpt-6-luna","modelProvider":"openai","serviceTier":null,"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"],"instructionSources":["/home/replay-user/.codex/AGENTS.md","/home/replay-user/t3code/AGENTS.md"],"approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":{"id":":workspace","extends":null},"reasoningEffort":null,"multiAgentMode":"explicitRequestOnly"}}} +{"type":"expect_outbound","label":"thread/name/set","frame":{"id":4,"method":"thread/name/set","params":{"name":"Replay fixture: queued_turn","threadId":"01a0d5ed-3b1d-7b03-a1a3-075d3fa4bc67"}}} +{"type":"emit_inbound","label":"thread/name/set","frame":{"id":4,"result":{}}} {"type":"emit_inbound","label":"thread/name/updated","frame":{"method":"thread/name/updated","params":{"threadId":"01a0d5ed-3b1d-7b03-a1a3-075d3fa4bc67","threadName":"Replay fixture: queued_turn"}}} -{"type":"expect_outbound","label":"config/read","frame":{"id":4,"method":"config/read","params":{"cwd":"","includeLayers":false}}} -{"type":"emit_inbound","label":"config/read","frame":{"id":4,"result":{"config":{},"origins":{}}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":5,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Respond with exactly: first fixture turn complete","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"auto","threadId":"01a0d5ed-3b1d-7b03-a1a3-075d3fa4bc67","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":5,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":5,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":6,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Respond with exactly: first fixture turn complete","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"auto","threadId":"01a0d5ed-3b1d-7b03-a1a3-075d3fa4bc67","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} {"type":"emit_inbound","label":"thread/started","frame":{"method":"thread/started","params":{"thread":{"id":"01a0d5ed-3b1d-7b03-a1a3-075d3fa4bc67","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d5ed-3b1d-7b03-a1a3-075d3fa4bc67","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790295489,"updatedAt":1790295489,"recencyAt":1790295489,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-18-09-01a0d5ed-3b1d-7b03-a1a3-075d3fa4bc67.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]}},"emittedAtMs":1790295489585}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0d5ed-3b1d-7b03-a1a3-075d3fa4bc67","name":"codex_apps","status":"starting","error":null,"failureReason":null},"emittedAtMs":1790295489585}} {"type":"emit_inbound","label":"thread/settings/updated","frame":{"method":"thread/settings/updated","params":{"threadId":"01a0d5ed-3b1d-7b03-a1a3-075d3fa4bc67","threadSettings":{"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","approvalPolicy":"never","approvalsReviewer":"user","sandboxPolicy":{"type":"dangerFullAccess"},"activePermissionProfile":null,"model":"gpt-6-luna","modelProvider":"openai","serviceTier":null,"effort":null,"summary":"detailed","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna","reasoning_effort":null,"developer_instructions":null}},"multiAgentMode":"explicitRequestOnly","personality":null}},"emittedAtMs":1790295489600}} -{"type":"emit_inbound","label":"turn/start","frame":{"id":5,"result":{"turn":{"id":"01a0d5ed-3c38-77a3-ab7d-7b1af28c714e","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} +{"type":"emit_inbound","label":"turn/start","frame":{"id":6,"result":{"turn":{"id":"01a0d5ed-3c38-77a3-ab7d-7b1af28c714e","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d5ed-3b1d-7b03-a1a3-075d3fa4bc67","status":{"type":"active","activeFlags":[]}},"emittedAtMs":1790295489653}} {"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"01a0d5ed-3b1d-7b03-a1a3-075d3fa4bc67","turn":{"id":"01a0d5ed-3c38-77a3-ab7d-7b1af28c714e","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1790295489,"completedAt":null,"durationMs":null}},"emittedAtMs":1790295489653}} {"type":"emit_inbound","label":"account/updated","frame":{"method":"account/updated","params":{"authMode":"chatgpt","planType":"unknown"},"emittedAtMs":1790295490048}} @@ -33,10 +35,10 @@ {"type":"emit_inbound","label":"thread/tokenUsage/updated","frame":{"method":"thread/tokenUsage/updated","params":{"threadId":"01a0d5ed-3b1d-7b03-a1a3-075d3fa4bc67","turnId":"01a0d5ed-3c38-77a3-ab7d-7b1af28c714e","tokenUsage":{"total":{"totalTokens":21426,"inputTokens":21418,"cachedInputTokens":11008,"cacheWriteInputTokens":0,"outputTokens":8,"reasoningOutputTokens":0},"last":{"totalTokens":21426,"inputTokens":21418,"cachedInputTokens":11008,"cacheWriteInputTokens":0,"outputTokens":8,"reasoningOutputTokens":0},"modelContextWindow":258400}},"emittedAtMs":1790295494469}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d5ed-3b1d-7b03-a1a3-075d3fa4bc67","status":{"type":"idle"}},"emittedAtMs":1790295494492}} {"type":"emit_inbound","label":"turn/completed","frame":{"method":"turn/completed","params":{"threadId":"01a0d5ed-3b1d-7b03-a1a3-075d3fa4bc67","turn":{"id":"01a0d5ed-3c38-77a3-ab7d-7b1af28c714e","items":[{"type":"agentMessage","id":"msg_0e736caa8e522655016ab5bdc6199487d097782bddce2cbb65","text":"first fixture turn complete","phase":"final_answer","memoryCitation":null,"delivery":null,"questions":null}],"itemsView":"summary","status":"completed","error":null,"startedAt":1790295489,"completedAt":1790295494,"durationMs":4885}},"emittedAtMs":1790295494492}} -{"type":"expect_outbound","label":"config/read","frame":{"id":6,"method":"config/read","params":{"cwd":"","includeLayers":false}}} -{"type":"emit_inbound","label":"config/read","frame":{"id":6,"result":{"config":{},"origins":{}}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":7,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Respond with exactly: second fixture turn complete","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"auto","threadId":"01a0d5ed-3b1d-7b03-a1a3-075d3fa4bc67","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} -{"type":"emit_inbound","label":"turn/start","frame":{"id":7,"result":{"turn":{"id":"01a0d5ed-4f65-7182-8985-cb9fba86acad","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":7,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":7,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":8,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Respond with exactly: second fixture turn complete","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"auto","threadId":"01a0d5ed-3b1d-7b03-a1a3-075d3fa4bc67","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} +{"type":"emit_inbound","label":"turn/start","frame":{"id":8,"result":{"turn":{"id":"01a0d5ed-4f65-7182-8985-cb9fba86acad","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d5ed-3b1d-7b03-a1a3-075d3fa4bc67","status":{"type":"active","activeFlags":[]}},"emittedAtMs":1790295494545}} {"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"01a0d5ed-3b1d-7b03-a1a3-075d3fa4bc67","turn":{"id":"01a0d5ed-4f65-7182-8985-cb9fba86acad","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1790295494,"completedAt":null,"durationMs":null}},"emittedAtMs":1790295494545}} {"type":"emit_inbound","label":"item/started","frame":{"method":"item/started","params":{"item":{"type":"userMessage","id":"01a0d5ed-5011-74c1-aa40-36a1a7a1a79c","clientId":null,"content":[{"type":"text","text":"Respond with exactly: second fixture turn complete","text_elements":[]}]},"threadId":"01a0d5ed-3b1d-7b03-a1a3-075d3fa4bc67","turnId":"01a0d5ed-4f65-7182-8985-cb9fba86acad","startedAtMs":1790295494685},"emittedAtMs":1790295494685}} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/simple/codex_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/simple/codex_transcript.ndjson index 2663074270d55..a5d43930ee4ba 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/simple/codex_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/simple/codex_transcript.ndjson @@ -2,22 +2,24 @@ {"type":"expect_outbound","label":"initialize","frame":{"id":1,"method":"initialize","params":{"capabilities":{"experimentalApi":true,"optOutNotificationMethods":["turn/diff/updated"],"extensions":{"io.modelcontextprotocol/ui":{"mimeTypes":["text/html;profile=mcp-app"]}}},"clientInfo":{"name":"T3 Code","title":"T3 Code","version":"0.0.44"}}}} {"type":"emit_inbound","label":"initialize","frame":{"id":1,"result":{"userAgent":"t3code_desktop/0.156.1 (Debian 13.0.0; x86_64) unknown (t3code_desktop; 0.1.0)","codexHome":"/home/replay-user/.codex","platformFamily":"unix","platformOs":"linux"}}} {"type":"expect_outbound","label":"initialized","frame":{"method":"initialized"}} -{"type":"expect_outbound","label":"thread/start","frame":{"id":2,"method":"thread/start","params":{"config":{"tools.update_plan.enabled":true,"mcp_optional_startup_grace_ms":10000,"features.concurrent_reasoning_summaries":true},"cwd":"","model":"gpt-6-luna"}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":2,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":2,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"thread/start","frame":{"id":3,"method":"thread/start","params":{"config":{"tools.update_plan.enabled":true,"mcp_optional_startup_grace_ms":10000,"features.concurrent_reasoning_summaries":true},"cwd":"","model":"gpt-6-luna"}}} {"type":"emit_inbound","label":"configWarning","frame":{"method":"configWarning","params":{"summary":"Codex could not find bubblewrap on PATH. Install bubblewrap with your OS package manager. See the sandbox prerequisites: https://developers.openai.com/codex/concepts/sandboxing#prerequisites. Codex will use the bundled bubblewrap in the meantime.","details":null},"emittedAtMs":1790295403441}} {"type":"emit_inbound","label":"remoteControl/status/changed","frame":{"method":"remoteControl/status/changed","params":{"status":"disabled","serverName":"replay-host","installationId":"00000000-0000-4000-8000-000000000000","environmentId":null},"emittedAtMs":1790295403441}} {"type":"emit_inbound","label":"account/updated","frame":{"method":"account/updated","params":{"authMode":"chatgpt","planType":"unknown"},"emittedAtMs":1790295404347}} -{"type":"emit_inbound","label":"thread/start","frame":{"id":2,"result":{"thread":{"id":"01a0d5eb-f0c0-7481-a417-5e8871805cbc","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d5eb-f0c0-7481-a417-5e8871805cbc","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790295404,"updatedAt":1790295404,"recencyAt":1790295404,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-16-44-01a0d5eb-f0c0-7481-a417-5e8871805cbc.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]},"model":"gpt-6-luna","modelProvider":"openai","serviceTier":null,"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"],"instructionSources":["/home/replay-user/.codex/AGENTS.md","/home/replay-user/t3code/AGENTS.md"],"approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":{"id":":workspace","extends":null},"reasoningEffort":null,"multiAgentMode":"explicitRequestOnly"}}} -{"type":"expect_outbound","label":"thread/name/set","frame":{"id":3,"method":"thread/name/set","params":{"name":"Replay fixture: simple","threadId":"01a0d5eb-f0c0-7481-a417-5e8871805cbc"}}} -{"type":"emit_inbound","label":"thread/name/set","frame":{"id":3,"result":{}}} +{"type":"emit_inbound","label":"thread/start","frame":{"id":3,"result":{"thread":{"id":"01a0d5eb-f0c0-7481-a417-5e8871805cbc","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d5eb-f0c0-7481-a417-5e8871805cbc","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790295404,"updatedAt":1790295404,"recencyAt":1790295404,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-16-44-01a0d5eb-f0c0-7481-a417-5e8871805cbc.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]},"model":"gpt-6-luna","modelProvider":"openai","serviceTier":null,"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"],"instructionSources":["/home/replay-user/.codex/AGENTS.md","/home/replay-user/t3code/AGENTS.md"],"approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":{"id":":workspace","extends":null},"reasoningEffort":null,"multiAgentMode":"explicitRequestOnly"}}} +{"type":"expect_outbound","label":"thread/name/set","frame":{"id":4,"method":"thread/name/set","params":{"name":"Replay fixture: simple","threadId":"01a0d5eb-f0c0-7481-a417-5e8871805cbc"}}} +{"type":"emit_inbound","label":"thread/name/set","frame":{"id":4,"result":{}}} {"type":"emit_inbound","label":"thread/name/updated","frame":{"method":"thread/name/updated","params":{"threadId":"01a0d5eb-f0c0-7481-a417-5e8871805cbc","threadName":"Replay fixture: simple"}}} -{"type":"expect_outbound","label":"config/read","frame":{"id":4,"method":"config/read","params":{"cwd":"","includeLayers":false}}} -{"type":"emit_inbound","label":"config/read","frame":{"id":4,"result":{"config":{},"origins":{}}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":5,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Respond with the following text: fixture simple ok","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"auto","threadId":"01a0d5eb-f0c0-7481-a417-5e8871805cbc","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":5,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":5,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":6,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Respond with the following text: fixture simple ok","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"auto","threadId":"01a0d5eb-f0c0-7481-a417-5e8871805cbc","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} {"type":"emit_inbound","label":"thread/started","frame":{"method":"thread/started","params":{"thread":{"id":"01a0d5eb-f0c0-7481-a417-5e8871805cbc","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d5eb-f0c0-7481-a417-5e8871805cbc","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790295404,"updatedAt":1790295404,"recencyAt":1790295404,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-16-44-01a0d5eb-f0c0-7481-a417-5e8871805cbc.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]}},"emittedAtMs":1790295404904}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0d5eb-f0c0-7481-a417-5e8871805cbc","name":"xcodebuildmcp","status":"starting","error":null,"failureReason":null},"emittedAtMs":1790295404904}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0d5eb-f0c0-7481-a417-5e8871805cbc","name":"codex_apps","status":"starting","error":null,"failureReason":null},"emittedAtMs":1790295404904}} {"type":"emit_inbound","label":"thread/settings/updated","frame":{"method":"thread/settings/updated","params":{"threadId":"01a0d5eb-f0c0-7481-a417-5e8871805cbc","threadSettings":{"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","approvalPolicy":"never","approvalsReviewer":"user","sandboxPolicy":{"type":"dangerFullAccess"},"activePermissionProfile":null,"model":"gpt-6-luna","modelProvider":"openai","serviceTier":null,"effort":null,"summary":"detailed","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna","reasoning_effort":null,"developer_instructions":null}},"multiAgentMode":"explicitRequestOnly","personality":null}},"emittedAtMs":1790295404923}} -{"type":"emit_inbound","label":"turn/start","frame":{"id":5,"result":{"turn":{"id":"01a0d5eb-f176-71d0-8e1c-a459700443de","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} +{"type":"emit_inbound","label":"turn/start","frame":{"id":6,"result":{"turn":{"id":"01a0d5eb-f176-71d0-8e1c-a459700443de","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d5eb-f0c0-7481-a417-5e8871805cbc","status":{"type":"active","activeFlags":[]}},"emittedAtMs":1790295404965}} {"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"01a0d5eb-f0c0-7481-a417-5e8871805cbc","turn":{"id":"01a0d5eb-f176-71d0-8e1c-a459700443de","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1790295404,"completedAt":null,"durationMs":null}},"emittedAtMs":1790295404965}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0d5eb-f0c0-7481-a417-5e8871805cbc","name":"codex_apps","status":"ready","error":null,"failureReason":null},"emittedAtMs":1790295405685}} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/subagent/codex_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/subagent/codex_transcript.ndjson index 9255c2572ac51..355c40ef407eb 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/subagent/codex_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/subagent/codex_transcript.ndjson @@ -2,21 +2,23 @@ {"type":"expect_outbound","label":"initialize","frame":{"id":1,"method":"initialize","params":{"capabilities":{"experimentalApi":true,"optOutNotificationMethods":["turn/diff/updated"],"extensions":{"io.modelcontextprotocol/ui":{"mimeTypes":["text/html;profile=mcp-app"]}}},"clientInfo":{"name":"T3 Code","title":"T3 Code","version":"0.0.44"}}}} {"type":"emit_inbound","label":"initialize","frame":{"id":1,"result":{"userAgent":"t3code_desktop/0.156.1 (Debian 13.0.0; x86_64) unknown (t3code_desktop; 0.1.0)","codexHome":"/home/replay-user/.codex","platformFamily":"unix","platformOs":"linux"}}} {"type":"expect_outbound","label":"initialized","frame":{"method":"initialized"}} -{"type":"expect_outbound","label":"thread/start","frame":{"id":2,"method":"thread/start","params":{"config":{"tools.update_plan.enabled":true,"mcp_optional_startup_grace_ms":10000,"features.concurrent_reasoning_summaries":true,"skills.include_instructions":false},"cwd":"","model":"gpt-5.6-luna"}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":2,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":2,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"thread/start","frame":{"id":3,"method":"thread/start","params":{"config":{"tools.update_plan.enabled":true,"mcp_optional_startup_grace_ms":10000,"features.concurrent_reasoning_summaries":true,"skills.include_instructions":false},"cwd":"","model":"gpt-5.6-luna"}}} {"type":"emit_inbound","label":"configWarning","frame":{"method":"configWarning","params":{"summary":"Codex could not find bubblewrap on PATH. Install bubblewrap with your OS package manager. See the sandbox prerequisites: https://developers.openai.com/codex/concepts/sandboxing#prerequisites. Codex will use the bundled bubblewrap in the meantime.","details":null},"emittedAtMs":1790298236268}} {"type":"emit_inbound","label":"remoteControl/status/changed","frame":{"method":"remoteControl/status/changed","params":{"status":"disabled","serverName":"replay-host","installationId":"00000000-0000-4000-8000-000000000000","environmentId":null},"emittedAtMs":1790298236268}} {"type":"emit_inbound","label":"account/updated","frame":{"method":"account/updated","params":{"authMode":"chatgpt","planType":"unknown"},"emittedAtMs":1790298236941}} -{"type":"emit_inbound","label":"thread/start","frame":{"id":2,"result":{"thread":{"id":"01a0d617-2920-75e0-8957-ee5a48afefc4","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d617-2920-75e0-8957-ee5a48afefc4","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-5.6-luna","reasoningEffort":null,"createdAt":1790298237,"updatedAt":1790298237,"recencyAt":1790298237,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T18-03-57-01a0d617-2920-75e0-8957-ee5a48afefc4.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]},"model":"gpt-5.6-luna","modelProvider":"openai","serviceTier":null,"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"],"instructionSources":["/home/replay-user/.codex/AGENTS.md"],"approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":{"id":":workspace","extends":null},"reasoningEffort":null,"multiAgentMode":"explicitRequestOnly"}}} -{"type":"expect_outbound","label":"thread/name/set","frame":{"id":3,"method":"thread/name/set","params":{"name":"Replay fixture: subagent","threadId":"01a0d617-2920-75e0-8957-ee5a48afefc4"}}} -{"type":"emit_inbound","label":"thread/name/set","frame":{"id":3,"result":{}}} +{"type":"emit_inbound","label":"thread/start","frame":{"id":3,"result":{"thread":{"id":"01a0d617-2920-75e0-8957-ee5a48afefc4","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d617-2920-75e0-8957-ee5a48afefc4","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-5.6-luna","reasoningEffort":null,"createdAt":1790298237,"updatedAt":1790298237,"recencyAt":1790298237,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T18-03-57-01a0d617-2920-75e0-8957-ee5a48afefc4.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]},"model":"gpt-5.6-luna","modelProvider":"openai","serviceTier":null,"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"],"instructionSources":["/home/replay-user/.codex/AGENTS.md"],"approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":{"id":":workspace","extends":null},"reasoningEffort":null,"multiAgentMode":"explicitRequestOnly"}}} +{"type":"expect_outbound","label":"thread/name/set","frame":{"id":4,"method":"thread/name/set","params":{"name":"Replay fixture: subagent","threadId":"01a0d617-2920-75e0-8957-ee5a48afefc4"}}} +{"type":"emit_inbound","label":"thread/name/set","frame":{"id":4,"result":{}}} {"type":"emit_inbound","label":"thread/name/updated","frame":{"method":"thread/name/updated","params":{"threadId":"01a0d617-2920-75e0-8957-ee5a48afefc4","threadName":"Replay fixture: subagent"}}} -{"type":"expect_outbound","label":"config/read","frame":{"id":4,"method":"config/read","params":{"cwd":"","includeLayers":false}}} -{"type":"emit_inbound","label":"config/read","frame":{"id":4,"result":{"config":{},"origins":{}}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":5,"method":"turn/start","params":{"approvalPolicy":"on-request","approvalsReviewer":"user","cwd":"","input":[{"text":"Spawn 2 subagents, one to read package.json and one to read tsconfig.json","type":"text"}],"model":"gpt-5.6-luna","sandboxPolicy":{"networkAccess":false,"type":"readOnly"},"summary":"auto","threadId":"01a0d617-2920-75e0-8957-ee5a48afefc4","collaborationMode":{"mode":"default","settings":{"model":"gpt-5.6-luna"}}}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":5,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":5,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":6,"method":"turn/start","params":{"approvalPolicy":"on-request","approvalsReviewer":"user","cwd":"","input":[{"text":"Spawn 2 subagents, one to read package.json and one to read tsconfig.json","type":"text"}],"model":"gpt-5.6-luna","sandboxPolicy":{"networkAccess":false,"type":"readOnly"},"summary":"auto","threadId":"01a0d617-2920-75e0-8957-ee5a48afefc4","collaborationMode":{"mode":"default","settings":{"model":"gpt-5.6-luna"}}}}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0d617-2920-75e0-8957-ee5a48afefc4","name":"codex_apps","status":"starting","error":null,"failureReason":null},"emittedAtMs":1790298237401}} {"type":"emit_inbound","label":"thread/started","frame":{"method":"thread/started","params":{"thread":{"id":"01a0d617-2920-75e0-8957-ee5a48afefc4","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d617-2920-75e0-8957-ee5a48afefc4","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-5.6-luna","reasoningEffort":null,"createdAt":1790298237,"updatedAt":1790298237,"recencyAt":1790298237,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T18-03-57-01a0d617-2920-75e0-8957-ee5a48afefc4.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]}},"emittedAtMs":1790298237402}} {"type":"emit_inbound","label":"thread/settings/updated","frame":{"method":"thread/settings/updated","params":{"threadId":"01a0d617-2920-75e0-8957-ee5a48afefc4","threadSettings":{"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","approvalPolicy":"on-request","approvalsReviewer":"user","sandboxPolicy":{"type":"readOnly","networkAccess":false},"activePermissionProfile":null,"model":"gpt-5.6-luna","modelProvider":"openai","serviceTier":null,"effort":null,"summary":"detailed","collaborationMode":{"mode":"default","settings":{"model":"gpt-5.6-luna","reasoning_effort":null,"developer_instructions":null}},"multiAgentMode":"explicitRequestOnly","personality":null}},"emittedAtMs":1790298237414}} -{"type":"emit_inbound","label":"turn/start","frame":{"id":5,"result":{"turn":{"id":"01a0d617-29e0-73d3-a4fd-856238566501","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} +{"type":"emit_inbound","label":"turn/start","frame":{"id":6,"result":{"turn":{"id":"01a0d617-29e0-73d3-a4fd-856238566501","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d617-2920-75e0-8957-ee5a48afefc4","status":{"type":"active","activeFlags":[]}},"emittedAtMs":1790298237472}} {"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"01a0d617-2920-75e0-8957-ee5a48afefc4","turn":{"id":"01a0d617-29e0-73d3-a4fd-856238566501","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1790298237,"completedAt":null,"durationMs":null}},"emittedAtMs":1790298237472}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0d617-2920-75e0-8957-ee5a48afefc4","name":"xcodebuildmcp","status":"starting","error":null,"failureReason":null},"emittedAtMs":1790298237772}} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/subagent_continue/codex_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/subagent_continue/codex_transcript.ndjson index 4deb50c422bd1..4cfd0788bc0aa 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/subagent_continue/codex_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/subagent_continue/codex_transcript.ndjson @@ -2,20 +2,22 @@ {"type":"expect_outbound","label":"initialize","frame":{"id":1,"method":"initialize","params":{"capabilities":{"experimentalApi":true,"optOutNotificationMethods":["turn/diff/updated"],"extensions":{"io.modelcontextprotocol/ui":{"mimeTypes":["text/html;profile=mcp-app"]}}},"clientInfo":{"name":"T3 Code","title":"T3 Code","version":"0.0.44"}}}} {"type":"emit_inbound","label":"initialize","frame":{"id":1,"result":{"userAgent":"t3code_desktop/0.156.1 (Debian 13.0.0; x86_64) unknown (t3code_desktop; 0.1.0)","codexHome":"/home/replay-user/.codex","platformFamily":"unix","platformOs":"linux"}}} {"type":"expect_outbound","label":"initialized","frame":{"method":"initialized"}} -{"type":"expect_outbound","label":"thread/start","frame":{"id":2,"method":"thread/start","params":{"config":{"tools.update_plan.enabled":true,"mcp_optional_startup_grace_ms":10000,"features.concurrent_reasoning_summaries":true},"cwd":"","model":"gpt-5.6-luna"}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":2,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":2,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"thread/start","frame":{"id":3,"method":"thread/start","params":{"config":{"tools.update_plan.enabled":true,"mcp_optional_startup_grace_ms":10000,"features.concurrent_reasoning_summaries":true},"cwd":"","model":"gpt-5.6-luna"}}} {"type":"emit_inbound","label":"configWarning","frame":{"method":"configWarning","params":{"summary":"Codex could not find bubblewrap on PATH. Install bubblewrap with your OS package manager. See the sandbox prerequisites: https://developers.openai.com/codex/concepts/sandboxing#prerequisites. Codex will use the bundled bubblewrap in the meantime.","details":null},"emittedAtMs":1790296707143}} {"type":"emit_inbound","label":"remoteControl/status/changed","frame":{"method":"remoteControl/status/changed","params":{"status":"disabled","serverName":"replay-host","installationId":"00000000-0000-4000-8000-000000000000","environmentId":null},"emittedAtMs":1790296707143}} -{"type":"emit_inbound","label":"thread/start","frame":{"id":2,"result":{"thread":{"id":"01a0d5ff-d059-77b3-a2cc-81be5c40d448","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d5ff-d059-77b3-a2cc-81be5c40d448","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-5.6-luna","reasoningEffort":null,"createdAt":1790296707,"updatedAt":1790296707,"recencyAt":1790296707,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-38-27-01a0d5ff-d059-77b3-a2cc-81be5c40d448.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]},"model":"gpt-5.6-luna","modelProvider":"openai","serviceTier":null,"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"],"instructionSources":["/home/replay-user/.codex/AGENTS.md","/home/replay-user/t3code/AGENTS.md"],"approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":{"id":":workspace","extends":null},"reasoningEffort":null,"multiAgentMode":"explicitRequestOnly"}}} -{"type":"expect_outbound","label":"thread/name/set","frame":{"id":3,"method":"thread/name/set","params":{"name":"Replay fixture: subagent_continue","threadId":"01a0d5ff-d059-77b3-a2cc-81be5c40d448"}}} -{"type":"emit_inbound","label":"thread/name/set","frame":{"id":3,"result":{}}} +{"type":"emit_inbound","label":"thread/start","frame":{"id":3,"result":{"thread":{"id":"01a0d5ff-d059-77b3-a2cc-81be5c40d448","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d5ff-d059-77b3-a2cc-81be5c40d448","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-5.6-luna","reasoningEffort":null,"createdAt":1790296707,"updatedAt":1790296707,"recencyAt":1790296707,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-38-27-01a0d5ff-d059-77b3-a2cc-81be5c40d448.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]},"model":"gpt-5.6-luna","modelProvider":"openai","serviceTier":null,"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"],"instructionSources":["/home/replay-user/.codex/AGENTS.md","/home/replay-user/t3code/AGENTS.md"],"approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":{"id":":workspace","extends":null},"reasoningEffort":null,"multiAgentMode":"explicitRequestOnly"}}} +{"type":"expect_outbound","label":"thread/name/set","frame":{"id":4,"method":"thread/name/set","params":{"name":"Replay fixture: subagent_continue","threadId":"01a0d5ff-d059-77b3-a2cc-81be5c40d448"}}} +{"type":"emit_inbound","label":"thread/name/set","frame":{"id":4,"result":{}}} {"type":"emit_inbound","label":"thread/name/updated","frame":{"method":"thread/name/updated","params":{"threadId":"01a0d5ff-d059-77b3-a2cc-81be5c40d448","threadName":"Replay fixture: subagent_continue"}}} -{"type":"expect_outbound","label":"config/read","frame":{"id":4,"method":"config/read","params":{"cwd":"","includeLayers":false}}} -{"type":"emit_inbound","label":"config/read","frame":{"id":4,"result":{"config":{},"origins":{}}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":5,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Spawn one subagent and have it reply exactly: initial subagent response","type":"text"}],"model":"gpt-5.6-luna","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"auto","threadId":"01a0d5ff-d059-77b3-a2cc-81be5c40d448","collaborationMode":{"mode":"default","settings":{"model":"gpt-5.6-luna"}}}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":5,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":5,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":6,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Spawn one subagent and have it reply exactly: initial subagent response","type":"text"}],"model":"gpt-5.6-luna","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"auto","threadId":"01a0d5ff-d059-77b3-a2cc-81be5c40d448","collaborationMode":{"mode":"default","settings":{"model":"gpt-5.6-luna"}}}}} {"type":"emit_inbound","label":"thread/started","frame":{"method":"thread/started","params":{"thread":{"id":"01a0d5ff-d059-77b3-a2cc-81be5c40d448","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d5ff-d059-77b3-a2cc-81be5c40d448","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-5.6-luna","reasoningEffort":null,"createdAt":1790296707,"updatedAt":1790296707,"recencyAt":1790296707,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-38-27-01a0d5ff-d059-77b3-a2cc-81be5c40d448.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]}},"emittedAtMs":1790296707328}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0d5ff-d059-77b3-a2cc-81be5c40d448","name":"codex_apps","status":"starting","error":null,"failureReason":null},"emittedAtMs":1790296707328}} {"type":"emit_inbound","label":"thread/settings/updated","frame":{"method":"thread/settings/updated","params":{"threadId":"01a0d5ff-d059-77b3-a2cc-81be5c40d448","threadSettings":{"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","approvalPolicy":"never","approvalsReviewer":"user","sandboxPolicy":{"type":"dangerFullAccess"},"activePermissionProfile":null,"model":"gpt-5.6-luna","modelProvider":"openai","serviceTier":null,"effort":null,"summary":"detailed","collaborationMode":{"mode":"default","settings":{"model":"gpt-5.6-luna","reasoning_effort":null,"developer_instructions":null}},"multiAgentMode":"explicitRequestOnly","personality":null}},"emittedAtMs":1790296707337}} -{"type":"emit_inbound","label":"turn/start","frame":{"id":5,"result":{"turn":{"id":"01a0d5ff-d107-72b0-b80e-eee523c86b42","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} +{"type":"emit_inbound","label":"turn/start","frame":{"id":6,"result":{"turn":{"id":"01a0d5ff-d107-72b0-b80e-eee523c86b42","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d5ff-d059-77b3-a2cc-81be5c40d448","status":{"type":"active","activeFlags":[]}},"emittedAtMs":1790296707369}} {"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"01a0d5ff-d059-77b3-a2cc-81be5c40d448","turn":{"id":"01a0d5ff-d107-72b0-b80e-eee523c86b42","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1790296707,"completedAt":null,"durationMs":null}},"emittedAtMs":1790296707369}} {"type":"emit_inbound","label":"account/updated","frame":{"method":"account/updated","params":{"authMode":"chatgpt","planType":"unknown"},"emittedAtMs":1790296707761}} @@ -81,10 +83,10 @@ {"type":"emit_inbound","label":"thread/tokenUsage/updated","frame":{"method":"thread/tokenUsage/updated","params":{"threadId":"01a0d5ff-d059-77b3-a2cc-81be5c40d448","turnId":"01a0d5ff-d107-72b0-b80e-eee523c86b42","tokenUsage":{"total":{"totalTokens":88196,"inputTokens":87953,"cachedInputTokens":61440,"cacheWriteInputTokens":0,"outputTokens":243,"reasoningOutputTokens":74},"last":{"totalTokens":22955,"inputTokens":22918,"cachedInputTokens":22272,"cacheWriteInputTokens":0,"outputTokens":37,"reasoningOutputTokens":27},"modelContextWindow":258400}},"emittedAtMs":1790296721553}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d5ff-d059-77b3-a2cc-81be5c40d448","status":{"type":"idle"}},"emittedAtMs":1790296721558}} {"type":"emit_inbound","label":"turn/completed","frame":{"method":"turn/completed","params":{"threadId":"01a0d5ff-d059-77b3-a2cc-81be5c40d448","turn":{"id":"01a0d5ff-d107-72b0-b80e-eee523c86b42","items":[{"type":"agentMessage","id":"msg_0cd47e60427f33b8016ab5c29140b487d0abe357be8230ade9","text":"initial subagent response","phase":"final_answer","memoryCitation":null,"delivery":null,"questions":null}],"itemsView":"summary","status":"completed","error":null,"startedAt":1790296707,"completedAt":1790296721,"durationMs":14219}},"emittedAtMs":1790296721558}} -{"type":"expect_outbound","label":"config/read","frame":{"id":6,"method":"config/read","params":{"cwd":"","includeLayers":false}}} -{"type":"emit_inbound","label":"config/read","frame":{"id":6,"result":{"config":{},"origins":{}}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":7,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Have the same subagent you spawned earlier reply exactly: continued subagent response","type":"text"}],"model":"gpt-5.6-luna","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"auto","threadId":"01a0d5ff-d059-77b3-a2cc-81be5c40d448","collaborationMode":{"mode":"default","settings":{"model":"gpt-5.6-luna"}}}}} -{"type":"emit_inbound","label":"turn/start","frame":{"id":7,"result":{"turn":{"id":"01a0d600-0899-7c10-9106-0eac1b8d18f9","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":7,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":7,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":8,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Have the same subagent you spawned earlier reply exactly: continued subagent response","type":"text"}],"model":"gpt-5.6-luna","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"auto","threadId":"01a0d5ff-d059-77b3-a2cc-81be5c40d448","collaborationMode":{"mode":"default","settings":{"model":"gpt-5.6-luna"}}}}} +{"type":"emit_inbound","label":"turn/start","frame":{"id":8,"result":{"turn":{"id":"01a0d600-0899-7c10-9106-0eac1b8d18f9","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d5ff-d059-77b3-a2cc-81be5c40d448","status":{"type":"active","activeFlags":[]}},"emittedAtMs":1790296721577}} {"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"01a0d5ff-d059-77b3-a2cc-81be5c40d448","turn":{"id":"01a0d600-0899-7c10-9106-0eac1b8d18f9","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1790296721,"completedAt":null,"durationMs":null}},"emittedAtMs":1790296721577}} {"type":"emit_inbound","label":"item/started","frame":{"method":"item/started","params":{"item":{"type":"userMessage","id":"01a0d600-0931-74b0-9bed-eacf1497bdf5","clientId":null,"content":[{"type":"text","text":"Have the same subagent you spawned earlier reply exactly: continued subagent response","text_elements":[]}]},"threadId":"01a0d5ff-d059-77b3-a2cc-81be5c40d448","turnId":"01a0d600-0899-7c10-9106-0eac1b8d18f9","startedAtMs":1790296721714},"emittedAtMs":1790296721715}} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/subagent_v2/codex_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/subagent_v2/codex_transcript.ndjson index df4278b9e22d7..8038354788e45 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/subagent_v2/codex_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/subagent_v2/codex_transcript.ndjson @@ -2,22 +2,24 @@ {"type":"expect_outbound","label":"initialize","frame":{"id":1,"method":"initialize","params":{"capabilities":{"experimentalApi":true,"optOutNotificationMethods":["turn/diff/updated"],"extensions":{"io.modelcontextprotocol/ui":{"mimeTypes":["text/html;profile=mcp-app"]}}},"clientInfo":{"name":"T3 Code","title":"T3 Code","version":"0.0.44"}}}} {"type":"emit_inbound","label":"initialize","frame":{"id":1,"result":{"userAgent":"t3code_desktop/0.156.1 (Debian 13.0.0; x86_64) unknown (t3code_desktop; 0.1.0)","codexHome":"/home/replay-user/.codex","platformFamily":"unix","platformOs":"linux"}}} {"type":"expect_outbound","label":"initialized","frame":{"method":"initialized"}} -{"type":"expect_outbound","label":"thread/start","frame":{"id":2,"method":"thread/start","params":{"config":{"tools.update_plan.enabled":true,"mcp_optional_startup_grace_ms":10000,"features.concurrent_reasoning_summaries":true},"cwd":"","model":"gpt-6-luna"}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":2,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":2,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"thread/start","frame":{"id":3,"method":"thread/start","params":{"config":{"tools.update_plan.enabled":true,"mcp_optional_startup_grace_ms":10000,"features.concurrent_reasoning_summaries":true},"cwd":"","model":"gpt-6-luna"}}} {"type":"emit_inbound","label":"configWarning","frame":{"method":"configWarning","params":{"summary":"Codex could not find bubblewrap on PATH. Install bubblewrap with your OS package manager. See the sandbox prerequisites: https://developers.openai.com/codex/concepts/sandboxing#prerequisites. Codex will use the bundled bubblewrap in the meantime.","details":null},"emittedAtMs":1790296671810}} {"type":"emit_inbound","label":"remoteControl/status/changed","frame":{"method":"remoteControl/status/changed","params":{"status":"disabled","serverName":"replay-host","installationId":"00000000-0000-4000-8000-000000000000","environmentId":null},"emittedAtMs":1790296671810}} {"type":"emit_inbound","label":"account/updated","frame":{"method":"account/updated","params":{"authMode":"chatgpt","planType":"unknown"},"emittedAtMs":1790296672562}} -{"type":"emit_inbound","label":"thread/start","frame":{"id":2,"result":{"thread":{"id":"01a0d5ff-49e8-7741-9ca7-b12aa375019a","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d5ff-49e8-7741-9ca7-b12aa375019a","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790296672,"updatedAt":1790296672,"recencyAt":1790296672,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-37-52-01a0d5ff-49e8-7741-9ca7-b12aa375019a.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]},"model":"gpt-6-luna","modelProvider":"openai","serviceTier":null,"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"],"instructionSources":["/home/replay-user/.codex/AGENTS.md","/home/replay-user/t3code/AGENTS.md"],"approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":{"id":":workspace","extends":null},"reasoningEffort":null,"multiAgentMode":"explicitRequestOnly"}}} -{"type":"expect_outbound","label":"thread/name/set","frame":{"id":3,"method":"thread/name/set","params":{"name":"Replay fixture: subagent_v2","threadId":"01a0d5ff-49e8-7741-9ca7-b12aa375019a"}}} -{"type":"emit_inbound","label":"thread/name/set","frame":{"id":3,"result":{}}} +{"type":"emit_inbound","label":"thread/start","frame":{"id":3,"result":{"thread":{"id":"01a0d5ff-49e8-7741-9ca7-b12aa375019a","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d5ff-49e8-7741-9ca7-b12aa375019a","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790296672,"updatedAt":1790296672,"recencyAt":1790296672,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-37-52-01a0d5ff-49e8-7741-9ca7-b12aa375019a.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]},"model":"gpt-6-luna","modelProvider":"openai","serviceTier":null,"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"],"instructionSources":["/home/replay-user/.codex/AGENTS.md","/home/replay-user/t3code/AGENTS.md"],"approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":{"id":":workspace","extends":null},"reasoningEffort":null,"multiAgentMode":"explicitRequestOnly"}}} +{"type":"expect_outbound","label":"thread/name/set","frame":{"id":4,"method":"thread/name/set","params":{"name":"Replay fixture: subagent_v2","threadId":"01a0d5ff-49e8-7741-9ca7-b12aa375019a"}}} +{"type":"emit_inbound","label":"thread/name/set","frame":{"id":4,"result":{}}} {"type":"emit_inbound","label":"thread/name/updated","frame":{"method":"thread/name/updated","params":{"threadId":"01a0d5ff-49e8-7741-9ca7-b12aa375019a","threadName":"Replay fixture: subagent_v2"}}} -{"type":"expect_outbound","label":"config/read","frame":{"id":4,"method":"config/read","params":{"cwd":"","includeLayers":false}}} -{"type":"emit_inbound","label":"config/read","frame":{"id":4,"result":{"config":{},"origins":{}}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":5,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Spawn one subagent whose only task is to reply with exactly: Hello. Wait for it to finish, then reply with exactly what it said.","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"auto","threadId":"01a0d5ff-49e8-7741-9ca7-b12aa375019a","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":5,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":5,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":6,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Spawn one subagent whose only task is to reply with exactly: Hello. Wait for it to finish, then reply with exactly what it said.","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"auto","threadId":"01a0d5ff-49e8-7741-9ca7-b12aa375019a","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} {"type":"emit_inbound","label":"thread/started","frame":{"method":"thread/started","params":{"thread":{"id":"01a0d5ff-49e8-7741-9ca7-b12aa375019a","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d5ff-49e8-7741-9ca7-b12aa375019a","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790296672,"updatedAt":1790296672,"recencyAt":1790296672,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-37-52-01a0d5ff-49e8-7741-9ca7-b12aa375019a.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]}},"emittedAtMs":1790296673000}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0d5ff-49e8-7741-9ca7-b12aa375019a","name":"codex_apps","status":"starting","error":null,"failureReason":null},"emittedAtMs":1790296673000}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0d5ff-49e8-7741-9ca7-b12aa375019a","name":"xcodebuildmcp","status":"starting","error":null,"failureReason":null},"emittedAtMs":1790296673000}} {"type":"emit_inbound","label":"thread/settings/updated","frame":{"method":"thread/settings/updated","params":{"threadId":"01a0d5ff-49e8-7741-9ca7-b12aa375019a","threadSettings":{"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","approvalPolicy":"never","approvalsReviewer":"user","sandboxPolicy":{"type":"dangerFullAccess"},"activePermissionProfile":null,"model":"gpt-6-luna","modelProvider":"openai","serviceTier":null,"effort":null,"summary":"detailed","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna","reasoning_effort":null,"developer_instructions":null}},"multiAgentMode":"explicitRequestOnly","personality":null}},"emittedAtMs":1790296673032}} -{"type":"emit_inbound","label":"turn/start","frame":{"id":5,"result":{"turn":{"id":"01a0d5ff-4b00-7641-bba1-06faa0ef23f1","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} +{"type":"emit_inbound","label":"turn/start","frame":{"id":6,"result":{"turn":{"id":"01a0d5ff-4b00-7641-bba1-06faa0ef23f1","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d5ff-49e8-7741-9ca7-b12aa375019a","status":{"type":"active","activeFlags":[]}},"emittedAtMs":1790296673081}} {"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"01a0d5ff-49e8-7741-9ca7-b12aa375019a","turn":{"id":"01a0d5ff-4b00-7641-bba1-06faa0ef23f1","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1790296673,"completedAt":null,"durationMs":null}},"emittedAtMs":1790296673081}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0d5ff-49e8-7741-9ca7-b12aa375019a","name":"codex_apps","status":"ready","error":null,"failureReason":null},"emittedAtMs":1790296673765}} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/subagent_v2_approval/codex_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/subagent_v2_approval/codex_transcript.ndjson index b7178ee2cd4ce..2f2f000ce1bb1 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/subagent_v2_approval/codex_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/subagent_v2_approval/codex_transcript.ndjson @@ -2,21 +2,23 @@ {"type":"expect_outbound","label":"initialize","frame":{"id":1,"method":"initialize","params":{"capabilities":{"experimentalApi":true,"optOutNotificationMethods":["turn/diff/updated"],"extensions":{"io.modelcontextprotocol/ui":{"mimeTypes":["text/html;profile=mcp-app"]}}},"clientInfo":{"name":"T3 Code","title":"T3 Code","version":"0.0.44"}}}} {"type":"emit_inbound","label":"initialize","frame":{"id":1,"result":{"userAgent":"t3code_desktop/0.156.1 (Debian 13.0.0; x86_64) unknown (t3code_desktop; 0.1.0)","codexHome":"/home/replay-user/tmp/codex-subagent-approval-rec/codex-home","platformFamily":"unix","platformOs":"linux"}}} {"type":"expect_outbound","label":"initialized","frame":{"method":"initialized"}} -{"type":"expect_outbound","label":"thread/start","frame":{"id":2,"method":"thread/start","params":{"config":{"tools.update_plan.enabled":true,"mcp_optional_startup_grace_ms":10000,"features.concurrent_reasoning_summaries":true},"cwd":"","model":"gpt-6-luna"}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":2,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":2,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"thread/start","frame":{"id":3,"method":"thread/start","params":{"config":{"tools.update_plan.enabled":true,"mcp_optional_startup_grace_ms":10000,"features.concurrent_reasoning_summaries":true},"cwd":"","model":"gpt-6-luna"}}} {"type":"emit_inbound","label":"configWarning","frame":{"method":"configWarning","params":{"summary":"Codex could not find bubblewrap on PATH. Install bubblewrap with your OS package manager. See the sandbox prerequisites: https://developers.openai.com/codex/concepts/sandboxing#prerequisites. Codex will use the bundled bubblewrap in the meantime.","details":null},"emittedAtMs":1790368128814}} {"type":"emit_inbound","label":"remoteControl/status/changed","frame":{"method":"remoteControl/status/changed","params":{"status":"disabled","serverName":"replay-host","installationId":"00000000-0000-4000-8000-000000000000","environmentId":null},"emittedAtMs":1790368128814}} {"type":"emit_inbound","label":"account/updated","frame":{"method":"account/updated","params":{"authMode":"chatgpt","planType":"unknown"},"emittedAtMs":1790368129787}} -{"type":"emit_inbound","label":"thread/start","frame":{"id":2,"result":{"thread":{"id":"01a0da41-a28d-7271-b6f6-59123b5bb248","environments":[{"environmentId":"local","cwd":"/home/replay-user/tmp/codex-subagent-approval-rec/repo","runtimeWorkspaceRoots":["/home/replay-user/tmp/codex-subagent-approval-rec/repo"]}],"extra":null,"sessionId":"01a0da41-a28d-7271-b6f6-59123b5bb248","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790368129,"updatedAt":1790368129,"recencyAt":1790368129,"status":{"type":"idle"},"path":"/home/replay-user/tmp/codex-subagent-approval-rec/codex-home/sessions/2026/09/25/rollout-2026-09-25T13-28-49-01a0da41-a28d-7271-b6f6-59123b5bb248.jsonl","cwd":"/home/replay-user/tmp/codex-subagent-approval-rec/repo","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]},"model":"gpt-6-luna","modelProvider":"openai","serviceTier":null,"disabledPluginIds":[],"cwd":"/home/replay-user/tmp/codex-subagent-approval-rec/repo","runtimeWorkspaceRoots":["/home/replay-user/tmp/codex-subagent-approval-rec/repo"],"instructionSources":[],"approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":{"id":":workspace","extends":null},"reasoningEffort":null,"multiAgentMode":"explicitRequestOnly"}}} -{"type":"expect_outbound","label":"thread/name/set","frame":{"id":3,"method":"thread/name/set","params":{"name":"Replay fixture: subagent_v2_approval","threadId":"01a0da41-a28d-7271-b6f6-59123b5bb248"}}} -{"type":"emit_inbound","label":"thread/name/set","frame":{"id":3,"result":{}}} +{"type":"emit_inbound","label":"thread/start","frame":{"id":3,"result":{"thread":{"id":"01a0da41-a28d-7271-b6f6-59123b5bb248","environments":[{"environmentId":"local","cwd":"/home/replay-user/tmp/codex-subagent-approval-rec/repo","runtimeWorkspaceRoots":["/home/replay-user/tmp/codex-subagent-approval-rec/repo"]}],"extra":null,"sessionId":"01a0da41-a28d-7271-b6f6-59123b5bb248","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790368129,"updatedAt":1790368129,"recencyAt":1790368129,"status":{"type":"idle"},"path":"/home/replay-user/tmp/codex-subagent-approval-rec/codex-home/sessions/2026/09/25/rollout-2026-09-25T13-28-49-01a0da41-a28d-7271-b6f6-59123b5bb248.jsonl","cwd":"/home/replay-user/tmp/codex-subagent-approval-rec/repo","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]},"model":"gpt-6-luna","modelProvider":"openai","serviceTier":null,"disabledPluginIds":[],"cwd":"/home/replay-user/tmp/codex-subagent-approval-rec/repo","runtimeWorkspaceRoots":["/home/replay-user/tmp/codex-subagent-approval-rec/repo"],"instructionSources":[],"approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":{"id":":workspace","extends":null},"reasoningEffort":null,"multiAgentMode":"explicitRequestOnly"}}} +{"type":"expect_outbound","label":"thread/name/set","frame":{"id":4,"method":"thread/name/set","params":{"name":"Replay fixture: subagent_v2_approval","threadId":"01a0da41-a28d-7271-b6f6-59123b5bb248"}}} +{"type":"emit_inbound","label":"thread/name/set","frame":{"id":4,"result":{}}} {"type":"emit_inbound","label":"thread/name/updated","frame":{"method":"thread/name/updated","params":{"threadId":"01a0da41-a28d-7271-b6f6-59123b5bb248","threadName":"Replay fixture: subagent_v2_approval"}}} -{"type":"expect_outbound","label":"config/read","frame":{"id":4,"method":"config/read","params":{"cwd":"","includeLayers":false}}} -{"type":"emit_inbound","label":"config/read","frame":{"id":4,"result":{"config":{},"origins":{}}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":5,"method":"turn/start","params":{"approvalPolicy":"untrusted","approvalsReviewer":"user","cwd":"","input":[{"text":"Do not run any commands yourself. Spawn one subagent whose only task is to run this exact shell command: printf 'subagent approval fixture' > subagent-approval.txt and then reply with exactly: Written. Wait for it to finish, then reply with exactly what it said.","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"type":"readOnly"},"summary":"auto","threadId":"01a0da41-a28d-7271-b6f6-59123b5bb248","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":5,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":5,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":6,"method":"turn/start","params":{"approvalPolicy":"untrusted","approvalsReviewer":"user","cwd":"","input":[{"text":"Do not run any commands yourself. Spawn one subagent whose only task is to run this exact shell command: printf 'subagent approval fixture' > subagent-approval.txt and then reply with exactly: Written. Wait for it to finish, then reply with exactly what it said.","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"type":"readOnly"},"summary":"auto","threadId":"01a0da41-a28d-7271-b6f6-59123b5bb248","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} {"type":"emit_inbound","label":"thread/started","frame":{"method":"thread/started","params":{"thread":{"id":"01a0da41-a28d-7271-b6f6-59123b5bb248","environments":[{"environmentId":"local","cwd":"/home/replay-user/tmp/codex-subagent-approval-rec/repo","runtimeWorkspaceRoots":["/home/replay-user/tmp/codex-subagent-approval-rec/repo"]}],"extra":null,"sessionId":"01a0da41-a28d-7271-b6f6-59123b5bb248","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790368129,"updatedAt":1790368129,"recencyAt":1790368129,"status":{"type":"idle"},"path":"/home/replay-user/tmp/codex-subagent-approval-rec/codex-home/sessions/2026/09/25/rollout-2026-09-25T13-28-49-01a0da41-a28d-7271-b6f6-59123b5bb248.jsonl","cwd":"/home/replay-user/tmp/codex-subagent-approval-rec/repo","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]}},"emittedAtMs":1790368129812}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0da41-a28d-7271-b6f6-59123b5bb248","name":"codex_apps","status":"starting","error":null,"failureReason":null},"emittedAtMs":1790368129813}} {"type":"emit_inbound","label":"thread/settings/updated","frame":{"method":"thread/settings/updated","params":{"threadId":"01a0da41-a28d-7271-b6f6-59123b5bb248","threadSettings":{"disabledPluginIds":[],"cwd":"/home/replay-user/tmp/codex-subagent-approval-rec/repo","approvalPolicy":"untrusted","approvalsReviewer":"user","sandboxPolicy":{"type":"readOnly","networkAccess":false},"activePermissionProfile":null,"model":"gpt-6-luna","modelProvider":"openai","serviceTier":null,"effort":null,"summary":"detailed","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna","reasoning_effort":null,"developer_instructions":null}},"multiAgentMode":"explicitRequestOnly","personality":null}},"emittedAtMs":1790368129830}} -{"type":"emit_inbound","label":"turn/start","frame":{"id":5,"result":{"turn":{"id":"01a0da41-a31f-7741-bda3-ebc5ad36c38f","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} +{"type":"emit_inbound","label":"turn/start","frame":{"id":6,"result":{"turn":{"id":"01a0da41-a31f-7741-bda3-ebc5ad36c38f","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0da41-a28d-7271-b6f6-59123b5bb248","status":{"type":"active","activeFlags":[]}},"emittedAtMs":1790368129893}} {"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"01a0da41-a28d-7271-b6f6-59123b5bb248","turn":{"id":"01a0da41-a31f-7741-bda3-ebc5ad36c38f","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1790368129,"completedAt":null,"durationMs":null}},"emittedAtMs":1790368129894}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0da41-a28d-7271-b6f6-59123b5bb248","name":"codex_apps","status":"ready","error":null,"failureReason":null},"emittedAtMs":1790368131004}} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/subagent_v2_nested/codex_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/subagent_v2_nested/codex_transcript.ndjson index d895b9ad9849c..777ed6e802a7d 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/subagent_v2_nested/codex_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/subagent_v2_nested/codex_transcript.ndjson @@ -2,20 +2,22 @@ {"type":"expect_outbound","label":"initialize","frame":{"id":1,"method":"initialize","params":{"capabilities":{"experimentalApi":true,"optOutNotificationMethods":["turn/diff/updated"],"extensions":{"io.modelcontextprotocol/ui":{"mimeTypes":["text/html;profile=mcp-app"]}}},"clientInfo":{"name":"T3 Code","title":"T3 Code","version":"0.0.44"}}}} {"type":"emit_inbound","label":"initialize","frame":{"id":1,"result":{"userAgent":"t3code_desktop/0.156.1 (Debian 13.0.0; x86_64) unknown (t3code_desktop; 0.1.0)","codexHome":"/home/replay-user/.codex","platformFamily":"unix","platformOs":"linux"}}} {"type":"expect_outbound","label":"initialized","frame":{"method":"initialized"}} -{"type":"expect_outbound","label":"thread/start","frame":{"id":2,"method":"thread/start","params":{"config":{"tools.update_plan.enabled":true,"mcp_optional_startup_grace_ms":10000,"features.concurrent_reasoning_summaries":true,"agents.max_depth":3},"cwd":"","model":"gpt-6-luna"}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":2,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":2,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"thread/start","frame":{"id":3,"method":"thread/start","params":{"config":{"tools.update_plan.enabled":true,"mcp_optional_startup_grace_ms":10000,"features.concurrent_reasoning_summaries":true,"agents.max_depth":3},"cwd":"","model":"gpt-6-luna"}}} {"type":"emit_inbound","label":"configWarning","frame":{"method":"configWarning","params":{"summary":"Codex could not find bubblewrap on PATH. Install bubblewrap with your OS package manager. See the sandbox prerequisites: https://developers.openai.com/codex/concepts/sandboxing#prerequisites. Codex will use the bundled bubblewrap in the meantime.","details":null},"emittedAtMs":1790296685424}} {"type":"emit_inbound","label":"remoteControl/status/changed","frame":{"method":"remoteControl/status/changed","params":{"status":"disabled","serverName":"replay-host","installationId":"00000000-0000-4000-8000-000000000000","environmentId":null},"emittedAtMs":1790296685424}} -{"type":"emit_inbound","label":"thread/start","frame":{"id":2,"result":{"thread":{"id":"01a0d5ff-7b98-7e50-a216-1581ca5ebd3a","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d5ff-7b98-7e50-a216-1581ca5ebd3a","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790296685,"updatedAt":1790296685,"recencyAt":1790296685,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-38-05-01a0d5ff-7b98-7e50-a216-1581ca5ebd3a.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]},"model":"gpt-6-luna","modelProvider":"openai","serviceTier":null,"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"],"instructionSources":["/home/replay-user/.codex/AGENTS.md","/home/replay-user/t3code/AGENTS.md"],"approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":{"id":":workspace","extends":null},"reasoningEffort":null,"multiAgentMode":"explicitRequestOnly"}}} -{"type":"expect_outbound","label":"thread/name/set","frame":{"id":3,"method":"thread/name/set","params":{"name":"Replay fixture: subagent_v2_nested","threadId":"01a0d5ff-7b98-7e50-a216-1581ca5ebd3a"}}} -{"type":"emit_inbound","label":"thread/name/set","frame":{"id":3,"result":{}}} +{"type":"emit_inbound","label":"thread/start","frame":{"id":3,"result":{"thread":{"id":"01a0d5ff-7b98-7e50-a216-1581ca5ebd3a","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d5ff-7b98-7e50-a216-1581ca5ebd3a","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790296685,"updatedAt":1790296685,"recencyAt":1790296685,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-38-05-01a0d5ff-7b98-7e50-a216-1581ca5ebd3a.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]},"model":"gpt-6-luna","modelProvider":"openai","serviceTier":null,"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"],"instructionSources":["/home/replay-user/.codex/AGENTS.md","/home/replay-user/t3code/AGENTS.md"],"approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":{"id":":workspace","extends":null},"reasoningEffort":null,"multiAgentMode":"explicitRequestOnly"}}} +{"type":"expect_outbound","label":"thread/name/set","frame":{"id":4,"method":"thread/name/set","params":{"name":"Replay fixture: subagent_v2_nested","threadId":"01a0d5ff-7b98-7e50-a216-1581ca5ebd3a"}}} +{"type":"emit_inbound","label":"thread/name/set","frame":{"id":4,"result":{}}} {"type":"emit_inbound","label":"thread/name/updated","frame":{"method":"thread/name/updated","params":{"threadId":"01a0d5ff-7b98-7e50-a216-1581ca5ebd3a","threadName":"Replay fixture: subagent_v2_nested"}}} -{"type":"expect_outbound","label":"config/read","frame":{"id":4,"method":"config/read","params":{"cwd":"","includeLayers":false}}} -{"type":"emit_inbound","label":"config/read","frame":{"id":4,"result":{"config":{},"origins":{}}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":5,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Spawn one subagent and tell it to spawn its own subagent, which must in turn spawn one more subagent whose only task is to reply with exactly: Hello. Each agent waits for its child and replies with exactly what the child said. Wait for your subagent, then reply with exactly what it said.","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"auto","threadId":"01a0d5ff-7b98-7e50-a216-1581ca5ebd3a","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":5,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":5,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":6,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Spawn one subagent and tell it to spawn its own subagent, which must in turn spawn one more subagent whose only task is to reply with exactly: Hello. Each agent waits for its child and replies with exactly what the child said. Wait for your subagent, then reply with exactly what it said.","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"auto","threadId":"01a0d5ff-7b98-7e50-a216-1581ca5ebd3a","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} {"type":"emit_inbound","label":"thread/started","frame":{"method":"thread/started","params":{"thread":{"id":"01a0d5ff-7b98-7e50-a216-1581ca5ebd3a","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d5ff-7b98-7e50-a216-1581ca5ebd3a","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790296685,"updatedAt":1790296685,"recencyAt":1790296685,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-38-05-01a0d5ff-7b98-7e50-a216-1581ca5ebd3a.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]}},"emittedAtMs":1790296685651}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0d5ff-7b98-7e50-a216-1581ca5ebd3a","name":"codex_apps","status":"starting","error":null,"failureReason":null},"emittedAtMs":1790296685651}} {"type":"emit_inbound","label":"thread/settings/updated","frame":{"method":"thread/settings/updated","params":{"threadId":"01a0d5ff-7b98-7e50-a216-1581ca5ebd3a","threadSettings":{"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","approvalPolicy":"never","approvalsReviewer":"user","sandboxPolicy":{"type":"dangerFullAccess"},"activePermissionProfile":null,"model":"gpt-6-luna","modelProvider":"openai","serviceTier":null,"effort":null,"summary":"detailed","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna","reasoning_effort":null,"developer_instructions":null}},"multiAgentMode":"explicitRequestOnly","personality":null}},"emittedAtMs":1790296685666}} -{"type":"emit_inbound","label":"turn/start","frame":{"id":5,"result":{"turn":{"id":"01a0d5ff-7c5b-7bf1-a92a-39f93af77a6c","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} +{"type":"emit_inbound","label":"turn/start","frame":{"id":6,"result":{"turn":{"id":"01a0d5ff-7c5b-7bf1-a92a-39f93af77a6c","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d5ff-7b98-7e50-a216-1581ca5ebd3a","status":{"type":"active","activeFlags":[]}},"emittedAtMs":1790296685723}} {"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"01a0d5ff-7b98-7e50-a216-1581ca5ebd3a","turn":{"id":"01a0d5ff-7c5b-7bf1-a92a-39f93af77a6c","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1790296685,"completedAt":null,"durationMs":null}},"emittedAtMs":1790296685723}} {"type":"emit_inbound","label":"account/updated","frame":{"method":"account/updated","params":{"authMode":"chatgpt","planType":"unknown"},"emittedAtMs":1790296686001}} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/subagent_v2_nested_approval/codex_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/subagent_v2_nested_approval/codex_transcript.ndjson index 213b6d6d36f6a..e286b3f59cdf1 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/subagent_v2_nested_approval/codex_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/subagent_v2_nested_approval/codex_transcript.ndjson @@ -2,20 +2,22 @@ {"type":"expect_outbound","label":"initialize","frame":{"id":1,"method":"initialize","params":{"capabilities":{"experimentalApi":true,"optOutNotificationMethods":["turn/diff/updated"],"extensions":{"io.modelcontextprotocol/ui":{"mimeTypes":["text/html;profile=mcp-app"]}}},"clientInfo":{"name":"T3 Code","title":"T3 Code","version":"0.0.44"}}}} {"type":"emit_inbound","label":"initialize","frame":{"id":1,"result":{"userAgent":"t3code_desktop/0.156.1 (Debian 13.0.0; x86_64) unknown (t3code_desktop; 0.1.0)","codexHome":"/home/replay-user/.cache/codex-nested-approval-rec/codex-home","platformFamily":"unix","platformOs":"linux"}}} {"type":"expect_outbound","label":"initialized","frame":{"method":"initialized"}} -{"type":"expect_outbound","label":"thread/start","frame":{"id":2,"method":"thread/start","params":{"config":{"tools.update_plan.enabled":true,"mcp_optional_startup_grace_ms":10000,"features.concurrent_reasoning_summaries":true,"agents.max_depth":2},"cwd":"","model":"gpt-6-luna"}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":2,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":2,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"thread/start","frame":{"id":3,"method":"thread/start","params":{"config":{"tools.update_plan.enabled":true,"mcp_optional_startup_grace_ms":10000,"features.concurrent_reasoning_summaries":true,"agents.max_depth":2},"cwd":"","model":"gpt-6-luna"}}} {"type":"emit_inbound","label":"configWarning","frame":{"method":"configWarning","params":{"summary":"Codex could not find bubblewrap on PATH. Install bubblewrap with your OS package manager. See the sandbox prerequisites: https://developers.openai.com/codex/concepts/sandboxing#prerequisites. Codex will use the bundled bubblewrap in the meantime.","details":null},"emittedAtMs":1790374254500}} {"type":"emit_inbound","label":"remoteControl/status/changed","frame":{"method":"remoteControl/status/changed","params":{"status":"disabled","serverName":"replay-host","installationId":"00000000-0000-4000-8000-000000000000","environmentId":null},"emittedAtMs":1790374254500}} -{"type":"emit_inbound","label":"thread/start","frame":{"id":2,"result":{"thread":{"id":"01a0da9f-1b19-7301-961c-a4f5e1b31832","environments":[{"environmentId":"local","cwd":"/home/replay-user/.cache/codex-nested-approval-rec/repo","runtimeWorkspaceRoots":["/home/replay-user/.cache/codex-nested-approval-rec/repo"]}],"extra":null,"sessionId":"01a0da9f-1b19-7301-961c-a4f5e1b31832","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790374255,"updatedAt":1790374255,"recencyAt":1790374255,"status":{"type":"idle"},"path":"/home/replay-user/.cache/codex-nested-approval-rec/codex-home/sessions/2026/09/25/rollout-2026-09-25T15-10-55-01a0da9f-1b19-7301-961c-a4f5e1b31832.jsonl","cwd":"/home/replay-user/.cache/codex-nested-approval-rec/repo","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]},"model":"gpt-6-luna","modelProvider":"openai","serviceTier":null,"disabledPluginIds":[],"cwd":"/home/replay-user/.cache/codex-nested-approval-rec/repo","runtimeWorkspaceRoots":["/home/replay-user/.cache/codex-nested-approval-rec/repo"],"instructionSources":[],"approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":{"id":":workspace","extends":null},"reasoningEffort":null,"multiAgentMode":"explicitRequestOnly"}}} -{"type":"expect_outbound","label":"thread/name/set","frame":{"id":3,"method":"thread/name/set","params":{"name":"Replay fixture: subagent_v2_nested_approval","threadId":"01a0da9f-1b19-7301-961c-a4f5e1b31832"}}} -{"type":"emit_inbound","label":"thread/name/set","frame":{"id":3,"result":{}}} +{"type":"emit_inbound","label":"thread/start","frame":{"id":3,"result":{"thread":{"id":"01a0da9f-1b19-7301-961c-a4f5e1b31832","environments":[{"environmentId":"local","cwd":"/home/replay-user/.cache/codex-nested-approval-rec/repo","runtimeWorkspaceRoots":["/home/replay-user/.cache/codex-nested-approval-rec/repo"]}],"extra":null,"sessionId":"01a0da9f-1b19-7301-961c-a4f5e1b31832","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790374255,"updatedAt":1790374255,"recencyAt":1790374255,"status":{"type":"idle"},"path":"/home/replay-user/.cache/codex-nested-approval-rec/codex-home/sessions/2026/09/25/rollout-2026-09-25T15-10-55-01a0da9f-1b19-7301-961c-a4f5e1b31832.jsonl","cwd":"/home/replay-user/.cache/codex-nested-approval-rec/repo","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]},"model":"gpt-6-luna","modelProvider":"openai","serviceTier":null,"disabledPluginIds":[],"cwd":"/home/replay-user/.cache/codex-nested-approval-rec/repo","runtimeWorkspaceRoots":["/home/replay-user/.cache/codex-nested-approval-rec/repo"],"instructionSources":[],"approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":{"id":":workspace","extends":null},"reasoningEffort":null,"multiAgentMode":"explicitRequestOnly"}}} +{"type":"expect_outbound","label":"thread/name/set","frame":{"id":4,"method":"thread/name/set","params":{"name":"Replay fixture: subagent_v2_nested_approval","threadId":"01a0da9f-1b19-7301-961c-a4f5e1b31832"}}} +{"type":"emit_inbound","label":"thread/name/set","frame":{"id":4,"result":{}}} {"type":"emit_inbound","label":"thread/name/updated","frame":{"method":"thread/name/updated","params":{"threadId":"01a0da9f-1b19-7301-961c-a4f5e1b31832","threadName":"Replay fixture: subagent_v2_nested_approval"}}} -{"type":"expect_outbound","label":"config/read","frame":{"id":4,"method":"config/read","params":{"cwd":"","includeLayers":false}}} -{"type":"emit_inbound","label":"config/read","frame":{"id":4,"result":{"config":{},"origins":{}}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":5,"method":"turn/start","params":{"approvalPolicy":"untrusted","approvalsReviewer":"user","cwd":"","input":[{"text":"Do not run any commands yourself. Spawn one subagent and tell it not to run any commands itself but to spawn its own subagent, whose only task is to run this exact shell command: printf 'nested approval fixture' > nested-approval.txt and then reply with exactly: Written. Each agent waits for its child and replies with exactly what the child said. Wait for your subagent, then reply with exactly what it said.","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"type":"readOnly"},"summary":"auto","threadId":"01a0da9f-1b19-7301-961c-a4f5e1b31832","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":5,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":5,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":6,"method":"turn/start","params":{"approvalPolicy":"untrusted","approvalsReviewer":"user","cwd":"","input":[{"text":"Do not run any commands yourself. Spawn one subagent and tell it not to run any commands itself but to spawn its own subagent, whose only task is to run this exact shell command: printf 'nested approval fixture' > nested-approval.txt and then reply with exactly: Written. Each agent waits for its child and replies with exactly what the child said. Wait for your subagent, then reply with exactly what it said.","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"type":"readOnly"},"summary":"auto","threadId":"01a0da9f-1b19-7301-961c-a4f5e1b31832","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} {"type":"emit_inbound","label":"thread/started","frame":{"method":"thread/started","params":{"thread":{"id":"01a0da9f-1b19-7301-961c-a4f5e1b31832","environments":[{"environmentId":"local","cwd":"/home/replay-user/.cache/codex-nested-approval-rec/repo","runtimeWorkspaceRoots":["/home/replay-user/.cache/codex-nested-approval-rec/repo"]}],"extra":null,"sessionId":"01a0da9f-1b19-7301-961c-a4f5e1b31832","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790374255,"updatedAt":1790374255,"recencyAt":1790374255,"status":{"type":"idle"},"path":"/home/replay-user/.cache/codex-nested-approval-rec/codex-home/sessions/2026/09/25/rollout-2026-09-25T15-10-55-01a0da9f-1b19-7301-961c-a4f5e1b31832.jsonl","cwd":"/home/replay-user/.cache/codex-nested-approval-rec/repo","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]}},"emittedAtMs":1790374255463}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0da9f-1b19-7301-961c-a4f5e1b31832","name":"codex_apps","status":"starting","error":null,"failureReason":null},"emittedAtMs":1790374255463}} {"type":"emit_inbound","label":"thread/settings/updated","frame":{"method":"thread/settings/updated","params":{"threadId":"01a0da9f-1b19-7301-961c-a4f5e1b31832","threadSettings":{"disabledPluginIds":[],"cwd":"/home/replay-user/.cache/codex-nested-approval-rec/repo","approvalPolicy":"untrusted","approvalsReviewer":"user","sandboxPolicy":{"type":"readOnly","networkAccess":false},"activePermissionProfile":null,"model":"gpt-6-luna","modelProvider":"openai","serviceTier":null,"effort":null,"summary":"detailed","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna","reasoning_effort":null,"developer_instructions":null}},"multiAgentMode":"explicitRequestOnly","personality":null}},"emittedAtMs":1790374255475}} -{"type":"emit_inbound","label":"turn/start","frame":{"id":5,"result":{"turn":{"id":"01a0da9f-1b6f-7dd3-90da-e6c8797c1da6","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} +{"type":"emit_inbound","label":"turn/start","frame":{"id":6,"result":{"turn":{"id":"01a0da9f-1b6f-7dd3-90da-e6c8797c1da6","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0da9f-1b19-7301-961c-a4f5e1b31832","status":{"type":"active","activeFlags":[]}},"emittedAtMs":1790374255518}} {"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"01a0da9f-1b19-7301-961c-a4f5e1b31832","turn":{"id":"01a0da9f-1b6f-7dd3-90da-e6c8797c1da6","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1790374255,"completedAt":null,"durationMs":null}},"emittedAtMs":1790374255518}} {"type":"emit_inbound","label":"account/updated","frame":{"method":"account/updated","params":{"authMode":"chatgpt","planType":"unknown"},"emittedAtMs":1790374255710}} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/thread_fork_native_prior_turn/codex_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/thread_fork_native_prior_turn/codex_transcript.ndjson index 8d84a2031d661..405ce582f6ea0 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/thread_fork_native_prior_turn/codex_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/thread_fork_native_prior_turn/codex_transcript.ndjson @@ -2,21 +2,23 @@ {"type":"expect_outbound","label":"initialize/source","frame":{"id":1,"method":"initialize","params":{"capabilities":{"experimentalApi":true,"optOutNotificationMethods":["turn/diff/updated"],"extensions":{"io.modelcontextprotocol/ui":{"mimeTypes":["text/html;profile=mcp-app"]}}},"clientInfo":{"name":"T3 Code","title":"T3 Code","version":"0.0.44"}}}} {"type":"emit_inbound","label":"initialize/source","frame":{"id":1,"result":{"userAgent":"t3code_desktop/0.124.0-alpha.3","codexHome":"/home/replay-user/.codex","platformFamily":"unix","platformOs":"macos"}}} {"type":"expect_outbound","label":"initialized/source","frame":{"method":"initialized"}} -{"type":"expect_outbound","label":"thread/start","frame":{"id":2,"method":"thread/start","params":{"config":{"tools.update_plan.enabled":true,"mcp_optional_startup_grace_ms":10000,"features.concurrent_reasoning_summaries":true}}}} -{"type":"emit_inbound","label":"thread/start","frame":{"id":2,"result":{"thread":{"id":"019dd6ba-2681-7bf0-b051-141b0cbcbb27","forkedFromId":null,"preview":"","ephemeral":false,"modelProvider":"openai","createdAt":1777424017,"updatedAt":1777424017,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/04/28/rollout-2026-04-28T17-53-37-019dd6ba-2681-7bf0-b051-141b0cbcbb27.jsonl","cwd":"/home/replay-user/t3code","cliVersion":"0.124.0-alpha.3","source":"vscode","agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"turns":[]},"model":"gpt-5.5","modelProvider":"openai","serviceTier":"fast","cwd":"/home/replay-user/t3code","instructionSources":["/home/replay-user/.codex/AGENTS.md","/home/replay-user/t3code/AGENTS.md"],"approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":["/home/replay-user/.codex/memories"],"readOnlyAccess":{"type":"fullAccess"},"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"permissionProfile":{"network":{"enabled":false},"fileSystem":{"entries":[{"path":{"type":"special","value":{"kind":"root"}},"access":"read"},{"path":{"type":"special","value":{"kind":"current_working_directory"}},"access":"write"},{"path":{"type":"special","value":{"kind":"slash_tmp"}},"access":"write"},{"path":{"type":"special","value":{"kind":"tmpdir"}},"access":"write"},{"path":{"type":"path","path":"/home/replay-user/.codex/memories"},"access":"write"},{"path":{"type":"path","path":"/home/replay-user/Development/Work/codething-mvp/.git/worktrees/t3code-c1e5e1d1"},"access":"read"},{"path":{"type":"path","path":"/home/replay-user/t3code/.git"},"access":"read"},{"path":{"type":"path","path":"/home/replay-user/t3code/.codex"},"access":"read"}]}},"reasoningEffort":"medium"}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":2,"method":"config/read","params":{"includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":2,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"thread/start","frame":{"id":3,"method":"thread/start","params":{"config":{"tools.update_plan.enabled":true,"mcp_optional_startup_grace_ms":10000,"features.concurrent_reasoning_summaries":true}}}} +{"type":"emit_inbound","label":"thread/start","frame":{"id":3,"result":{"thread":{"id":"019dd6ba-2681-7bf0-b051-141b0cbcbb27","forkedFromId":null,"preview":"","ephemeral":false,"modelProvider":"openai","createdAt":1777424017,"updatedAt":1777424017,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/04/28/rollout-2026-04-28T17-53-37-019dd6ba-2681-7bf0-b051-141b0cbcbb27.jsonl","cwd":"/home/replay-user/t3code","cliVersion":"0.124.0-alpha.3","source":"vscode","agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"turns":[]},"model":"gpt-5.5","modelProvider":"openai","serviceTier":"fast","cwd":"/home/replay-user/t3code","instructionSources":["/home/replay-user/.codex/AGENTS.md","/home/replay-user/t3code/AGENTS.md"],"approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":["/home/replay-user/.codex/memories"],"readOnlyAccess":{"type":"fullAccess"},"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"permissionProfile":{"network":{"enabled":false},"fileSystem":{"entries":[{"path":{"type":"special","value":{"kind":"root"}},"access":"read"},{"path":{"type":"special","value":{"kind":"current_working_directory"}},"access":"write"},{"path":{"type":"special","value":{"kind":"slash_tmp"}},"access":"write"},{"path":{"type":"special","value":{"kind":"tmpdir"}},"access":"write"},{"path":{"type":"path","path":"/home/replay-user/.codex/memories"},"access":"write"},{"path":{"type":"path","path":"/home/replay-user/Development/Work/codething-mvp/.git/worktrees/t3code-c1e5e1d1"},"access":"read"},{"path":{"type":"path","path":"/home/replay-user/t3code/.git"},"access":"read"},{"path":{"type":"path","path":"/home/replay-user/t3code/.codex"},"access":"read"}]}},"reasoningEffort":"medium"}}} {"type":"emit_inbound","label":"thread/started","frame":{"method":"thread/started","params":{"thread":{"id":"019dd6ba-2681-7bf0-b051-141b0cbcbb27","forkedFromId":null,"preview":"","ephemeral":false,"modelProvider":"openai","createdAt":1777424017,"updatedAt":1777424017,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/04/28/rollout-2026-04-28T17-53-37-019dd6ba-2681-7bf0-b051-141b0cbcbb27.jsonl","cwd":"/home/replay-user/t3code","cliVersion":"0.124.0-alpha.3","source":"vscode","agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"turns":[]}}}} -{"type":"expect_outbound","label":"thread/name/set","frame":{"id":3,"method":"thread/name/set","params":{"name":"Source thread","threadId":"019dd6ba-2681-7bf0-b051-141b0cbcbb27"}}} -{"type":"emit_inbound","label":"thread/name/set","frame":{"id":3,"result":{}}} +{"type":"expect_outbound","label":"thread/name/set","frame":{"id":4,"method":"thread/name/set","params":{"name":"Source thread","threadId":"019dd6ba-2681-7bf0-b051-141b0cbcbb27"}}} +{"type":"emit_inbound","label":"thread/name/set","frame":{"id":4,"result":{}}} {"type":"emit_inbound","label":"thread/name/updated","frame":{"method":"thread/name/updated","params":{"threadId":"019dd6ba-2681-7bf0-b051-141b0cbcbb27","threadName":"Source thread"}}} -{"type":"expect_outbound","label":"config/read","frame":{"id":4,"method":"config/read","params":{"cwd":"","includeLayers":false}}} -{"type":"emit_inbound","label":"config/read","frame":{"id":4,"result":{"config":{},"origins":{}}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":5,"method":"turn/start","params":{"approvalPolicy":"never","cwd":"","input":[{"type":"text","text":"For this fork-boundary fixture, respond with exactly: fork boundary alpha"}],"model":"gpt-5.4","sandboxPolicy":{"type":"readOnly","networkAccess":false},"threadId":"019dd6ba-2681-7bf0-b051-141b0cbcbb27","approvalsReviewer":"user","summary":"auto","collaborationMode":{"mode":"default","settings":{"model":"gpt-5.4"}}}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":5,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":5,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":6,"method":"turn/start","params":{"approvalPolicy":"never","cwd":"","input":[{"type":"text","text":"For this fork-boundary fixture, respond with exactly: fork boundary alpha"}],"model":"gpt-5.4","sandboxPolicy":{"type":"readOnly","networkAccess":false},"threadId":"019dd6ba-2681-7bf0-b051-141b0cbcbb27","approvalsReviewer":"user","summary":"auto","collaborationMode":{"mode":"default","settings":{"model":"gpt-5.4"}}}}} {"type":"emit_inbound","label":"deprecationNotice","frame":{"method":"deprecationNotice","params":{"summary":"`[features].collab` is deprecated. Use `[features].multi_agent` instead.","details":"Enable it with `--enable multi_agent` or `[features].multi_agent` in config.toml. See https://developers.openai.com/codex/config-basic#feature-flags for details."}}} {"type":"emit_inbound","label":"warning","frame":{"method":"warning","params":{"threadId":"019dd6ba-2681-7bf0-b051-141b0cbcbb27","message":"Under-development features enabled: apply_patch_freeform. Under-development features are incomplete and may behave unpredictably. To suppress this warning, set `suppress_unstable_features_warning = true` in /home/replay-user/.codex/config.toml."}}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"name":"codex_apps","status":"starting","error":null}}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"name":"computer-use","status":"starting","error":null}}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"name":"uidotsh","status":"starting","error":null}}} -{"type":"emit_inbound","label":"turn/start","frame":{"id":5,"result":{"turn":{"id":"019dd6ba-268b-7f82-8f4c-9fde0edcfd55","items":[],"status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} +{"type":"emit_inbound","label":"turn/start","frame":{"id":6,"result":{"turn":{"id":"019dd6ba-268b-7f82-8f4c-9fde0edcfd55","items":[],"status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"019dd6ba-2681-7bf0-b051-141b0cbcbb27","status":{"type":"active","activeFlags":[]}}}} {"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"019dd6ba-2681-7bf0-b051-141b0cbcbb27","turn":{"id":"019dd6ba-268b-7f82-8f4c-9fde0edcfd55","items":[],"status":"inProgress","error":null,"startedAt":1777424017,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"name":"computer-use","status":"ready","error":null}}} @@ -36,10 +38,10 @@ {"type":"emit_inbound","label":"account/rateLimits/updated","frame":{"method":"account/rateLimits/updated","params":{"rateLimits":{"limitId":"codex","limitName":null,"primary":{"usedPercent":61,"windowDurationMins":300,"resetsAt":1777429830},"secondary":{"usedPercent":23,"windowDurationMins":10080,"resetsAt":1777959590},"credits":null,"planType":"unknown","rateLimitReachedType":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"019dd6ba-2681-7bf0-b051-141b0cbcbb27","status":{"type":"idle"}}}} {"type":"emit_inbound","label":"turn/completed","frame":{"method":"turn/completed","params":{"threadId":"019dd6ba-2681-7bf0-b051-141b0cbcbb27","turn":{"id":"019dd6ba-268b-7f82-8f4c-9fde0edcfd55","items":[],"status":"completed","error":null,"startedAt":1777424017,"completedAt":1777424023,"durationMs":6880}}}} -{"type":"expect_outbound","label":"config/read","frame":{"id":6,"method":"config/read","params":{"cwd":"","includeLayers":false}}} -{"type":"emit_inbound","label":"config/read","frame":{"id":6,"result":{"config":{},"origins":{}}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":7,"method":"turn/start","params":{"approvalPolicy":"never","cwd":"","input":[{"type":"text","text":"For this fork-boundary fixture, respond with exactly: fork boundary beta"}],"model":"gpt-5.4","sandboxPolicy":{"type":"readOnly","networkAccess":false},"threadId":"019dd6ba-2681-7bf0-b051-141b0cbcbb27","approvalsReviewer":"user","summary":"auto","collaborationMode":{"mode":"default","settings":{"model":"gpt-5.4"}}}}} -{"type":"emit_inbound","label":"turn/start","frame":{"id":7,"result":{"turn":{"id":"019dd6ba-416d-7902-95cf-d4179c3f4738","items":[],"status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":7,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":7,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":8,"method":"turn/start","params":{"approvalPolicy":"never","cwd":"","input":[{"type":"text","text":"For this fork-boundary fixture, respond with exactly: fork boundary beta"}],"model":"gpt-5.4","sandboxPolicy":{"type":"readOnly","networkAccess":false},"threadId":"019dd6ba-2681-7bf0-b051-141b0cbcbb27","approvalsReviewer":"user","summary":"auto","collaborationMode":{"mode":"default","settings":{"model":"gpt-5.4"}}}}} +{"type":"emit_inbound","label":"turn/start","frame":{"id":8,"result":{"turn":{"id":"019dd6ba-416d-7902-95cf-d4179c3f4738","items":[],"status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"019dd6ba-2681-7bf0-b051-141b0cbcbb27","status":{"type":"active","activeFlags":[]}}}} {"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"019dd6ba-2681-7bf0-b051-141b0cbcbb27","turn":{"id":"019dd6ba-416d-7902-95cf-d4179c3f4738","items":[],"status":"inProgress","error":null,"startedAt":1777424023,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"item/started","frame":{"method":"item/started","params":{"item":{"type":"userMessage","id":"e8550ffa-7e59-48b3-8fd2-7bbca932ab95","content":[{"type":"text","text":"For this fork-boundary fixture, respond with exactly: fork boundary beta","text_elements":[]}]},"threadId":"019dd6ba-2681-7bf0-b051-141b0cbcbb27","turnId":"019dd6ba-416d-7902-95cf-d4179c3f4738"}}} @@ -55,21 +57,23 @@ {"type":"emit_inbound","label":"account/rateLimits/updated","frame":{"method":"account/rateLimits/updated","params":{"rateLimits":{"limitId":"codex","limitName":null,"primary":{"usedPercent":61,"windowDurationMins":300,"resetsAt":1777429830},"secondary":{"usedPercent":23,"windowDurationMins":10080,"resetsAt":1777959590},"credits":null,"planType":"unknown","rateLimitReachedType":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"019dd6ba-2681-7bf0-b051-141b0cbcbb27","status":{"type":"idle"}}}} {"type":"emit_inbound","label":"turn/completed","frame":{"method":"turn/completed","params":{"threadId":"019dd6ba-2681-7bf0-b051-141b0cbcbb27","turn":{"id":"019dd6ba-416d-7902-95cf-d4179c3f4738","items":[],"status":"completed","error":null,"startedAt":1777424023,"completedAt":1777424025,"durationMs":1596}}}} -{"type":"expect_outbound","label":"thread/fork","frame":{"id":8,"method":"thread/fork","params":{"threadId":"019dd6ba-2681-7bf0-b051-141b0cbcbb27","excludeTurns":true,"lastTurnId":"019dd6ba-268b-7f82-8f4c-9fde0edcfd55","config":{"tools.update_plan.enabled":true,"mcp_optional_startup_grace_ms":10000,"features.concurrent_reasoning_summaries":true}}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":9,"method":"config/read","params":{"includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":9,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"thread/fork","frame":{"id":10,"method":"thread/fork","params":{"threadId":"019dd6ba-2681-7bf0-b051-141b0cbcbb27","excludeTurns":true,"lastTurnId":"019dd6ba-268b-7f82-8f4c-9fde0edcfd55","config":{"tools.update_plan.enabled":true,"mcp_optional_startup_grace_ms":10000,"features.concurrent_reasoning_summaries":true}}}} {"type":"emit_inbound","label":"deprecationNotice","frame":{"method":"deprecationNotice","params":{"summary":"`[features].collab` is deprecated. Use `[features].multi_agent` instead.","details":"Enable it with `--enable multi_agent` or `[features].multi_agent` in config.toml. See https://developers.openai.com/codex/config-basic#feature-flags for details."}}} {"type":"emit_inbound","label":"warning","frame":{"method":"warning","params":{"threadId":"019dd6ba-47b7-7092-8688-9cf7fe5f6498","message":"Under-development features enabled: apply_patch_freeform. Under-development features are incomplete and may behave unpredictably. To suppress this warning, set `suppress_unstable_features_warning = true` in /home/replay-user/.codex/config.toml."}}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"name":"uidotsh","status":"starting","error":null}}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"name":"computer-use","status":"starting","error":null}}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"name":"codex_apps","status":"starting","error":null}}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"name":"computer-use","status":"ready","error":null}}} -{"type":"emit_inbound","label":"thread/fork","frame":{"id":8,"result":{"thread":{"id":"019dd6ba-47b7-7092-8688-9cf7fe5f6498","forkedFromId":"019dd6ba-2681-7bf0-b051-141b0cbcbb27","preview":"For this fork-boundary fixture, respond with exactly: fork boundary alpha","ephemeral":false,"modelProvider":"openai","createdAt":1777424025,"updatedAt":1777424025,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/04/28/rollout-2026-04-28T17-53-45-019dd6ba-47b7-7092-8688-9cf7fe5f6498.jsonl","cwd":"/home/replay-user/t3code","cliVersion":"0.124.0-alpha.3","source":"vscode","agentNickname":null,"agentRole":null,"gitInfo":{"sha":"969e8ea4fac1f2066ed50dd4f82b5fd0014d8a4d","branch":"t3code/codex-turn-mapping","originUrl":"git@github.com:pingdotgg/t3code.git"},"name":null,"turns":[{"id":"019dd6ba-268b-7f82-8f4c-9fde0edcfd55","items":[{"type":"userMessage","id":"item-1","content":[{"type":"text","text":"For this fork-boundary fixture, respond with exactly: fork boundary alpha","text_elements":[]}]},{"type":"agentMessage","id":"item-2","text":"fork boundary alpha","phase":"final_answer","memoryCitation":null}],"status":"completed","error":null,"startedAt":1777424017,"completedAt":1777424023,"durationMs":6880}]},"model":"gpt-5.5","modelProvider":"openai","serviceTier":"fast","cwd":"/home/replay-user/t3code","instructionSources":["/home/replay-user/.codex/AGENTS.md","/home/replay-user/t3code/AGENTS.md"],"approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":["/home/replay-user/.codex/memories"],"readOnlyAccess":{"type":"fullAccess"},"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"permissionProfile":{"network":{"enabled":false},"fileSystem":{"entries":[{"path":{"type":"special","value":{"kind":"root"}},"access":"read"},{"path":{"type":"special","value":{"kind":"current_working_directory"}},"access":"write"},{"path":{"type":"special","value":{"kind":"slash_tmp"}},"access":"write"},{"path":{"type":"special","value":{"kind":"tmpdir"}},"access":"write"},{"path":{"type":"path","path":"/home/replay-user/.codex/memories"},"access":"write"},{"path":{"type":"path","path":"/home/replay-user/Development/Work/codething-mvp/.git/worktrees/t3code-c1e5e1d1"},"access":"read"},{"path":{"type":"path","path":"/home/replay-user/t3code/.git"},"access":"read"},{"path":{"type":"path","path":"/home/replay-user/t3code/.codex"},"access":"read"}]}},"reasoningEffort":"medium"}}} -{"type":"expect_outbound","label":"thread/name/set","frame":{"id":9,"method":"thread/name/set","params":{"name":"Forked from first response","threadId":"019dd6ba-47b7-7092-8688-9cf7fe5f6498"}}} -{"type":"emit_inbound","label":"thread/name/set","frame":{"id":9,"result":{}}} +{"type":"emit_inbound","label":"thread/fork","frame":{"id":10,"result":{"thread":{"id":"019dd6ba-47b7-7092-8688-9cf7fe5f6498","forkedFromId":"019dd6ba-2681-7bf0-b051-141b0cbcbb27","preview":"For this fork-boundary fixture, respond with exactly: fork boundary alpha","ephemeral":false,"modelProvider":"openai","createdAt":1777424025,"updatedAt":1777424025,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/04/28/rollout-2026-04-28T17-53-45-019dd6ba-47b7-7092-8688-9cf7fe5f6498.jsonl","cwd":"/home/replay-user/t3code","cliVersion":"0.124.0-alpha.3","source":"vscode","agentNickname":null,"agentRole":null,"gitInfo":{"sha":"969e8ea4fac1f2066ed50dd4f82b5fd0014d8a4d","branch":"t3code/codex-turn-mapping","originUrl":"git@github.com:pingdotgg/t3code.git"},"name":null,"turns":[{"id":"019dd6ba-268b-7f82-8f4c-9fde0edcfd55","items":[{"type":"userMessage","id":"item-1","content":[{"type":"text","text":"For this fork-boundary fixture, respond with exactly: fork boundary alpha","text_elements":[]}]},{"type":"agentMessage","id":"item-2","text":"fork boundary alpha","phase":"final_answer","memoryCitation":null}],"status":"completed","error":null,"startedAt":1777424017,"completedAt":1777424023,"durationMs":6880}]},"model":"gpt-5.5","modelProvider":"openai","serviceTier":"fast","cwd":"/home/replay-user/t3code","instructionSources":["/home/replay-user/.codex/AGENTS.md","/home/replay-user/t3code/AGENTS.md"],"approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":["/home/replay-user/.codex/memories"],"readOnlyAccess":{"type":"fullAccess"},"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"permissionProfile":{"network":{"enabled":false},"fileSystem":{"entries":[{"path":{"type":"special","value":{"kind":"root"}},"access":"read"},{"path":{"type":"special","value":{"kind":"current_working_directory"}},"access":"write"},{"path":{"type":"special","value":{"kind":"slash_tmp"}},"access":"write"},{"path":{"type":"special","value":{"kind":"tmpdir"}},"access":"write"},{"path":{"type":"path","path":"/home/replay-user/.codex/memories"},"access":"write"},{"path":{"type":"path","path":"/home/replay-user/Development/Work/codething-mvp/.git/worktrees/t3code-c1e5e1d1"},"access":"read"},{"path":{"type":"path","path":"/home/replay-user/t3code/.git"},"access":"read"},{"path":{"type":"path","path":"/home/replay-user/t3code/.codex"},"access":"read"}]}},"reasoningEffort":"medium"}}} +{"type":"expect_outbound","label":"thread/name/set","frame":{"id":11,"method":"thread/name/set","params":{"name":"Forked from first response","threadId":"019dd6ba-47b7-7092-8688-9cf7fe5f6498"}}} +{"type":"emit_inbound","label":"thread/name/set","frame":{"id":11,"result":{}}} {"type":"emit_inbound","label":"thread/name/updated","frame":{"method":"thread/name/updated","params":{"threadId":"019dd6ba-47b7-7092-8688-9cf7fe5f6498","threadName":"Forked from first response"}}} -{"type":"expect_outbound","label":"config/read","frame":{"id":10,"method":"config/read","params":{"cwd":"","includeLayers":false}}} -{"type":"emit_inbound","label":"config/read","frame":{"id":10,"result":{"config":{},"origins":{}}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":11,"method":"turn/start","params":{"approvalPolicy":"never","cwd":"","input":[{"type":"text","text":"Repeat the user-visible conversation so far verbatim. Include only user and assistant messages. Do not include hidden system/developer content."}],"model":"gpt-5.4","sandboxPolicy":{"type":"readOnly","networkAccess":false},"threadId":"019dd6ba-47b7-7092-8688-9cf7fe5f6498","approvalsReviewer":"user","summary":"auto","collaborationMode":{"mode":"default","settings":{"model":"gpt-5.4"}}}}} -{"type":"emit_inbound","label":"turn/start","frame":{"id":11,"result":{"turn":{"id":"019dd6ba-47eb-7041-ad45-5abe752c28c9","items":[],"status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":12,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":12,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":13,"method":"turn/start","params":{"approvalPolicy":"never","cwd":"","input":[{"type":"text","text":"Repeat the user-visible conversation so far verbatim. Include only user and assistant messages. Do not include hidden system/developer content."}],"model":"gpt-5.4","sandboxPolicy":{"type":"readOnly","networkAccess":false},"threadId":"019dd6ba-47b7-7092-8688-9cf7fe5f6498","approvalsReviewer":"user","summary":"auto","collaborationMode":{"mode":"default","settings":{"model":"gpt-5.4"}}}}} +{"type":"emit_inbound","label":"turn/start","frame":{"id":13,"result":{"turn":{"id":"019dd6ba-47eb-7041-ad45-5abe752c28c9","items":[],"status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"019dd6ba-47b7-7092-8688-9cf7fe5f6498","status":{"type":"active","activeFlags":[]}}}} {"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"019dd6ba-47b7-7092-8688-9cf7fe5f6498","turn":{"id":"019dd6ba-47eb-7041-ad45-5abe752c28c9","items":[],"status":"inProgress","error":null,"startedAt":1777424025,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"name":"uidotsh","status":"ready","error":null}}} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/thread_merge_back_siblings/codex_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/thread_merge_back_siblings/codex_transcript.ndjson index 4a9de158436dd..42802821be26e 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/thread_merge_back_siblings/codex_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/thread_merge_back_siblings/codex_transcript.ndjson @@ -2,20 +2,22 @@ {"type":"expect_outbound","label":"initialize","frame":{"id":1,"method":"initialize","params":{"capabilities":{"experimentalApi":true,"optOutNotificationMethods":["turn/diff/updated"],"extensions":{"io.modelcontextprotocol/ui":{"mimeTypes":["text/html;profile=mcp-app"]}}},"clientInfo":{"name":"T3 Code","title":"T3 Code","version":"0.0.44"}}}} {"type":"emit_inbound","label":"initialize","frame":{"id":1,"result":{"userAgent":"t3code_desktop/0.156.1 (Debian 13.0.0; x86_64) unknown (t3code_desktop; 0.1.0)","codexHome":"/home/replay-user/.codex","platformFamily":"unix","platformOs":"linux"}}} {"type":"expect_outbound","label":"initialized","frame":{"method":"initialized"}} -{"type":"expect_outbound","label":"thread/start","frame":{"id":2,"method":"thread/start","params":{"config":{"tools.update_plan.enabled":true,"mcp_optional_startup_grace_ms":10000,"features.concurrent_reasoning_summaries":true},"cwd":"","model":"gpt-6-sol"}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":2,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":2,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"thread/start","frame":{"id":3,"method":"thread/start","params":{"config":{"tools.update_plan.enabled":true,"mcp_optional_startup_grace_ms":10000,"features.concurrent_reasoning_summaries":true},"cwd":"","model":"gpt-6-sol"}}} {"type":"emit_inbound","label":"configWarning","frame":{"method":"configWarning","params":{"summary":"Codex could not find bubblewrap on PATH. Install bubblewrap with your OS package manager. See the sandbox prerequisites: https://developers.openai.com/codex/concepts/sandboxing#prerequisites. Codex will use the bundled bubblewrap in the meantime.","details":null},"emittedAtMs":1790297773374}} {"type":"emit_inbound","label":"remoteControl/status/changed","frame":{"method":"remoteControl/status/changed","params":{"status":"disabled","serverName":"replay-host","installationId":"00000000-0000-4000-8000-000000000000","environmentId":null},"emittedAtMs":1790297773374}} -{"type":"emit_inbound","label":"thread/start","frame":{"id":2,"result":{"thread":{"id":"01a0d610-155f-7391-843e-120bf1475357","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d610-155f-7391-843e-120bf1475357","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-sol","reasoningEffort":null,"createdAt":1790297773,"updatedAt":1790297773,"recencyAt":1790297773,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-56-13-01a0d610-155f-7391-843e-120bf1475357.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]},"model":"gpt-6-sol","modelProvider":"openai","serviceTier":null,"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"],"instructionSources":["/home/replay-user/.codex/AGENTS.md"],"approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":{"id":":workspace","extends":null},"reasoningEffort":null,"multiAgentMode":"explicitRequestOnly"}}} -{"type":"expect_outbound","label":"thread/name/set","frame":{"id":3,"method":"thread/name/set","params":{"name":"Merge-back source","threadId":"01a0d610-155f-7391-843e-120bf1475357"}}} -{"type":"emit_inbound","label":"thread/name/set","frame":{"id":3,"result":{}}} +{"type":"emit_inbound","label":"thread/start","frame":{"id":3,"result":{"thread":{"id":"01a0d610-155f-7391-843e-120bf1475357","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d610-155f-7391-843e-120bf1475357","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-sol","reasoningEffort":null,"createdAt":1790297773,"updatedAt":1790297773,"recencyAt":1790297773,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-56-13-01a0d610-155f-7391-843e-120bf1475357.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]},"model":"gpt-6-sol","modelProvider":"openai","serviceTier":null,"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"],"instructionSources":["/home/replay-user/.codex/AGENTS.md"],"approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":{"id":":workspace","extends":null},"reasoningEffort":null,"multiAgentMode":"explicitRequestOnly"}}} +{"type":"expect_outbound","label":"thread/name/set","frame":{"id":4,"method":"thread/name/set","params":{"name":"Merge-back source","threadId":"01a0d610-155f-7391-843e-120bf1475357"}}} +{"type":"emit_inbound","label":"thread/name/set","frame":{"id":4,"result":{}}} {"type":"emit_inbound","label":"thread/name/updated","frame":{"method":"thread/name/updated","params":{"threadId":"01a0d610-155f-7391-843e-120bf1475357","threadName":"Merge-back source"}}} -{"type":"expect_outbound","label":"config/read","frame":{"id":4,"method":"config/read","params":{"cwd":"","includeLayers":false}}} -{"type":"emit_inbound","label":"config/read","frame":{"id":4,"result":{"config":{},"origins":{}}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":5,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Remember the opaque marker merge-sibling-source-3C7K for later in this conversation. Respond with exactly: merge sibling source stored","type":"text"}],"model":"gpt-6-sol","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"auto","threadId":"01a0d610-155f-7391-843e-120bf1475357","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-sol"}}}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":5,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":5,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":6,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Remember the opaque marker merge-sibling-source-3C7K for later in this conversation. Respond with exactly: merge sibling source stored","type":"text"}],"model":"gpt-6-sol","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"auto","threadId":"01a0d610-155f-7391-843e-120bf1475357","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-sol"}}}}} {"type":"emit_inbound","label":"thread/started","frame":{"method":"thread/started","params":{"thread":{"id":"01a0d610-155f-7391-843e-120bf1475357","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d610-155f-7391-843e-120bf1475357","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-sol","reasoningEffort":null,"createdAt":1790297773,"updatedAt":1790297773,"recencyAt":1790297773,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-56-13-01a0d610-155f-7391-843e-120bf1475357.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]}},"emittedAtMs":1790297773588}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0d610-155f-7391-843e-120bf1475357","name":"codex_apps","status":"starting","error":null,"failureReason":null},"emittedAtMs":1790297773588}} {"type":"emit_inbound","label":"thread/settings/updated","frame":{"method":"thread/settings/updated","params":{"threadId":"01a0d610-155f-7391-843e-120bf1475357","threadSettings":{"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","approvalPolicy":"never","approvalsReviewer":"user","sandboxPolicy":{"type":"dangerFullAccess"},"activePermissionProfile":null,"model":"gpt-6-sol","modelProvider":"openai","serviceTier":null,"effort":null,"summary":"detailed","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-sol","reasoning_effort":null,"developer_instructions":null}},"multiAgentMode":"explicitRequestOnly","personality":null}},"emittedAtMs":1790297773608}} -{"type":"emit_inbound","label":"turn/start","frame":{"id":5,"result":{"turn":{"id":"01a0d610-1619-7d91-bae2-ec4a7b899193","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} +{"type":"emit_inbound","label":"turn/start","frame":{"id":6,"result":{"turn":{"id":"01a0d610-1619-7d91-bae2-ec4a7b899193","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d610-155f-7391-843e-120bf1475357","status":{"type":"active","activeFlags":[]}},"emittedAtMs":1790297773650}} {"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"01a0d610-155f-7391-843e-120bf1475357","turn":{"id":"01a0d610-1619-7d91-bae2-ec4a7b899193","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1790297773,"completedAt":null,"durationMs":null}},"emittedAtMs":1790297773650}} {"type":"emit_inbound","label":"account/updated","frame":{"method":"account/updated","params":{"authMode":"chatgpt","planType":"unknown"},"emittedAtMs":1790297773993}} @@ -32,22 +34,24 @@ {"type":"emit_inbound","label":"thread/tokenUsage/updated","frame":{"method":"thread/tokenUsage/updated","params":{"threadId":"01a0d610-155f-7391-843e-120bf1475357","turnId":"01a0d610-1619-7d91-bae2-ec4a7b899193","tokenUsage":{"total":{"totalTokens":17752,"inputTokens":17744,"cachedInputTokens":14848,"cacheWriteInputTokens":0,"outputTokens":8,"reasoningOutputTokens":0},"last":{"totalTokens":17752,"inputTokens":17744,"cachedInputTokens":14848,"cacheWriteInputTokens":0,"outputTokens":8,"reasoningOutputTokens":0},"modelContextWindow":258400}},"emittedAtMs":1790297778003}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d610-155f-7391-843e-120bf1475357","status":{"type":"idle"}},"emittedAtMs":1790297778011}} {"type":"emit_inbound","label":"turn/completed","frame":{"method":"turn/completed","params":{"threadId":"01a0d610-155f-7391-843e-120bf1475357","turn":{"id":"01a0d610-1619-7d91-bae2-ec4a7b899193","items":[{"type":"agentMessage","id":"msg_0c4d0b070a58ed52016ab5c6b1b0fc87d0a540ea4be4112eb0","text":"merge sibling source stored","phase":"final_answer","memoryCitation":null,"delivery":null,"questions":null}],"itemsView":"summary","status":"completed","error":null,"startedAt":1790297773,"completedAt":1790297778,"durationMs":4400}},"emittedAtMs":1790297778011}} -{"type":"expect_outbound","label":"thread/fork","frame":{"id":6,"method":"thread/fork","params":{"config":{"tools.update_plan.enabled":true,"mcp_optional_startup_grace_ms":10000,"features.concurrent_reasoning_summaries":true},"cwd":"","excludeTurns":true,"lastTurnId":"01a0d610-1619-7d91-bae2-ec4a7b899193","model":"gpt-6-sol","threadId":"01a0d610-155f-7391-843e-120bf1475357"}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":7,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":7,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"thread/fork","frame":{"id":8,"method":"thread/fork","params":{"config":{"tools.update_plan.enabled":true,"mcp_optional_startup_grace_ms":10000,"features.concurrent_reasoning_summaries":true},"cwd":"","excludeTurns":true,"lastTurnId":"01a0d610-1619-7d91-bae2-ec4a7b899193","model":"gpt-6-sol","threadId":"01a0d610-155f-7391-843e-120bf1475357"}}} {"type":"emit_inbound","label":"deprecationNotice","frame":{"method":"deprecationNotice","params":{"summary":"Full-history hydration is deprecated for paginated threads; use `excludeTurns: true`, then page with `thread/turns/list` and `thread/items/list`.","details":null},"emittedAtMs":1790297778016}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0d610-155f-7391-843e-120bf1475357","name":"xcodebuildmcp","status":"ready","error":null,"failureReason":null},"emittedAtMs":1790297778263}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0d610-2789-7bb3-a492-ad7fa8a7db9c","name":"codex_apps","status":"starting","error":null,"failureReason":null},"emittedAtMs":1790297778313}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0d610-2789-7bb3-a492-ad7fa8a7db9c","name":"xcodebuildmcp","status":"starting","error":null,"failureReason":null},"emittedAtMs":1790297778313}} -{"type":"emit_inbound","label":"thread/fork","frame":{"id":6,"result":{"thread":{"id":"01a0d610-2789-7bb3-a492-ad7fa8a7db9c","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d610-2789-7bb3-a492-ad7fa8a7db9c","forkedFromId":"01a0d610-155f-7391-843e-120bf1475357","parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-sol","reasoningEffort":null,"createdAt":1790297778,"updatedAt":1790297778,"recencyAt":1790297778,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-56-18-01a0d610-2789-7bb3-a492-ad7fa8a7db9c.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":{"sha":"1563a64b41d5e7e2e640b46f52cee724913f8851","branch":"v2/codex-gpt6-luna-rerecord","originUrl":"https://github.com/pingdotgg/t3code.git"},"name":null,"daybreakEnabled":null,"turns":[{"id":"01a0d610-1619-7d91-bae2-ec4a7b899193","items":[{"type":"userMessage","id":"01a0d610-1f48-7281-871b-c5d12ab0a228","clientId":null,"content":[{"type":"text","text":"Remember the opaque marker merge-sibling-source-3C7K for later in this conversation. Respond with exactly: merge sibling source stored","text_elements":[]}]},{"type":"agentMessage","id":"msg_0c4d0b070a58ed52016ab5c6b1b0fc87d0a540ea4be4112eb0","text":"merge sibling source stored","phase":"final_answer","memoryCitation":null,"delivery":null,"questions":null}],"itemsView":"full","status":"completed","error":null,"startedAt":1790297773,"completedAt":1790297778,"durationMs":4400}]},"model":"gpt-6-sol","modelProvider":"openai","serviceTier":null,"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"],"instructionSources":["/home/replay-user/.codex/AGENTS.md"],"approvalPolicy":"never","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":{"id":":workspace","extends":null},"reasoningEffort":null,"multiAgentMode":"explicitRequestOnly"}}} -{"type":"expect_outbound","label":"thread/name/set","frame":{"id":7,"method":"thread/name/set","params":{"name":"First merge-back sibling","threadId":"01a0d610-2789-7bb3-a492-ad7fa8a7db9c"}}} -{"type":"emit_inbound","label":"thread/name/set","frame":{"id":7,"result":{}}} +{"type":"emit_inbound","label":"thread/fork","frame":{"id":8,"result":{"thread":{"id":"01a0d610-2789-7bb3-a492-ad7fa8a7db9c","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d610-2789-7bb3-a492-ad7fa8a7db9c","forkedFromId":"01a0d610-155f-7391-843e-120bf1475357","parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-sol","reasoningEffort":null,"createdAt":1790297778,"updatedAt":1790297778,"recencyAt":1790297778,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-56-18-01a0d610-2789-7bb3-a492-ad7fa8a7db9c.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":{"sha":"1563a64b41d5e7e2e640b46f52cee724913f8851","branch":"v2/codex-gpt6-luna-rerecord","originUrl":"https://github.com/pingdotgg/t3code.git"},"name":null,"daybreakEnabled":null,"turns":[{"id":"01a0d610-1619-7d91-bae2-ec4a7b899193","items":[{"type":"userMessage","id":"01a0d610-1f48-7281-871b-c5d12ab0a228","clientId":null,"content":[{"type":"text","text":"Remember the opaque marker merge-sibling-source-3C7K for later in this conversation. Respond with exactly: merge sibling source stored","text_elements":[]}]},{"type":"agentMessage","id":"msg_0c4d0b070a58ed52016ab5c6b1b0fc87d0a540ea4be4112eb0","text":"merge sibling source stored","phase":"final_answer","memoryCitation":null,"delivery":null,"questions":null}],"itemsView":"full","status":"completed","error":null,"startedAt":1790297773,"completedAt":1790297778,"durationMs":4400}]},"model":"gpt-6-sol","modelProvider":"openai","serviceTier":null,"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"],"instructionSources":["/home/replay-user/.codex/AGENTS.md"],"approvalPolicy":"never","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":{"id":":workspace","extends":null},"reasoningEffort":null,"multiAgentMode":"explicitRequestOnly"}}} +{"type":"expect_outbound","label":"thread/name/set","frame":{"id":9,"method":"thread/name/set","params":{"name":"First merge-back sibling","threadId":"01a0d610-2789-7bb3-a492-ad7fa8a7db9c"}}} +{"type":"emit_inbound","label":"thread/name/set","frame":{"id":9,"result":{}}} {"type":"emit_inbound","label":"thread/name/updated","frame":{"method":"thread/name/updated","params":{"threadId":"01a0d610-2789-7bb3-a492-ad7fa8a7db9c","threadName":"First merge-back sibling"}}} -{"type":"expect_outbound","label":"config/read","frame":{"id":8,"method":"config/read","params":{"cwd":"","includeLayers":false}}} -{"type":"emit_inbound","label":"config/read","frame":{"id":8,"result":{"config":{},"origins":{}}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":9,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Remember the fork-local marker merge-sibling-first-6V2J. Respond with exactly: first merge sibling stored","type":"text"}],"model":"gpt-6-sol","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"auto","threadId":"01a0d610-2789-7bb3-a492-ad7fa8a7db9c","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-sol"}}}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":10,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":10,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":11,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Remember the fork-local marker merge-sibling-first-6V2J. Respond with exactly: first merge sibling stored","type":"text"}],"model":"gpt-6-sol","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"auto","threadId":"01a0d610-2789-7bb3-a492-ad7fa8a7db9c","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-sol"}}}}} {"type":"emit_inbound","label":"thread/tokenUsage/updated","frame":{"method":"thread/tokenUsage/updated","params":{"threadId":"01a0d610-2789-7bb3-a492-ad7fa8a7db9c","turnId":"01a0d610-1619-7d91-bae2-ec4a7b899193","tokenUsage":{"total":{"totalTokens":17752,"inputTokens":17744,"cachedInputTokens":14848,"cacheWriteInputTokens":0,"outputTokens":8,"reasoningOutputTokens":0},"last":{"totalTokens":17752,"inputTokens":17744,"cachedInputTokens":14848,"cacheWriteInputTokens":0,"outputTokens":8,"reasoningOutputTokens":0},"modelContextWindow":258400}},"emittedAtMs":1790297778338}} {"type":"emit_inbound","label":"thread/started","frame":{"method":"thread/started","params":{"thread":{"id":"01a0d610-2789-7bb3-a492-ad7fa8a7db9c","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d610-2789-7bb3-a492-ad7fa8a7db9c","forkedFromId":"01a0d610-155f-7391-843e-120bf1475357","parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-sol","reasoningEffort":null,"createdAt":1790297778,"updatedAt":1790297778,"recencyAt":1790297778,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-56-18-01a0d610-2789-7bb3-a492-ad7fa8a7db9c.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":{"sha":"1563a64b41d5e7e2e640b46f52cee724913f8851","branch":"v2/codex-gpt6-luna-rerecord","originUrl":"https://github.com/pingdotgg/t3code.git"},"name":null,"daybreakEnabled":null,"turns":[]}},"emittedAtMs":1790297778338}} {"type":"emit_inbound","label":"thread/settings/updated","frame":{"method":"thread/settings/updated","params":{"threadId":"01a0d610-2789-7bb3-a492-ad7fa8a7db9c","threadSettings":{"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","approvalPolicy":"never","approvalsReviewer":"user","sandboxPolicy":{"type":"dangerFullAccess"},"activePermissionProfile":null,"model":"gpt-6-sol","modelProvider":"openai","serviceTier":null,"effort":null,"summary":"detailed","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-sol","reasoning_effort":null,"developer_instructions":null}},"multiAgentMode":"explicitRequestOnly","personality":null}},"emittedAtMs":1790297778364}} -{"type":"emit_inbound","label":"turn/start","frame":{"id":9,"result":{"turn":{"id":"01a0d610-28ad-7071-82a1-f55ea8178ae8","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} +{"type":"emit_inbound","label":"turn/start","frame":{"id":11,"result":{"turn":{"id":"01a0d610-28ad-7071-82a1-f55ea8178ae8","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d610-2789-7bb3-a492-ad7fa8a7db9c","status":{"type":"active","activeFlags":[]}},"emittedAtMs":1790297778383}} {"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"01a0d610-2789-7bb3-a492-ad7fa8a7db9c","turn":{"id":"01a0d610-28ad-7071-82a1-f55ea8178ae8","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1790297778,"completedAt":null,"durationMs":null}},"emittedAtMs":1790297778383}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0d610-2789-7bb3-a492-ad7fa8a7db9c","name":"codex_apps","status":"ready","error":null,"failureReason":null},"emittedAtMs":1790297779053}} @@ -62,21 +66,23 @@ {"type":"emit_inbound","label":"thread/tokenUsage/updated","frame":{"method":"thread/tokenUsage/updated","params":{"threadId":"01a0d610-2789-7bb3-a492-ad7fa8a7db9c","turnId":"01a0d610-28ad-7071-82a1-f55ea8178ae8","tokenUsage":{"total":{"totalTokens":39723,"inputTokens":39707,"cachedInputTokens":26624,"cacheWriteInputTokens":0,"outputTokens":16,"reasoningOutputTokens":0},"last":{"totalTokens":21971,"inputTokens":21963,"cachedInputTokens":11776,"cacheWriteInputTokens":0,"outputTokens":8,"reasoningOutputTokens":0},"modelContextWindow":258400}},"emittedAtMs":1790297782125}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d610-2789-7bb3-a492-ad7fa8a7db9c","status":{"type":"idle"}},"emittedAtMs":1790297782161}} {"type":"emit_inbound","label":"turn/completed","frame":{"method":"turn/completed","params":{"threadId":"01a0d610-2789-7bb3-a492-ad7fa8a7db9c","turn":{"id":"01a0d610-28ad-7071-82a1-f55ea8178ae8","items":[{"type":"agentMessage","id":"msg_0c4d0b070a58ed52016ab5c6b5b44c87d08e7e5612c5312499","text":"first merge sibling stored","phase":"final_answer","memoryCitation":null,"delivery":null,"questions":null}],"itemsView":"summary","status":"completed","error":null,"startedAt":1790297778,"completedAt":1790297782,"durationMs":3783}},"emittedAtMs":1790297782161}} -{"type":"expect_outbound","label":"thread/fork","frame":{"id":10,"method":"thread/fork","params":{"config":{"tools.update_plan.enabled":true,"mcp_optional_startup_grace_ms":10000,"features.concurrent_reasoning_summaries":true},"cwd":"","excludeTurns":true,"lastTurnId":"01a0d610-1619-7d91-bae2-ec4a7b899193","model":"gpt-6-sol","threadId":"01a0d610-155f-7391-843e-120bf1475357"}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":12,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":12,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"thread/fork","frame":{"id":13,"method":"thread/fork","params":{"config":{"tools.update_plan.enabled":true,"mcp_optional_startup_grace_ms":10000,"features.concurrent_reasoning_summaries":true},"cwd":"","excludeTurns":true,"lastTurnId":"01a0d610-1619-7d91-bae2-ec4a7b899193","model":"gpt-6-sol","threadId":"01a0d610-155f-7391-843e-120bf1475357"}}} {"type":"emit_inbound","label":"deprecationNotice","frame":{"method":"deprecationNotice","params":{"summary":"Full-history hydration is deprecated for paginated threads; use `excludeTurns: true`, then page with `thread/turns/list` and `thread/items/list`.","details":null},"emittedAtMs":1790297782170}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0d610-37d1-7ba1-918f-136cfdbd9bfd","name":"xcodebuildmcp","status":"starting","error":null,"failureReason":null},"emittedAtMs":1790297782559}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0d610-37d1-7ba1-918f-136cfdbd9bfd","name":"codex_apps","status":"starting","error":null,"failureReason":null},"emittedAtMs":1790297782559}} -{"type":"emit_inbound","label":"thread/fork","frame":{"id":10,"result":{"thread":{"id":"01a0d610-37d1-7ba1-918f-136cfdbd9bfd","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d610-37d1-7ba1-918f-136cfdbd9bfd","forkedFromId":"01a0d610-155f-7391-843e-120bf1475357","parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-sol","reasoningEffort":null,"createdAt":1790297782,"updatedAt":1790297782,"recencyAt":1790297782,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-56-22-01a0d610-37d1-7ba1-918f-136cfdbd9bfd.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":{"sha":"1563a64b41d5e7e2e640b46f52cee724913f8851","branch":"v2/codex-gpt6-luna-rerecord","originUrl":"https://github.com/pingdotgg/t3code.git"},"name":null,"daybreakEnabled":null,"turns":[{"id":"01a0d610-1619-7d91-bae2-ec4a7b899193","items":[{"type":"userMessage","id":"01a0d610-1f48-7281-871b-c5d12ab0a228","clientId":null,"content":[{"type":"text","text":"Remember the opaque marker merge-sibling-source-3C7K for later in this conversation. Respond with exactly: merge sibling source stored","text_elements":[]}]},{"type":"agentMessage","id":"msg_0c4d0b070a58ed52016ab5c6b1b0fc87d0a540ea4be4112eb0","text":"merge sibling source stored","phase":"final_answer","memoryCitation":null,"delivery":null,"questions":null}],"itemsView":"full","status":"completed","error":null,"startedAt":1790297773,"completedAt":1790297778,"durationMs":4400}]},"model":"gpt-6-sol","modelProvider":"openai","serviceTier":null,"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"],"instructionSources":["/home/replay-user/.codex/AGENTS.md"],"approvalPolicy":"never","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":{"id":":workspace","extends":null},"reasoningEffort":null,"multiAgentMode":"explicitRequestOnly"}}} -{"type":"expect_outbound","label":"thread/name/set","frame":{"id":11,"method":"thread/name/set","params":{"name":"Second merge-back sibling","threadId":"01a0d610-37d1-7ba1-918f-136cfdbd9bfd"}}} -{"type":"emit_inbound","label":"thread/name/set","frame":{"id":11,"result":{}}} +{"type":"emit_inbound","label":"thread/fork","frame":{"id":13,"result":{"thread":{"id":"01a0d610-37d1-7ba1-918f-136cfdbd9bfd","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d610-37d1-7ba1-918f-136cfdbd9bfd","forkedFromId":"01a0d610-155f-7391-843e-120bf1475357","parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-sol","reasoningEffort":null,"createdAt":1790297782,"updatedAt":1790297782,"recencyAt":1790297782,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-56-22-01a0d610-37d1-7ba1-918f-136cfdbd9bfd.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":{"sha":"1563a64b41d5e7e2e640b46f52cee724913f8851","branch":"v2/codex-gpt6-luna-rerecord","originUrl":"https://github.com/pingdotgg/t3code.git"},"name":null,"daybreakEnabled":null,"turns":[{"id":"01a0d610-1619-7d91-bae2-ec4a7b899193","items":[{"type":"userMessage","id":"01a0d610-1f48-7281-871b-c5d12ab0a228","clientId":null,"content":[{"type":"text","text":"Remember the opaque marker merge-sibling-source-3C7K for later in this conversation. Respond with exactly: merge sibling source stored","text_elements":[]}]},{"type":"agentMessage","id":"msg_0c4d0b070a58ed52016ab5c6b1b0fc87d0a540ea4be4112eb0","text":"merge sibling source stored","phase":"final_answer","memoryCitation":null,"delivery":null,"questions":null}],"itemsView":"full","status":"completed","error":null,"startedAt":1790297773,"completedAt":1790297778,"durationMs":4400}]},"model":"gpt-6-sol","modelProvider":"openai","serviceTier":null,"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"],"instructionSources":["/home/replay-user/.codex/AGENTS.md"],"approvalPolicy":"never","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":{"id":":workspace","extends":null},"reasoningEffort":null,"multiAgentMode":"explicitRequestOnly"}}} +{"type":"expect_outbound","label":"thread/name/set","frame":{"id":14,"method":"thread/name/set","params":{"name":"Second merge-back sibling","threadId":"01a0d610-37d1-7ba1-918f-136cfdbd9bfd"}}} +{"type":"emit_inbound","label":"thread/name/set","frame":{"id":14,"result":{}}} {"type":"emit_inbound","label":"thread/name/updated","frame":{"method":"thread/name/updated","params":{"threadId":"01a0d610-37d1-7ba1-918f-136cfdbd9bfd","threadName":"Second merge-back sibling"}}} -{"type":"expect_outbound","label":"config/read","frame":{"id":12,"method":"config/read","params":{"cwd":"","includeLayers":false}}} -{"type":"emit_inbound","label":"config/read","frame":{"id":12,"result":{"config":{},"origins":{}}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":13,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Remember the fork-local marker merge-sibling-second-9X5B. Respond with exactly: second merge sibling stored","type":"text"}],"model":"gpt-6-sol","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"auto","threadId":"01a0d610-37d1-7ba1-918f-136cfdbd9bfd","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-sol"}}}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":15,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":15,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":16,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Remember the fork-local marker merge-sibling-second-9X5B. Respond with exactly: second merge sibling stored","type":"text"}],"model":"gpt-6-sol","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"auto","threadId":"01a0d610-37d1-7ba1-918f-136cfdbd9bfd","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-sol"}}}}} {"type":"emit_inbound","label":"thread/tokenUsage/updated","frame":{"method":"thread/tokenUsage/updated","params":{"threadId":"01a0d610-37d1-7ba1-918f-136cfdbd9bfd","turnId":"01a0d610-1619-7d91-bae2-ec4a7b899193","tokenUsage":{"total":{"totalTokens":17752,"inputTokens":17744,"cachedInputTokens":14848,"cacheWriteInputTokens":0,"outputTokens":8,"reasoningOutputTokens":0},"last":{"totalTokens":17752,"inputTokens":17744,"cachedInputTokens":14848,"cacheWriteInputTokens":0,"outputTokens":8,"reasoningOutputTokens":0},"modelContextWindow":258400}},"emittedAtMs":1790297782630}} {"type":"emit_inbound","label":"thread/started","frame":{"method":"thread/started","params":{"thread":{"id":"01a0d610-37d1-7ba1-918f-136cfdbd9bfd","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d610-37d1-7ba1-918f-136cfdbd9bfd","forkedFromId":"01a0d610-155f-7391-843e-120bf1475357","parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-sol","reasoningEffort":null,"createdAt":1790297782,"updatedAt":1790297782,"recencyAt":1790297782,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-56-22-01a0d610-37d1-7ba1-918f-136cfdbd9bfd.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":{"sha":"1563a64b41d5e7e2e640b46f52cee724913f8851","branch":"v2/codex-gpt6-luna-rerecord","originUrl":"https://github.com/pingdotgg/t3code.git"},"name":null,"daybreakEnabled":null,"turns":[]}},"emittedAtMs":1790297782630}} {"type":"emit_inbound","label":"thread/settings/updated","frame":{"method":"thread/settings/updated","params":{"threadId":"01a0d610-37d1-7ba1-918f-136cfdbd9bfd","threadSettings":{"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","approvalPolicy":"never","approvalsReviewer":"user","sandboxPolicy":{"type":"dangerFullAccess"},"activePermissionProfile":null,"model":"gpt-6-sol","modelProvider":"openai","serviceTier":null,"effort":null,"summary":"detailed","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-sol","reasoning_effort":null,"developer_instructions":null}},"multiAgentMode":"explicitRequestOnly","personality":null}},"emittedAtMs":1790297782690}} -{"type":"emit_inbound","label":"turn/start","frame":{"id":13,"result":{"turn":{"id":"01a0d610-398b-7ea0-b252-1ba58fc7d14d","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} +{"type":"emit_inbound","label":"turn/start","frame":{"id":16,"result":{"turn":{"id":"01a0d610-398b-7ea0-b252-1ba58fc7d14d","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d610-37d1-7ba1-918f-136cfdbd9bfd","status":{"type":"active","activeFlags":[]}},"emittedAtMs":1790297782728}} {"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"01a0d610-37d1-7ba1-918f-136cfdbd9bfd","turn":{"id":"01a0d610-398b-7ea0-b252-1ba58fc7d14d","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1790297782,"completedAt":null,"durationMs":null}},"emittedAtMs":1790297782728}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0d610-2789-7bb3-a492-ad7fa8a7db9c","name":"xcodebuildmcp","status":"ready","error":null,"failureReason":null},"emittedAtMs":1790297782926}} @@ -92,10 +98,10 @@ {"type":"emit_inbound","label":"thread/tokenUsage/updated","frame":{"method":"thread/tokenUsage/updated","params":{"threadId":"01a0d610-37d1-7ba1-918f-136cfdbd9bfd","turnId":"01a0d610-398b-7ea0-b252-1ba58fc7d14d","tokenUsage":{"total":{"totalTokens":39723,"inputTokens":39707,"cachedInputTokens":32384,"cacheWriteInputTokens":0,"outputTokens":16,"reasoningOutputTokens":0},"last":{"totalTokens":21971,"inputTokens":21963,"cachedInputTokens":17536,"cacheWriteInputTokens":0,"outputTokens":8,"reasoningOutputTokens":0},"modelContextWindow":258400}},"emittedAtMs":1790297786356}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d610-37d1-7ba1-918f-136cfdbd9bfd","status":{"type":"idle"}},"emittedAtMs":1790297786381}} {"type":"emit_inbound","label":"turn/completed","frame":{"method":"turn/completed","params":{"threadId":"01a0d610-37d1-7ba1-918f-136cfdbd9bfd","turn":{"id":"01a0d610-398b-7ea0-b252-1ba58fc7d14d","items":[{"type":"agentMessage","id":"msg_0c4d0b070a58ed52016ab5c6b9e23887d0aead55548c08d807","text":"second merge sibling stored","phase":"final_answer","memoryCitation":null,"delivery":null,"questions":null}],"itemsView":"summary","status":"completed","error":null,"startedAt":1790297782,"completedAt":1790297786,"durationMs":3683}},"emittedAtMs":1790297786381}} -{"type":"expect_outbound","label":"config/read","frame":{"id":14,"method":"config/read","params":{"cwd":"","includeLayers":false}}} -{"type":"emit_inbound","label":"config/read","frame":{"id":14,"result":{"config":{},"origins":{}}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":15,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Context handoff (merge_back / fork_delta_summary):\nMerge-back context from first forked conversation.\n\nFork delta:\n- User introduced opaque marker merge-sibling-first-6V2J.\n- Assistant confirmed: first merge sibling stored\n\nUser message:\nRetain the first transferred marker for later. Respond with exactly: first merge delta stored","type":"text"}],"model":"gpt-6-sol","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"auto","threadId":"01a0d610-155f-7391-843e-120bf1475357","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-sol"}}}}} -{"type":"emit_inbound","label":"turn/start","frame":{"id":15,"result":{"turn":{"id":"01a0d610-481e-7522-ab04-234cac3907b5","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":17,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":17,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":18,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Context handoff (merge_back / fork_delta_summary):\nMerge-back context from first forked conversation.\n\nFork delta:\n- User introduced opaque marker merge-sibling-first-6V2J.\n- Assistant confirmed: first merge sibling stored\n\nUser message:\nRetain the first transferred marker for later. Respond with exactly: first merge delta stored","type":"text"}],"model":"gpt-6-sol","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"auto","threadId":"01a0d610-155f-7391-843e-120bf1475357","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-sol"}}}}} +{"type":"emit_inbound","label":"turn/start","frame":{"id":18,"result":{"turn":{"id":"01a0d610-481e-7522-ab04-234cac3907b5","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d610-155f-7391-843e-120bf1475357","status":{"type":"active","activeFlags":[]}},"emittedAtMs":1790297786444}} {"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"01a0d610-155f-7391-843e-120bf1475357","turn":{"id":"01a0d610-481e-7522-ab04-234cac3907b5","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1790297786,"completedAt":null,"durationMs":null}},"emittedAtMs":1790297786444}} {"type":"emit_inbound","label":"item/started","frame":{"method":"item/started","params":{"item":{"type":"userMessage","id":"01a0d610-48e6-7791-90d7-390fdc407d60","clientId":null,"content":[{"type":"text","text":"Context handoff (merge_back / fork_delta_summary):\nMerge-back context from first forked conversation.\n\nFork delta:\n- User introduced opaque marker merge-sibling-first-6V2J.\n- Assistant confirmed: first merge sibling stored\n\nUser message:\nRetain the first transferred marker for later. Respond with exactly: first merge delta stored","text_elements":[]}]},"threadId":"01a0d610-155f-7391-843e-120bf1475357","turnId":"01a0d610-481e-7522-ab04-234cac3907b5","startedAtMs":1790297786608},"emittedAtMs":1790297786608}} @@ -114,10 +120,10 @@ {"type":"emit_inbound","label":"thread/tokenUsage/updated","frame":{"method":"thread/tokenUsage/updated","params":{"threadId":"01a0d610-155f-7391-843e-120bf1475357","turnId":"01a0d610-481e-7522-ab04-234cac3907b5","tokenUsage":{"total":{"totalTokens":39782,"inputTokens":39751,"cachedInputTokens":32384,"cacheWriteInputTokens":0,"outputTokens":31,"reasoningOutputTokens":13},"last":{"totalTokens":22030,"inputTokens":22007,"cachedInputTokens":17536,"cacheWriteInputTokens":0,"outputTokens":23,"reasoningOutputTokens":13},"modelContextWindow":258400}},"emittedAtMs":1790297790394}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d610-155f-7391-843e-120bf1475357","status":{"type":"idle"}},"emittedAtMs":1790297790409}} {"type":"emit_inbound","label":"turn/completed","frame":{"method":"turn/completed","params":{"threadId":"01a0d610-155f-7391-843e-120bf1475357","turn":{"id":"01a0d610-481e-7522-ab04-234cac3907b5","items":[{"type":"agentMessage","id":"msg_0c4d0b070a58ed52016ab5c6be15bc87d0b5c0c3a9a6045bbb","text":"first merge delta stored","phase":"final_answer","memoryCitation":null,"delivery":null,"questions":null}],"itemsView":"summary","status":"completed","error":null,"startedAt":1790297786,"completedAt":1790297790,"durationMs":3979}},"emittedAtMs":1790297790409}} -{"type":"expect_outbound","label":"config/read","frame":{"id":16,"method":"config/read","params":{"cwd":"","includeLayers":false}}} -{"type":"emit_inbound","label":"config/read","frame":{"id":16,"result":{"config":{},"origins":{}}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":17,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Context handoff (merge_back / fork_delta_summary):\nMerge-back context from second forked conversation.\n\nFork delta:\n- User introduced opaque marker merge-sibling-second-9X5B.\n- Assistant confirmed: second merge sibling stored\n\nUser message:\nRetain the second transferred marker for later. Respond with exactly: second merge delta stored","type":"text"}],"model":"gpt-6-sol","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"auto","threadId":"01a0d610-155f-7391-843e-120bf1475357","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-sol"}}}}} -{"type":"emit_inbound","label":"turn/start","frame":{"id":17,"result":{"turn":{"id":"01a0d610-57d2-7671-858a-d9e868574664","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":19,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":19,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":20,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Context handoff (merge_back / fork_delta_summary):\nMerge-back context from second forked conversation.\n\nFork delta:\n- User introduced opaque marker merge-sibling-second-9X5B.\n- Assistant confirmed: second merge sibling stored\n\nUser message:\nRetain the second transferred marker for later. Respond with exactly: second merge delta stored","type":"text"}],"model":"gpt-6-sol","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"auto","threadId":"01a0d610-155f-7391-843e-120bf1475357","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-sol"}}}}} +{"type":"emit_inbound","label":"turn/start","frame":{"id":20,"result":{"turn":{"id":"01a0d610-57d2-7671-858a-d9e868574664","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d610-155f-7391-843e-120bf1475357","status":{"type":"active","activeFlags":[]}},"emittedAtMs":1790297790438}} {"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"01a0d610-155f-7391-843e-120bf1475357","turn":{"id":"01a0d610-57d2-7671-858a-d9e868574664","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1790297790,"completedAt":null,"durationMs":null}},"emittedAtMs":1790297790438}} {"type":"emit_inbound","label":"item/started","frame":{"method":"item/started","params":{"item":{"type":"userMessage","id":"01a0d610-5897-7993-b78c-2e5977b826e8","clientId":null,"content":[{"type":"text","text":"Context handoff (merge_back / fork_delta_summary):\nMerge-back context from second forked conversation.\n\nFork delta:\n- User introduced opaque marker merge-sibling-second-9X5B.\n- Assistant confirmed: second merge sibling stored\n\nUser message:\nRetain the second transferred marker for later. Respond with exactly: second merge delta stored","text_elements":[]}]},"threadId":"01a0d610-155f-7391-843e-120bf1475357","turnId":"01a0d610-57d2-7671-858a-d9e868574664","startedAtMs":1790297790625},"emittedAtMs":1790297790625}} @@ -131,10 +137,10 @@ {"type":"emit_inbound","label":"thread/tokenUsage/updated","frame":{"method":"thread/tokenUsage/updated","params":{"threadId":"01a0d610-155f-7391-843e-120bf1475357","turnId":"01a0d610-57d2-7671-858a-d9e868574664","tokenUsage":{"total":{"totalTokens":61893,"inputTokens":61854,"cachedInputTokens":54272,"cacheWriteInputTokens":0,"outputTokens":39,"reasoningOutputTokens":13},"last":{"totalTokens":22111,"inputTokens":22103,"cachedInputTokens":21888,"cacheWriteInputTokens":0,"outputTokens":8,"reasoningOutputTokens":0},"modelContextWindow":258400}},"emittedAtMs":1790297793240}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d610-155f-7391-843e-120bf1475357","status":{"type":"idle"}},"emittedAtMs":1790297793249}} {"type":"emit_inbound","label":"turn/completed","frame":{"method":"turn/completed","params":{"threadId":"01a0d610-155f-7391-843e-120bf1475357","turn":{"id":"01a0d610-57d2-7671-858a-d9e868574664","items":[{"type":"agentMessage","id":"msg_0c4d0b070a58ed52016ab5c6c071ec87d0ad6a38add1f18e1a","text":"second merge delta stored","phase":"final_answer","memoryCitation":null,"delivery":null,"questions":null}],"itemsView":"summary","status":"completed","error":null,"startedAt":1790297790,"completedAt":1790297793,"durationMs":2814}},"emittedAtMs":1790297793249}} -{"type":"expect_outbound","label":"config/read","frame":{"id":18,"method":"config/read","params":{"cwd":"","includeLayers":false}}} -{"type":"emit_inbound","label":"config/read","frame":{"id":18,"result":{"config":{},"origins":{}}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":19,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Return the source marker followed by both transferred fork markers in merge order, separated by single | characters. Respond with only the markers and separators.","type":"text"}],"model":"gpt-6-sol","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"auto","threadId":"01a0d610-155f-7391-843e-120bf1475357","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-sol"}}}}} -{"type":"emit_inbound","label":"turn/start","frame":{"id":19,"result":{"turn":{"id":"01a0d610-62e7-7610-9b44-1d654367e4bf","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":21,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":21,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":22,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Return the source marker followed by both transferred fork markers in merge order, separated by single | characters. Respond with only the markers and separators.","type":"text"}],"model":"gpt-6-sol","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"auto","threadId":"01a0d610-155f-7391-843e-120bf1475357","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-sol"}}}}} +{"type":"emit_inbound","label":"turn/start","frame":{"id":22,"result":{"turn":{"id":"01a0d610-62e7-7610-9b44-1d654367e4bf","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d610-155f-7391-843e-120bf1475357","status":{"type":"active","activeFlags":[]}},"emittedAtMs":1790297793308}} {"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"01a0d610-155f-7391-843e-120bf1475357","turn":{"id":"01a0d610-62e7-7610-9b44-1d654367e4bf","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1790297793,"completedAt":null,"durationMs":null}},"emittedAtMs":1790297793308}} {"type":"emit_inbound","label":"item/started","frame":{"method":"item/started","params":{"item":{"type":"userMessage","id":"01a0d610-63a5-7aa0-bdd9-6d0a56bf21e7","clientId":null,"content":[{"type":"text","text":"Return the source marker followed by both transferred fork markers in merge order, separated by single | characters. Respond with only the markers and separators.","text_elements":[]}]},"threadId":"01a0d610-155f-7391-843e-120bf1475357","turnId":"01a0d610-62e7-7610-9b44-1d654367e4bf","startedAtMs":1790297793453},"emittedAtMs":1790297793453}} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/thread_rollback/codex_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/thread_rollback/codex_transcript.ndjson index ba52432940a03..3bb8185a7390b 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/thread_rollback/codex_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/thread_rollback/codex_transcript.ndjson @@ -2,20 +2,22 @@ {"type":"expect_outbound","label":"initialize","frame":{"id":1,"method":"initialize","params":{"capabilities":{"experimentalApi":true,"optOutNotificationMethods":["turn/diff/updated"],"extensions":{"io.modelcontextprotocol/ui":{"mimeTypes":["text/html;profile=mcp-app"]}}},"clientInfo":{"name":"T3 Code","title":"T3 Code","version":"0.0.44"}}}} {"type":"emit_inbound","label":"initialize","frame":{"id":1,"result":{"userAgent":"t3code_desktop/0.156.1 (Debian 13.0.0; x86_64) unknown (t3code_desktop; 0.1.0)","codexHome":"/home/replay-user/.codex","platformFamily":"unix","platformOs":"linux"}}} {"type":"expect_outbound","label":"initialized","frame":{"method":"initialized"}} -{"type":"expect_outbound","label":"thread/start","frame":{"id":2,"method":"thread/start","params":{"config":{"tools.update_plan.enabled":true,"mcp_optional_startup_grace_ms":10000,"features.concurrent_reasoning_summaries":true},"cwd":"","model":"gpt-6-luna"}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":2,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":2,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"thread/start","frame":{"id":3,"method":"thread/start","params":{"config":{"tools.update_plan.enabled":true,"mcp_optional_startup_grace_ms":10000,"features.concurrent_reasoning_summaries":true},"cwd":"","model":"gpt-6-luna"}}} {"type":"emit_inbound","label":"configWarning","frame":{"method":"configWarning","params":{"summary":"Codex could not find bubblewrap on PATH. Install bubblewrap with your OS package manager. See the sandbox prerequisites: https://developers.openai.com/codex/concepts/sandboxing#prerequisites. Codex will use the bundled bubblewrap in the meantime.","details":null},"emittedAtMs":1790295644807}} {"type":"emit_inbound","label":"remoteControl/status/changed","frame":{"method":"remoteControl/status/changed","params":{"status":"disabled","serverName":"replay-host","installationId":"00000000-0000-4000-8000-000000000000","environmentId":null},"emittedAtMs":1790295644807}} -{"type":"emit_inbound","label":"thread/start","frame":{"id":2,"result":{"thread":{"id":"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790295644,"updatedAt":1790295644,"recencyAt":1790295644,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-20-44-01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]},"model":"gpt-6-luna","modelProvider":"openai","serviceTier":null,"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"],"instructionSources":["/home/replay-user/.codex/AGENTS.md","/home/replay-user/t3code/AGENTS.md"],"approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":{"id":":workspace","extends":null},"reasoningEffort":null,"multiAgentMode":"explicitRequestOnly"}}} -{"type":"expect_outbound","label":"thread/name/set","frame":{"id":3,"method":"thread/name/set","params":{"name":"Replay fixture: thread_rollback","threadId":"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff"}}} -{"type":"emit_inbound","label":"thread/name/set","frame":{"id":3,"result":{}}} +{"type":"emit_inbound","label":"thread/start","frame":{"id":3,"result":{"thread":{"id":"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790295644,"updatedAt":1790295644,"recencyAt":1790295644,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-20-44-01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]},"model":"gpt-6-luna","modelProvider":"openai","serviceTier":null,"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"],"instructionSources":["/home/replay-user/.codex/AGENTS.md","/home/replay-user/t3code/AGENTS.md"],"approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":{"id":":workspace","extends":null},"reasoningEffort":null,"multiAgentMode":"explicitRequestOnly"}}} +{"type":"expect_outbound","label":"thread/name/set","frame":{"id":4,"method":"thread/name/set","params":{"name":"Replay fixture: thread_rollback","threadId":"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff"}}} +{"type":"emit_inbound","label":"thread/name/set","frame":{"id":4,"result":{}}} {"type":"emit_inbound","label":"thread/name/updated","frame":{"method":"thread/name/updated","params":{"threadId":"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff","threadName":"Replay fixture: thread_rollback"}}} -{"type":"expect_outbound","label":"config/read","frame":{"id":4,"method":"config/read","params":{"cwd":"","includeLayers":false}}} -{"type":"emit_inbound","label":"config/read","frame":{"id":4,"result":{"config":{},"origins":{}}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":5,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Respond with exactly: rollback fixture first turn complete","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"auto","threadId":"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":5,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":5,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":6,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Respond with exactly: rollback fixture first turn complete","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"auto","threadId":"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} {"type":"emit_inbound","label":"thread/started","frame":{"method":"thread/started","params":{"thread":{"id":"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790295644,"updatedAt":1790295644,"recencyAt":1790295644,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-20-44-01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]}},"emittedAtMs":1790295645009}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff","name":"codex_apps","status":"starting","error":null,"failureReason":null},"emittedAtMs":1790295645009}} {"type":"emit_inbound","label":"thread/settings/updated","frame":{"method":"thread/settings/updated","params":{"threadId":"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff","threadSettings":{"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","approvalPolicy":"never","approvalsReviewer":"user","sandboxPolicy":{"type":"dangerFullAccess"},"activePermissionProfile":null,"model":"gpt-6-luna","modelProvider":"openai","serviceTier":null,"effort":null,"summary":"detailed","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna","reasoning_effort":null,"developer_instructions":null}},"multiAgentMode":"explicitRequestOnly","personality":null}},"emittedAtMs":1790295645023}} -{"type":"emit_inbound","label":"turn/start","frame":{"id":5,"result":{"turn":{"id":"01a0d5ef-9b58-7980-9e7a-2463dd068a8e","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} +{"type":"emit_inbound","label":"turn/start","frame":{"id":6,"result":{"turn":{"id":"01a0d5ef-9b58-7980-9e7a-2463dd068a8e","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff","status":{"type":"active","activeFlags":[]}},"emittedAtMs":1790295645070}} {"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff","turn":{"id":"01a0d5ef-9b58-7980-9e7a-2463dd068a8e","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1790295645,"completedAt":null,"durationMs":null}},"emittedAtMs":1790295645070}} {"type":"emit_inbound","label":"account/updated","frame":{"method":"account/updated","params":{"authMode":"chatgpt","planType":"unknown"},"emittedAtMs":1790295645465}} @@ -33,10 +35,10 @@ {"type":"emit_inbound","label":"thread/tokenUsage/updated","frame":{"method":"thread/tokenUsage/updated","params":{"threadId":"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff","turnId":"01a0d5ef-9b58-7980-9e7a-2463dd068a8e","tokenUsage":{"total":{"totalTokens":21428,"inputTokens":21419,"cachedInputTokens":21248,"cacheWriteInputTokens":0,"outputTokens":9,"reasoningOutputTokens":0},"last":{"totalTokens":21428,"inputTokens":21419,"cachedInputTokens":21248,"cacheWriteInputTokens":0,"outputTokens":9,"reasoningOutputTokens":0},"modelContextWindow":258400}},"emittedAtMs":1790295649339}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff","status":{"type":"idle"}},"emittedAtMs":1790295649352}} {"type":"emit_inbound","label":"turn/completed","frame":{"method":"turn/completed","params":{"threadId":"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff","turn":{"id":"01a0d5ef-9b58-7980-9e7a-2463dd068a8e","items":[{"type":"agentMessage","id":"msg_044082e5a0068297016ab5be60f20c87d0aed9858a5d1f00b2","text":"rollback fixture first turn complete","phase":"final_answer","memoryCitation":null,"delivery":null,"questions":null}],"itemsView":"summary","status":"completed","error":null,"startedAt":1790295645,"completedAt":1790295649,"durationMs":4326}},"emittedAtMs":1790295649352}} -{"type":"expect_outbound","label":"config/read","frame":{"id":6,"method":"config/read","params":{"cwd":"","includeLayers":false}}} -{"type":"emit_inbound","label":"config/read","frame":{"id":6,"result":{"config":{},"origins":{}}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":7,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Respond with exactly: rollback fixture second turn complete","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"auto","threadId":"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} -{"type":"emit_inbound","label":"turn/start","frame":{"id":7,"result":{"turn":{"id":"01a0d5ef-ac4e-7471-a4a8-6776e39e6d29","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":7,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":7,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":8,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Respond with exactly: rollback fixture second turn complete","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"auto","threadId":"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} +{"type":"emit_inbound","label":"turn/start","frame":{"id":8,"result":{"turn":{"id":"01a0d5ef-ac4e-7471-a4a8-6776e39e6d29","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff","status":{"type":"active","activeFlags":[]}},"emittedAtMs":1790295649424}} {"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff","turn":{"id":"01a0d5ef-ac4e-7471-a4a8-6776e39e6d29","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1790295649,"completedAt":null,"durationMs":null}},"emittedAtMs":1790295649424}} {"type":"emit_inbound","label":"item/started","frame":{"method":"item/started","params":{"item":{"type":"userMessage","id":"01a0d5ef-ad0e-78d0-af5c-7145f750bd81","clientId":null,"content":[{"type":"text","text":"Respond with exactly: rollback fixture second turn complete","text_elements":[]}]},"threadId":"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff","turnId":"01a0d5ef-ac4e-7471-a4a8-6776e39e6d29","startedAtMs":1790295649555},"emittedAtMs":1790295649555}} @@ -52,21 +54,21 @@ {"type":"emit_inbound","label":"thread/tokenUsage/updated","frame":{"method":"thread/tokenUsage/updated","params":{"threadId":"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff","turnId":"01a0d5ef-ac4e-7471-a4a8-6776e39e6d29","tokenUsage":{"total":{"totalTokens":47217,"inputTokens":47199,"cachedInputTokens":42496,"cacheWriteInputTokens":0,"outputTokens":18,"reasoningOutputTokens":0},"last":{"totalTokens":25789,"inputTokens":25780,"cachedInputTokens":21248,"cacheWriteInputTokens":0,"outputTokens":9,"reasoningOutputTokens":0},"modelContextWindow":258400}},"emittedAtMs":1790295651330}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff","status":{"type":"idle"}},"emittedAtMs":1790295651335}} {"type":"emit_inbound","label":"turn/completed","frame":{"method":"turn/completed","params":{"threadId":"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff","turn":{"id":"01a0d5ef-ac4e-7471-a4a8-6776e39e6d29","items":[{"type":"agentMessage","id":"msg_044082e5a0068297016ab5be62fefc87d0bbf3fdbed6561ac8","text":"rollback fixture second turn complete","phase":"final_answer","memoryCitation":null,"delivery":null,"questions":null}],"itemsView":"summary","status":"completed","error":null,"startedAt":1790295649,"completedAt":1790295651,"durationMs":1931}},"emittedAtMs":1790295651335}} -{"type":"expect_outbound","label":"thread/read","frame":{"id":8,"method":"thread/read","params":{"includeTurns":false,"threadId":"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff"}}} -{"type":"emit_inbound","label":"thread/read","frame":{"id":8,"result":{"thread":{"id":"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff","forkedFromId":null,"parentThreadId":null,"preview":"Respond with exactly: rollback fixture first turn complete","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790295644,"updatedAt":1790295651,"recencyAt":1790295649,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-20-44-01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":{"sha":"1563a64b41d5e7e2e640b46f52cee724913f8851","branch":"v2/codex-gpt6-luna-rerecord","originUrl":"https://github.com/pingdotgg/t3code.git"},"name":null,"daybreakEnabled":null,"turns":[]}}}} -{"type":"expect_outbound","label":"thread/turns/list","frame":{"id":9,"method":"thread/turns/list","params":{"cursor":null,"itemsView":"summary","limit":1,"sortDirection":"desc","threadId":"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff"}}} -{"type":"emit_inbound","label":"thread/turns/list","frame":{"id":9,"result":{"data":[{"id":"01a0d5ef-ac4e-7471-a4a8-6776e39e6d29","items":[{"type":"userMessage","id":"01a0d5ef-ad0e-78d0-af5c-7145f750bd81","clientId":null,"content":[{"type":"text","text":"Respond with exactly: rollback fixture second turn complete","text_elements":[]}]},{"type":"agentMessage","id":"msg_044082e5a0068297016ab5be62fefc87d0bbf3fdbed6561ac8","text":"rollback fixture second turn complete","phase":"final_answer","memoryCitation":null,"delivery":null,"questions":null}],"itemsView":"summary","status":"completed","error":null,"startedAt":1790295649,"completedAt":1790295651,"durationMs":1931}],"nextCursor":"{\"requestedThreadId\":\"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff\",\"rolloutOrdinal\":16,\"includeAnchor\":false,\"scope\":{\"kind\":\"turns\"}}","backwardsCursor":"{\"requestedThreadId\":\"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff\",\"rolloutOrdinal\":16,\"includeAnchor\":true,\"scope\":{\"kind\":\"turns\"}}"}}} -{"type":"expect_outbound","label":"thread/revert","frame":{"id":10,"method":"thread/revert","params":{"beforeTurnId":"01a0d5ef-ac4e-7471-a4a8-6776e39e6d29","threadId":"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff"}}} +{"type":"expect_outbound","label":"thread/read","frame":{"id":9,"method":"thread/read","params":{"includeTurns":false,"threadId":"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff"}}} +{"type":"emit_inbound","label":"thread/read","frame":{"id":9,"result":{"thread":{"id":"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff","forkedFromId":null,"parentThreadId":null,"preview":"Respond with exactly: rollback fixture first turn complete","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790295644,"updatedAt":1790295651,"recencyAt":1790295649,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-20-44-01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":{"sha":"1563a64b41d5e7e2e640b46f52cee724913f8851","branch":"v2/codex-gpt6-luna-rerecord","originUrl":"https://github.com/pingdotgg/t3code.git"},"name":null,"daybreakEnabled":null,"turns":[]}}}} +{"type":"expect_outbound","label":"thread/turns/list","frame":{"id":10,"method":"thread/turns/list","params":{"cursor":null,"itemsView":"summary","limit":1,"sortDirection":"desc","threadId":"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff"}}} +{"type":"emit_inbound","label":"thread/turns/list","frame":{"id":10,"result":{"data":[{"id":"01a0d5ef-ac4e-7471-a4a8-6776e39e6d29","items":[{"type":"userMessage","id":"01a0d5ef-ad0e-78d0-af5c-7145f750bd81","clientId":null,"content":[{"type":"text","text":"Respond with exactly: rollback fixture second turn complete","text_elements":[]}]},{"type":"agentMessage","id":"msg_044082e5a0068297016ab5be62fefc87d0bbf3fdbed6561ac8","text":"rollback fixture second turn complete","phase":"final_answer","memoryCitation":null,"delivery":null,"questions":null}],"itemsView":"summary","status":"completed","error":null,"startedAt":1790295649,"completedAt":1790295651,"durationMs":1931}],"nextCursor":"{\"requestedThreadId\":\"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff\",\"rolloutOrdinal\":16,\"includeAnchor\":false,\"scope\":{\"kind\":\"turns\"}}","backwardsCursor":"{\"requestedThreadId\":\"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff\",\"rolloutOrdinal\":16,\"includeAnchor\":true,\"scope\":{\"kind\":\"turns\"}}"}}} +{"type":"expect_outbound","label":"thread/revert","frame":{"id":11,"method":"thread/revert","params":{"beforeTurnId":"01a0d5ef-ac4e-7471-a4a8-6776e39e6d29","threadId":"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff"}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff","status":{"type":"notLoaded"}},"emittedAtMs":1790295651358}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff","name":"xcodebuildmcp","status":"starting","error":null,"failureReason":null},"emittedAtMs":1790295651544}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff","name":"codex_apps","status":"starting","error":null,"failureReason":null},"emittedAtMs":1790295651544}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff","status":{"type":"idle"}},"emittedAtMs":1790295651551}} -{"type":"emit_inbound","label":"thread/revert","frame":{"id":10,"result":{"thread":{"id":"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff","forkedFromId":null,"parentThreadId":null,"preview":"Respond with exactly: rollback fixture first turn complete","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790295651,"updatedAt":1790295651,"recencyAt":1790295649,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-20-51-01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff_01a0d5ef-b424-72f2-9853-9b112f028a71.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":{"sha":"1563a64b41d5e7e2e640b46f52cee724913f8851","branch":"v2/codex-gpt6-luna-rerecord","originUrl":"https://github.com/pingdotgg/t3code.git"},"name":null,"daybreakEnabled":null,"turns":[]},"turnsBackwardsCursor":"{\"requestedThreadId\":\"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff\",\"rolloutOrdinal\":1,\"includeAnchor\":true,\"scope\":{\"kind\":\"turns\"}}","itemsBackwardsCursor":"{\"requestedThreadId\":\"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff\",\"rolloutOrdinal\":10,\"includeAnchor\":true,\"scope\":{\"kind\":\"itemsByCreatedAtOrdinal\"}}"}}} -{"type":"expect_outbound","label":"config/read","frame":{"id":11,"method":"config/read","params":{"cwd":"","includeLayers":false}}} -{"type":"emit_inbound","label":"config/read","frame":{"id":11,"result":{"config":{},"origins":{}}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":12,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Repeat the conversation verbatim.","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"auto","threadId":"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} +{"type":"emit_inbound","label":"thread/revert","frame":{"id":11,"result":{"thread":{"id":"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff","forkedFromId":null,"parentThreadId":null,"preview":"Respond with exactly: rollback fixture first turn complete","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790295651,"updatedAt":1790295651,"recencyAt":1790295649,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-20-51-01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff_01a0d5ef-b424-72f2-9853-9b112f028a71.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":{"sha":"1563a64b41d5e7e2e640b46f52cee724913f8851","branch":"v2/codex-gpt6-luna-rerecord","originUrl":"https://github.com/pingdotgg/t3code.git"},"name":null,"daybreakEnabled":null,"turns":[]},"turnsBackwardsCursor":"{\"requestedThreadId\":\"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff\",\"rolloutOrdinal\":1,\"includeAnchor\":true,\"scope\":{\"kind\":\"turns\"}}","itemsBackwardsCursor":"{\"requestedThreadId\":\"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff\",\"rolloutOrdinal\":10,\"includeAnchor\":true,\"scope\":{\"kind\":\"itemsByCreatedAtOrdinal\"}}"}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":12,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":12,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":13,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Repeat the conversation verbatim.","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"auto","threadId":"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} {"type":"emit_inbound","label":"thread/reverted","frame":{"method":"thread/reverted","params":{"threadId":"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff"},"emittedAtMs":1790295651568}} -{"type":"emit_inbound","label":"turn/start","frame":{"id":12,"result":{"turn":{"id":"01a0d5ef-b4f4-7aa2-b4c2-f5f494881401","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} +{"type":"emit_inbound","label":"turn/start","frame":{"id":13,"result":{"turn":{"id":"01a0d5ef-b4f4-7aa2-b4c2-f5f494881401","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff","status":{"type":"active","activeFlags":[]}},"emittedAtMs":1790295651594}} {"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff","turn":{"id":"01a0d5ef-b4f4-7aa2-b4c2-f5f494881401","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1790295651,"completedAt":null,"durationMs":null}},"emittedAtMs":1790295651594}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff","name":"codex_apps","status":"ready","error":null,"failureReason":null},"emittedAtMs":1790295652127}} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/thread_rollback_after_restart/codex_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/thread_rollback_after_restart/codex_transcript.ndjson index 4083e4f61f3f7..086462cb51e05 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/thread_rollback_after_restart/codex_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/thread_rollback_after_restart/codex_transcript.ndjson @@ -2,20 +2,22 @@ {"type":"expect_outbound","label":"initialize","frame":{"id":1,"method":"initialize","params":{"capabilities":{"experimentalApi":true,"optOutNotificationMethods":["turn/diff/updated"],"extensions":{"io.modelcontextprotocol/ui":{"mimeTypes":["text/html;profile=mcp-app"]}}},"clientInfo":{"name":"T3 Code","title":"T3 Code","version":"0.0.44"}}}} {"type":"emit_inbound","label":"initialize","frame":{"id":1,"result":{"userAgent":"t3code_desktop/0.156.1 (Debian 13.0.0; x86_64) unknown (t3code_desktop; 0.1.0)","codexHome":"/home/replay-user/tmp/bughunt-codex/codex-home","platformFamily":"unix","platformOs":"linux"}}} {"type":"expect_outbound","label":"initialized","frame":{"method":"initialized"}} -{"type":"expect_outbound","label":"thread/start","frame":{"id":2,"method":"thread/start","params":{"config":{"tools.update_plan.enabled":true,"mcp_optional_startup_grace_ms":10000,"features.concurrent_reasoning_summaries":true},"cwd":"","model":"gpt-6-luna"}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":2,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":2,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"thread/start","frame":{"id":3,"method":"thread/start","params":{"config":{"tools.update_plan.enabled":true,"mcp_optional_startup_grace_ms":10000,"features.concurrent_reasoning_summaries":true},"cwd":"","model":"gpt-6-luna"}}} {"type":"emit_inbound","label":"configWarning","frame":{"method":"configWarning","params":{"summary":"Codex could not find bubblewrap on PATH. Install bubblewrap with your OS package manager. See the sandbox prerequisites: https://developers.openai.com/codex/concepts/sandboxing#prerequisites. Codex will use the bundled bubblewrap in the meantime.","details":null},"emittedAtMs":1790404926353}} {"type":"emit_inbound","label":"remoteControl/status/changed","frame":{"method":"remoteControl/status/changed","params":{"status":"disabled","serverName":"replay-host","installationId":"00000000-0000-4000-8000-000000000000","environmentId":null},"emittedAtMs":1790404926353}} -{"type":"emit_inbound","label":"thread/start","frame":{"id":2,"result":{"thread":{"id":"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/apps/server","runtimeWorkspaceRoots":["/home/replay-user/t3code/apps/server"]}],"extra":null,"sessionId":"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790404926,"updatedAt":1790404926,"recencyAt":1790404926,"status":{"type":"idle"},"path":"/home/replay-user/tmp/bughunt-codex/codex-home/sessions/2026/09/25/rollout-2026-09-25T23-42-06-01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a.jsonl","cwd":"/home/replay-user/t3code/apps/server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]},"model":"gpt-6-luna","modelProvider":"openai","serviceTier":null,"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/apps/server","runtimeWorkspaceRoots":["/home/replay-user/t3code/apps/server"],"instructionSources":["/home/replay-user/t3code/AGENTS.md"],"approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":{"id":":workspace","extends":null},"reasoningEffort":null,"multiAgentMode":"explicitRequestOnly"}}} -{"type":"expect_outbound","label":"thread/name/set","frame":{"id":3,"method":"thread/name/set","params":{"name":"Replay fixture: thread_rollback_after_restart","threadId":"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a"}}} -{"type":"emit_inbound","label":"thread/name/set","frame":{"id":3,"result":{}}} +{"type":"emit_inbound","label":"thread/start","frame":{"id":3,"result":{"thread":{"id":"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/apps/server","runtimeWorkspaceRoots":["/home/replay-user/t3code/apps/server"]}],"extra":null,"sessionId":"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790404926,"updatedAt":1790404926,"recencyAt":1790404926,"status":{"type":"idle"},"path":"/home/replay-user/tmp/bughunt-codex/codex-home/sessions/2026/09/25/rollout-2026-09-25T23-42-06-01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a.jsonl","cwd":"/home/replay-user/t3code/apps/server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]},"model":"gpt-6-luna","modelProvider":"openai","serviceTier":null,"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/apps/server","runtimeWorkspaceRoots":["/home/replay-user/t3code/apps/server"],"instructionSources":["/home/replay-user/t3code/AGENTS.md"],"approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":{"id":":workspace","extends":null},"reasoningEffort":null,"multiAgentMode":"explicitRequestOnly"}}} +{"type":"expect_outbound","label":"thread/name/set","frame":{"id":4,"method":"thread/name/set","params":{"name":"Replay fixture: thread_rollback_after_restart","threadId":"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a"}}} +{"type":"emit_inbound","label":"thread/name/set","frame":{"id":4,"result":{}}} {"type":"emit_inbound","label":"thread/name/updated","frame":{"method":"thread/name/updated","params":{"threadId":"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a","threadName":"Replay fixture: thread_rollback_after_restart"}}} -{"type":"expect_outbound","label":"config/read","frame":{"id":4,"method":"config/read","params":{"cwd":"","includeLayers":false}}} -{"type":"emit_inbound","label":"config/read","frame":{"id":4,"result":{"config":{},"origins":{}}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":5,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Respond with exactly: rollback fixture first turn complete","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"auto","threadId":"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":5,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":5,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":6,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Respond with exactly: rollback fixture first turn complete","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"auto","threadId":"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} {"type":"emit_inbound","label":"thread/started","frame":{"method":"thread/started","params":{"thread":{"id":"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/apps/server","runtimeWorkspaceRoots":["/home/replay-user/t3code/apps/server"]}],"extra":null,"sessionId":"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790404926,"updatedAt":1790404926,"recencyAt":1790404926,"status":{"type":"idle"},"path":"/home/replay-user/tmp/bughunt-codex/codex-home/sessions/2026/09/25/rollout-2026-09-25T23-42-06-01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a.jsonl","cwd":"/home/replay-user/t3code/apps/server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]}},"emittedAtMs":1790404926549}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a","name":"codex_apps","status":"starting","error":null,"failureReason":null},"emittedAtMs":1790404926550}} {"type":"emit_inbound","label":"thread/settings/updated","frame":{"method":"thread/settings/updated","params":{"threadId":"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a","threadSettings":{"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/apps/server","approvalPolicy":"never","approvalsReviewer":"user","sandboxPolicy":{"type":"dangerFullAccess"},"activePermissionProfile":null,"model":"gpt-6-luna","modelProvider":"openai","serviceTier":null,"effort":null,"summary":"detailed","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna","reasoning_effort":null,"developer_instructions":null}},"multiAgentMode":"explicitRequestOnly","personality":null}},"emittedAtMs":1790404926569}} -{"type":"emit_inbound","label":"turn/start","frame":{"id":5,"result":{"turn":{"id":"01a0dc73-1c60-70a3-9a3c-d54c0020efa2","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} +{"type":"emit_inbound","label":"turn/start","frame":{"id":6,"result":{"turn":{"id":"01a0dc73-1c60-70a3-9a3c-d54c0020efa2","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a","status":{"type":"active","activeFlags":[]}},"emittedAtMs":1790404926645}} {"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a","turn":{"id":"01a0dc73-1c60-70a3-9a3c-d54c0020efa2","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1790404926,"completedAt":null,"durationMs":null}},"emittedAtMs":1790404926645}} {"type":"emit_inbound","label":"account/updated","frame":{"method":"account/updated","params":{"authMode":"chatgpt","planType":"unknown"},"emittedAtMs":1790404926921}} @@ -33,10 +35,10 @@ {"type":"emit_inbound","label":"thread/tokenUsage/updated","frame":{"method":"thread/tokenUsage/updated","params":{"threadId":"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a","turnId":"01a0dc73-1c60-70a3-9a3c-d54c0020efa2","tokenUsage":{"total":{"totalTokens":19805,"inputTokens":19796,"cachedInputTokens":0,"cacheWriteInputTokens":0,"outputTokens":9,"reasoningOutputTokens":0},"last":{"totalTokens":19805,"inputTokens":19796,"cachedInputTokens":0,"cacheWriteInputTokens":0,"outputTokens":9,"reasoningOutputTokens":0},"modelContextWindow":258400}},"emittedAtMs":1790404930976}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a","status":{"type":"idle"}},"emittedAtMs":1790404931000}} {"type":"emit_inbound","label":"turn/completed","frame":{"method":"turn/completed","params":{"threadId":"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a","turn":{"id":"01a0dc73-1c60-70a3-9a3c-d54c0020efa2","items":[{"type":"agentMessage","id":"msg_0f3ce1c685f16088016ab7694298d087d0a53f8de6070d33ad","text":"rollback fixture first turn complete","phase":"final_answer","memoryCitation":null,"delivery":null,"questions":null}],"itemsView":"summary","status":"completed","error":null,"startedAt":1790404926,"completedAt":1790404930,"durationMs":4426}},"emittedAtMs":1790404931000}} -{"type":"expect_outbound","label":"config/read","frame":{"id":6,"method":"config/read","params":{"cwd":"","includeLayers":false}}} -{"type":"emit_inbound","label":"config/read","frame":{"id":6,"result":{"config":{},"origins":{}}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":7,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Respond with exactly: rollback fixture second turn complete","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"auto","threadId":"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} -{"type":"emit_inbound","label":"turn/start","frame":{"id":7,"result":{"turn":{"id":"01a0dc73-2dc4-7911-a448-c66b9bf3318b","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":7,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":7,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":8,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Respond with exactly: rollback fixture second turn complete","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"auto","threadId":"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} +{"type":"emit_inbound","label":"turn/start","frame":{"id":8,"result":{"turn":{"id":"01a0dc73-2dc4-7911-a448-c66b9bf3318b","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a","status":{"type":"active","activeFlags":[]}},"emittedAtMs":1790404931059}} {"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a","turn":{"id":"01a0dc73-2dc4-7911-a448-c66b9bf3318b","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1790404931,"completedAt":null,"durationMs":null}},"emittedAtMs":1790404931059}} {"type":"emit_inbound","label":"item/started","frame":{"method":"item/started","params":{"item":{"type":"userMessage","id":"01a0dc73-2e86-7131-a632-7a2b7e8186fb","clientId":null,"content":[{"type":"text","text":"Respond with exactly: rollback fixture second turn complete","text_elements":[]}]},"threadId":"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a","turnId":"01a0dc73-2dc4-7911-a448-c66b9bf3318b","startedAtMs":1790404931208},"emittedAtMs":1790404931208}} @@ -59,32 +61,36 @@ {"type":"emit_inbound","label":"configWarning","frame":{"method":"configWarning","params":{"summary":"Codex could not find bubblewrap on PATH. Install bubblewrap with your OS package manager. See the sandbox prerequisites: https://developers.openai.com/codex/concepts/sandboxing#prerequisites. Codex will use the bundled bubblewrap in the meantime.","details":null},"emittedAtMs":1790404935235}} {"type":"emit_inbound","label":"remoteControl/status/changed","frame":{"method":"remoteControl/status/changed","params":{"status":"disabled","serverName":"replay-host","installationId":"00000000-0000-4000-8000-000000000000","environmentId":null},"emittedAtMs":1790404935235}} {"type":"emit_inbound","label":"thread/read","frame":{"id":2,"result":{"thread":{"id":"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a","environments":null,"extra":null,"sessionId":"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a","forkedFromId":null,"parentThreadId":null,"preview":"Respond with exactly: rollback fixture first turn complete","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790404926,"updatedAt":1790404934,"recencyAt":1790404931,"status":{"type":"notLoaded"},"path":"/home/replay-user/tmp/bughunt-codex/codex-home/sessions/2026/09/25/rollout-2026-09-25T23-42-06-01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a.jsonl","cwd":"/home/replay-user/t3code/apps/server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":null,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":{"sha":"70629cdddbe2c29749e8dce588b1828580b2777b","branch":"fix/codex-rollback-resume","originUrl":"https://github.com/pingdotgg/t3code.git"},"name":null,"daybreakEnabled":null,"turns":[]}}}} -{"type":"expect_outbound","label":"thread/resume","frame":{"id":3,"method":"thread/resume","params":{"config":{"tools.update_plan.enabled":true,"mcp_optional_startup_grace_ms":10000,"features.concurrent_reasoning_summaries":true},"cwd":"","excludeTurns":true,"model":"gpt-6-luna","threadId":"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a"}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":3,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":3,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"thread/resume","frame":{"id":4,"method":"thread/resume","params":{"config":{"tools.update_plan.enabled":true,"mcp_optional_startup_grace_ms":10000,"features.concurrent_reasoning_summaries":true},"cwd":"","excludeTurns":true,"model":"gpt-6-luna","threadId":"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a"}}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a","name":"codex_apps","status":"starting","error":null,"failureReason":null},"emittedAtMs":1790404935482}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a","status":{"type":"idle"}},"emittedAtMs":1790404935500}} -{"type":"emit_inbound","label":"thread/resume","frame":{"id":3,"result":{"thread":{"id":"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/apps/server","runtimeWorkspaceRoots":["/home/replay-user/t3code/apps/server"]}],"extra":null,"sessionId":"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a","forkedFromId":null,"parentThreadId":null,"preview":"Respond with exactly: rollback fixture first turn complete","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790404926,"updatedAt":1790404935,"recencyAt":1790404931,"status":{"type":"idle"},"path":"/home/replay-user/tmp/bughunt-codex/codex-home/sessions/2026/09/25/rollout-2026-09-25T23-42-06-01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a.jsonl","cwd":"/home/replay-user/t3code/apps/server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":{"sha":"70629cdddbe2c29749e8dce588b1828580b2777b","branch":"fix/codex-rollback-resume","originUrl":"https://github.com/pingdotgg/t3code.git"},"name":null,"daybreakEnabled":null,"turns":[]},"model":"gpt-6-luna","modelProvider":"openai","serviceTier":null,"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/apps/server","runtimeWorkspaceRoots":["/home/replay-user/t3code/apps/server"],"instructionSources":["/home/replay-user/t3code/AGENTS.md"],"approvalPolicy":"never","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":{"id":":workspace","extends":null},"reasoningEffort":null,"collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna","reasoning_effort":null,"developer_instructions":null}},"multiAgentMode":"explicitRequestOnly","initialTurnsPage":null,"turnsBackwardsCursor":"{\"requestedThreadId\":\"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a\",\"rolloutOrdinal\":16,\"includeAnchor\":true,\"scope\":{\"kind\":\"turns\"}}","itemsBackwardsCursor":"{\"requestedThreadId\":\"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a\",\"rolloutOrdinal\":22,\"includeAnchor\":true,\"scope\":{\"kind\":\"itemsByCreatedAtOrdinal\"}}"}}} -{"type":"expect_outbound","label":"thread/turns/list","frame":{"id":4,"method":"thread/turns/list","params":{"cursor":null,"itemsView":"summary","limit":1,"sortDirection":"desc","threadId":"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a"}}} +{"type":"emit_inbound","label":"thread/resume","frame":{"id":4,"result":{"thread":{"id":"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/apps/server","runtimeWorkspaceRoots":["/home/replay-user/t3code/apps/server"]}],"extra":null,"sessionId":"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a","forkedFromId":null,"parentThreadId":null,"preview":"Respond with exactly: rollback fixture first turn complete","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790404926,"updatedAt":1790404935,"recencyAt":1790404931,"status":{"type":"idle"},"path":"/home/replay-user/tmp/bughunt-codex/codex-home/sessions/2026/09/25/rollout-2026-09-25T23-42-06-01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a.jsonl","cwd":"/home/replay-user/t3code/apps/server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":{"sha":"70629cdddbe2c29749e8dce588b1828580b2777b","branch":"fix/codex-rollback-resume","originUrl":"https://github.com/pingdotgg/t3code.git"},"name":null,"daybreakEnabled":null,"turns":[]},"model":"gpt-6-luna","modelProvider":"openai","serviceTier":null,"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/apps/server","runtimeWorkspaceRoots":["/home/replay-user/t3code/apps/server"],"instructionSources":["/home/replay-user/t3code/AGENTS.md"],"approvalPolicy":"never","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":{"id":":workspace","extends":null},"reasoningEffort":null,"collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna","reasoning_effort":null,"developer_instructions":null}},"multiAgentMode":"explicitRequestOnly","initialTurnsPage":null,"turnsBackwardsCursor":"{\"requestedThreadId\":\"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a\",\"rolloutOrdinal\":16,\"includeAnchor\":true,\"scope\":{\"kind\":\"turns\"}}","itemsBackwardsCursor":"{\"requestedThreadId\":\"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a\",\"rolloutOrdinal\":22,\"includeAnchor\":true,\"scope\":{\"kind\":\"itemsByCreatedAtOrdinal\"}}"}}} +{"type":"expect_outbound","label":"thread/turns/list","frame":{"id":5,"method":"thread/turns/list","params":{"cursor":null,"itemsView":"summary","limit":1,"sortDirection":"desc","threadId":"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a"}}} {"type":"emit_inbound","label":"thread/tokenUsage/updated","frame":{"method":"thread/tokenUsage/updated","params":{"threadId":"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a","turnId":"01a0dc73-2dc4-7911-a448-c66b9bf3318b","tokenUsage":{"total":{"totalTokens":44003,"inputTokens":43985,"cachedInputTokens":19200,"cacheWriteInputTokens":0,"outputTokens":18,"reasoningOutputTokens":0},"last":{"totalTokens":24198,"inputTokens":24189,"cachedInputTokens":19200,"cacheWriteInputTokens":0,"outputTokens":9,"reasoningOutputTokens":0},"modelContextWindow":258400}},"emittedAtMs":1790404935520}} {"type":"emit_inbound","label":"thread/goal/cleared","frame":{"method":"thread/goal/cleared","params":{"threadId":"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a"},"emittedAtMs":1790404935521}} -{"type":"emit_inbound","label":"thread/turns/list","frame":{"id":4,"result":{"data":[{"id":"01a0dc73-2dc4-7911-a448-c66b9bf3318b","items":[{"type":"userMessage","id":"01a0dc73-2e86-7131-a632-7a2b7e8186fb","clientId":null,"content":[{"type":"text","text":"Respond with exactly: rollback fixture second turn complete","text_elements":[]}]},{"type":"agentMessage","id":"msg_0f3ce1c685f16088016ab769447c6087d08bd0018d724b5401","text":"rollback fixture second turn complete","phase":"final_answer","memoryCitation":null,"delivery":null,"questions":null}],"itemsView":"summary","status":"completed","error":null,"startedAt":1790404931,"completedAt":1790404934,"durationMs":3756}],"nextCursor":"{\"requestedThreadId\":\"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a\",\"rolloutOrdinal\":16,\"includeAnchor\":false,\"scope\":{\"kind\":\"turns\"}}","backwardsCursor":"{\"requestedThreadId\":\"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a\",\"rolloutOrdinal\":16,\"includeAnchor\":true,\"scope\":{\"kind\":\"turns\"}}"}}} -{"type":"expect_outbound","label":"thread/revert","frame":{"id":5,"method":"thread/revert","params":{"beforeTurnId":"01a0dc73-2dc4-7911-a448-c66b9bf3318b","threadId":"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a"}}} +{"type":"emit_inbound","label":"thread/turns/list","frame":{"id":5,"result":{"data":[{"id":"01a0dc73-2dc4-7911-a448-c66b9bf3318b","items":[{"type":"userMessage","id":"01a0dc73-2e86-7131-a632-7a2b7e8186fb","clientId":null,"content":[{"type":"text","text":"Respond with exactly: rollback fixture second turn complete","text_elements":[]}]},{"type":"agentMessage","id":"msg_0f3ce1c685f16088016ab769447c6087d08bd0018d724b5401","text":"rollback fixture second turn complete","phase":"final_answer","memoryCitation":null,"delivery":null,"questions":null}],"itemsView":"summary","status":"completed","error":null,"startedAt":1790404931,"completedAt":1790404934,"durationMs":3756}],"nextCursor":"{\"requestedThreadId\":\"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a\",\"rolloutOrdinal\":16,\"includeAnchor\":false,\"scope\":{\"kind\":\"turns\"}}","backwardsCursor":"{\"requestedThreadId\":\"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a\",\"rolloutOrdinal\":16,\"includeAnchor\":true,\"scope\":{\"kind\":\"turns\"}}"}}} +{"type":"expect_outbound","label":"thread/revert","frame":{"id":6,"method":"thread/revert","params":{"beforeTurnId":"01a0dc73-2dc4-7911-a448-c66b9bf3318b","threadId":"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a"}}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a","name":"codex_apps","status":"cancelled","error":null,"failureReason":null},"emittedAtMs":1790404935542}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a","status":{"type":"notLoaded"}},"emittedAtMs":1790404935544}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a","name":"codex_apps","status":"starting","error":null,"failureReason":null},"emittedAtMs":1790404935656}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a","status":{"type":"idle"}},"emittedAtMs":1790404935660}} -{"type":"emit_inbound","label":"thread/revert","frame":{"id":5,"result":{"thread":{"id":"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/apps/server","runtimeWorkspaceRoots":["/home/replay-user/t3code/apps/server"]}],"extra":null,"sessionId":"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a","forkedFromId":null,"parentThreadId":null,"preview":"Respond with exactly: rollback fixture first turn complete","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790404935,"updatedAt":1790404935,"recencyAt":1790404931,"status":{"type":"idle"},"path":"/home/replay-user/tmp/bughunt-codex/codex-home/sessions/2026/09/25/rollout-2026-09-25T23-42-15-01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a_01a0dc73-3f89-7660-9a2a-81865e6273eb.jsonl","cwd":"/home/replay-user/t3code/apps/server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":{"sha":"70629cdddbe2c29749e8dce588b1828580b2777b","branch":"fix/codex-rollback-resume","originUrl":"https://github.com/pingdotgg/t3code.git"},"name":null,"daybreakEnabled":null,"turns":[]},"turnsBackwardsCursor":"{\"requestedThreadId\":\"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a\",\"rolloutOrdinal\":1,\"includeAnchor\":true,\"scope\":{\"kind\":\"turns\"}}","itemsBackwardsCursor":"{\"requestedThreadId\":\"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a\",\"rolloutOrdinal\":10,\"includeAnchor\":true,\"scope\":{\"kind\":\"itemsByCreatedAtOrdinal\"}}"}}} -{"type":"expect_outbound","label":"thread/resume","frame":{"id":6,"method":"thread/resume","params":{"config":{"tools.update_plan.enabled":true,"mcp_optional_startup_grace_ms":10000,"features.concurrent_reasoning_summaries":true},"cwd":"","excludeTurns":true,"model":"gpt-6-luna","threadId":"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a"}}} +{"type":"emit_inbound","label":"thread/revert","frame":{"id":6,"result":{"thread":{"id":"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/apps/server","runtimeWorkspaceRoots":["/home/replay-user/t3code/apps/server"]}],"extra":null,"sessionId":"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a","forkedFromId":null,"parentThreadId":null,"preview":"Respond with exactly: rollback fixture first turn complete","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790404935,"updatedAt":1790404935,"recencyAt":1790404931,"status":{"type":"idle"},"path":"/home/replay-user/tmp/bughunt-codex/codex-home/sessions/2026/09/25/rollout-2026-09-25T23-42-15-01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a_01a0dc73-3f89-7660-9a2a-81865e6273eb.jsonl","cwd":"/home/replay-user/t3code/apps/server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":{"sha":"70629cdddbe2c29749e8dce588b1828580b2777b","branch":"fix/codex-rollback-resume","originUrl":"https://github.com/pingdotgg/t3code.git"},"name":null,"daybreakEnabled":null,"turns":[]},"turnsBackwardsCursor":"{\"requestedThreadId\":\"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a\",\"rolloutOrdinal\":1,\"includeAnchor\":true,\"scope\":{\"kind\":\"turns\"}}","itemsBackwardsCursor":"{\"requestedThreadId\":\"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a\",\"rolloutOrdinal\":10,\"includeAnchor\":true,\"scope\":{\"kind\":\"itemsByCreatedAtOrdinal\"}}"}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":7,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":7,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"thread/resume","frame":{"id":8,"method":"thread/resume","params":{"config":{"tools.update_plan.enabled":true,"mcp_optional_startup_grace_ms":10000,"features.concurrent_reasoning_summaries":true},"cwd":"","excludeTurns":true,"model":"gpt-6-luna","threadId":"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a"}}} {"type":"emit_inbound","label":"thread/reverted","frame":{"method":"thread/reverted","params":{"threadId":"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a"},"emittedAtMs":1790404935694}} -{"type":"emit_inbound","label":"thread/resume","frame":{"id":6,"result":{"thread":{"id":"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/apps/server","runtimeWorkspaceRoots":["/home/replay-user/t3code/apps/server"]}],"extra":null,"sessionId":"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a","forkedFromId":null,"parentThreadId":null,"preview":"Respond with exactly: rollback fixture first turn complete","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790404935,"updatedAt":1790404935,"recencyAt":1790404931,"status":{"type":"idle"},"path":"/home/replay-user/tmp/bughunt-codex/codex-home/sessions/2026/09/25/rollout-2026-09-25T23-42-15-01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a_01a0dc73-3f89-7660-9a2a-81865e6273eb.jsonl","cwd":"/home/replay-user/t3code/apps/server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":{"sha":"70629cdddbe2c29749e8dce588b1828580b2777b","branch":"fix/codex-rollback-resume","originUrl":"https://github.com/pingdotgg/t3code.git"},"name":null,"daybreakEnabled":null,"turns":[]},"model":"gpt-6-luna","modelProvider":"openai","serviceTier":"default","disabledPluginIds":[],"cwd":"/home/replay-user/t3code/apps/server","runtimeWorkspaceRoots":["/home/replay-user/t3code/apps/server"],"instructionSources":["/home/replay-user/t3code/AGENTS.md"],"approvalPolicy":"never","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":{"id":":workspace","extends":null},"reasoningEffort":null,"collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna","reasoning_effort":null,"developer_instructions":null}},"multiAgentMode":"explicitRequestOnly","initialTurnsPage":null,"turnsBackwardsCursor":"{\"requestedThreadId\":\"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a\",\"rolloutOrdinal\":1,\"includeAnchor\":true,\"scope\":{\"kind\":\"turns\"}}","itemsBackwardsCursor":"{\"requestedThreadId\":\"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a\",\"rolloutOrdinal\":10,\"includeAnchor\":true,\"scope\":{\"kind\":\"itemsByCreatedAtOrdinal\"}}"}}} -{"type":"expect_outbound","label":"thread/name/set","frame":{"id":7,"method":"thread/name/set","params":{"name":"Replay fixture: thread_rollback_after_restart","threadId":"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a"}}} -{"type":"emit_inbound","label":"thread/name/set","frame":{"id":7,"result":{}}} +{"type":"emit_inbound","label":"thread/resume","frame":{"id":8,"result":{"thread":{"id":"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/apps/server","runtimeWorkspaceRoots":["/home/replay-user/t3code/apps/server"]}],"extra":null,"sessionId":"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a","forkedFromId":null,"parentThreadId":null,"preview":"Respond with exactly: rollback fixture first turn complete","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790404935,"updatedAt":1790404935,"recencyAt":1790404931,"status":{"type":"idle"},"path":"/home/replay-user/tmp/bughunt-codex/codex-home/sessions/2026/09/25/rollout-2026-09-25T23-42-15-01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a_01a0dc73-3f89-7660-9a2a-81865e6273eb.jsonl","cwd":"/home/replay-user/t3code/apps/server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":{"sha":"70629cdddbe2c29749e8dce588b1828580b2777b","branch":"fix/codex-rollback-resume","originUrl":"https://github.com/pingdotgg/t3code.git"},"name":null,"daybreakEnabled":null,"turns":[]},"model":"gpt-6-luna","modelProvider":"openai","serviceTier":"default","disabledPluginIds":[],"cwd":"/home/replay-user/t3code/apps/server","runtimeWorkspaceRoots":["/home/replay-user/t3code/apps/server"],"instructionSources":["/home/replay-user/t3code/AGENTS.md"],"approvalPolicy":"never","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":{"id":":workspace","extends":null},"reasoningEffort":null,"collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna","reasoning_effort":null,"developer_instructions":null}},"multiAgentMode":"explicitRequestOnly","initialTurnsPage":null,"turnsBackwardsCursor":"{\"requestedThreadId\":\"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a\",\"rolloutOrdinal\":1,\"includeAnchor\":true,\"scope\":{\"kind\":\"turns\"}}","itemsBackwardsCursor":"{\"requestedThreadId\":\"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a\",\"rolloutOrdinal\":10,\"includeAnchor\":true,\"scope\":{\"kind\":\"itemsByCreatedAtOrdinal\"}}"}}} +{"type":"expect_outbound","label":"thread/name/set","frame":{"id":9,"method":"thread/name/set","params":{"name":"Replay fixture: thread_rollback_after_restart","threadId":"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a"}}} +{"type":"emit_inbound","label":"thread/name/set","frame":{"id":9,"result":{}}} {"type":"emit_inbound","label":"thread/name/updated","frame":{"method":"thread/name/updated","params":{"threadId":"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a","threadName":"Replay fixture: thread_rollback_after_restart"}}} -{"type":"expect_outbound","label":"config/read","frame":{"id":8,"method":"config/read","params":{"cwd":"","includeLayers":false}}} -{"type":"emit_inbound","label":"config/read","frame":{"id":8,"result":{"config":{},"origins":{}}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":9,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Repeat the conversation verbatim.","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"auto","threadId":"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":10,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":10,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":11,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Repeat the conversation verbatim.","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"auto","threadId":"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} {"type":"emit_inbound","label":"thread/goal/cleared","frame":{"method":"thread/goal/cleared","params":{"threadId":"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a"},"emittedAtMs":1790404935729}} {"type":"emit_inbound","label":"thread/settings/updated","frame":{"method":"thread/settings/updated","params":{"threadId":"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a","threadSettings":{"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/apps/server","approvalPolicy":"never","approvalsReviewer":"user","sandboxPolicy":{"type":"dangerFullAccess"},"activePermissionProfile":null,"model":"gpt-6-luna","modelProvider":"openai","serviceTier":"default","effort":null,"summary":"detailed","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna","reasoning_effort":null,"developer_instructions":null}},"multiAgentMode":"explicitRequestOnly","personality":null}},"emittedAtMs":1790404935753}} -{"type":"emit_inbound","label":"turn/start","frame":{"id":9,"result":{"turn":{"id":"01a0dc73-4034-7201-88e4-13d0d27303a3","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} +{"type":"emit_inbound","label":"turn/start","frame":{"id":11,"result":{"turn":{"id":"01a0dc73-4034-7201-88e4-13d0d27303a3","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a","status":{"type":"active","activeFlags":[]}},"emittedAtMs":1790404935798}} {"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a","turn":{"id":"01a0dc73-4034-7201-88e4-13d0d27303a3","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1790404935,"completedAt":null,"durationMs":null}},"emittedAtMs":1790404935798}} {"type":"emit_inbound","label":"account/updated","frame":{"method":"account/updated","params":{"authMode":"chatgpt","planType":"unknown"},"emittedAtMs":1790404935820}} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/thread_rollback_to_stopped_turn/codex_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/thread_rollback_to_stopped_turn/codex_transcript.ndjson index 7868924d82823..9b5eece1211e0 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/thread_rollback_to_stopped_turn/codex_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/thread_rollback_to_stopped_turn/codex_transcript.ndjson @@ -2,20 +2,22 @@ {"type":"expect_outbound","label":"initialize","frame":{"id":1,"method":"initialize","params":{"capabilities":{"experimentalApi":true,"optOutNotificationMethods":["turn/diff/updated"],"extensions":{"io.modelcontextprotocol/ui":{"mimeTypes":["text/html;profile=mcp-app"]}}},"clientInfo":{"name":"T3 Code","title":"T3 Code","version":"0.0.44"}}}} {"type":"emit_inbound","label":"initialize","frame":{"id":1,"result":{"userAgent":"t3code_desktop/0.156.1 (Debian 13.0.0; x86_64) unknown (t3code_desktop; 0.1.0)","codexHome":"/home/replay-user/.codex","platformFamily":"unix","platformOs":"linux"}}} {"type":"expect_outbound","label":"initialized","frame":{"method":"initialized"}} -{"type":"expect_outbound","label":"thread/start","frame":{"id":2,"method":"thread/start","params":{"config":{"tools.update_plan.enabled":true,"mcp_optional_startup_grace_ms":10000,"features.concurrent_reasoning_summaries":true},"cwd":"","model":"gpt-6-luna"}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":2,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":2,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"thread/start","frame":{"id":3,"method":"thread/start","params":{"config":{"tools.update_plan.enabled":true,"mcp_optional_startup_grace_ms":10000,"features.concurrent_reasoning_summaries":true},"cwd":"","model":"gpt-6-luna"}}} {"type":"emit_inbound","label":"configWarning","frame":{"method":"configWarning","params":{"summary":"Codex could not find bubblewrap on PATH. Install bubblewrap with your OS package manager. See the sandbox prerequisites: https://developers.openai.com/codex/concepts/sandboxing#prerequisites. Codex will use the bundled bubblewrap in the meantime.","details":null},"emittedAtMs":1790459891821}} {"type":"emit_inbound","label":"remoteControl/status/changed","frame":{"method":"remoteControl/status/changed","params":{"status":"disabled","serverName":"replay-host","installationId":"00000000-0000-4000-8000-000000000000","environmentId":null},"emittedAtMs":1790459891821}} -{"type":"emit_inbound","label":"thread/start","frame":{"id":2,"result":{"thread":{"id":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code","runtimeWorkspaceRoots":["/home/replay-user/t3code"]}],"extra":null,"sessionId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790459892,"updatedAt":1790459892,"recencyAt":1790459892,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/26/rollout-2026-09-26T14-58-12-01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88.jsonl","cwd":"/home/replay-user/t3code","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]},"model":"gpt-6-luna","modelProvider":"openai","serviceTier":null,"disabledPluginIds":[],"cwd":"/home/replay-user/t3code","runtimeWorkspaceRoots":["/home/replay-user/t3code"],"instructionSources":[],"approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":{"id":":workspace","extends":null},"reasoningEffort":null,"multiAgentMode":"explicitRequestOnly"}}} -{"type":"expect_outbound","label":"thread/name/set","frame":{"id":3,"method":"thread/name/set","params":{"name":"Replay fixture: thread_rollback_to_stopped_turn","threadId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88"}}} -{"type":"emit_inbound","label":"thread/name/set","frame":{"id":3,"result":{}}} +{"type":"emit_inbound","label":"thread/start","frame":{"id":3,"result":{"thread":{"id":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code","runtimeWorkspaceRoots":["/home/replay-user/t3code"]}],"extra":null,"sessionId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790459892,"updatedAt":1790459892,"recencyAt":1790459892,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/26/rollout-2026-09-26T14-58-12-01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88.jsonl","cwd":"/home/replay-user/t3code","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]},"model":"gpt-6-luna","modelProvider":"openai","serviceTier":null,"disabledPluginIds":[],"cwd":"/home/replay-user/t3code","runtimeWorkspaceRoots":["/home/replay-user/t3code"],"instructionSources":[],"approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":{"id":":workspace","extends":null},"reasoningEffort":null,"multiAgentMode":"explicitRequestOnly"}}} +{"type":"expect_outbound","label":"thread/name/set","frame":{"id":4,"method":"thread/name/set","params":{"name":"Replay fixture: thread_rollback_to_stopped_turn","threadId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88"}}} +{"type":"emit_inbound","label":"thread/name/set","frame":{"id":4,"result":{}}} {"type":"emit_inbound","label":"thread/name/updated","frame":{"method":"thread/name/updated","params":{"threadId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","threadName":"Replay fixture: thread_rollback_to_stopped_turn"}}} -{"type":"expect_outbound","label":"config/read","frame":{"id":4,"method":"config/read","params":{"cwd":"","includeLayers":false}}} -{"type":"emit_inbound","label":"config/read","frame":{"id":4,"result":{"config":{},"origins":{}}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":5,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Respond with exactly: rollback fixture first turn complete","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"networkAccess":false,"type":"workspaceWrite","writableRoots":[]},"summary":"auto","threadId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":5,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":5,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":6,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Respond with exactly: rollback fixture first turn complete","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"networkAccess":false,"type":"workspaceWrite","writableRoots":[]},"summary":"auto","threadId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} {"type":"emit_inbound","label":"thread/started","frame":{"method":"thread/started","params":{"thread":{"id":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code","runtimeWorkspaceRoots":["/home/replay-user/t3code"]}],"extra":null,"sessionId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790459892,"updatedAt":1790459892,"recencyAt":1790459892,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/26/rollout-2026-09-26T14-58-12-01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88.jsonl","cwd":"/home/replay-user/t3code","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]}},"emittedAtMs":1790459892845}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","name":"codex_apps","status":"starting","error":null,"failureReason":null},"emittedAtMs":1790459892846}} {"type":"emit_inbound","label":"thread/settings/updated","frame":{"method":"thread/settings/updated","params":{"threadId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","threadSettings":{"disabledPluginIds":[],"cwd":"/home/replay-user/t3code","approvalPolicy":"never","approvalsReviewer":"user","sandboxPolicy":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":null,"model":"gpt-6-luna","modelProvider":"openai","serviceTier":null,"effort":null,"summary":"detailed","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna","reasoning_effort":null,"developer_instructions":null}},"multiAgentMode":"explicitRequestOnly","personality":null}},"emittedAtMs":1790459892862}} -{"type":"emit_inbound","label":"turn/start","frame":{"id":5,"result":{"turn":{"id":"01a0dfb9-d479-70c0-9d88-912b52f7f613","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} +{"type":"emit_inbound","label":"turn/start","frame":{"id":6,"result":{"turn":{"id":"01a0dfb9-d479-70c0-9d88-912b52f7f613","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","status":{"type":"active","activeFlags":[]}},"emittedAtMs":1790459892915}} {"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","turn":{"id":"01a0dfb9-d479-70c0-9d88-912b52f7f613","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1790459892,"completedAt":null,"durationMs":null}},"emittedAtMs":1790459892915}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","name":"codex_apps","status":"failed","error":"MCP client for `codex_apps` failed to start: MCP startup failed: handshaking with MCP server failed: Send message error Transport [codex_rmcp_client::event_notification_transport::EventNotificationTransport>>] error: unexpected server response: HTTP 401: {\n \"error\": {\n \"message\": \"Encountered invalidated oauth token for user, failing request\",\n \"type\": null,\n \"code\": \"token_revoked\",\n \"param\": null\n },\n \"status\": 401\n}, when send initialize request: Send message error Transport [codex_rmcp_client::event_notification_transport::EventNotificationTransport>>] error: unexpected server response: HTTP 401: {\n \"error\": {\n \"message\": \"Encountered invalidated oauth token for user, failing request\",\n \"type\": null,\n \"code\": \"token_revoked\",\n \"param\": null\n },\n \"status\": 401\n}, when send initialize request","failureReason":null},"emittedAtMs":1790459893144}} @@ -31,10 +33,10 @@ {"type":"emit_inbound","label":"thread/tokenUsage/updated","frame":{"method":"thread/tokenUsage/updated","params":{"threadId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","turnId":"01a0dfb9-d479-70c0-9d88-912b52f7f613","tokenUsage":{"total":{"totalTokens":15291,"inputTokens":15282,"cachedInputTokens":0,"cacheWriteInputTokens":0,"outputTokens":9,"reasoningOutputTokens":0},"last":{"totalTokens":15291,"inputTokens":15282,"cachedInputTokens":0,"cacheWriteInputTokens":0,"outputTokens":9,"reasoningOutputTokens":0},"modelContextWindow":258400}},"emittedAtMs":1790459897074}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","status":{"type":"idle"}},"emittedAtMs":1790459897082}} {"type":"emit_inbound","label":"turn/completed","frame":{"method":"turn/completed","params":{"threadId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","turn":{"id":"01a0dfb9-d479-70c0-9d88-912b52f7f613","items":[{"type":"agentMessage","id":"msg_0508263b0487774d016ab83ff8973c87d0afab5ac113234803","text":"rollback fixture first turn complete","phase":"final_answer","memoryCitation":null,"delivery":null,"questions":null}],"itemsView":"summary","status":"completed","error":null,"startedAt":1790459892,"completedAt":1790459897,"durationMs":4216}},"emittedAtMs":1790459897082}} -{"type":"expect_outbound","label":"config/read","frame":{"id":6,"method":"config/read","params":{"cwd":"","includeLayers":false}}} -{"type":"emit_inbound","label":"config/read","frame":{"id":6,"result":{"config":{},"origins":{}}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":7,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Run this exact local command: `node -e \"console.log('interrupt fixture tool started'); setTimeout(() => {}, 30000)\"`. Do not answer until it completes, then respond exactly: interrupt fixture should not finish naturally.","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"networkAccess":false,"type":"workspaceWrite","writableRoots":[]},"summary":"auto","threadId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} -{"type":"emit_inbound","label":"turn/start","frame":{"id":7,"result":{"turn":{"id":"01a0dfb9-e509-7001-ba72-fe324f527fb9","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":7,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":7,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":8,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Run this exact local command: `node -e \"console.log('interrupt fixture tool started'); setTimeout(() => {}, 30000)\"`. Do not answer until it completes, then respond exactly: interrupt fixture should not finish naturally.","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"networkAccess":false,"type":"workspaceWrite","writableRoots":[]},"summary":"auto","threadId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} +{"type":"emit_inbound","label":"turn/start","frame":{"id":8,"result":{"turn":{"id":"01a0dfb9-e509-7001-ba72-fe324f527fb9","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","status":{"type":"active","activeFlags":[]}},"emittedAtMs":1790459897121}} {"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","turn":{"id":"01a0dfb9-e509-7001-ba72-fe324f527fb9","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1790459897,"completedAt":null,"durationMs":null}},"emittedAtMs":1790459897121}} {"type":"emit_inbound","label":"item/started","frame":{"method":"item/started","params":{"item":{"type":"userMessage","id":"01a0dfb9-e8f3-7011-a214-7479457edb56","clientId":null,"content":[{"type":"text","text":"Run this exact local command: `node -e \"console.log('interrupt fixture tool started'); setTimeout(() => {}, 30000)\"`. Do not answer until it completes, then respond exactly: interrupt fixture should not finish naturally.","text_elements":[]}]},"threadId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","turnId":"01a0dfb9-e509-7001-ba72-fe324f527fb9","startedAtMs":1790459898101},"emittedAtMs":1790459898101}} @@ -61,19 +63,19 @@ {"type":"emit_inbound","label":"item/agentMessage/delta","frame":{"method":"item/agentMessage/delta","params":{"threadId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","turnId":"01a0dfb9-e509-7001-ba72-fe324f527fb9","itemId":"msg_0508263b0487774d016ab83ffcc71887d0874b12a3fb65dd41","delta":"."},"emittedAtMs":1790459902812}} {"type":"emit_inbound","label":"item/completed","frame":{"method":"item/completed","params":{"item":{"type":"agentMessage","id":"msg_0508263b0487774d016ab83ffcc71887d0874b12a3fb65dd41","text":"I’ll run the command exactly as given and wait for it to exit.","phase":"commentary","memoryCitation":null,"delivery":null,"questions":null},"threadId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","turnId":"01a0dfb9-e509-7001-ba72-fe324f527fb9","completedAtMs":1790459903007},"emittedAtMs":1790459903009}} {"type":"emit_inbound","label":"item/started","frame":{"method":"item/started","params":{"item":{"type":"commandExecution","id":"exec-6964412e-1d91-47b5-8a37-7a669b30c03e","pluginId":null,"scriptPath":null,"command":"/bin/bash -lc \"node -e \\\"console.log('interrupt fixture tool started'); setTimeout(() => {}, 30000)\\\"\"","cwd":"/home/replay-user/t3code","processId":"26675","source":"unifiedExecStartup","status":"inProgress","commandActions":[{"type":"unknown","command":"node -e \"console.log('interrupt fixture tool started'); setTimeout(() => {}, 30000)\""}],"aggregatedOutput":null,"exitCode":null,"durationMs":null},"threadId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","turnId":"01a0dfb9-e509-7001-ba72-fe324f527fb9","startedAtMs":1790459903878},"emittedAtMs":1790459903884}} -{"type":"expect_outbound","label":"turn/interrupt","frame":{"id":8,"method":"turn/interrupt","params":{"threadId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","turnId":"01a0dfb9-e509-7001-ba72-fe324f527fb9"}}} +{"type":"expect_outbound","label":"turn/interrupt","frame":{"id":9,"method":"turn/interrupt","params":{"threadId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","turnId":"01a0dfb9-e509-7001-ba72-fe324f527fb9"}}} {"type":"emit_inbound","label":"thread/tokenUsage/updated","frame":{"method":"thread/tokenUsage/updated","params":{"threadId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","turnId":"01a0dfb9-e509-7001-ba72-fe324f527fb9","tokenUsage":{"total":{"totalTokens":30736,"inputTokens":30626,"cachedInputTokens":15104,"cacheWriteInputTokens":0,"outputTokens":110,"reasoningOutputTokens":15},"last":{"totalTokens":15445,"inputTokens":15344,"cachedInputTokens":15104,"cacheWriteInputTokens":0,"outputTokens":101,"reasoningOutputTokens":15},"modelContextWindow":258400}},"emittedAtMs":1790459903893}} -{"type":"emit_inbound","label":"turn/interrupt","frame":{"id":8,"result":{}}} -{"type":"expect_outbound","label":"thread/backgroundTerminals/terminate","frame":{"id":9,"method":"thread/backgroundTerminals/terminate","params":{"threadId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","processId":"26675"}}} +{"type":"emit_inbound","label":"turn/interrupt","frame":{"id":9,"result":{}}} +{"type":"expect_outbound","label":"thread/backgroundTerminals/terminate","frame":{"id":10,"method":"thread/backgroundTerminals/terminate","params":{"threadId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","processId":"26675"}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","status":{"type":"idle"}},"emittedAtMs":1790459903899}} {"type":"emit_inbound","label":"turn/completed","frame":{"method":"turn/completed","params":{"threadId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","turn":{"id":"01a0dfb9-e509-7001-ba72-fe324f527fb9","items":[],"itemsView":"notLoaded","status":"interrupted","error":null,"startedAt":1790459897,"completedAt":1790459903,"durationMs":6789}},"emittedAtMs":1790459903899}} -{"type":"emit_inbound","label":"thread/backgroundTerminals/terminate","frame":{"id":9,"result":{"terminated":true}}} -{"type":"expect_outbound","label":"config/read","frame":{"id":10,"method":"config/read","params":{"cwd":"","includeLayers":false}}} -{"type":"emit_inbound","label":"config/read","frame":{"id":10,"result":{"config":{},"origins":{}}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":11,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Respond with exactly: rollback fixture second turn complete","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"networkAccess":false,"type":"workspaceWrite","writableRoots":[]},"summary":"auto","threadId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} +{"type":"emit_inbound","label":"thread/backgroundTerminals/terminate","frame":{"id":10,"result":{"terminated":true}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":11,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":11,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":12,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Respond with exactly: rollback fixture second turn complete","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"networkAccess":false,"type":"workspaceWrite","writableRoots":[]},"summary":"auto","threadId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","name":"codex_apps","status":"starting","error":null,"failureReason":null},"emittedAtMs":1790459903907}} {"type":"emit_inbound","label":"item/completed","frame":{"method":"item/completed","params":{"item":{"type":"commandExecution","id":"exec-6964412e-1d91-47b5-8a37-7a669b30c03e","pluginId":null,"scriptPath":null,"command":"/bin/bash -lc \"node -e \\\"console.log('interrupt fixture tool started'); setTimeout(() => {}, 30000)\\\"\"","cwd":"/home/replay-user/t3code","processId":"26675","source":"unifiedExecStartup","status":"failed","commandActions":[{"type":"unknown","command":"node -e \"console.log('interrupt fixture tool started'); setTimeout(() => {}, 30000)\""}],"aggregatedOutput":null,"exitCode":-1,"durationMs":22},"threadId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","turnId":"01a0dfb9-e509-7001-ba72-fe324f527fb9","completedAtMs":1790459903901},"emittedAtMs":1790459903912}} -{"type":"emit_inbound","label":"turn/start","frame":{"id":11,"result":{"turn":{"id":"01a0dfb9-ff9f-7902-a370-d05cc4ec5959","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} +{"type":"emit_inbound","label":"turn/start","frame":{"id":12,"result":{"turn":{"id":"01a0dfb9-ff9f-7902-a370-d05cc4ec5959","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","status":{"type":"active","activeFlags":[]}},"emittedAtMs":1790459903925}} {"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","turn":{"id":"01a0dfb9-ff9f-7902-a370-d05cc4ec5959","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1790459903,"completedAt":null,"durationMs":null}},"emittedAtMs":1790459903925}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","name":"codex_apps","status":"failed","error":"MCP client for `codex_apps` failed to start: MCP startup failed: handshaking with MCP server failed: Send message error Transport [codex_rmcp_client::event_notification_transport::EventNotificationTransport>>] error: unexpected server response: HTTP 401: {\n \"error\": {\n \"message\": \"Encountered invalidated oauth token for user, failing request\",\n \"type\": null,\n \"code\": \"token_revoked\",\n \"param\": null\n },\n \"status\": 401\n}, when send initialize request: Send message error Transport [codex_rmcp_client::event_notification_transport::EventNotificationTransport>>] error: unexpected server response: HTTP 401: {\n \"error\": {\n \"message\": \"Encountered invalidated oauth token for user, failing request\",\n \"type\": null,\n \"code\": \"token_revoked\",\n \"param\": null\n },\n \"status\": 401\n}, when send initialize request","failureReason":null},"emittedAtMs":1790459904186}} @@ -89,20 +91,20 @@ {"type":"emit_inbound","label":"thread/tokenUsage/updated","frame":{"method":"thread/tokenUsage/updated","params":{"threadId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","turnId":"01a0dfb9-ff9f-7902-a370-d05cc4ec5959","tokenUsage":{"total":{"totalTokens":46272,"inputTokens":46153,"cachedInputTokens":30208,"cacheWriteInputTokens":0,"outputTokens":119,"reasoningOutputTokens":15},"last":{"totalTokens":15536,"inputTokens":15527,"cachedInputTokens":15104,"cacheWriteInputTokens":0,"outputTokens":9,"reasoningOutputTokens":0},"modelContextWindow":258400}},"emittedAtMs":1790459906339}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","status":{"type":"idle"}},"emittedAtMs":1790459906344}} {"type":"emit_inbound","label":"turn/completed","frame":{"method":"turn/completed","params":{"threadId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","turn":{"id":"01a0dfb9-ff9f-7902-a370-d05cc4ec5959","items":[{"type":"agentMessage","id":"msg_0508263b0487774d016ab840020e1087d08e559660413ebcd6","text":"rollback fixture second turn complete","phase":"final_answer","memoryCitation":null,"delivery":null,"questions":null}],"itemsView":"summary","status":"completed","error":null,"startedAt":1790459903,"completedAt":1790459906,"durationMs":2423}},"emittedAtMs":1790459906344}} -{"type":"expect_outbound","label":"thread/read","frame":{"id":12,"method":"thread/read","params":{"includeTurns":false,"threadId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88"}}} -{"type":"emit_inbound","label":"thread/read","frame":{"id":12,"result":{"thread":{"id":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code","runtimeWorkspaceRoots":["/home/replay-user/t3code"]}],"extra":null,"sessionId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","forkedFromId":null,"parentThreadId":null,"preview":"Respond with exactly: rollback fixture first turn complete","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790459892,"updatedAt":1790459906,"recencyAt":1790459903,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/26/rollout-2026-09-26T14-58-12-01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88.jsonl","cwd":"/home/replay-user/t3code","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":{"sha":"147b1509eac4291b323371299d0925a44035680c","branch":"master","originUrl":null},"name":null,"daybreakEnabled":null,"turns":[]}}}} -{"type":"expect_outbound","label":"thread/turns/list","frame":{"id":13,"method":"thread/turns/list","params":{"cursor":null,"itemsView":"summary","limit":1,"sortDirection":"desc","threadId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88"}}} -{"type":"emit_inbound","label":"thread/turns/list","frame":{"id":13,"result":{"data":[{"id":"01a0dfb9-ff9f-7902-a370-d05cc4ec5959","items":[{"type":"userMessage","id":"01a0dfba-0390-7aa0-a945-e25ca01302e2","clientId":null,"content":[{"type":"text","text":"Respond with exactly: rollback fixture second turn complete","text_elements":[]}]},{"type":"agentMessage","id":"msg_0508263b0487774d016ab840020e1087d08e559660413ebcd6","text":"rollback fixture second turn complete","phase":"final_answer","memoryCitation":null,"delivery":null,"questions":null}],"itemsView":"summary","status":"completed","error":null,"startedAt":1790459903,"completedAt":1790459906,"durationMs":2423}],"nextCursor":"{\"requestedThreadId\":\"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88\",\"rolloutOrdinal\":32,\"includeAnchor\":false,\"scope\":{\"kind\":\"turns\"}}","backwardsCursor":"{\"requestedThreadId\":\"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88\",\"rolloutOrdinal\":32,\"includeAnchor\":true,\"scope\":{\"kind\":\"turns\"}}"}}} -{"type":"expect_outbound","label":"thread/revert","frame":{"id":14,"method":"thread/revert","params":{"beforeTurnId":"01a0dfb9-ff9f-7902-a370-d05cc4ec5959","threadId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88"}}} +{"type":"expect_outbound","label":"thread/read","frame":{"id":13,"method":"thread/read","params":{"includeTurns":false,"threadId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88"}}} +{"type":"emit_inbound","label":"thread/read","frame":{"id":13,"result":{"thread":{"id":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code","runtimeWorkspaceRoots":["/home/replay-user/t3code"]}],"extra":null,"sessionId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","forkedFromId":null,"parentThreadId":null,"preview":"Respond with exactly: rollback fixture first turn complete","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790459892,"updatedAt":1790459906,"recencyAt":1790459903,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/26/rollout-2026-09-26T14-58-12-01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88.jsonl","cwd":"/home/replay-user/t3code","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":{"sha":"147b1509eac4291b323371299d0925a44035680c","branch":"master","originUrl":null},"name":null,"daybreakEnabled":null,"turns":[]}}}} +{"type":"expect_outbound","label":"thread/turns/list","frame":{"id":14,"method":"thread/turns/list","params":{"cursor":null,"itemsView":"summary","limit":1,"sortDirection":"desc","threadId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88"}}} +{"type":"emit_inbound","label":"thread/turns/list","frame":{"id":14,"result":{"data":[{"id":"01a0dfb9-ff9f-7902-a370-d05cc4ec5959","items":[{"type":"userMessage","id":"01a0dfba-0390-7aa0-a945-e25ca01302e2","clientId":null,"content":[{"type":"text","text":"Respond with exactly: rollback fixture second turn complete","text_elements":[]}]},{"type":"agentMessage","id":"msg_0508263b0487774d016ab840020e1087d08e559660413ebcd6","text":"rollback fixture second turn complete","phase":"final_answer","memoryCitation":null,"delivery":null,"questions":null}],"itemsView":"summary","status":"completed","error":null,"startedAt":1790459903,"completedAt":1790459906,"durationMs":2423}],"nextCursor":"{\"requestedThreadId\":\"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88\",\"rolloutOrdinal\":32,\"includeAnchor\":false,\"scope\":{\"kind\":\"turns\"}}","backwardsCursor":"{\"requestedThreadId\":\"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88\",\"rolloutOrdinal\":32,\"includeAnchor\":true,\"scope\":{\"kind\":\"turns\"}}"}}} +{"type":"expect_outbound","label":"thread/revert","frame":{"id":15,"method":"thread/revert","params":{"beforeTurnId":"01a0dfb9-ff9f-7902-a370-d05cc4ec5959","threadId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88"}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","status":{"type":"notLoaded"}},"emittedAtMs":1790459906373}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","name":"codex_apps","status":"starting","error":null,"failureReason":null},"emittedAtMs":1790459906471}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","status":{"type":"idle"}},"emittedAtMs":1790459906478}} -{"type":"emit_inbound","label":"thread/revert","frame":{"id":14,"result":{"thread":{"id":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code","runtimeWorkspaceRoots":["/home/replay-user/t3code"]}],"extra":null,"sessionId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","forkedFromId":null,"parentThreadId":null,"preview":"Respond with exactly: rollback fixture first turn complete","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790459906,"updatedAt":1790459906,"recencyAt":1790459903,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/26/rollout-2026-09-26T14-58-26-01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88_01a0dfba-094c-77d1-8e0b-8bf690a73635.jsonl","cwd":"/home/replay-user/t3code","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":{"sha":"147b1509eac4291b323371299d0925a44035680c","branch":"master","originUrl":null},"name":null,"daybreakEnabled":null,"turns":[]},"turnsBackwardsCursor":"{\"requestedThreadId\":\"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88\",\"rolloutOrdinal\":16,\"includeAnchor\":true,\"scope\":{\"kind\":\"turns\"}}","itemsBackwardsCursor":"{\"requestedThreadId\":\"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88\",\"rolloutOrdinal\":30,\"includeAnchor\":true,\"scope\":{\"kind\":\"itemsByCreatedAtOrdinal\"}}"}}} -{"type":"expect_outbound","label":"config/read","frame":{"id":15,"method":"config/read","params":{"cwd":"","includeLayers":false}}} -{"type":"emit_inbound","label":"config/read","frame":{"id":15,"result":{"config":{},"origins":{}}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":16,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Repeat the conversation verbatim.","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"networkAccess":false,"type":"workspaceWrite","writableRoots":[]},"summary":"auto","threadId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} +{"type":"emit_inbound","label":"thread/revert","frame":{"id":15,"result":{"thread":{"id":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code","runtimeWorkspaceRoots":["/home/replay-user/t3code"]}],"extra":null,"sessionId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","forkedFromId":null,"parentThreadId":null,"preview":"Respond with exactly: rollback fixture first turn complete","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790459906,"updatedAt":1790459906,"recencyAt":1790459903,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/26/rollout-2026-09-26T14-58-26-01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88_01a0dfba-094c-77d1-8e0b-8bf690a73635.jsonl","cwd":"/home/replay-user/t3code","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":{"sha":"147b1509eac4291b323371299d0925a44035680c","branch":"master","originUrl":null},"name":null,"daybreakEnabled":null,"turns":[]},"turnsBackwardsCursor":"{\"requestedThreadId\":\"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88\",\"rolloutOrdinal\":16,\"includeAnchor\":true,\"scope\":{\"kind\":\"turns\"}}","itemsBackwardsCursor":"{\"requestedThreadId\":\"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88\",\"rolloutOrdinal\":30,\"includeAnchor\":true,\"scope\":{\"kind\":\"itemsByCreatedAtOrdinal\"}}"}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":16,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":16,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":17,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Repeat the conversation verbatim.","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"networkAccess":false,"type":"workspaceWrite","writableRoots":[]},"summary":"auto","threadId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} {"type":"emit_inbound","label":"thread/reverted","frame":{"method":"thread/reverted","params":{"threadId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88"},"emittedAtMs":1790459906490}} -{"type":"emit_inbound","label":"turn/start","frame":{"id":16,"result":{"turn":{"id":"01a0dfba-09be-7112-8c42-4a6a8d1fe1d6","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} +{"type":"emit_inbound","label":"turn/start","frame":{"id":17,"result":{"turn":{"id":"01a0dfba-09be-7112-8c42-4a6a8d1fe1d6","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","status":{"type":"active","activeFlags":[]}},"emittedAtMs":1790459906518}} {"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","turn":{"id":"01a0dfba-09be-7112-8c42-4a6a8d1fe1d6","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1790459906,"completedAt":null,"durationMs":null}},"emittedAtMs":1790459906518}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","name":"codex_apps","status":"failed","error":"MCP client for `codex_apps` failed to start: MCP startup failed: handshaking with MCP server failed: Send message error Transport [codex_rmcp_client::event_notification_transport::EventNotificationTransport>>] error: unexpected server response: HTTP 401: {\n \"error\": {\n \"message\": \"Encountered invalidated oauth token for user, failing request\",\n \"type\": null,\n \"code\": \"token_revoked\",\n \"param\": null\n },\n \"status\": 401\n}, when send initialize request: Send message error Transport [codex_rmcp_client::event_notification_transport::EventNotificationTransport>>] error: unexpected server response: HTTP 401: {\n \"error\": {\n \"message\": \"Encountered invalidated oauth token for user, failing request\",\n \"type\": null,\n \"code\": \"token_revoked\",\n \"param\": null\n },\n \"status\": 401\n}, when send initialize request","failureReason":null},"emittedAtMs":1790459906779}} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/todo_list/codex_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/todo_list/codex_transcript.ndjson index a7efceb7e8ecd..0582c6a465c31 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/todo_list/codex_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/todo_list/codex_transcript.ndjson @@ -2,22 +2,24 @@ {"type":"expect_outbound","label":"initialize","frame":{"id":1,"method":"initialize","params":{"capabilities":{"experimentalApi":true,"optOutNotificationMethods":["turn/diff/updated"],"extensions":{"io.modelcontextprotocol/ui":{"mimeTypes":["text/html;profile=mcp-app"]}}},"clientInfo":{"name":"T3 Code","title":"T3 Code","version":"0.0.44"}}}} {"type":"emit_inbound","label":"initialize","frame":{"id":1,"result":{"userAgent":"t3code_desktop/0.156.1 (Debian 13.0.0; x86_64) unknown (t3code_desktop; 0.1.0)","codexHome":"/home/replay-user/.codex","platformFamily":"unix","platformOs":"linux"}}} {"type":"expect_outbound","label":"initialized","frame":{"method":"initialized"}} -{"type":"expect_outbound","label":"thread/start","frame":{"id":2,"method":"thread/start","params":{"config":{"tools.update_plan.enabled":true,"mcp_optional_startup_grace_ms":10000,"features.concurrent_reasoning_summaries":true},"cwd":"","model":"gpt-6-luna"}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":2,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":2,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"thread/start","frame":{"id":3,"method":"thread/start","params":{"config":{"tools.update_plan.enabled":true,"mcp_optional_startup_grace_ms":10000,"features.concurrent_reasoning_summaries":true},"cwd":"","model":"gpt-6-luna"}}} {"type":"emit_inbound","label":"configWarning","frame":{"method":"configWarning","params":{"summary":"Codex could not find bubblewrap on PATH. Install bubblewrap with your OS package manager. See the sandbox prerequisites: https://developers.openai.com/codex/concepts/sandboxing#prerequisites. Codex will use the bundled bubblewrap in the meantime.","details":null},"emittedAtMs":1790306244669}} {"type":"emit_inbound","label":"remoteControl/status/changed","frame":{"method":"remoteControl/status/changed","params":{"status":"disabled","serverName":"replay-host","installationId":"00000000-0000-4000-8000-000000000000","environmentId":null},"emittedAtMs":1790306244669}} {"type":"emit_inbound","label":"account/updated","frame":{"method":"account/updated","params":{"authMode":"chatgpt","planType":"unknown"},"emittedAtMs":1790306245652}} -{"type":"emit_inbound","label":"thread/start","frame":{"id":2,"result":{"thread":{"id":"01a0d691-5ba5-77b1-bf0d-1bf7be8e9abe","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d691-5ba5-77b1-bf0d-1bf7be8e9abe","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790306245,"updatedAt":1790306245,"recencyAt":1790306245,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T20-17-25-01a0d691-5ba5-77b1-bf0d-1bf7be8e9abe.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]},"model":"gpt-6-luna","modelProvider":"openai","serviceTier":null,"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"],"instructionSources":["/home/replay-user/.codex/AGENTS.md","/home/replay-user/t3code/AGENTS.md"],"approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":{"id":":workspace","extends":null},"reasoningEffort":null,"multiAgentMode":"explicitRequestOnly"}}} -{"type":"expect_outbound","label":"thread/name/set","frame":{"id":3,"method":"thread/name/set","params":{"name":"Replay fixture: todo_list","threadId":"01a0d691-5ba5-77b1-bf0d-1bf7be8e9abe"}}} -{"type":"emit_inbound","label":"thread/name/set","frame":{"id":3,"result":{}}} +{"type":"emit_inbound","label":"thread/start","frame":{"id":3,"result":{"thread":{"id":"01a0d691-5ba5-77b1-bf0d-1bf7be8e9abe","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d691-5ba5-77b1-bf0d-1bf7be8e9abe","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790306245,"updatedAt":1790306245,"recencyAt":1790306245,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T20-17-25-01a0d691-5ba5-77b1-bf0d-1bf7be8e9abe.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]},"model":"gpt-6-luna","modelProvider":"openai","serviceTier":null,"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"],"instructionSources":["/home/replay-user/.codex/AGENTS.md","/home/replay-user/t3code/AGENTS.md"],"approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":{"id":":workspace","extends":null},"reasoningEffort":null,"multiAgentMode":"explicitRequestOnly"}}} +{"type":"expect_outbound","label":"thread/name/set","frame":{"id":4,"method":"thread/name/set","params":{"name":"Replay fixture: todo_list","threadId":"01a0d691-5ba5-77b1-bf0d-1bf7be8e9abe"}}} +{"type":"emit_inbound","label":"thread/name/set","frame":{"id":4,"result":{}}} {"type":"emit_inbound","label":"thread/name/updated","frame":{"method":"thread/name/updated","params":{"threadId":"01a0d691-5ba5-77b1-bf0d-1bf7be8e9abe","threadName":"Replay fixture: todo_list"}}} -{"type":"expect_outbound","label":"config/read","frame":{"id":4,"method":"config/read","params":{"cwd":"","includeLayers":false}}} -{"type":"emit_inbound","label":"config/read","frame":{"id":4,"result":{"config":{},"origins":{}}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":5,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Use the update_plan tool to track exactly three steps: inspect package.json, inspect tsconfig.json, report completion. Then read package.json and tsconfig.json, and answer exactly: todo list fixture complete","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"networkAccess":false,"type":"readOnly"},"summary":"auto","threadId":"01a0d691-5ba5-77b1-bf0d-1bf7be8e9abe","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":5,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":5,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":6,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Use the update_plan tool to track exactly three steps: inspect package.json, inspect tsconfig.json, report completion. Then read package.json and tsconfig.json, and answer exactly: todo list fixture complete","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"networkAccess":false,"type":"readOnly"},"summary":"auto","threadId":"01a0d691-5ba5-77b1-bf0d-1bf7be8e9abe","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} {"type":"emit_inbound","label":"thread/started","frame":{"method":"thread/started","params":{"thread":{"id":"01a0d691-5ba5-77b1-bf0d-1bf7be8e9abe","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d691-5ba5-77b1-bf0d-1bf7be8e9abe","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790306245,"updatedAt":1790306245,"recencyAt":1790306245,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T20-17-25-01a0d691-5ba5-77b1-bf0d-1bf7be8e9abe.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]}},"emittedAtMs":1790306245772}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0d691-5ba5-77b1-bf0d-1bf7be8e9abe","name":"codex_apps","status":"starting","error":null,"failureReason":null},"emittedAtMs":1790306245772}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0d691-5ba5-77b1-bf0d-1bf7be8e9abe","name":"xcodebuildmcp","status":"starting","error":null,"failureReason":null},"emittedAtMs":1790306245772}} {"type":"emit_inbound","label":"thread/settings/updated","frame":{"method":"thread/settings/updated","params":{"threadId":"01a0d691-5ba5-77b1-bf0d-1bf7be8e9abe","threadSettings":{"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","approvalPolicy":"never","approvalsReviewer":"user","sandboxPolicy":{"type":"readOnly","networkAccess":false},"activePermissionProfile":null,"model":"gpt-6-luna","modelProvider":"openai","serviceTier":null,"effort":null,"summary":"detailed","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna","reasoning_effort":null,"developer_instructions":null}},"multiAgentMode":"explicitRequestOnly","personality":null}},"emittedAtMs":1790306245794}} -{"type":"emit_inbound","label":"turn/start","frame":{"id":5,"result":{"turn":{"id":"01a0d691-5c9c-7873-a191-5a599fd58099","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} +{"type":"emit_inbound","label":"turn/start","frame":{"id":6,"result":{"turn":{"id":"01a0d691-5c9c-7873-a191-5a599fd58099","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d691-5ba5-77b1-bf0d-1bf7be8e9abe","status":{"type":"active","activeFlags":[]}},"emittedAtMs":1790306245845}} {"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"01a0d691-5ba5-77b1-bf0d-1bf7be8e9abe","turn":{"id":"01a0d691-5c9c-7873-a191-5a599fd58099","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1790306245,"completedAt":null,"durationMs":null}},"emittedAtMs":1790306245845}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0d691-5ba5-77b1-bf0d-1bf7be8e9abe","name":"codex_apps","status":"ready","error":null,"failureReason":null},"emittedAtMs":1790306246472}} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/tool_call_read_only_on_request/codex_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/tool_call_read_only_on_request/codex_transcript.ndjson index 2fc49ff87b092..60ed0f1c710a0 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/tool_call_read_only_on_request/codex_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/tool_call_read_only_on_request/codex_transcript.ndjson @@ -2,20 +2,22 @@ {"type":"expect_outbound","label":"initialize","frame":{"id":1,"method":"initialize","params":{"capabilities":{"experimentalApi":true,"optOutNotificationMethods":["turn/diff/updated"],"extensions":{"io.modelcontextprotocol/ui":{"mimeTypes":["text/html;profile=mcp-app"]}}},"clientInfo":{"name":"T3 Code","title":"T3 Code","version":"0.0.44"}}}} {"type":"emit_inbound","label":"initialize","frame":{"id":1,"result":{"userAgent":"t3code_desktop/0.156.1 (Debian 13.0.0; x86_64) unknown (t3code_desktop; 0.1.0)","codexHome":"/home/replay-user/.codex","platformFamily":"unix","platformOs":"linux"}}} {"type":"expect_outbound","label":"initialized","frame":{"method":"initialized"}} -{"type":"expect_outbound","label":"thread/start","frame":{"id":2,"method":"thread/start","params":{"config":{"tools.update_plan.enabled":true,"mcp_optional_startup_grace_ms":10000,"features.concurrent_reasoning_summaries":true},"cwd":"","model":"gpt-6-sol"}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":2,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":2,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"thread/start","frame":{"id":3,"method":"thread/start","params":{"config":{"tools.update_plan.enabled":true,"mcp_optional_startup_grace_ms":10000,"features.concurrent_reasoning_summaries":true},"cwd":"","model":"gpt-6-sol"}}} {"type":"emit_inbound","label":"configWarning","frame":{"method":"configWarning","params":{"summary":"Codex could not find bubblewrap on PATH. Install bubblewrap with your OS package manager. See the sandbox prerequisites: https://developers.openai.com/codex/concepts/sandboxing#prerequisites. Codex will use the bundled bubblewrap in the meantime.","details":null},"emittedAtMs":1790296989543}} {"type":"emit_inbound","label":"remoteControl/status/changed","frame":{"method":"remoteControl/status/changed","params":{"status":"disabled","serverName":"replay-host","installationId":"00000000-0000-4000-8000-000000000000","environmentId":null},"emittedAtMs":1790296989543}} -{"type":"emit_inbound","label":"thread/start","frame":{"id":2,"result":{"thread":{"id":"01a0d604-1f8d-7522-8fe1-371c6626896e","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d604-1f8d-7522-8fe1-371c6626896e","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-sol","reasoningEffort":null,"createdAt":1790296989,"updatedAt":1790296989,"recencyAt":1790296989,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-43-09-01a0d604-1f8d-7522-8fe1-371c6626896e.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]},"model":"gpt-6-sol","modelProvider":"openai","serviceTier":null,"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"],"instructionSources":["/home/replay-user/.codex/AGENTS.md","/home/replay-user/t3code/AGENTS.md"],"approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":{"id":":workspace","extends":null},"reasoningEffort":null,"multiAgentMode":"explicitRequestOnly"}}} -{"type":"expect_outbound","label":"thread/name/set","frame":{"id":3,"method":"thread/name/set","params":{"name":"Replay fixture: tool_call_read_only_on_request","threadId":"01a0d604-1f8d-7522-8fe1-371c6626896e"}}} -{"type":"emit_inbound","label":"thread/name/set","frame":{"id":3,"result":{}}} +{"type":"emit_inbound","label":"thread/start","frame":{"id":3,"result":{"thread":{"id":"01a0d604-1f8d-7522-8fe1-371c6626896e","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d604-1f8d-7522-8fe1-371c6626896e","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-sol","reasoningEffort":null,"createdAt":1790296989,"updatedAt":1790296989,"recencyAt":1790296989,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-43-09-01a0d604-1f8d-7522-8fe1-371c6626896e.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]},"model":"gpt-6-sol","modelProvider":"openai","serviceTier":null,"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"],"instructionSources":["/home/replay-user/.codex/AGENTS.md","/home/replay-user/t3code/AGENTS.md"],"approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":{"id":":workspace","extends":null},"reasoningEffort":null,"multiAgentMode":"explicitRequestOnly"}}} +{"type":"expect_outbound","label":"thread/name/set","frame":{"id":4,"method":"thread/name/set","params":{"name":"Replay fixture: tool_call_read_only_on_request","threadId":"01a0d604-1f8d-7522-8fe1-371c6626896e"}}} +{"type":"emit_inbound","label":"thread/name/set","frame":{"id":4,"result":{}}} {"type":"emit_inbound","label":"thread/name/updated","frame":{"method":"thread/name/updated","params":{"threadId":"01a0d604-1f8d-7522-8fe1-371c6626896e","threadName":"Replay fixture: tool_call_read_only_on_request"}}} -{"type":"expect_outbound","label":"config/read","frame":{"id":4,"method":"config/read","params":{"cwd":"","includeLayers":false}}} -{"type":"emit_inbound","label":"config/read","frame":{"id":4,"result":{"config":{},"origins":{}}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":5,"method":"turn/start","params":{"approvalPolicy":"on-request","approvalsReviewer":"user","cwd":"","input":[{"text":"Create or overwrite .codex-probe-write-action.txt with exactly this text: codex app-server approval fixture. Use a local shell command or file edit only, then briefly report what happened. Do not read package metadata, use GitHub, use web, or use MCP.","type":"text"}],"model":"gpt-6-sol","sandboxPolicy":{"networkAccess":false,"type":"readOnly"},"summary":"auto","threadId":"01a0d604-1f8d-7522-8fe1-371c6626896e","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-sol"}}}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":5,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":5,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":6,"method":"turn/start","params":{"approvalPolicy":"on-request","approvalsReviewer":"user","cwd":"","input":[{"text":"Create or overwrite .codex-probe-write-action.txt with exactly this text: codex app-server approval fixture. Use a local shell command or file edit only, then briefly report what happened. Do not read package metadata, use GitHub, use web, or use MCP.","type":"text"}],"model":"gpt-6-sol","sandboxPolicy":{"networkAccess":false,"type":"readOnly"},"summary":"auto","threadId":"01a0d604-1f8d-7522-8fe1-371c6626896e","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-sol"}}}}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0d604-1f8d-7522-8fe1-371c6626896e","name":"codex_apps","status":"starting","error":null,"failureReason":null},"emittedAtMs":1790296989839}} {"type":"emit_inbound","label":"thread/started","frame":{"method":"thread/started","params":{"thread":{"id":"01a0d604-1f8d-7522-8fe1-371c6626896e","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d604-1f8d-7522-8fe1-371c6626896e","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-sol","reasoningEffort":null,"createdAt":1790296989,"updatedAt":1790296989,"recencyAt":1790296989,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-43-09-01a0d604-1f8d-7522-8fe1-371c6626896e.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]}},"emittedAtMs":1790296989839}} {"type":"emit_inbound","label":"thread/settings/updated","frame":{"method":"thread/settings/updated","params":{"threadId":"01a0d604-1f8d-7522-8fe1-371c6626896e","threadSettings":{"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","approvalPolicy":"on-request","approvalsReviewer":"user","sandboxPolicy":{"type":"readOnly","networkAccess":false},"activePermissionProfile":null,"model":"gpt-6-sol","modelProvider":"openai","serviceTier":null,"effort":null,"summary":"detailed","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-sol","reasoning_effort":null,"developer_instructions":null}},"multiAgentMode":"explicitRequestOnly","personality":null}},"emittedAtMs":1790296989848}} -{"type":"emit_inbound","label":"turn/start","frame":{"id":5,"result":{"turn":{"id":"01a0d604-2095-7fb0-a7e6-3f63d1949bbe","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} +{"type":"emit_inbound","label":"turn/start","frame":{"id":6,"result":{"turn":{"id":"01a0d604-2095-7fb0-a7e6-3f63d1949bbe","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d604-1f8d-7522-8fe1-371c6626896e","status":{"type":"active","activeFlags":[]}},"emittedAtMs":1790296989915}} {"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"01a0d604-1f8d-7522-8fe1-371c6626896e","turn":{"id":"01a0d604-2095-7fb0-a7e6-3f63d1949bbe","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1790296989,"completedAt":null,"durationMs":null}},"emittedAtMs":1790296989915}} {"type":"emit_inbound","label":"account/updated","frame":{"method":"account/updated","params":{"authMode":"chatgpt","planType":"unknown"},"emittedAtMs":1790296990273}} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/tool_call_restricted_granular/codex_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/tool_call_restricted_granular/codex_transcript.ndjson index a15f5dd2b1d6e..bc6baa5a3c232 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/tool_call_restricted_granular/codex_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/tool_call_restricted_granular/codex_transcript.ndjson @@ -2,20 +2,22 @@ {"type":"expect_outbound","label":"initialize","frame":{"id":1,"method":"initialize","params":{"capabilities":{"experimentalApi":true,"optOutNotificationMethods":["turn/diff/updated"],"extensions":{"io.modelcontextprotocol/ui":{"mimeTypes":["text/html;profile=mcp-app"]}}},"clientInfo":{"name":"T3 Code","title":"T3 Code","version":"0.0.44"}}}} {"type":"emit_inbound","label":"initialize","frame":{"id":1,"result":{"userAgent":"t3code_desktop/0.156.1 (Debian 13.0.0; x86_64) unknown (t3code_desktop; 0.1.0)","codexHome":"/home/replay-user/.codex","platformFamily":"unix","platformOs":"linux"}}} {"type":"expect_outbound","label":"initialized","frame":{"method":"initialized"}} -{"type":"expect_outbound","label":"thread/start","frame":{"id":2,"method":"thread/start","params":{"config":{"tools.update_plan.enabled":true,"mcp_optional_startup_grace_ms":10000,"features.concurrent_reasoning_summaries":true},"cwd":"","model":"gpt-5.6-terra"}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":2,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":2,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"thread/start","frame":{"id":3,"method":"thread/start","params":{"config":{"tools.update_plan.enabled":true,"mcp_optional_startup_grace_ms":10000,"features.concurrent_reasoning_summaries":true},"cwd":"","model":"gpt-5.6-terra"}}} {"type":"emit_inbound","label":"configWarning","frame":{"method":"configWarning","params":{"summary":"Codex could not find bubblewrap on PATH. Install bubblewrap with your OS package manager. See the sandbox prerequisites: https://developers.openai.com/codex/concepts/sandboxing#prerequisites. Codex will use the bundled bubblewrap in the meantime.","details":null},"emittedAtMs":1790297006729}} {"type":"emit_inbound","label":"remoteControl/status/changed","frame":{"method":"remoteControl/status/changed","params":{"status":"disabled","serverName":"replay-host","installationId":"00000000-0000-4000-8000-000000000000","environmentId":null},"emittedAtMs":1790297006729}} -{"type":"emit_inbound","label":"thread/start","frame":{"id":2,"result":{"thread":{"id":"01a0d604-629d-7162-b667-18c96f6fdf56","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d604-629d-7162-b667-18c96f6fdf56","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-5.6-terra","reasoningEffort":null,"createdAt":1790297006,"updatedAt":1790297006,"recencyAt":1790297006,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-43-26-01a0d604-629d-7162-b667-18c96f6fdf56.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]},"model":"gpt-5.6-terra","modelProvider":"openai","serviceTier":null,"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"],"instructionSources":["/home/replay-user/.codex/AGENTS.md","/home/replay-user/t3code/AGENTS.md"],"approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":{"id":":workspace","extends":null},"reasoningEffort":null,"multiAgentMode":"explicitRequestOnly"}}} -{"type":"expect_outbound","label":"thread/name/set","frame":{"id":3,"method":"thread/name/set","params":{"name":"Replay fixture: tool_call_restricted_granular","threadId":"01a0d604-629d-7162-b667-18c96f6fdf56"}}} -{"type":"emit_inbound","label":"thread/name/set","frame":{"id":3,"result":{}}} +{"type":"emit_inbound","label":"thread/start","frame":{"id":3,"result":{"thread":{"id":"01a0d604-629d-7162-b667-18c96f6fdf56","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d604-629d-7162-b667-18c96f6fdf56","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-5.6-terra","reasoningEffort":null,"createdAt":1790297006,"updatedAt":1790297006,"recencyAt":1790297006,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-43-26-01a0d604-629d-7162-b667-18c96f6fdf56.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]},"model":"gpt-5.6-terra","modelProvider":"openai","serviceTier":null,"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"],"instructionSources":["/home/replay-user/.codex/AGENTS.md","/home/replay-user/t3code/AGENTS.md"],"approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":{"id":":workspace","extends":null},"reasoningEffort":null,"multiAgentMode":"explicitRequestOnly"}}} +{"type":"expect_outbound","label":"thread/name/set","frame":{"id":4,"method":"thread/name/set","params":{"name":"Replay fixture: tool_call_restricted_granular","threadId":"01a0d604-629d-7162-b667-18c96f6fdf56"}}} +{"type":"emit_inbound","label":"thread/name/set","frame":{"id":4,"result":{}}} {"type":"emit_inbound","label":"thread/name/updated","frame":{"method":"thread/name/updated","params":{"threadId":"01a0d604-629d-7162-b667-18c96f6fdf56","threadName":"Replay fixture: tool_call_restricted_granular"}}} -{"type":"expect_outbound","label":"config/read","frame":{"id":4,"method":"config/read","params":{"cwd":"","includeLayers":false}}} -{"type":"emit_inbound","label":"config/read","frame":{"id":4,"result":{"config":{},"origins":{}}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":5,"method":"turn/start","params":{"approvalPolicy":{"granular":{"mcp_elicitations":true,"request_permissions":true,"rules":true,"sandbox_approval":true,"skill_approval":true}},"approvalsReviewer":"user","cwd":"","input":[{"text":"Create or overwrite .codex-probe-write-action.txt with exactly this text: codex app-server approval fixture. Use a local shell command or file edit only, then briefly report what happened. Do not read package metadata, use GitHub, use web, or use MCP.","type":"text"}],"model":"gpt-5.6-terra","sandboxPolicy":{"networkAccess":false,"type":"readOnly"},"summary":"auto","threadId":"01a0d604-629d-7162-b667-18c96f6fdf56","collaborationMode":{"mode":"default","settings":{"model":"gpt-5.6-terra"}}}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":5,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":5,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":6,"method":"turn/start","params":{"approvalPolicy":{"granular":{"mcp_elicitations":true,"request_permissions":true,"rules":true,"sandbox_approval":true,"skill_approval":true}},"approvalsReviewer":"user","cwd":"","input":[{"text":"Create or overwrite .codex-probe-write-action.txt with exactly this text: codex app-server approval fixture. Use a local shell command or file edit only, then briefly report what happened. Do not read package metadata, use GitHub, use web, or use MCP.","type":"text"}],"model":"gpt-5.6-terra","sandboxPolicy":{"networkAccess":false,"type":"readOnly"},"summary":"auto","threadId":"01a0d604-629d-7162-b667-18c96f6fdf56","collaborationMode":{"mode":"default","settings":{"model":"gpt-5.6-terra"}}}}} {"type":"emit_inbound","label":"thread/started","frame":{"method":"thread/started","params":{"thread":{"id":"01a0d604-629d-7162-b667-18c96f6fdf56","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d604-629d-7162-b667-18c96f6fdf56","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-5.6-terra","reasoningEffort":null,"createdAt":1790297006,"updatedAt":1790297006,"recencyAt":1790297006,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-43-26-01a0d604-629d-7162-b667-18c96f6fdf56.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]}},"emittedAtMs":1790297006923}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0d604-629d-7162-b667-18c96f6fdf56","name":"codex_apps","status":"starting","error":null,"failureReason":null},"emittedAtMs":1790297006923}} {"type":"emit_inbound","label":"thread/settings/updated","frame":{"method":"thread/settings/updated","params":{"threadId":"01a0d604-629d-7162-b667-18c96f6fdf56","threadSettings":{"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","approvalPolicy":{"granular":{"sandbox_approval":true,"rules":true,"skill_approval":true,"request_permissions":true,"mcp_elicitations":true}},"approvalsReviewer":"user","sandboxPolicy":{"type":"readOnly","networkAccess":false},"activePermissionProfile":null,"model":"gpt-5.6-terra","modelProvider":"openai","serviceTier":null,"effort":null,"summary":"detailed","collaborationMode":{"mode":"default","settings":{"model":"gpt-5.6-terra","reasoning_effort":null,"developer_instructions":null}},"multiAgentMode":"explicitRequestOnly","personality":null}},"emittedAtMs":1790297006943}} -{"type":"emit_inbound","label":"turn/start","frame":{"id":5,"result":{"turn":{"id":"01a0d604-6358-72f1-bb89-7361cce0045c","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} +{"type":"emit_inbound","label":"turn/start","frame":{"id":6,"result":{"turn":{"id":"01a0d604-6358-72f1-bb89-7361cce0045c","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d604-629d-7162-b667-18c96f6fdf56","status":{"type":"active","activeFlags":[]}},"emittedAtMs":1790297007009}} {"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"01a0d604-629d-7162-b667-18c96f6fdf56","turn":{"id":"01a0d604-6358-72f1-bb89-7361cce0045c","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1790297006,"completedAt":null,"durationMs":null}},"emittedAtMs":1790297007009}} {"type":"emit_inbound","label":"account/updated","frame":{"method":"account/updated","params":{"authMode":"chatgpt","planType":"unknown"},"emittedAtMs":1790297007345}} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/tool_call_workspace_never/codex_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/tool_call_workspace_never/codex_transcript.ndjson index e7fc6334e7fd2..318a98ecc54df 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/tool_call_workspace_never/codex_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/tool_call_workspace_never/codex_transcript.ndjson @@ -2,20 +2,22 @@ {"type":"expect_outbound","label":"initialize","frame":{"id":1,"method":"initialize","params":{"capabilities":{"experimentalApi":true,"optOutNotificationMethods":["turn/diff/updated"],"extensions":{"io.modelcontextprotocol/ui":{"mimeTypes":["text/html;profile=mcp-app"]}}},"clientInfo":{"name":"T3 Code","title":"T3 Code","version":"0.0.44"}}}} {"type":"emit_inbound","label":"initialize","frame":{"id":1,"result":{"userAgent":"t3code_desktop/0.156.1 (Debian 13.0.0; x86_64) unknown (t3code_desktop; 0.1.0)","codexHome":"/home/replay-user/.codex","platformFamily":"unix","platformOs":"linux"}}} {"type":"expect_outbound","label":"initialized","frame":{"method":"initialized"}} -{"type":"expect_outbound","label":"thread/start","frame":{"id":2,"method":"thread/start","params":{"config":{"tools.update_plan.enabled":true,"mcp_optional_startup_grace_ms":10000,"features.concurrent_reasoning_summaries":true},"cwd":"","model":"gpt-6-luna"}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":2,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":2,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"thread/start","frame":{"id":3,"method":"thread/start","params":{"config":{"tools.update_plan.enabled":true,"mcp_optional_startup_grace_ms":10000,"features.concurrent_reasoning_summaries":true},"cwd":"","model":"gpt-6-luna"}}} {"type":"emit_inbound","label":"configWarning","frame":{"method":"configWarning","params":{"summary":"Codex could not find bubblewrap on PATH. Install bubblewrap with your OS package manager. See the sandbox prerequisites: https://developers.openai.com/codex/concepts/sandboxing#prerequisites. Codex will use the bundled bubblewrap in the meantime.","details":null},"emittedAtMs":1790295509345}} {"type":"emit_inbound","label":"remoteControl/status/changed","frame":{"method":"remoteControl/status/changed","params":{"status":"disabled","serverName":"replay-host","installationId":"00000000-0000-4000-8000-000000000000","environmentId":null},"emittedAtMs":1790295509345}} -{"type":"emit_inbound","label":"thread/start","frame":{"id":2,"result":{"thread":{"id":"01a0d5ed-896f-73b3-8c42-3ffa820eb343","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d5ed-896f-73b3-8c42-3ffa820eb343","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790295509,"updatedAt":1790295509,"recencyAt":1790295509,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-18-29-01a0d5ed-896f-73b3-8c42-3ffa820eb343.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]},"model":"gpt-6-luna","modelProvider":"openai","serviceTier":null,"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"],"instructionSources":["/home/replay-user/.codex/AGENTS.md","/home/replay-user/t3code/AGENTS.md"],"approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":{"id":":workspace","extends":null},"reasoningEffort":null,"multiAgentMode":"explicitRequestOnly"}}} -{"type":"expect_outbound","label":"thread/name/set","frame":{"id":3,"method":"thread/name/set","params":{"name":"Replay fixture: tool_call_workspace_never","threadId":"01a0d5ed-896f-73b3-8c42-3ffa820eb343"}}} -{"type":"emit_inbound","label":"thread/name/set","frame":{"id":3,"result":{}}} +{"type":"emit_inbound","label":"thread/start","frame":{"id":3,"result":{"thread":{"id":"01a0d5ed-896f-73b3-8c42-3ffa820eb343","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d5ed-896f-73b3-8c42-3ffa820eb343","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790295509,"updatedAt":1790295509,"recencyAt":1790295509,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-18-29-01a0d5ed-896f-73b3-8c42-3ffa820eb343.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]},"model":"gpt-6-luna","modelProvider":"openai","serviceTier":null,"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"],"instructionSources":["/home/replay-user/.codex/AGENTS.md","/home/replay-user/t3code/AGENTS.md"],"approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":{"id":":workspace","extends":null},"reasoningEffort":null,"multiAgentMode":"explicitRequestOnly"}}} +{"type":"expect_outbound","label":"thread/name/set","frame":{"id":4,"method":"thread/name/set","params":{"name":"Replay fixture: tool_call_workspace_never","threadId":"01a0d5ed-896f-73b3-8c42-3ffa820eb343"}}} +{"type":"emit_inbound","label":"thread/name/set","frame":{"id":4,"result":{}}} {"type":"emit_inbound","label":"thread/name/updated","frame":{"method":"thread/name/updated","params":{"threadId":"01a0d5ed-896f-73b3-8c42-3ffa820eb343","threadName":"Replay fixture: tool_call_workspace_never"}}} -{"type":"expect_outbound","label":"config/read","frame":{"id":4,"method":"config/read","params":{"cwd":"","includeLayers":false}}} -{"type":"emit_inbound","label":"config/read","frame":{"id":4,"result":{"config":{},"origins":{}}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":5,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Create or overwrite .codex-probe-write-action.txt with exactly this text: codex app-server approval fixture. Use a local shell command or file edit only, then briefly report what happened. Do not read package metadata, use GitHub, use web, or use MCP.","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"networkAccess":false,"type":"workspaceWrite","writableRoots":[]},"summary":"auto","threadId":"01a0d5ed-896f-73b3-8c42-3ffa820eb343","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":5,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":5,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":6,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Create or overwrite .codex-probe-write-action.txt with exactly this text: codex app-server approval fixture. Use a local shell command or file edit only, then briefly report what happened. Do not read package metadata, use GitHub, use web, or use MCP.","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"networkAccess":false,"type":"workspaceWrite","writableRoots":[]},"summary":"auto","threadId":"01a0d5ed-896f-73b3-8c42-3ffa820eb343","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} {"type":"emit_inbound","label":"thread/started","frame":{"method":"thread/started","params":{"thread":{"id":"01a0d5ed-896f-73b3-8c42-3ffa820eb343","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d5ed-896f-73b3-8c42-3ffa820eb343","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790295509,"updatedAt":1790295509,"recencyAt":1790295509,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-18-29-01a0d5ed-896f-73b3-8c42-3ffa820eb343.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]}},"emittedAtMs":1790295509540}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0d5ed-896f-73b3-8c42-3ffa820eb343","name":"codex_apps","status":"starting","error":null,"failureReason":null},"emittedAtMs":1790295509540}} {"type":"emit_inbound","label":"thread/settings/updated","frame":{"method":"thread/settings/updated","params":{"threadId":"01a0d5ed-896f-73b3-8c42-3ffa820eb343","threadSettings":{"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","approvalPolicy":"never","approvalsReviewer":"user","sandboxPolicy":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":null,"model":"gpt-6-luna","modelProvider":"openai","serviceTier":null,"effort":null,"summary":"detailed","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna","reasoning_effort":null,"developer_instructions":null}},"multiAgentMode":"explicitRequestOnly","personality":null}},"emittedAtMs":1790295509553}} -{"type":"emit_inbound","label":"turn/start","frame":{"id":5,"result":{"turn":{"id":"01a0d5ed-8a2a-7002-b65d-fe5885c9f4e0","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} +{"type":"emit_inbound","label":"turn/start","frame":{"id":6,"result":{"turn":{"id":"01a0d5ed-8a2a-7002-b65d-fe5885c9f4e0","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d5ed-896f-73b3-8c42-3ffa820eb343","status":{"type":"active","activeFlags":[]}},"emittedAtMs":1790295509613}} {"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"01a0d5ed-896f-73b3-8c42-3ffa820eb343","turn":{"id":"01a0d5ed-8a2a-7002-b65d-fe5885c9f4e0","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1790295509,"completedAt":null,"durationMs":null}},"emittedAtMs":1790295509613}} {"type":"emit_inbound","label":"account/updated","frame":{"method":"account/updated","params":{"authMode":"chatgpt","planType":"unknown"},"emittedAtMs":1790295510000}} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/turn_interrupt/codex_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/turn_interrupt/codex_transcript.ndjson index 8408743473657..cd2a4d2f38346 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/turn_interrupt/codex_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/turn_interrupt/codex_transcript.ndjson @@ -2,29 +2,31 @@ {"type":"expect_outbound","label":"initialize","frame":{"id":1,"method":"initialize","params":{"capabilities":{"experimentalApi":true,"optOutNotificationMethods":["turn/diff/updated"],"extensions":{"io.modelcontextprotocol/ui":{"mimeTypes":["text/html;profile=mcp-app"]}}},"clientInfo":{"name":"T3 Code","title":"T3 Code","version":"0.0.44"}}}} {"type":"emit_inbound","label":"initialize","frame":{"id":1,"result":{"userAgent":"t3code_desktop/0.156.1 (Debian 13.0.0; x86_64) unknown (t3code_desktop; 0.1.0)","codexHome":"/home/replay-user/.codex","platformFamily":"unix","platformOs":"linux"}}} {"type":"expect_outbound","label":"initialized","frame":{"method":"initialized"}} -{"type":"expect_outbound","label":"thread/start","frame":{"id":2,"method":"thread/start","params":{"config":{"tools.update_plan.enabled":true,"mcp_optional_startup_grace_ms":10000,"features.concurrent_reasoning_summaries":true},"cwd":"","model":"gpt-6-luna"}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":2,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":2,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"thread/start","frame":{"id":3,"method":"thread/start","params":{"config":{"tools.update_plan.enabled":true,"mcp_optional_startup_grace_ms":10000,"features.concurrent_reasoning_summaries":true},"cwd":"","model":"gpt-6-luna"}}} {"type":"emit_inbound","label":"configWarning","frame":{"method":"configWarning","params":{"summary":"Codex could not find bubblewrap on PATH. Install bubblewrap with your OS package manager. See the sandbox prerequisites: https://developers.openai.com/codex/concepts/sandboxing#prerequisites. Codex will use the bundled bubblewrap in the meantime.","details":null},"emittedAtMs":1790295488496}} {"type":"emit_inbound","label":"remoteControl/status/changed","frame":{"method":"remoteControl/status/changed","params":{"status":"disabled","serverName":"replay-host","installationId":"00000000-0000-4000-8000-000000000000","environmentId":null},"emittedAtMs":1790295488496}} -{"type":"emit_inbound","label":"thread/start","frame":{"id":2,"result":{"thread":{"id":"01a0d5ed-3804-72d0-9a3f-929885a11f32","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d5ed-3804-72d0-9a3f-929885a11f32","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790295488,"updatedAt":1790295488,"recencyAt":1790295488,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-18-08-01a0d5ed-3804-72d0-9a3f-929885a11f32.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]},"model":"gpt-6-luna","modelProvider":"openai","serviceTier":null,"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"],"instructionSources":["/home/replay-user/.codex/AGENTS.md","/home/replay-user/t3code/AGENTS.md"],"approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":{"id":":workspace","extends":null},"reasoningEffort":null,"multiAgentMode":"explicitRequestOnly"}}} -{"type":"expect_outbound","label":"thread/name/set","frame":{"id":3,"method":"thread/name/set","params":{"name":"Replay fixture: turn_interrupt","threadId":"01a0d5ed-3804-72d0-9a3f-929885a11f32"}}} -{"type":"emit_inbound","label":"thread/name/set","frame":{"id":3,"result":{}}} +{"type":"emit_inbound","label":"thread/start","frame":{"id":3,"result":{"thread":{"id":"01a0d5ed-3804-72d0-9a3f-929885a11f32","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d5ed-3804-72d0-9a3f-929885a11f32","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790295488,"updatedAt":1790295488,"recencyAt":1790295488,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-18-08-01a0d5ed-3804-72d0-9a3f-929885a11f32.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]},"model":"gpt-6-luna","modelProvider":"openai","serviceTier":null,"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"],"instructionSources":["/home/replay-user/.codex/AGENTS.md","/home/replay-user/t3code/AGENTS.md"],"approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":{"id":":workspace","extends":null},"reasoningEffort":null,"multiAgentMode":"explicitRequestOnly"}}} +{"type":"expect_outbound","label":"thread/name/set","frame":{"id":4,"method":"thread/name/set","params":{"name":"Replay fixture: turn_interrupt","threadId":"01a0d5ed-3804-72d0-9a3f-929885a11f32"}}} +{"type":"emit_inbound","label":"thread/name/set","frame":{"id":4,"result":{}}} {"type":"emit_inbound","label":"thread/name/updated","frame":{"method":"thread/name/updated","params":{"threadId":"01a0d5ed-3804-72d0-9a3f-929885a11f32","threadName":"Replay fixture: turn_interrupt"}}} -{"type":"expect_outbound","label":"config/read","frame":{"id":4,"method":"config/read","params":{"cwd":"","includeLayers":false}}} -{"type":"emit_inbound","label":"config/read","frame":{"id":4,"result":{"config":{},"origins":{}}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":5,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Do not answer immediately. First run the local shell command `sleep 30`, then respond with exactly: interrupt fixture should not finish naturally.","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"networkAccess":false,"type":"workspaceWrite","writableRoots":[]},"summary":"auto","threadId":"01a0d5ed-3804-72d0-9a3f-929885a11f32","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":5,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":5,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":6,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Do not answer immediately. First run the local shell command `sleep 30`, then respond with exactly: interrupt fixture should not finish naturally.","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"networkAccess":false,"type":"workspaceWrite","writableRoots":[]},"summary":"auto","threadId":"01a0d5ed-3804-72d0-9a3f-929885a11f32","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} {"type":"emit_inbound","label":"thread/started","frame":{"method":"thread/started","params":{"thread":{"id":"01a0d5ed-3804-72d0-9a3f-929885a11f32","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d5ed-3804-72d0-9a3f-929885a11f32","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790295488,"updatedAt":1790295488,"recencyAt":1790295488,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-18-08-01a0d5ed-3804-72d0-9a3f-929885a11f32.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]}},"emittedAtMs":1790295488683}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0d5ed-3804-72d0-9a3f-929885a11f32","name":"codex_apps","status":"starting","error":null,"failureReason":null},"emittedAtMs":1790295488683}} {"type":"emit_inbound","label":"thread/settings/updated","frame":{"method":"thread/settings/updated","params":{"threadId":"01a0d5ed-3804-72d0-9a3f-929885a11f32","threadSettings":{"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","approvalPolicy":"never","approvalsReviewer":"user","sandboxPolicy":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":null,"model":"gpt-6-luna","modelProvider":"openai","serviceTier":null,"effort":null,"summary":"detailed","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna","reasoning_effort":null,"developer_instructions":null}},"multiAgentMode":"explicitRequestOnly","personality":null}},"emittedAtMs":1790295488699}} -{"type":"emit_inbound","label":"turn/start","frame":{"id":5,"result":{"turn":{"id":"01a0d5ed-38b3-7a11-9203-bd9650a02764","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} +{"type":"emit_inbound","label":"turn/start","frame":{"id":6,"result":{"turn":{"id":"01a0d5ed-38b3-7a11-9203-bd9650a02764","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d5ed-3804-72d0-9a3f-929885a11f32","status":{"type":"active","activeFlags":[]}},"emittedAtMs":1790295488747}} {"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"01a0d5ed-3804-72d0-9a3f-929885a11f32","turn":{"id":"01a0d5ed-38b3-7a11-9203-bd9650a02764","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1790295488,"completedAt":null,"durationMs":null}},"emittedAtMs":1790295488747}} {"type":"emit_inbound","label":"account/updated","frame":{"method":"account/updated","params":{"authMode":"chatgpt","planType":"unknown"},"emittedAtMs":1790295489056}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0d5ed-3804-72d0-9a3f-929885a11f32","name":"xcodebuildmcp","status":"starting","error":null,"failureReason":null},"emittedAtMs":1790295489323}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0d5ed-3804-72d0-9a3f-929885a11f32","name":"codex_apps","status":"ready","error":null,"failureReason":null},"emittedAtMs":1790295489469}} -{"type":"expect_outbound","label":"turn/interrupt","frame":{"id":6,"method":"turn/interrupt","params":{"threadId":"01a0d5ed-3804-72d0-9a3f-929885a11f32","turnId":"01a0d5ed-38b3-7a11-9203-bd9650a02764"}}} +{"type":"expect_outbound","label":"turn/interrupt","frame":{"id":7,"method":"turn/interrupt","params":{"threadId":"01a0d5ed-3804-72d0-9a3f-929885a11f32","turnId":"01a0d5ed-38b3-7a11-9203-bd9650a02764"}}} {"type":"emit_inbound","label":"item/started","frame":{"method":"item/started","params":{"item":{"type":"userMessage","id":"01a0d5ed-3ea7-7aa3-a029-700c3b1aa2e8","clientId":null,"content":[{"type":"text","text":"Do not answer immediately. First run the local shell command `sleep 30`, then respond with exactly: interrupt fixture should not finish naturally.","text_elements":[]}]},"threadId":"01a0d5ed-3804-72d0-9a3f-929885a11f32","turnId":"01a0d5ed-38b3-7a11-9203-bd9650a02764","startedAtMs":1790295490219},"emittedAtMs":1790295490220}} {"type":"emit_inbound","label":"item/completed","frame":{"method":"item/completed","params":{"item":{"type":"userMessage","id":"01a0d5ed-3ea7-7aa3-a029-700c3b1aa2e8","clientId":null,"content":[{"type":"text","text":"Do not answer immediately. First run the local shell command `sleep 30`, then respond with exactly: interrupt fixture should not finish naturally.","text_elements":[]}]},"threadId":"01a0d5ed-3804-72d0-9a3f-929885a11f32","turnId":"01a0d5ed-38b3-7a11-9203-bd9650a02764","completedAtMs":1790295490219},"emittedAtMs":1790295490229}} -{"type":"emit_inbound","label":"turn/interrupt","frame":{"id":6,"result":{}}} +{"type":"emit_inbound","label":"turn/interrupt","frame":{"id":7,"result":{}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d5ed-3804-72d0-9a3f-929885a11f32","status":{"type":"idle"}},"emittedAtMs":1790295490246}} {"type":"emit_inbound","label":"turn/completed","frame":{"method":"turn/completed","params":{"threadId":"01a0d5ed-3804-72d0-9a3f-929885a11f32","turn":{"id":"01a0d5ed-38b3-7a11-9203-bd9650a02764","items":[],"itemsView":"notLoaded","status":"interrupted","error":null,"startedAt":1790295488,"completedAt":1790295490,"durationMs":1544}},"emittedAtMs":1790295490246}} {"type":"runtime_exit","status":"success"} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/turn_interrupt_mid_tool/codex_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/turn_interrupt_mid_tool/codex_transcript.ndjson index c50bb4c3d650f..14a413c4c4c9d 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/turn_interrupt_mid_tool/codex_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/turn_interrupt_mid_tool/codex_transcript.ndjson @@ -2,20 +2,22 @@ {"type":"expect_outbound","label":"initialize","frame":{"id":1,"method":"initialize","params":{"capabilities":{"experimentalApi":true,"optOutNotificationMethods":["turn/diff/updated"],"extensions":{"io.modelcontextprotocol/ui":{"mimeTypes":["text/html;profile=mcp-app"]}}},"clientInfo":{"name":"T3 Code","title":"T3 Code","version":"0.0.44"}}}} {"type":"emit_inbound","label":"initialize","frame":{"id":1,"result":{"userAgent":"t3code_desktop/0.156.1 (Debian 13.0.0; x86_64) unknown (t3code_desktop; 0.1.0)","codexHome":"/home/replay-user/.codex","platformFamily":"unix","platformOs":"linux"}}} {"type":"expect_outbound","label":"initialized","frame":{"method":"initialized"}} -{"type":"expect_outbound","label":"thread/start","frame":{"id":2,"method":"thread/start","params":{"config":{"tools.update_plan.enabled":true,"mcp_optional_startup_grace_ms":10000,"features.concurrent_reasoning_summaries":true},"cwd":"","model":"gpt-6-luna"}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":2,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":2,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"thread/start","frame":{"id":3,"method":"thread/start","params":{"config":{"tools.update_plan.enabled":true,"mcp_optional_startup_grace_ms":10000,"features.concurrent_reasoning_summaries":true},"cwd":"","model":"gpt-6-luna"}}} {"type":"emit_inbound","label":"configWarning","frame":{"method":"configWarning","params":{"summary":"Codex could not find bubblewrap on PATH. Install bubblewrap with your OS package manager. See the sandbox prerequisites: https://developers.openai.com/codex/concepts/sandboxing#prerequisites. Codex will use the bundled bubblewrap in the meantime.","details":null},"emittedAtMs":1790297700256}} {"type":"emit_inbound","label":"remoteControl/status/changed","frame":{"method":"remoteControl/status/changed","params":{"status":"disabled","serverName":"replay-host","installationId":"00000000-0000-4000-8000-000000000000","environmentId":null},"emittedAtMs":1790297700256}} -{"type":"emit_inbound","label":"thread/start","frame":{"id":2,"result":{"thread":{"id":"01a0d60e-f7cc-7a50-bdff-90174e2c3b56","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d60e-f7cc-7a50-bdff-90174e2c3b56","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790297700,"updatedAt":1790297700,"recencyAt":1790297700,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-55-00-01a0d60e-f7cc-7a50-bdff-90174e2c3b56.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]},"model":"gpt-6-luna","modelProvider":"openai","serviceTier":null,"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"],"instructionSources":["/home/replay-user/.codex/AGENTS.md"],"approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":{"id":":workspace","extends":null},"reasoningEffort":null,"multiAgentMode":"explicitRequestOnly"}}} -{"type":"expect_outbound","label":"thread/name/set","frame":{"id":3,"method":"thread/name/set","params":{"name":"Replay fixture: turn_interrupt_mid_tool","threadId":"01a0d60e-f7cc-7a50-bdff-90174e2c3b56"}}} -{"type":"emit_inbound","label":"thread/name/set","frame":{"id":3,"result":{}}} +{"type":"emit_inbound","label":"thread/start","frame":{"id":3,"result":{"thread":{"id":"01a0d60e-f7cc-7a50-bdff-90174e2c3b56","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d60e-f7cc-7a50-bdff-90174e2c3b56","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790297700,"updatedAt":1790297700,"recencyAt":1790297700,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-55-00-01a0d60e-f7cc-7a50-bdff-90174e2c3b56.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]},"model":"gpt-6-luna","modelProvider":"openai","serviceTier":null,"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"],"instructionSources":["/home/replay-user/.codex/AGENTS.md"],"approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":{"id":":workspace","extends":null},"reasoningEffort":null,"multiAgentMode":"explicitRequestOnly"}}} +{"type":"expect_outbound","label":"thread/name/set","frame":{"id":4,"method":"thread/name/set","params":{"name":"Replay fixture: turn_interrupt_mid_tool","threadId":"01a0d60e-f7cc-7a50-bdff-90174e2c3b56"}}} +{"type":"emit_inbound","label":"thread/name/set","frame":{"id":4,"result":{}}} {"type":"emit_inbound","label":"thread/name/updated","frame":{"method":"thread/name/updated","params":{"threadId":"01a0d60e-f7cc-7a50-bdff-90174e2c3b56","threadName":"Replay fixture: turn_interrupt_mid_tool"}}} -{"type":"expect_outbound","label":"config/read","frame":{"id":4,"method":"config/read","params":{"cwd":"","includeLayers":false}}} -{"type":"emit_inbound","label":"config/read","frame":{"id":4,"result":{"config":{},"origins":{}}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":5,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Run this exact local command: `node -e \"console.log('interrupt fixture tool started'); setTimeout(() => {}, 30000)\"`. Do not answer until it completes, then respond exactly: interrupt fixture should not finish naturally.","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"networkAccess":false,"type":"workspaceWrite","writableRoots":[]},"summary":"auto","threadId":"01a0d60e-f7cc-7a50-bdff-90174e2c3b56","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":5,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":5,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":6,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Run this exact local command: `node -e \"console.log('interrupt fixture tool started'); setTimeout(() => {}, 30000)\"`. Do not answer until it completes, then respond exactly: interrupt fixture should not finish naturally.","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"networkAccess":false,"type":"workspaceWrite","writableRoots":[]},"summary":"auto","threadId":"01a0d60e-f7cc-7a50-bdff-90174e2c3b56","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} {"type":"emit_inbound","label":"thread/started","frame":{"method":"thread/started","params":{"thread":{"id":"01a0d60e-f7cc-7a50-bdff-90174e2c3b56","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d60e-f7cc-7a50-bdff-90174e2c3b56","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790297700,"updatedAt":1790297700,"recencyAt":1790297700,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-55-00-01a0d60e-f7cc-7a50-bdff-90174e2c3b56.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]}},"emittedAtMs":1790297700615}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0d60e-f7cc-7a50-bdff-90174e2c3b56","name":"codex_apps","status":"starting","error":null,"failureReason":null},"emittedAtMs":1790297700615}} {"type":"emit_inbound","label":"thread/settings/updated","frame":{"method":"thread/settings/updated","params":{"threadId":"01a0d60e-f7cc-7a50-bdff-90174e2c3b56","threadSettings":{"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","approvalPolicy":"never","approvalsReviewer":"user","sandboxPolicy":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":null,"model":"gpt-6-luna","modelProvider":"openai","serviceTier":null,"effort":null,"summary":"detailed","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna","reasoning_effort":null,"developer_instructions":null}},"multiAgentMode":"explicitRequestOnly","personality":null}},"emittedAtMs":1790297700629}} -{"type":"emit_inbound","label":"turn/start","frame":{"id":5,"result":{"turn":{"id":"01a0d60e-f90f-7f23-b6ba-9ca7ee20b5cd","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} +{"type":"emit_inbound","label":"turn/start","frame":{"id":6,"result":{"turn":{"id":"01a0d60e-f90f-7f23-b6ba-9ca7ee20b5cd","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d60e-f7cc-7a50-bdff-90174e2c3b56","status":{"type":"active","activeFlags":[]}},"emittedAtMs":1790297700691}} {"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"01a0d60e-f7cc-7a50-bdff-90174e2c3b56","turn":{"id":"01a0d60e-f90f-7f23-b6ba-9ca7ee20b5cd","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1790297700,"completedAt":null,"durationMs":null}},"emittedAtMs":1790297700691}} {"type":"emit_inbound","label":"account/updated","frame":{"method":"account/updated","params":{"authMode":"chatgpt","planType":"unknown"},"emittedAtMs":1790297700959}} @@ -30,11 +32,11 @@ {"type":"emit_inbound","label":"item/reasoning/summaryTextDelta","frame":{"method":"item/reasoning/summaryTextDelta","params":{"threadId":"01a0d60e-f7cc-7a50-bdff-90174e2c3b56","turnId":"01a0d60e-f90f-7f23-b6ba-9ca7ee20b5cd","itemId":"rs_02867d76e88a025b016ab5c669424c87d09ca784eb308b0650","delta":"**Running exact command**","summaryIndex":0},"emittedAtMs":1790297707152}} {"type":"emit_inbound","label":"item/completed","frame":{"method":"item/completed","params":{"item":{"type":"reasoning","id":"rs_02867d76e88a025b016ab5c669424c87d09ca784eb308b0650","summary":["**Running exact command**"],"content":[]},"threadId":"01a0d60e-f7cc-7a50-bdff-90174e2c3b56","turnId":"01a0d60e-f90f-7f23-b6ba-9ca7ee20b5cd","completedAtMs":1790297707229},"emittedAtMs":1790297707234}} {"type":"emit_inbound","label":"item/started","frame":{"method":"item/started","params":{"item":{"type":"commandExecution","id":"exec-0ce96e49-aa1c-4bae-b4f8-687a7473017c","pluginId":null,"scriptPath":null,"command":"/bin/bash -lc \"node -e \\\"console.log('interrupt fixture tool started'); setTimeout(() => {}, 30000)\\\"\"","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","processId":"87302","source":"unifiedExecStartup","status":"inProgress","commandActions":[{"type":"unknown","command":"node -e \"console.log('interrupt fixture tool started'); setTimeout(() => {}, 30000)\""}],"aggregatedOutput":null,"exitCode":null,"durationMs":null},"threadId":"01a0d60e-f7cc-7a50-bdff-90174e2c3b56","turnId":"01a0d60e-f90f-7f23-b6ba-9ca7ee20b5cd","startedAtMs":1790297707619},"emittedAtMs":1790297707621}} -{"type":"expect_outbound","label":"turn/interrupt","frame":{"id":6,"method":"turn/interrupt","params":{"threadId":"01a0d60e-f7cc-7a50-bdff-90174e2c3b56","turnId":"01a0d60e-f90f-7f23-b6ba-9ca7ee20b5cd"}}} +{"type":"expect_outbound","label":"turn/interrupt","frame":{"id":7,"method":"turn/interrupt","params":{"threadId":"01a0d60e-f7cc-7a50-bdff-90174e2c3b56","turnId":"01a0d60e-f90f-7f23-b6ba-9ca7ee20b5cd"}}} {"type":"emit_inbound","label":"thread/tokenUsage/updated","frame":{"method":"thread/tokenUsage/updated","params":{"threadId":"01a0d60e-f7cc-7a50-bdff-90174e2c3b56","turnId":"01a0d60e-f90f-7f23-b6ba-9ca7ee20b5cd","tokenUsage":{"total":{"totalTokens":17953,"inputTokens":17855,"cachedInputTokens":11008,"cacheWriteInputTokens":0,"outputTokens":98,"reasoningOutputTokens":25},"last":{"totalTokens":17953,"inputTokens":17855,"cachedInputTokens":11008,"cacheWriteInputTokens":0,"outputTokens":98,"reasoningOutputTokens":25},"modelContextWindow":258400}},"emittedAtMs":1790297707635}} -{"type":"emit_inbound","label":"turn/interrupt","frame":{"id":6,"result":{}}} -{"type":"expect_outbound","label":"thread/backgroundTerminals/terminate","frame":{"id":7,"method":"thread/backgroundTerminals/terminate","params":{"threadId":"01a0d60e-f7cc-7a50-bdff-90174e2c3b56","processId":"87302"}}} +{"type":"emit_inbound","label":"turn/interrupt","frame":{"id":7,"result":{}}} +{"type":"expect_outbound","label":"thread/backgroundTerminals/terminate","frame":{"id":8,"method":"thread/backgroundTerminals/terminate","params":{"threadId":"01a0d60e-f7cc-7a50-bdff-90174e2c3b56","processId":"87302"}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d60e-f7cc-7a50-bdff-90174e2c3b56","status":{"type":"idle"}},"emittedAtMs":1790297707650}} {"type":"emit_inbound","label":"turn/completed","frame":{"method":"turn/completed","params":{"threadId":"01a0d60e-f7cc-7a50-bdff-90174e2c3b56","turn":{"id":"01a0d60e-f90f-7f23-b6ba-9ca7ee20b5cd","items":[],"itemsView":"notLoaded","status":"interrupted","error":null,"startedAt":1790297700,"completedAt":1790297707,"durationMs":7017}},"emittedAtMs":1790297707650}} -{"type":"emit_inbound","label":"thread/backgroundTerminals/terminate","frame":{"id":7,"result":{"terminated":true}}} +{"type":"emit_inbound","label":"thread/backgroundTerminals/terminate","frame":{"id":8,"result":{"terminated":true}}} {"type":"runtime_exit","status":"success"} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/web_search/codex_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/web_search/codex_transcript.ndjson index 13e2b2b73a404..34013740bd798 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/web_search/codex_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/web_search/codex_transcript.ndjson @@ -2,20 +2,22 @@ {"type":"expect_outbound","label":"initialize","frame":{"id":1,"method":"initialize","params":{"capabilities":{"experimentalApi":true,"optOutNotificationMethods":["turn/diff/updated"],"extensions":{"io.modelcontextprotocol/ui":{"mimeTypes":["text/html;profile=mcp-app"]}}},"clientInfo":{"name":"T3 Code","title":"T3 Code","version":"0.0.44"}}}} {"type":"emit_inbound","label":"initialize","frame":{"id":1,"result":{"userAgent":"t3code_desktop/0.156.1 (Debian 13.0.0; x86_64) unknown (t3code_desktop; 0.1.0)","codexHome":"/home/replay-user/.codex","platformFamily":"unix","platformOs":"linux"}}} {"type":"expect_outbound","label":"initialized","frame":{"method":"initialized"}} -{"type":"expect_outbound","label":"thread/start","frame":{"id":2,"method":"thread/start","params":{"config":{"tools.update_plan.enabled":true,"mcp_optional_startup_grace_ms":10000,"features.concurrent_reasoning_summaries":true},"cwd":"","model":"gpt-6-luna"}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":2,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":2,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"thread/start","frame":{"id":3,"method":"thread/start","params":{"config":{"tools.update_plan.enabled":true,"mcp_optional_startup_grace_ms":10000,"features.concurrent_reasoning_summaries":true},"cwd":"","model":"gpt-6-luna"}}} {"type":"emit_inbound","label":"configWarning","frame":{"method":"configWarning","params":{"summary":"Codex could not find bubblewrap on PATH. Install bubblewrap with your OS package manager. See the sandbox prerequisites: https://developers.openai.com/codex/concepts/sandboxing#prerequisites. Codex will use the bundled bubblewrap in the meantime.","details":null},"emittedAtMs":1790295574462}} {"type":"emit_inbound","label":"remoteControl/status/changed","frame":{"method":"remoteControl/status/changed","params":{"status":"disabled","serverName":"replay-host","installationId":"00000000-0000-4000-8000-000000000000","environmentId":null},"emittedAtMs":1790295574462}} -{"type":"emit_inbound","label":"thread/start","frame":{"id":2,"result":{"thread":{"id":"01a0d5ee-87e4-7461-9ab7-5c316b503107","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d5ee-87e4-7461-9ab7-5c316b503107","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790295574,"updatedAt":1790295574,"recencyAt":1790295574,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-19-34-01a0d5ee-87e4-7461-9ab7-5c316b503107.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]},"model":"gpt-6-luna","modelProvider":"openai","serviceTier":null,"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"],"instructionSources":["/home/replay-user/.codex/AGENTS.md","/home/replay-user/t3code/AGENTS.md"],"approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":{"id":":workspace","extends":null},"reasoningEffort":null,"multiAgentMode":"explicitRequestOnly"}}} -{"type":"expect_outbound","label":"thread/name/set","frame":{"id":3,"method":"thread/name/set","params":{"name":"Replay fixture: web_search","threadId":"01a0d5ee-87e4-7461-9ab7-5c316b503107"}}} -{"type":"emit_inbound","label":"thread/name/set","frame":{"id":3,"result":{}}} +{"type":"emit_inbound","label":"thread/start","frame":{"id":3,"result":{"thread":{"id":"01a0d5ee-87e4-7461-9ab7-5c316b503107","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d5ee-87e4-7461-9ab7-5c316b503107","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790295574,"updatedAt":1790295574,"recencyAt":1790295574,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-19-34-01a0d5ee-87e4-7461-9ab7-5c316b503107.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]},"model":"gpt-6-luna","modelProvider":"openai","serviceTier":null,"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"],"instructionSources":["/home/replay-user/.codex/AGENTS.md","/home/replay-user/t3code/AGENTS.md"],"approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":{"id":":workspace","extends":null},"reasoningEffort":null,"multiAgentMode":"explicitRequestOnly"}}} +{"type":"expect_outbound","label":"thread/name/set","frame":{"id":4,"method":"thread/name/set","params":{"name":"Replay fixture: web_search","threadId":"01a0d5ee-87e4-7461-9ab7-5c316b503107"}}} +{"type":"emit_inbound","label":"thread/name/set","frame":{"id":4,"result":{}}} {"type":"emit_inbound","label":"thread/name/updated","frame":{"method":"thread/name/updated","params":{"threadId":"01a0d5ee-87e4-7461-9ab7-5c316b503107","threadName":"Replay fixture: web_search"}}} -{"type":"expect_outbound","label":"config/read","frame":{"id":4,"method":"config/read","params":{"cwd":"","includeLayers":false}}} -{"type":"emit_inbound","label":"config/read","frame":{"id":4,"result":{"config":{},"origins":{}}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":5,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Search the web for FIFA World Cup ticket pricing, then answer exactly: web search fixture complete","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"auto","threadId":"01a0d5ee-87e4-7461-9ab7-5c316b503107","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} +{"type":"expect_outbound","label":"config/read","frame":{"id":5,"method":"config/read","params":{"cwd":"","includeLayers":false}}} +{"type":"emit_inbound","label":"config/read","frame":{"id":5,"result":{"config":{},"origins":{}}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":6,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Search the web for FIFA World Cup ticket pricing, then answer exactly: web search fixture complete","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"auto","threadId":"01a0d5ee-87e4-7461-9ab7-5c316b503107","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} {"type":"emit_inbound","label":"thread/started","frame":{"method":"thread/started","params":{"thread":{"id":"01a0d5ee-87e4-7461-9ab7-5c316b503107","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d5ee-87e4-7461-9ab7-5c316b503107","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790295574,"updatedAt":1790295574,"recencyAt":1790295574,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-19-34-01a0d5ee-87e4-7461-9ab7-5c316b503107.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]}},"emittedAtMs":1790295574652}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0d5ee-87e4-7461-9ab7-5c316b503107","name":"codex_apps","status":"starting","error":null,"failureReason":null},"emittedAtMs":1790295574652}} {"type":"emit_inbound","label":"thread/settings/updated","frame":{"method":"thread/settings/updated","params":{"threadId":"01a0d5ee-87e4-7461-9ab7-5c316b503107","threadSettings":{"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","approvalPolicy":"never","approvalsReviewer":"user","sandboxPolicy":{"type":"dangerFullAccess"},"activePermissionProfile":null,"model":"gpt-6-luna","modelProvider":"openai","serviceTier":null,"effort":null,"summary":"detailed","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna","reasoning_effort":null,"developer_instructions":null}},"multiAgentMode":"explicitRequestOnly","personality":null}},"emittedAtMs":1790295574669}} -{"type":"emit_inbound","label":"turn/start","frame":{"id":5,"result":{"turn":{"id":"01a0d5ee-8888-7d30-8f2b-68fe28f521bc","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} +{"type":"emit_inbound","label":"turn/start","frame":{"id":6,"result":{"turn":{"id":"01a0d5ee-8888-7d30-8f2b-68fe28f521bc","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d5ee-87e4-7461-9ab7-5c316b503107","status":{"type":"active","activeFlags":[]}},"emittedAtMs":1790295574742}} {"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"01a0d5ee-87e4-7461-9ab7-5c316b503107","turn":{"id":"01a0d5ee-8888-7d30-8f2b-68fe28f521bc","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1790295574,"completedAt":null,"durationMs":null}},"emittedAtMs":1790295574742}} {"type":"emit_inbound","label":"account/updated","frame":{"method":"account/updated","params":{"authMode":"chatgpt","planType":"unknown"},"emittedAtMs":1790295575098}} diff --git a/packages/effect-codex-app-server/src/replay.ts b/packages/effect-codex-app-server/src/replay.ts index 219feae25126a..384e11c8b4a3e 100644 --- a/packages/effect-codex-app-server/src/replay.ts +++ b/packages/effect-codex-app-server/src/replay.ts @@ -252,11 +252,20 @@ function recorderThreadConfigKeys(transcript: CodexAppServerReplayTranscript): R /** * `cwd`, `model`, host-supplied MCP servers (machine-local URLs, short-lived * authorization headers) and the T3 thread id vary per machine or run, and - * recorder-only keys are not the client's. + * recorder-only keys are not the client's. The config read before a thread + * request carries the same `cwd`. */ function normalizeThreadRequest(frame: unknown, ignoredConfigKeys: ReadonlySet): unknown { if (typeof frame !== "object" || frame === null) return frame; const record = frame as Record; + if ( + record.method === "config/read" && + typeof record.params === "object" && + record.params !== null + ) { + const { cwd: _cwd, ...params } = record.params as Record; + return { ...record, params }; + } if ( (record.method !== "thread/start" && record.method !== "thread/resume" && From 505f6d6cf4fcd61aeafc2f32f8bc7adfd8713f5f Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 19 Nov 2026 15:36:00 -0800 Subject: [PATCH 91/97] fix(server): Antigravity accepts t3_background_wait for its own background commands (#39421) --- .../Adapters/AntigravityAdapterV2.test.ts | 19 +++++++++++++++ packages/provider-acp/src/server/adapter.ts | 23 +++++++++++++++++++ 2 files changed, 42 insertions(+) diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts index 21022a97f36d5..c7b8c6ffaf1b2 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts @@ -1462,6 +1462,25 @@ describe("AntigravityAdapterV2 work after the prompt ends", () => { }).pipe(Effect.provide(layerSession)), ); + // agy names its background commands `/task-`; the agent passes that to + // t3_background_wait, which must not fail since the adapter already holds the run open. + it.effect("accepts t3_background_wait for a command it already tracks", () => + Effect.gen(function* () { + const { session, providerThread, startTurn, throughPromptSettled } = + yield* openSessionWithRunningCommand({ WaitMsBeforeAsync: 10000 }); + yield* startTurn(1, false); + yield* throughPromptSettled; + const taskIds = ["mock-session-1/task-2"]; + assert.isDefined(session.awaitBackgroundTasks, "t3_background_wait must not be unsupported"); + const result = yield* session.awaitBackgroundTasks!({ + providerThread, + taskIds, + awaited: true, + }); + assert.deepEqual(result.matched, taskIds); + }).pipe(Effect.provide(layerSession)), + ); + // agy 1.5.11 reads a prompt sent mid-turn as a steer: it answers the running prompt end_turn // and goes on under the new one. session/cancel would end its running commands and subagents. it.effect("steers a running prompt with the next one and leaves its work running", () => diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index 3e0864054c32f..e096bf25a4577 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -9972,6 +9972,29 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( ), ), ), + // The held turn already waits on these commands; their tool calls carry no task id, + // so any id matches while one runs on this thread. + ...(flavor.toolOutlivesPrompt === undefined + ? {} + : { + awaitBackgroundTasks: Effect.fn("AcpAdapterV2.awaitBackgroundTasks")(function* ({ + providerThread, + taskIds, + }) { + const outlives = flavor.toolOutlivesPrompt; + const context = yield* Ref.get(activeTurn); + const holdsCommand = + outlives !== undefined && + defersFinalizeForBackgroundWork && + context !== null && + !context.finalized && + context.nativeThreadId === providerThread.nativeThreadRef?.nativeId && + [...context.tools.values()].some( + (tool) => toolStatus(tool.status) === "running" && outlives(tool), + ); + return { matched: holdsCommand ? [...new Set(taskIds)] : [] }; + }), + }), interruptTurn: Effect.fn("AcpAdapterV2.interruptTurn")( function* (turnInput: ProviderAdapter.ProviderAdapterV2InterruptInput) { return yield* Effect.uninterruptibleMask((restore) => From 990f31cac2567163a15c7fa603abfebe5bdcdb9e Mon Sep 17 00:00:00 2001 From: Omar Espinosa <77650361+OmarAlex24@users.noreply.github.com> Date: Thu, 19 Nov 2026 17:36:13 -0600 Subject: [PATCH 92/97] fix(server): host sleep no longer times out an Antigravity turn (#39395) Co-authored-by: Julius Marminge --- .../Adapters/AcpAdapterV2.test.ts | 60 +++++++++++++++++++ packages/provider-acp/src/server/adapter.ts | 15 ++++- 2 files changed, 72 insertions(+), 3 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts index c3d54f06719fa..9c8b403a748a6 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts @@ -45,6 +45,7 @@ import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; import * as FileSystem from "effect/FileSystem"; import * as Fiber from "effect/Fiber"; +import * as Latch from "effect/Latch"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Path from "effect/Path"; @@ -5531,6 +5532,65 @@ describe("AcpAdapterV2", () => { }).pipe(Effect.provide(layerTest)), ); + // regression: #34160 a turn failed as silent right after the computer woke from sleep + it.effect.each([ + { label: "a timer due during sleep fires on wake", timerCountsSleep: true, asleep: "2 hours" }, + { label: "the host wakes before the deadline", timerCountsSleep: true, asleep: "9 minutes" }, + { + label: "timers pause while only wall time jumps", + timerCountsSleep: false, + asleep: "2 hours", + }, + ] as const)( + "does not count host sleep as prompt inactivity when $label", + ({ timerCountsSleep, asleep }) => + Effect.gen(function* () { + const testClock = yield* TestClock.testClockWith(Effect.succeed); + const awake = yield* Latch.make(true); + let wallJumpMillis = 0; + // macOS and Windows timers count sleep and fire on the first tick after wake; on Linux + // timers pause while the wall clock jumps. + const hostClock: TestClock.TestClock = { + ...testClock, + currentTimeMillisUnsafe: () => testClock.currentTimeMillisUnsafe() + wallJumpMillis, + currentTimeMillis: Effect.sync( + () => testClock.currentTimeMillisUnsafe() + wallJumpMillis, + ), + sleep: (duration) => testClock.sleep(duration).pipe(Effect.andThen(awake.await)), + }; + yield* Effect.gen(function* () { + const harness = yield* makePromptInactivityHarness({ + environment: (runtimeOrdinal) => + runtimeOrdinal === 1 ? { T3_ACP_HANG_PROMPT_FOREVER: "1" } : {}, + }); + yield* harness.startTurn(1); + yield* TestClock.adjust("5 minutes"); + yield* harness.emitUpdate({ + sessionId: "mock-session-1", + update: { + sessionUpdate: "agent_thought_chunk", + content: { type: "text", text: "Still working." }, + }, + }); + if (timerCountsSleep) { + yield* awake.close; + yield* TestClock.adjust(asleep); + yield* awake.open; + } else { + wallJumpMillis = Duration.toMillis(asleep); + } + yield* TestClock.adjust(Duration.millis(15 * 60_000 - 1)); + assert.isTrue(yield* harness.nextTurnRejected(2)); + + yield* TestClock.adjust("2 minutes"); + yield* harness.startTurn(2); + const [silent, next] = yield* harness.terminals(2); + assert.equal(silent?.status, "failed"); + assert.equal(next?.status, "completed"); + }).pipe(Effect.provideService(Clock.Clock, hostClock)); + }).pipe(Effect.provide(layerTest)), + ); + it.effect( "holds the inactivity timeout while a tool runs and restarts it when the tool ends", () => diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index e096bf25a4577..ea1c83091d5f9 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -147,6 +147,8 @@ const ACP_DEFERRED_FINALIZE_DEBOUNCE: Duration.Input = "3000 millis"; // A model can stay silent this long before the first token of a reply the agent started itself. const ACP_OPEN_REPLY_QUIET_LIMIT: Duration.Input = "2 minutes"; const ACP_BUSY_PROMPT_RETRY_INTERVAL: Duration.Input = "1 second"; +const ACP_PROMPT_INACTIVITY_SLICE_MILLIS = 60_000; +const ACP_HOST_SLEEP_TOLERANCE_MILLIS = 10_000; // pi-agent-core agents (oh-my-pi) end a turn while background work runs and reject // prompts until it finishes; the prompt is resent rather than failing the turn. @@ -8767,10 +8769,17 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( yield* Deferred.await(context.promptDispatched); context.lastProgressAt = yield* Clock.currentTimeMillis; while (true) { - const remaining = - context.lastProgressAt + timeoutMillis - (yield* Clock.currentTimeMillis); + const sliceStartedAt = yield* Clock.currentTimeMillis; + const remaining = context.lastProgressAt + timeoutMillis - sliceStartedAt; if (remaining > 0) { - yield* Effect.sleep(Duration.millis(remaining)); + const slice = Math.min(remaining, ACP_PROMPT_INACTIVITY_SLICE_MILLIS); + yield* Effect.sleep(Duration.millis(slice)); + // Host sleep is not agent silence. Timers either fire late on wake (macOS, Windows) + // or pause while the wall clock jumps (Linux); both overrun a short slice. + const now = yield* Clock.currentTimeMillis; + if (now - sliceStartedAt > slice + ACP_HOST_SLEEP_TOLERANCE_MILLIS) { + context.lastProgressAt = now; + } continue; } const outcome = yield* runtimeTransitionPermit.withPermit( From 944d1820e2b797fd1369f81035a13746b02a99de Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 19 Nov 2026 15:41:28 -0800 Subject: [PATCH 93/97] fix(server): Antigravity Google sign-in shows its link with the native CLI (#38953) --- .../src/provider/AntigravityAuth.test.ts | 57 ++++++++ apps/server/src/provider/AntigravityAuth.ts | 121 +++++++++++++++-- .../src/provider/Drivers/AntigravityDriver.ts | 128 ++++++++++++++++-- .../provider/antigravityAuthSupport.test.ts | 41 ++++++ .../src/provider/antigravityAuthSupport.ts | 38 +++++- docs/user/providers-antigravity.md | 6 +- 6 files changed, 361 insertions(+), 30 deletions(-) diff --git a/apps/server/src/provider/AntigravityAuth.test.ts b/apps/server/src/provider/AntigravityAuth.test.ts index 48cb3f1912da3..af730c75f12c8 100644 --- a/apps/server/src/provider/AntigravityAuth.test.ts +++ b/apps/server/src/provider/AntigravityAuth.test.ts @@ -27,6 +27,8 @@ const otherOwner = "t3-auth-session-other"; const authorizationUrl = "https://accounts.google.com/o/oauth2/v2/auth?response_type=code&redirect_uri=http%3A%2F%2F127.0.0.1%3A51234%2F&state=test-state"; const callbackUrl = "http://127.0.0.1:51234/?state=test-state&code=test-code"; +const loginUrl = + "https://accounts.google.com/o/oauth2/auth?response_type=code&redirect_uri=https%3A%2F%2Fantigravity.google%2Foauth-callback&state=login-state"; const initialized = { protocolVersion: 1, @@ -60,8 +62,11 @@ const makeHarness = Effect.fn("makeAuthTestHarness")(function* ( readonly supportsLogout?: boolean; readonly beforeInitialize?: Effect.Effect; readonly forwardCallback?: Effect.Effect; + readonly codeLogin?: boolean; } = {}, ) { + const loginCodes: string[] = []; + const loginCode = yield* Deferred.make(); const authenticated = yield* Deferred.make(); const discovered = yield* Deferred.make(); const closed = yield* Deferred.make(); @@ -132,6 +137,21 @@ const makeHarness = Effect.fn("makeAuthTestHarness")(function* ( Effect.sync(() => { forwarded += 1; }), + codeLogin: ({ onAuthorizationUrl }) => + Effect.gen(function* () { + if (!options.codeLogin) return undefined; + events.push("login-open"); + yield* Effect.addFinalizer(() => Effect.sync(() => events.push("login-close"))); + yield* onAuthorizationUrl(loginUrl); + return { + submit: (response: string) => + Effect.sync(() => loginCodes.push(response)).pipe( + Effect.andThen(Deferred.succeed(loginCode, undefined)), + Effect.asVoid, + ), + completed: Deferred.await(loginCode), + }; + }), }); return { auth, @@ -142,6 +162,7 @@ const makeHarness = Effect.fn("makeAuthTestHarness")(function* ( events, catalog: () => catalog, forwarded: () => forwarded, + loginCodes, receiveAuthorizationUrl: (url: string) => Effect.suspend(() => receiveAuthorizationUrl @@ -170,6 +191,42 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("AntigravityAuth" }), ); + it.effect("signs in through the CLI's code login, then authenticates a fresh process", () => + Effect.gen(function* () { + const harness = yield* makeHarness({ codeLogin: true }); + const state = yield* harness.auth.controller.start(owner); + const waiting = yield* phase(harness.auth, "waiting"); + assert.equal(waiting.authorizationUrl, loginUrl); + assert.equal(waiting.interaction?.type, "credentials"); + const respond = (code: string) => + harness.auth.controller.respond!(owner, { + instanceId, + flowId: state.flowId!, + interactionId: state.flowId!, + response: { type: "credentials", values: { code } }, + }); + for (const invalid of [callbackUrl, "two words", ""]) { + assert.isTrue(Exit.isFailure(yield* respond(invalid).pipe(Effect.exit)), invalid); + } + assert.equal((yield* respond("4/0Ab-code")).phase, "verifying"); + assert.deepEqual(harness.loginCodes, ["4/0Ab-code"]); + + yield* Deferred.succeed(harness.authenticated, undefined); + yield* Deferred.succeed(harness.discovered, undefined); + yield* phase(harness.auth, "succeeded"); + assert.deepEqual(harness.events, [ + "login-open", + "login-close", + "process-open", + "initialize", + "authenticate", + "session-new", + "catalog-published", + "process-close", + ]); + }), + ); + it.effect("rejects a different second authorization URL", () => Effect.gen(function* () { const harness = yield* makeHarness({ diff --git a/apps/server/src/provider/AntigravityAuth.ts b/apps/server/src/provider/AntigravityAuth.ts index 6e471dad4dc1a..5f5d3f1143a34 100644 --- a/apps/server/src/provider/AntigravityAuth.ts +++ b/apps/server/src/provider/AntigravityAuth.ts @@ -21,6 +21,7 @@ import * as AcpErrors from "effect-acp/errors"; import type * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime"; import { + antigravityLoginResponse, parseAntigravityAuthorizationUrl, type AntigravityAuthorizationUrl, } from "./antigravityAuthSupport.ts"; @@ -45,6 +46,7 @@ const NO_RESPONSE_MESSAGE = const UNREACHABLE_MESSAGE = "Antigravity could not reach Google. Check this machine's network connection, then start sign-in again."; const FORWARDING_FAILED_MESSAGE = "Could not deliver the sign-in response. Start sign-in again."; +const LOGIN_CODE_FIELD = "code"; const isSetupError = Schema.is(ProviderSetupError); const isAcpRequestError = Schema.is(AcpErrors.AcpRequestError); const isAcpProcessExitedError = Schema.is(AcpErrors.AcpProcessExitedError); @@ -52,6 +54,7 @@ const isAcpProcessExitedError = Schema.is(AcpErrors.AcpProcessExitedError); interface AuthSnapshot { readonly ownerSessionId: string | null; readonly state: ProviderAuthState; + readonly codeLogin?: boolean; } interface AuthFlow { @@ -62,6 +65,8 @@ interface AuthFlow { pending: AntigravityAuthorizationUrl | undefined; initialized: boolean; callbackSent: boolean; + codeLogin: boolean; + submitCode: ((response: string) => Effect.Effect) | undefined; fiber: Fiber.Fiber | undefined; forwarding: Fiber.Fiber | undefined; } @@ -79,6 +84,13 @@ export interface AntigravityAuth { ) => Effect.Effect; } +/** `agy acp --login`: it prints a Google link and reads the code the Antigravity page shows. */ +export interface AntigravityCodeLogin { + readonly submit: (response: string) => Effect.Effect; + /** Succeeds once the runtime has stored the sign-in. */ + readonly completed: Effect.Effect; +} + export type AntigravityAuthRuntime = Pick< AcpSessionRuntime.AcpSessionRuntime["Service"], "initialize" | "start" | "request" @@ -98,6 +110,14 @@ export interface AntigravityAuthOptions< readonly onSignedOut: Effect.Effect; readonly forwardCallback?: (callback: URL) => Effect.Effect; readonly usesBrowser?: boolean; + /** Undefined when the runtime signs in through ACP `authenticate` and T3's browser helper. */ + readonly codeLogin?: (input: { + readonly onAuthorizationUrl: (url: string) => Effect.Effect; + }) => Effect.Effect< + AntigravityCodeLogin | undefined, + AcpErrors.AcpError | ProviderSetupError, + Scope.Scope + >; } function visibleSnapshot(snapshot: AuthSnapshot, ownerSessionId: string): ProviderAuthState { @@ -185,7 +205,11 @@ export const makeAntigravityAuth = Effect.fn("makeAntigravityAuth")(function* < ); const publishFlow = (flow: AuthFlow, state: ProviderAuthState) => { flow.state = state; - return SubscriptionRef.set(snapshot, { ownerSessionId: flow.ownerSessionId, state }); + return SubscriptionRef.set(snapshot, { + ownerSessionId: flow.ownerSessionId, + state, + codeLogin: flow.codeLogin, + }); }; const stopOwnedProcesses = Effect.suspend(() => Effect.forEach( @@ -260,8 +284,8 @@ export const makeAntigravityAuth = Effect.fn("makeAntigravityAuth")(function* < }), ); - const receiveAuthorizationUrl = (flow: AuthFlow, url: string) => - parseAntigravityAuthorizationUrl(url).pipe( + const receiveAuthorizationUrl = (flow: AuthFlow, url: string, redirect: "loopback" | "code") => + parseAntigravityAuthorizationUrl(url, redirect).pipe( Effect.flatMap((authorization) => lock.withPermits(1)( Effect.gen(function* () { @@ -274,12 +298,15 @@ export const makeAntigravityAuth = Effect.fn("makeAntigravityAuth")(function* < }); } flow.pending = authorization; + flow.codeLogin = redirect === "code"; yield* publishFlow(flow, { ...flow.state, phase: "waiting", authorizationUrl: authorization.authorizationUrl, message: - "Open the Google sign-in link. If you are remote, paste the redirect URL here.", + redirect === "loopback" + ? "Open the Google sign-in link. If you are remote, paste the redirect URL here." + : "Open the Google sign-in link, then paste the code from the Antigravity page here.", }); }), ), @@ -302,9 +329,24 @@ export const makeAntigravityAuth = Effect.fn("makeAntigravityAuth")(function* < const runSignIn = Effect.fn("AntigravityAuth.runSignIn")( function* (flow: AuthFlow, stopSessions: Effect.Effect) { yield* stopSessions.pipe(Effect.ensuring(stopOwnedProcesses)); - const runtime = yield* options.makeRuntime({ - onAuthorizationUrl: (url) => receiveAuthorizationUrl(flow, url), - }); + const signedIn = yield* Effect.scoped( + Effect.gen(function* () { + const login = yield* ( + options.codeLogin?.({ + onAuthorizationUrl: (url) => receiveAuthorizationUrl(flow, url, "code"), + }) ?? Effect.undefined + ); + if (login === undefined) return false; + flow.submitCode = login.submit; + yield* login.completed; + return true; + }), + ); + const runtime = yield* options.makeRuntime( + signedIn + ? {} + : { onAuthorizationUrl: (url) => receiveAuthorizationUrl(flow, url, "loopback") }, + ); const startupHint = yield* publishStartingHint(flow, STARTUP_HINT_MS, NOT_STARTED_MESSAGE); // `start` reuses this memoized handshake. yield* runtime.initialize(); @@ -428,6 +470,8 @@ export const makeAntigravityAuth = Effect.fn("makeAntigravityAuth")(function* < pending: undefined, initialized: false, callbackSent: false, + codeLogin: false, + submitCode: undefined, fiber: undefined, forwarding: undefined, }; @@ -489,6 +533,43 @@ export const makeAntigravityAuth = Effect.fn("makeAntigravityAuth")(function* < } return pending.flow.state; }), + respond: Effect.fn("AntigravityAuth.respond")(function* (ownerSessionId, input) { + return yield* lock.withPermits(1)( + Effect.gen(function* () { + const flow = yield* requireFlow(ownerSessionId, input.flowId, "respond"); + if (!flow.pending || !flow.submitCode || flow.callbackSent) { + return yield* setupError( + "respond", + flow.callbackSent + ? "The sign-in response was already sent. Wait for Google to finish." + : "Wait for the Google sign-in link before you send a code.", + ); + } + const response = + input.interactionId === flow.id && input.response.type === "credentials" + ? antigravityLoginResponse( + flow.pending, + input.response.values[LOGIN_CODE_FIELD] ?? "", + ) + : undefined; + if (response === undefined) { + return yield* setupError( + "respond", + "Paste the code from the Antigravity page, or that page's full URL.", + ); + } + flow.callbackSent = true; + yield* flow.submitCode(response); + yield* publishFlow(flow, { + ...flow.state, + phase: "verifying", + authorizationUrl: null, + message: "Waiting for Google to finish sign-in.", + }); + return flow.state; + }), + ); + }), cancel: Effect.fn("AntigravityAuth.cancel")(function* (ownerSessionId, flowId) { const flow = yield* lock.withPermits(1)(requireFlow(ownerSessionId, flowId, "cancel")); yield* stopFlow(flow, "cancelled", "Google sign-in was cancelled."); @@ -580,13 +661,25 @@ export const makeAntigravityAuth = Effect.fn("makeAntigravityAuth")(function* < credentialOwner: "provider" as const, interaction: state.phase === "waiting" && state.authorizationUrl && state.flowId - ? { - type: "browser" as const, - id: state.flowId, - url: state.authorizationUrl, - requiresConsent: false, - acceptsCallback: true, - } + ? value.codeLogin + ? { + type: "credentials" as const, + id: state.flowId, + fields: [ + { + name: LOGIN_CODE_FIELD, + label: "Code from the Antigravity page", + secret: false, + }, + ], + } + : { + type: "browser" as const, + id: state.flowId, + url: state.authorizationUrl, + requiresConsent: false, + acceptsCallback: true, + } : null, }; }), diff --git a/apps/server/src/provider/Drivers/AntigravityDriver.ts b/apps/server/src/provider/Drivers/AntigravityDriver.ts index 1117fc3b9376c..2114aec8e5c60 100644 --- a/apps/server/src/provider/Drivers/AntigravityDriver.ts +++ b/apps/server/src/provider/Drivers/AntigravityDriver.ts @@ -16,11 +16,14 @@ import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; +import * as Fiber from "effect/Fiber"; import * as FileSystem from "effect/FileSystem"; +import * as Option from "effect/Option"; import * as Path from "effect/Path"; import * as Schema from "effect/Schema"; import * as Scope from "effect/Scope"; import * as Stream from "effect/Stream"; +import * as ChildProcess from "effect/process/ChildProcess"; import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; import { HttpClient } from "effect/http"; import * as AcpErrors from "effect-acp/errors"; @@ -200,10 +203,14 @@ export const AntigravityDriver: ProviderDriver< Effect.map((catalog) => stampIdentity(ModelCatalog.applyModelCatalog(draft, catalog))), ); - const makeRuntime = Effect.fn("AntigravityDriver.makeRuntime")(function* ( - input: AntigravityAdapterV2RuntimeInput, + const prepareSpawn = Effect.fn("AntigravityDriver.prepareSpawn")(function* ( + cwd: string, + baseEnv: NodeJS.ProcessEnv, ): Effect.fn.Return< - AcpSessionRuntime.AcpSessionRuntime["Service"], + { + readonly executable: AntigravityInstallation.AntigravityExecutable; + readonly spawn: AcpSessionRuntime.AcpSpawnInput; + }, AcpErrors.AcpError | ProviderSetupError, Scope.Scope > { @@ -270,26 +277,41 @@ export const AntigravityDriver: ProviderDriver< ), ), ); + return { + executable, + spawn: buildAntigravityAcpSpawnInput({ + installation: executable, + profile, + cwd, + baseEnv, + auth, + runtimeTempDirectory, + }), + }; + }); + + const makeRuntime = Effect.fn("AntigravityDriver.makeRuntime")(function* ( + input: AntigravityAdapterV2RuntimeInput, + ): Effect.fn.Return< + AcpSessionRuntime.AcpSessionRuntime["Service"], + AcpErrors.AcpError | ProviderSetupError, + Scope.Scope + > { // `buildAntigravityAcpSpawnInput` sets `extendEnv: false`, so thread variables only reach the // agent's shell through `baseEnv`. const { processEnvironment: threadEnvironment, ...runtimeInput } = input; - const spawnEnvironment = + const { executable, spawn } = yield* prepareSpawn( + runtimeInput.cwd, threadEnvironment === undefined ? processEnvironment - : { ...processEnvironment, ...threadEnvironment }; + : { ...processEnvironment, ...threadEnvironment }, + ); const runtime = yield* makeAntigravityAcpRuntime({ ...runtimeInput, runtimeVersion: executable.version, authMethod: auth.authMethod, childProcessSpawner: spawner, - spawn: buildAntigravityAcpSpawnInput({ - installation: executable, - profile, - cwd: runtimeInput.cwd, - baseEnv: spawnEnvironment, - auth, - runtimeTempDirectory, - }), + spawn, }).pipe(Effect.provideService(SecureRandom.SecureRandom, random)); return { ...runtime, @@ -354,6 +376,85 @@ export const AntigravityDriver: ProviderDriver< }; }); + // The agy CLI ignores T3's browser helper during ACP `authenticate`, so Google sign-in runs its + // remote-friendly `--login`, which stores the sign-in where the ACP process reads it. + const codeLogin = Effect.fn("AntigravityDriver.codeLogin")(function* (input: { + readonly onAuthorizationUrl: (url: string) => Effect.Effect; + }) { + if (auth.authMethod !== "oauth-personal") return undefined; + const resolved = yield* installation + .resolve(settings.binaryPath, processEnvironment) + .pipe(Effect.option); + if (Option.isSome(resolved) && resolved.value.harnessPath !== null) return undefined; + const cwd = yield* fileSystem + .makeTempDirectoryScoped({ prefix: "t3-antigravity-login-" }) + .pipe( + Effect.mapError( + () => + new ProviderSetupError({ + instanceId, + operation: "start", + detail: "Could not create an Antigravity setup workspace.", + }), + ), + ); + const { executable, spawn } = yield* prepareSpawn(cwd, processEnvironment); + if (executable.harnessPath !== null) return undefined; + const failed = (detail: string, cause?: unknown) => + new ProviderSetupError({ instanceId, operation: "start", detail, cause }); + // Without a display it prints the link only, instead of opening a browser on this machine. + const { DISPLAY: _display, WAYLAND_DISPLAY: _wayland, ...env } = spawn.env ?? {}; + const child = yield* spawner + .spawn( + ChildProcess.make(spawn.command, [...spawn.args, "--login"], { + cwd, + env, + extendEnv: false, + shell: false, + }), + ) + .pipe(Effect.mapError((cause) => failed("Could not start Antigravity sign-in.", cause))); + const code = yield* Deferred.make(); + yield* Stream.fromEffect(Deferred.await(code)).pipe( + Stream.map((response) => `${response}\n`), + Stream.encodeText, + Stream.run(child.stdin), + Effect.ignore, + Effect.forkScoped, + ); + const output = yield* child.stdout.pipe( + Stream.decodeText(), + Stream.splitLines, + Stream.map((line) => line.trim()), + Stream.runForEach((line) => + line.startsWith("https://accounts.google.com/") + ? input.onAuthorizationUrl(line) + : Effect.void, + ), + Effect.forkScoped, + ); + yield* Stream.runDrain(child.stderr).pipe(Effect.ignore, Effect.forkScoped); + return { + submit: (response: string) => Deferred.succeed(code, response).pipe(Effect.asVoid), + completed: Effect.gen(function* () { + // Stdout closes when the process exits, or this fails first on an unusable link. + yield* Fiber.join(output).pipe( + Effect.mapError((cause) => + failed("Antigravity returned an invalid Google sign-in link.", cause), + ), + ); + const exitCode = yield* child.exitCode.pipe( + Effect.mapError((cause) => failed("Antigravity sign-in stopped unexpectedly.", cause)), + ); + if (Number(exitCode) !== 0) { + return yield* failed( + "Antigravity could not finish Google sign-in. Start sign-in again.", + ); + } + }), + }; + }); + const publishCatalog = Effect.fn("AntigravityDriver.publishCatalog")(function* ( started: AcpSessionRuntime.AcpSessionRuntimeStartResult, runtime: Pick< @@ -394,6 +495,7 @@ export const AntigravityDriver: ProviderDriver< ), onSignedOut: Effect.suspend(() => provider.onSignedOut), usesBrowser: antigravityAuthUsesBrowser(auth.authMethod), + codeLogin, }); // The probe must not spawn. The agent is a PyInstaller one-file bundle diff --git a/apps/server/src/provider/antigravityAuthSupport.test.ts b/apps/server/src/provider/antigravityAuthSupport.test.ts index 4476ccd3a2d1c..d4e4ed2ddff90 100644 --- a/apps/server/src/provider/antigravityAuthSupport.test.ts +++ b/apps/server/src/provider/antigravityAuthSupport.test.ts @@ -30,6 +30,7 @@ import { isAntigravitySignInRequiredError, makeAntigravityStderrHandler, makeAntigravityStdoutTransform, + antigravityLoginResponse, parseAntigravityAuthorizationUrl, prepareAntigravityProfile, resolveAntigravityInstanceDirectories, @@ -272,6 +273,46 @@ describe("Antigravity authorization URL", () => { ); }); +describe("Antigravity code sign-in", () => { + const loginUrl = + "https://accounts.google.com/o/oauth2/auth?access_type=offline&code_challenge_method=S256&redirect_uri=https%3A%2F%2Fantigravity.google%2Foauth-callback&response_type=code&state=login-state"; + + it.effect("accepts the agy CLI's link and only a code or page URL for that sign-in", () => + Effect.gen(function* () { + const pending = yield* parseAntigravityAuthorizationUrl(loginUrl, "code"); + expect(pending.redirectUri).toBe("https://antigravity.google/oauth-callback"); + for (const other of [ + loginUrl.replace("antigravity.google", "antigravity.google.example.invalid"), + loginUrl.replace("/o/oauth2/auth", "/o/oauth2/v2/auth"), + ]) { + expect( + Result.isFailure( + yield* parseAntigravityAuthorizationUrl(other, "code").pipe(Effect.result), + ), + ).toBe(true); + } + expect( + Result.isFailure(yield* parseAntigravityAuthorizationUrl(loginUrl).pipe(Effect.result)), + ).toBe(true); + + const page = "https://antigravity.google/oauth-callback?state=login-state&code=4%2F0Ab-c"; + expect(antigravityLoginResponse(pending, " 4/0Ab-code_1.x~ ")).toBe("4/0Ab-code_1.x~"); + expect(antigravityLoginResponse(pending, page)).toBe(page); + for (const invalid of [ + "", + "4/0Ab code", + "4/0Ab\nsecond line", + page.replace("login-state", "other-state"), + page.replace("antigravity.google", "evil.example"), + page.replace("&code=4%2F0Ab-c", ""), + `${page}&code=again`, + ]) { + expect(antigravityLoginResponse(pending, invalid)).toBeUndefined(); + } + }), + ); +}); + describe("Antigravity sign-in errors", () => { it("recognizes native auth-required errors and the blocked-login transport error", () => { expect(isAntigravitySignInRequiredError(AcpErrors.AcpRequestError.authRequired())).toBe(true); diff --git a/apps/server/src/provider/antigravityAuthSupport.ts b/apps/server/src/provider/antigravityAuthSupport.ts index 47be6bf31ccae..c7245536a5535 100644 --- a/apps/server/src/provider/antigravityAuthSupport.ts +++ b/apps/server/src/provider/antigravityAuthSupport.ts @@ -499,9 +499,13 @@ export function buildAntigravityAcpSpawnInput(input: { }; } +/** Where `agy acp --login` sends Google; the page shows a code the user pastes back. */ +const ANTIGRAVITY_CODE_REDIRECT_URI = "https://antigravity.google/oauth-callback"; + export const parseAntigravityAuthorizationUrl = Effect.fn("parseAntigravityAuthorizationUrl")( function* ( authorizationUrl: string, + kind: "loopback" | "code" = "loopback", ): Effect.fn.Return { const invalidUrl = () => authSupportError("Antigravity returned an invalid Google sign-in URL."); @@ -513,7 +517,7 @@ export const parseAntigravityAuthorizationUrl = Effect.fn("parseAntigravityAutho const redirectUri = url.searchParams.get("redirect_uri"); if ( url.origin !== "https://accounts.google.com" || - url.pathname !== "/o/oauth2/v2/auth" || + url.pathname !== (kind === "loopback" ? "/o/oauth2/v2/auth" : "/o/oauth2/auth") || url.username !== "" || url.password !== "" || url.hash !== "" || @@ -526,16 +530,46 @@ export const parseAntigravityAuthorizationUrl = Effect.fn("parseAntigravityAutho state.length > 512 || /\s/.test(state) || redirectUri === null || - !/^http:\/\/127\.0\.0\.1:[1-9][0-9]{0,4}\/$/.test(redirectUri) + (kind === "loopback" + ? !/^http:\/\/127\.0\.0\.1:[1-9][0-9]{0,4}\/$/.test(redirectUri) + : redirectUri !== ANTIGRAVITY_CODE_REDIRECT_URI) ) { return yield* invalidUrl(); } + if (kind === "code") return { authorizationUrl, redirectUri, state }; const redirect = yield* decodeUrl(redirectUri).pipe(Effect.mapError(invalidUrl)); if (Number(redirect.port) < 1_024) return yield* invalidUrl(); return { authorizationUrl, redirectUri, state }; }, ); +/** + * What `agy acp --login` reads after its link: the code the Antigravity page shows, or that page's + * URL, which must answer this sign-in. Undefined for anything else, including any line break. + */ +export function antigravityLoginResponse( + pending: AntigravityAuthorizationUrl, + response: string, +): string | undefined { + const value = response.trim(); + if (/^[\w./~-]{1,2048}$/.test(value)) return value; + if (value.length > maxAuthorizationUrlLength || /\s/.test(value)) return undefined; + const url = URL.parse(value); + if ( + url === null || + `${url.origin}${url.pathname}` !== pending.redirectUri || + url.username !== "" || + url.password !== "" || + url.searchParams.getAll("state").length !== 1 || + url.searchParams.get("state") !== pending.state || + url.searchParams.getAll("code").length !== 1 || + !url.searchParams.get("code") + ) { + return undefined; + } + return value; +} + export function makeAntigravityStdoutTransform( input: { readonly onAuthorizationUrl?: ( diff --git a/docs/user/providers-antigravity.md b/docs/user/providers-antigravity.md index db2a06661c8e7..d8d811bd58f68 100644 --- a/docs/user/providers-antigravity.md +++ b/docs/user/providers-antigravity.md @@ -18,7 +18,11 @@ Antigravity setup. ### Sign in from a remote device -Google returns to a `127.0.0.1` address. It can finish directly when your browser is +With the native CLI, Google finishes on an Antigravity page that shows a code. Paste that +code, or the page's full address, into the code field in the client where you started +sign-in. This works the same from any device. + +With the older 1.4.5 runtime, Google returns to a `127.0.0.1` address. It can finish directly when your browser is on the environment's machine. From another device, the final page will usually fail to load because the sign-in listener is on the environment. From 9f6f5540cfe975b6c2748f8e11de62c243dd4414 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 19 Nov 2026 15:41:54 -0800 Subject: [PATCH 94/97] fix(server): worktree handoff no longer leaves Antigravity threads Waiting (#39422) --- .../Adapters/AcpAdapterV2.test.ts | 42 ++++++++++++++- .../orchestration-v2/RunExecutionService.ts | 6 ++- .../SelectionRestart.integration.test.ts | 51 +++++++++++++++++-- packages/provider-acp/src/server/adapter.ts | 6 +++ 4 files changed, 99 insertions(+), 6 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts index 9c8b403a748a6..4fb03956e9e13 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts @@ -623,6 +623,7 @@ const makePromptInactivityHarness = Effect.fnUntraced(function* (input: { ) => AcpSessionRuntime.AcpSessionRuntime["Service"]["prompt"]; readonly cancelled?: Deferred.Deferred; readonly followAgentWorkState?: boolean; + readonly sessionScope?: Scope.Scope; }) { const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; const natives: Array = []; @@ -663,12 +664,15 @@ const makePromptInactivityHarness = Effect.fnUntraced(function* (input: { cwd: process.cwd(), }); const modelSelection = { instanceId, model: "default" } as const; - const runtime = yield* adapter.openSession({ + const opened = adapter.openSession({ threadId, providerSessionId: ProviderSessionId.make("provider-session-acp-prompt-inactivity"), modelSelection, runtimePolicy, }); + const runtime = yield* input.sessionScope === undefined + ? opened + : opened.pipe(Effect.provideService(Scope.Scope, input.sessionScope)); const providerThread = yield* runtime.ensureThread({ threadId, modelSelection, runtimePolicy }); const startTurn = (ordinal: number) => DateTime.now.pipe( @@ -5840,6 +5844,42 @@ describe("AcpAdapterV2", () => { }).pipe(Effect.provide(layerTest)), ); + it.effect("ends a running T3 MCP tool call when its session closes mid-prompt", () => + Effect.gen(function* () { + const sessionScope = yield* Scope.make(); + const harness = yield* makePromptInactivityHarness({ + sessionScope, + environment: () => ({ T3_ACP_EMIT_TRACKED_TOOL_CALL_KIND_THEN_HANG: "other" }), + }); + const trackedToolStatus = (event: ProviderAdapter.ProviderAdapterV2Event) => + event.type === "turn_item.updated" && + event.turnItem.nativeItemRef?.nativeId === "tracked-tool-call" + ? event.turnItem.status + : undefined; + yield* harness.startTurn(1); + yield* harness.runtime.events.pipe( + Stream.filter((event) => trackedToolStatus(event) !== undefined), + Stream.runHead, + ); + // t3_worktree_handoff releases the live session while its own tool call is open. + yield* Scope.close(sessionScope, Exit.void); + // The event queue outlives the session; only events emitted by the close remain. + const after = yield* harness.runtime.events.pipe( + Stream.filter((event) => trackedToolStatus(event) !== undefined), + Stream.map(trackedToolStatus), + Stream.takeUntil((status) => status !== "pending" && status !== "running"), + Stream.runCollect, + Effect.map((collected) => Array.from(collected)), + Effect.timeoutOption("1 second"), + Effect.forkChild, + ); + yield* TestClock.adjust("1 second"); + const statuses = Option.getOrElse(yield* Fiber.join(after), () => []); + // regression: #39410 the handoff's tool call stayed running after the session closed. + assert.include(["completed", "failed", "interrupted", "cancelled"], statuses.at(-1)); + }).pipe(Effect.provide(layerTest)), + ); + it.live("does not poll the process ledger while a cgroup lease owns teardown", () => Effect.gen(function* () { if ((yield* HostProcess.Platform) !== "linux") return; diff --git a/apps/server/src/orchestration-v2/RunExecutionService.ts b/apps/server/src/orchestration-v2/RunExecutionService.ts index f1d21f4a6bad5..da162282719aa 100644 --- a/apps/server/src/orchestration-v2/RunExecutionService.ts +++ b/apps/server/src/orchestration-v2/RunExecutionService.ts @@ -2055,7 +2055,11 @@ export const layer: Layer.Layer< ).pipe(Effect.as(false)), ), ); - if (handedOff) return; + if (handedOff) { + // Its tool calls, the handoff's own among them, died with that process. + yield* endWorkLostAfterRootRun(completedAt); + return; + } } yield* Effect.logWarning("orchestration V2 provider event ingestion failed", { runId: input.run.id, diff --git a/apps/server/src/orchestration-v2/SelectionRestart.integration.test.ts b/apps/server/src/orchestration-v2/SelectionRestart.integration.test.ts index 683fb14d44cc3..890aa9d97467e 100644 --- a/apps/server/src/orchestration-v2/SelectionRestart.integration.test.ts +++ b/apps/server/src/orchestration-v2/SelectionRestart.integration.test.ts @@ -16,6 +16,7 @@ import { ProviderTurnId, type RunId, ThreadId, + TurnItemId, } from "@t3tools/contracts"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; @@ -462,19 +463,54 @@ it.live.each(["pooled", "exclusive"] as const)( state, mode === "pooled" ? pooledCapabilities : exclusiveCapabilities, ); + const handoffToolId = TurnItemId.make(`turn-item:workspace-handoff:${mode}:tool`); // A session that closes on detach is never asked to interrupt: Claude's cannot answer. + // Its turn is inside the handoff's own tool call, which the closed session never ends. const adapter: ProviderAdapter.ProviderAdapterV2["Service"] = mode === "pooled" ? base : { ...base, openSession: (input) => - base.openSession(input).pipe( - Effect.map((session) => ({ + Effect.gen(function* () { + const session = yield* base.openSession(input); + const toolEvents = + yield* Queue.unbounded(); + return { ...session, + events: Stream.merge(session.events, Stream.fromQueue(toolEvents)), + startTurn: (turn) => + Effect.gen(function* () { + yield* session.startTurn(turn); + const now = yield* DateTime.now; + yield* Queue.offer(toolEvents, { + type: "turn_item.updated", + driver, + turnItem: { + id: handoffToolId, + type: "dynamic_tool", + threadId: turn.threadId, + runId: turn.runId, + nodeId: turn.rootNodeId, + providerThreadId: turn.providerThread.id, + providerTurnId: ProviderTurnId.make(`provider-turn:${turn.attemptId}`), + nativeItemRef: null, + parentItemId: null, + ordinal: 1, + status: "running", + title: "t3_worktree_handoff", + toolName: "t3-code.t3_worktree_handoff", + input: {}, + output: null, + startedAt: now, + completedAt: null, + updatedAt: now, + }, + }); + }), interruptTurn: () => Effect.die("an exclusive handoff must not interrupt"), - })), - ), + }; + }), }; const layerRegistry = ProviderAdapterRegistry.layerSingle(adapter); @@ -585,6 +621,13 @@ it.live.each(["pooled", "exclusive"] as const)( ), "an intentional workspace handoff must not project an interrupt result or a failure", ); + if (mode === "exclusive") { + // regression: #39410 the handoff's tool call stayed running after its session closed. + assert.equal( + projection.turnItems.find((item) => item.id === handoffToolId)?.status, + "interrupted", + ); + } assert.deepEqual( (yield* Ref.get(state)).started.map((turn) => turn.cwd), [cwd, handoffCwd], diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index ea1c83091d5f9..8b696761742f7 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -9646,6 +9646,12 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( yield* Ref.update(continuationGeneration, (value) => value + 1); }), ); + // A session released mid-prompt (worktree handoff) never sees its prompt settle. + const openTurn = yield* Ref.get(activeTurn); + if (openTurn !== null && !openTurn.finalized) { + openTurn.interrupted = true; + yield* finalizeTurn(openTurn, "interrupted"); + } const requests = [...(yield* Ref.get(pendingRuntimeRequests)).values()]; yield* Effect.forEach( requests, From dcf158c5915baaf961ddc1bce06cafd4d2eeeb00 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 19 Nov 2026 15:47:05 -0800 Subject: [PATCH 95/97] feat(server): setting and managed policy to turn off the preview tunnel (#39415) Co-authored-by: Claude Opus 5.5 --- .../src/features/browser/BrowserTabMenu.tsx | 4 +- .../browser/LocalPreviewRouteScreen.tsx | 23 +++- .../src/features/threads/ThreadFeed.tsx | 11 +- apps/mobile/src/i18n/translations/de.json | 3 + apps/mobile/src/i18n/translations/en.json | 3 + apps/mobile/src/i18n/translations/es.json | 3 + apps/mobile/src/i18n/translations/fr.json | 3 + apps/mobile/src/i18n/translations/ja.json | 3 + apps/mobile/src/i18n/translations/ko.json | 3 + apps/mobile/src/i18n/translations/pt-BR.json | 3 + apps/mobile/src/i18n/translations/ru.json | 3 + apps/mobile/src/i18n/translations/sv.json | 3 + apps/mobile/src/i18n/translations/zh.json | 3 + apps/mobile/src/lib/filePreview.test.ts | 1 + apps/mobile/src/state/entities.ts | 7 ++ .../src/environment/ServerEnvironment.ts | 1 + apps/server/src/policy/ManagedPolicy.test.ts | 9 +- apps/server/src/policy/ManagedPolicy.ts | 4 +- apps/server/src/policy/policyTemplates.ts | 6 + apps/server/src/preview/PreviewTunnel.test.ts | 115 +++++++++++++++++- apps/server/src/preview/PreviewTunnel.ts | 59 ++++++++- apps/web/src/browser/previewRuntime.ts | 34 +++++- .../CommandPalettePortForwardItems.tsx | 3 +- .../components/chat/ThreadServersPanel.tsx | 25 +++- .../src/components/preview/PreviewView.tsx | 8 +- .../settings/ConnectionsSettings.tsx | 27 ++++ .../src/components/settings/settingsSearch.ts | 9 ++ apps/web/src/i18n/translations/de.json | 6 + apps/web/src/i18n/translations/en.json | 6 + apps/web/src/i18n/translations/es.json | 6 + apps/web/src/i18n/translations/fr.json | 6 + apps/web/src/i18n/translations/ja.json | 6 + apps/web/src/i18n/translations/ko.json | 6 + apps/web/src/i18n/translations/pt-BR.json | 6 + apps/web/src/i18n/translations/ru.json | 6 + apps/web/src/i18n/translations/sv.json | 6 + apps/web/src/i18n/translations/zh.json | 6 + apps/web/src/state/portForwards.ts | 18 ++- docs/internals/remote.md | 3 + docs/user/managed-policy.md | 5 + docs/user/remote-access.md | 8 ++ packages/client-runtime/src/contractLabels.ts | 10 +- packages/contracts/src/environment.ts | 2 + packages/contracts/src/managedPolicy.ts | 14 +++ packages/contracts/src/settings.ts | 5 +- packages/shared/src/managedPolicyFile.ts | 1 + 46 files changed, 472 insertions(+), 30 deletions(-) diff --git a/apps/mobile/src/features/browser/BrowserTabMenu.tsx b/apps/mobile/src/features/browser/BrowserTabMenu.tsx index c0df3fb971419..a98bded8b883e 100644 --- a/apps/mobile/src/features/browser/BrowserTabMenu.tsx +++ b/apps/mobile/src/features/browser/BrowserTabMenu.tsx @@ -16,6 +16,7 @@ import { msg, useGT, useMessages } from "gt-react-native"; import { ControlPill } from "../../components/ui/ControlPill"; import { Menu } from "../../components/ui/Menu"; import { m } from "../../i18n/messages"; +import { useEnvironmentPreviewTunnelOff } from "../../state/entities"; import { previewEnvironment } from "../../state/preview"; import { useAtomCommand } from "../../state/use-atom-command"; import { browserTabUrl, loopbackUrlForDevice } from "./browserTabs"; @@ -65,6 +66,7 @@ export function BrowserTabMenu({ readonly onReleaseControl?: () => void; }) { const openLocalPreview = useOpenLocalPreview(); + const tunnelOff = useEnvironmentPreviewTunnelOff(environmentId); const adjust = useAtomCommand(previewEnvironment.adjust, "browser tab change"); const resize = useAtomCommand(previewEnvironment.resize, "browser viewport change"); const close = useAtomCommand(previewEnvironment.close, "browser tab close"); @@ -92,7 +94,7 @@ export function BrowserTabMenu({ image: "xmark", attributes: { destructive: true, disabled: !canClose }, }; - const deviceUrl = loopbackUrlForDevice(browserTabUrl(tab)); + const deviceUrl = tunnelOff ? null : loopbackUrlForDevice(browserTabUrl(tab)); // The device preview has its own webview and tunnel, so it doesn't wait for the stream. const openOnDevice: MenuAction[] = deviceUrl ? [{ id: "open-on-device", title: gt("Open on this device"), image: "iphone" }] diff --git a/apps/mobile/src/features/browser/LocalPreviewRouteScreen.tsx b/apps/mobile/src/features/browser/LocalPreviewRouteScreen.tsx index e8750bcf74349..8cfd22142698a 100644 --- a/apps/mobile/src/features/browser/LocalPreviewRouteScreen.tsx +++ b/apps/mobile/src/features/browser/LocalPreviewRouteScreen.tsx @@ -10,6 +10,7 @@ import { AppText } from "../../components/ui/AppText"; import * as Dialog from "../../components/ui/Dialog"; import { EmptyState } from "../../components/ui/EmptyState"; import { m } from "../../i18n/messages"; +import { useEnvironmentPreviewTunnelOff } from "../../state/entities"; import { useEnvironments } from "../../state/environments"; import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider"; import { BrowserChrome } from "./BrowserBar"; @@ -49,6 +50,7 @@ export function LocalPreviewScreen(props: { useEnvironments().presentationById.get(environmentId)?.entry.target.label ?? gt("the environment", { $context: "stands in for an environment name in a sentence" }); const { themeVariables } = useAppearancePreferences(); + const tunnelOff = useEnvironmentPreviewTunnelOff(environmentId); const webView = useRef(null); const [requested, setRequested] = useState(initialUrl); const [page, setPage] = useState(null); @@ -77,7 +79,7 @@ export function LocalPreviewScreen(props: { }; const back = () => void webView.current?.goBack(); const canGoBack = page?.canGoBack ?? false; - const pageColor = failed || unsupported !== null ? null : page?.pageColor || null; + const pageColor = failed || tunnelOff || unsupported !== null ? null : page?.pageColor || null; return ( // Full screen spans the Duo's rail, so it insets its own sides; the pane is inset already. @@ -127,7 +129,24 @@ export function LocalPreviewScreen(props: { setFailed(true); }} /> - {unsupported !== null ? ( + {tunnelOff ? ( + + + + + + ) : unsupported !== null ? ( + previewTunnelOff ? null : loopbackUrlForDevice(href); // Recycling a row disposes its native audio player, so a started clip's row stays rendered. const [retainedMediaRowId, setRetainedMediaRowId] = useState(null); const focused = useIsFocused(); @@ -3421,7 +3426,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { return; } // Safari would open the phone's own localhost, so these open on the device by default. - const deviceUrl = loopbackUrlForDevice(href); + const deviceUrl = deviceLoopbackUrl(href); if (deviceUrl) { openLocalPreview( { environmentId: String(props.environmentId), threadId: String(props.threadId) }, @@ -3559,7 +3564,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { }; } // The environment's localhost, which this device can only reach through the tunnel. - if (loopbackUrlForDevice(href)) { + if (deviceLoopbackUrl(href)) { return { title: href, actions: [ @@ -3585,7 +3590,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { else if (actionId === "copy-thread-link") copyTextWithHaptic(hostedThreadLink(thread)); return; } - const deviceUrl = loopbackUrlForDevice(href); + const deviceUrl = deviceLoopbackUrl(href); if (deviceUrl) { if (actionId === "open-on-device") { markdownLinkRequest.current?.abort(); diff --git a/apps/mobile/src/i18n/translations/de.json b/apps/mobile/src/i18n/translations/de.json index 084c9bb22d63b..14a72ef456de5 100644 --- a/apps/mobile/src/i18n/translations/de.json +++ b/apps/mobile/src/i18n/translations/de.json @@ -23,6 +23,7 @@ "ef9533bcc048f17b": "Die Richtlinie von {organization} erlaubt T3 Connect nicht.", "986b0873f913a840": "Die Richtlinie von {organization} erlaubt keine Webhook-Aufgaben.", "eebc538e25b09fe2": "Die Richtlinie von {organization} erlaubt keinen Import von Browser-Cookies.", + "7642a133db05f164": "Die Richtlinie von {organization} erlaubt nicht, die lokalen Server dieses Rechners auf anderen Geräten zu öffnen.", "39f6771b49f9b3b6": "Standard verwenden", "45bb0e90e1c42046": "Wenn du zurückkommst", "d8fa0a55446bbb0d": "Bevor der Cache abläuft (Beta)", @@ -1780,6 +1781,8 @@ "9bce41be8fc55a47": "Cache leeren", "4d7f5af0445371fd": "Optionen für Browser-Tab", "27025b00be488485": "die Umgebung", + "4391875125b7882c": "{environment} teilt seinen localhost nicht", + "ec7a78dd403ccf6a": "Der Vorschau-Tunnel ist dort ausgeschaltet, daher öffnen sich seine lokalen Server nur im gestreamten Browser.", "e1ffd0532d64e52c": "Dieses Gerät kann keine localhost-Seiten öffnen", "f72cc72b321f93a5": "{reason} Für diesen Tab kannst du weiterhin den gestreamten Browser verwenden.", "6bf09d4b7e4ba53b": "T3 Code auf {environment} aktualisieren", diff --git a/apps/mobile/src/i18n/translations/en.json b/apps/mobile/src/i18n/translations/en.json index e4258c6dec547..3596aa21e36af 100644 --- a/apps/mobile/src/i18n/translations/en.json +++ b/apps/mobile/src/i18n/translations/en.json @@ -23,6 +23,7 @@ "ef9533bcc048f17b": "{organization}'s policy does not allow T3 Connect.", "986b0873f913a840": "{organization}'s policy does not allow webhook tasks.", "eebc538e25b09fe2": "{organization}'s policy does not allow importing browser cookies.", + "7642a133db05f164": "{organization}'s policy does not allow opening this machine's local servers on other devices.", "39f6771b49f9b3b6": "Use default", "45bb0e90e1c42046": "When you return", "d8fa0a55446bbb0d": "Before the cache expires (beta)", @@ -1780,6 +1781,8 @@ "9bce41be8fc55a47": "Clear cache", "4d7f5af0445371fd": "Browser tab options", "27025b00be488485": "the environment", + "4391875125b7882c": "{environment} doesn't share its localhost", + "ec7a78dd403ccf6a": "The preview tunnel is off there, so its local servers only open in the streamed browser.", "e1ffd0532d64e52c": "This device can't open localhost pages", "f72cc72b321f93a5": "{reason} You can still use the streamed browser for this tab.", "6bf09d4b7e4ba53b": "Update T3 Code on {environment}", diff --git a/apps/mobile/src/i18n/translations/es.json b/apps/mobile/src/i18n/translations/es.json index 9723fc5471f3b..a18764f050d09 100644 --- a/apps/mobile/src/i18n/translations/es.json +++ b/apps/mobile/src/i18n/translations/es.json @@ -23,6 +23,7 @@ "ef9533bcc048f17b": "La política de {organization} no permite T3 Connect.", "986b0873f913a840": "La política de {organization} no permite tareas de webhook.", "eebc538e25b09fe2": "La política de {organization} no permite importar cookies del navegador.", + "7642a133db05f164": "La política de {organization} no permite abrir los servidores locales de esta máquina en otros dispositivos.", "39f6771b49f9b3b6": "Usar valor predeterminado", "45bb0e90e1c42046": "Cuando vuelvas", "d8fa0a55446bbb0d": "Antes de que caduque la caché (beta)", @@ -1780,6 +1781,8 @@ "9bce41be8fc55a47": "Borrar caché", "4d7f5af0445371fd": "Opciones de la pestaña del navegador", "27025b00be488485": "el entorno", + "4391875125b7882c": "{environment} no comparte su localhost", + "ec7a78dd403ccf6a": "El túnel de vista previa está desactivado allí, así que sus servidores locales solo se abren en el navegador transmitido.", "e1ffd0532d64e52c": "Este dispositivo no puede abrir páginas de localhost", "f72cc72b321f93a5": "{reason} Aún puedes usar el navegador transmitido para esta pestaña.", "6bf09d4b7e4ba53b": "Actualiza T3 Code en {environment}", diff --git a/apps/mobile/src/i18n/translations/fr.json b/apps/mobile/src/i18n/translations/fr.json index 795b4bc67312d..9f12d87dd513b 100644 --- a/apps/mobile/src/i18n/translations/fr.json +++ b/apps/mobile/src/i18n/translations/fr.json @@ -23,6 +23,7 @@ "ef9533bcc048f17b": "La politique de {organization} n’autorise pas T3 Connect.", "986b0873f913a840": "La politique de {organization} n’autorise pas les tâches webhook.", "eebc538e25b09fe2": "La politique de {organization} n’autorise pas l’import des cookies du navigateur.", + "7642a133db05f164": "La stratégie de {organization} n’autorise pas l’ouverture des serveurs locaux de cette machine sur d’autres appareils.", "39f6771b49f9b3b6": "Utiliser la valeur par défaut", "45bb0e90e1c42046": "À votre retour", "d8fa0a55446bbb0d": "Avant l’expiration du cache (bêta)", @@ -1780,6 +1781,8 @@ "9bce41be8fc55a47": "Vider le cache", "4d7f5af0445371fd": "Options de l’onglet du navigateur", "27025b00be488485": "l’environnement", + "4391875125b7882c": "{environment} ne partage pas son localhost", + "ec7a78dd403ccf6a": "Le tunnel d’aperçu y est désactivé, ses serveurs locaux ne s’ouvrent donc que dans le navigateur diffusé.", "e1ffd0532d64e52c": "Cet appareil ne peut pas ouvrir les pages localhost", "f72cc72b321f93a5": "{reason} Tu peux toujours utiliser le navigateur diffusé pour cet onglet.", "6bf09d4b7e4ba53b": "Mettez à jour T3 Code sur {environment}", diff --git a/apps/mobile/src/i18n/translations/ja.json b/apps/mobile/src/i18n/translations/ja.json index 97f21ae2fe472..441175f85337e 100644 --- a/apps/mobile/src/i18n/translations/ja.json +++ b/apps/mobile/src/i18n/translations/ja.json @@ -23,6 +23,7 @@ "ef9533bcc048f17b": "{organization} のポリシーでは、T3 Connect は許可されていません。", "986b0873f913a840": "{organization} のポリシーでは、Webhook タスクは許可されていません。", "eebc538e25b09fe2": "{organization} のポリシーでは、ブラウザーの Cookie のインポートは許可されていません。", + "7642a133db05f164": "{organization} のポリシーでは、このマシンのローカルサーバーを他のデバイスで開くことは許可されていません。", "39f6771b49f9b3b6": "デフォルトを使用", "45bb0e90e1c42046": "戻ってきたとき", "d8fa0a55446bbb0d": "キャッシュの期限切れ前 (ベータ)", @@ -1780,6 +1781,8 @@ "9bce41be8fc55a47": "キャッシュを消去", "4d7f5af0445371fd": "ブラウザータブのオプション", "27025b00be488485": "環境", + "4391875125b7882c": "{environment} は localhost を共有していません", + "ec7a78dd403ccf6a": "そちらではプレビュートンネルがオフのため、ローカルサーバーはストリーミングブラウザでのみ開けます。", "e1ffd0532d64e52c": "このデバイスでは localhost のページを開けません", "f72cc72b321f93a5": "{reason} このタブではストリーミングブラウザを引き続き使えます。", "6bf09d4b7e4ba53b": "{environment} の T3 Code を更新してください", diff --git a/apps/mobile/src/i18n/translations/ko.json b/apps/mobile/src/i18n/translations/ko.json index 2d95884bfc32c..c73c767074bde 100644 --- a/apps/mobile/src/i18n/translations/ko.json +++ b/apps/mobile/src/i18n/translations/ko.json @@ -23,6 +23,7 @@ "ef9533bcc048f17b": "{organization}의 정책상 T3 Connect를 사용할 수 없습니다.", "986b0873f913a840": "{organization}의 정책상 웹후크 작업을 사용할 수 없습니다.", "eebc538e25b09fe2": "{organization}의 정책상 브라우저 쿠키를 가져올 수 없습니다.", + "7642a133db05f164": "{organization}의 정책은 이 컴퓨터의 로컬 서버를 다른 기기에서 여는 것을 허용하지 않습니다.", "39f6771b49f9b3b6": "기본값 사용", "45bb0e90e1c42046": "돌아왔을 때", "d8fa0a55446bbb0d": "캐시가 만료되기 전(베타)", @@ -1780,6 +1781,8 @@ "9bce41be8fc55a47": "캐시 지우기", "4d7f5af0445371fd": "브라우저 탭 옵션", "27025b00be488485": "환경", + "4391875125b7882c": "{environment}에서 localhost를 공유하지 않습니다", + "ec7a78dd403ccf6a": "그곳에서 미리보기 터널이 꺼져 있어 로컬 서버는 스트리밍 브라우저에서만 열립니다.", "e1ffd0532d64e52c": "이 기기에서는 localhost 페이지를 열 수 없습니다", "f72cc72b321f93a5": "{reason} 이 탭에서는 스트리밍 브라우저를 계속 사용할 수 있습니다.", "6bf09d4b7e4ba53b": "{environment}의 T3 Code를 업데이트하세요", diff --git a/apps/mobile/src/i18n/translations/pt-BR.json b/apps/mobile/src/i18n/translations/pt-BR.json index 412808cc9d686..8c9071db5dfee 100644 --- a/apps/mobile/src/i18n/translations/pt-BR.json +++ b/apps/mobile/src/i18n/translations/pt-BR.json @@ -23,6 +23,7 @@ "ef9533bcc048f17b": "A política de {organization} não permite o T3 Connect.", "986b0873f913a840": "A política de {organization} não permite tarefas de webhook.", "eebc538e25b09fe2": "A política de {organization} não permite importar cookies do navegador.", + "7642a133db05f164": "A política de {organization} não permite abrir os servidores locais desta máquina em outros dispositivos.", "39f6771b49f9b3b6": "Usar padrão", "45bb0e90e1c42046": "Quando você voltar", "d8fa0a55446bbb0d": "Antes de o cache expirar (beta)", @@ -1780,6 +1781,8 @@ "9bce41be8fc55a47": "Limpar cache", "4d7f5af0445371fd": "Opções da aba do navegador", "27025b00be488485": "o ambiente", + "4391875125b7882c": "{environment} não compartilha seu localhost", + "ec7a78dd403ccf6a": "O túnel de pré-visualização está desativado lá, então seus servidores locais só abrem no navegador transmitido.", "e1ffd0532d64e52c": "Este dispositivo não consegue abrir páginas de localhost", "f72cc72b321f93a5": "{reason} Você ainda pode usar o navegador transmitido para esta aba.", "6bf09d4b7e4ba53b": "Atualize o T3 Code em {environment}", diff --git a/apps/mobile/src/i18n/translations/ru.json b/apps/mobile/src/i18n/translations/ru.json index b76e105104a8a..ce752d7d25c6f 100644 --- a/apps/mobile/src/i18n/translations/ru.json +++ b/apps/mobile/src/i18n/translations/ru.json @@ -23,6 +23,7 @@ "ef9533bcc048f17b": "Политика {organization} запрещает T3 Connect.", "986b0873f913a840": "Политика {organization} запрещает задачи по вебхуку.", "eebc538e25b09fe2": "Политика {organization} запрещает импорт cookie браузера.", + "7642a133db05f164": "Политика {organization} не разрешает открывать локальные серверы этого компьютера на других устройствах.", "39f6771b49f9b3b6": "По умолчанию", "45bb0e90e1c42046": "Когда вы вернётесь", "d8fa0a55446bbb0d": "До истечения кеша (бета)", @@ -1780,6 +1781,8 @@ "9bce41be8fc55a47": "Очистить кеш", "4d7f5af0445371fd": "Параметры вкладки браузера", "27025b00be488485": "окружение", + "4391875125b7882c": "{environment} не открывает доступ к своему localhost", + "ec7a78dd403ccf6a": "Там выключен туннель предпросмотра, поэтому его локальные серверы открываются только в транслируемом браузере.", "e1ffd0532d64e52c": "Это устройство не может открывать страницы localhost", "f72cc72b321f93a5": "{reason} Для этой вкладки можно по-прежнему использовать транслируемый браузер.", "6bf09d4b7e4ba53b": "Обновите T3 Code на {environment}", diff --git a/apps/mobile/src/i18n/translations/sv.json b/apps/mobile/src/i18n/translations/sv.json index 8629e708c09fe..c87a75ea47e5d 100644 --- a/apps/mobile/src/i18n/translations/sv.json +++ b/apps/mobile/src/i18n/translations/sv.json @@ -23,6 +23,7 @@ "ef9533bcc048f17b": "Policyn för {organization} tillåter inte T3 Connect.", "986b0873f913a840": "Policyn för {organization} tillåter inte webhook-uppgifter.", "eebc538e25b09fe2": "Policyn för {organization} tillåter inte import av cookies från webbläsare.", + "7642a133db05f164": "{organization}s policy tillåter inte att den här datorns lokala servrar öppnas på andra enheter.", "39f6771b49f9b3b6": "Använd standard", "45bb0e90e1c42046": "När du kommer tillbaka", "d8fa0a55446bbb0d": "Innan cachen går ut (beta)", @@ -1780,6 +1781,8 @@ "9bce41be8fc55a47": "Rensa cache", "4d7f5af0445371fd": "Alternativ för webbläsarflik", "27025b00be488485": "miljön", + "4391875125b7882c": "{environment} delar inte sin localhost", + "ec7a78dd403ccf6a": "Förhandsgranskningstunneln är avstängd där, så dess lokala servrar öppnas bara i den strömmade webbläsaren.", "e1ffd0532d64e52c": "Den här enheten kan inte öppna localhost-sidor", "f72cc72b321f93a5": "{reason} Du kan fortfarande använda den strömmade webbläsaren för den här fliken.", "6bf09d4b7e4ba53b": "Uppdatera T3 Code på {environment}", diff --git a/apps/mobile/src/i18n/translations/zh.json b/apps/mobile/src/i18n/translations/zh.json index 45e032bebe433..ce8b8caf281d5 100644 --- a/apps/mobile/src/i18n/translations/zh.json +++ b/apps/mobile/src/i18n/translations/zh.json @@ -23,6 +23,7 @@ "ef9533bcc048f17b": "{organization} 的策略不允许使用 T3 Connect。", "986b0873f913a840": "{organization} 的策略不允许使用 webhook 任务。", "eebc538e25b09fe2": "{organization} 的策略不允许导入浏览器 Cookie。", + "7642a133db05f164": "{organization} 的策略不允许在其他设备上打开此机器的本地服务器。", "39f6771b49f9b3b6": "使用默认值", "45bb0e90e1c42046": "在你回来后", "d8fa0a55446bbb0d": "缓存过期前(测试版)", @@ -1781,6 +1782,8 @@ "9bce41be8fc55a47": "清除缓存", "4d7f5af0445371fd": "浏览器标签页选项", "27025b00be488485": "该环境", + "4391875125b7882c": "{environment} 未共享其 localhost", + "ec7a78dd403ccf6a": "那里的预览隧道已关闭,因此其本地服务器只能在串流浏览器中打开。", "e1ffd0532d64e52c": "此设备无法打开 localhost 页面", "f72cc72b321f93a5": "{reason} 你仍可以为此标签页使用流式浏览器。", "6bf09d4b7e4ba53b": "请更新 {environment} 上的 T3 Code", diff --git a/apps/mobile/src/lib/filePreview.test.ts b/apps/mobile/src/lib/filePreview.test.ts index b93913c00da55..d82e0c5f7abeb 100644 --- a/apps/mobile/src/lib/filePreview.test.ts +++ b/apps/mobile/src/lib/filePreview.test.ts @@ -184,6 +184,7 @@ vi.mock("../state/threads", () => ({ environmentThreadShells: {}, threadEnvironm vi.mock("../state/entities", () => ({ useLiveThreadLinkLabels: (text: string) => text, useThreadChipIcons: () => new Map(), + useEnvironmentPreviewTunnelOff: () => false, })); vi.mock("../state/use-thread-selection", () => ({ useThreadSelection: () => ({ selectedThread: null }), diff --git a/apps/mobile/src/state/entities.ts b/apps/mobile/src/state/entities.ts index 9ca7f1d64496f..462c8dd68c795 100644 --- a/apps/mobile/src/state/entities.ts +++ b/apps/mobile/src/state/entities.ts @@ -8,6 +8,7 @@ import type { EnvironmentThreadShell, } from "@t3tools/client-runtime/state/shell"; import { + allowsPreviewTunnel, EnvironmentId, ThreadId, type ComposerContextRecord, @@ -304,6 +305,12 @@ export function useEnvironmentServerConfig( ); } +/** Whether the environment turned its preview tunnel off; false until its config loads. */ +export function useEnvironmentPreviewTunnelOff(environmentId: EnvironmentId | null): boolean { + const config = useEnvironmentServerConfig(environmentId); + return config !== null && !allowsPreviewTunnel(config); +} + export function useServerConfigs(): ReadonlyMap { return useAtomValue(environmentServerConfigsAtom); } diff --git a/apps/server/src/environment/ServerEnvironment.ts b/apps/server/src/environment/ServerEnvironment.ts index 04f5c9082b606..a9dfdcb6e6048 100644 --- a/apps/server/src/environment/ServerEnvironment.ts +++ b/apps/server/src/environment/ServerEnvironment.ts @@ -273,6 +273,7 @@ export const make = Effect.gen(function* () { serverResolvedCommandContext: true, threadStop: true, ...(hostPlatform === "win32" ? {} : { localServerStop: true }), + previewTunnelSetting: true, environmentIcon: true, projectCloneTracking: true, projectOrganization: true, diff --git a/apps/server/src/policy/ManagedPolicy.test.ts b/apps/server/src/policy/ManagedPolicy.test.ts index a91cdec613095..c52c1f036009a 100644 --- a/apps/server/src/policy/ManagedPolicy.test.ts +++ b/apps/server/src/policy/ManagedPolicy.test.ts @@ -60,11 +60,16 @@ it.layer(NodeServices.layer)("ManagedPolicy.load", (it) => { JSON.stringify({ schemaVersion: 1, organization: "Example Corp", - limits: { webhookTasks: false, telemetry: true }, + limits: { webhookTasks: false, telemetry: true, previewTunnel: false }, }), ); - assert.deepEqual(policy.summary?.limits, { webhookTasks: false, telemetry: true }); + assert.deepEqual(policy.summary?.limits, { + webhookTasks: false, + telemetry: true, + previewTunnel: false, + }); assert.equal(ManagedPolicy.deniedBy(policy, "webhookTasks"), "Example Corp"); + assert.equal(ManagedPolicy.deniedBy(policy, "previewTunnel"), "Example Corp"); assert.isUndefined(ManagedPolicy.deniedBy(policy, "telemetry")); }), ); diff --git a/apps/server/src/policy/ManagedPolicy.ts b/apps/server/src/policy/ManagedPolicy.ts index 01651051893c0..36665b6e1572b 100644 --- a/apps/server/src/policy/ManagedPolicy.ts +++ b/apps/server/src/policy/ManagedPolicy.ts @@ -70,7 +70,7 @@ export const loadedPolicy = Effect.fn("ManagedPolicy.loadedPolicy")(function* ( */ export function deniedBy( policy: Pick, - capability: "webhookTasks" | "telemetry", + capability: "webhookTasks" | "telemetry" | "previewTunnel", ): string | undefined { return policy.document?.limits?.[capability] === false ? policy.document.organization : undefined; } @@ -135,6 +135,7 @@ function summarizeLimits( webhookTasks, telemetry, browserCookieImport, + previewTunnel, providers, updates, } = document.limits ?? {}; @@ -146,6 +147,7 @@ function summarizeLimits( ...(webhookTasks === undefined ? {} : { webhookTasks }), ...(telemetry === undefined ? {} : { telemetry }), ...(browserCookieImport === undefined ? {} : { browserCookieImport }), + ...(previewTunnel === undefined ? {} : { previewTunnel }), ...(providers?.allowedDrivers === undefined && Object.keys(lockedInstanceFields).length === 0 ? {} : { diff --git a/apps/server/src/policy/policyTemplates.ts b/apps/server/src/policy/policyTemplates.ts index 55c15fb94f56c..602bb740db04f 100644 --- a/apps/server/src/policy/policyTemplates.ts +++ b/apps/server/src/policy/policyTemplates.ts @@ -119,6 +119,12 @@ const policies = (): ReadonlyArray => [ help: "Disabled stops users from importing cookies from another browser into T3 Code's browser.", toggle: "BrowserCookieImport", }, + { + id: "PreviewTunnel", + title: "Allow the preview tunnel", + help: "Disabled stops other devices from opening this machine's local servers through T3 Code: no in-app browser tabs loaded on the device, no Open on this device, no port forwarding. Browser tabs still stream from this machine.", + toggle: "PreviewTunnel", + }, { id: "Telemetry", title: "Allow usage data", diff --git a/apps/server/src/preview/PreviewTunnel.test.ts b/apps/server/src/preview/PreviewTunnel.test.ts index 684622e488424..b8a7732d56f83 100644 --- a/apps/server/src/preview/PreviewTunnel.test.ts +++ b/apps/server/src/preview/PreviewTunnel.test.ts @@ -5,16 +5,23 @@ import { AuthOrchestrationReadScope, AuthSessionId, AuthTerminalOperateScope, + DEFAULT_SERVER_SETTINGS, + type ManagedPolicySummary, + type ServerSettings, } from "@t3tools/contracts"; import * as NodeNet from "node:net"; import * as Context from "effect/Context"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; +import * as PubSub from "effect/PubSub"; +import * as Ref from "effect/Ref"; +import * as Stream from "effect/Stream"; import { HttpRouter, HttpServer } from "effect/http"; import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts"; import * as SessionStore from "../auth/SessionStore.ts"; +import { ServerSettingsService } from "../serverSettings.ts"; import * as PreviewTunnel from "./PreviewTunnel.ts"; const listen = (onConnection: (socket: NodeNet.Socket) => void) => @@ -40,13 +47,51 @@ const listen = (onConnection: (socket: NodeNet.Socket) => void) => ), ).pipe(Effect.map(({ server }) => ({ port: (server.address() as NodeNet.AddressInfo).port }))); +/** Settings the route reads; `set` publishes a change as the real service does. */ +const makeSettings = Effect.fn(function* ( + enablePreviewTunnel = true, + managedPolicy?: ManagedPolicySummary, + /** Applied right after the first read, as a change landing while a tunnel dials. */ + afterFirstRead?: Partial, +) { + const current = yield* Ref.make({ + ...DEFAULT_SERVER_SETTINGS, + enablePreviewTunnel, + }); + const changes = yield* PubSub.unbounded(); + const set = (patch: Partial) => + Ref.updateAndGet(current, (settings) => ({ ...settings, ...patch })).pipe( + Effect.flatMap((settings) => PubSub.publish(changes, settings)), + ); + let pendingChange = afterFirstRead; + return { + set, + layer: Layer.mock(ServerSettingsService, { + managedPolicy, + getSettings: Ref.get(current).pipe( + Effect.tap(() => { + const change = pendingChange; + pendingChange = undefined; + return change ? set(change) : Effect.void; + }), + ), + streamChanges: Stream.fromPubSub(changes), + subscribeChanges: PubSub.subscribe(changes).pipe(Effect.map(Stream.fromSubscription)), + }), + }; +}); + /** Serves the tunnel route; `wsTicket=reader` authenticates without terminal:operate. */ -const serveTunnel = (sessionInvalidated: Effect.Effect = Effect.never) => +const serveTunnel = ( + sessionInvalidated: Effect.Effect = Effect.never, + settings?: Layer.Layer, +) => Effect.gen(function* () { + const settingsLayer = settings ?? (yield* makeSettings()).layer; const services = yield* Layer.build( HttpRouter.serve(PreviewTunnel.routeLayer, { disableListenLog: true }).pipe( Layer.provideMerge(NodeHttpServer.layerTest), - Layer.provide(PreviewTunnel.layer), + Layer.provide(PreviewTunnel.layer.pipe(Layer.provide(settingsLayer))), Layer.provide( Layer.mock(SessionStore.SessionStore, { cookieName: "t3_session", @@ -183,3 +228,69 @@ it.effect("closes an open tunnel when its session is revoked", () => yield* Effect.promise(() => Promise.all([clientClosed, upstreamClosed.promise])); }), ); + +it.effect.each([ + { case: "the setting", enabled: false, policy: undefined }, + { + case: "a policy, whatever the setting", + enabled: true, + policy: { + organization: "Example Corp", + lockedSettings: [], + limits: { previewTunnel: false }, + } satisfies ManagedPolicySummary, + }, +])("refuses every tunnel with 403 when $case turns it off", ({ enabled, policy }) => + Effect.gen(function* () { + let dialled = 0; + const listed = yield* listen((socket) => { + dialled++; + socket.destroy(); + }); + const settings = yield* makeSettings(enabled, policy); + const tunnel = yield* serveTunnel(Effect.never, settings.layer); + const client = yield* openTunnel(`${tunnel.origin}/api/preview/tunnel?port=${listed.port}`); + const status = yield* Effect.promise( + () => + new Promise<{ status: number | undefined; disabled: boolean }>((resolve, reject) => { + client.on("unexpected-response", (_request, response) => + resolve({ + status: response.statusCode, + disabled: + response.headers[PreviewTunnel.PREVIEW_TUNNEL_DISABLED_HEADER] !== undefined, + }), + ); + client.on("open", () => reject(new Error("tunnel opened"))); + client.on("error", reject); + }), + ); + expect(status).toEqual({ status: 403, disabled: true }); + expect(dialled).toBe(0); + }), +); + +it.effect("closes an open tunnel when the setting turns it off", () => + Effect.gen(function* () { + const upstreamClosed = Promise.withResolvers(); + const upstream = yield* listen((socket) => socket.on("close", () => upstreamClosed.resolve())); + const settings = yield* makeSettings(); + const tunnel = yield* serveTunnel(Effect.never, settings.layer); + const client = yield* openTunnel(`${tunnel.origin}/api/preview/tunnel?port=${upstream.port}`); + yield* Effect.promise(() => new Promise((resolve) => client.once("open", resolve))); + const clientClosed = new Promise((resolve) => client.once("close", resolve)); + yield* settings.set({ enablePreviewTunnel: false }); + yield* Effect.promise(() => Promise.all([clientClosed, upstreamClosed.promise])); + }), +); + +it.effect("closes a tunnel the setting turns off while it is still dialling", () => + Effect.gen(function* () { + const settings = yield* makeSettings(true, undefined, { enablePreviewTunnel: false }); + const upstreamClosed = Promise.withResolvers(); + const upstream = yield* listen((socket) => socket.on("close", () => upstreamClosed.resolve())); + const tunnel = yield* serveTunnel(Effect.never, settings.layer); + const client = yield* openTunnel(`${tunnel.origin}/api/preview/tunnel?port=${upstream.port}`); + const clientClosed = new Promise((resolve) => client.once("close", resolve)); + yield* Effect.promise(() => Promise.all([clientClosed, upstreamClosed.promise])); + }), +); diff --git a/apps/server/src/preview/PreviewTunnel.ts b/apps/server/src/preview/PreviewTunnel.ts index 7984a81420e52..8071e4ef1eb0a 100644 --- a/apps/server/src/preview/PreviewTunnel.ts +++ b/apps/server/src/preview/PreviewTunnel.ts @@ -2,7 +2,7 @@ // connection per WebSocket. Raw bytes, so pages keep their own origin, HMR sockets and TLS. import * as NodeHttpServerRequest from "@effect/platform-node/NodeHttpServerRequest"; import * as NodeSocket from "@effect/platform-node/NodeSocket"; -import { AuthTerminalOperateScope } from "@t3tools/contracts"; +import { allowsPreviewTunnel, AuthTerminalOperateScope } from "@t3tools/contracts"; import type * as NodeNet from "node:net"; import * as Context from "effect/Context"; import * as Effect from "effect/Effect"; @@ -10,12 +10,14 @@ import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; import type * as Scope from "effect/Scope"; +import * as Stream from "effect/Stream"; import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/http"; import type * as Socket from "effect/socket/Socket"; import { authenticateMediaRequest } from "../auth/http.ts"; import * as SessionStore from "../auth/SessionStore.ts"; import { requestUrl } from "../requestUrl.ts"; +import { ServerSettingsService } from "../serverSettings.ts"; const PREVIEW_TUNNEL_ROUTE = "/api/preview/tunnel"; /** @@ -23,6 +25,8 @@ const PREVIEW_TUNNEL_ROUTE = "/api/preview/tunnel"; * in front of the environment answering 502 because the environment is down. */ export const PREVIEW_TUNNEL_PORT_REFUSED_HEADER = "x-t3-tunnel-port-refused"; +/** Marks a refusal because the tunnel is switched off here, by the setting or by policy. */ +export const PREVIEW_TUNNEL_DISABLED_HEADER = "x-t3-tunnel-disabled"; const CONNECT_TIMEOUT = "5 seconds"; @@ -35,6 +39,15 @@ export class PreviewTunnelPortRefusedError extends Schema.TaggedError()( + "PreviewTunnelDisabledError", + {}, +) { + override get message(): string { + return "The preview tunnel is turned off on this T3 Code server."; + } +} + export class PreviewTunnelConnectError extends Schema.TaggedError()( "PreviewTunnelConnectError", { port: Schema.Number, cause: Schema.Defect() }, @@ -53,13 +66,38 @@ export class PreviewTunnel extends Context.Service< readonly servedPort: number | undefined; }) => Effect.Effect< { readonly reader: Socket.Reader; readonly writer: Socket.Writer }, - PreviewTunnelPortRefusedError | PreviewTunnelConnectError, + PreviewTunnelDisabledError | PreviewTunnelPortRefusedError | PreviewTunnelConnectError, Scope.Scope >; + /** + * Subscribes now, before `connect` reads the setting, so a switch-off during dialling isn't + * missed. The returned effect completes once the tunnel is switched off. + */ + readonly watchTurnedOff: Effect.Effect, never, Scope.Scope>; } >()("t3/preview/PreviewTunnel") {} -const make = Effect.sync(() => { +const make = Effect.gen(function* () { + const serverSettings = yield* ServerSettingsService; + const managedPolicy = serverSettings.managedPolicy; + const allowedBy = (settings: { readonly enablePreviewTunnel: boolean }) => + allowsPreviewTunnel({ settings, managedPolicy }); + // Unreadable settings fail closed: the tunnel is raw TCP into the host. + const enabled = serverSettings.getSettings.pipe( + Effect.map(allowedBy), + Effect.orElseSucceed(() => false), + ); + const watchTurnedOff = serverSettings.subscribeChanges.pipe( + Effect.map((changes) => + changes.pipe( + Stream.filter((settings) => !allowedBy(settings)), + Stream.runHead, + // A change stream that ends without switching the tunnel off never does. + Effect.flatMap((change) => (Option.isSome(change) ? Effect.void : Effect.never)), + ), + ), + ); + const dial = Effect.fnUntraced(function* (host: string, port: number) { const socket = yield* NodeSocket.makeNet({ host, port, openTimeout: CONNECT_TIMEOUT }); return { reader: yield* socket.reader, writer: yield* socket.writer }; @@ -68,6 +106,7 @@ const make = Effect.sync(() => { const connect: PreviewTunnel["Service"]["connect"] = Effect.fn("PreviewTunnel.connect")( function* ({ port, servedPort }) { yield* Effect.annotateCurrentSpan({ port }); + if (!(yield* enabled)) return yield* new PreviewTunnelDisabledError(); // Tunnelling to this server would hand the page an unauthenticated loopback client. if (port === servedPort) { return yield* new PreviewTunnelPortRefusedError({ port }); @@ -79,7 +118,7 @@ const make = Effect.sync(() => { }, ); - return PreviewTunnel.of({ connect }); + return PreviewTunnel.of({ connect, watchTurnedOff }); }); export const layer = Layer.effect(PreviewTunnel, make); @@ -133,23 +172,32 @@ const handler = Effect.gen(function* () { const connection = NodeHttpServerRequest.toIncomingMessage(request).socket; const servedPort = connection.localPort; return yield* Effect.gen(function* () { + const turnedOff = yield* tunnel.watchTurnedOff; // Dialled before the upgrade so a dead port fails the handshake instead of an open socket. const upstream = yield* tunnel.connect({ port, servedPort }); const client = yield* request.upgrade; const clientReader = yield* client.reader; const clientWriter = yield* client.writer; // A tunnel is raw TCP into the host, so it closes with its session like the RPC socket. + // So does switching the tunnel off. yield* Effect.raceFirst( Effect.raceFirst( pump(upstream.reader, clientWriter, drained(connection)), pump(clientReader, upstream.writer), ), - sessions.awaitInvalidation(session.sessionId, session.proofKeyThumbprint), + Effect.raceFirst( + sessions.awaitInvalidation(session.sessionId, session.proofKeyThumbprint), + turnedOff, + ), ).pipe(Effect.ignoreCause); return HttpServerResponse.empty(); }).pipe( Effect.scoped, Effect.catchTags({ + PreviewTunnelDisabledError: (error) => + Effect.succeed( + HttpServerResponse.text(error.message, { status: 403, headers: DISABLED_HEADERS }), + ), PreviewTunnelPortRefusedError: (error) => Effect.succeed( HttpServerResponse.text(error.message, { status: 403, headers: PORT_REFUSED_HEADERS }), @@ -163,5 +211,6 @@ const handler = Effect.gen(function* () { }); const PORT_REFUSED_HEADERS = { [PREVIEW_TUNNEL_PORT_REFUSED_HEADER]: "1" }; +const DISABLED_HEADERS = { [PREVIEW_TUNNEL_DISABLED_HEADER]: "1" }; export const routeLayer = HttpRouter.add("GET", PREVIEW_TUNNEL_ROUTE, handler); diff --git a/apps/web/src/browser/previewRuntime.ts b/apps/web/src/browser/previewRuntime.ts index 7ca4a8a8f6995..8b68ff5e96aaa 100644 --- a/apps/web/src/browser/previewRuntime.ts +++ b/apps/web/src/browser/previewRuntime.ts @@ -1,6 +1,13 @@ import { useAtomValue } from "@effect/atom-react"; -import type { EnvironmentId, PreviewRuntime, PreviewSessionSnapshot } from "@t3tools/contracts"; +import { + allowsPreviewTunnel, + type EnvironmentId, + type PreviewRuntime, + type PreviewSessionSnapshot, +} from "@t3tools/contracts"; +import { Atom } from "effect/reactivity"; +import { environmentCatalog } from "~/connection/catalog"; import { isElectron } from "~/env"; import { isPreviewSupportedInRuntime } from "~/previewStateStore"; import { appAtomRegistry } from "~/rpc/atomRegistry"; @@ -9,12 +16,27 @@ import { readEnvironmentSupportsServerBrowser, useEnvironmentSupportsServerBrowser, } from "~/state/entities"; +import { environmentServerConfigsAtom } from "~/state/server"; + +import { tunnelsEnvironmentLoopback } from "./browserTargetResolver"; + +/** Whether this desktop loads the environment's localhost itself: it is local, or its tunnel is on. */ +const desktopLoadsLoopbackAtom = Atom.family((environmentId: EnvironmentId) => + Atom.make((get) => { + const target = get(environmentCatalog.catalogValueAtom).entries.get(environmentId)?.target; + if (!tunnelsEnvironmentLoopback(target)) return true; + const config = get(environmentServerConfigsAtom).get(environmentId); + return config !== undefined && allowsPreviewTunnel(config); + }).pipe(Atom.withLabel(`preview:desktop-loads-loopback:${environmentId}`)), +); export function previewRuntimeFor(environmentId: EnvironmentId): PreviewRuntime | undefined { if (!readEnvironmentSupportsServerBrowser(environmentId)) return undefined; + // Without its tunnel, another environment's tabs stream from it, as on the web. if ( isPreviewSupportedInRuntime() && - environmentId !== appAtomRegistry.get(primaryEnvironmentIdAtom) + environmentId !== appAtomRegistry.get(primaryEnvironmentIdAtom) && + appAtomRegistry.get(desktopLoadsLoopbackAtom(environmentId)) ) { return undefined; } @@ -25,11 +47,17 @@ export function alternatePreviewRuntime( environmentId: EnvironmentId, primaryEnvironmentId: EnvironmentId | null, serverBrowser: boolean, + desktopLoadsLoopback: boolean, snapshot: Pick | null | undefined, ): PreviewRuntime | null { if (!snapshot || !serverBrowser || !isPreviewSupportedInRuntime()) return null; if (environmentId === primaryEnvironmentId) return null; - return snapshot.runtime === "server" ? "desktop" : "server"; + if (snapshot.runtime === "server") return desktopLoadsLoopback ? "desktop" : null; + return "server"; +} + +export function useDesktopLoadsLoopback(environmentId: EnvironmentId): boolean { + return useAtomValue(desktopLoadsLoopbackAtom(environmentId)); } export function isPreviewAvailableFor(environmentId: EnvironmentId): boolean { diff --git a/apps/web/src/components/CommandPalettePortForwardItems.tsx b/apps/web/src/components/CommandPalettePortForwardItems.tsx index 2a03b19d300c1..0c50c2eaf1e12 100644 --- a/apps/web/src/components/CommandPalettePortForwardItems.tsx +++ b/apps/web/src/components/CommandPalettePortForwardItems.tsx @@ -54,8 +54,7 @@ export function useCommandPalettePortForwardItem(input: { const forwards = usePortForwards(); const { environments } = useEnvironments(); const reachable = environments.filter( - (environment) => - environment.connection.phase === "connected" && canForwardPorts(environment.entry.target), + (environment) => environment.connection.phase === "connected" && canForwardPorts(environment), ); const tunnelling = useEnvironmentsWithScope(reachable, AuthTerminalOperateScope); const tunnelled = reachable.filter((environment) => tunnelling.has(environment.environmentId)); diff --git a/apps/web/src/components/chat/ThreadServersPanel.tsx b/apps/web/src/components/chat/ThreadServersPanel.tsx index b392a78f21b9a..5f6f11636e806 100644 --- a/apps/web/src/components/chat/ThreadServersPanel.tsx +++ b/apps/web/src/components/chat/ThreadServersPanel.tsx @@ -12,12 +12,16 @@ import { isAtomCommandInterrupted, squashAtomCommandFailure, } from "@t3tools/client-runtime/state/runtime"; +import { isLoopbackHost } from "@t3tools/shared/preview"; import { T, useGT, Var } from "gt-react"; import { m } from "~/i18n/messages"; import { CableIcon, GlobeIcon, SquareIcon, ChevronDownIcon, ChevronUpIcon } from "lucide-react"; import { type MouseEvent, useState } from "react"; -import { resolveExternalServerUrl } from "../../browser/browserTargetResolver"; +import { + resolveExternalServerUrl, + tunnelsEnvironmentLoopback, +} from "../../browser/browserTargetResolver"; import { readLocalApi } from "../../localApi"; import { cn, isMacPlatform } from "../../lib/utils"; import { useThreadDiscoveredPorts } from "../../portDiscoveryState"; @@ -69,7 +73,7 @@ function ThreadServersList(props: ThreadServersPanelProps) { const forwardable = useEnvironmentScope(props.environmentId, AuthTerminalOperateScope) && environment?.connection.phase === "connected" && - canForwardPorts(environment.entry.target); + canForwardPorts(environment); const locality = useForwardLocality(forwardable ? props.environmentId : null); const canForward = locality === "remote"; const openPreview = useAtomCommand(previewEnvironment.open, { reportFailure: false }); @@ -113,6 +117,23 @@ function ThreadServersList(props: ThreadServersPanelProps) { ) : resolveExternalServerUrl(props.environmentId, server.url); if (url === null) return; + // Without a forward, a remote environment's localhost would open this machine's instead. + if ( + locality !== "local" && + tunnelsEnvironmentLoopback(environment?.entry.target) && + isLoopbackHost(new URL(url).hostname) + ) { + reportFailure( + gt("Unable to open in browser"), + new Error( + gt( + "localhost:{port} runs on another machine, and port forwarding isn't available for it right now.", + { port: server.port }, + ), + ), + ); + return; + } await readLocalApi() ?.shell.openExternal(url) .catch((error: unknown) => reportFailure(gt("Unable to open in browser"), error)); diff --git a/apps/web/src/components/preview/PreviewView.tsx b/apps/web/src/components/preview/PreviewView.tsx index 481e6d8e0f291..bb62228b93736 100644 --- a/apps/web/src/components/preview/PreviewView.tsx +++ b/apps/web/src/components/preview/PreviewView.tsx @@ -91,7 +91,11 @@ import type { MessageResolver } from "~/i18n/messages"; import { revealInFileExplorerLabel } from "./fileExplorerLabel"; import { Badge } from "~/components/ui/badge"; import { BrowserSurfaceSlot } from "~/browser/BrowserSurfaceSlot"; -import { alternatePreviewRuntime, useRendersServerTabNatively } from "~/browser/previewRuntime"; +import { + alternatePreviewRuntime, + useDesktopLoadsLoopback, + useRendersServerTabNatively, +} from "~/browser/previewRuntime"; import { ServerBrowserSurface, type ServerBrowserHandle } from "~/browser/ServerBrowserSurface"; import { cn } from "~/lib/utils"; import { useBrowserSurfaceStore } from "~/browser/browserSurfaceStore"; @@ -205,6 +209,7 @@ export function PreviewView({ const environmentLabel = useEnvironment(threadRef.environmentId)?.label ?? null; const primaryEnvironmentId = usePrimaryEnvironmentId(); const serverBrowser = useEnvironmentSupportsServerBrowser(threadRef.environmentId); + const desktopLoadsLoopback = useDesktopLoadsLoopback(threadRef.environmentId); const adjust = useAtomCommand(previewEnvironment.adjust, "preview appearance or zoom"); usePreviewSession(threadRef); @@ -463,6 +468,7 @@ export function PreviewView({ threadRef.environmentId, primaryEnvironmentId, serverBrowser, + desktopLoadsLoopback, snapshot, ); const moveLabel = diff --git a/apps/web/src/components/settings/ConnectionsSettings.tsx b/apps/web/src/components/settings/ConnectionsSettings.tsx index a6cf6a03b3a28..8f4d8778bcf80 100644 --- a/apps/web/src/components/settings/ConnectionsSettings.tsx +++ b/apps/web/src/components/settings/ConnectionsSettings.tsx @@ -13,6 +13,8 @@ import { AuthEnvironmentMaintainScope, AuthRelayReadScope, AuthRelayWriteScope, + allowsPreviewTunnel, + isManagedSettingPath, type AuthClientSession, type AuthPairingLink, type AuthPairingCredentialResult, @@ -1255,6 +1257,12 @@ function ConnectionsSettingsContent({ ); const accessServerConfig = accessEnvironment?.serverConfig ?? null; + const accessPolicy = accessServerConfig?.managedPolicy; + const previewTunnelDenial = + managedCapabilityDenial(accessPolicy, "previewTunnel", m) ?? + (accessPolicy !== undefined && isManagedSettingPath(accessPolicy, "enablePreviewTunnel") + ? gt("Managed by {organization}.", { organization: accessPolicy.organization }) + : undefined); const primarySettings = ( <> {accessEnvironmentPicker} @@ -1377,6 +1385,25 @@ function ConnectionsSettingsContent({ } /> ) : null} + {accessServerConfig?.environment.capabilities.previewTunnelSetting ? ( + + void updateAccessSettings({ enablePreviewTunnel: enabled }) + } + /> + } + /> + ) : null} {accessEnvironment ? (
    diff --git a/apps/web/src/components/settings/settingsSearch.ts b/apps/web/src/components/settings/settingsSearch.ts index b02f8d2f0b0c8..51ac4d7e19add 100644 --- a/apps/web/src/components/settings/settingsSearch.ts +++ b/apps/web/src/components/settings/settingsSearch.ts @@ -1391,6 +1391,15 @@ export const SETTINGS_SEARCH_ITEMS = [ searchTerms: [msg("mobile push notifications live activities cloud tunnel")], cloudOnly: true, }, + { + id: "preview-tunnel", + title: msg("Preview tunnel"), + to: "/settings/access", + targetId: "connections-environment", + searchTerms: [ + msg("localhost loopback port forwarding open on this device browser tabs stream security"), + ], + }, { id: "connections-environment", title: msg("This machine"), diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index 661098ee35afc..2ec76aa57cfd7 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -23,6 +23,7 @@ "ef9533bcc048f17b": "Die Richtlinie von {organization} erlaubt T3 Connect nicht.", "986b0873f913a840": "Die Richtlinie von {organization} erlaubt keine Webhook-Aufgaben.", "eebc538e25b09fe2": "Die Richtlinie von {organization} erlaubt keinen Import von Browser-Cookies.", + "7642a133db05f164": "Die Richtlinie von {organization} erlaubt nicht, die lokalen Server dieses Rechners auf anderen Geräten zu öffnen.", "39f6771b49f9b3b6": "Standard verwenden", "45bb0e90e1c42046": "Wenn du zurückkommst", "d8fa0a55446bbb0d": "Bevor der Cache abläuft (Beta)", @@ -4198,6 +4199,7 @@ "075398ac562d74b0": "Agentensitzung trennen", "1d2025060ba3d1c3": "Port {port} konnte nicht weitergeleitet werden", "086ecbb6f4c2e959": "Kann nicht im Browser geöffnet werden", + "112173d046bfc910": "localhost:{port} läuft auf einem anderen Rechner, und Portweiterleitung ist dafür gerade nicht verfügbar.", "51052c00ab1ac8cc": "Vorschau kann nicht geöffnet werden", "0ccd37739f9cf2b6": "Server konnte nicht gestoppt werden", "a610a81c4061bb4c": "Server", @@ -8006,6 +8008,8 @@ "9bfddd9a835be5de": "Server", "43b545c01503eee4": "Update wiederholen", "2f015e6d5459dce9": "Auf {version} aktualisieren", + "8ebba639f92932c3": "Erlaubt anderen Geräten, die lokalen Server dieses Rechners zu öffnen: auf dem Gerät geladene Browser-Tabs, Auf diesem Gerät öffnen und Portweiterleitung. Aus: Browser-Tabs werden von diesem Rechner gestreamt.", + "1c5266bf18d0ed24": "Vorschau-Tunnel erlauben", "a0e93cca71d0417e": "Autorisierte Clients", "03b9501ae07b5cf3": "Netzwerkzugriff aktivieren?", "a09aff32ef3d89c7": "Netzwerkzugriff deaktivieren?", @@ -11630,6 +11634,8 @@ "b5cd79513a06e7c3": "Webhooks offline zurückhalten", "fadd0fcd7b9e1651": "webhook automatisierungen offline warteschlange postfach t3 connect", "9bebacdcfbde18d4": "mobil push-benachrichtigungen live-aktivitäten cloud tunnel", + "a4e6dee662edc3cf": "Vorschau-Tunnel", + "8ed7c2a2226f4663": "localhost loopback portweiterleitung auf diesem gerät öffnen browser tabs streamen sicherheit port forwarding", "1c3e0ac06c8a1f1e": "verbindungen server backend lokal remote zugriff administrativ berechtigungen bereich kopplungslinks qr-code autorisierte clients sitzungen widerrufen endpunkt", "744fd34e8049efeb": "verknüpfen peer anderer rechner vps agenten dort arbeiten übergabe kopplungscode", "3d00c452287f50bd": "hinzufügen koppeln backend host code ssh konfiguration agent tunnel gespeichert t3 connect", diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index a873be091b0c9..83909c95ae905 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -23,6 +23,7 @@ "ef9533bcc048f17b": "{organization}'s policy does not allow T3 Connect.", "986b0873f913a840": "{organization}'s policy does not allow webhook tasks.", "eebc538e25b09fe2": "{organization}'s policy does not allow importing browser cookies.", + "7642a133db05f164": "{organization}'s policy does not allow opening this machine's local servers on other devices.", "39f6771b49f9b3b6": "Use default", "45bb0e90e1c42046": "When you return", "d8fa0a55446bbb0d": "Before the cache expires (beta)", @@ -4197,6 +4198,7 @@ "075398ac562d74b0": "Disconnect agent session", "1d2025060ba3d1c3": "Could not forward port {port}", "086ecbb6f4c2e959": "Unable to open in browser", + "112173d046bfc910": "localhost:{port} runs on another machine, and port forwarding isn't available for it right now.", "51052c00ab1ac8cc": "Unable to open preview", "0ccd37739f9cf2b6": "Could not stop server", "a610a81c4061bb4c": "Servers", @@ -8013,6 +8015,8 @@ "9bfddd9a835be5de": "server", "43b545c01503eee4": "Retry update", "2f015e6d5459dce9": "Update to {version}", + "8ebba639f92932c3": "Lets other devices open this machine's local servers: browser tabs loaded on the device, Open on this device, and port forwarding. Off: browser tabs stream from this machine.", + "1c5266bf18d0ed24": "Allow the preview tunnel", "a0e93cca71d0417e": "Authorized clients", "03b9501ae07b5cf3": "Enable network access?", "a09aff32ef3d89c7": "Disable network access?", @@ -11638,6 +11642,8 @@ "b5cd79513a06e7c3": "Hold webhooks while offline", "fadd0fcd7b9e1651": "webhook automations offline queue mailbox t3 connect", "9bebacdcfbde18d4": "mobile push notifications live activities cloud tunnel", + "a4e6dee662edc3cf": "Preview tunnel", + "8ed7c2a2226f4663": "localhost loopback port forwarding open on this device browser tabs stream security", "1c3e0ac06c8a1f1e": "connections server backend local remote access administrative permissions scope pairing links qr code authorized clients sessions revoke endpoint", "744fd34e8049efeb": "link peer another machine vps agents work there handoff pairing code", "3d00c452287f50bd": "add pair backend host code ssh config agent tunnel saved t3 connect", diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index 3e730353316fe..58a70229908d8 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -23,6 +23,7 @@ "ef9533bcc048f17b": "La política de {organization} no permite T3 Connect.", "986b0873f913a840": "La política de {organization} no permite tareas de webhook.", "eebc538e25b09fe2": "La política de {organization} no permite importar cookies del navegador.", + "7642a133db05f164": "La política de {organization} no permite abrir los servidores locales de esta máquina en otros dispositivos.", "39f6771b49f9b3b6": "Usar valor predeterminado", "45bb0e90e1c42046": "Cuando vuelvas", "d8fa0a55446bbb0d": "Antes de que caduque la caché (beta)", @@ -4195,6 +4196,7 @@ "075398ac562d74b0": "Desconectar la sesión del agente", "1d2025060ba3d1c3": "No se pudo reenviar el puerto {port}", "086ecbb6f4c2e959": "No se puede abrir en el navegador", + "112173d046bfc910": "localhost:{port} se ejecuta en otro equipo y el reenvío de puertos no está disponible para él ahora.", "51052c00ab1ac8cc": "No se puede abrir la vista previa", "0ccd37739f9cf2b6": "No se pudo detener el servidor", "a610a81c4061bb4c": "Servidores", @@ -8005,6 +8007,8 @@ "9bfddd9a835be5de": "servidor", "43b545c01503eee4": "Reintentar actualización", "2f015e6d5459dce9": "Actualizar a {version}", + "8ebba639f92932c3": "Permite que otros dispositivos abran los servidores locales de esta máquina: pestañas del navegador cargadas en el dispositivo, Abrir en este dispositivo y reenvío de puertos. Desactivado: las pestañas del navegador se transmiten desde esta máquina.", + "1c5266bf18d0ed24": "Permitir el túnel de vista previa", "a0e93cca71d0417e": "Clientes autorizados", "03b9501ae07b5cf3": "¿Activar el acceso a la red?", "a09aff32ef3d89c7": "¿Desactivar el acceso a la red?", @@ -11623,6 +11627,8 @@ "b5cd79513a06e7c3": "Retener webhooks sin conexión", "fadd0fcd7b9e1651": "webhook automatizaciones sin conexión cola buzón t3 connect", "9bebacdcfbde18d4": "móvil notificaciones push actividades en directo live activities nube túnel", + "a4e6dee662edc3cf": "Túnel de vista previa", + "8ed7c2a2226f4663": "localhost loopback reenvío de puertos abrir en este dispositivo pestañas navegador transmitir seguridad port forwarding", "1c3e0ac06c8a1f1e": "conexiones servidor backend local remoto acceso administrativo permisos ámbito enlaces de emparejamiento código qr clientes autorizados sesiones revocar endpoint", "744fd34e8049efeb": "vincular par otra máquina vps agentes trabajar allí traspaso código de emparejamiento", "3d00c452287f50bd": "añadir emparejar backend host código ssh config agente túnel guardado t3 connect", diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index 24dba2e932684..829d5654d59e5 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -23,6 +23,7 @@ "ef9533bcc048f17b": "La politique de {organization} n’autorise pas T3 Connect.", "986b0873f913a840": "La politique de {organization} n’autorise pas les tâches webhook.", "eebc538e25b09fe2": "La politique de {organization} n’autorise pas l’import des cookies du navigateur.", + "7642a133db05f164": "La stratégie de {organization} n’autorise pas l’ouverture des serveurs locaux de cette machine sur d’autres appareils.", "39f6771b49f9b3b6": "Utiliser la valeur par défaut", "45bb0e90e1c42046": "À votre retour", "d8fa0a55446bbb0d": "Avant l’expiration du cache (bêta)", @@ -4196,6 +4197,7 @@ "075398ac562d74b0": "Déconnecter la session de l’agent", "1d2025060ba3d1c3": "Impossible de rediriger le port {port}", "086ecbb6f4c2e959": "Impossible d’ouvrir dans le navigateur", + "112173d046bfc910": "localhost:{port} tourne sur une autre machine, et la redirection de ports n’est pas disponible pour elle pour le moment.", "51052c00ab1ac8cc": "Impossible d’ouvrir l’aperçu", "0ccd37739f9cf2b6": "Impossible d’arrêter le serveur", "a610a81c4061bb4c": "Serveurs", @@ -8006,6 +8008,8 @@ "9bfddd9a835be5de": "serveur", "43b545c01503eee4": "Réessayer la mise à jour", "2f015e6d5459dce9": "Mettre à jour vers {version}", + "8ebba639f92932c3": "Permet à d’autres appareils d’ouvrir les serveurs locaux de cette machine : onglets de navigateur chargés sur l’appareil, Ouvrir sur cet appareil et redirection de ports. Désactivé : les onglets du navigateur sont diffusés depuis cette machine.", + "1c5266bf18d0ed24": "Autoriser le tunnel d’aperçu", "a0e93cca71d0417e": "Clients autorisés", "03b9501ae07b5cf3": "Activer l’accès réseau ?", "a09aff32ef3d89c7": "Désactiver l’accès réseau ?", @@ -11628,6 +11632,8 @@ "b5cd79513a06e7c3": "Conserver les webhooks hors ligne", "fadd0fcd7b9e1651": "webhook automatisations file d’attente hors ligne boîte aux lettres t3 connect", "9bebacdcfbde18d4": "mobile notifications push live activities tunnel cloud", + "a4e6dee662edc3cf": "Tunnel d’aperçu", + "8ed7c2a2226f4663": "localhost loopback redirection de ports ouvrir sur cet appareil onglets navigateur diffusion sécurité port forwarding", "1c3e0ac06c8a1f1e": "connexions serveur backend local accès distant autorisations administratives portée liens d’appairage code qr clients autorisés sessions révoquer point de terminaison", "744fd34e8049efeb": "associer pair autre machine vps agents y travaillent transfert code d’appairage", "3d00c452287f50bd": "ajouter appairer backend hôte code ssh config agent tunnel enregistré t3 connect", diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index e88cc490a8590..dac6333be5e1a 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -23,6 +23,7 @@ "ef9533bcc048f17b": "{organization} のポリシーでは、T3 Connect は許可されていません。", "986b0873f913a840": "{organization} のポリシーでは、Webhook タスクは許可されていません。", "eebc538e25b09fe2": "{organization} のポリシーでは、ブラウザーの Cookie のインポートは許可されていません。", + "7642a133db05f164": "{organization} のポリシーでは、このマシンのローカルサーバーを他のデバイスで開くことは許可されていません。", "39f6771b49f9b3b6": "デフォルトを使用", "45bb0e90e1c42046": "戻ってきたとき", "d8fa0a55446bbb0d": "キャッシュの期限切れ前 (ベータ)", @@ -4186,6 +4187,7 @@ "075398ac562d74b0": "エージェントのセッションを切断", "1d2025060ba3d1c3": "ポート {port} を転送できませんでした", "086ecbb6f4c2e959": "ブラウザーで開けません", + "112173d046bfc910": "localhost:{port} は別のマシンで動いており、現在このポートは転送できません。", "51052c00ab1ac8cc": "プレビューを開けません", "0ccd37739f9cf2b6": "サーバーを停止できませんでした", "a610a81c4061bb4c": "サーバー", @@ -7966,6 +7968,8 @@ "9bfddd9a835be5de": "サーバー", "43b545c01503eee4": "更新を再試行", "2f015e6d5459dce9": "{version} に更新", + "8ebba639f92932c3": "他のデバイスがこのマシンのローカルサーバーを開けるようにします:デバイス上で読み込むブラウザタブ、「このデバイスで開く」、ポートフォワーディング。オフ:ブラウザタブはこのマシンからストリーミングされます。", + "1c5266bf18d0ed24": "プレビュートンネルを許可", "a0e93cca71d0417e": "承認済みクライアント", "03b9501ae07b5cf3": "ネットワークアクセスを有効にしますか?", "a09aff32ef3d89c7": "ネットワークアクセスを無効にしますか?", @@ -11578,6 +11582,8 @@ "b5cd79513a06e7c3": "オフライン中の Webhook を保持", "fadd0fcd7b9e1651": "Webhook オートメーション オフライン キュー メールボックス T3 Connect webhook", "9bebacdcfbde18d4": "モバイル プッシュ通知 ライブアクティビティ クラウド トンネル push", + "a4e6dee662edc3cf": "プレビュートンネル", + "8ed7c2a2226f4663": "localhost ループバック ポートフォワーディング このデバイスで開く ブラウザ タブ ストリーミング セキュリティ port forwarding", "1c3e0ac06c8a1f1e": "接続 サーバー バックエンド ローカル リモート アクセス 管理者 権限 スコープ ペアリングリンク QR コード 認可済みクライアント セッション 取り消し エンドポイント connections", "744fd34e8049efeb": "リンク ピア 別のマシン VPS エージェント そこで作業 引き継ぎ ペアリングコード link machine", "3d00c452287f50bd": "追加 ペアリング バックエンド ホスト コード SSH 構成 エージェント トンネル 保存済み T3 Connect add pair", diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index c80d5dc373208..937913f4ba846 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -23,6 +23,7 @@ "ef9533bcc048f17b": "{organization}의 정책상 T3 Connect를 사용할 수 없습니다.", "986b0873f913a840": "{organization}의 정책상 웹후크 작업을 사용할 수 없습니다.", "eebc538e25b09fe2": "{organization}의 정책상 브라우저 쿠키를 가져올 수 없습니다.", + "7642a133db05f164": "{organization}의 정책은 이 컴퓨터의 로컬 서버를 다른 기기에서 여는 것을 허용하지 않습니다.", "39f6771b49f9b3b6": "기본값 사용", "45bb0e90e1c42046": "돌아왔을 때", "d8fa0a55446bbb0d": "캐시가 만료되기 전(베타)", @@ -4183,6 +4184,7 @@ "075398ac562d74b0": "에이전트 세션 연결 끊기", "1d2025060ba3d1c3": "포트 {port}을(를) 포워딩할 수 없습니다", "086ecbb6f4c2e959": "브라우저에서 열 수 없습니다", + "112173d046bfc910": "localhost:{port}는 다른 컴퓨터에서 실행 중이며, 지금은 포트 포워딩을 사용할 수 없습니다.", "51052c00ab1ac8cc": "미리 보기를 열 수 없습니다", "0ccd37739f9cf2b6": "서버를 중지할 수 없습니다", "a610a81c4061bb4c": "서버", @@ -7968,6 +7970,8 @@ "9bfddd9a835be5de": "서버", "43b545c01503eee4": "업데이트 다시 시도", "2f015e6d5459dce9": "{version}(으)로 업데이트", + "8ebba639f92932c3": "다른 기기에서 이 컴퓨터의 로컬 서버를 열 수 있게 합니다: 기기에서 불러오는 브라우저 탭, 이 기기에서 열기, 포트 포워딩. 끄면 브라우저 탭이 이 컴퓨터에서 스트리밍됩니다.", + "1c5266bf18d0ed24": "미리보기 터널 허용", "a0e93cca71d0417e": "승인된 클라이언트", "03b9501ae07b5cf3": "네트워크 액세스를 켤까요?", "a09aff32ef3d89c7": "네트워크 액세스를 끌까요?", @@ -11575,6 +11579,8 @@ "b5cd79513a06e7c3": "오프라인 동안 웹후크 보관", "fadd0fcd7b9e1651": "웹후크 자동화 오프라인 대기열 메일함 T3 Connect", "9bebacdcfbde18d4": "모바일 푸시 알림 실시간 현황 클라우드 터널", + "a4e6dee662edc3cf": "미리보기 터널", + "8ed7c2a2226f4663": "localhost 루프백 포트 포워딩 이 기기에서 열기 브라우저 탭 스트리밍 보안 port forwarding", "1c3e0ac06c8a1f1e": "연결 서버 백엔드 로컬 원격 액세스 관리 권한 범위 페어링 링크 QR 코드 인증된 클라이언트 세션 취소 엔드포인트", "744fd34e8049efeb": "다른 머신 연결 피어 vps 에이전트 원격 작업 넘기기 페어링 코드", "3d00c452287f50bd": "추가 페어링 백엔드 호스트 코드 ssh 구성 에이전트 터널 저장됨 T3 Connect", diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index a2a2daa2b7ccc..6ab44ccc24f70 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -23,6 +23,7 @@ "ef9533bcc048f17b": "A política de {organization} não permite o T3 Connect.", "986b0873f913a840": "A política de {organization} não permite tarefas de webhook.", "eebc538e25b09fe2": "A política de {organization} não permite importar cookies do navegador.", + "7642a133db05f164": "A política de {organization} não permite abrir os servidores locais desta máquina em outros dispositivos.", "39f6771b49f9b3b6": "Usar padrão", "45bb0e90e1c42046": "Quando você voltar", "d8fa0a55446bbb0d": "Antes de o cache expirar (beta)", @@ -4195,6 +4196,7 @@ "075398ac562d74b0": "Desconectar a sessão do agente", "1d2025060ba3d1c3": "Não foi possível encaminhar a porta {port}", "086ecbb6f4c2e959": "Não foi possível abrir no navegador", + "112173d046bfc910": "localhost:{port} roda em outra máquina, e o encaminhamento de portas não está disponível para ela agora.", "51052c00ab1ac8cc": "Não foi possível abrir a pré-visualização", "0ccd37739f9cf2b6": "Não foi possível parar o servidor", "a610a81c4061bb4c": "Servidores", @@ -8005,6 +8007,8 @@ "9bfddd9a835be5de": "servidor", "43b545c01503eee4": "Tentar atualizar novamente", "2f015e6d5459dce9": "Atualizar para {version}", + "8ebba639f92932c3": "Permite que outros dispositivos abram os servidores locais desta máquina: abas do navegador carregadas no dispositivo, Abrir neste dispositivo e encaminhamento de portas. Desativado: as abas do navegador são transmitidas desta máquina.", + "1c5266bf18d0ed24": "Permitir o túnel de pré-visualização", "a0e93cca71d0417e": "Clientes autorizados", "03b9501ae07b5cf3": "Ativar o acesso à rede?", "a09aff32ef3d89c7": "Desativar o acesso à rede?", @@ -11627,6 +11631,8 @@ "b5cd79513a06e7c3": "Reter webhooks enquanto offline", "fadd0fcd7b9e1651": "webhook automações offline fila caixa de correio t3 connect", "9bebacdcfbde18d4": "celular notificações push live activities nuvem túnel", + "a4e6dee662edc3cf": "Túnel de pré-visualização", + "8ed7c2a2226f4663": "localhost loopback encaminhamento de portas abrir neste dispositivo abas navegador transmitir segurança port forwarding", "1c3e0ac06c8a1f1e": "conexões servidor backend local remoto acesso administrativo permissões escopo links de pareamento código qr clientes autorizados sessões revogar endpoint", "744fd34e8049efeb": "vincular par outra máquina vps agentes trabalham lá transferir código de pareamento", "3d00c452287f50bd": "adicionar parear backend host código ssh config agente túnel salvo t3 connect", diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index 852b80217f746..ea00719da3b6b 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -23,6 +23,7 @@ "ef9533bcc048f17b": "Политика {organization} запрещает T3 Connect.", "986b0873f913a840": "Политика {organization} запрещает задачи по вебхуку.", "eebc538e25b09fe2": "Политика {organization} запрещает импорт cookie браузера.", + "7642a133db05f164": "Политика {organization} не разрешает открывать локальные серверы этого компьютера на других устройствах.", "39f6771b49f9b3b6": "По умолчанию", "45bb0e90e1c42046": "Когда вы вернётесь", "d8fa0a55446bbb0d": "До истечения кеша (бета)", @@ -4195,6 +4196,7 @@ "075398ac562d74b0": "Отключить сеанс агента", "1d2025060ba3d1c3": "Не удалось перенаправить порт {port}", "086ecbb6f4c2e959": "Не удалось открыть в браузере", + "112173d046bfc910": "localhost:{port} работает на другом компьютере, и перенаправление портов для него сейчас недоступно.", "51052c00ab1ac8cc": "Не удалось открыть предпросмотр", "0ccd37739f9cf2b6": "Не удалось остановить сервер", "a610a81c4061bb4c": "Серверы", @@ -8005,6 +8007,8 @@ "9bfddd9a835be5de": "сервер", "43b545c01503eee4": "Повторить обновление", "2f015e6d5459dce9": "Обновить до {version}", + "8ebba639f92932c3": "Позволяет другим устройствам открывать локальные серверы этого компьютера: вкладки браузера, загружаемые на устройстве, «Открыть на этом устройстве» и перенаправление портов. Выключено: вкладки браузера транслируются с этого компьютера.", + "1c5266bf18d0ed24": "Разрешить туннель предпросмотра", "a0e93cca71d0417e": "Авторизованные клиенты", "03b9501ae07b5cf3": "Включить сетевой доступ?", "a09aff32ef3d89c7": "Отключить сетевой доступ?", @@ -11628,6 +11632,8 @@ "b5cd79513a06e7c3": "Удерживать вебхуки в офлайне", "fadd0fcd7b9e1651": "вебхук автоматизации офлайн очередь почтовый ящик t3 connect", "9bebacdcfbde18d4": "мобильные push-уведомления live activities облако туннель", + "a4e6dee662edc3cf": "Туннель предпросмотра", + "8ed7c2a2226f4663": "localhost loopback перенаправление портов открыть на этом устройстве вкладки браузер трансляция безопасность port forwarding", "1c3e0ac06c8a1f1e": "подключения сервер бэкенд локальный удалённый доступ административные разрешения область ссылки сопряжения qr-код авторизованные клиенты сеансы отозвать конечная точка", "744fd34e8049efeb": "привязать другой компьютер vps агенты работают там передача код сопряжения", "3d00c452287f50bd": "добавить сопряжение бэкенд хост код ssh конфигурация агент туннель сохранённые t3 connect", diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index f8c06f7408c75..baf63922386cb 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -23,6 +23,7 @@ "ef9533bcc048f17b": "Policyn för {organization} tillåter inte T3 Connect.", "986b0873f913a840": "Policyn för {organization} tillåter inte webhook-uppgifter.", "eebc538e25b09fe2": "Policyn för {organization} tillåter inte import av cookies från webbläsare.", + "7642a133db05f164": "{organization}s policy tillåter inte att den här datorns lokala servrar öppnas på andra enheter.", "39f6771b49f9b3b6": "Använd standard", "45bb0e90e1c42046": "När du kommer tillbaka", "d8fa0a55446bbb0d": "Innan cachen går ut (beta)", @@ -4196,6 +4197,7 @@ "075398ac562d74b0": "Koppla från agentsession", "1d2025060ba3d1c3": "Kunde inte vidarebefordra port {port}", "086ecbb6f4c2e959": "Det gick inte att öppna i webbläsaren", + "112173d046bfc910": "localhost:{port} körs på en annan dator, och portvidarebefordring är inte tillgänglig för den just nu.", "51052c00ab1ac8cc": "Det gick inte att öppna förhandsvisningen", "0ccd37739f9cf2b6": "Kunde inte stoppa servern", "a610a81c4061bb4c": "Servrar", @@ -8011,6 +8013,8 @@ "9bfddd9a835be5de": "server", "43b545c01503eee4": "Försök uppdatera igen", "2f015e6d5459dce9": "Uppdatera till {version}", + "8ebba639f92932c3": "Låter andra enheter öppna den här datorns lokala servrar: webbläsarflikar som läses in på enheten, Öppna på den här enheten och portvidarebefordran. Av: webbläsarflikar strömmas från den här datorn.", + "1c5266bf18d0ed24": "Tillåt förhandsgranskningstunneln", "a0e93cca71d0417e": "Auktoriserade klienter", "03b9501ae07b5cf3": "Aktivera nätverksåtkomst?", "a09aff32ef3d89c7": "Inaktivera nätverksåtkomst?", @@ -11636,6 +11640,8 @@ "b5cd79513a06e7c3": "Håll kvar webhooks i offlineläge", "fadd0fcd7b9e1651": "webhook automatiseringar offline kö brevlåda t3 connect", "9bebacdcfbde18d4": "mobil pushaviseringar liveaktiviteter live activities moln tunnel", + "a4e6dee662edc3cf": "Förhandsgranskningstunnel", + "8ed7c2a2226f4663": "localhost loopback portvidarebefordran öppna på den här enheten webbläsarflikar strömma säkerhet port forwarding", "1c3e0ac06c8a1f1e": "anslutningar server backend lokal fjärråtkomst administrativa behörigheter omfång parkopplingslänkar qr-kod auktoriserade klienter sessioner återkalla slutpunkt", "744fd34e8049efeb": "länka peer annan dator vps agenter arbetar där överlämning parkopplingskod", "3d00c452287f50bd": "lägg till parkoppla backend värd kod ssh-konfiguration agent tunnel sparad t3 connect", diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index 74245c4e54300..8f05fc5be57bc 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -23,6 +23,7 @@ "ef9533bcc048f17b": "{organization} 的策略不允许使用 T3 Connect。", "986b0873f913a840": "{organization} 的策略不允许使用 webhook 任务。", "eebc538e25b09fe2": "{organization} 的策略不允许导入浏览器 Cookie。", + "7642a133db05f164": "{organization} 的策略不允许在其他设备上打开此机器的本地服务器。", "39f6771b49f9b3b6": "使用默认值", "45bb0e90e1c42046": "在你回来后", "d8fa0a55446bbb0d": "缓存过期前(测试版)", @@ -4202,6 +4203,7 @@ "075398ac562d74b0": "断开智能体会话", "1d2025060ba3d1c3": "无法转发端口 {port}", "086ecbb6f4c2e959": "无法在浏览器中打开", + "112173d046bfc910": "localhost:{port} 运行在另一台机器上,目前无法为它转发端口。", "51052c00ab1ac8cc": "无法打开预览", "0ccd37739f9cf2b6": "无法停止服务器", "a610a81c4061bb4c": "服务器", @@ -8024,6 +8026,8 @@ "9bfddd9a835be5de": "服务器", "43b545c01503eee4": "重试更新", "2f015e6d5459dce9": "更新到 {version}", + "8ebba639f92932c3": "允许其他设备打开此机器的本地服务器:在设备上加载的浏览器标签页、“在此设备上打开”以及端口转发。关闭后:浏览器标签页从此机器串流。", + "1c5266bf18d0ed24": "允许预览隧道", "a0e93cca71d0417e": "已授权的客户端", "03b9501ae07b5cf3": "启用网络访问?", "a09aff32ef3d89c7": "停用网络访问?", @@ -11652,6 +11656,8 @@ "b5cd79513a06e7c3": "离线时保留 webhook", "fadd0fcd7b9e1651": "webhook 自动化 离线 队列 邮箱 t3 connect", "9bebacdcfbde18d4": "移动 推送通知 实时活动 云 隧道", + "a4e6dee662edc3cf": "预览隧道", + "8ed7c2a2226f4663": "localhost 回环 端口转发 在此设备上打开 浏览器 标签页 串流 安全 port forwarding", "1c3e0ac06c8a1f1e": "连接 服务器 后端 本地 远程 访问 管理员 权限 范围 配对链接 二维码 已授权的客户端 客户端连接 撤销 端点", "744fd34e8049efeb": "关联 对等 另一台机器 vps 智能体 在那里工作 移交 配对码", "3d00c452287f50bd": "添加 配对 后端 主机 代码 ssh 配置 认证代理 隧道 已保存 t3 connect", diff --git a/apps/web/src/state/portForwards.ts b/apps/web/src/state/portForwards.ts index 3a0c767791bfb..477ad39885adb 100644 --- a/apps/web/src/state/portForwards.ts +++ b/apps/web/src/state/portForwards.ts @@ -1,5 +1,9 @@ import { useAtomValue } from "@effect/atom-react"; -import type { DesktopPortForward, EnvironmentId } from "@t3tools/contracts"; +import { + allowsPreviewTunnel, + type DesktopPortForward, + type EnvironmentId, +} from "@t3tools/contracts"; import * as Effect from "effect/Effect"; import * as Option from "effect/Option"; import * as Queue from "effect/Queue"; @@ -49,9 +53,15 @@ export function usePortForwards(): ReadonlyArray { return AsyncResult.getOrElse(useAtomValue(portForwardsAtom), () => EMPTY_FORWARDS); } -/** Only the desktop app forwards, and only from environments it reaches through the tunnel. */ -export const canForwardPorts = (target: ConnectionTarget | undefined): boolean => - previewBridge() !== undefined && tunnelsEnvironmentLoopback(target); +/** Only the desktop app forwards, and only from environments whose tunnel it may use. */ +export const canForwardPorts = (environment: { + readonly entry: { readonly target: ConnectionTarget }; + readonly serverConfig: Parameters[0] | null; +}): boolean => + previewBridge() !== undefined && + tunnelsEnvironmentLoopback(environment.entry.target) && + environment.serverConfig !== null && + allowsPreviewTunnel(environment.serverConfig); /** * Whether the environment runs on another machine. A saved route can still lead back to this diff --git a/docs/internals/remote.md b/docs/internals/remote.md index 585c834d40038..818467de54502 100644 --- a/docs/internals/remote.md +++ b/docs/internals/remote.md @@ -181,6 +181,9 @@ undo by accident: up in `/proc/net/tcp` and refuses other users. macOS and Windows have no such check yet. The mobile app's device preview has the same listener while it is open: iOS suspends other apps, but Android lets any app reach it, and apps cannot see another app's socket owner there. +- **Off stays routed.** `allowsPreviewTunnel` (setting plus policy) gates the route and, from + server config, the clients, which then stream. The partition keeps its tunnel proxy anyway, so a + desktop tab left open fails instead of loading the reviewer's own localhost. - **System browser links** have no tunnel. They keep the private-network rewrite in [`browserTargetResolver.ts`](../../apps/web/src/browser/browserTargetResolver.ts). diff --git a/docs/user/managed-policy.md b/docs/user/managed-policy.md index ab8d7133c5dbd..210f3316e046e 100644 --- a/docs/user/managed-policy.md +++ b/docs/user/managed-policy.md @@ -169,6 +169,7 @@ A few settings need care: "connect": false, "webhookTasks": false, "browserCookieImport": false, + "previewTunnel": false, "telemetry": false, "providers": { "allowedDrivers": ["claudeAgent", "codex"], @@ -250,6 +251,10 @@ so restart T3 Code after that. but do not run, and cannot be turned back on. Users can still edit or delete them. - `browserCookieImport: false`: users cannot import cookies from another browser into T3 Code's browser. +- `previewTunnel: false`: other devices cannot load this machine's `localhost` pages themselves. + Browser tabs stream from it instead, and port forwarding and **Open on this device** are + unavailable. This wins over the user's + [Preview tunnel setting](./remote-access.md#browser-on-a-remote-environment). - `telemetry: false`: the server and desktop app send no [product usage data](./telemetry.md) or relay connection traces. A policy cannot turn them on. A browser that opens the server, such as app.t3.codes, still sends its own relay traces. diff --git a/docs/user/remote-access.md b/docs/user/remote-access.md index 17c6e36df1576..1b80179a3f319 100644 --- a/docs/user/remote-access.md +++ b/docs/user/remote-access.md @@ -330,6 +330,14 @@ and site data on the phone. On iPhone and iPad the page runs under a stand-in address while the address bar shows `localhost`, so browser features that need a secure page, such as the clipboard or service workers, aren't available there. +All of this rides the host's preview tunnel. Turn off **Settings → Sharing & +access → Preview tunnel** on the host to stop other devices from loading its +`localhost` pages themselves: port forwarding and **Open on this device** go +away, and open tunnels close. Tabs keep working by streaming from the host, so +anyone who can use the host's browser tabs can still view its `localhost` pages +there. An administrator can also turn it off with a +[managed policy](./managed-policy.md#other-capabilities). + The first tab downloads a headless Chrome, about 120 MB, into the T3 home. It is the same browser [HTML renders](html-renders.md) use, so a host downloads it only once. Some Linux hosts need [setup](#browser-host-setup) before it can diff --git a/packages/client-runtime/src/contractLabels.ts b/packages/client-runtime/src/contractLabels.ts index 2ff6d7f994c34..bfeb284300b09 100644 --- a/packages/client-runtime/src/contractLabels.ts +++ b/packages/client-runtime/src/contractLabels.ts @@ -129,7 +129,8 @@ export type ManagedCapability = | "remoteClients" | "connect" | "webhookTasks" - | "browserCookieImport"; + | "browserCookieImport" + | "previewTunnel"; function managedCapabilityDeniedMessage( organization: string, @@ -155,6 +156,13 @@ function managedCapabilityDeniedMessage( organization, }), ); + case "previewTunnel": + return resolve( + msg( + "{organization}'s policy does not allow opening this machine's local servers on other devices.", + { organization }, + ), + ); } } diff --git a/packages/contracts/src/environment.ts b/packages/contracts/src/environment.ts index f95b7f8c04b97..a7316a9f0482d 100644 --- a/packages/contracts/src/environment.ts +++ b/packages/contracts/src/environment.ts @@ -146,6 +146,8 @@ export const ExecutionEnvironmentCapabilities = Schema.Struct({ threadStop: Schema.optionalKey(Schema.Boolean), /** Absent on older servers and on Windows hosts, which cannot stop a discovered server. */ localServerStop: Schema.optionalKey(Schema.Boolean), + /** Honors `enablePreviewTunnel`; hide the switch where absent, since the tunnel stays on there. */ + previewTunnelSetting: Schema.optionalKey(Schema.Boolean), threadPullRequests: Schema.optionalKey(Schema.Boolean), threadPullRequestWatch: Schema.optionalKey(Schema.Boolean), pullRequestStackActions: Schema.optionalKey(Schema.Boolean), diff --git a/packages/contracts/src/managedPolicy.ts b/packages/contracts/src/managedPolicy.ts index 7d1c7ed8b8aae..e35f9f6e5c173 100644 --- a/packages/contracts/src/managedPolicy.ts +++ b/packages/contracts/src/managedPolicy.ts @@ -81,6 +81,8 @@ export const ManagedPolicyLimits = Schema.Struct({ /** Can only turn product analytics off, never force it on. */ telemetry: Schema.optionalKey(Schema.Boolean), browserCookieImport: Schema.optionalKey(Schema.Boolean), + /** `false` turns the preview tunnel off: no client reaches this machine's loopback ports. */ + previewTunnel: Schema.optionalKey(Schema.Boolean), providers: Schema.optionalKey(ManagedProviderLimits), updates: Schema.optionalKey(ManagedUpdatesPolicy), }); @@ -95,6 +97,7 @@ export const ManagedPolicySummaryLimits = Schema.Struct({ webhookTasks: Schema.optionalKey(Schema.Boolean), telemetry: Schema.optionalKey(Schema.Boolean), browserCookieImport: Schema.optionalKey(Schema.Boolean), + previewTunnel: Schema.optionalKey(Schema.Boolean), providers: Schema.optionalKey( Schema.Struct({ /** Absent means every driver is allowed. */ @@ -209,6 +212,7 @@ const CAPABILITY_LABELS = { connect: "T3 Connect", webhookTasks: "webhook tasks", browserCookieImport: "importing browser cookies", + previewTunnel: "opening this machine's local servers on other devices", } as const; /** Why a capability is unavailable on an environment with `summary`, or undefined when allowed. */ @@ -227,6 +231,16 @@ export function managedCapabilityDenial( : undefined; } +/** Whether the preview tunnel serves: the setting is on and no policy switches it off. */ +export function allowsPreviewTunnel(config: { + readonly settings: { readonly enablePreviewTunnel: boolean }; + readonly managedPolicy?: ManagedPolicySummary | undefined; +}): boolean { + return ( + config.settings.enablePreviewTunnel && config.managedPolicy?.limits?.previewTunnel !== false + ); +} + /** Whether the policy lets `driver` run; clients name it with their own provider label. */ export function isManagedDriverAllowed( summary: ManagedPolicySummary | undefined, diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts index 678f58294c66a..378b8af0e466f 100644 --- a/packages/contracts/src/settings.ts +++ b/packages/contracts/src/settings.ts @@ -1396,6 +1396,8 @@ export const ServerSettings = Schema.Struct({ ), enableAgentBrowserAccess: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))), + /** Lets clients reach this machine's loopback ports over `/api/preview/tunnel`. */ + enablePreviewTunnel: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))), cloudSpeechCredentials: CloudSpeechCredentials.pipe( Schema.withDecodingDefault(Effect.succeed({ openai: "", xai: "", openrouter: "" })), ), @@ -1858,6 +1860,7 @@ export const ServerSettingsPatch = Schema.Struct({ keepAwakeWhileAgentsWork: Schema.optionalKey(Schema.Boolean), requireConnectDeviceApproval: Schema.optionalKey(Schema.Boolean), enableAgentBrowserAccess: Schema.optionalKey(Schema.Boolean), + enablePreviewTunnel: Schema.optionalKey(Schema.Boolean), cloudSpeechCredentials: Schema.optionalKey( Schema.Struct({ openai: Schema.optionalKey(SettingsSecretValue), @@ -2006,7 +2009,7 @@ export function requiredScopesForServerSettingsPatch( let changesAccess = false; for (const [key, value] of Object.entries(patch)) { if (value === undefined) continue; - if (key === "requireConnectDeviceApproval") { + if (key === "requireConnectDeviceApproval" || key === "enablePreviewTunnel") { changesAccess = true; } else if ( key === "providers" || diff --git a/packages/shared/src/managedPolicyFile.ts b/packages/shared/src/managedPolicyFile.ts index 2f775abb8a02a..e222c7cb94190 100644 --- a/packages/shared/src/managedPolicyFile.ts +++ b/packages/shared/src/managedPolicyFile.ts @@ -114,6 +114,7 @@ export const WINDOWS_POLICY_VALUES = { WebhookTasks: { type: "boolean", path: ["limits", "webhookTasks"] }, Telemetry: { type: "boolean", path: ["limits", "telemetry"] }, BrowserCookieImport: { type: "boolean", path: ["limits", "browserCookieImport"] }, + PreviewTunnel: { type: "boolean", path: ["limits", "previewTunnel"] }, ProviderInstances: { type: "json", path: ["limits", "providers", "instances"] }, UpdatesMode: { type: "string", path: ["limits", "updates", "mode"] }, UpdatesFeedUrl: { type: "string", path: ["limits", "updates", "feedUrl"] }, From 5ee1c2f652edbb488592ec93c3bf0096302803d6 Mon Sep 17 00:00:00 2001 From: Simone Date: Fri, 20 Nov 2026 00:51:07 +0100 Subject: [PATCH 96/97] fix(server): accept Antigravity model IDs with thinking levels when delegating (#39413) Co-authored-by: Simone <185146821+Lucenx9@users.noreply.github.com> Co-authored-by: Julius Marminge --- .../src/mcp/OrchestratorMcpService.test.ts | 57 ++++++++++++++++++- apps/server/src/mcp/OrchestratorMcpService.ts | 31 ++++++++-- 2 files changed, 83 insertions(+), 5 deletions(-) diff --git a/apps/server/src/mcp/OrchestratorMcpService.test.ts b/apps/server/src/mcp/OrchestratorMcpService.test.ts index 0890d5de0340e..2afed50b27c6e 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.test.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.test.ts @@ -4361,6 +4361,7 @@ describe("OrchestratorMcpService provider resolution", () => { () => Effect.gen(function* () { const peerId = ProviderInstanceId.make("codex-subscription-2"); + const antigravityId = ProviderInstanceId.make("antigravity"); const driver = ProviderDriverKind.make("codex"); const inherited = { instanceId: codexInstanceId, @@ -4408,6 +4409,33 @@ describe("OrchestratorMcpService provider resolution", () => { target: { providerInstanceId: peerId, options: { reasoningEffort: "max" } }, expected: { instanceId: peerId, model: inherited.model, options: override }, }, + { + name: "Antigravity model with a thinking suffix", + target: { providerInstanceId: antigravityId, model: "gemini-4-neon-high" }, + expected: { + instanceId: antigravityId, + model: "gemini-4-neon", + options: [{ id: "thought_level", value: "high" }], + }, + }, + { + name: "explicit Antigravity thinking overrides the suffix", + target: { + providerInstanceId: antigravityId, + model: "gemini-4-neon-high", + options: { thought_level: "medium" }, + }, + expected: { + instanceId: antigravityId, + model: "gemini-4-neon", + options: [{ id: "thought_level", value: "medium" }], + }, + }, + { + name: "clear Antigravity suffix options", + target: { providerInstanceId: antigravityId, model: "gemini-4-neon-high", options: {} }, + expected: { instanceId: antigravityId, model: "gemini-4-neon", options: [] }, + }, { name: "old Ultracode effort level", target: { model: "ultracode-model", options: { effort: "ultracode" } }, @@ -4495,8 +4523,35 @@ describe("OrchestratorMcpService provider resolution", () => { ], }, providerSnapshot({ instanceId: peerId, driver, model: inherited.model }), + { + ...providerSnapshot({ + instanceId: antigravityId, + driver: ProviderDriverKind.make("antigravity"), + }), + models: [ + { + slug: "gemini-4-neon", + name: "Gemini 4 Neon", + isCustom: false, + capabilities: { + optionDescriptors: [ + { + id: "thought_level", + role: "reasoning", + label: "Thinking", + type: "select", + options: [ + { id: "medium", label: "Medium" }, + { id: "high", label: "High" }, + ], + }, + ], + }, + }, + ], + }, ]), - adapterRegistryLayer([codexInstanceId, peerId]), + adapterRegistryLayer([codexInstanceId, peerId, antigravityId]), Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }), Layer.mock(SecretRequests.SecretRequests)({}), Layer.mock(RemoteDelegation.RemoteDelegation)({}), diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts index c9009d6597671..bd57bebb3fc35 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.ts @@ -397,6 +397,23 @@ const advertisedModel = (provider: ServerProvider, model: string) => candidate.aliases?.some((alias) => alias.toLowerCase() === model.toLowerCase()), ); +/** Antigravity 1.3 IDs append the thinking level (`gemini-3.8-flash-high`); the agent still accepts them. */ +function antigravitySuffixedModel(provider: ServerProvider, model: string) { + if (provider.driver !== "antigravity" || advertisedModel(provider, model)) return; + const separator = model.lastIndexOf("-"); + if (separator === -1) return; + const family = model.slice(0, separator); + const value = model.slice(separator + 1); + const thinking = provider.models + .find((candidate) => candidate.slug === family) + ?.capabilities?.optionDescriptors?.find( + (descriptor) => descriptor.type === "select" && descriptor.role === "reasoning", + ); + if (thinking?.type === "select" && thinking.options.some((choice) => choice.id === value)) { + return { model: family, thinking: { id: thinking.id, value } }; + } +} + /** A folder's own provider config can add models that only its workspace snapshot lists. */ export const withWorkspaceModels = ( providers: ReadonlyArray, @@ -1690,7 +1707,10 @@ const make = Effect.gen(function* () { const inheritedSelection = input.parent.thread.modelSelection; const requestedModel = input.target?.model; + const antigravityTarget = + requestedModel === undefined ? undefined : antigravitySuffixedModel(provider, requestedModel); const model = + antigravityTarget?.model ?? requestedModel ?? (instanceId === inheritedSelection.instanceId ? inheritedSelection.model @@ -1701,7 +1721,7 @@ const make = Effect.gen(function* () { `Provider ${instanceId} has no model available for inheritance.`, ); } - if (requestedModel !== undefined) yield* requireAdvertisedModel(provider, requestedModel); + if (requestedModel !== undefined) yield* requireAdvertisedModel(provider, model); const advertised = advertisedModel(provider, model); const descriptors = advertised?.capabilities?.optionDescriptors; const requestedOptions = withLegacyUltracodeEffort(descriptors, input.target?.options); @@ -1725,14 +1745,17 @@ const make = Effect.gen(function* () { descriptors, ) : undefined; - if (requestedOptions !== undefined) { + if (requestedOptions !== undefined || antigravityTarget !== undefined) { const selections = new Map( - (requestedOptions.length === 0 ? [] : (options ?? [])).map((selection) => [ + (requestedOptions?.length === 0 ? [] : (options ?? [])).map((selection) => [ selection.id, selection, ]), ); - for (const selection of requestedOptions) { + if (antigravityTarget !== undefined && requestedOptions?.length !== 0) { + selections.set(antigravityTarget.thinking.id, antigravityTarget.thinking); + } + for (const selection of requestedOptions ?? []) { selections.set(selection.id, selection); } options = [...selections.values()]; From 38bac7091a71eb6e01b63b70f6b1bae7441ed5bc Mon Sep 17 00:00:00 2001 From: Viktor Leukocyte Date: Thu, 19 Nov 2026 23:54:11 +0000 Subject: [PATCH 97/97] fix(client-runtime): an unexpected failure no longer stops the reconnect loop for good (#39420) Co-authored-by: Julius Marminge --- .../src/connection/supervisor.test.ts | 339 +++++++++++++++++- .../src/connection/supervisor.ts | 213 ++++++----- ...ig-stream-failing-while-interrupted.e2e.ts | 85 +++++ 3 files changed, 531 insertions(+), 106 deletions(-) create mode 100644 scripts/scenarios/reconnect-survives-config-stream-failing-while-interrupted.e2e.ts diff --git a/packages/client-runtime/src/connection/supervisor.test.ts b/packages/client-runtime/src/connection/supervisor.test.ts index 46b9757d0cd83..81c8bf4064a45 100644 --- a/packages/client-runtime/src/connection/supervisor.test.ts +++ b/packages/client-runtime/src/connection/supervisor.test.ts @@ -6,14 +6,19 @@ import { } from "@t3tools/contracts"; import { describe, expect, it } from "@effect/vitest"; import { RelayClientTracer } from "@t3tools/shared/relayTracing"; +import * as Cause from "effect/Cause"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; +import * as Logger from "effect/Logger"; import * as Option from "effect/Option"; import * as Queue from "effect/Queue"; import * as Random from "effect/Random"; import * as Ref from "effect/Ref"; +import * as References from "effect/References"; +import * as Scope from "effect/Scope"; import * as Stream from "effect/Stream"; import * as SubscriptionRef from "effect/SubscriptionRef"; import * as Clock from "effect/Clock"; @@ -167,6 +172,18 @@ function awaitState( ); } +function recordLogs(logs: Array, annotations?: Array) { + return Logger.layer( + [ + Logger.make(({ message, fiber }) => { + logs.push(message); + annotations?.push(fiber.getRef(References.CurrentLogAnnotations)); + }), + ], + { mergeWithExisting: false }, + ); +} + const makeHarness = Effect.fn("TestConnectionHarness.make")(function* (options?: { readonly networkStatus?: NetworkStatus; readonly prepare?: ( @@ -174,6 +191,7 @@ const makeHarness = Effect.fn("TestConnectionHarness.make")(function* (options?: target: ConnectionTarget, ) => Effect.Effect; readonly ready?: (attempt: number) => Effect.Effect; + readonly release?: (attempt: number) => Effect.Effect; readonly probe?: (attempt: number) => Effect.Effect; readonly configEvents?: Stream.Stream | undefined; readonly initialConfig?: (attempt: number) => Effect.Effect; @@ -245,7 +263,10 @@ const makeHarness = Effect.fn("TestConnectionHarness.make")(function* (options?: inboundFrames: options?.inboundFrames ?? Effect.succeed(0), closed: Deferred.await(closed), } satisfies RpcSession.RpcSession), - () => Ref.update(releaseCount, (count) => count + 1), + () => + Ref.update(releaseCount, (count) => count + 1).pipe( + Effect.andThen(options?.release?.(attempt) ?? Effect.void), + ), ); yield* reportProgress({ stage: "synchronizing", prepared }); @@ -308,12 +329,12 @@ const makeHarness = Effect.fn("TestConnectionHarness.make")(function* (options?: reason, })), closeLatestSession: Effect.fn("TestConnectionHarness.closeLatestSession")(function* ( - error = transient("Session closed."), + exit: Exit.Exit = Exit.fail(transient("Session closed.")), ) { const sessions = yield* Ref.get(closedSessions); const latest = sessions.at(-1); if (latest) { - yield* Deferred.fail(latest, error); + yield* Deferred.done(latest, exit); } }), }; @@ -581,9 +602,11 @@ describe("EnvironmentSupervisor", () => { ? Effect.die(new Error("Native transport defect.")) : Effect.succeed(PREPARED_CONNECTION), }); + const logs: unknown[] = []; + const annotations: unknown[] = []; const supervisor = yield* EnvironmentSupervisor.make(RELAY_ENTRY, { initiallyDesired: true, - }).pipe(Effect.provide(harness.dependencies)); + }).pipe(Effect.provide(Layer.merge(harness.dependencies, recordLogs(logs, annotations)))); const failed = yield* awaitState( supervisor.state, @@ -596,6 +619,10 @@ describe("EnvironmentSupervisor", () => { message: "Test environment connection failed unexpectedly.", }, }); + expect(logs).toEqual([["Connection attempt failed with an unexpected defect."]]); + expect(annotations).toMatchObject([ + { "environment.id": RELAY_TARGET.environmentId, errorName: "Error" }, + ]); yield* TestClock.adjust("3 seconds"); yield* awaitState(supervisor.state, (state) => state.phase === "connected"); @@ -603,42 +630,322 @@ describe("EnvironmentSupervisor", () => { }).pipe(Effect.provide(TestClock.layer())), ); - it.effect("explicit retry interrupts the current backoff", () => + it.effect.each([ + { + label: "the attempt's network-status read dies", + firstPrepare: Effect.never, + statusDefect: true, + log: "Connection attempt failed with an unexpected defect.", + }, + { + label: "an attempt interrupts itself", + firstPrepare: Effect.interrupt, + statusDefect: false, + log: "Connection attempt failed with an unexpected interruption.", + }, + ])("retries after $label", ({ firstPrepare, statusDefect, log }) => + Effect.gen(function* () { + const harness = yield* makeHarness({ + prepare: (attempt) => (attempt === 1 ? firstPrepare : Effect.succeed(PREPARED_CONNECTION)), + }); + const statusReads = yield* Ref.make(0); + const logs: unknown[] = []; + const annotations: Array> = []; + const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, { + initiallyDesired: true, + }).pipe( + Effect.provideService( + Connectivity.Connectivity, + Connectivity.Connectivity.of({ + // The supervisor reads once at startup; the second read belongs to the first attempt. + status: Ref.updateAndGet(statusReads, (count) => count + 1).pipe( + Effect.flatMap((count) => + statusDefect && count === 2 + ? Effect.die(new Error("Platform connectivity defect.")) + : Effect.succeed("online" as const), + ), + ), + changes: Stream.never, + }), + ), + Effect.provide(Layer.merge(harness.dependencies, recordLogs(logs, annotations))), + ); + + const failed = yield* awaitState( + supervisor.state, + (state) => state.phase === "backoff" && state.attempt === 1, + ); + expect(failed).toMatchObject({ + generation: 0, + lastFailure: { _tag: "ConnectionTransientError", reason: "transport" }, + }); + expect(logs).toEqual([[log]]); + expect(Object.hasOwn(annotations[0]!, "errorType")).toBe(statusDefect); + + yield* TestClock.adjust("999 millis"); + expect(yield* Ref.get(harness.prepareCount)).toBe(1); + yield* TestClock.adjust("2 seconds"); + yield* awaitState(supervisor.state, (state) => state.phase === "connected"); + expect(yield* Ref.get(harness.prepareCount)).toBe(2); + }).pipe(Effect.provide(TestClock.layer())), + ); + + it.effect.each([ + { + label: "is interrupted", + closed: Exit.interrupt(), + releaseDefect: false, + log: "Connection attempt failed with an unexpected interruption.", + }, + { + label: "fails while interrupted", + closed: Exit.failCause( + Cause.combine(Cause.fail(transient("Session closed.")), Cause.interrupt()), + ), + releaseDefect: false, + log: null, + }, + { + label: "closes while its release defects", + closed: Exit.fail(transient("Session closed.")), + releaseDefect: true, + log: "Connection release failed with an unexpected defect.", + }, + ])("reconnects soon after a stable session $label", ({ closed, releaseDefect, log }) => Effect.gen(function* () { const harness = yield* makeHarness({ prepare: (attempt) => attempt === 1 ? Effect.fail(transient()) : Effect.succeed(PREPARED_CONNECTION), + release: (session) => + releaseDefect && session === 1 + ? Effect.die(new Error("Session release defect.")) + : Effect.void, }); + const logs: unknown[] = []; const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, { initiallyDesired: true, - }).pipe(Effect.provide(harness.dependencies)); + }).pipe(Effect.provide(Layer.merge(harness.dependencies, recordLogs(logs)))); yield* awaitState(supervisor.state, (state) => state.phase === "backoff"); + yield* TestClock.adjust("2 seconds"); + yield* awaitState( + supervisor.state, + (state) => state.phase === "connected" && state.generation === 1, + ); + yield* TestClock.adjust("1 minute"); + yield* harness.closeLatestSession(closed); + const lost = yield* awaitState(supervisor.state, (state) => state.phase !== "connected"); + expect(logs).toEqual(log === null ? [] : [[log]]); + expect(lost).toMatchObject({ phase: "backoff", generation: 1 }); + expect(lost.retryAt).toBeLessThanOrEqual((yield* Clock.currentTimeMillis) + 250); + + yield* TestClock.adjust("250 millis"); + const replaced = yield* awaitState(supervisor.state, (state) => state.phase === "connected"); + expect(replaced.generation).toBe(2); + }).pipe(Effect.provide(TestClock.layer())), + ); + + it.effect( + "does not reuse a live session's generation when its attempt defects after going live", + () => + Effect.gen(function* () { + const harness = yield* makeHarness({ + prepare: (attempt) => + attempt === 1 ? Effect.fail(transient()) : Effect.succeed(PREPARED_CONNECTION), + }); + let logCalls = 0; + const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, { + initiallyDesired: true, + }).pipe( + Effect.provide( + Layer.merge( + harness.dependencies, + Logger.layer( + [ + // Logging the lost session's interruption throws, so the attempt itself defects. + Logger.make(() => { + logCalls += 1; + if (logCalls === 1) throw new Error("Logger defect."); + }), + ], + { mergeWithExisting: false }, + ), + ), + ), + ); + + yield* awaitState(supervisor.state, (state) => state.phase === "backoff"); + yield* TestClock.adjust("2 seconds"); + yield* awaitState( + supervisor.state, + (state) => state.phase === "connected" && state.generation === 1, + ); + yield* harness.closeLatestSession(Exit.interrupt()); + const backoff = yield* awaitState(supervisor.state, (state) => state.phase === "backoff"); + expect(backoff).toMatchObject({ generation: 1, lastFailure: null }); + + yield* TestClock.adjust("4 seconds"); + const replaced = yield* awaitState( + supervisor.state, + (state) => state.phase === "connected", + ); + expect(replaced.generation).toBe(2); + }).pipe(Effect.provide(TestClock.layer())), + ); + + it.effect("restarts the loop after a defect outside an attempt", () => + Effect.gen(function* () { + const harness = yield* makeHarness(); + const logs: unknown[] = []; + let randomReads = 0; + const supervisor = yield* EnvironmentSupervisor.make(RELAY_ENTRY, { + initiallyDesired: true, + }).pipe( + Effect.provideService(Random.Random, { + // Both session losses below die here, so the second reaches the restart handler again. + nextDoubleUnsafe: () => { + randomReads += 1; + if (randomReads <= 2) throw new Error("Random defect."); + return 1 - Number.EPSILON; + }, + nextIntUnsafe: () => 0, + }), + Effect.provide(Layer.merge(harness.dependencies, recordLogs(logs))), + ); + + yield* awaitState( + supervisor.state, + (state) => state.phase === "connected" && state.generation === 1, + ); + yield* harness.closeLatestSession(); + const restarted = yield* awaitState(supervisor.state, (state) => state.phase === "backoff"); + expect(logs).toEqual([["Connection loop failed with an unexpected defect."]]); + expect(restarted).toMatchObject({ + attempt: 1, + generation: 1, + lastFailure: { _tag: "ConnectionTransientError", reason: "transport" }, + retryAt: (yield* Clock.currentTimeMillis) + 300_000, + }); + + yield* TestClock.adjust("299999 millis"); + expect(yield* Ref.get(harness.sessionCount)).toBe(1); + yield* TestClock.adjust("1 millis"); + const reconnected = yield* awaitState( + supervisor.state, + (state) => state.phase === "connected", + ); + expect(reconnected.generation).toBe(2); + + yield* harness.setNetworkStatus("offline"); + yield* harness.closeLatestSession(); + const offline = yield* awaitState(supervisor.state, (state) => state.phase !== "connected"); + expect(offline).toMatchObject({ + phase: "offline", + attempt: 1, + lastFailure: { _tag: "ConnectionTransientError", reason: "transport" }, + }); + yield* supervisor.retryNow; - yield* awaitState(supervisor.state, (state) => state.phase === "connected"); + const retried = yield* awaitState(supervisor.state, (state) => state.phase === "connected"); + expect(retried.generation).toBe(3); + }).pipe(Effect.provide(TestClock.layer())), + ); - expect(yield* Ref.get(harness.prepareCount)).toBe(2); - }), + it.effect.each(["connecting", "connected"] as const)( + "stops attempting when its scope closes while %s", + (phase) => + Effect.gen(function* () { + const preparing = yield* Deferred.make(); + const harness = yield* makeHarness({ + prepare: () => + Deferred.succeed(preparing, undefined).pipe( + Effect.andThen( + phase === "connected" ? Effect.succeed(PREPARED_CONNECTION) : Effect.never, + ), + ), + }); + const logs: unknown[] = []; + const scope = yield* Scope.make(); + const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, { + initiallyDesired: true, + }).pipe( + Effect.provide(Layer.merge(harness.dependencies, recordLogs(logs))), + Scope.provide(scope), + ); + + yield* Deferred.await(preparing); + yield* awaitState(supervisor.state, (state) => state.phase === phase); + // Yielding between finalizers lets the loop run if the queue shuts down before its interrupt. + yield* Scope.close(scope, Exit.void).pipe( + Effect.provideService(References.MaxOpsBeforeYield, 1), + ); + yield* TestClock.adjust("10 minutes"); + expect(logs).toEqual([]); + expect(yield* Ref.get(harness.prepareCount)).toBe(1); + }).pipe(Effect.provide(TestClock.layer())), ); - it.effect("keeps blocked failures idle until an external signal requests another attempt", () => + it.effect("explicit retry interrupts the current backoff", () => Effect.gen(function* () { const harness = yield* makeHarness({ prepare: (attempt) => - attempt === 1 ? Effect.fail(blocked()) : Effect.succeed(PREPARED_CONNECTION), + attempt === 1 ? Effect.fail(transient()) : Effect.succeed(PREPARED_CONNECTION), }); const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, { initiallyDesired: true, }).pipe(Effect.provide(harness.dependencies)); - yield* awaitState(supervisor.state, (state) => state.phase === "blocked"); - yield* TestClock.adjust("1 hour"); - expect(yield* Ref.get(harness.prepareCount)).toBe(1); - + yield* awaitState(supervisor.state, (state) => state.phase === "backoff"); yield* supervisor.retryNow; yield* awaitState(supervisor.state, (state) => state.phase === "connected"); + expect(yield* Ref.get(harness.prepareCount)).toBe(2); - }).pipe(Effect.provide(TestClock.layer())), + }), + ); + + it.effect.each([ + { label: "fails", cause: Cause.fail(blocked()) }, + { + label: "fails while interrupted", + cause: Cause.combine(Cause.fail(blocked()), Cause.interrupt()), + }, + ])( + "keeps a blocked host that $label idle until an external signal requests another attempt", + ({ cause }) => + Effect.gen(function* () { + const harness = yield* makeHarness(); + const driver = yield* ConnectionDriver.ConnectionDriver.pipe( + Effect.provide(harness.dependencies), + ); + const connects = yield* Ref.make(0); + const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, { + initiallyDesired: true, + }).pipe( + // The driver keeps only the typed error of a failed route, so the cause is mixed here. + Effect.provideService(ConnectionDriver.ConnectionDriver, { + ...driver, + connect: (entry, reportProgress) => + Ref.updateAndGet(connects, (count) => count + 1).pipe( + Effect.flatMap((count) => + count === 1 ? Effect.failCause(cause) : driver.connect(entry, reportProgress), + ), + ), + }), + Effect.provide(harness.dependencies), + ); + + const failed = yield* awaitState(supervisor.state, (state) => state.lastFailure !== null); + expect(failed).toMatchObject({ + phase: "blocked", + lastFailure: { _tag: "ConnectionBlockedError", detail: "Authentication required." }, + }); + yield* TestClock.adjust("1 hour"); + expect(yield* Ref.get(connects)).toBe(1); + + yield* supervisor.retryNow; + yield* awaitState(supervisor.state, (state) => state.phase === "connected"); + expect(yield* Ref.get(connects)).toBe(2); + }).pipe(Effect.provide(TestClock.layer())), ); it.effect("retries a blocked connection when platform credentials change", () => diff --git a/packages/client-runtime/src/connection/supervisor.ts b/packages/client-runtime/src/connection/supervisor.ts index 58411d795b7fc..79e6802805205 100644 --- a/packages/client-runtime/src/connection/supervisor.ts +++ b/packages/client-runtime/src/connection/supervisor.ts @@ -149,16 +149,6 @@ type EstablishmentEvent = | { readonly _tag: "Interrupted"; readonly resetRetry: boolean } | { readonly _tag: "TimedOut" }; -function exitUnlessInterrupted( - effect: Effect.Effect, -): Effect.Effect, never, R> { - return Effect.matchCauseEffect(effect, { - onFailure: (cause) => - Cause.hasInterrupts(cause) ? Effect.interrupt : Effect.succeed(Exit.failCause(cause)), - onSuccess: (value) => Effect.succeed(Exit.succeed(value)), - }); -} - export interface EnvironmentSupervisorOptions { readonly initiallyDesired?: boolean; readonly learnRoutes?: (input: { @@ -247,37 +237,27 @@ function connectingState( }; } -function failureFromExit( +function failureFromCause( target: ConnectionTarget, - exit: Exit.Exit, + cause: Cause.Cause, established: boolean, stable: boolean, -): AttemptOutcome { - if (Exit.isSuccess(exit) || Cause.hasInterruptsOnly(exit.cause)) { - return { _tag: "Interrupted", established, stable, resetRetry: false }; - } - const typedFailure = exit.cause.reasons.find(Cause.isFailReason); - if (typedFailure) { - return { - _tag: "Failure", - established, - stable, - failure: typedFailure.error, - }; - } +) { return { _tag: "Failure", established, stable, - failure: { - error: new ConnectionTransientError({ - reason: "transport", - ...translatableDetail( - msg("{host} connection failed unexpectedly.", { host: target.label }), - ), - }), - attemptSpan: Option.none(), - }, + failure: cause.reasons.find(Cause.isFailReason)?.error ?? unexpectedFailure(target), + } satisfies AttemptOutcome; +} + +function unexpectedFailure(target: ConnectionTarget): TracedAttemptFailure { + return { + error: new ConnectionTransientError({ + reason: "transport", + ...translatableDetail(msg("{host} connection failed unexpectedly.", { host: target.label })), + }), + attemptSpan: Option.none(), }; } @@ -496,9 +476,27 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* ( }), ); + const logUnexpectedFailure = ( + failed: "attempt" | "release" | "loop", + cause: Cause.Cause, + ) => { + const died = cause.reasons.find(Cause.isDieReason); + if (!died && cause.reasons.some(Cause.isFailReason)) return Effect.void; + return Effect.logError( + `Connection ${failed} failed with an unexpected ${died ? "defect" : "interruption"}.`, + ).pipe( + Effect.annotateLogs({ + "environment.id": target.environmentId, + "environment.label": target.label, + "cause.reason_count": cause.reasons.length, + ...(died ? safeErrorLogAttributes(died.defect) : {}), + }), + ); + }; + const reportProgress = Effect.fn("EnvironmentSupervisor.reportProgress")(function* ( attempt: number, - generation: number, + nextGeneration: number, lastFailure: ConnectionAttemptError | null, progress: ConnectionDriver.ConnectionDriverProgress, ) { @@ -506,13 +504,13 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* ( yield* SubscriptionRef.set(prepared, Option.some(progress.prepared)); } yield* setState( - connectingState(yield* Ref.get(intent), generation, attempt, lastFailure, progress.stage), + connectingState(yield* Ref.get(intent), nextGeneration, attempt, lastFailure, progress.stage), ); }); const establishConnection = Effect.fnUntraced(function* ( attempt: number, - generation: number, + nextGeneration: number, lastFailure: ConnectionAttemptError | null, synchronizedRoutes: Ref.Ref, ) { @@ -520,7 +518,7 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* ( (progress.stage === "synchronizing" ? Ref.update(synchronizedRoutes, (count) => count + 1) : Effect.void - ).pipe(Effect.andThen(reportProgress(attempt, generation, lastFailure, progress))), + ).pipe(Effect.andThen(reportProgress(attempt, nextGeneration, lastFailure, progress))), ); }); @@ -559,7 +557,7 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* ( Scope.Scope >, attempt: number, - generation: number, + nextGeneration: number, pendingRetry: Option.Option, ) => { // The span must end with the ConnectionAttemptError itself: the exporter @@ -572,7 +570,7 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* ( "environment.id": target.environmentId, "environment.target.kind": target._tag, "connection.attempt": attempt, - "connection.generation": generation, + "connection.generation": nextGeneration, "connection.retry.failure_count": Option.match(pendingRetry, { onNone: () => 0, onSome: (retry) => retry.failureCount, @@ -599,20 +597,25 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* ( const establishTracedConnection = Effect.fnUntraced(function* ( attempt: number, - generation: number, + nextGeneration: number, lastFailure: ConnectionAttemptError | null, pendingRetry: Option.Option, synchronizedRoutes: Ref.Ref, ) { if (usesRelay) { return yield* traceRelayEstablishment( - establishConnection(attempt, generation, lastFailure, synchronizedRoutes), + establishConnection(attempt, nextGeneration, lastFailure, synchronizedRoutes), attempt, - generation, + nextGeneration, pendingRetry, ); } - return yield* establishConnection(attempt, generation, lastFailure, synchronizedRoutes).pipe( + return yield* establishConnection( + attempt, + nextGeneration, + lastFailure, + synchronizedRoutes, + ).pipe( Effect.map((lease) => ({ attemptSpan: Option.none(), lease, @@ -946,9 +949,11 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* ( } }); + // Advanced as a session goes live and kept across loop restarts, so no two sessions share one. + let generation = 0; const runAttempt = Effect.fnUntraced(function* ( attempt: number, - generation: number, + nextGeneration: number, lastFailure: ConnectionAttemptError | null, pendingRetry: Option.Option, ignoreOffline: boolean, @@ -957,10 +962,10 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* ( yield* SubscriptionRef.set(prepared, Option.none()); const synchronizedRoutes = yield* Ref.make(0); const establishment = yield* Effect.raceAllFirst([ - exitUnlessInterrupted( + Effect.exit( establishTracedConnection( attempt, - generation, + nextGeneration, lastFailure, pendingRetry, synchronizedRoutes, @@ -1031,22 +1036,8 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* ( } satisfies AttemptOutcome; } if (Exit.isFailure(establishment.exit)) { - const isUnexpectedDefect = - !Cause.hasInterruptsOnly(establishment.exit.cause) && - !establishment.exit.cause.reasons.some(Cause.isFailReason); - const outcome = failureFromExit(target, establishment.exit, false, false); - if (isUnexpectedDefect) { - const defect = establishment.exit.cause.reasons.find(Cause.isDieReason)?.defect; - yield* Effect.logError("Connection attempt failed with an unexpected defect.").pipe( - Effect.annotateLogs({ - "environment.id": target.environmentId, - "environment.label": target.label, - "cause.reason_count": establishment.exit.cause.reasons.length, - ...safeErrorLogAttributes(defect), - }), - ); - } - return outcome; + yield* logUnexpectedFailure("attempt", establishment.exit.cause); + return failureFromCause(target, establishment.exit.cause, false, false); } const active = establishment.exit.value; @@ -1075,7 +1066,7 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* ( const connectedLease: ConnectedLease = { ...active.lease, activeRoute: routes.find((route) => connectionRouteId(route.target) === activeRouteId), - generation, + generation: nextGeneration, }; const refusedRouteIds = yield* Ref.updateAndGet(refusedRoutes, (known) => mergeRefusedRoutes( @@ -1086,6 +1077,7 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* ( ), ); const connectedAt = yield* Clock.currentTimeMillis; + generation = nextGeneration; yield* SubscriptionRef.set(prepared, Option.some(connectedLease.prepared)); yield* SubscriptionRef.set(session, Option.some(connectedLease.session)); if (options?.learnRoutes !== undefined) { @@ -1097,7 +1089,7 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* ( phase: "connected", stage: null, attempt, - generation, + generation: nextGeneration, lastFailure: null, retryAt: null, refusedRouteIds, @@ -1116,7 +1108,7 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* ( attemptSpan: active.attemptSpan, })), ), - ).pipe(exitUnlessInterrupted); + ).pipe(Effect.exit); const connectedForMs = (yield* Clock.currentTimeMillis) - connectedAt; if (Exit.isSuccess(connectedExit)) { return { @@ -1126,27 +1118,26 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* ( resetRetry: connectedExit.value, } satisfies AttemptOutcome; } - const outcome = failureFromExit( + yield* logUnexpectedFailure("attempt", connectedExit.cause); + const outcome = failureFromCause( target, - connectedExit, + connectedExit.cause, true, connectedForMs >= BACKOFF_RESET_AFTER_MS, ); - if (outcome._tag === "Failure") { - yield* Effect.void.pipe( - Effect.withSpan("EnvironmentSupervisor.connectionLost", { - root: true, - attributes: { - "environment.id": target.environmentId, - "environment.label": target.label, - "environment.target.kind": target._tag, - "connection.connected_ms": connectedForMs, - "connection.failure.reason": outcome.failure.error.reason, - "connection.failure.detail": outcome.failure.error.detail, - }, - }), - ); - } + yield* Effect.void.pipe( + Effect.withSpan("EnvironmentSupervisor.connectionLost", { + root: true, + attributes: { + "environment.id": target.environmentId, + "environment.label": target.label, + "environment.target.kind": target._tag, + "connection.connected_ms": connectedForMs, + "connection.failure.reason": outcome.failure.error.reason, + "connection.failure.detail": outcome.failure.error.detail, + }, + }), + ); return outcome; }, Effect.ensuring(clearLease)); @@ -1185,7 +1176,6 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* ( // Approval waits count as attempts but not toward backoff, so a later outage starts low. let backoffFailures = 0; let approvalWaits = 0; - let generation = 0; let latestFailure: ConnectionAttemptError | null = null; let pendingRetry = Option.none(); const resetRetryLadder = () => { @@ -1229,13 +1219,25 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* ( const attempt = failureCount + 1; const nextGeneration = generation + 1; - const outcome: AttemptOutcome = yield* Effect.scoped( - runAttempt(attempt, nextGeneration, latestFailure, pendingRetry, ignoreOffline), + const outcome: AttemptOutcome = yield* Effect.acquireUseRelease( + Scope.make(), + (scope) => + runAttempt(attempt, nextGeneration, latestFailure, pendingRetry, ignoreOffline).pipe( + Scope.provide(scope), + Effect.catchCause((cause) => + logUnexpectedFailure("attempt", cause).pipe( + Effect.as(failureFromCause(target, cause, generation === nextGeneration, false)), + ), + ), + ), + (scope, exit) => + Scope.close(scope, exit).pipe( + Effect.catchCause((cause) => logUnexpectedFailure("release", cause)), + ), ); replacing = false; const failedProbe = yield* Ref.getAndSet(probeUnanswered, false); if (outcome.established) { - generation = nextGeneration; // A session came up, so no earlier failure describes the connection. // Losing a live session is not a failed connection either, for example // a socket the OS killed while the app was suspended: its replacement @@ -1327,6 +1329,9 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* ( } }); + // Registered before the fibers below so closing the scope interrupts them first. + // A loop still running when the queue shuts down would report that as a failure. + yield* Effect.addFinalizer(() => Queue.shutdown(signals).pipe(Effect.andThen(clearLease))); yield* connectivity.changes.pipe( Stream.runForEach((network) => Ref.modify(intent, (current) => { @@ -1362,7 +1367,37 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* ( Effect.forever, Effect.forkScoped, ); - yield* run().pipe(Effect.forkScoped); + // A restarted loop has forgotten its retry ladder, so it waits out the + // ladder's ceiling unless a signal cuts the wait short. + yield* run().pipe( + Effect.catchCause((cause) => + Effect.gen(function* () { + yield* logUnexpectedFailure("loop", cause); + const currentIntent = yield* Ref.get(intent); + const lastFailure = unexpectedFailure(target).error; + yield* setState( + !currentIntent.desired + ? availableState(currentIntent, generation) + : currentIntent.network === "offline" + ? offlineState(currentIntent, generation, 1, lastFailure) + : { + desired: true, + network: currentIntent.network, + phase: "backoff", + stage: null, + attempt: 1, + generation, + lastFailure, + retryAt: (yield* Clock.currentTimeMillis) + RETRY_MAX_DELAY_MS, + refusedRouteIds: NO_REFUSED_ROUTES, + }, + ); + yield* waitForRetrySignal(RETRY_MAX_DELAY_MS); + }), + ), + Effect.forever, + Effect.forkScoped, + ); const connect = Ref.update(intent, (current) => ({ ...current, @@ -1385,8 +1420,6 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* ( Effect.withSpan("EnvironmentSupervisor.retryNow"), ); - yield* Effect.addFinalizer(() => Queue.shutdown(signals).pipe(Effect.andThen(clearLease))); - return EnvironmentSupervisor.of({ target, state, diff --git a/scripts/scenarios/reconnect-survives-config-stream-failing-while-interrupted.e2e.ts b/scripts/scenarios/reconnect-survives-config-stream-failing-while-interrupted.e2e.ts new file mode 100644 index 0000000000000..8e6a2606c1ba9 --- /dev/null +++ b/scripts/scenarios/reconnect-survives-config-stream-failing-while-interrupted.e2e.ts @@ -0,0 +1,85 @@ +import { expect } from "e2e"; +import * as Effect from "effect/Effect"; + +import { runPromise, test, WEB } from "./t3.ts"; + +interface Fault { + readonly failConfigStreamWhileInterrupted: () => boolean; +} + +test( + "The app reconnects after its config stream fails while interrupted", + WEB, + async ({ t3, app, screen, browser }) => { + const project = await t3.project("demo"); + const thread = await t3.thread({ + project, + title: "Earlier work", + messages: ["Print the JSON"], + model: "command-output", + }); + // Injected fault: the page hands the app one server frame that ends the config + // subscription with a typed failure and an interruption in the same cause. + await browser.addInitScript(() => { + let deliver: (() => void) | null = null; + const NativeWebSocket = window.WebSocket; + window.WebSocket = class extends NativeWebSocket { + override send(data: Parameters[0]) { + if (typeof data === "string" && data.includes('"tag":"subscribeServerConfig"')) { + const requestId = (JSON.parse(data) as { id: number | string }).id; + deliver = () => + this.dispatchEvent( + new MessageEvent("message", { + data: JSON.stringify({ + _tag: "Exit", + requestId, + exit: { + _tag: "Failure", + cause: [ + { + _tag: "Fail", + error: { + _tag: "KeybindingsConfigParseError", + configPath: "/demo/keybindings.json", + detail: "Injected failure.", + }, + }, + { _tag: "Interrupt", fiberId: 1 }, + ], + }, + }), + }), + ); + } + super.send(data); + } + }; + (window as unknown as { __fault: Fault }).__fault = { + failConfigStreamWhileInterrupted: () => { + deliver?.(); + return deliver !== null; + }, + }; + }); + await browser.emulateMedia({ colorScheme: "dark", reducedMotion: "reduce" }); + await t3.open(thread); + + const reply = screen.getByText("The command printed one JSON line."); + await expect(reply.first()).toBeVisible(); + await app.screenshot("1-connected"); + + const delivered = await browser.evaluate(() => + (window as unknown as { __fault: Fault }).__fault.failConfigStreamWhileInterrupted(), + ); + expect(delivered).toBe(true); + // A live loop reconnects well within each wait; a dead one never does. + await runPromise(Effect.sleep("5 seconds")); + await app.screenshot("2-five-seconds-after-the-failure"); + + await screen.getByRole("textbox").fill("Are you still there?"); + await screen.getByRole("textbox").press("Enter"); + await runPromise(Effect.sleep("3 seconds")); + await app.screenshot("3-after-pressing-enter"); + await expect(reply.nth(1)).toBeVisible(); + }, +);