From 6b48288f771f75e77b80f101e095547f3b0a8836 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 20 May 2026 13:17:57 +0200 Subject: [PATCH] Sync mobile remote branch with main Co-authored-by: codex --- .../review/nativeReviewDiffAdapter.ts | 431 ++++++++++++++++++ .../features/threads/NewTaskDraftScreen.tsx | 39 +- .../src/features/threads/ThreadComposer.tsx | 96 ++-- .../features/threads/ThreadDetailScreen.tsx | 2 +- .../features/threads/ThreadGitControls.tsx | 16 +- .../features/threads/claudeEffortOptions.ts | 6 +- .../features/threads/git/GitBranchesSheet.tsx | 2 +- .../features/threads/git/GitCommitSheet.tsx | 6 +- .../features/threads/git/GitOverviewSheet.tsx | 20 +- apps/mobile/src/lib/modelOptions.ts | 30 +- apps/mobile/src/lib/repositoryGroups.test.ts | 6 +- apps/mobile/src/lib/threadActivity.test.ts | 3 +- .../state/use-selected-thread-git-state.ts | 4 +- apps/mobile/src/state/use-vcs-refs.ts | 2 +- apps/mobile/src/state/use-vcs-status.ts | 2 +- apps/server/src/review/ReviewService.test.ts | 23 +- apps/server/src/review/ReviewService.ts | 7 +- .../src/terminal/Layers/Manager.test.ts | 6 +- apps/server/src/terminal/Layers/Manager.ts | 28 +- apps/server/src/vcs/GitVcsDriverCore.ts | 8 +- apps/web/src/components/ChatView.tsx | 2 +- apps/web/src/components/Sidebar.tsx | 2 - .../src/environments/runtime/connection.ts | 4 +- .../service.threadSubscriptions.test.ts | 27 +- apps/web/src/environments/runtime/service.ts | 5 +- apps/web/src/rpc/wsTransport.test.ts | 3 +- packages/client-runtime/src/gitActions.ts | 26 +- .../src/shellSnapshotReducer.test.ts | 4 +- .../src/shellSnapshotState.test.ts | 3 +- .../src/sourceControlDiscoveryState.test.ts | 1 - .../src/threadDetailReducer.test.ts | 8 +- .../src/threadDetailState.test.ts | 3 +- .../client-runtime/src/threadDetailState.ts | 49 +- packages/client-runtime/src/wsRpcClient.ts | 119 +++-- packages/client-runtime/src/wsRpcProtocol.ts | 13 +- .../client-runtime/src/wsTransport.test.ts | 12 +- packages/client-runtime/src/wsTransport.ts | 27 +- packages/contracts/src/review.ts | 2 +- 38 files changed, 799 insertions(+), 248 deletions(-) create mode 100644 apps/mobile/src/features/review/nativeReviewDiffAdapter.ts diff --git a/apps/mobile/src/features/review/nativeReviewDiffAdapter.ts b/apps/mobile/src/features/review/nativeReviewDiffAdapter.ts new file mode 100644 index 0000000000..d747dfc531 --- /dev/null +++ b/apps/mobile/src/features/review/nativeReviewDiffAdapter.ts @@ -0,0 +1,431 @@ +import type { NativeReviewDiffRow, NativeReviewDiffTheme } from "../diffs/nativeReviewDiffSurface"; +import type { + NativeReviewDiffFile, + NativeReviewDiffLanguage, +} from "../diffs/nativeReviewDiffTypes"; +import * as Arr from "effect/Array"; +import { pipe } from "effect/Function"; +import { getPierreTerminalTheme, type TerminalAppearanceScheme } from "../terminal/terminalTheme"; +import { computeWordAltDiffRanges } from "./reviewWordDiffs"; +import { + getReviewFilePreviewState, + type ReviewParsedDiff, + type ReviewRenderableFile, + type ReviewRenderableLineRow, +} from "./reviewModel"; +import type { ReviewInlineComment } from "./reviewCommentSelection"; + +const NATIVE_REVIEW_MAX_WORD_DIFF_RANGE_COUNT = 4; +const NATIVE_REVIEW_MAX_WORD_DIFF_COVERAGE = 0.45; + +export const NATIVE_REVIEW_DIFF_ROW_HEIGHT = 20; +export const NATIVE_REVIEW_DIFF_CONTENT_WIDTH = 2_800; + +export const NATIVE_REVIEW_DIFF_STYLE = { + rowHeight: NATIVE_REVIEW_DIFF_ROW_HEIGHT, + contentWidth: NATIVE_REVIEW_DIFF_CONTENT_WIDTH, + changeBarWidth: 4, + gutterWidth: 46, + codePadding: 7, + textVerticalInset: 2, + fileHeaderHeight: 56, + fileHeaderHorizontalMargin: 8, + fileHeaderVerticalMargin: 6, + fileHeaderCornerRadius: 10, + fileHeaderHorizontalPadding: 10, + fileHeaderPathRightPadding: 118, + fileHeaderCountColumnWidth: 38, + fileHeaderCountGap: 5, + codeFontSize: 11, + codeFontWeight: "regular", + lineNumberFontSize: 10, + lineNumberFontWeight: "regular", + hunkFontSize: 11, + hunkFontWeight: "medium", + fileHeaderFontSize: 11, + fileHeaderFontWeight: "semibold", + fileHeaderMetaFontSize: 10, + fileHeaderMetaFontWeight: "semibold", + fileHeaderSubtextFontSize: 11, + fileHeaderSubtextFontWeight: "medium", + fileHeaderStatusFontSize: 9, + fileHeaderStatusFontWeight: "bold", + emptyStateFontSize: 12, + emptyStateFontWeight: "medium", +} as const; + +export interface NativeReviewDiffData { + readonly rows: ReadonlyArray; + readonly files: ReadonlyArray; + readonly commentTargetsByRowId: ReadonlyMap; + readonly rowIdByCommentLineId: ReadonlyMap; + readonly additions: number; + readonly deletions: number; +} + +export interface NativeReviewDiffCommentTarget { + readonly filePath: string; + readonly lines: ReadonlyArray; + readonly lineIndex: number; +} + +export interface BuildNativeReviewDiffDataInput { + readonly parsedDiff: ReviewParsedDiff; + readonly comments?: ReadonlyArray; +} + +export function createNativeReviewDiffTheme( + scheme: TerminalAppearanceScheme, +): NativeReviewDiffTheme { + const terminalTheme = getPierreTerminalTheme(scheme); + const [, terminalRed, , , terminalBlue] = terminalTheme.palette; + + if (scheme === "dark") { + return { + background: terminalTheme.background, + text: terminalTheme.foreground, + mutedText: terminalTheme.mutedForeground, + headerBackground: terminalTheme.background, + border: terminalTheme.border, + hunkBackground: "#071f28", + hunkText: terminalBlue ?? "#009fff", + addBackground: "#0d2f28", + deleteBackground: "#391415", + addBar: "#00cab1", + deleteBar: terminalRed ?? "#ff2e3f", + addText: "#5ECC71", + deleteText: "#FF6762", + }; + } + + return { + background: "#ffffff", + text: "#070707", + mutedText: terminalTheme.mutedForeground, + headerBackground: "#ffffff", + border: terminalTheme.border, + hunkBackground: "#e0f2ff", + hunkText: terminalBlue ?? "#009fff", + addBackground: "#e5f8f5", + deleteBackground: "#ffe6e7", + addBar: "#00cab1", + deleteBar: terminalRed ?? "#ff2e3f", + addText: "#199F43", + deleteText: "#D52C36", + }; +} + +function mapChangeType(file: ReviewRenderableFile): NativeReviewDiffRow["changeType"] { + switch (file.changeType) { + case "change": + return "modified"; + case "new": + case "deleted": + case "rename-pure": + case "rename-changed": + return file.changeType; + default: + return "modified"; + } +} + +function getLanguageForPath( + filePath: string, + languageHint: string | null, +): NativeReviewDiffLanguage { + const hinted = languageHint?.toLowerCase(); + if (hinted === "typescript" || hinted === "tsx" || hinted === "javascript" || hinted === "jsx") { + return hinted; + } + if (hinted === "json" || hinted === "yaml" || hinted === "bash" || hinted === "diff") { + return hinted; + } + + const normalizedPath = filePath.toLowerCase(); + if (normalizedPath.endsWith(".tsx")) return "tsx"; + if (normalizedPath.endsWith(".ts")) return "typescript"; + if (normalizedPath.endsWith(".jsx")) return "jsx"; + if (normalizedPath.endsWith(".js") || normalizedPath.endsWith(".cjs")) return "javascript"; + if (normalizedPath.endsWith(".json") || normalizedPath.endsWith(".jsonc")) return "json"; + if (normalizedPath.endsWith(".yml") || normalizedPath.endsWith(".yaml")) return "yaml"; + if ( + normalizedPath.endsWith(".sh") || + normalizedPath.includes("/bin/") || + normalizedPath.includes("shell") + ) { + return "bash"; + } + return "diff"; +} + +function createNoticeRow(fileId: string, suffix: string, text: string): NativeReviewDiffRow { + return { + kind: "notice", + id: `${fileId}:notice:${suffix}`, + fileId, + text, + }; +} + +function noticeRowsForFile(file: ReviewRenderableFile): ReadonlyArray { + if (file.rows.length > 0) { + return []; + } + + const previewState = getReviewFilePreviewState(file); + if (previewState.kind === "suppressed" && previewState.reason === "non-text") { + return [ + createNoticeRow(file.id, "non-text", "Unsupported format. Diff contents are not available."), + ]; + } + + if (file.changeType === "rename-pure") { + return [createNoticeRow(file.id, "rename", "This file was renamed without modifications.")]; + } + + return []; +} + +function trimWordDiffRanges( + content: string, + ranges: NonNullable, +): NonNullable { + return pipe( + ranges, + Arr.flatMap((range) => { + let start = Math.max(0, range.start); + let end = Math.min(content.length, range.end); + + while (start < end && /\s/.test(content[start] ?? "")) { + start += 1; + } + while (end > start && /\s/.test(content[end - 1] ?? "")) { + end -= 1; + } + + return end > start ? [{ start, end }] : []; + }), + ); +} + +function nonWhitespaceLength(value: string) { + return value.replace(/\s/g, "").length; +} + +function shouldUseWordDiffRanges( + content: string, + ranges: NonNullable, +) { + if (ranges.length === 0 || ranges.length > NATIVE_REVIEW_MAX_WORD_DIFF_RANGE_COUNT) { + return false; + } + + const meaningfulLength = nonWhitespaceLength(content); + if (meaningfulLength === 0) { + return false; + } + + const highlightedLength = ranges.reduce( + (total, range) => total + nonWhitespaceLength(content.slice(range.start, range.end)), + 0, + ); + return highlightedLength / meaningfulLength <= NATIVE_REVIEW_MAX_WORD_DIFF_COVERAGE; +} + +function addNativeWordDiffRanges( + rows: ReadonlyArray, +): ReadonlyArray { + const nextRows = [...rows]; + let index = 0; + + while (index < nextRows.length) { + const deletedRowIndexes: number[] = []; + const addedRowIndexes: number[] = []; + const fileId = nextRows[index]?.fileId; + + while ( + nextRows[index]?.kind === "line" && + nextRows[index]?.change === "delete" && + nextRows[index]?.fileId === fileId + ) { + deletedRowIndexes.push(index); + index += 1; + } + + while ( + nextRows[index]?.kind === "line" && + nextRows[index]?.change === "add" && + nextRows[index]?.fileId === fileId + ) { + addedRowIndexes.push(index); + index += 1; + } + + const pairedCount = Math.min(deletedRowIndexes.length, addedRowIndexes.length); + for (let pairIndex = 0; pairIndex < pairedCount; pairIndex += 1) { + const deletedRowIndex = deletedRowIndexes[pairIndex]; + const addedRowIndex = addedRowIndexes[pairIndex]; + const deletedRow = nextRows[deletedRowIndex]; + const addedRow = nextRows[addedRowIndex]; + if (!deletedRow?.content || !addedRow?.content) { + continue; + } + + const ranges = computeWordAltDiffRanges({ + deletionLine: deletedRow.content, + additionLine: addedRow.content, + }); + const deletionRanges = trimWordDiffRanges(deletedRow.content, ranges.deletion); + const additionRanges = trimWordDiffRanges(addedRow.content, ranges.addition); + + if (shouldUseWordDiffRanges(deletedRow.content, deletionRanges)) { + nextRows[deletedRowIndex] = { ...deletedRow, wordDiffRanges: deletionRanges }; + } + if (shouldUseWordDiffRanges(addedRow.content, additionRanges)) { + nextRows[addedRowIndex] = { ...addedRow, wordDiffRanges: additionRanges }; + } + } + + if (deletedRowIndexes.length === 0 && addedRowIndexes.length === 0) { + index += 1; + } + } + + return nextRows; +} + +function mapLineRow( + file: ReviewRenderableFile, + row: ReviewRenderableLineRow, + rowIndex: number, +): NativeReviewDiffRow { + return { + kind: "line", + id: `${file.id}:line:${rowIndex}:${row.id}`, + fileId: file.id, + content: row.content, + change: row.change, + oldLineNumber: row.oldLineNumber, + newLineNumber: row.newLineNumber, + }; +} + +function mapFileRows( + file: ReviewRenderableFile, + comments: ReadonlyArray, + commentTargetsByRowId: Map, + rowIdByCommentLineId: Map, +): ReadonlyArray { + const rows: NativeReviewDiffRow[] = [ + { + kind: "file", + id: `${file.id}:header`, + fileId: file.id, + filePath: file.path, + previousPath: file.previousPath, + changeType: mapChangeType(file), + additions: file.additions, + deletions: file.deletions, + }, + ]; + + const lineRows = file.rows.filter((row): row is ReviewRenderableLineRow => row.kind === "line"); + const commentsByEndIndex = new Map(); + comments.forEach((comment) => { + if (comment.filePath !== file.path) { + return; + } + const endIndex = Math.min(comment.endIndex, lineRows.length - 1); + if (endIndex < 0) { + return; + } + const existing = commentsByEndIndex.get(endIndex); + if (existing) { + existing.push(comment); + return; + } + commentsByEndIndex.set(endIndex, [comment]); + }); + let lineIndex = 0; + file.rows.forEach((row, rowIndex) => { + if (row.kind === "hunk") { + rows.push({ + kind: "hunk", + id: `${file.id}:hunk:${rowIndex}:${row.id}`, + fileId: file.id, + text: row.context ? `${row.header} ${row.context}` : row.header, + }); + return; + } + + const nativeRow = mapLineRow(file, row, rowIndex); + rows.push(nativeRow); + rowIdByCommentLineId.set(row.id, nativeRow.id); + commentTargetsByRowId.set(nativeRow.id, { + filePath: file.path, + lines: lineRows, + lineIndex, + }); + const commentsForLine = commentsByEndIndex.get(lineIndex) ?? []; + for (const comment of commentsForLine) { + rows.push({ + kind: "comment", + id: comment.id, + fileId: file.id, + filePath: file.path, + commentText: comment.text, + commentRangeLabel: comment.rangeLabel, + commentSectionTitle: comment.sectionTitle, + }); + } + lineIndex += 1; + }); + + rows.push(...noticeRowsForFile(file)); + return rows; +} + +export function buildNativeReviewDiffData( + input: BuildNativeReviewDiffDataInput, +): NativeReviewDiffData; +export function buildNativeReviewDiffData(parsedDiff: ReviewParsedDiff): NativeReviewDiffData; +export function buildNativeReviewDiffData( + input: ReviewParsedDiff | BuildNativeReviewDiffDataInput, +): NativeReviewDiffData { + const parsedDiff = "parsedDiff" in input ? input.parsedDiff : input; + const comments = "parsedDiff" in input ? (input.comments ?? []) : []; + if (parsedDiff.kind !== "files") { + return { + rows: [], + files: [], + commentTargetsByRowId: new Map(), + rowIdByCommentLineId: new Map(), + additions: 0, + deletions: 0, + }; + } + + const files = parsedDiff.files.map((file) => ({ + id: file.id, + path: file.path, + language: getLanguageForPath(file.path, file.languageHint), + additions: file.additions, + deletions: file.deletions, + })); + const commentTargetsByRowId = new Map(); + const rowIdByCommentLineId = new Map(); + const rows = addNativeWordDiffRanges( + Arr.flatMap(parsedDiff.files, (file) => + mapFileRows(file, comments, commentTargetsByRowId, rowIdByCommentLineId), + ), + ); + + return { + rows, + files, + commentTargetsByRowId, + rowIdByCommentLineId, + additions: parsedDiff.additions, + deletions: parsedDiff.deletions, + }; +} diff --git a/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx b/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx index a7db692803..0c713ec5df 100644 --- a/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx +++ b/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx @@ -23,6 +23,18 @@ import { CLAUDE_AGENT_EFFORT_OPTIONS } from "./claudeEffortOptions"; import { branchBadgeLabel, useNewTaskFlow } from "./new-task-flow-provider"; import { useProjectActions } from "./use-project-actions"; +function withModelSelectionOption( + selection: ModelSelection, + id: string, + value: string | boolean | undefined, +): ModelSelection { + const options = (selection.options ?? []).filter((option) => option.id !== id); + return { + ...selection, + options: value === undefined ? options : [...options, { id, value }], + }; +} + export function NewTaskDraftScreen(props: { readonly initialProjectRef?: { readonly environmentId?: string; @@ -102,7 +114,7 @@ export function NewTaskDraftScreen(props: { subtitle: group.models.find( (model) => flow.selectedModel && - model.selection.provider === flow.selectedModel.provider && + model.selection.instanceId === flow.selectedModel.instanceId && model.selection.model === flow.selectedModel.model, )?.label, subactions: group.models.map((option) => ({ @@ -110,7 +122,7 @@ export function NewTaskDraftScreen(props: { title: option.label, state: flow.selectedModel && - option.selection.provider === flow.selectedModel.provider && + option.selection.instanceId === flow.selectedModel.instanceId && option.selection.model === flow.selectedModel.model ? ("on" as const) : undefined, @@ -345,17 +357,18 @@ export function NewTaskDraftScreen(props: { flow.setSubmitting(true); try { const modelWithOptions: ModelSelection = - flow.selectedModel.provider === "claudeAgent" - ? { - ...flow.selectedModel, - options: { - effort: flow.effort, - fastMode: flow.fastMode || undefined, - contextWindow: flow.contextWindow, - }, - } - : flow.selectedModel.provider === "codex" - ? { ...flow.selectedModel, options: { fastMode: flow.fastMode || undefined } } + flow.selectedModelOption?.providerDriver === "claudeAgent" + ? withModelSelectionOption( + withModelSelectionOption( + withModelSelectionOption(flow.selectedModel, "effort", flow.effort), + "fastMode", + flow.fastMode || undefined, + ), + "contextWindow", + flow.contextWindow, + ) + : flow.selectedModelOption?.providerDriver === "codex" + ? withModelSelectionOption(flow.selectedModel, "fastMode", flow.fastMode || undefined) : flow.selectedModel; const createdThread = await onCreateThreadWithOptions({ diff --git a/apps/mobile/src/features/threads/ThreadComposer.tsx b/apps/mobile/src/features/threads/ThreadComposer.tsx index 9d99a60525..16b7bc11f2 100644 --- a/apps/mobile/src/features/threads/ThreadComposer.tsx +++ b/apps/mobile/src/features/threads/ThreadComposer.tsx @@ -42,8 +42,12 @@ import { normalizeSearchQuery, scoreQueryMatch, } from "@t3tools/shared/searchRanking"; +import { + getModelSelectionBooleanOptionValue, + getModelSelectionStringOptionValue, +} from "@t3tools/shared/model"; import { useComposerPathSearch } from "../../state/use-composer-path-search"; -import { CLAUDE_AGENT_EFFORT_OPTIONS, type ClaudeAgentEffort } from "./claudeEffortOptions"; +import { CLAUDE_AGENT_EFFORT_OPTIONS } from "./claudeEffortOptions"; import { ComposerCommandPopover, type ComposerCommandItem } from "./ComposerCommandPopover"; /** @@ -65,22 +69,6 @@ export const COMPOSER_EXPANDED_CHROME = 174; */ export const COMPOSER_EXPANDED_TOOLBAR_CHROME = 54; -function withModelSelectionOption( - selection: ModelSelection, - id: string, - value: string | boolean | undefined, -): ModelSelection { - const options = (selection.options ?? []).filter((option) => option.id !== id); - if (value !== undefined) { - options.push({ id, value }); - } - if (options.length === 0) { - const { options: _options, ...rest } = selection; - return rest as ModelSelection; - } - return { ...selection, options } as ModelSelection; -} - export interface ThreadComposerProps { readonly draftMessage: string; readonly draftAttachments: ReadonlyArray; @@ -145,6 +133,18 @@ function ComposerSurface(props: { ); } +function withModelSelectionOption( + selection: ModelSelection, + id: string, + value: string | boolean | undefined, +): ModelSelection { + const options = (selection.options ?? []).filter((option) => option.id !== id); + return { + ...selection, + options: value === undefined ? options : [...options, { id, value }], + }; +} + export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposerProps) { const isDarkMode = useColorScheme() === "dark"; const themePlaceholderColor = useThemeColor("--color-placeholder"); @@ -184,23 +184,30 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer props.queueCount > 0; const sendLabel = props.activeThreadBusy || props.queueCount > 0 ? "Queue" : "Send"; - const modelProvider = props.selectedThread.modelSelection?.provider ?? null; + const modelProvider = props.selectedThread.modelSelection?.instanceId ?? null; const currentModelSelection = props.selectedThread.modelSelection; const currentRuntimeMode = props.selectedThread.runtimeMode; const currentInteractionMode = props.selectedThread.interactionMode ?? "default"; + const selectedProviderStatus = useMemo(() => { + if (!props.serverConfig) return null; + return ( + props.serverConfig.providers.find( + (p) => p.instanceId === props.selectedThread.modelSelection.instanceId, + ) ?? null + ); + }, [props.serverConfig, props.selectedThread.modelSelection.instanceId]); // Extract current model options (effort, fastMode, contextWindow) + const selectedProviderDriver = selectedProviderStatus?.driver ?? null; const currentEffort = - currentModelSelection.provider === "claudeAgent" - ? (currentModelSelection.options?.effort ?? "high") + selectedProviderDriver === "claudeAgent" + ? (getModelSelectionStringOptionValue(currentModelSelection, "effort") ?? "high") : "high"; const currentFastMode = - currentModelSelection.options && "fastMode" in currentModelSelection.options - ? (currentModelSelection.options.fastMode ?? false) - : false; + getModelSelectionBooleanOptionValue(currentModelSelection, "fastMode") ?? false; const currentContextWindow = - currentModelSelection.provider === "claudeAgent" - ? (currentModelSelection.options?.contextWindow ?? "1M") + selectedProviderDriver === "claudeAgent" + ? (getModelSelectionStringOptionValue(currentModelSelection, "contextWindow") ?? "1M") : "1M"; const handleNativePaste = useNativePaste((uris) => { @@ -228,16 +235,6 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer query: composerTrigger?.kind === "path" ? composerTrigger.query : null, }); - // ── Build menu items ───────────────────────────────────── - const selectedProviderStatus = useMemo(() => { - if (!props.serverConfig) return null; - return ( - props.serverConfig.providers.find( - (p) => p.provider === props.selectedThread.modelSelection.provider, - ) ?? null - ); - }, [props.serverConfig, props.selectedThread.modelSelection.provider]); - const composerMenuItems: ComposerCommandItem[] = useMemo(() => { if (!composerTrigger) return []; @@ -446,14 +443,14 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer title: group.providerLabel, subtitle: group.models.find( (model) => - model.selection.provider === currentModelSelection.provider && + model.selection.instanceId === currentModelSelection.instanceId && model.selection.model === currentModelSelection.model, )?.label, subactions: group.models.map((option) => ({ id: `model:${option.key}`, title: option.label, state: - option.selection.provider === currentModelSelection.provider && + option.selection.instanceId === currentModelSelection.instanceId && option.selection.model === currentModelSelection.model ? ("on" as const) : undefined, @@ -560,11 +557,12 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer if (event.startsWith("options:effort:")) { const effort = event.slice("options:effort:".length); const updated: ModelSelection = - currentModelSelection.provider === "claudeAgent" - ? { - ...currentModelSelection, - options: { ...currentModelSelection.options, effort: effort as typeof currentEffort }, - } + selectedProviderDriver === "claudeAgent" + ? withModelSelectionOption( + currentModelSelection, + "effort", + effort as typeof currentEffort, + ) : currentModelSelection; void props.onUpdateModelSelection(updated); return; @@ -572,24 +570,18 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer if (event.startsWith("options:fast-mode:")) { const fastMode = event.endsWith(":on"); const nextFast = fastMode || undefined; - if (currentModelSelection.provider === "opencode") { + if (selectedProviderDriver === "opencode") { return; } - const updated: ModelSelection = { - ...currentModelSelection, - options: { ...currentModelSelection.options, fastMode: nextFast }, - }; + const updated = withModelSelectionOption(currentModelSelection, "fastMode", nextFast); void props.onUpdateModelSelection(updated); return; } if (event.startsWith("options:context-window:")) { const contextWindow = event.slice("options:context-window:".length); const updated: ModelSelection = - currentModelSelection.provider === "claudeAgent" - ? { - ...currentModelSelection, - options: { ...currentModelSelection.options, contextWindow }, - } + selectedProviderDriver === "claudeAgent" + ? withModelSelectionOption(currentModelSelection, "contextWindow", contextWindow) : currentModelSelection; void props.onUpdateModelSelection(updated); return; diff --git a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx index 4fd89c23df..d41d6500d8 100644 --- a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx +++ b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx @@ -201,7 +201,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread const { onOpenDrawer, onRefresh } = props; const insets = useSafeAreaInsets(); - const agentLabel = `${props.selectedThread.modelSelection.provider} agent`; + const agentLabel = `${props.selectedThread.modelSelection.instanceId} agent`; const composerBottomInset = Math.max(insets.bottom, 12); const [composerExpanded, setComposerExpanded] = useState(false); const composerChrome = composerExpanded ? COMPOSER_EXPANDED_CHROME : COMPOSER_COLLAPSED_CHROME; diff --git a/apps/mobile/src/features/threads/ThreadGitControls.tsx b/apps/mobile/src/features/threads/ThreadGitControls.tsx index 860ac8d34e..500594f0ba 100644 --- a/apps/mobile/src/features/threads/ThreadGitControls.tsx +++ b/apps/mobile/src/features/threads/ThreadGitControls.tsx @@ -84,23 +84,23 @@ export function ThreadGitControls(props: { }>(); const { gitStatus, gitOperationLabel, onPull, onRunAction } = props; - const currentBranchLabel = gitStatus?.branch ?? props.currentBranch ?? "Detached HEAD"; + const currentBranchLabel = gitStatus?.refName ?? props.currentBranch ?? "Detached HEAD"; const busy = gitOperationLabel !== null; const isRepo = gitStatus?.isRepo ?? true; - const hasOriginRemote = gitStatus?.hasOriginRemote ?? false; - const isDefaultBranch = gitStatus?.isDefaultBranch ?? false; + const hasPrimaryRemote = gitStatus?.hasPrimaryRemote ?? false; + const isDefaultRef = gitStatus?.isDefaultRef ?? false; const quickAction = useMemo( () => isRepo - ? resolveQuickAction(gitStatus, busy, isDefaultBranch, hasOriginRemote) + ? resolveQuickAction(gitStatus, busy, isDefaultRef, hasPrimaryRemote) : { label: "Git unavailable", disabled: true, kind: "show_hint" as const, hint: "This workspace is not a git repository.", }, - [busy, gitStatus, hasOriginRemote, isDefaultBranch, isRepo], + [busy, gitStatus, hasPrimaryRemote, isDefaultRef, isRepo], ); const quickActionHint = quickAction.disabled @@ -143,12 +143,12 @@ export function ThreadGitControls(props: { input.action === "commit_push_pr" ? input.action : null; - const branchName = gitStatus?.branch; + const branchName = gitStatus?.refName; if ( branchName && confirmableAction && !input.featureBranch && - requiresDefaultBranchConfirmation(input.action, isDefaultBranch) + requiresDefaultBranchConfirmation(input.action, isDefaultRef) ) { router.push({ pathname: "/threads/[environmentId]/[threadId]/git-confirm", @@ -167,7 +167,7 @@ export function ThreadGitControls(props: { await onRunAction(input); }, - [environmentId, gitStatus, isDefaultBranch, onRunAction, router, threadId], + [environmentId, gitStatus, isDefaultRef, onRunAction, router, threadId], ); const runQuickAction = useCallback(async () => { diff --git a/apps/mobile/src/features/threads/claudeEffortOptions.ts b/apps/mobile/src/features/threads/claudeEffortOptions.ts index 62f2e13efa..58a4032b0b 100644 --- a/apps/mobile/src/features/threads/claudeEffortOptions.ts +++ b/apps/mobile/src/features/threads/claudeEffortOptions.ts @@ -1,5 +1,3 @@ -import type { ClaudeAgentEffort } from "@t3tools/contracts"; - export const CLAUDE_AGENT_EFFORT_OPTIONS = [ "low", "medium", @@ -7,4 +5,6 @@ export const CLAUDE_AGENT_EFFORT_OPTIONS = [ "xhigh", "max", "ultrathink", -] as const satisfies readonly ClaudeAgentEffort[]; +] as const; + +export type ClaudeAgentEffort = (typeof CLAUDE_AGENT_EFFORT_OPTIONS)[number]; diff --git a/apps/mobile/src/features/threads/git/GitBranchesSheet.tsx b/apps/mobile/src/features/threads/git/GitBranchesSheet.tsx index 40eda92d0f..a6b29fbe43 100644 --- a/apps/mobile/src/features/threads/git/GitBranchesSheet.tsx +++ b/apps/mobile/src/features/threads/git/GitBranchesSheet.tsx @@ -32,7 +32,7 @@ export function GitBranchesSheet() { cwd: selectedThreadCwd, }); - const currentBranchLabel = gitStatus.data?.branch ?? selectedThread?.branch ?? "Detached HEAD"; + const currentBranchLabel = gitStatus.data?.refName ?? selectedThread?.branch ?? "Detached HEAD"; const currentWorktreePath = selectedThreadWorktreePath; const availableBranches = gitState.selectedThreadBranches; const branchesLoading = gitState.selectedThreadBranchesLoading; diff --git a/apps/mobile/src/features/threads/git/GitCommitSheet.tsx b/apps/mobile/src/features/threads/git/GitCommitSheet.tsx index df163d3a7d..478e264203 100644 --- a/apps/mobile/src/features/threads/git/GitCommitSheet.tsx +++ b/apps/mobile/src/features/threads/git/GitCommitSheet.tsx @@ -33,7 +33,7 @@ export function GitCommitSheet() { }); const busy = gitState.gitOperationLabel !== null; - const isDefaultBranch = gitStatus.data?.isDefaultBranch ?? false; + const isDefaultRef = gitStatus.data?.isDefaultRef ?? false; const allFiles = gitStatus.data?.workingTree?.files ?? []; const [dialogCommitMessage, setDialogCommitMessage] = useState(""); @@ -76,10 +76,10 @@ export function GitCommitSheet() { Branch - {gitStatus.data?.branch ?? "(detached HEAD)"} + {gitStatus.data?.refName ?? "(detached HEAD)"} - {isDefaultBranch ? ( + {isDefaultRef ? ( (isRepo ? buildMenuItems(gitStatus.data, busy, hasOriginRemote) : []), - [busy, gitStatus.data, hasOriginRemote, isRepo], + () => (isRepo ? buildMenuItems(gitStatus.data, busy, hasPrimaryRemote) : []), + [busy, gitStatus.data, hasPrimaryRemote, isRepo], ); const sheetMenuItems = useMemo( @@ -62,10 +62,10 @@ export function GitOverviewSheet() { item, gitStatus: gitStatus.data, isBusy: busy, - hasOriginRemote, + hasOriginRemote: hasPrimaryRemote, }), })), - [busy, gitStatus.data, hasOriginRemote, menuItems], + [busy, gitStatus.data, hasPrimaryRemote, menuItems], ); useEffect(() => { @@ -97,12 +97,12 @@ export function GitOverviewSheet() { input.action === "commit_push_pr" ? input.action : null; - const branchName = gitStatus.data?.branch; + const branchName = gitStatus.data?.refName; if ( branchName && confirmableAction && !input.featureBranch && - requiresDefaultBranchConfirmation(input.action, isDefaultBranch) + requiresDefaultBranchConfirmation(input.action, isDefaultRef) ) { router.push({ pathname: "/threads/[environmentId]/[threadId]/git-confirm", @@ -122,7 +122,7 @@ export function GitOverviewSheet() { router.dismiss(); await gitActions.onRunSelectedThreadGitAction(input); }, - [environmentId, gitActions, gitStatus.data, isDefaultBranch, router, threadId], + [environmentId, gitActions, gitStatus.data, isDefaultRef, router, threadId], ); const onPressMenuItem = useCallback( diff --git a/apps/mobile/src/lib/modelOptions.ts b/apps/mobile/src/lib/modelOptions.ts index 7497b7147e..778e5bfb5b 100644 --- a/apps/mobile/src/lib/modelOptions.ts +++ b/apps/mobile/src/lib/modelOptions.ts @@ -6,6 +6,7 @@ export type ModelOption = { readonly subtitle: string; readonly providerKey: string; readonly providerLabel: string; + readonly providerDriver: string; readonly selection: ModelSelection; }; @@ -15,10 +16,15 @@ export type ProviderGroup = { readonly models: ReadonlyArray; }; -function providerDisplayLabel(provider: string): string { - if (provider === "codex") return "Codex"; - if (provider === "claudeAgent") return "Claude"; - return provider; +function providerDisplayLabel(provider: { + readonly displayName?: string | undefined; + readonly driver: string; + readonly instanceId: string; +}): string { + if (provider.displayName) return provider.displayName; + if (provider.driver === "codex") return "Codex"; + if (provider.driver === "claudeAgent") return "Claude"; + return provider.instanceId; } export function buildModelOptions( @@ -32,17 +38,18 @@ export function buildModelOptions( continue; } - const providerLabel = providerDisplayLabel(provider.provider); + const providerLabel = providerDisplayLabel(provider); for (const model of provider.models) { - const key = `${provider.provider}:${model.slug}`; + const key = `${provider.instanceId}:${model.slug}`; options.set(key, { key, label: model.name, subtitle: providerLabel, - providerKey: provider.provider, + providerKey: provider.instanceId, providerLabel, + providerDriver: provider.driver, selection: { - provider: provider.provider, + instanceId: provider.instanceId, model: model.slug, }, }); @@ -50,15 +57,16 @@ export function buildModelOptions( } if (fallbackModelSelection) { - const key = `${fallbackModelSelection.provider}:${fallbackModelSelection.model}`; + const key = `${fallbackModelSelection.instanceId}:${fallbackModelSelection.model}`; if (!options.has(key)) { - const providerLabel = providerDisplayLabel(fallbackModelSelection.provider); + const providerLabel = fallbackModelSelection.instanceId; options.set(key, { key, label: fallbackModelSelection.model, subtitle: providerLabel, - providerKey: fallbackModelSelection.provider, + providerKey: fallbackModelSelection.instanceId, providerLabel, + providerDriver: fallbackModelSelection.instanceId, selection: fallbackModelSelection, }); } diff --git a/apps/mobile/src/lib/repositoryGroups.test.ts b/apps/mobile/src/lib/repositoryGroups.test.ts index 088ce3b1a5..ddc9a5e8ac 100644 --- a/apps/mobile/src/lib/repositoryGroups.test.ts +++ b/apps/mobile/src/lib/repositoryGroups.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from "vitest"; -import { EnvironmentId, ProjectId, ThreadId } from "@t3tools/contracts"; +import { EnvironmentId, ProjectId, ProviderInstanceId, ThreadId } from "@t3tools/contracts"; import { groupProjectsByRepository } from "./repositoryGroups"; import { @@ -84,7 +84,7 @@ describe("groupProjectsByRepository", () => { id: ThreadId.make("thread-2"), projectId: ProjectId.make("project-staging"), title: "Fix reconnect flow", - modelSelection: { provider: "codex", model: "gpt-5.4" }, + modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" }, updatedAt: "2026-04-02T12:00:00.000Z", }), makeThread({ @@ -92,7 +92,7 @@ describe("groupProjectsByRepository", () => { id: ThreadId.make("thread-1"), projectId: ProjectId.make("project-local"), title: "Polish mobile shell", - modelSelection: { provider: "codex", model: "gpt-5.4" }, + modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" }, updatedAt: "2026-04-03T12:00:00.000Z", }), ]; diff --git a/apps/mobile/src/lib/threadActivity.test.ts b/apps/mobile/src/lib/threadActivity.test.ts index bc235c2ed7..70f6736e85 100644 --- a/apps/mobile/src/lib/threadActivity.test.ts +++ b/apps/mobile/src/lib/threadActivity.test.ts @@ -3,6 +3,7 @@ import { describe, expect, it } from "vitest"; import { EventId, ProjectId, + ProviderInstanceId, ThreadId, TurnId, type OrchestrationThread, @@ -27,7 +28,7 @@ function makeThread( input: Partial & Pick, ): OrchestrationThread { return { - modelSelection: { provider: "codex", model: "gpt-5.4" }, + modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" }, runtimeMode: "full-access", interactionMode: "default", branch: null, diff --git a/apps/mobile/src/state/use-selected-thread-git-state.ts b/apps/mobile/src/state/use-selected-thread-git-state.ts index ae0fb1d7b6..6c855a3ebf 100644 --- a/apps/mobile/src/state/use-selected-thread-git-state.ts +++ b/apps/mobile/src/state/use-selected-thread-git-state.ts @@ -33,10 +33,10 @@ export function useSelectedThreadGitState() { const selectedThreadBranchState = useVcsRefs(selectedThreadBranchTarget); const selectedThreadBranches = useMemo( () => - dedupeRemoteBranchesWithLocalMatches(selectedThreadBranchState.data?.branches ?? []).filter( + dedupeRemoteBranchesWithLocalMatches(selectedThreadBranchState.data?.refs ?? []).filter( (branch) => !branch.isRemote, ), - [selectedThreadBranchState.data?.branches], + [selectedThreadBranchState.data?.refs], ); return { diff --git a/apps/mobile/src/state/use-vcs-refs.ts b/apps/mobile/src/state/use-vcs-refs.ts index 5067fc7fc4..3af3a6e945 100644 --- a/apps/mobile/src/state/use-vcs-refs.ts +++ b/apps/mobile/src/state/use-vcs-refs.ts @@ -23,7 +23,7 @@ export const vcsRefManager = createVcsRefManager({ getRegistry: () => appAtomRegistry, getClient: (environmentId) => { const client = getEnvironmentClient(environmentId); - return client ? client.git : null; + return client ? client.vcs : null; }, subscribeClientChanges: subscribeEnvironmentConnections, watchLimit: VCS_REF_LIST_LIMIT, diff --git a/apps/mobile/src/state/use-vcs-status.ts b/apps/mobile/src/state/use-vcs-status.ts index 2e8b12a0d1..e7d7049d33 100644 --- a/apps/mobile/src/state/use-vcs-status.ts +++ b/apps/mobile/src/state/use-vcs-status.ts @@ -32,7 +32,7 @@ export const vcsStatusManager = createVcsStatusManager({ getRegistry: () => appAtomRegistry, getClient: (environmentId) => { const client = getEnvironmentClient(environmentId); - return client ? client.git : null; + return client ? client.vcs : null; }, getClientIdentity: (environmentId) => { return getEnvironmentClient(environmentId) ? environmentId : null; diff --git a/apps/server/src/review/ReviewService.test.ts b/apps/server/src/review/ReviewService.test.ts index ae1df4d55d..eb8758b128 100644 --- a/apps/server/src/review/ReviewService.test.ts +++ b/apps/server/src/review/ReviewService.test.ts @@ -1,9 +1,8 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, describe, it } from "@effect/vitest"; -import fs from "node:fs"; -import os from "node:os"; -import path from "node:path"; -import { Effect, Layer } from "effect"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Layer from "effect/Layer"; import { ServerConfig } from "../config.ts"; import * as GitVcsDriver from "../vcs/GitVcsDriver.ts"; @@ -36,9 +35,10 @@ function makeLayer(input: { describe("ReviewService", () => { it.effect("rejects diff preview cwd outside the configured workspace roots", () => Effect.gen(function* () { - const workspaceRoot = fs.mkdtempSync(path.join(os.tmpdir(), "t3-review-workspace-")); - const outsideRoot = fs.mkdtempSync(path.join(os.tmpdir(), "t3-review-outside-")); - const baseDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-review-base-")); + const fs = yield* FileSystem.FileSystem; + const workspaceRoot = yield* fs.makeTempDirectoryScoped({ prefix: "t3-review-workspace-" }); + const outsideRoot = yield* fs.makeTempDirectoryScoped({ prefix: "t3-review-outside-" }); + const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-review-base-" }); const detectCalls: Array<{ readonly cwd: string }> = []; const error = yield* Effect.gen(function* () { @@ -53,13 +53,14 @@ describe("ReviewService", () => { /must stay within the configured workspace root/, ); assert.deepStrictEqual(detectCalls, []); - }), + }).pipe(Effect.provide(NodeServices.layer)), ); it.effect("allows diff preview cwd inside the configured workspace root", () => Effect.gen(function* () { - const workspaceRoot = fs.mkdtempSync(path.join(os.tmpdir(), "t3-review-workspace-")); - const baseDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-review-base-")); + const fs = yield* FileSystem.FileSystem; + const workspaceRoot = yield* fs.makeTempDirectoryScoped({ prefix: "t3-review-workspace-" }); + const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-review-base-" }); const detectCalls: Array<{ readonly cwd: string }> = []; const result = yield* Effect.gen(function* () { @@ -70,6 +71,6 @@ describe("ReviewService", () => { assert.strictEqual(result.cwd, workspaceRoot); assert.deepStrictEqual(result.sources, []); assert.deepStrictEqual(detectCalls, [{ cwd: workspaceRoot }]); - }), + }).pipe(Effect.provide(NodeServices.layer)), ); }); diff --git a/apps/server/src/review/ReviewService.ts b/apps/server/src/review/ReviewService.ts index 0853f76000..ddbad606e9 100644 --- a/apps/server/src/review/ReviewService.ts +++ b/apps/server/src/review/ReviewService.ts @@ -1,4 +1,9 @@ -import { Context, DateTime, Effect, FileSystem, Layer, Path } from "effect"; +import * as Context from "effect/Context"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Layer from "effect/Layer"; +import * as Path from "effect/Path"; import { VcsRepositoryDetectionError, diff --git a/apps/server/src/terminal/Layers/Manager.test.ts b/apps/server/src/terminal/Layers/Manager.test.ts index 3c373d4597..56de7c56d5 100644 --- a/apps/server/src/terminal/Layers/Manager.test.ts +++ b/apps/server/src/terminal/Layers/Manager.test.ts @@ -586,6 +586,7 @@ it.layer( it.effect("restarts a running session when open is called with a different cwd", () => Effect.gen(function* () { const { manager, ptyAdapter, logsDir, baseDir } = yield* createManager(); + const path = yield* Path.Path; const originalCwd = path.join(baseDir, "original"); const differentCwd = path.join(baseDir, "different"); yield* makeDirectory(originalCwd); @@ -597,7 +598,8 @@ it.layer( if (!firstProcess) return; firstProcess.emitData("before reopen\n"); - yield* waitFor(pathExists(historyLogPath(logsDir))); + const logPath = yield* historyLogPath(logsDir); + yield* waitFor(pathExists(logPath)); const reopened = yield* manager.open(openInput({ cwd: differentCwd })); @@ -605,7 +607,7 @@ it.layer( assert.equal(firstProcess.killed, true); assert.equal(reopened.cwd, differentCwd); assert.equal(reopened.history, ""); - yield* waitFor(Effect.map(readFileString(historyLogPath(logsDir)), (text) => text === "")); + yield* waitFor(Effect.map(readFileString(logPath), (text) => text === "")); }), ); diff --git a/apps/server/src/terminal/Layers/Manager.ts b/apps/server/src/terminal/Layers/Manager.ts index 97181c30a5..d511cd585f 100644 --- a/apps/server/src/terminal/Layers/Manager.ts +++ b/apps/server/src/terminal/Layers/Manager.ts @@ -11,7 +11,6 @@ import { } from "@t3tools/contracts"; import { makeKeyedCoalescingWorker } from "@t3tools/shared/KeyedCoalescingWorker"; import { getTerminalLabel } from "@t3tools/shared/terminalLabels"; -import NodePath from "node:path"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as Encoding from "effect/Encoding"; @@ -181,8 +180,8 @@ function normalizeChildCommandName(raw: string, platform: NodeJS.Platform): stri } const firstToken = (trimmed.split(/\s+/)[0] ?? trimmed).trim(); if (firstToken.length === 0) return null; - const base = - platform === "win32" ? NodePath.win32.basename(firstToken) : NodePath.basename(firstToken); + const separators = platform === "win32" ? /[\\/]/ : /\//; + const base = firstToken.split(separators).at(-1) ?? firstToken; const withoutExe = platform === "win32" && base.toLowerCase().endsWith(".exe") ? base.slice(0, -4) : base; return withoutExe.length > 0 ? withoutExe : null; @@ -280,7 +279,7 @@ function advanceEventSequence(session: TerminalSessionState): { readonly updatedAt: string; readonly sequence: number; } { - const updatedAt = new Date().toISOString(); + const updatedAt = DateTime.formatIso(DateTime.nowUnsafe()); session.eventSequence += 1; session.updatedAt = updatedAt; return { updatedAt, sequence: session.eventSequence }; @@ -671,9 +670,7 @@ const posixInspectSubprocess = Effect.fn("terminal.posixInspectSubprocess")(func }; }); -function defaultSubprocessInspectorForPlatform( - platform: NodeJS.Platform, -): TerminalSubprocessInspector { +function defaultSubprocessInspectorForPlatform(platform: NodeJS.Platform) { return Effect.fn("terminal.defaultSubprocessInspector")(function* (terminalPid: number) { if (!Number.isInteger(terminalPid) || terminalPid <= 0) { return { hasRunningSubprocess: false, childCommand: null }; @@ -1403,7 +1400,6 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith expectedPid: number, ) { while (true) { - const updatedAt = yield* nowIso; const action: DrainProcessEventAction = yield* Effect.sync(() => { if (session.pid !== expectedPid || !session.process || session.status !== "running") { session.pendingProcessEvents = []; @@ -1489,7 +1485,6 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith yield* queuePersist(action.threadId, action.terminalId, action.history); } - const createdAt = yield* nowIso; yield* publishEvent({ type: "output", threadId: action.threadId, @@ -1501,7 +1496,6 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith } yield* clearKillFiber(action.process); - const createdAt = yield* nowIso; yield* publishEvent({ type: "exited", threadId: action.threadId, @@ -1671,7 +1665,6 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith return [undefined, state] as const; }); - const createdAt = yield* nowIso; yield* publishEvent({ type: eventType, threadId: session.threadId, @@ -1693,7 +1686,6 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith if (ptyProcess) { yield* startKillEscalation(ptyProcess, session.threadId, session.terminalId); } - const erroredAt = yield* nowIso; yield* modifyManagerState((state) => { session.status = "error"; @@ -1713,7 +1705,6 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith yield* evictInactiveSessionsIfNeeded(); const message = error.message; - const createdAt = yield* nowIso; yield* publishEvent({ type: "error", threadId: session.threadId, @@ -1916,7 +1907,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith processEventDrainRunning: false, exitCode: null, exitSignal: null, - updatedAt: new Date().toISOString(), + updatedAt: yield* nowIso, eventSequence: 0, cols, rows, @@ -2007,7 +1998,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith if (liveSession.cols !== targetCols || liveSession.rows !== targetRows) { liveSession.cols = targetCols; liveSession.rows = targetRows; - liveSession.updatedAt = new Date().toISOString(); + liveSession.updatedAt = yield* nowIso; liveSession.process.resize(targetCols, targetRows); } @@ -2058,7 +2049,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith ) { session.cols = targetCols; session.rows = targetRows; - session.updatedAt = new Date().toISOString(); + session.updatedAt = yield* nowIso; yield* Effect.sync(() => session.process?.resize(targetCols, targetRows)); } @@ -2272,7 +2263,6 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith Effect.gen(function* () { const terminalId = input.terminalId; const session = yield* requireSession(input.threadId, terminalId); - const updatedAt = yield* nowIso; session.history = ""; session.pendingHistoryControlSequence = ""; session.pendingProcessEvents = []; @@ -2280,7 +2270,6 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith session.processEventDrainRunning = false; const eventStamp = advanceEventSequence(session); yield* persistHistory(input.threadId, terminalId, session.history); - const createdAt = yield* nowIso; yield* publishEvent({ type: "cleared", threadId: input.threadId, @@ -2304,7 +2293,6 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith if (Option.isNone(existingSession)) { const cols = input.cols ?? DEFAULT_OPEN_COLS; const rows = input.rows ?? DEFAULT_OPEN_ROWS; - const createdAt = yield* nowIso; session = { threadId: input.threadId, terminalId, @@ -2319,7 +2307,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith processEventDrainRunning: false, exitCode: null, exitSignal: null, - updatedAt: new Date().toISOString(), + updatedAt: yield* nowIso, eventSequence: 0, cols, rows, diff --git a/apps/server/src/vcs/GitVcsDriverCore.ts b/apps/server/src/vcs/GitVcsDriverCore.ts index 2a2b277e1d..7ede5c3bb0 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.ts @@ -1669,7 +1669,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* ["ls-files", "--others", "--exclude-standard", "-z"], { maxOutputBytes: WORKSPACE_FILES_MAX_OUTPUT_BYTES, - truncateOutputAtMaxBytes: true, + appendTruncationMarker: true, }, ); const untrackedPaths = splitNullSeparatedGitStdoutPaths(untrackedResult); @@ -1687,7 +1687,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* { allowNonZeroExit: true, maxOutputBytes: REVIEW_UNTRACKED_DIFF_MAX_OUTPUT_BYTES, - truncateOutputAtMaxBytes: true, + appendTruncationMarker: true, }, ), { concurrency: 4 }, @@ -1728,7 +1728,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* ["diff", "--patch", "--minimal", "HEAD", "--"], { maxOutputBytes: REVIEW_DIFF_PATCH_MAX_OUTPUT_BYTES, - truncateOutputAtMaxBytes: true, + appendTruncationMarker: true, }, ).pipe( Effect.catch(() => @@ -1756,7 +1756,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* ["diff", "--patch", "--minimal", `${baseRef}...HEAD`], { maxOutputBytes: REVIEW_DIFF_PATCH_MAX_OUTPUT_BYTES, - truncateOutputAtMaxBytes: true, + appendTruncationMarker: true, }, ).pipe( Effect.catch(() => diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 7185a082ab..e964058c69 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -106,7 +106,7 @@ import { resolveShortcutCommand, shortcutLabelForCommand } from "../keybindings" import PlanSidebar from "./PlanSidebar"; import ThreadTerminalDrawer from "./ThreadTerminalDrawer"; import { ChevronDownIcon, TriangleAlertIcon, WifiOffIcon } from "lucide-react"; -import { cn, randomUUID } from "~/lib/utils"; +import { cn } from "~/lib/utils"; import { stackedThreadToast, toastManager } from "./ui/toast"; import { decodeProjectScriptKeybindingRule } from "~/lib/projectScriptKeybindings"; import { type NewProjectScriptInput } from "./ProjectScriptsControl"; diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index e584f9adea..f3f163b017 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -343,7 +343,6 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP const threadKey = scopedThreadKey(threadRef); const lastVisitedAt = useUiStateStore((state) => state.threadLastVisitedAtById[threadKey]); const isSelected = useThreadSelectionStore((state) => state.selectedThreadKeys.has(threadKey)); - const hasSelection = useThreadSelectionStore((state) => state.selectedThreadKeys.size > 0); const runningTerminalIds = useThreadRunningTerminalIds({ environmentId: thread.environmentId, threadId: thread.id, @@ -1984,7 +1983,6 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec void; - readonly applyTerminalEvent: (event: TerminalEvent, environmentId: EnvironmentId) => void; + readonly applyTerminalEvent?: (event: TerminalEvent, environmentId: EnvironmentId) => void; } interface EnvironmentConnectionInput extends OrchestrationHandlers { @@ -145,7 +145,7 @@ export function createEnvironmentConnection( const unsubTerminalEvent = input.client.terminal.onEvent( (event: Parameters[0]>[0]) => { - input.applyTerminalEvent(event, environmentId); + input.applyTerminalEvent?.(event, environmentId); }, ); diff --git a/apps/web/src/environments/runtime/service.threadSubscriptions.test.ts b/apps/web/src/environments/runtime/service.threadSubscriptions.test.ts index 414ec8f7eb..74a36b0356 100644 --- a/apps/web/src/environments/runtime/service.threadSubscriptions.test.ts +++ b/apps/web/src/environments/runtime/service.threadSubscriptions.test.ts @@ -81,10 +81,12 @@ vi.mock("@t3tools/client-runtime", async (importOriginal) => { const stubWsClient: WsRpcClient = { dispose: async () => undefined, reconnect: async () => undefined, + isHeartbeatFresh: () => false, orchestration: { dispatchCommand: vi.fn(), getTurnDiff: vi.fn(), getFullThreadDiff: vi.fn(), + getArchivedShellSnapshot: vi.fn(), subscribeShell: vi.fn(() => () => undefined), subscribeThread: mockSubscribeThread, }, @@ -96,6 +98,7 @@ vi.mock("@t3tools/client-runtime", async (importOriginal) => { clear: vi.fn(), restart: vi.fn(), close: vi.fn(), + onEvent: vi.fn(() => () => undefined), onMetadata: vi.fn(() => () => undefined), }, projects: { @@ -105,20 +108,27 @@ vi.mock("@t3tools/client-runtime", async (importOriginal) => { filesystem: { browse: vi.fn(), }, + sourceControl: { + lookupRepository: vi.fn(), + cloneRepository: vi.fn(), + publishRepository: vi.fn(), + }, shell: { openInEditor: vi.fn(), }, - git: { + vcs: { pull: vi.fn(), refreshStatus: vi.fn(), onStatus: vi.fn(() => () => undefined), - runStackedAction: vi.fn(), - listBranches: vi.fn(), + listRefs: vi.fn(), createWorktree: vi.fn(), removeWorktree: vi.fn(), - createBranch: vi.fn(), - checkout: vi.fn(), + createRef: vi.fn(), + switchRef: vi.fn(), init: vi.fn(), + }, + git: { + runStackedAction: vi.fn(), resolvePullRequest: vi.fn(), preparePullRequestThread: vi.fn(), }, @@ -128,12 +138,19 @@ vi.mock("@t3tools/client-runtime", async (importOriginal) => { server: { getConfig: vi.fn(), refreshProviders: vi.fn(), + discoverSourceControl: vi.fn(), + updateProvider: vi.fn(), upsertKeybinding: vi.fn(), + removeKeybinding: vi.fn(), getSettings: vi.fn(), updateSettings: vi.fn(), subscribeConfig: vi.fn(() => () => undefined), subscribeLifecycle: vi.fn(() => () => undefined), subscribeAuthAccess: vi.fn(() => () => undefined), + getTraceDiagnostics: vi.fn(), + getProcessDiagnostics: vi.fn(), + getProcessResourceHistory: vi.fn(), + signalProcess: vi.fn(), }, }; return { diff --git a/apps/web/src/environments/runtime/service.ts b/apps/web/src/environments/runtime/service.ts index 681ad3cd56..de8bc76041 100644 --- a/apps/web/src/environments/runtime/service.ts +++ b/apps/web/src/environments/runtime/service.ts @@ -9,7 +9,10 @@ import { type ServerConfig, ThreadId, } from "@t3tools/contracts"; -import { createWsRpcClient as createBaseWsRpcClient, type WsRpcClient } from "@t3tools/client-runtime"; +import { + createWsRpcClient as createBaseWsRpcClient, + type WsRpcClient, +} from "@t3tools/client-runtime"; import { type QueryClient } from "@tanstack/react-query"; import { Throttler } from "@tanstack/react-pacer"; diff --git a/apps/web/src/rpc/wsTransport.test.ts b/apps/web/src/rpc/wsTransport.test.ts index 7ee6a5e351..bbf178b29d 100644 --- a/apps/web/src/rpc/wsTransport.test.ts +++ b/apps/web/src/rpc/wsTransport.test.ts @@ -1,4 +1,5 @@ -import { DEFAULT_SERVER_SETTINGS, WS_METHODS } from "@t3tools/contracts"; +import { DEFAULT_SERVER_SETTINGS, ServerSettings, WS_METHODS } from "@t3tools/contracts"; +import * as Schema from "effect/Schema"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { diff --git a/packages/client-runtime/src/gitActions.ts b/packages/client-runtime/src/gitActions.ts index e6f3a15000..436db17110 100644 --- a/packages/client-runtime/src/gitActions.ts +++ b/packages/client-runtime/src/gitActions.ts @@ -2,7 +2,7 @@ import type { GitRunStackedActionInput, GitRunStackedActionResult, GitStackedAction, - GitStatusResult, + VcsStatusResult, } from "@t3tools/contracts"; import { isTemporaryWorktreeBranch } from "@t3tools/shared/git"; @@ -83,13 +83,13 @@ export function buildGitActionProgressStages(input: { } export function buildMenuItems( - gitStatus: GitStatusResult | null, + gitStatus: VcsStatusResult | null, isBusy: boolean, hasOriginRemote = true, ): GitActionMenuItem[] { if (!gitStatus) return []; - const hasBranch = gitStatus.branch !== null; + const hasBranch = gitStatus.refName !== null; const hasChanges = gitStatus.hasWorkingTreeChanges; const hasOpenPr = gitStatus.pr?.state === "open"; const isBehind = gitStatus.behindCount > 0; @@ -149,7 +149,7 @@ export function buildMenuItems( } export function resolveQuickAction( - gitStatus: GitStatusResult | null, + gitStatus: VcsStatusResult | null, isBusy: boolean, isDefaultBranch = false, hasOriginRemote = true, @@ -167,7 +167,7 @@ export function resolveQuickAction( }; } - const hasBranch = gitStatus.branch !== null; + const hasBranch = gitStatus.refName !== null; const hasChanges = gitStatus.hasWorkingTreeChanges; const hasOpenPr = gitStatus.pr?.state === "open"; const isAhead = gitStatus.aheadCount > 0; @@ -285,7 +285,7 @@ export function resolveQuickAction( export function getGitActionDisabledReason(input: { item: GitActionMenuItem; - gitStatus: GitStatusResult | null; + gitStatus: VcsStatusResult | null; isBusy: boolean; hasOriginRemote: boolean; }): string | null { @@ -294,7 +294,7 @@ export function getGitActionDisabledReason(input: { if (isBusy) return "Git action in progress."; if (!gitStatus) return "Git status is unavailable."; - const hasBranch = gitStatus.branch !== null; + const hasBranch = gitStatus.refName !== null; const hasChanges = gitStatus.hasWorkingTreeChanges; const hasOpenPr = gitStatus.pr?.state === "open"; const isAhead = gitStatus.aheadCount > 0; @@ -411,30 +411,30 @@ export function resolveThreadBranchUpdate( export function resolveLiveThreadBranchUpdate(input: { threadBranch: string | null; - gitStatus: GitStatusResult | null; + gitStatus: VcsStatusResult | null; }): { branch: string | null } | null { if (!input.gitStatus) { return null; } - if (input.gitStatus.branch === null && input.threadBranch !== null) { + if (input.gitStatus.refName === null && input.threadBranch !== null) { return null; } - if (input.threadBranch === input.gitStatus.branch) { + if (input.threadBranch === input.gitStatus.refName) { return null; } if ( input.threadBranch !== null && - input.gitStatus.branch !== null && + input.gitStatus.refName !== null && !isTemporaryWorktreeBranch(input.threadBranch) && - isTemporaryWorktreeBranch(input.gitStatus.branch) + isTemporaryWorktreeBranch(input.gitStatus.refName) ) { return null; } return { - branch: input.gitStatus.branch, + branch: input.gitStatus.refName, }; } diff --git a/packages/client-runtime/src/shellSnapshotReducer.test.ts b/packages/client-runtime/src/shellSnapshotReducer.test.ts index c3b2188b15..052245d415 100644 --- a/packages/client-runtime/src/shellSnapshotReducer.test.ts +++ b/packages/client-runtime/src/shellSnapshotReducer.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from "vitest"; -import { ProjectId, ThreadId } from "@t3tools/contracts"; +import { ProjectId, ProviderInstanceId, ThreadId } from "@t3tools/contracts"; import type { OrchestrationShellSnapshot, OrchestrationShellStreamEvent } from "@t3tools/contracts"; import { applyShellStreamEvent } from "./shellSnapshotReducer.ts"; @@ -27,7 +27,7 @@ const stubThread = { id: ThreadId.make("thread-1"), projectId: ProjectId.make("project-1"), title: "Test Thread", - modelSelection: { provider: "codex", model: "gpt-5.4" }, + modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" }, runtimeMode: "full-access" as const, interactionMode: "default" as const, branch: null, diff --git a/packages/client-runtime/src/shellSnapshotState.test.ts b/packages/client-runtime/src/shellSnapshotState.test.ts index 65f23031fd..706536bfda 100644 --- a/packages/client-runtime/src/shellSnapshotState.test.ts +++ b/packages/client-runtime/src/shellSnapshotState.test.ts @@ -4,6 +4,7 @@ import { afterEach, describe, expect, it } from "vitest"; import { EnvironmentId, ProjectId, + ProviderInstanceId, ThreadId, type OrchestrationShellSnapshot, } from "@t3tools/contracts"; @@ -37,7 +38,7 @@ const BASE_SNAPSHOT: OrchestrationShellSnapshot = { id: ThreadId.make("thread-1"), projectId: ProjectId.make("project-1"), title: "Thread", - modelSelection: { provider: "codex", model: "gpt-5.4" }, + modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" }, runtimeMode: "full-access", interactionMode: "default", branch: null, diff --git a/packages/client-runtime/src/sourceControlDiscoveryState.test.ts b/packages/client-runtime/src/sourceControlDiscoveryState.test.ts index 0a81e9ec07..82d0d9a2ee 100644 --- a/packages/client-runtime/src/sourceControlDiscoveryState.test.ts +++ b/packages/client-runtime/src/sourceControlDiscoveryState.test.ts @@ -29,7 +29,6 @@ const GITHUB_RESULT: SourceControlDiscoveryResult = { { kind: "github", label: "GitHub", - implemented: true, status: "available", version: Option.some("2.85.0"), installHint: "Install GitHub CLI.", diff --git a/packages/client-runtime/src/threadDetailReducer.test.ts b/packages/client-runtime/src/threadDetailReducer.test.ts index 6770b697c6..e8014ebd6a 100644 --- a/packages/client-runtime/src/threadDetailReducer.test.ts +++ b/packages/client-runtime/src/threadDetailReducer.test.ts @@ -2,14 +2,14 @@ import { describe, expect, it } from "vitest"; import { CheckpointRef, - CommandId, EventId, MessageId, ProjectId, + ProviderInstanceId, ThreadId, TurnId, } from "@t3tools/contracts"; -import type { OrchestrationEvent, OrchestrationThread } from "@t3tools/contracts"; +import type { OrchestrationThread } from "@t3tools/contracts"; import { applyThreadDetailEvent } from "./threadDetailReducer.ts"; @@ -25,7 +25,7 @@ const baseThread: OrchestrationThread = { id: ThreadId.make("thread-1"), projectId: ProjectId.make("project-1"), title: "Test Thread", - modelSelection: { provider: "codex", model: "gpt-5.4" }, + modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" }, runtimeMode: "full-access", interactionMode: "default", branch: null, @@ -81,7 +81,7 @@ describe("applyThreadDetailEvent", () => { threadId: ThreadId.make("thread-2"), projectId: ProjectId.make("project-1"), title: "New Thread", - modelSelection: { provider: "codex", model: "gpt-5.4" }, + modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" }, runtimeMode: "full-access", interactionMode: "default", branch: "main", diff --git a/packages/client-runtime/src/threadDetailState.test.ts b/packages/client-runtime/src/threadDetailState.test.ts index a331f98b71..9545e0729c 100644 --- a/packages/client-runtime/src/threadDetailState.test.ts +++ b/packages/client-runtime/src/threadDetailState.test.ts @@ -6,6 +6,7 @@ import { EnvironmentId, MessageId, ProjectId, + ProviderInstanceId, ThreadId, TurnId, type OrchestrationThread, @@ -40,7 +41,7 @@ const BASE_THREAD: OrchestrationThread = { id: ThreadId.make("thread-1"), projectId: ProjectId.make("project-1"), title: "Test Thread", - modelSelection: { provider: "codex", model: "gpt-5.4" }, + modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" }, runtimeMode: "full-access", interactionMode: "default", branch: null, diff --git a/packages/client-runtime/src/threadDetailState.ts b/packages/client-runtime/src/threadDetailState.ts index 86e5eeb5a1..d8c5cc4add 100644 --- a/packages/client-runtime/src/threadDetailState.ts +++ b/packages/client-runtime/src/threadDetailState.ts @@ -1,6 +1,10 @@ import { pipe } from "effect/Function"; import * as Order from "effect/Order"; import * as Arr from "effect/Array"; +import * as DateTime from "effect/DateTime"; +import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; import type { OrchestrationThread, OrchestrationThreadStreamItem, @@ -48,15 +52,16 @@ interface ThreadDetailEntry { retainCount: number; teardown: () => void; lastAccessedAt: number; - evictionTimeoutId: ReturnType | null; + evictionFiber: Fiber.Fiber | null; } const NOOP: () => void = () => undefined; +const nowMs = () => DateTime.toEpochMillis(DateTime.nowUnsafe()); function clearEntryEviction(entry: ThreadDetailEntry): void { - if (entry.evictionTimeoutId !== null) { - clearTimeout(entry.evictionTimeoutId); - entry.evictionTimeoutId = null; + if (entry.evictionFiber !== null) { + Effect.runFork(Fiber.interrupt(entry.evictionFiber)); + entry.evictionFiber = null; } } @@ -202,19 +207,25 @@ export function createThreadDetailManager(config: ThreadDetailManagerConfig) { return; } - entry.evictionTimeoutId = setTimeout(() => { - const current = entries.get(targetKey); - if (!current) { - return; - } + entry.evictionFiber = Effect.runFork( + Effect.sleep(Duration.millis(retention.idleTtlMs)).pipe( + Effect.andThen( + Effect.sync(() => { + const current = entries.get(targetKey); + if (!current) { + return; + } - current.evictionTimeoutId = null; - if (current.watcherCount > 0 || current.retainCount > 0 || shouldKeepWarm(current)) { - return; - } + current.evictionFiber = null; + if (current.watcherCount > 0 || current.retainCount > 0 || shouldKeepWarm(current)) { + return; + } - disposeEntry(targetKey); - }, retention.idleTtlMs); + disposeEntry(targetKey); + }), + ), + ), + ); } function reconcileRetention(targetKey: string): void { @@ -339,7 +350,7 @@ export function createThreadDetailManager(config: ThreadDetailManagerConfig) { const existing = entries.get(targetKey); if (existing) { clearEntryEviction(existing); - existing.lastAccessedAt = Date.now(); + existing.lastAccessedAt = nowMs(); if (kind === "watcher") { existing.watcherCount += 1; } else { @@ -371,8 +382,8 @@ export function createThreadDetailManager(config: ThreadDetailManagerConfig) { watcherCount: kind === "watcher" ? 1 : 0, retainCount: kind === "retain" ? 1 : 0, teardown, - lastAccessedAt: Date.now(), - evictionTimeoutId: null, + lastAccessedAt: nowMs(), + evictionFiber: null, }); evictIdleEntriesToCapacity(); return () => release(targetKey, kind); @@ -389,7 +400,7 @@ export function createThreadDetailManager(config: ThreadDetailManagerConfig) { } else { entry.retainCount = Math.max(0, entry.retainCount - 1); } - entry.lastAccessedAt = Date.now(); + entry.lastAccessedAt = nowMs(); reconcileRetention(targetKey); } diff --git a/packages/client-runtime/src/wsRpcClient.ts b/packages/client-runtime/src/wsRpcClient.ts index a043e2241a..ea3fb8074e 100644 --- a/packages/client-runtime/src/wsRpcClient.ts +++ b/packages/client-runtime/src/wsRpcClient.ts @@ -2,15 +2,16 @@ import { type GitActionProgressEvent, type GitRunStackedActionInput, type GitRunStackedActionResult, - type GitStatusResult, - type GitStatusStreamEvent, type LocalApi, ORCHESTRATION_WS_METHODS, type ServerSettingsPatch, + type VcsStatusResult, + type VcsStatusStreamEvent, WS_METHODS, } from "@t3tools/contracts"; import { applyGitStatusStreamEvent } from "@t3tools/shared/git"; -import { Effect, Stream } from "effect"; +import type * as Effect from "effect/Effect"; +import type * as Stream from "effect/Stream"; import { type WsRpcProtocolClient } from "./wsRpcProtocol.ts"; import { WsTransport } from "./wsTransport.ts"; @@ -64,6 +65,7 @@ interface GitRunStackedActionOptions { export interface WsRpcClient { readonly dispose: () => Promise; readonly reconnect: () => Promise; + readonly isHeartbeatFresh: () => boolean; readonly terminal: { readonly open: RpcUnaryMethod; readonly attach: RpcInputStreamMethod; @@ -72,6 +74,7 @@ export interface WsRpcClient { readonly clear: RpcUnaryMethod; readonly restart: RpcUnaryMethod; readonly close: RpcUnaryMethod; + readonly onEvent: RpcStreamMethod; readonly onMetadata: RpcStreamMethod; }; readonly projects: { @@ -81,30 +84,37 @@ export interface WsRpcClient { readonly filesystem: { readonly browse: RpcUnaryMethod; }; + readonly sourceControl: { + readonly lookupRepository: RpcUnaryMethod; + readonly cloneRepository: RpcUnaryMethod; + readonly publishRepository: RpcUnaryMethod; + }; readonly shell: { readonly openInEditor: (input: { readonly cwd: Parameters[0]; readonly editor: Parameters[1]; }) => ReturnType; }; - readonly git: { - readonly pull: RpcUnaryMethod; - readonly refreshStatus: RpcUnaryMethod; + readonly vcs: { + readonly pull: RpcUnaryMethod; + readonly refreshStatus: RpcUnaryMethod; readonly onStatus: ( - input: RpcInput, - listener: (status: GitStatusResult) => void, + input: RpcInput, + listener: (status: VcsStatusResult) => void, options?: StreamSubscriptionOptions, ) => () => void; + readonly listRefs: RpcUnaryMethod; + readonly createWorktree: RpcUnaryMethod; + readonly removeWorktree: RpcUnaryMethod; + readonly createRef: RpcUnaryMethod; + readonly switchRef: RpcUnaryMethod; + readonly init: RpcUnaryMethod; + }; + readonly git: { readonly runStackedAction: ( input: GitRunStackedActionInput, options?: GitRunStackedActionOptions, ) => Promise; - readonly listBranches: RpcUnaryMethod; - readonly createWorktree: RpcUnaryMethod; - readonly removeWorktree: RpcUnaryMethod; - readonly createBranch: RpcUnaryMethod; - readonly checkout: RpcUnaryMethod; - readonly init: RpcUnaryMethod; readonly resolvePullRequest: RpcUnaryMethod; readonly preparePullRequestThread: RpcUnaryMethod< typeof WS_METHODS.gitPreparePullRequestThread @@ -116,7 +126,12 @@ export interface WsRpcClient { readonly server: { readonly getConfig: RpcUnaryNoArgMethod; readonly refreshProviders: RpcUnaryNoArgMethod; + readonly discoverSourceControl: RpcUnaryNoArgMethod< + typeof WS_METHODS.serverDiscoverSourceControl + >; + readonly updateProvider: RpcUnaryMethod; readonly upsertKeybinding: RpcUnaryMethod; + readonly removeKeybinding: RpcUnaryMethod; readonly getSettings: RpcUnaryNoArgMethod; readonly updateSettings: ( patch: ServerSettingsPatch, @@ -124,11 +139,22 @@ export interface WsRpcClient { readonly subscribeConfig: RpcStreamMethod; readonly subscribeLifecycle: RpcStreamMethod; readonly subscribeAuthAccess: RpcStreamMethod; + readonly getTraceDiagnostics: RpcUnaryNoArgMethod; + readonly getProcessDiagnostics: RpcUnaryNoArgMethod< + typeof WS_METHODS.serverGetProcessDiagnostics + >; + readonly getProcessResourceHistory: RpcUnaryMethod< + typeof WS_METHODS.serverGetProcessResourceHistory + >; + readonly signalProcess: RpcUnaryMethod; }; readonly orchestration: { readonly dispatchCommand: RpcUnaryMethod; readonly getTurnDiff: RpcUnaryMethod; readonly getFullThreadDiff: RpcUnaryMethod; + readonly getArchivedShellSnapshot: RpcUnaryNoArgMethod< + typeof ORCHESTRATION_WS_METHODS.getArchivedShellSnapshot + >; readonly subscribeShell: RpcStreamMethod; readonly subscribeThread: RpcInputStreamMethod; }; @@ -145,6 +171,7 @@ export function createWsRpcClient( ): WsRpcClient { return { dispose: () => transport.dispose(), + isHeartbeatFresh: () => false, reconnect: async () => { options?.beforeReconnect?.(); await transport.reconnect(); @@ -162,6 +189,12 @@ export function createWsRpcClient( clear: (input) => transport.request((client) => client[WS_METHODS.terminalClear](input)), restart: (input) => transport.request((client) => client[WS_METHODS.terminalRestart](input)), close: (input) => transport.request((client) => client[WS_METHODS.terminalClose](input)), + onEvent: (listener, options) => + transport.subscribe( + (client) => client[WS_METHODS.subscribeTerminalEvents]({}), + listener, + subscriptionOptions(options, WS_METHODS.subscribeTerminalEvents), + ), onMetadata: (listener, options) => transport.subscribe( (client) => client[WS_METHODS.subscribeTerminalMetadata]({}), @@ -178,25 +211,43 @@ export function createWsRpcClient( filesystem: { browse: (input) => transport.request((client) => client[WS_METHODS.filesystemBrowse](input)), }, + sourceControl: { + lookupRepository: (input) => + transport.request((client) => client[WS_METHODS.sourceControlLookupRepository](input)), + cloneRepository: (input) => + transport.request((client) => client[WS_METHODS.sourceControlCloneRepository](input)), + publishRepository: (input) => + transport.request((client) => client[WS_METHODS.sourceControlPublishRepository](input)), + }, shell: { openInEditor: (input) => transport.request((client) => client[WS_METHODS.shellOpenInEditor](input)), }, - git: { - pull: (input) => transport.request((client) => client[WS_METHODS.gitPull](input)), + vcs: { + pull: (input) => transport.request((client) => client[WS_METHODS.vcsPull](input)), refreshStatus: (input) => - transport.request((client) => client[WS_METHODS.gitRefreshStatus](input)), + transport.request((client) => client[WS_METHODS.vcsRefreshStatus](input)), onStatus: (input, listener, options) => { - let current: GitStatusResult | null = null; + let current: VcsStatusResult | null = null; return transport.subscribe( - (client) => client[WS_METHODS.subscribeGitStatus](input), - (event: GitStatusStreamEvent) => { + (client) => client[WS_METHODS.subscribeVcsStatus](input), + (event: VcsStatusStreamEvent) => { current = applyGitStatusStreamEvent(current, event); listener(current); }, subscriptionOptions(options, WS_METHODS.subscribeVcsStatus), ); }, + listRefs: (input) => transport.request((client) => client[WS_METHODS.vcsListRefs](input)), + createWorktree: (input) => + transport.request((client) => client[WS_METHODS.vcsCreateWorktree](input)), + removeWorktree: (input) => + transport.request((client) => client[WS_METHODS.vcsRemoveWorktree](input)), + createRef: (input) => transport.request((client) => client[WS_METHODS.vcsCreateRef](input)), + switchRef: (input) => transport.request((client) => client[WS_METHODS.vcsSwitchRef](input)), + init: (input) => transport.request((client) => client[WS_METHODS.vcsInit](input)), + }, + git: { runStackedAction: async (input, options) => { let result: GitRunStackedActionResult | null = null; @@ -216,16 +267,6 @@ export function createWsRpcClient( throw new Error("Git action stream completed without a final result."); }, - listBranches: (input) => - transport.request((client) => client[WS_METHODS.gitListBranches](input)), - createWorktree: (input) => - transport.request((client) => client[WS_METHODS.gitCreateWorktree](input)), - removeWorktree: (input) => - transport.request((client) => client[WS_METHODS.gitRemoveWorktree](input)), - createBranch: (input) => - transport.request((client) => client[WS_METHODS.gitCreateBranch](input)), - checkout: (input) => transport.request((client) => client[WS_METHODS.gitCheckout](input)), - init: (input) => transport.request((client) => client[WS_METHODS.gitInit](input)), resolvePullRequest: (input) => transport.request((client) => client[WS_METHODS.gitResolvePullRequest](input)), preparePullRequestThread: (input) => @@ -239,8 +280,14 @@ export function createWsRpcClient( getConfig: () => transport.request((client) => client[WS_METHODS.serverGetConfig]({})), refreshProviders: () => transport.request((client) => client[WS_METHODS.serverRefreshProviders]({})), + discoverSourceControl: () => + transport.request((client) => client[WS_METHODS.serverDiscoverSourceControl]({})), + updateProvider: (input) => + transport.request((client) => client[WS_METHODS.serverUpdateProvider](input)), upsertKeybinding: (input) => transport.request((client) => client[WS_METHODS.serverUpsertKeybinding](input)), + removeKeybinding: (input) => + transport.request((client) => client[WS_METHODS.serverRemoveKeybinding](input)), getSettings: () => transport.request((client) => client[WS_METHODS.serverGetSettings]({})), updateSettings: (patch) => transport.request((client) => client[WS_METHODS.serverUpdateSettings]({ patch })), @@ -262,6 +309,14 @@ export function createWsRpcClient( listener, subscriptionOptions(options, WS_METHODS.subscribeAuthAccess), ), + getTraceDiagnostics: () => + transport.request((client) => client[WS_METHODS.serverGetTraceDiagnostics]({})), + getProcessDiagnostics: () => + transport.request((client) => client[WS_METHODS.serverGetProcessDiagnostics]({})), + getProcessResourceHistory: (input) => + transport.request((client) => client[WS_METHODS.serverGetProcessResourceHistory](input)), + signalProcess: (input) => + transport.request((client) => client[WS_METHODS.serverSignalProcess](input)), }, orchestration: { dispatchCommand: (input) => @@ -270,6 +325,10 @@ export function createWsRpcClient( transport.request((client) => client[ORCHESTRATION_WS_METHODS.getTurnDiff](input)), getFullThreadDiff: (input) => transport.request((client) => client[ORCHESTRATION_WS_METHODS.getFullThreadDiff](input)), + getArchivedShellSnapshot: () => + transport.request((client) => + client[ORCHESTRATION_WS_METHODS.getArchivedShellSnapshot]({}), + ), subscribeShell: (listener, options) => transport.subscribe( (client) => client[ORCHESTRATION_WS_METHODS.subscribeShell]({}), diff --git a/packages/client-runtime/src/wsRpcProtocol.ts b/packages/client-runtime/src/wsRpcProtocol.ts index ec04156ce6..152ca3cb6d 100644 --- a/packages/client-runtime/src/wsRpcProtocol.ts +++ b/packages/client-runtime/src/wsRpcProtocol.ts @@ -1,5 +1,8 @@ import { WsRpcGroup } from "@t3tools/contracts"; -import { Duration, Effect, Layer, Schedule } from "effect"; +import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Schedule from "effect/Schedule"; import { RpcClient, RpcSerialization } from "effect/unstable/rpc"; import * as Socket from "effect/unstable/socket/Socket"; @@ -10,6 +13,8 @@ import { } from "./reconnectBackoff.ts"; export interface WsProtocolLifecycleHandlers { + readonly getConnectionLabel?: () => string | null; + readonly getVersionMismatchHint?: () => string | null; readonly onAttempt?: (socketUrl: string) => void; readonly onOpen?: () => void; readonly onError?: (message: string) => void; @@ -64,6 +69,8 @@ function defaultLifecycleHandlers(): Required { onOpen: () => undefined, onError: () => undefined, onClose: () => undefined, + getConnectionLabel: () => null, + getVersionMismatchHint: () => null, }; } @@ -79,6 +86,10 @@ function resolveLifecycleHandlers( } return { + getConnectionLabel: () => + handlers?.getConnectionLabel?.() ?? telemetryLifecycle.getConnectionLabel?.() ?? null, + getVersionMismatchHint: () => + handlers?.getVersionMismatchHint?.() ?? telemetryLifecycle.getVersionMismatchHint?.() ?? null, onAttempt: (socketUrl) => { telemetryLifecycle.onAttempt?.(socketUrl); handlers?.onAttempt?.(socketUrl); diff --git a/packages/client-runtime/src/wsTransport.test.ts b/packages/client-runtime/src/wsTransport.test.ts index 1ce01479fd..ba4acc46f5 100644 --- a/packages/client-runtime/src/wsTransport.test.ts +++ b/packages/client-runtime/src/wsTransport.test.ts @@ -1,5 +1,7 @@ import { WS_METHODS } from "@t3tools/contracts"; -import { Stream } from "effect"; +import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import * as Stream from "effect/Stream"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { WsTransport } from "./wsTransport.ts"; @@ -80,16 +82,16 @@ function getSocket(): MockWebSocket { } async function waitFor(assertion: () => void, timeoutMs = 1_000): Promise { - const startedAt = Date.now(); + const startedAt = performance.now(); for (;;) { try { assertion(); return; } catch (error) { - if (Date.now() - startedAt >= timeoutMs) { + if (performance.now() - startedAt >= timeoutMs) { throw error; } - await new Promise((resolve) => setTimeout(resolve, 10)); + await Effect.runPromise(Effect.sleep(Duration.millis(10))); } } } @@ -666,7 +668,7 @@ describe("WsTransport", () => { await waitFor(() => { expect(attempts).toBe(1); }); - await new Promise((resolve) => setTimeout(resolve, 50)); + await Effect.runPromise(Effect.sleep(Duration.millis(50))); expect(attempts).toBe(1); expect(warnSpy).toHaveBeenCalledWith("WebSocket RPC subscription failed", { diff --git a/packages/client-runtime/src/wsTransport.ts b/packages/client-runtime/src/wsTransport.ts index 639b854217..2a5a044c51 100644 --- a/packages/client-runtime/src/wsTransport.ts +++ b/packages/client-runtime/src/wsTransport.ts @@ -1,4 +1,11 @@ -import { Cause, Duration, Effect, Exit, Layer, ManagedRuntime, Scope, Stream } from "effect"; +import * as Cause from "effect/Cause"; +import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; +import * as Layer from "effect/Layer"; +import * as ManagedRuntime from "effect/ManagedRuntime"; +import * as Scope from "effect/Scope"; +import * as Stream from "effect/Stream"; import { RpcClient } from "effect/unstable/rpc"; import { isTransportConnectionErrorMessage } from "./transportError.ts"; @@ -165,16 +172,18 @@ export class WsTransport { const formattedError = formatErrorMessage(error); if (!isTransportConnectionErrorMessage(formattedError)) { - console.warn("WebSocket RPC subscription failed", { - error: formattedError, - }); + Effect.runSync( + Effect.logWarning("WebSocket RPC subscription failed", { error: formattedError }), + ); return; } if (!this.hasReportedTransportDisconnect) { - console.warn("WebSocket RPC subscription disconnected", { - error: formattedError, - }); + Effect.runSync( + Effect.logWarning("WebSocket RPC subscription disconnected", { + error: formattedError, + }), + ); } this.hasReportedTransportDisconnect = true; await sleep(retryDelayMs); @@ -298,7 +307,5 @@ export class WsTransport { } function sleep(ms: number): Promise { - return new Promise((resolve) => { - setTimeout(resolve, ms); - }); + return Effect.runPromise(Effect.sleep(Duration.millis(ms))); } diff --git a/packages/contracts/src/review.ts b/packages/contracts/src/review.ts index 0a7f0928eb..363b124bf2 100644 --- a/packages/contracts/src/review.ts +++ b/packages/contracts/src/review.ts @@ -1,4 +1,4 @@ -import { Schema } from "effect"; +import * as Schema from "effect/Schema"; import { TrimmedNonEmptyString } from "./baseSchemas.ts"; import { GitCommandError } from "./git.ts"; import { VcsError } from "./vcs.ts";