diff --git a/apps/mobile/package.json b/apps/mobile/package.json index 0d833dc828..fe3bccdd5e 100644 --- a/apps/mobile/package.json +++ b/apps/mobile/package.json @@ -16,7 +16,7 @@ "@effect/atom-react": "catalog:", "@expo-google-fonts/dm-sans": "^0.4.2", "@gorhom/bottom-sheet": "^5", - "@legendapp/list": "^3.0.0-beta.44", + "@legendapp/list": "3.0.0-beta.44", "@react-native-menu/menu": "^2.0.0", "@sethwebster/react-ethereal-input": "^0.4.0", "@shopify/flash-list": "2.0.2", diff --git a/apps/mobile/src/app/_layout.tsx b/apps/mobile/src/app/_layout.tsx index 6338d7dce7..121e69299c 100644 --- a/apps/mobile/src/app/_layout.tsx +++ b/apps/mobile/src/app/_layout.tsx @@ -95,11 +95,7 @@ export default function RootLayout() { - {fontsLoaded ? ( - - ) : ( - - )} + {fontsLoaded ? : } diff --git a/apps/mobile/src/app/threads/[environmentId]/[threadId]/git/_layout.tsx b/apps/mobile/src/app/threads/[environmentId]/[threadId]/git/_layout.tsx index 42b3a482b9..c2d725188d 100644 --- a/apps/mobile/src/app/threads/[environmentId]/[threadId]/git/_layout.tsx +++ b/apps/mobile/src/app/threads/[environmentId]/[threadId]/git/_layout.tsx @@ -8,7 +8,9 @@ export const unstable_settings = { export default function GitSheetLayout() { const sheetStyle = StyleSheet.flatten(useResolveClassNames("bg-sheet")); - const headerBg = { backgroundColor: (sheetStyle as { backgroundColor?: string })?.backgroundColor }; + const headerBg = { + backgroundColor: (sheetStyle as { backgroundColor?: string })?.backgroundColor, + }; return ( void; + readonly onReconnect: (environmentId: string) => void; readonly onRemove: (environmentId: string) => void; readonly onUpdate: ( environmentId: string, @@ -40,7 +41,10 @@ function EnvironmentRow(props: { return ( - + @@ -53,6 +57,14 @@ function EnvironmentRow(props: { {props.environment.displayUrl} + {props.environment.connectionError ? ( + + {props.environment.connectionError} + + ) : null} @@ -124,7 +136,19 @@ function EnvironmentRow(props: { props.onReconnect(props.environment.environmentId)} + > + + + + props.onRemove(props.environment.environmentId)} > @@ -137,8 +161,12 @@ function EnvironmentRow(props: { } export function ConnectionsRouteScreen() { - const { connectedEnvironments, onRemoveEnvironmentPress, onUpdateEnvironment } = - useRemoteConnections(); + const { + connectedEnvironments, + onReconnectEnvironment, + onRemoveEnvironmentPress, + onUpdateEnvironment, + } = useRemoteConnections(); const insets = useSafeAreaInsets(); const hasEnvironments = connectedEnvironments.length > 0; const [expandedId, setExpandedId] = useState(null); @@ -158,7 +186,7 @@ export function ConnectionsRouteScreen() { title: "Backends", headerRight: () => ( - + handleToggle(environment.environmentId)} + onReconnect={onReconnectEnvironment} onRemove={onRemoveEnvironmentPress} onUpdate={onUpdateEnvironment} /> diff --git a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx index 4a951e3998..072d7a30e6 100644 --- a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx +++ b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx @@ -209,20 +209,18 @@ export function ThreadDetailScreen(props: ThreadDetailScreenProps) { {/* Feed area — KAV shrinks this when keyboard opens */} {showContent ? ( - - void handleRefresh()} - /> - + void handleRefresh()} + /> ) : ( )} diff --git a/apps/mobile/src/features/threads/ThreadFeed.tsx b/apps/mobile/src/features/threads/ThreadFeed.tsx index b8b14f3501..a1fbac4082 100644 --- a/apps/mobile/src/features/threads/ThreadFeed.tsx +++ b/apps/mobile/src/features/threads/ThreadFeed.tsx @@ -7,6 +7,7 @@ import Markdown from "react-native-markdown-display"; import { Image, Pressable, ScrollView, View } from "react-native"; import { TouchableOpacity } from "react-native-gesture-handler"; import ImageViewing from "react-native-image-viewing"; +import { useSafeAreaInsets } from "react-native-safe-area-context"; import { useThemeColor } from "../../lib/useThemeColor"; import { AppText as Text } from "../../components/AppText"; @@ -440,6 +441,8 @@ function renderFeedEntry( ); } +const IOS_NAV_BAR_HEIGHT = 44; + export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { const listRef = useRef(null); const copyFeedbackTimeoutRef = useRef | null>(null); @@ -450,6 +453,8 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { headers?: Record; } | null>(null); const horizontalPadding = props.layoutVariant === "split" ? 20 : 16; + const insets = useSafeAreaInsets(); + const topContentInset = insets.top + IOS_NAV_BAR_HEIGHT; const iconSubtleColor = useThemeColor("--color-icon-subtle"); const markdownStyles = useMarkdownStyles(); @@ -533,7 +538,10 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { return ( + <> `${entry.type}:${entry.id}`} @@ -567,8 +577,8 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { refreshing={props.refreshing ?? false} onRefresh={props.onRefresh} contentContainerStyle={{ + paddingTop: 12, paddingHorizontal: horizontalPadding, - paddingTop: 8, paddingBottom: props.contentBottomInset ?? 18, }} /> @@ -590,6 +600,6 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { swipeToCloseEnabled doubleTapToZoomEnabled /> - + ); }); diff --git a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx index 81c113c74d..97504ecc7b 100644 --- a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx +++ b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx @@ -19,6 +19,7 @@ import { useSelectedThreadGitActions } from "../../state/use-selected-thread-git import { useSelectedThreadGitState } from "../../state/use-selected-thread-git-state"; import { useSelectedThreadCommands } from "../../state/use-selected-thread-commands"; import { useThreadComposerState } from "../../state/use-thread-composer-state"; +import { useThreadDetailSubscription } from "../../state/use-thread-detail-subscription"; import { useThreadSelection } from "../../state/use-thread-selection"; import { ThreadDetailScreen } from "./ThreadDetailScreen"; import { ThreadGitControls } from "./ThreadGitControls"; @@ -61,6 +62,8 @@ export function ThreadRouteScreen() { const environmentId = firstRouteParam(params.environmentId); const threadId = firstRouteParam(params.threadId); + useThreadDetailSubscription(environmentId, threadId); + /* ─── Native header theming ──────────────────────────────────────── */ const isDark = useColorScheme() === "dark"; const iconColor = String(useThemeColor("--color-icon")); diff --git a/apps/mobile/src/features/threads/git/GitBranchesSheet.tsx b/apps/mobile/src/features/threads/git/GitBranchesSheet.tsx index 6591646fb3..ad1957bfb6 100644 --- a/apps/mobile/src/features/threads/git/GitBranchesSheet.tsx +++ b/apps/mobile/src/features/threads/git/GitBranchesSheet.tsx @@ -64,142 +64,140 @@ export function GitBranchesSheet() { gap: 16, }} > - - - New branch - - - { - const branch = sanitizeFeatureBranchName(newBranchName.trim()); - if (branch.length === 0) return; - void gitActions.onCreateSelectedThreadBranch(branch).then(() => { - setNewBranchName(""); - router.dismiss(); - }); - }} - /> - + + + New branch + + + { + const branch = sanitizeFeatureBranchName(newBranchName.trim()); + if (branch.length === 0) return; + void gitActions.onCreateSelectedThreadBranch(branch).then(() => { + setNewBranchName(""); + router.dismiss(); + }); + }} + /> + - - - New worktree + + + New worktree + + + + { + const baseBranch = worktreeBaseBranch.trim(); + const newBranch = worktreeBranchName.trim(); + if (baseBranch.length === 0 || newBranch.length === 0) return; + void gitActions.onCreateSelectedThreadWorktree({ baseBranch, newBranch }).then(() => { + setWorktreeBranchName(""); + router.dismiss(); + }); + }} + /> + + + + + Existing branches + + {branchesLoading ? ( + + Loading branches... - - - { - const baseBranch = worktreeBaseBranch.trim(); - const newBranch = worktreeBranchName.trim(); - if (baseBranch.length === 0 || newBranch.length === 0) return; - void gitActions - .onCreateSelectedThreadWorktree({ baseBranch, newBranch }) - .then(() => { - setWorktreeBranchName(""); + ) : null} + {!branchesLoading && availableBranches.length === 0 ? ( + + No local branches found. + + ) : null} + {availableBranches.map((branch) => { + const disabled = disabledExistingBranches.has(branch.name); + const subtitle = branch.worktreePath + ? branch.worktreePath === currentWorktreePath + ? "Checked out in this thread" + : "Checked out in another worktree" + : branch.isDefault + ? "Default branch" + : "Local branch"; + + return ( + { + void gitActions.onCheckoutSelectedThreadBranch(branch.name).then(() => { router.dismiss(); }); - }} - /> - - - - - Existing branches - - {branchesLoading ? ( - - Loading branches... - - ) : null} - {!branchesLoading && availableBranches.length === 0 ? ( - - No local branches found. - - ) : null} - {availableBranches.map((branch) => { - const disabled = disabledExistingBranches.has(branch.name); - const subtitle = branch.worktreePath - ? branch.worktreePath === currentWorktreePath - ? "Checked out in this thread" - : "Checked out in another worktree" - : branch.isDefault - ? "Default branch" - : "Local branch"; - - return ( - { - void gitActions.onCheckoutSelectedThreadBranch(branch.name).then(() => { - router.dismiss(); - }); - }} - > - - {branch.name} - {subtitle} - - ); - })} - + }} + > + + {branch.name} + {subtitle} + + ); + })} + ); } diff --git a/apps/mobile/src/features/threads/git/GitCommitSheet.tsx b/apps/mobile/src/features/threads/git/GitCommitSheet.tsx index 8b1413f9bb..7f2d3584a4 100644 --- a/apps/mobile/src/features/threads/git/GitCommitSheet.tsx +++ b/apps/mobile/src/features/threads/git/GitCommitSheet.tsx @@ -70,173 +70,170 @@ export function GitCommitSheet() { gap: 16, }} > - - - Branch - - {gitStatus.data?.branch ?? "(detached HEAD)"} + + + Branch + + {gitStatus.data?.branch ?? "(detached HEAD)"} + + + {isDefaultBranch ? ( + + Warning: this is the default branch. + + ) : null} + + + + + + Files + + {selectedFiles.length} selected · +{selectedInsertions} / -{selectedDeletions} - {isDefaultBranch ? ( - - Warning: this is the default branch. - - ) : null} - - - - - - Files - - {selectedFiles.length} selected · +{selectedInsertions} / -{selectedDeletions} - - - - {!allSelected && isEditingFiles ? ( - setExcludedFiles(new Set())} - > - Reset - - ) : null} + + {!allSelected && isEditingFiles ? ( setIsEditingFiles((current) => !current)} + onPress={() => setExcludedFiles(new Set())} > - - {isEditingFiles ? "Done" : "Edit"} - + Reset - + ) : null} + setIsEditingFiles((current) => !current)} + > + + {isEditingFiles ? "Done" : "Edit"} + + - - {allFiles.length === 0 ? ( - - No changed files are available to commit. - - ) : !isEditingFiles ? ( - - {selectedFilePreview.map((file) => ( - - - {file.path} - - - +{file.insertions} - - - -{file.deletions} - - - ))} - {selectedFiles.length > selectedFilePreview.length ? ( - - +{selectedFiles.length - selectedFilePreview.length} more files - - ) : null} - - ) : ( - - {allFiles.map((file) => { - const included = !excludedFiles.has(file.path); - return ( - { - setExcludedFiles((current) => { - const next = new Set(current); - if (next.has(file.path)) { - next.delete(file.path); - } else { - next.add(file.path); - } - return next; - }); - }} - > - - - - - {file.path} - - {!included ? ( - - Excluded from this commit - - ) : null} - - - - +{file.insertions} - - - -{file.deletions} - - - - - ); - })} - - )} - - Commit message - + No changed files are available to commit. + + ) : !isEditingFiles ? ( + + {selectedFilePreview.map((file) => ( + + + {file.path} + + + +{file.insertions} + + + -{file.deletions} + + + ))} + {selectedFiles.length > selectedFilePreview.length ? ( + + +{selectedFiles.length - selectedFilePreview.length} more files + + ) : null} + + ) : ( + + {allFiles.map((file) => { + const included = !excludedFiles.has(file.path); + return ( + { + setExcludedFiles((current) => { + const next = new Set(current); + if (next.has(file.path)) { + next.delete(file.path); + } else { + next.add(file.path); + } + return next; + }); + }} + > + + + + + {file.path} + + {!included ? ( + + Excluded from this commit + + ) : null} + + + + +{file.insertions} + + + -{file.deletions} + + + + + ); + })} + + )} + + + + Commit message + + + + + + void runCommitAction(true)} /> - - - - void runCommitAction(true)} - /> - - - void runCommitAction(false)} - /> - + + void runCommitAction(false)} + /> + ); } diff --git a/apps/mobile/src/features/threads/git/GitConfirmSheet.tsx b/apps/mobile/src/features/threads/git/GitConfirmSheet.tsx index 38b5d26103..6e792f6091 100644 --- a/apps/mobile/src/features/threads/git/GitConfirmSheet.tsx +++ b/apps/mobile/src/features/threads/git/GitConfirmSheet.tsx @@ -81,10 +81,7 @@ export function GitConfirmSheet() { }, [confirmAction, gitActions, gitState.selectedThreadBranches, includesCommit, params, router]); return ( - + diff --git a/apps/mobile/src/features/threads/git/gitSheetComponents.tsx b/apps/mobile/src/features/threads/git/gitSheetComponents.tsx index 8dd8e32ac6..b13f6a3020 100644 --- a/apps/mobile/src/features/threads/git/gitSheetComponents.tsx +++ b/apps/mobile/src/features/threads/git/gitSheetComponents.tsx @@ -122,7 +122,16 @@ export function menuItemIconName( return "arrow.up.right.circle"; } -export function statusSummary(gitStatus: { readonly isRepo?: boolean; readonly hasWorkingTreeChanges?: boolean; readonly workingTree?: { readonly files: readonly { readonly path: string }[] }; readonly aheadCount?: number; readonly behindCount?: number; readonly pr?: { readonly state?: string; readonly number?: number } | null } | null): string { +export function statusSummary( + gitStatus: { + readonly isRepo?: boolean; + readonly hasWorkingTreeChanges?: boolean; + readonly workingTree?: { readonly files: readonly { readonly path: string }[] }; + readonly aheadCount?: number; + readonly behindCount?: number; + readonly pr?: { readonly state?: string; readonly number?: number } | null; + } | null, +): string { if (!gitStatus) { return "Loading branch status\u2026"; } diff --git a/apps/mobile/src/lib/orchestration.test.ts b/apps/mobile/src/lib/orchestration.test.ts deleted file mode 100644 index c87b2e24f4..0000000000 --- a/apps/mobile/src/lib/orchestration.test.ts +++ /dev/null @@ -1,104 +0,0 @@ -import { describe, expect, it } from "vitest"; - -import { EventId, ProjectId } from "@t3tools/contracts"; -import type { OrchestrationReadModel } from "@t3tools/contracts"; - -import { applyRealtimeEvent } from "./orchestration"; - -const baseSnapshot: OrchestrationReadModel = { - snapshotSequence: 0, - updatedAt: "2026-04-01T00:00:00.000Z", - projects: [], - threads: [], -}; - -const baseEventFields = { - eventId: EventId.makeUnsafe("event-1"), - commandId: null, - causationEventId: null, - correlationId: null, - metadata: {}, -} as const; - -describe("applyRealtimeEvent project identity handling", () => { - it("preserves repository identity on project.created", () => { - const next = applyRealtimeEvent(baseSnapshot, { - ...baseEventFields, - sequence: 1, - occurredAt: "2026-04-01T01:00:00.000Z", - aggregateKind: "project", - aggregateId: ProjectId.makeUnsafe("project-1"), - type: "project.created", - payload: { - projectId: ProjectId.makeUnsafe("project-1"), - title: "T3 Code", - workspaceRoot: "/repo", - repositoryIdentity: { - canonicalKey: "github.com/t3tools/t3code", - locator: { - source: "git-remote", - remoteName: "origin", - remoteUrl: "git@github.com:t3tools/t3code.git", - }, - provider: "github", - owner: "t3tools", - name: "t3code", - }, - defaultModelSelection: null, - scripts: [], - createdAt: "2026-04-01T01:00:00.000Z", - updatedAt: "2026-04-01T01:00:00.000Z", - }, - }); - - expect(next.projects[0]?.repositoryIdentity?.canonicalKey).toBe("github.com/t3tools/t3code"); - }); - - it("applies repository identity updates on project.meta-updated", () => { - const seeded = applyRealtimeEvent(baseSnapshot, { - ...baseEventFields, - sequence: 1, - occurredAt: "2026-04-01T01:00:00.000Z", - aggregateKind: "project", - aggregateId: ProjectId.makeUnsafe("project-1"), - type: "project.created", - payload: { - projectId: ProjectId.makeUnsafe("project-1"), - title: "T3 Code", - workspaceRoot: "/repo", - repositoryIdentity: null, - defaultModelSelection: null, - scripts: [], - createdAt: "2026-04-01T01:00:00.000Z", - updatedAt: "2026-04-01T01:00:00.000Z", - }, - }); - - const next = applyRealtimeEvent(seeded, { - ...baseEventFields, - eventId: EventId.makeUnsafe("event-2"), - sequence: 2, - occurredAt: "2026-04-01T02:00:00.000Z", - aggregateKind: "project", - aggregateId: ProjectId.makeUnsafe("project-1"), - type: "project.meta-updated", - payload: { - projectId: ProjectId.makeUnsafe("project-1"), - repositoryIdentity: { - canonicalKey: "github.com/t3tools/t3code", - locator: { - source: "git-remote", - remoteName: "origin", - remoteUrl: "git@github.com:t3tools/t3code.git", - }, - provider: "github", - owner: "t3tools", - name: "t3code", - }, - updatedAt: "2026-04-01T02:00:00.000Z", - }, - }); - - expect(next.projects[0]?.repositoryIdentity?.canonicalKey).toBe("github.com/t3tools/t3code"); - }); -}); diff --git a/apps/mobile/src/lib/orchestration.ts b/apps/mobile/src/lib/orchestration.ts deleted file mode 100644 index 1c45d3ac15..0000000000 --- a/apps/mobile/src/lib/orchestration.ts +++ /dev/null @@ -1,449 +0,0 @@ -import * as Order from "effect/Order"; -import type { - ChatAttachment, - MessageId, - OrchestrationEvent, - OrchestrationProject, - OrchestrationReadModel, - OrchestrationThread, - ThreadId, -} from "@t3tools/contracts"; -import * as Arr from "effect/Array"; - -const MAX_THREAD_PROPOSED_PLANS = 200; - -function updateThread( - snapshot: OrchestrationReadModel, - threadId: ThreadId, - updater: ( - thread: OrchestrationReadModel["threads"][number], - ) => OrchestrationReadModel["threads"][number], -): OrchestrationReadModel["threads"] { - return snapshot.threads.map((thread) => (thread.id === threadId ? updater(thread) : thread)); -} - -function updateProject( - snapshot: OrchestrationReadModel, - projectId: OrchestrationProject["id"], - updater: (project: OrchestrationProject) => OrchestrationProject, -): OrchestrationReadModel["projects"] { - return snapshot.projects.map((project) => - project.id === projectId ? updater(project) : project, - ); -} - -function upsertProject( - snapshot: OrchestrationReadModel, - nextProject: OrchestrationProject, -): OrchestrationReadModel["projects"] { - const existing = snapshot.projects.find((project) => project.id === nextProject.id); - if (existing) { - return updateProject(snapshot, nextProject.id, () => nextProject); - } - return [...snapshot.projects, nextProject]; -} - -function upsertThread( - snapshot: OrchestrationReadModel, - nextThread: OrchestrationThread, -): OrchestrationReadModel["threads"] { - const existing = snapshot.threads.find((thread) => thread.id === nextThread.id); - if (existing) { - return updateThread(snapshot, nextThread.id, () => nextThread); - } - return [...snapshot.threads, nextThread]; -} - -export function applyRealtimeEvent( - snapshot: OrchestrationReadModel, - event: OrchestrationEvent, -): OrchestrationReadModel { - const nextBase: OrchestrationReadModel = { - ...snapshot, - snapshotSequence: event.sequence, - updatedAt: event.occurredAt, - }; - - switch (event.type) { - case "project.created": - return { - ...nextBase, - projects: upsertProject(nextBase, { - id: event.payload.projectId, - title: event.payload.title, - workspaceRoot: event.payload.workspaceRoot, - repositoryIdentity: event.payload.repositoryIdentity ?? null, - defaultModelSelection: event.payload.defaultModelSelection, - scripts: event.payload.scripts, - createdAt: event.payload.createdAt, - updatedAt: event.payload.updatedAt, - deletedAt: null, - }), - }; - - case "project.meta-updated": - return { - ...nextBase, - projects: updateProject(nextBase, event.payload.projectId, (project) => ({ - ...project, - ...(event.payload.title !== undefined ? { title: event.payload.title } : {}), - ...(event.payload.workspaceRoot !== undefined - ? { workspaceRoot: event.payload.workspaceRoot } - : {}), - ...(event.payload.repositoryIdentity !== undefined - ? { repositoryIdentity: event.payload.repositoryIdentity } - : {}), - ...(event.payload.defaultModelSelection !== undefined - ? { defaultModelSelection: event.payload.defaultModelSelection } - : {}), - ...(event.payload.scripts !== undefined ? { scripts: event.payload.scripts } : {}), - updatedAt: event.payload.updatedAt, - })), - }; - - case "project.deleted": - return { - ...nextBase, - projects: updateProject(nextBase, event.payload.projectId, (project) => ({ - ...project, - deletedAt: event.payload.deletedAt, - updatedAt: event.payload.deletedAt, - })), - }; - - case "thread.created": - return { - ...nextBase, - threads: upsertThread(nextBase, { - id: event.payload.threadId, - projectId: event.payload.projectId, - title: event.payload.title, - modelSelection: event.payload.modelSelection, - runtimeMode: event.payload.runtimeMode, - interactionMode: event.payload.interactionMode, - branch: event.payload.branch, - worktreePath: event.payload.worktreePath, - latestTurn: null, - createdAt: event.payload.createdAt, - updatedAt: event.payload.updatedAt, - archivedAt: null, - deletedAt: null, - messages: [], - proposedPlans: [], - activities: [], - checkpoints: [], - session: null, - }), - }; - - case "thread.deleted": - return { - ...nextBase, - threads: updateThread(nextBase, event.payload.threadId, (thread) => ({ - ...thread, - deletedAt: event.payload.deletedAt, - updatedAt: event.payload.deletedAt, - })), - }; - - case "thread.archived": - return { - ...nextBase, - threads: updateThread(nextBase, event.payload.threadId, (thread) => ({ - ...thread, - archivedAt: event.payload.archivedAt, - updatedAt: event.payload.updatedAt, - })), - }; - - case "thread.unarchived": - return { - ...nextBase, - threads: updateThread(nextBase, event.payload.threadId, (thread) => ({ - ...thread, - archivedAt: null, - updatedAt: event.payload.updatedAt, - })), - }; - - case "thread.meta-updated": - return { - ...nextBase, - threads: updateThread(nextBase, event.payload.threadId, (thread) => ({ - ...thread, - ...(event.payload.title !== undefined ? { title: event.payload.title } : {}), - ...(event.payload.modelSelection !== undefined - ? { modelSelection: event.payload.modelSelection } - : {}), - ...(event.payload.branch !== undefined ? { branch: event.payload.branch } : {}), - ...(event.payload.worktreePath !== undefined - ? { worktreePath: event.payload.worktreePath } - : {}), - updatedAt: event.payload.updatedAt, - })), - }; - - case "thread.runtime-mode-set": - return { - ...nextBase, - threads: updateThread(nextBase, event.payload.threadId, (thread) => ({ - ...thread, - runtimeMode: event.payload.runtimeMode, - updatedAt: event.payload.updatedAt, - })), - }; - - case "thread.interaction-mode-set": - return { - ...nextBase, - threads: updateThread(nextBase, event.payload.threadId, (thread) => ({ - ...thread, - interactionMode: event.payload.interactionMode, - updatedAt: event.payload.updatedAt, - })), - }; - - case "thread.message-sent": - return { - ...nextBase, - threads: updateThread(nextBase, event.payload.threadId, (thread) => { - const existing = thread.messages.find( - (message) => message.id === event.payload.messageId, - ); - const nextMessages = existing - ? thread.messages.map((message) => - message.id === event.payload.messageId - ? { - ...message, - text: event.payload.streaming - ? `${message.text}${event.payload.text}` - : event.payload.text.length > 0 - ? event.payload.text - : message.text, - turnId: event.payload.turnId, - streaming: event.payload.streaming, - updatedAt: event.payload.updatedAt, - ...(event.payload.attachments - ? { attachments: event.payload.attachments } - : {}), - } - : message, - ) - : [ - ...thread.messages, - { - id: event.payload.messageId, - role: event.payload.role, - text: event.payload.text, - turnId: event.payload.turnId, - streaming: event.payload.streaming, - createdAt: event.payload.createdAt, - updatedAt: event.payload.updatedAt, - ...(event.payload.attachments ? { attachments: event.payload.attachments } : {}), - }, - ]; - - return { - ...thread, - messages: nextMessages, - updatedAt: event.occurredAt, - }; - }), - }; - - case "thread.turn-start-requested": - return { - ...nextBase, - threads: updateThread(nextBase, event.payload.threadId, (thread) => ({ - ...thread, - updatedAt: event.occurredAt, - })), - }; - - case "thread.session-set": - return { - ...nextBase, - threads: updateThread(nextBase, event.payload.threadId, (thread) => ({ - ...thread, - session: event.payload.session, - latestTurn: - event.payload.session.status === "running" && - event.payload.session.activeTurnId !== null - ? { - turnId: event.payload.session.activeTurnId, - state: "running", - requestedAt: - thread.latestTurn?.turnId === event.payload.session.activeTurnId - ? thread.latestTurn.requestedAt - : event.payload.session.updatedAt, - startedAt: - thread.latestTurn?.turnId === event.payload.session.activeTurnId - ? (thread.latestTurn.startedAt ?? event.payload.session.updatedAt) - : event.payload.session.updatedAt, - completedAt: null, - assistantMessageId: - thread.latestTurn?.turnId === event.payload.session.activeTurnId - ? thread.latestTurn.assistantMessageId - : null, - } - : thread.latestTurn, - updatedAt: event.occurredAt, - })), - }; - - case "thread.proposed-plan-upserted": - return { - ...nextBase, - threads: updateThread(nextBase, event.payload.threadId, (thread) => ({ - ...thread, - proposedPlans: Arr.sortWith( - [ - ...thread.proposedPlans.filter((proposedPlan) => { - return proposedPlan.id !== event.payload.proposedPlan.id; - }), - event.payload.proposedPlan, - ], - (s) => new Date(s.createdAt), - Order.Date, - ).slice(-MAX_THREAD_PROPOSED_PLANS), - updatedAt: event.occurredAt, - })), - }; - - case "thread.turn-diff-completed": - return { - ...nextBase, - threads: updateThread(nextBase, event.payload.threadId, (thread) => { - const checkpoints = Arr.sortWith( - [ - ...thread.checkpoints.filter( - (checkpoint) => checkpoint.turnId !== event.payload.turnId, - ), - { - turnId: event.payload.turnId, - checkpointTurnCount: event.payload.checkpointTurnCount, - checkpointRef: event.payload.checkpointRef, - status: event.payload.status, - files: event.payload.files, - assistantMessageId: event.payload.assistantMessageId, - completedAt: event.payload.completedAt, - }, - ], - (s) => s.checkpointTurnCount, - Order.Number, - ); - - const latestTurnState = - event.payload.status === "error" - ? "error" - : event.payload.status === "missing" - ? "interrupted" - : "completed"; - - return { - ...thread, - checkpoints, - latestTurn: { - turnId: event.payload.turnId, - state: latestTurnState, - requestedAt: - thread.latestTurn?.turnId === event.payload.turnId - ? thread.latestTurn.requestedAt - : event.payload.completedAt, - startedAt: - thread.latestTurn?.turnId === event.payload.turnId - ? (thread.latestTurn.startedAt ?? event.payload.completedAt) - : event.payload.completedAt, - completedAt: event.payload.completedAt, - assistantMessageId: event.payload.assistantMessageId, - }, - updatedAt: event.occurredAt, - }; - }), - }; - - case "thread.activity-appended": - return { - ...nextBase, - threads: updateThread(nextBase, event.payload.threadId, (thread) => ({ - ...thread, - activities: Arr.sortWith( - [ - ...thread.activities.filter((activity) => activity.id !== event.payload.activity.id), - event.payload.activity, - ], - (s) => new Date(s.createdAt), - Order.Date, - ), - updatedAt: event.occurredAt, - })), - }; - - default: - return nextBase; - } -} - -export function requiresSnapshotRefresh(event: OrchestrationEvent): boolean { - switch (event.type) { - case "project.created": - case "project.meta-updated": - case "project.deleted": - case "thread.created": - case "thread.deleted": - case "thread.archived": - case "thread.unarchived": - case "thread.meta-updated": - case "thread.runtime-mode-set": - case "thread.interaction-mode-set": - case "thread.message-sent": - case "thread.turn-start-requested": - case "thread.session-set": - case "thread.proposed-plan-upserted": - case "thread.turn-diff-completed": - case "thread.activity-appended": - return false; - default: - return true; - } -} - -export function applyOptimisticUserMessage( - snapshot: OrchestrationReadModel, - input: { - readonly threadId: ThreadId; - readonly messageId: MessageId; - readonly text: string; - readonly attachments?: ReadonlyArray; - readonly createdAt: string; - }, -): OrchestrationReadModel { - return { - ...snapshot, - updatedAt: input.createdAt, - threads: updateThread(snapshot, input.threadId, (thread) => { - if (thread.messages.some((message) => message.id === input.messageId)) { - return thread; - } - return { - ...thread, - updatedAt: input.createdAt, - messages: [ - ...thread.messages, - { - id: input.messageId, - role: "user", - text: input.text, - turnId: null, - streaming: false, - createdAt: input.createdAt, - updatedAt: input.createdAt, - ...(input.attachments && input.attachments.length > 0 - ? { attachments: input.attachments } - : {}), - }, - ], - }; - }), - }; -} diff --git a/apps/mobile/src/lib/repositoryGroups.test.ts b/apps/mobile/src/lib/repositoryGroups.test.ts index 3b3b3bd6af..6a9714f28f 100644 --- a/apps/mobile/src/lib/repositoryGroups.test.ts +++ b/apps/mobile/src/lib/repositoryGroups.test.ts @@ -16,7 +16,6 @@ function makeProject( scripts: [], createdAt: "2026-04-01T00:00:00.000Z", updatedAt: "2026-04-01T00:00:00.000Z", - deletedAt: null, ...input, }; } @@ -43,6 +42,10 @@ function makeThread( activities: [], checkpoints: [], session: null, + latestUserMessageAt: null, + hasPendingApprovals: false, + hasPendingUserInput: false, + hasActionableProposedPlan: false, ...input, }; } @@ -66,14 +69,14 @@ describe("groupProjectsByRepository", () => { makeProject({ environmentId: "env-local", environmentLabel: "Local", - id: ProjectId.makeUnsafe("project-local"), + id: ProjectId.make("project-local"), title: "T3 Code", repositoryIdentity: repoIdentity, }), makeProject({ environmentId: "env-staging", environmentLabel: "Staging", - id: ProjectId.makeUnsafe("project-staging"), + id: ProjectId.make("project-staging"), title: "T3 Code", repositoryIdentity: repoIdentity, }), @@ -83,8 +86,8 @@ describe("groupProjectsByRepository", () => { makeThread({ environmentId: "env-staging", environmentLabel: "Staging", - id: ThreadId.makeUnsafe("thread-2"), - projectId: ProjectId.makeUnsafe("project-staging"), + id: ThreadId.make("thread-2"), + projectId: ProjectId.make("project-staging"), title: "Fix reconnect flow", modelSelection: { provider: "codex", model: "gpt-5.4" }, updatedAt: "2026-04-02T12:00:00.000Z", @@ -92,8 +95,8 @@ describe("groupProjectsByRepository", () => { makeThread({ environmentId: "env-local", environmentLabel: "Local", - id: ThreadId.makeUnsafe("thread-1"), - projectId: ProjectId.makeUnsafe("project-local"), + id: ThreadId.make("thread-1"), + projectId: ProjectId.make("project-local"), title: "Polish mobile shell", modelSelection: { provider: "codex", model: "gpt-5.4" }, updatedAt: "2026-04-03T12:00:00.000Z", @@ -121,7 +124,7 @@ describe("groupProjectsByRepository", () => { makeProject({ environmentId: "env-local", environmentLabel: "Local", - id: ProjectId.makeUnsafe("project-local"), + id: ProjectId.make("project-local"), title: "Scratchpad", }), ]; diff --git a/apps/mobile/src/lib/scopedEntities.ts b/apps/mobile/src/lib/scopedEntities.ts index 153fbbb648..28728dc513 100644 --- a/apps/mobile/src/lib/scopedEntities.ts +++ b/apps/mobile/src/lib/scopedEntities.ts @@ -1,19 +1,32 @@ import type { ApprovalRequestId, - OrchestrationProject, + OrchestrationProjectShell, OrchestrationThread, + OrchestrationThreadShell, ProjectId, ThreadId, } from "@t3tools/contracts"; -export interface ScopedMobileProject extends OrchestrationProject { +export interface ScopedMobileProject extends OrchestrationProjectShell { readonly environmentId: string; readonly environmentLabel: string; } -export interface ScopedMobileThread extends OrchestrationThread { +/** + * Thread shape used throughout the mobile UI. Extends the lightweight shell + * type with the full-detail fields the composer and detail screen expect. + * The shell snapshot stubs these as empty arrays; `useThreadSelection` + * overlays real data from the per-thread `subscribeThread` subscription + * when a thread is selected. + */ +export interface ScopedMobileThread extends OrchestrationThreadShell { readonly environmentId: string; readonly environmentLabel: string; + readonly deletedAt: OrchestrationThread["deletedAt"]; + readonly messages: OrchestrationThread["messages"]; + readonly proposedPlans: OrchestrationThread["proposedPlans"]; + readonly activities: OrchestrationThread["activities"]; + readonly checkpoints: OrchestrationThread["checkpoints"]; } export function scopedProjectKey(environmentId: string, projectId: ProjectId): string { diff --git a/apps/mobile/src/state/remote-environment-store.ts b/apps/mobile/src/state/remote-environment-store.ts index 2ace6715cb..7592f62939 100644 --- a/apps/mobile/src/state/remote-environment-store.ts +++ b/apps/mobile/src/state/remote-environment-store.ts @@ -1,6 +1,7 @@ import { useStore } from "zustand"; import { createStore } from "zustand/vanilla"; +import type { OrchestrationThread } from "@t3tools/contracts"; import type { SavedRemoteConnection } from "../lib/connection"; import { defaultEnvironmentRuntimeState, @@ -13,6 +14,8 @@ export interface RemoteEnvironmentStoreState { readonly pendingConnectionError: string | null; readonly savedConnectionsById: Record; readonly environmentStateById: Record; + /** Full thread detail keyed by `${environmentId}:${threadId}`. */ + readonly threadDetailByKey: Record; readonly setIsLoadingSavedConnection: (value: boolean) => void; readonly setConnectionPairingUrl: (pairingUrl: string) => void; @@ -27,6 +30,8 @@ export interface RemoteEnvironmentStoreState { updater: (current: EnvironmentRuntimeState) => EnvironmentRuntimeState, ) => void; readonly removeEnvironmentRuntimeState: (environmentId: string) => void; + readonly setThreadDetail: (key: string, thread: OrchestrationThread) => void; + readonly removeThreadDetail: (key: string) => void; } export const remoteEnvironmentStore = createStore()((set) => ({ @@ -35,6 +40,7 @@ export const remoteEnvironmentStore = createStore() pendingConnectionError: null, savedConnectionsById: {}, environmentStateById: {}, + threadDetailByKey: {}, setIsLoadingSavedConnection: (value) => set({ isLoadingSavedConnection: value }), setConnectionPairingUrl: (pairingUrl) => set({ connectionPairingUrl: pairingUrl }), @@ -70,6 +76,16 @@ export const remoteEnvironmentStore = createStore() delete next[environmentId]; return { environmentStateById: next }; }), + setThreadDetail: (key, thread) => + set((state) => ({ + threadDetailByKey: { ...state.threadDetailByKey, [key]: thread }, + })), + removeThreadDetail: (key) => + set((state) => { + const next = { ...state.threadDetailByKey }; + delete next[key]; + return { threadDetailByKey: next }; + }), })); export function useRemoteEnvironmentStore( diff --git a/apps/mobile/src/state/remote-runtime-types.ts b/apps/mobile/src/state/remote-runtime-types.ts index f186d39971..528c3c5778 100644 --- a/apps/mobile/src/state/remote-runtime-types.ts +++ b/apps/mobile/src/state/remote-runtime-types.ts @@ -1,4 +1,7 @@ -import type { OrchestrationReadModel, ServerConfig as T3ServerConfig } from "@t3tools/contracts"; +import type { + OrchestrationShellSnapshot, + ServerConfig as T3ServerConfig, +} from "@t3tools/contracts"; import type { EnvironmentConnection, WsRpcClient } from "@t3tools/client-runtime"; export type RemoteClientConnectionState = @@ -24,7 +27,7 @@ export interface SelectedThreadRef { export interface EnvironmentRuntimeState { readonly connectionState: RemoteClientConnectionState; readonly connectionError: string | null; - readonly snapshot: OrchestrationReadModel | null; + readonly snapshot: OrchestrationShellSnapshot | null; readonly serverConfig: T3ServerConfig | null; } diff --git a/apps/mobile/src/state/use-project-actions.ts b/apps/mobile/src/state/use-project-actions.ts index f4f60ec9da..2bfeda1da4 100644 --- a/apps/mobile/src/state/use-project-actions.ts +++ b/apps/mobile/src/state/use-project-actions.ts @@ -42,14 +42,10 @@ function useRefreshRemoteData() { } try { - const [serverConfig, snapshot] = await Promise.all([ - client.server.getConfig(), - client.orchestration.getSnapshot(), - ]); + const serverConfig = await client.server.getConfig(); patchEnvironmentRuntimeState(environmentId, (current) => ({ ...current, serverConfig, - snapshot, connectionError: null, })); } catch (error) { @@ -91,7 +87,7 @@ export function useProjectActions() { return null; } - const threadId = ThreadId.makeUnsafe(uuidv4()); + const threadId = ThreadId.make(uuidv4()); const createdAt = new Date().toISOString(); const initialMessageText = input.initialMessageText.trim(); const nextTitle = deriveThreadTitleFromPrompt(input.initialMessageText); @@ -103,10 +99,10 @@ export function useProjectActions() { await client.orchestration.dispatchCommand({ type: "thread.turn.start", - commandId: CommandId.makeUnsafe(uuidv4()), + commandId: CommandId.make(uuidv4()), threadId, message: { - messageId: MessageId.makeUnsafe(uuidv4()), + messageId: MessageId.make(uuidv4()), role: "user", text: initialMessageText, attachments: input.initialAttachments, @@ -138,7 +134,7 @@ export function useProjectActions() { } else { await client.orchestration.dispatchCommand({ type: "thread.create", - commandId: CommandId.makeUnsafe(uuidv4()), + commandId: CommandId.make(uuidv4()), threadId, projectId: input.project.id, title: nextTitle, @@ -153,10 +149,10 @@ export function useProjectActions() { if (initialMessageText.length > 0 || input.initialAttachments.length > 0) { await client.orchestration.dispatchCommand({ type: "thread.turn.start", - commandId: CommandId.makeUnsafe(uuidv4()), + commandId: CommandId.make(uuidv4()), threadId, message: { - messageId: MessageId.makeUnsafe(uuidv4()), + messageId: MessageId.make(uuidv4()), role: "user", text: initialMessageText, attachments: input.initialAttachments, diff --git a/apps/mobile/src/state/use-remote-catalog.ts b/apps/mobile/src/state/use-remote-catalog.ts index 5427427a4f..ac9aa2039d 100644 --- a/apps/mobile/src/state/use-remote-catalog.ts +++ b/apps/mobile/src/state/use-remote-catalog.ts @@ -34,14 +34,13 @@ export function useRemoteCatalog() { () => Arr.sort( Object.values(savedConnectionsById).flatMap((connection) => - (environmentStateById[connection.environmentId]?.snapshot?.projects ?? []) - .filter((project) => project.deletedAt === null) - .map((project) => + (environmentStateById[connection.environmentId]?.snapshot?.projects ?? []).map( + (project) => Object.assign({}, project, { environmentId: connection.environmentId, environmentLabel: connection.environmentLabel, }), - ), + ), ), projectsSortOrder, ), @@ -52,14 +51,17 @@ export function useRemoteCatalog() { () => Arr.sort( Object.values(savedConnectionsById).flatMap((connection) => - (environmentStateById[connection.environmentId]?.snapshot?.threads ?? []) - .filter((thread) => thread.deletedAt === null) - .map((thread) => - Object.assign({}, thread, { - environmentId: connection.environmentId, - environmentLabel: connection.environmentLabel, - }), - ), + (environmentStateById[connection.environmentId]?.snapshot?.threads ?? []).map((thread) => + Object.assign({}, thread, { + environmentId: connection.environmentId, + environmentLabel: connection.environmentLabel, + deletedAt: null, + messages: [], + proposedPlans: [], + activities: [], + checkpoints: [], + }), + ), ), threadsSortOrder, ), diff --git a/apps/mobile/src/state/use-remote-environment-registry.ts b/apps/mobile/src/state/use-remote-environment-registry.ts index a1412817e2..0f41857548 100644 --- a/apps/mobile/src/state/use-remote-environment-registry.ts +++ b/apps/mobile/src/state/use-remote-environment-registry.ts @@ -2,18 +2,18 @@ import { useCallback, useEffect, useMemo } from "react"; import { Alert } from "react-native"; import { + applyShellStreamEvent, createEnvironmentConnection, createKnownEnvironment, createWsRpcClient, WsTransport, } from "@t3tools/client-runtime"; -import { EnvironmentId, type OrchestrationReadModel } from "@t3tools/contracts"; +import { EnvironmentId } from "@t3tools/contracts"; import { resolveRemoteWebSocketConnectionUrl } from "@t3tools/shared/remote"; import { useShallow } from "zustand/react/shallow"; import * as Arr from "effect/Array"; import * as Order from "effect/Order"; import { type SavedRemoteConnection, bootstrapRemoteConnection } from "../lib/connection"; -import { applyRealtimeEvent, requiresSnapshotRefresh } from "../lib/orchestration"; import { clearSavedConnection, loadSavedConnections, saveConnection } from "../lib/storage"; import { firstNonNull, @@ -141,36 +141,22 @@ export async function connectSavedEnvironment( wsBaseUrl: connection.wsBaseUrl, }, }), - environmentId: EnvironmentId.makeUnsafe(connection.environmentId), + environmentId: EnvironmentId.make(connection.environmentId), }, client, - applyEventBatch: (events, environmentId) => { - remoteEnvironmentStore.getState().patchEnvironmentRuntimeState(environmentId, (runtime) => ({ - ...runtime, - snapshot: runtime.snapshot - ? events.reduce( - (snapshot, event) => applyRealtimeEvent(snapshot, event), - runtime.snapshot, - ) - : runtime.snapshot, - })); + applyShellEvent: (event, environmentId) => { + remoteEnvironmentStore.getState().patchEnvironmentRuntimeState(environmentId, (runtime) => { + if (!runtime.snapshot) { + return runtime; + } - if (events.some((event) => requiresSnapshotRefresh(event))) { - void environmentSessions - .get(environmentId) - ?.client.orchestration.getSnapshot() - .then((snapshot: OrchestrationReadModel) => { - remoteEnvironmentStore - .getState() - .patchEnvironmentRuntimeState(environmentId, (runtime) => ({ - ...runtime, - snapshot, - })); - }) - .catch(() => undefined); - } + return { + ...runtime, + snapshot: applyShellStreamEvent(runtime.snapshot, event), + }; + }); }, - syncSnapshot: (snapshot, environmentId) => { + syncShellSnapshot: (snapshot, environmentId) => { remoteEnvironmentStore.getState().patchEnvironmentRuntimeState(environmentId, (runtime) => ({ ...runtime, snapshot, @@ -241,7 +227,7 @@ export function useRemoteEnvironmentBootstrap() { let cancelled = false; void loadSavedConnections() - .then(async (connections) => { + .then((connections) => { if (cancelled) { return; } @@ -252,7 +238,9 @@ export function useRemoteEnvironmentBootstrap() { ), ); - await Promise.all( + setIsLoadingSavedConnection(false); + + void Promise.all( connections.map((connection) => connectSavedEnvironment(connection, { persist: false, @@ -260,7 +248,7 @@ export function useRemoteEnvironmentBootstrap() { ), ); }) - .finally(() => { + .catch(() => { if (!cancelled) { setIsLoadingSavedConnection(false); } @@ -388,6 +376,14 @@ export function useRemoteConnections() { [], ); + const onReconnectEnvironment = useCallback((environmentId: string) => { + const connection = remoteEnvironmentStore.getState().savedConnectionsById[environmentId]; + if (!connection) { + return; + } + void connectSavedEnvironment(connection, { persist: false }); + }, []); + const onRemoveEnvironmentPress = useCallback((environmentId: string) => { const connection = remoteEnvironmentStore.getState().savedConnectionsById[environmentId]; if (!connection) { @@ -418,6 +414,7 @@ export function useRemoteConnections() { connectedEnvironmentCount: connectedEnvironments.length, onChangeConnectionPairingUrl: setConnectionPairingUrl, onConnectPress, + onReconnectEnvironment, onUpdateEnvironment, onRemoveEnvironmentPress, }; diff --git a/apps/mobile/src/state/use-selected-thread-commands.ts b/apps/mobile/src/state/use-selected-thread-commands.ts index 104362c794..60f17a282f 100644 --- a/apps/mobile/src/state/use-selected-thread-commands.ts +++ b/apps/mobile/src/state/use-selected-thread-commands.ts @@ -59,14 +59,10 @@ export function useSelectedThreadCommands(input: { } try { - const [serverConfig, snapshot] = await Promise.all([ - client.server.getConfig(), - client.orchestration.getSnapshot(), - ]); + const serverConfig = await client.server.getConfig(); patchEnvironmentRuntimeState(environmentId, (current) => ({ ...current, serverConfig, - snapshot, connectionError: null, })); } catch (error) { @@ -102,7 +98,7 @@ export function useSelectedThreadCommands(input: { await client.orchestration.dispatchCommand({ type: "thread.meta.update", - commandId: CommandId.makeUnsafe(uuidv4()), + commandId: CommandId.make(uuidv4()), threadId: selectedThread.id, modelSelection, }); @@ -123,7 +119,7 @@ export function useSelectedThreadCommands(input: { await client.orchestration.dispatchCommand({ type: "thread.runtime-mode.set", - commandId: CommandId.makeUnsafe(uuidv4()), + commandId: CommandId.make(uuidv4()), threadId: selectedThread.id, runtimeMode, createdAt: new Date().toISOString(), @@ -145,7 +141,7 @@ export function useSelectedThreadCommands(input: { await client.orchestration.dispatchCommand({ type: "thread.interaction-mode.set", - commandId: CommandId.makeUnsafe(uuidv4()), + commandId: CommandId.make(uuidv4()), threadId: selectedThread.id, interactionMode, createdAt: new Date().toISOString(), @@ -173,7 +169,7 @@ export function useSelectedThreadCommands(input: { await client.orchestration.dispatchCommand({ type: "thread.turn.interrupt", - commandId: CommandId.makeUnsafe(uuidv4()), + commandId: CommandId.make(uuidv4()), threadId: selectedThread.id, ...(selectedThread.session?.activeTurnId ? { turnId: selectedThread.session.activeTurnId } @@ -200,7 +196,7 @@ export function useSelectedThreadCommands(input: { await client.orchestration.dispatchCommand({ type: "thread.meta.update", - commandId: CommandId.makeUnsafe(uuidv4()), + commandId: CommandId.make(uuidv4()), threadId: selectedThread.id, title: trimmed, }); @@ -223,7 +219,7 @@ export function useSelectedThreadCommands(input: { try { await client.orchestration.dispatchCommand({ type: "thread.approval.respond", - commandId: CommandId.makeUnsafe(uuidv4()), + commandId: CommandId.make(uuidv4()), threadId: selectedThread.id, requestId, decision, @@ -250,7 +246,7 @@ export function useSelectedThreadCommands(input: { try { await client.orchestration.dispatchCommand({ type: "thread.user-input.respond", - commandId: CommandId.makeUnsafe(uuidv4()), + commandId: CommandId.make(uuidv4()), threadId: selectedThread.id, requestId: activePendingUserInput.requestId, answers: activePendingUserInputAnswers, diff --git a/apps/mobile/src/state/use-selected-thread-git-actions.ts b/apps/mobile/src/state/use-selected-thread-git-actions.ts index 3134afef70..bfe680e1fe 100644 --- a/apps/mobile/src/state/use-selected-thread-git-actions.ts +++ b/apps/mobile/src/state/use-selected-thread-git-actions.ts @@ -44,8 +44,8 @@ export function useSelectedThreadGitActions() { await client.orchestration.dispatchCommand({ type: "thread.meta.update", - commandId: CommandId.makeUnsafe(uuidv4()), - threadId: ThreadId.makeUnsafe(thread.id), + commandId: CommandId.make(uuidv4()), + threadId: ThreadId.make(thread.id), ...(nextState.branch !== undefined ? { branch: nextState.branch } : {}), ...(nextState.worktreePath !== undefined ? { worktreePath: nextState.worktreePath } : {}), }); diff --git a/apps/mobile/src/state/use-thread-composer-state.ts b/apps/mobile/src/state/use-thread-composer-state.ts index d411fde8bc..e39cb34be5 100644 --- a/apps/mobile/src/state/use-thread-composer-state.ts +++ b/apps/mobile/src/state/use-thread-composer-state.ts @@ -8,7 +8,6 @@ import { pasteComposerClipboard, pickComposerImages, } from "../lib/composerImages"; -import { applyOptimisticUserMessage } from "../lib/orchestration"; import type { ScopedMobileThread } from "../lib/scopedEntities"; import { scopedRequestKey, scopedThreadKey } from "../lib/scopedEntities"; import { @@ -106,9 +105,7 @@ export function useThreadComposerState() { const { connectedEnvironments } = useRemoteConnectionStatus(); const { threads } = useRemoteCatalog(); const { selectedThread } = useThreadSelection(); - const patchEnvironmentRuntimeState = useRemoteEnvironmentStore( - (state) => state.patchEnvironmentRuntimeState, - ); + const setPendingConnectionError = useRemoteEnvironmentStore( (state) => state.setPendingConnectionError, ); @@ -242,10 +239,10 @@ export function useThreadComposerState() { try { await client.orchestration.dispatchCommand({ type: "thread.turn.start", - commandId: CommandId.makeUnsafe(queuedMessage.commandId), - threadId: ThreadId.makeUnsafe(queuedMessage.threadId), + commandId: CommandId.make(queuedMessage.commandId), + threadId: ThreadId.make(queuedMessage.threadId), message: { - messageId: MessageId.makeUnsafe(queuedMessage.messageId), + messageId: MessageId.make(queuedMessage.messageId), role: "user", text: queuedMessage.text, attachments: queuedMessage.attachments, @@ -260,18 +257,6 @@ export function useThreadComposerState() { queuedMessage.threadId, queuedMessage.messageId, ); - patchEnvironmentRuntimeState(queuedMessage.environmentId, (runtime) => ({ - ...runtime, - snapshot: runtime.snapshot - ? applyOptimisticUserMessage(runtime.snapshot, { - threadId: ThreadId.makeUnsafe(queuedMessage.threadId), - messageId: MessageId.makeUnsafe(queuedMessage.messageId), - text: queuedMessage.text, - attachments: queuedMessage.attachments, - createdAt: queuedMessage.createdAt, - }) - : runtime.snapshot, - })); } catch (error) { removeQueuedMessage( queuedMessage.environmentId, @@ -288,7 +273,6 @@ export function useThreadComposerState() { [ beginDispatchingQueuedMessage, finishDispatchingQueuedMessage, - patchEnvironmentRuntimeState, removeQueuedMessage, setPendingConnectionError, threads, @@ -319,8 +303,8 @@ export function useThreadComposerState() { enqueueQueuedMessage({ environmentId: selectedThread.environmentId, threadId: selectedThread.id, - messageId: MessageId.makeUnsafe(uuidv4()), - commandId: CommandId.makeUnsafe(uuidv4()), + messageId: MessageId.make(uuidv4()), + commandId: CommandId.make(uuidv4()), text, attachments, createdAt, diff --git a/apps/mobile/src/state/use-thread-detail-subscription.ts b/apps/mobile/src/state/use-thread-detail-subscription.ts new file mode 100644 index 0000000000..3b126d8b41 --- /dev/null +++ b/apps/mobile/src/state/use-thread-detail-subscription.ts @@ -0,0 +1,100 @@ +import { useEffect } from "react"; + +import { applyThreadDetailEvent } from "@t3tools/client-runtime"; +import { ThreadId } from "@t3tools/contracts"; + +import { scopedThreadKey } from "../lib/scopedEntities"; +import { remoteEnvironmentStore } from "./remote-environment-store"; +import { getEnvironmentClient } from "./use-remote-environment-registry"; + +/** + * Subscribe to full thread detail (messages, activities, checkpoints, etc.) + * for the given environment + thread. The subscription is torn down when the + * component unmounts or the identifiers change. + * + * Received snapshots and incremental events are written into + * `remoteEnvironmentStore.threadDetailByKey` so that `useThreadSelection` can + * merge them over the shell stubs. + */ +export function useThreadDetailSubscription( + environmentId: string | null, + threadId: string | null, +): void { + useEffect(() => { + if (!environmentId || !threadId) { + return; + } + + const brandedThreadId = ThreadId.make(threadId); + const key = scopedThreadKey(environmentId, brandedThreadId); + let unsubscribe: (() => void) | null = null; + let disposed = false; + + function attach() { + if (disposed) { + return; + } + + const client = getEnvironmentClient(environmentId!); + if (!client) { + return; + } + + unsubscribe = client.orchestration.subscribeThread({ threadId: brandedThreadId }, (item) => { + if (disposed) { + return; + } + + const store = remoteEnvironmentStore.getState(); + + if (item.kind === "snapshot") { + store.setThreadDetail(key, item.snapshot.thread); + return; + } + + const current = store.threadDetailByKey[key]; + if (!current) { + return; + } + + const result = applyThreadDetailEvent(current, item.event); + if (result.kind === "updated") { + store.setThreadDetail(key, result.thread); + } else if (result.kind === "deleted") { + store.removeThreadDetail(key); + } + }); + } + + attach(); + + // If the client isn't available yet (still connecting), retry when the + // connection state changes via a simple polling interval that clears once + // attached. This avoids coupling to the connection listener API. + let retryTimer: ReturnType | null = null; + if (!unsubscribe) { + retryTimer = setInterval(() => { + if (disposed) { + if (retryTimer) clearInterval(retryTimer); + return; + } + if (unsubscribe) { + if (retryTimer) clearInterval(retryTimer); + return; + } + attach(); + if (unsubscribe && retryTimer) { + clearInterval(retryTimer); + retryTimer = null; + } + }, 500); + } + + return () => { + disposed = true; + if (retryTimer) clearInterval(retryTimer); + unsubscribe?.(); + remoteEnvironmentStore.getState().removeThreadDetail(key); + }; + }, [environmentId, threadId]); +} diff --git a/apps/mobile/src/state/use-thread-selection.ts b/apps/mobile/src/state/use-thread-selection.ts index 90024346ed..dba488701e 100644 --- a/apps/mobile/src/state/use-thread-selection.ts +++ b/apps/mobile/src/state/use-thread-selection.ts @@ -2,8 +2,10 @@ import { useCallback, useEffect, useMemo } from "react"; import type { SavedRemoteConnection } from "../lib/connection"; import type { ScopedMobileProject, ScopedMobileThread } from "../lib/scopedEntities"; +import { scopedThreadKey } from "../lib/scopedEntities"; import { useRemoteCatalog } from "./use-remote-catalog"; import { type EnvironmentRuntimeState } from "./remote-runtime-types"; +import { useRemoteEnvironmentStore } from "./remote-environment-store"; import { useRemoteEnvironmentState } from "./use-remote-environment-registry"; import { useThreadSelectionStore } from "./thread-selection-store"; @@ -48,10 +50,31 @@ export function useThreadSelection() { const selectThreadRef = useThreadSelectionStore((state) => state.selectThreadRef); const clearSelectedThreadRef = useThreadSelectionStore((state) => state.clearSelectedThreadRef); - const selectedThread = useMemo( - () => deriveSelectedThread(selectedThreadRef, threads), - [selectedThreadRef, threads], - ); + const threadDetailByKey = useRemoteEnvironmentStore((state) => state.threadDetailByKey); + + const selectedThread = useMemo(() => { + const shell = deriveSelectedThread(selectedThreadRef, threads); + if (!shell) { + return null; + } + + const key = scopedThreadKey(shell.environmentId, shell.id); + const detail = threadDetailByKey[key]; + if (!detail) { + return shell; + } + + return { + ...shell, + messages: detail.messages, + proposedPlans: detail.proposedPlans, + activities: detail.activities, + checkpoints: detail.checkpoints, + latestTurn: detail.latestTurn, + session: detail.session, + deletedAt: detail.deletedAt, + }; + }, [selectedThreadRef, threadDetailByKey, threads]); useEffect(() => { if (!selectedThreadRef || selectedThread) { diff --git a/apps/mobile/uniwind-types.d.ts b/apps/mobile/uniwind-types.d.ts index cc099419a9..14402dbcb4 100644 --- a/apps/mobile/uniwind-types.d.ts +++ b/apps/mobile/uniwind-types.d.ts @@ -1,10 +1,10 @@ // NOTE: This file is generated by uniwind and it should not be edited manually. /// -declare module 'uniwind' { - export interface UniwindConfig { - themes: readonly ['light', 'dark'] - } +declare module "uniwind" { + export interface UniwindConfig { + themes: readonly ["light", "dark"]; + } } -export {} +export {}; diff --git a/apps/web/src/rpc/protocol.ts b/apps/web/src/rpc/protocol.ts index 5c5c51d899..d4af10aad2 100644 --- a/apps/web/src/rpc/protocol.ts +++ b/apps/web/src/rpc/protocol.ts @@ -1,4 +1,9 @@ import { WsRpcGroup } from "@t3tools/contracts"; +import { + DEFAULT_RECONNECT_BACKOFF, + getReconnectDelayMs, + type WsProtocolLifecycleHandlers, +} from "@t3tools/client-runtime"; import { Duration, Effect, Layer, Schedule } from "effect"; import { RpcClient, RpcSerialization } from "effect/unstable/rpc"; import * as Socket from "effect/unstable/socket/Socket"; @@ -9,20 +14,13 @@ import { trackRpcRequestSent, } from "./requestLatencyState"; import { - getWsReconnectDelayMsForRetry, recordWsConnectionAttempt, recordWsConnectionClosed, recordWsConnectionErrored, recordWsConnectionOpened, - WS_RECONNECT_MAX_RETRIES, } from "./wsConnectionState"; -export interface WsProtocolLifecycleHandlers { - readonly onAttempt?: (socketUrl: string) => void; - readonly onOpen?: () => void; - readonly onError?: (message: string) => void; - readonly onClose?: (details: { readonly code: number; readonly reason: string }) => void; -} +export type { WsProtocolLifecycleHandlers }; export const makeWsRpcProtocolClient = RpcClient.make(WsRpcGroup); type RpcClientFactory = typeof makeWsRpcProtocolClient; @@ -142,8 +140,9 @@ export function createWsRpcProtocolLayer( const socketLayer = Socket.layerWebSocket(resolvedUrl).pipe( Layer.provide(trackingWebSocketConstructorLayer), ); - const retryPolicy = Schedule.addDelay(Schedule.recurs(WS_RECONNECT_MAX_RETRIES), (retryCount) => - Effect.succeed(Duration.millis(getWsReconnectDelayMsForRetry(retryCount) ?? 0)), + const retryPolicy = Schedule.addDelay( + Schedule.recurs(DEFAULT_RECONNECT_BACKOFF.maxRetries!), + (retryCount) => Effect.succeed(Duration.millis(getReconnectDelayMs(retryCount) ?? 0)), ); const protocolLayer = Layer.effect( RpcClient.Protocol, diff --git a/apps/web/src/rpc/transportError.ts b/apps/web/src/rpc/transportError.ts index edc90a5a3c..649d06f3a7 100644 --- a/apps/web/src/rpc/transportError.ts +++ b/apps/web/src/rpc/transportError.ts @@ -1,23 +1,4 @@ -const TRANSPORT_ERROR_PATTERNS = [ - /\bSocketCloseError\b/i, - /\bSocketOpenError\b/i, - /Unable to connect to the T3 server WebSocket\./i, - /\bping timeout\b/i, -] as const; - -export function isTransportConnectionErrorMessage(message: string | null | undefined): boolean { - if (typeof message !== "string") { - return false; - } - - const normalizedMessage = message.trim(); - if (normalizedMessage.length === 0) { - return false; - } - - return TRANSPORT_ERROR_PATTERNS.some((pattern) => pattern.test(normalizedMessage)); -} - -export function sanitizeThreadErrorMessage(message: string | null | undefined): string | null { - return isTransportConnectionErrorMessage(message) ? null : (message ?? null); -} +export { + isTransportConnectionErrorMessage, + sanitizeThreadErrorMessage, +} from "@t3tools/client-runtime"; diff --git a/apps/web/src/rpc/wsConnectionState.ts b/apps/web/src/rpc/wsConnectionState.ts index d3050a2b4c..97bec9c90f 100644 --- a/apps/web/src/rpc/wsConnectionState.ts +++ b/apps/web/src/rpc/wsConnectionState.ts @@ -1,4 +1,5 @@ import { useAtomValue } from "@effect/atom-react"; +import { DEFAULT_RECONNECT_BACKOFF, getReconnectDelayMs } from "@t3tools/client-runtime"; import { Atom } from "effect/unstable/reactivity"; import { appAtomRegistry } from "./atomRegistry"; @@ -6,10 +7,10 @@ import { appAtomRegistry } from "./atomRegistry"; export type WsConnectionUiState = "connected" | "connecting" | "error" | "offline" | "reconnecting"; export type WsReconnectPhase = "attempting" | "exhausted" | "idle" | "waiting"; -export const WS_RECONNECT_INITIAL_DELAY_MS = 1_000; -export const WS_RECONNECT_BACKOFF_FACTOR = 2; -export const WS_RECONNECT_MAX_DELAY_MS = 64_000; -export const WS_RECONNECT_MAX_RETRIES = 7; +export const WS_RECONNECT_INITIAL_DELAY_MS = DEFAULT_RECONNECT_BACKOFF.initialDelayMs; +export const WS_RECONNECT_BACKOFF_FACTOR = DEFAULT_RECONNECT_BACKOFF.backoffFactor; +export const WS_RECONNECT_MAX_DELAY_MS = DEFAULT_RECONNECT_BACKOFF.maxDelayMs; +export const WS_RECONNECT_MAX_RETRIES = DEFAULT_RECONNECT_BACKOFF.maxRetries!; export const WS_RECONNECT_MAX_ATTEMPTS = WS_RECONNECT_MAX_RETRIES + 1; export interface WsConnectionStatus { @@ -158,14 +159,7 @@ export function useWsConnectionStatus(): WsConnectionStatus { } export function getWsReconnectDelayMsForRetry(retryIndex: number): number | null { - if (!Number.isInteger(retryIndex) || retryIndex < 0 || retryIndex >= WS_RECONNECT_MAX_RETRIES) { - return null; - } - - return Math.min( - Math.round(WS_RECONNECT_INITIAL_DELAY_MS * WS_RECONNECT_BACKOFF_FACTOR ** retryIndex), - WS_RECONNECT_MAX_DELAY_MS, - ); + return getReconnectDelayMs(retryIndex); } function applyDisconnectState( diff --git a/apps/web/src/rpc/wsRpcClient.ts b/apps/web/src/rpc/wsRpcClient.ts index 42c2c64bd0..a7bd0236b5 100644 --- a/apps/web/src/rpc/wsRpcClient.ts +++ b/apps/web/src/rpc/wsRpcClient.ts @@ -9,6 +9,7 @@ import { type ServerSettingsPatch, WS_METHODS, } from "@t3tools/contracts"; +import type { WsRpcClient } from "@t3tools/client-runtime"; import { applyGitStatusStreamEvent } from "@t3tools/shared/git"; import { Effect, Stream } from "effect"; @@ -16,107 +17,7 @@ import { type WsRpcProtocolClient } from "./protocol"; import { resetWsReconnectBackoff } from "./wsConnectionState"; import { WsTransport } from "./wsTransport"; -type RpcTag = keyof WsRpcProtocolClient & string; -type RpcMethod = WsRpcProtocolClient[TTag]; -type RpcInput = Parameters>[0]; - -interface StreamSubscriptionOptions { - readonly onResubscribe?: () => void; -} - -type RpcUnaryMethod = - RpcMethod extends (input: any, options?: any) => Effect.Effect - ? (input: RpcInput) => Promise - : never; - -type RpcUnaryNoArgMethod = - RpcMethod extends (input: any, options?: any) => Effect.Effect - ? () => Promise - : never; - -type RpcStreamMethod = - RpcMethod extends (input: any, options?: any) => Stream.Stream - ? (listener: (event: TEvent) => void, options?: StreamSubscriptionOptions) => () => void - : never; - -type RpcInputStreamMethod = - RpcMethod extends (input: any, options?: any) => Stream.Stream - ? ( - input: RpcInput, - listener: (event: TEvent) => void, - options?: StreamSubscriptionOptions, - ) => () => void - : never; - -interface GitRunStackedActionOptions { - readonly onProgress?: (event: GitActionProgressEvent) => void; -} - -export interface WsRpcClient { - readonly dispose: () => Promise; - readonly reconnect: () => Promise; - readonly terminal: { - readonly open: RpcUnaryMethod; - readonly write: RpcUnaryMethod; - readonly resize: RpcUnaryMethod; - readonly clear: RpcUnaryMethod; - readonly restart: RpcUnaryMethod; - readonly close: RpcUnaryMethod; - readonly onEvent: RpcStreamMethod; - }; - readonly projects: { - readonly searchEntries: RpcUnaryMethod; - readonly writeFile: RpcUnaryMethod; - }; - readonly shell: { - readonly openInEditor: (input: { - readonly cwd: Parameters[0]; - readonly editor: Parameters[1]; - }) => ReturnType; - }; - readonly git: { - readonly pull: RpcUnaryMethod; - readonly refreshStatus: RpcUnaryMethod; - readonly onStatus: ( - input: RpcInput, - listener: (status: GitStatusResult) => void, - options?: StreamSubscriptionOptions, - ) => () => void; - 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 - >; - }; - readonly server: { - readonly getConfig: RpcUnaryNoArgMethod; - readonly refreshProviders: RpcUnaryNoArgMethod; - readonly upsertKeybinding: RpcUnaryMethod; - readonly getSettings: RpcUnaryNoArgMethod; - readonly updateSettings: ( - patch: ServerSettingsPatch, - ) => ReturnType>; - readonly subscribeConfig: RpcStreamMethod; - readonly subscribeLifecycle: RpcStreamMethod; - readonly subscribeAuthAccess: RpcStreamMethod; - }; - readonly orchestration: { - readonly dispatchCommand: RpcUnaryMethod; - readonly getTurnDiff: RpcUnaryMethod; - readonly getFullThreadDiff: RpcUnaryMethod; - readonly subscribeShell: RpcStreamMethod; - readonly subscribeThread: RpcInputStreamMethod; - }; -} +export type { WsRpcClient }; export function createWsRpcClient(transport: WsTransport): WsRpcClient { return { diff --git a/bun.lock b/bun.lock index a87c77e855..8932d47fee 100644 --- a/bun.lock +++ b/bun.lock @@ -48,7 +48,7 @@ "@effect/atom-react": "catalog:", "@expo-google-fonts/dm-sans": "^0.4.2", "@gorhom/bottom-sheet": "^5", - "@legendapp/list": "^3.0.0-beta.44", + "@legendapp/list": "3.0.0-beta.44", "@react-native-menu/menu": "^2.0.0", "@sethwebster/react-ethereal-input": "^0.4.0", "@shopify/flash-list": "2.0.2", @@ -186,6 +186,7 @@ "version": "0.0.0-alpha.1", "dependencies": { "@t3tools/contracts": "workspace:*", + "@t3tools/shared": "workspace:*", "effect": "catalog:", }, "devDependencies": { diff --git a/packages/client-runtime/package.json b/packages/client-runtime/package.json index c8bce1ad97..65ddccf9ac 100644 --- a/packages/client-runtime/package.json +++ b/packages/client-runtime/package.json @@ -21,6 +21,7 @@ }, "dependencies": { "@t3tools/contracts": "workspace:*", + "@t3tools/shared": "workspace:*", "effect": "catalog:" }, "devDependencies": { diff --git a/packages/client-runtime/src/environmentConnection.ts b/packages/client-runtime/src/environmentConnection.ts index 01eef725ed..385a816c63 100644 --- a/packages/client-runtime/src/environmentConnection.ts +++ b/packages/client-runtime/src/environmentConnection.ts @@ -1,48 +1,15 @@ import type { EnvironmentId, - OrchestrationEvent, - OrchestrationReadModel, + OrchestrationShellSnapshot, + OrchestrationShellStreamEvent, ServerConfig, ServerLifecycleWelcomePayload, TerminalEvent, } from "@t3tools/contracts"; -import * as Arr from "effect/Array"; -import * as Order from "effect/Order"; -import * as Option from "effect/Option"; -import { pipe } from "effect/Function"; import type { KnownEnvironment } from "./knownEnvironment"; import type { WsRpcClient } from "./wsRpcClient"; -type OrchestrationRecoveryReason = "bootstrap" | "replay-failed" | "resubscribe" | "sequence-gap"; - -interface OrchestrationRecoveryPhase { - readonly kind: "snapshot" | "replay"; - readonly reason: OrchestrationRecoveryReason; -} - -interface OrchestrationRecoveryState { - readonly latestSequence: number; - readonly highestObservedSequence: number; - readonly bootstrapped: boolean; - readonly pendingReplay: boolean; - readonly inFlight: OrchestrationRecoveryPhase | null; -} - -interface ReplayRecoveryCompletion { - readonly replayMadeProgress: boolean; - readonly shouldReplay: boolean; -} - -interface ReplayRetryTracker { - readonly attempts: number; - readonly latestSequence: number; - readonly highestObservedSequence: number; -} - -const REPLAY_RECOVERY_RETRY_DELAY_MS = 100; -const MAX_NO_PROGRESS_REPLAY_RETRIES = 3; - export interface EnvironmentConnection { readonly kind: "primary" | "saved"; readonly environmentId: EnvironmentId; @@ -54,11 +21,14 @@ export interface EnvironmentConnection { } interface OrchestrationHandlers { - readonly applyEventBatch: ( - events: ReadonlyArray, + readonly applyShellEvent: ( + event: OrchestrationShellStreamEvent, + environmentId: EnvironmentId, + ) => void; + readonly syncShellSnapshot: ( + snapshot: OrchestrationShellSnapshot, environmentId: EnvironmentId, ) => void; - readonly syncSnapshot: (snapshot: OrchestrationReadModel, environmentId: EnvironmentId) => void; readonly applyTerminalEvent: (event: TerminalEvent, environmentId: EnvironmentId) => void; } @@ -71,273 +41,9 @@ interface EnvironmentConnectionInput extends OrchestrationHandlers { readonly onWelcome?: (payload: ServerLifecycleWelcomePayload) => void; } -function createOrchestrationRecoveryCoordinator() { - let state: OrchestrationRecoveryState = { - latestSequence: 0, - highestObservedSequence: 0, - bootstrapped: false, - pendingReplay: false, - inFlight: null, - }; - let replayStartSequence: number | null = null; - - const snapshotState = (): OrchestrationRecoveryState => ({ - ...state, - ...(state.inFlight ? { inFlight: { ...state.inFlight } } : {}), - }); - - const observeSequence = (sequence: number) => { - state = { - ...state, - highestObservedSequence: Math.max(state.highestObservedSequence, sequence), - }; - }; - - const resolveReplayNeedAfterRecovery = () => { - const pendingReplayBeforeReset = state.pendingReplay; - const observedAhead = state.highestObservedSequence > state.latestSequence; - const shouldReplay = pendingReplayBeforeReset || observedAhead; - state = { - ...state, - pendingReplay: false, - }; - return { - shouldReplay, - pendingReplayBeforeReset, - observedAhead, - }; - }; - - return { - getState(): OrchestrationRecoveryState { - return snapshotState(); - }, - - classifyDomainEvent(sequence: number): "ignore" | "defer" | "recover" | "apply" { - observeSequence(sequence); - if (sequence <= state.latestSequence) { - return "ignore"; - } - - if (!state.bootstrapped || state.inFlight) { - state = { - ...state, - pendingReplay: true, - }; - return "defer"; - } - - if (sequence !== state.latestSequence + 1) { - state = { - ...state, - pendingReplay: true, - }; - return "recover"; - } - - return "apply"; - }, - - markEventBatchApplied>( - events: ReadonlyArray, - ): ReadonlyArray { - const nextEvents = pipe( - events, - Arr.filter((event) => event.sequence > state.latestSequence), - Arr.sortWith((event) => event.sequence, Order.Number), - ); - if (nextEvents.length === 0) { - return []; - } - - const latestSequence = Arr.last(nextEvents).pipe( - Option.map((event) => event.sequence), - Option.getOrElse(() => state.latestSequence), - ); - - state = { - ...state, - latestSequence, - highestObservedSequence: Math.max(state.highestObservedSequence, latestSequence), - }; - return nextEvents; - }, - - beginSnapshotRecovery(reason: OrchestrationRecoveryReason): boolean { - if (state.inFlight?.kind === "snapshot" || state.inFlight?.kind === "replay") { - state = { - ...state, - pendingReplay: true, - }; - return false; - } - - state = { - ...state, - inFlight: { kind: "snapshot", reason }, - }; - return true; - }, - - completeSnapshotRecovery(snapshotSequence: number): boolean { - state = { - ...state, - latestSequence: Math.max(state.latestSequence, snapshotSequence), - highestObservedSequence: Math.max( - state.highestObservedSequence, - Math.max(state.latestSequence, snapshotSequence), - ), - bootstrapped: true, - inFlight: null, - }; - return resolveReplayNeedAfterRecovery().shouldReplay; - }, - - failSnapshotRecovery() { - state = { - ...state, - inFlight: null, - }; - }, - - beginReplayRecovery(reason: OrchestrationRecoveryReason): boolean { - if (!state.bootstrapped || state.inFlight?.kind === "snapshot") { - state = { - ...state, - pendingReplay: true, - }; - return false; - } - - state = { - ...state, - pendingReplay: false, - inFlight: { kind: "replay", reason }, - }; - replayStartSequence = state.latestSequence; - return true; - }, - - completeReplayRecovery(): ReplayRecoveryCompletion { - const replayMadeProgress = - replayStartSequence !== null && state.latestSequence > replayStartSequence; - replayStartSequence = null; - state = { - ...state, - inFlight: null, - }; - const replayResolution = resolveReplayNeedAfterRecovery(); - return { - replayMadeProgress, - shouldReplay: replayResolution.shouldReplay, - }; - }, - - failReplayRecovery() { - state = { - ...state, - bootstrapped: false, - inFlight: null, - }; - replayStartSequence = null; - }, - }; -} - -function deriveReplayRetryDecision(input: { - readonly previousTracker: ReplayRetryTracker | null; - readonly completion: ReplayRecoveryCompletion; - readonly recoveryState: Pick< - OrchestrationRecoveryState, - "latestSequence" | "highestObservedSequence" - >; - readonly baseDelayMs: number; - readonly maxNoProgressRetries: number; -}): { - readonly shouldRetry: boolean; - readonly delayMs: number; - readonly tracker: ReplayRetryTracker | null; -} { - if (!input.completion.shouldReplay) { - return { - shouldRetry: false, - delayMs: 0, - tracker: null, - }; - } - - if (input.completion.replayMadeProgress) { - return { - shouldRetry: true, - delayMs: 0, - tracker: null, - }; - } - - const previousTracker = input.previousTracker; - const sameFrontier = - previousTracker !== null && - previousTracker.latestSequence === input.recoveryState.latestSequence && - previousTracker.highestObservedSequence === input.recoveryState.highestObservedSequence; - - const attempts = sameFrontier && previousTracker !== null ? previousTracker.attempts + 1 : 1; - if (attempts > input.maxNoProgressRetries) { - return { - shouldRetry: false, - delayMs: 0, - tracker: null, - }; - } - - return { - shouldRetry: true, - delayMs: input.baseDelayMs * 2 ** (attempts - 1), - tracker: { - attempts, - latestSequence: input.recoveryState.latestSequence, - highestObservedSequence: input.recoveryState.highestObservedSequence, - }, - }; -} - -function createSnapshotBootstrapController(input: { - readonly isBootstrapped: () => boolean; - readonly runSnapshotRecovery: ( - reason: Extract, - ) => Promise; -}) { - let inFlight: Promise | null = null; - - return { - ensureSnapshotRecovery( - reason: Extract, - ): Promise { - if (input.isBootstrapped()) { - return Promise.resolve(); - } - - if (inFlight !== null) { - return inFlight; - } - - const nextInFlight = input.runSnapshotRecovery(reason).finally(() => { - if (inFlight === nextInFlight) { - inFlight = null; - } - }); - inFlight = nextInFlight; - return nextInFlight; - }, - }; -} - export function createEnvironmentConnection( input: EnvironmentConnectionInput, ): EnvironmentConnection { - const recovery = createOrchestrationRecoveryCoordinator(); - let replayRetryTracker: ReplayRetryTracker | null = null; - const pendingDomainEvents: OrchestrationEvent[] = []; - let flushPendingDomainEventsScheduled = false; const environmentId = input.knownEnvironment.environmentId; if (!environmentId) { @@ -347,6 +53,19 @@ export function createEnvironmentConnection( } let disposed = false; + let bootstrapped = false; + let bootstrapResolve: (() => void) | null = null; + let bootstrapPromise: Promise | null = null; + + const resetBootstrapGate = () => { + bootstrapped = false; + bootstrapPromise = new Promise((resolve) => { + bootstrapResolve = resolve; + }); + }; + + // Initialize the bootstrap gate so ensureBootstrapped can await it. + resetBootstrapGate(); const observeEnvironmentIdentity = (nextEnvironmentId: EnvironmentId, source: string) => { if (environmentId !== nextEnvironmentId) { @@ -356,110 +75,6 @@ export function createEnvironmentConnection( } }; - const flushPendingDomainEvents = () => { - flushPendingDomainEventsScheduled = false; - if (disposed || pendingDomainEvents.length === 0) { - return; - } - - const events = pendingDomainEvents.splice(0, pendingDomainEvents.length); - const nextEvents = recovery.markEventBatchApplied(events); - if (nextEvents.length === 0) { - return; - } - - input.applyEventBatch(nextEvents, environmentId); - }; - - const schedulePendingDomainEventFlush = () => { - if (flushPendingDomainEventsScheduled) { - return; - } - - flushPendingDomainEventsScheduled = true; - queueMicrotask(flushPendingDomainEvents); - }; - - const runReplayRecovery = async ( - reason: Extract, - ): Promise => { - if (!recovery.beginReplayRecovery(reason)) { - return; - } - - const fromSequenceExclusive = recovery.getState().latestSequence; - try { - const events = await input.client.orchestration.replayEvents({ fromSequenceExclusive }); - if (!disposed) { - const nextEvents = recovery.markEventBatchApplied(events); - if (nextEvents.length > 0) { - input.applyEventBatch(nextEvents, environmentId); - } - } - } catch { - replayRetryTracker = null; - recovery.failReplayRecovery(); - await snapshotBootstrap.ensureSnapshotRecovery("replay-failed"); - return; - } - - if (disposed) { - return; - } - - const replayCompletion = recovery.completeReplayRecovery(); - const retryDecision = deriveReplayRetryDecision({ - previousTracker: replayRetryTracker, - completion: replayCompletion, - recoveryState: recovery.getState(), - baseDelayMs: REPLAY_RECOVERY_RETRY_DELAY_MS, - maxNoProgressRetries: MAX_NO_PROGRESS_REPLAY_RETRIES, - }); - replayRetryTracker = retryDecision.tracker; - - if (!retryDecision.shouldRetry) { - return; - } - - if (retryDecision.delayMs > 0) { - await new Promise((resolve) => { - setTimeout(resolve, retryDecision.delayMs); - }); - if (disposed) { - return; - } - } - - void runReplayRecovery(reason); - }; - - const runSnapshotRecovery = async ( - reason: Extract, - ): Promise => { - const started = recovery.beginSnapshotRecovery(reason); - if (!started) { - return; - } - - try { - const snapshot = await input.client.orchestration.getSnapshot(); - if (!disposed) { - input.syncSnapshot(snapshot, environmentId); - if (recovery.completeSnapshotRecovery(snapshot.snapshotSequence)) { - void runReplayRecovery("sequence-gap"); - } - } - } catch (error) { - recovery.failSnapshotRecovery(); - throw error; - } - }; - - const snapshotBootstrap = createSnapshotBootstrapController({ - isBootstrapped: () => recovery.getState().bootstrapped, - runSnapshotRecovery, - }); - const unsubLifecycle = input.client.server.subscribeLifecycle((event) => { if (event.type !== "welcome") { return; @@ -478,21 +93,21 @@ export function createEnvironmentConnection( input.onConfigSnapshot?.(event.config); }); - const unsubDomainEvent = input.client.orchestration.onDomainEvent( - (event) => { - const action = recovery.classifyDomainEvent(event.sequence); - if (action === "apply") { - pendingDomainEvents.push(event); - schedulePendingDomainEventFlush(); + const unsubShell = input.client.orchestration.subscribeShell( + (item) => { + if (disposed) { return; } - if (action === "ignore" || action === "defer") { + if (item.kind === "snapshot") { + input.syncShellSnapshot(item.snapshot, environmentId); + bootstrapped = true; + bootstrapResolve?.(); + bootstrapResolve = null; return; } - flushPendingDomainEvents(); - void runReplayRecovery("sequence-gap"); + input.applyShellEvent(item, environmentId); }, { onResubscribe: () => { @@ -500,8 +115,9 @@ export function createEnvironmentConnection( return; } - flushPendingDomainEvents(); - void runReplayRecovery("resubscribe"); + // The server will re-emit a snapshot on resubscribe, so reset the + // bootstrap gate so reconnect callers can await the fresh snapshot. + resetBootstrapGate(); }, }, ); @@ -510,13 +126,9 @@ export function createEnvironmentConnection( input.applyTerminalEvent(event, environmentId); }); - void snapshotBootstrap.ensureSnapshotRecovery("bootstrap").catch(() => undefined); - const cleanup = () => { disposed = true; - flushPendingDomainEventsScheduled = false; - pendingDomainEvents.length = 0; - unsubDomainEvent(); + unsubShell(); unsubTerminalEvent(); unsubLifecycle(); unsubConfig(); @@ -527,11 +139,20 @@ export function createEnvironmentConnection( environmentId, knownEnvironment: input.knownEnvironment, client: input.client, - ensureBootstrapped: () => snapshotBootstrap.ensureSnapshotRecovery("bootstrap"), + ensureBootstrapped: () => { + if (bootstrapped) { + return Promise.resolve(); + } + return bootstrapPromise ?? Promise.resolve(); + }, reconnect: async () => { await input.client.reconnect(); await input.refreshMetadata?.(); - await snapshotBootstrap.ensureSnapshotRecovery("bootstrap"); + // After reconnect the shell subscription's onResubscribe fires, which + // resets the bootstrap gate. Wait for the server to push a fresh snapshot. + if (bootstrapPromise) { + await bootstrapPromise; + } }, dispose: async () => { cleanup(); diff --git a/packages/client-runtime/src/index.ts b/packages/client-runtime/src/index.ts index 45ae7e2f4d..d9519f0741 100644 --- a/packages/client-runtime/src/index.ts +++ b/packages/client-runtime/src/index.ts @@ -1,9 +1,13 @@ export * from "./knownEnvironment"; +export * from "./reconnectBackoff"; export * from "./scoped"; +export * from "./shellSnapshotReducer"; +export * from "./threadDetailReducer"; export * from "./gitActions"; export * from "./gitActionState"; export * from "./gitBranchState"; export * from "./gitStatusState"; +export * from "./transportError"; export * from "./wsRpcProtocol"; export * from "./wsTransport"; export * from "./wsRpcClient"; diff --git a/packages/client-runtime/src/reconnectBackoff.test.ts b/packages/client-runtime/src/reconnectBackoff.test.ts new file mode 100644 index 0000000000..66047c16ae --- /dev/null +++ b/packages/client-runtime/src/reconnectBackoff.test.ts @@ -0,0 +1,65 @@ +import { describe, expect, it } from "vitest"; + +import { + DEFAULT_RECONNECT_BACKOFF, + getReconnectDelayMs, + type ReconnectBackoffConfig, +} from "./reconnectBackoff"; + +describe("getReconnectDelayMs", () => { + it("returns exponential delays with default config", () => { + expect(getReconnectDelayMs(0)).toBe(1_000); + expect(getReconnectDelayMs(1)).toBe(2_000); + expect(getReconnectDelayMs(2)).toBe(4_000); + expect(getReconnectDelayMs(3)).toBe(8_000); + expect(getReconnectDelayMs(4)).toBe(16_000); + expect(getReconnectDelayMs(5)).toBe(32_000); + expect(getReconnectDelayMs(6)).toBe(64_000); + }); + + it("returns null when retry index exceeds maxRetries", () => { + expect(getReconnectDelayMs(7)).toBeNull(); + expect(getReconnectDelayMs(100)).toBeNull(); + }); + + it("returns null for negative indices", () => { + expect(getReconnectDelayMs(-1)).toBeNull(); + }); + + it("returns null for non-integer indices", () => { + expect(getReconnectDelayMs(1.5)).toBeNull(); + }); + + it("caps delay at maxDelayMs", () => { + const config: ReconnectBackoffConfig = { + initialDelayMs: 10_000, + backoffFactor: 10, + maxDelayMs: 30_000, + maxRetries: 5, + }; + + expect(getReconnectDelayMs(0, config)).toBe(10_000); + expect(getReconnectDelayMs(1, config)).toBe(30_000); // 100_000 capped to 30_000 + expect(getReconnectDelayMs(2, config)).toBe(30_000); // 1_000_000 capped to 30_000 + }); + + it("supports unlimited retries when maxRetries is null", () => { + const config: ReconnectBackoffConfig = { + ...DEFAULT_RECONNECT_BACKOFF, + maxRetries: null, + }; + + expect(getReconnectDelayMs(0, config)).toBe(1_000); + expect(getReconnectDelayMs(50, config)).toBe(64_000); // capped at maxDelayMs + expect(getReconnectDelayMs(100, config)).toBe(64_000); + }); +}); + +describe("DEFAULT_RECONNECT_BACKOFF", () => { + it("has sensible defaults", () => { + expect(DEFAULT_RECONNECT_BACKOFF.initialDelayMs).toBe(1_000); + expect(DEFAULT_RECONNECT_BACKOFF.backoffFactor).toBe(2); + expect(DEFAULT_RECONNECT_BACKOFF.maxDelayMs).toBe(64_000); + expect(DEFAULT_RECONNECT_BACKOFF.maxRetries).toBe(7); + }); +}); diff --git a/packages/client-runtime/src/reconnectBackoff.ts b/packages/client-runtime/src/reconnectBackoff.ts new file mode 100644 index 0000000000..4f7ddd15a5 --- /dev/null +++ b/packages/client-runtime/src/reconnectBackoff.ts @@ -0,0 +1,47 @@ +/** + * Configuration for exponential reconnect backoff. + */ +export interface ReconnectBackoffConfig { + /** Base delay in milliseconds before the first retry. */ + readonly initialDelayMs: number; + /** Multiplier applied per retry (exponential factor). */ + readonly backoffFactor: number; + /** Hard upper bound on delay in milliseconds. */ + readonly maxDelayMs: number; + /** Maximum number of retries (0-based). `null` means unlimited. */ + readonly maxRetries: number | null; +} + +/** + * Sensible defaults for WebSocket reconnect backoff. + * + * - 1 s initial delay, doubling each retry, capped at 64 s, up to 7 retries. + */ +export const DEFAULT_RECONNECT_BACKOFF: ReconnectBackoffConfig = { + initialDelayMs: 1_000, + backoffFactor: 2, + maxDelayMs: 64_000, + maxRetries: 7, +}; + +/** + * Calculate the reconnect delay for a given retry index using exponential + * backoff. Returns `null` when `retryIndex` exceeds the configured maximum. + */ +export function getReconnectDelayMs( + retryIndex: number, + config: ReconnectBackoffConfig = DEFAULT_RECONNECT_BACKOFF, +): number | null { + if (!Number.isInteger(retryIndex) || retryIndex < 0) { + return null; + } + + if (config.maxRetries !== null && retryIndex >= config.maxRetries) { + return null; + } + + return Math.min( + Math.round(config.initialDelayMs * config.backoffFactor ** retryIndex), + config.maxDelayMs, + ); +} diff --git a/packages/client-runtime/src/shellSnapshotReducer.test.ts b/packages/client-runtime/src/shellSnapshotReducer.test.ts new file mode 100644 index 0000000000..c1da3851e4 --- /dev/null +++ b/packages/client-runtime/src/shellSnapshotReducer.test.ts @@ -0,0 +1,163 @@ +import { describe, expect, it } from "vitest"; + +import { ProjectId, ThreadId } from "@t3tools/contracts"; +import type { OrchestrationShellSnapshot, OrchestrationShellStreamEvent } from "@t3tools/contracts"; + +import { applyShellStreamEvent } from "./shellSnapshotReducer"; + +const baseSnapshot: OrchestrationShellSnapshot = { + snapshotSequence: 0, + projects: [], + threads: [], + updatedAt: "2026-04-01T00:00:00.000Z", +}; + +const stubProject = { + id: ProjectId.make("project-1"), + title: "Test Project", + workspaceRoot: "/workspace/test", + repositoryIdentity: null, + defaultModelSelection: null, + scripts: [], + createdAt: "2026-04-01T00:00:00.000Z", + updatedAt: "2026-04-01T00:00:00.000Z", +} as const; + +const stubThread = { + id: ThreadId.make("thread-1"), + projectId: ProjectId.make("project-1"), + title: "Test Thread", + modelSelection: { provider: "codex", model: "gpt-5.4" }, + runtimeMode: "full-access" as const, + interactionMode: "default" as const, + branch: null, + worktreePath: null, + latestTurn: null, + createdAt: "2026-04-01T00:00:00.000Z", + updatedAt: "2026-04-01T00:00:00.000Z", + archivedAt: null, + latestUserMessageAt: null, + hasPendingApprovals: false, + hasPendingUserInput: false, + hasActionableProposedPlan: false, + session: null, +} as const; + +describe("applyShellStreamEvent", () => { + describe("project-upserted", () => { + it("adds a new project", () => { + const event: OrchestrationShellStreamEvent = { + kind: "project-upserted", + sequence: 1, + project: stubProject, + }; + + const next = applyShellStreamEvent(baseSnapshot, event); + + expect(next.projects).toHaveLength(1); + expect(next.projects[0]?.id).toBe("project-1"); + expect(next.snapshotSequence).toBe(1); + }); + + it("updates an existing project", () => { + const snapshotWithProject: OrchestrationShellSnapshot = { + ...baseSnapshot, + projects: [stubProject], + }; + + const updatedProject = { ...stubProject, title: "Updated Title" }; + const event: OrchestrationShellStreamEvent = { + kind: "project-upserted", + sequence: 2, + project: updatedProject, + }; + + const next = applyShellStreamEvent(snapshotWithProject, event); + + expect(next.projects).toHaveLength(1); + expect(next.projects[0]?.title).toBe("Updated Title"); + expect(next.snapshotSequence).toBe(2); + }); + }); + + describe("project-removed", () => { + it("removes a project by id", () => { + const snapshotWithProject: OrchestrationShellSnapshot = { + ...baseSnapshot, + projects: [stubProject], + }; + + const event: OrchestrationShellStreamEvent = { + kind: "project-removed", + sequence: 3, + projectId: ProjectId.make("project-1"), + }; + + const next = applyShellStreamEvent(snapshotWithProject, event); + + expect(next.projects).toHaveLength(0); + expect(next.snapshotSequence).toBe(3); + }); + }); + + describe("thread-upserted", () => { + it("adds a new thread", () => { + const event: OrchestrationShellStreamEvent = { + kind: "thread-upserted", + sequence: 4, + thread: stubThread, + }; + + const next = applyShellStreamEvent(baseSnapshot, event); + + expect(next.threads).toHaveLength(1); + expect(next.threads[0]?.id).toBe("thread-1"); + expect(next.snapshotSequence).toBe(4); + }); + + it("updates an existing thread", () => { + const snapshotWithThread: OrchestrationShellSnapshot = { + ...baseSnapshot, + threads: [stubThread], + }; + + const updatedThread = { ...stubThread, title: "Updated Thread" }; + const event: OrchestrationShellStreamEvent = { + kind: "thread-upserted", + sequence: 5, + thread: updatedThread, + }; + + const next = applyShellStreamEvent(snapshotWithThread, event); + + expect(next.threads).toHaveLength(1); + expect(next.threads[0]?.title).toBe("Updated Thread"); + }); + }); + + describe("thread-removed", () => { + it("removes a thread by id", () => { + const snapshotWithThread: OrchestrationShellSnapshot = { + ...baseSnapshot, + threads: [stubThread], + }; + + const event: OrchestrationShellStreamEvent = { + kind: "thread-removed", + sequence: 6, + threadId: ThreadId.make("thread-1"), + }; + + const next = applyShellStreamEvent(snapshotWithThread, event); + + expect(next.threads).toHaveLength(0); + expect(next.snapshotSequence).toBe(6); + }); + }); + + it("returns original snapshot for unrecognized event kinds", () => { + const unknownEvent = { kind: "unknown-future-event", sequence: 99 } as any; + const next = applyShellStreamEvent(baseSnapshot, unknownEvent); + expect(next).toBe(baseSnapshot); + }); +}); diff --git a/packages/client-runtime/src/shellSnapshotReducer.ts b/packages/client-runtime/src/shellSnapshotReducer.ts new file mode 100644 index 0000000000..abca5b3d40 --- /dev/null +++ b/packages/client-runtime/src/shellSnapshotReducer.ts @@ -0,0 +1,43 @@ +import type { OrchestrationShellSnapshot, OrchestrationShellStreamEvent } from "@t3tools/contracts"; + +/** + * Apply a single shell stream event to an existing snapshot, returning a new + * snapshot with the event's changes applied. This is a pure reducer that both + * web and mobile can use to keep their local shell snapshot in sync. + * + * Returns the original snapshot reference unchanged if the event is not + * recognized (forward-compatible). + */ +export function applyShellStreamEvent( + snapshot: OrchestrationShellSnapshot, + event: OrchestrationShellStreamEvent, +): OrchestrationShellSnapshot { + switch (event.kind) { + case "project-upserted": { + const projects = snapshot.projects.some((p) => p.id === event.project.id) + ? snapshot.projects.map((p) => (p.id === event.project.id ? event.project : p)) + : [...snapshot.projects, event.project]; + return { ...snapshot, projects, snapshotSequence: event.sequence }; + } + case "project-removed": + return { + ...snapshot, + projects: snapshot.projects.filter((p) => p.id !== event.projectId), + snapshotSequence: event.sequence, + }; + case "thread-upserted": { + const threads = snapshot.threads.some((t) => t.id === event.thread.id) + ? snapshot.threads.map((t) => (t.id === event.thread.id ? event.thread : t)) + : [...snapshot.threads, event.thread]; + return { ...snapshot, threads, snapshotSequence: event.sequence }; + } + case "thread-removed": + return { + ...snapshot, + threads: snapshot.threads.filter((t) => t.id !== event.threadId), + snapshotSequence: event.sequence, + }; + default: + return snapshot; + } +} diff --git a/packages/client-runtime/src/threadDetailReducer.test.ts b/packages/client-runtime/src/threadDetailReducer.test.ts new file mode 100644 index 0000000000..287177e22e --- /dev/null +++ b/packages/client-runtime/src/threadDetailReducer.test.ts @@ -0,0 +1,568 @@ +import { describe, expect, it } from "vitest"; + +import { + CheckpointRef, + CommandId, + EventId, + MessageId, + ProjectId, + ThreadId, + TurnId, +} from "@t3tools/contracts"; +import type { OrchestrationEvent, OrchestrationThread } from "@t3tools/contracts"; + +import { applyThreadDetailEvent } from "./threadDetailReducer"; + +const baseEventFields = { + eventId: EventId.make("event-1"), + commandId: null, + causationEventId: null, + correlationId: null, + metadata: {}, +} as const; + +const baseThread: OrchestrationThread = { + id: ThreadId.make("thread-1"), + projectId: ProjectId.make("project-1"), + title: "Test Thread", + modelSelection: { provider: "codex", model: "gpt-5.4" }, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + latestTurn: null, + createdAt: "2026-04-01T00:00:00.000Z", + updatedAt: "2026-04-01T00:00:00.000Z", + archivedAt: null, + deletedAt: null, + messages: [], + proposedPlans: [], + activities: [], + checkpoints: [], + session: null, +}; + +describe("applyThreadDetailEvent", () => { + describe("project events", () => { + it("returns unchanged for project.created", () => { + const result = applyThreadDetailEvent(baseThread, { + ...baseEventFields, + sequence: 1, + occurredAt: "2026-04-01T01:00:00.000Z", + aggregateKind: "project", + aggregateId: ProjectId.make("project-1"), + type: "project.created", + payload: { + projectId: ProjectId.make("project-1"), + title: "T3 Code", + workspaceRoot: "/repo", + repositoryIdentity: null, + defaultModelSelection: null, + scripts: [], + createdAt: "2026-04-01T01:00:00.000Z", + updatedAt: "2026-04-01T01:00:00.000Z", + deletedAt: null, + }, + } as any); + expect(result.kind).toBe("unchanged"); + }); + }); + + describe("thread.created", () => { + it("creates a fresh thread", () => { + const result = applyThreadDetailEvent(baseThread, { + ...baseEventFields, + sequence: 1, + occurredAt: "2026-04-01T01:00:00.000Z", + aggregateKind: "thread", + aggregateId: ThreadId.make("thread-2"), + type: "thread.created", + payload: { + threadId: ThreadId.make("thread-2"), + projectId: ProjectId.make("project-1"), + title: "New Thread", + modelSelection: { provider: "codex", model: "gpt-5.4" }, + runtimeMode: "full-access", + interactionMode: "default", + branch: "main", + worktreePath: null, + createdAt: "2026-04-01T01:00:00.000Z", + updatedAt: "2026-04-01T01:00:00.000Z", + }, + }); + + expect(result.kind).toBe("updated"); + if (result.kind === "updated") { + expect(result.thread.id).toBe("thread-2"); + expect(result.thread.title).toBe("New Thread"); + expect(result.thread.branch).toBe("main"); + expect(result.thread.messages).toEqual([]); + expect(result.thread.session).toBeNull(); + } + }); + }); + + describe("thread.deleted", () => { + it("returns deleted signal", () => { + const result = applyThreadDetailEvent(baseThread, { + ...baseEventFields, + sequence: 2, + occurredAt: "2026-04-01T02:00:00.000Z", + aggregateKind: "thread", + aggregateId: ThreadId.make("thread-1"), + type: "thread.deleted", + payload: { + threadId: ThreadId.make("thread-1"), + deletedAt: "2026-04-01T02:00:00.000Z", + }, + }); + expect(result.kind).toBe("deleted"); + }); + }); + + describe("thread.archived / thread.unarchived", () => { + it("sets archivedAt", () => { + const result = applyThreadDetailEvent(baseThread, { + ...baseEventFields, + sequence: 3, + occurredAt: "2026-04-01T03:00:00.000Z", + aggregateKind: "thread", + aggregateId: ThreadId.make("thread-1"), + type: "thread.archived", + payload: { + threadId: ThreadId.make("thread-1"), + archivedAt: "2026-04-01T03:00:00.000Z", + updatedAt: "2026-04-01T03:00:00.000Z", + }, + }); + + expect(result.kind).toBe("updated"); + if (result.kind === "updated") { + expect(result.thread.archivedAt).toBe("2026-04-01T03:00:00.000Z"); + } + }); + + it("clears archivedAt", () => { + const archivedThread = { ...baseThread, archivedAt: "2026-04-01T03:00:00.000Z" }; + const result = applyThreadDetailEvent(archivedThread, { + ...baseEventFields, + sequence: 4, + occurredAt: "2026-04-01T04:00:00.000Z", + aggregateKind: "thread", + aggregateId: ThreadId.make("thread-1"), + type: "thread.unarchived", + payload: { + threadId: ThreadId.make("thread-1"), + updatedAt: "2026-04-01T04:00:00.000Z", + }, + }); + + expect(result.kind).toBe("updated"); + if (result.kind === "updated") { + expect(result.thread.archivedAt).toBeNull(); + } + }); + }); + + describe("thread.meta-updated", () => { + it("patches title and branch", () => { + const result = applyThreadDetailEvent(baseThread, { + ...baseEventFields, + sequence: 5, + occurredAt: "2026-04-01T05:00:00.000Z", + aggregateKind: "thread", + aggregateId: ThreadId.make("thread-1"), + type: "thread.meta-updated", + payload: { + threadId: ThreadId.make("thread-1"), + title: "Updated Title", + branch: "feature/demo", + updatedAt: "2026-04-01T05:00:00.000Z", + }, + }); + + expect(result.kind).toBe("updated"); + if (result.kind === "updated") { + expect(result.thread.title).toBe("Updated Title"); + expect(result.thread.branch).toBe("feature/demo"); + // Model selection should be unchanged since it wasn't in the payload + expect(result.thread.modelSelection).toEqual(baseThread.modelSelection); + } + }); + }); + + describe("thread.message-sent", () => { + it("appends a new message", () => { + const result = applyThreadDetailEvent(baseThread, { + ...baseEventFields, + sequence: 6, + occurredAt: "2026-04-01T06:00:00.000Z", + aggregateKind: "thread", + aggregateId: ThreadId.make("thread-1"), + type: "thread.message-sent", + payload: { + threadId: ThreadId.make("thread-1"), + messageId: MessageId.make("msg-1"), + role: "user", + text: "Hello, world!", + turnId: null, + streaming: false, + createdAt: "2026-04-01T06:00:00.000Z", + updatedAt: "2026-04-01T06:00:00.000Z", + }, + }); + + expect(result.kind).toBe("updated"); + if (result.kind === "updated") { + expect(result.thread.messages).toHaveLength(1); + expect(result.thread.messages[0]?.text).toBe("Hello, world!"); + } + }); + + it("appends text for streaming messages", () => { + const threadWithMessage: OrchestrationThread = { + ...baseThread, + messages: [ + { + id: MessageId.make("msg-2"), + role: "assistant", + text: "Hello", + turnId: TurnId.make("turn-1"), + streaming: true, + createdAt: "2026-04-01T06:00:00.000Z", + updatedAt: "2026-04-01T06:00:00.000Z", + }, + ], + }; + + const result = applyThreadDetailEvent(threadWithMessage, { + ...baseEventFields, + sequence: 7, + occurredAt: "2026-04-01T06:01:00.000Z", + aggregateKind: "thread", + aggregateId: ThreadId.make("thread-1"), + type: "thread.message-sent", + payload: { + threadId: ThreadId.make("thread-1"), + messageId: MessageId.make("msg-2"), + role: "assistant", + text: ", world!", + turnId: TurnId.make("turn-1"), + streaming: true, + createdAt: "2026-04-01T06:00:00.000Z", + updatedAt: "2026-04-01T06:01:00.000Z", + }, + }); + + expect(result.kind).toBe("updated"); + if (result.kind === "updated") { + expect(result.thread.messages).toHaveLength(1); + expect(result.thread.messages[0]?.text).toBe("Hello, world!"); + } + }); + + it("updates latestTurn for assistant messages with a turn", () => { + const result = applyThreadDetailEvent(baseThread, { + ...baseEventFields, + sequence: 8, + occurredAt: "2026-04-01T07:00:00.000Z", + aggregateKind: "thread", + aggregateId: ThreadId.make("thread-1"), + type: "thread.message-sent", + payload: { + threadId: ThreadId.make("thread-1"), + messageId: MessageId.make("msg-3"), + role: "assistant", + text: "Done.", + turnId: TurnId.make("turn-1"), + streaming: false, + createdAt: "2026-04-01T07:00:00.000Z", + updatedAt: "2026-04-01T07:00:00.000Z", + }, + }); + + expect(result.kind).toBe("updated"); + if (result.kind === "updated") { + expect(result.thread.latestTurn?.turnId).toBe("turn-1"); + expect(result.thread.latestTurn?.state).toBe("completed"); + expect(result.thread.latestTurn?.assistantMessageId).toBe("msg-3"); + } + }); + }); + + describe("thread.session-set", () => { + it("updates session and latestTurn for a running session", () => { + const result = applyThreadDetailEvent(baseThread, { + ...baseEventFields, + sequence: 9, + occurredAt: "2026-04-01T08:00:00.000Z", + aggregateKind: "thread", + aggregateId: ThreadId.make("thread-1"), + type: "thread.session-set", + payload: { + threadId: ThreadId.make("thread-1"), + session: { + threadId: ThreadId.make("thread-1"), + status: "running", + providerName: "codex", + runtimeMode: "full-access", + activeTurnId: TurnId.make("turn-1"), + lastError: null, + updatedAt: "2026-04-01T08:00:00.000Z", + }, + }, + }); + + expect(result.kind).toBe("updated"); + if (result.kind === "updated") { + expect(result.thread.session?.status).toBe("running"); + expect(result.thread.latestTurn?.turnId).toBe("turn-1"); + expect(result.thread.latestTurn?.state).toBe("running"); + } + }); + }); + + describe("thread.session-stop-requested", () => { + it("marks session as stopped", () => { + const threadWithSession: OrchestrationThread = { + ...baseThread, + session: { + threadId: ThreadId.make("thread-1"), + status: "running", + providerName: "codex", + runtimeMode: "full-access", + activeTurnId: TurnId.make("turn-1"), + lastError: null, + updatedAt: "2026-04-01T08:00:00.000Z", + }, + }; + + const result = applyThreadDetailEvent(threadWithSession, { + ...baseEventFields, + sequence: 10, + occurredAt: "2026-04-01T09:00:00.000Z", + aggregateKind: "thread", + aggregateId: ThreadId.make("thread-1"), + type: "thread.session-stop-requested", + payload: { + threadId: ThreadId.make("thread-1"), + createdAt: "2026-04-01T09:00:00.000Z", + }, + }); + + expect(result.kind).toBe("updated"); + if (result.kind === "updated") { + expect(result.thread.session?.status).toBe("stopped"); + expect(result.thread.session?.activeTurnId).toBeNull(); + } + }); + + it("returns unchanged when no session exists", () => { + const result = applyThreadDetailEvent(baseThread, { + ...baseEventFields, + sequence: 10, + occurredAt: "2026-04-01T09:00:00.000Z", + aggregateKind: "thread", + aggregateId: ThreadId.make("thread-1"), + type: "thread.session-stop-requested", + payload: { + threadId: ThreadId.make("thread-1"), + createdAt: "2026-04-01T09:00:00.000Z", + }, + }); + expect(result.kind).toBe("unchanged"); + }); + }); + + describe("thread.proposed-plan-upserted", () => { + it("adds a proposed plan", () => { + const result = applyThreadDetailEvent(baseThread, { + ...baseEventFields, + sequence: 11, + occurredAt: "2026-04-01T10:00:00.000Z", + aggregateKind: "thread", + aggregateId: ThreadId.make("thread-1"), + type: "thread.proposed-plan-upserted", + payload: { + threadId: ThreadId.make("thread-1"), + proposedPlan: { + id: "plan-1", + turnId: TurnId.make("turn-1"), + planMarkdown: "## Plan\n- Do stuff", + implementedAt: null, + implementationThreadId: null, + createdAt: "2026-04-01T10:00:00.000Z", + updatedAt: "2026-04-01T10:00:00.000Z", + }, + }, + }); + + expect(result.kind).toBe("updated"); + if (result.kind === "updated") { + expect(result.thread.proposedPlans).toHaveLength(1); + expect(result.thread.proposedPlans[0]?.id).toBe("plan-1"); + } + }); + }); + + describe("thread.activity-appended", () => { + it("adds an activity", () => { + const result = applyThreadDetailEvent(baseThread, { + ...baseEventFields, + sequence: 12, + occurredAt: "2026-04-01T11:00:00.000Z", + aggregateKind: "thread", + aggregateId: ThreadId.make("thread-1"), + type: "thread.activity-appended", + payload: { + threadId: ThreadId.make("thread-1"), + activity: { + id: EventId.make("activity-1"), + tone: "tool", + kind: "file-edit", + summary: "Edited src/index.ts", + payload: {}, + turnId: TurnId.make("turn-1"), + createdAt: "2026-04-01T11:00:00.000Z", + }, + }, + }); + + expect(result.kind).toBe("updated"); + if (result.kind === "updated") { + expect(result.thread.activities).toHaveLength(1); + expect(result.thread.activities[0]?.kind).toBe("file-edit"); + } + }); + }); + + describe("thread.turn-diff-completed", () => { + it("adds a checkpoint and updates latestTurn", () => { + const result = applyThreadDetailEvent(baseThread, { + ...baseEventFields, + sequence: 13, + occurredAt: "2026-04-01T12:00:00.000Z", + aggregateKind: "thread", + aggregateId: ThreadId.make("thread-1"), + type: "thread.turn-diff-completed", + payload: { + threadId: ThreadId.make("thread-1"), + turnId: TurnId.make("turn-1"), + checkpointTurnCount: 1, + checkpointRef: CheckpointRef.make("ref-1"), + status: "ready", + files: [], + assistantMessageId: MessageId.make("msg-3"), + completedAt: "2026-04-01T12:00:00.000Z", + }, + }); + + expect(result.kind).toBe("updated"); + if (result.kind === "updated") { + expect(result.thread.checkpoints).toHaveLength(1); + expect(result.thread.latestTurn?.turnId).toBe("turn-1"); + expect(result.thread.latestTurn?.state).toBe("completed"); + } + }); + }); + + describe("thread.reverted", () => { + it("filters entities to retained turns", () => { + const threadWithData: OrchestrationThread = { + ...baseThread, + messages: [ + { + id: MessageId.make("msg-1"), + role: "user", + text: "First", + turnId: null, + streaming: false, + createdAt: "2026-04-01T01:00:00.000Z", + updatedAt: "2026-04-01T01:00:00.000Z", + }, + { + id: MessageId.make("msg-2"), + role: "assistant", + text: "Response 1", + turnId: TurnId.make("turn-1"), + streaming: false, + createdAt: "2026-04-01T02:00:00.000Z", + updatedAt: "2026-04-01T02:00:00.000Z", + }, + { + id: MessageId.make("msg-3"), + role: "assistant", + text: "Response 2", + turnId: TurnId.make("turn-2"), + streaming: false, + createdAt: "2026-04-01T03:00:00.000Z", + updatedAt: "2026-04-01T03:00:00.000Z", + }, + ], + checkpoints: [ + { + turnId: TurnId.make("turn-1"), + checkpointTurnCount: 1, + checkpointRef: CheckpointRef.make("ref-1"), + status: "ready", + files: [], + assistantMessageId: MessageId.make("msg-2"), + completedAt: "2026-04-01T02:00:00.000Z", + }, + { + turnId: TurnId.make("turn-2"), + checkpointTurnCount: 2, + checkpointRef: CheckpointRef.make("ref-2"), + status: "ready", + files: [], + assistantMessageId: MessageId.make("msg-3"), + completedAt: "2026-04-01T03:00:00.000Z", + }, + ], + }; + + const result = applyThreadDetailEvent(threadWithData, { + ...baseEventFields, + sequence: 14, + occurredAt: "2026-04-01T04:00:00.000Z", + aggregateKind: "thread", + aggregateId: ThreadId.make("thread-1"), + type: "thread.reverted", + payload: { + threadId: ThreadId.make("thread-1"), + turnCount: 1, + }, + }); + + expect(result.kind).toBe("updated"); + if (result.kind === "updated") { + // turn-2 checkpoint is filtered out (turnCount 2 > revert target 1) + expect(result.thread.checkpoints).toHaveLength(1); + expect(result.thread.checkpoints[0]?.turnId).toBe("turn-1"); + // msg-3 (turn-2) is filtered, msg-1 (no turn) and msg-2 (turn-1) remain + expect(result.thread.messages).toHaveLength(2); + expect(result.thread.latestTurn?.turnId).toBe("turn-1"); + } + }); + }); + + describe("no-op events", () => { + it("returns unchanged for approval-response-requested", () => { + const result = applyThreadDetailEvent(baseThread, { + ...baseEventFields, + sequence: 15, + occurredAt: "2026-04-01T13:00:00.000Z", + aggregateKind: "thread", + aggregateId: ThreadId.make("thread-1"), + type: "thread.approval-response-requested", + payload: { + threadId: ThreadId.make("thread-1"), + requestId: "req-1", + decision: "approve", + createdAt: "2026-04-01T13:00:00.000Z", + }, + } as any); + expect(result.kind).toBe("unchanged"); + }); + }); +}); diff --git a/packages/client-runtime/src/threadDetailReducer.ts b/packages/client-runtime/src/threadDetailReducer.ts new file mode 100644 index 0000000000..260194dafa --- /dev/null +++ b/packages/client-runtime/src/threadDetailReducer.ts @@ -0,0 +1,519 @@ +import type { + MessageId, + OrchestrationCheckpointSummary, + OrchestrationEvent, + OrchestrationLatestTurn, + OrchestrationMessage, + OrchestrationThread, + OrchestrationThreadActivity, + TurnId, +} from "@t3tools/contracts"; + +/** + * Retention limits for collections within a thread. + * These prevent unbounded growth of in-memory thread state. + */ +export interface ThreadDetailRetentionLimits { + readonly maxMessages: number; + readonly maxProposedPlans: number; + readonly maxCheckpoints: number; + readonly maxActivities: number; +} + +export const DEFAULT_THREAD_DETAIL_LIMITS: ThreadDetailRetentionLimits = { + maxMessages: 512, + maxProposedPlans: 64, + maxCheckpoints: 256, + maxActivities: 128, +}; + +export type ThreadDetailReducerResult = + | { readonly kind: "updated"; readonly thread: OrchestrationThread } + | { readonly kind: "deleted" } + | { readonly kind: "unchanged" }; + +/** + * Apply a single orchestration event to an `OrchestrationThread`, returning + * the updated thread, a deletion signal, or an "unchanged" marker when the + * event doesn't affect this thread. + * + * This is a pure reducer operating on contract types. UI-specific mapping + * (e.g. resolving attachment preview URLs, normalising model slugs, adding + * scoped fields like `environmentId`) is the caller's responsibility. + */ +export function applyThreadDetailEvent( + thread: OrchestrationThread, + event: OrchestrationEvent, + limits: ThreadDetailRetentionLimits = DEFAULT_THREAD_DETAIL_LIMITS, +): ThreadDetailReducerResult { + switch (event.type) { + // ── Project events (irrelevant to thread detail) ──────────────── + case "project.created": + case "project.meta-updated": + case "project.deleted": + return { kind: "unchanged" }; + + // ── Thread lifecycle ──────────────────────────────────────────── + case "thread.created": + return { + kind: "updated", + thread: { + id: event.payload.threadId, + projectId: event.payload.projectId, + title: event.payload.title, + modelSelection: event.payload.modelSelection, + runtimeMode: event.payload.runtimeMode, + interactionMode: event.payload.interactionMode, + branch: event.payload.branch, + worktreePath: event.payload.worktreePath, + latestTurn: null, + createdAt: event.payload.createdAt, + updatedAt: event.payload.updatedAt, + archivedAt: null, + deletedAt: null, + messages: [], + proposedPlans: [], + activities: [], + checkpoints: [], + session: null, + }, + }; + + case "thread.deleted": + return { kind: "deleted" }; + + case "thread.archived": + return { + kind: "updated", + thread: { + ...thread, + archivedAt: event.payload.archivedAt, + updatedAt: event.payload.updatedAt, + }, + }; + + case "thread.unarchived": + return { + kind: "updated", + thread: { ...thread, archivedAt: null, updatedAt: event.payload.updatedAt }, + }; + + // ── Thread metadata ───────────────────────────────────────────── + case "thread.meta-updated": + return { + kind: "updated", + thread: { + ...thread, + ...(event.payload.title !== undefined ? { title: event.payload.title } : {}), + ...(event.payload.modelSelection !== undefined + ? { modelSelection: event.payload.modelSelection } + : {}), + ...(event.payload.branch !== undefined ? { branch: event.payload.branch } : {}), + ...(event.payload.worktreePath !== undefined + ? { worktreePath: event.payload.worktreePath } + : {}), + updatedAt: event.payload.updatedAt, + }, + }; + + case "thread.runtime-mode-set": + return { + kind: "updated", + thread: { + ...thread, + runtimeMode: event.payload.runtimeMode, + updatedAt: event.payload.updatedAt, + }, + }; + + case "thread.interaction-mode-set": + return { + kind: "updated", + thread: { + ...thread, + interactionMode: event.payload.interactionMode, + updatedAt: event.payload.updatedAt, + }, + }; + + // ── Turn lifecycle ────────────────────────────────────────────── + case "thread.turn-start-requested": + return { + kind: "updated", + thread: { + ...thread, + ...(event.payload.modelSelection !== undefined + ? { modelSelection: event.payload.modelSelection } + : {}), + runtimeMode: event.payload.runtimeMode, + interactionMode: event.payload.interactionMode, + updatedAt: event.occurredAt, + }, + }; + + case "thread.turn-interrupt-requested": { + if (event.payload.turnId === undefined) { + return { kind: "unchanged" }; + } + const latestTurn = thread.latestTurn; + if (latestTurn === null || latestTurn.turnId !== event.payload.turnId) { + return { kind: "unchanged" }; + } + return { + kind: "updated", + thread: { + ...thread, + latestTurn: { + ...latestTurn, + state: "interrupted", + startedAt: latestTurn.startedAt ?? event.payload.createdAt, + completedAt: latestTurn.completedAt ?? event.payload.createdAt, + }, + updatedAt: event.occurredAt, + }, + }; + } + + // ── Messages ──────────────────────────────────────────────────── + case "thread.message-sent": { + const message: OrchestrationMessage = { + id: event.payload.messageId, + role: event.payload.role, + text: event.payload.text, + ...(event.payload.attachments !== undefined + ? { attachments: event.payload.attachments } + : {}), + turnId: event.payload.turnId, + streaming: event.payload.streaming, + createdAt: event.payload.createdAt, + updatedAt: event.payload.updatedAt, + }; + + const existingMessage = thread.messages.find((entry) => entry.id === message.id); + const messages = existingMessage + ? thread.messages.map((entry) => + entry.id !== message.id + ? entry + : { + ...entry, + text: message.streaming + ? `${entry.text}${message.text}` + : message.text.length > 0 + ? message.text + : entry.text, + streaming: message.streaming, + ...(message.turnId !== undefined ? { turnId: message.turnId } : {}), + ...(message.streaming ? {} : { updatedAt: message.updatedAt }), + ...(message.attachments !== undefined + ? { attachments: message.attachments } + : {}), + }, + ) + : [...thread.messages, message]; + const cappedMessages = messages.slice(-limits.maxMessages); + + // Update latestTurn for assistant messages bound to a turn. + const latestTurn: OrchestrationThread["latestTurn"] = + event.payload.role === "assistant" && + event.payload.turnId !== null && + (thread.latestTurn === null || thread.latestTurn.turnId === event.payload.turnId) + ? { + turnId: event.payload.turnId, + state: event.payload.streaming + ? "running" + : thread.latestTurn?.state === "interrupted" + ? "interrupted" + : thread.latestTurn?.state === "error" + ? "error" + : "completed", + requestedAt: + thread.latestTurn?.turnId === event.payload.turnId + ? thread.latestTurn.requestedAt + : event.payload.createdAt, + startedAt: + thread.latestTurn?.turnId === event.payload.turnId + ? (thread.latestTurn.startedAt ?? event.payload.createdAt) + : event.payload.createdAt, + completedAt: event.payload.streaming + ? thread.latestTurn?.turnId === event.payload.turnId + ? (thread.latestTurn.completedAt ?? null) + : null + : event.payload.updatedAt, + assistantMessageId: event.payload.messageId, + } + : thread.latestTurn; + + // Rebind checkpoint assistant message IDs for assistant messages. + const checkpoints = + event.payload.role === "assistant" && event.payload.turnId !== null + ? rebindCheckpointAssistantMessage( + thread.checkpoints, + event.payload.turnId, + event.payload.messageId, + ) + : thread.checkpoints; + + return { + kind: "updated", + thread: { + ...thread, + messages: cappedMessages, + checkpoints, + latestTurn, + updatedAt: event.occurredAt, + }, + }; + } + + // ── Session ───────────────────────────────────────────────────── + case "thread.session-set": { + const latestTurn: OrchestrationLatestTurn | null = + event.payload.session.status === "running" && event.payload.session.activeTurnId !== null + ? { + turnId: event.payload.session.activeTurnId, + state: "running", + requestedAt: + thread.latestTurn?.turnId === event.payload.session.activeTurnId + ? thread.latestTurn.requestedAt + : event.payload.session.updatedAt, + startedAt: + thread.latestTurn?.turnId === event.payload.session.activeTurnId + ? (thread.latestTurn.startedAt ?? event.payload.session.updatedAt) + : event.payload.session.updatedAt, + completedAt: null, + assistantMessageId: + thread.latestTurn?.turnId === event.payload.session.activeTurnId + ? thread.latestTurn.assistantMessageId + : null, + } + : thread.latestTurn; + + return { + kind: "updated", + thread: { + ...thread, + session: event.payload.session, + latestTurn, + updatedAt: event.occurredAt, + }, + }; + } + + case "thread.session-stop-requested": + return thread.session === null + ? { kind: "unchanged" } + : { + kind: "updated", + thread: { + ...thread, + session: { + ...thread.session, + status: "stopped", + activeTurnId: null, + updatedAt: event.payload.createdAt, + }, + updatedAt: event.occurredAt, + }, + }; + + // ── Proposed plans ────────────────────────────────────────────── + case "thread.proposed-plan-upserted": { + const proposedPlan = event.payload.proposedPlan; + const proposedPlans = [ + ...thread.proposedPlans.filter((entry) => entry.id !== proposedPlan.id), + proposedPlan, + ] + .toSorted( + (left, right) => + left.createdAt.localeCompare(right.createdAt) || left.id.localeCompare(right.id), + ) + .slice(-limits.maxProposedPlans); + + return { + kind: "updated", + thread: { ...thread, proposedPlans, updatedAt: event.occurredAt }, + }; + } + + // ── Checkpoints / turn diffs ──────────────────────────────────── + case "thread.turn-diff-completed": { + const checkpoint: OrchestrationCheckpointSummary = { + turnId: event.payload.turnId, + checkpointTurnCount: event.payload.checkpointTurnCount, + checkpointRef: event.payload.checkpointRef, + status: event.payload.status, + files: event.payload.files, + assistantMessageId: event.payload.assistantMessageId, + completedAt: event.payload.completedAt, + }; + + const existing = thread.checkpoints.find((entry) => entry.turnId === checkpoint.turnId); + // Don't overwrite a non-missing checkpoint with a missing one. + if (existing && existing.status !== "missing" && checkpoint.status === "missing") { + return { kind: "unchanged" }; + } + + const checkpoints = [ + ...thread.checkpoints.filter((entry) => entry.turnId !== checkpoint.turnId), + checkpoint, + ] + .toSorted( + (left, right) => + (left.checkpointTurnCount ?? Number.MAX_SAFE_INTEGER) - + (right.checkpointTurnCount ?? Number.MAX_SAFE_INTEGER), + ) + .slice(-limits.maxCheckpoints); + + const latestTurn = + thread.latestTurn === null || thread.latestTurn.turnId === event.payload.turnId + ? { + turnId: event.payload.turnId, + state: checkpointStatusToTurnState(event.payload.status), + requestedAt: thread.latestTurn?.requestedAt ?? event.payload.completedAt, + startedAt: thread.latestTurn?.startedAt ?? event.payload.completedAt, + completedAt: event.payload.completedAt, + assistantMessageId: event.payload.assistantMessageId, + } + : thread.latestTurn; + + return { + kind: "updated", + thread: { ...thread, checkpoints, latestTurn, updatedAt: event.occurredAt }, + }; + } + + // ── Revert ────────────────────────────────────────────────────── + case "thread.reverted": { + const checkpoints = thread.checkpoints + .filter( + (entry) => + entry.checkpointTurnCount !== undefined && + entry.checkpointTurnCount <= event.payload.turnCount, + ) + .toSorted( + (left, right) => + (left.checkpointTurnCount ?? Number.MAX_SAFE_INTEGER) - + (right.checkpointTurnCount ?? Number.MAX_SAFE_INTEGER), + ) + .slice(-limits.maxCheckpoints); + + const retainedTurnIds = new Set(checkpoints.map((entry) => entry.turnId)); + const messages = retainMessagesAfterRevert( + thread.messages, + retainedTurnIds, + event.payload.turnCount, + ).slice(-limits.maxMessages); + const proposedPlans = thread.proposedPlans + .filter((plan) => plan.turnId === null || retainedTurnIds.has(plan.turnId)) + .slice(-limits.maxProposedPlans); + const activities = thread.activities.filter( + (activity) => activity.turnId === null || retainedTurnIds.has(activity.turnId), + ); + const latestCheckpoint = checkpoints.at(-1) ?? null; + + return { + kind: "updated", + thread: { + ...thread, + checkpoints, + messages, + proposedPlans, + activities, + latestTurn: + latestCheckpoint === null + ? null + : { + turnId: latestCheckpoint.turnId, + state: checkpointStatusToTurnState( + latestCheckpoint.status as "ready" | "missing" | "error", + ), + requestedAt: latestCheckpoint.completedAt, + startedAt: latestCheckpoint.completedAt, + completedAt: latestCheckpoint.completedAt, + assistantMessageId: latestCheckpoint.assistantMessageId ?? null, + }, + updatedAt: event.occurredAt, + }, + }; + } + + // ── Activities ────────────────────────────────────────────────── + case "thread.activity-appended": { + const activities = [ + ...thread.activities.filter((activity) => activity.id !== event.payload.activity.id), + event.payload.activity, + ] + .toSorted(compareActivities) + .slice(-limits.maxActivities); + + return { + kind: "updated", + thread: { ...thread, activities, updatedAt: event.occurredAt }, + }; + } + + // ── Events that don't mutate thread state directly ────────────── + case "thread.approval-response-requested": + case "thread.user-input-response-requested": + case "thread.checkpoint-revert-requested": + return { kind: "unchanged" }; + } + + // Forward-compatible: ignore unrecognized event types. + return { kind: "unchanged" }; +} + +// ── Helpers ────────────────────────────────────────────────────────── + +function checkpointStatusToTurnState( + status: "ready" | "missing" | "error", +): OrchestrationLatestTurn["state"] { + switch (status) { + case "ready": + return "completed"; + case "error": + return "error"; + case "missing": + return "completed"; + } +} + +function compareActivities( + left: OrchestrationThreadActivity, + right: OrchestrationThreadActivity, +): number { + const sequenceLeft = left.sequence ?? Number.MAX_SAFE_INTEGER; + const sequenceRight = right.sequence ?? Number.MAX_SAFE_INTEGER; + if (sequenceLeft !== sequenceRight) { + return sequenceLeft - sequenceRight; + } + return left.createdAt.localeCompare(right.createdAt) || left.id.localeCompare(right.id); +} + +function rebindCheckpointAssistantMessage( + checkpoints: ReadonlyArray, + turnId: TurnId, + messageId: MessageId, +): OrchestrationCheckpointSummary[] { + return checkpoints.map((entry) => + entry.turnId === turnId ? { ...entry, assistantMessageId: messageId } : entry, + ); +} + +function retainMessagesAfterRevert( + messages: ReadonlyArray, + retainedTurnIds: ReadonlySet, + turnCount: number, +): OrchestrationMessage[] { + // Keep messages that belong to a retained turn, plus system messages and + // messages without a turn binding (pre-turn-0 user messages). + return messages.filter((message) => { + if (message.role === "system") { + return true; + } + if (message.turnId === null) { + return true; + } + return retainedTurnIds.has(message.turnId); + }); +} diff --git a/packages/client-runtime/src/transportError.test.ts b/packages/client-runtime/src/transportError.test.ts new file mode 100644 index 0000000000..0e9e59b517 --- /dev/null +++ b/packages/client-runtime/src/transportError.test.ts @@ -0,0 +1,50 @@ +import { describe, expect, it } from "vitest"; + +import { isTransportConnectionErrorMessage, sanitizeThreadErrorMessage } from "./transportError"; + +describe("isTransportConnectionErrorMessage", () => { + it("returns true for SocketCloseError", () => { + expect(isTransportConnectionErrorMessage("SocketCloseError: connection reset")).toBe(true); + }); + + it("returns true for SocketOpenError", () => { + expect(isTransportConnectionErrorMessage("SocketOpenError: ECONNREFUSED")).toBe(true); + }); + + it("returns true for the T3 server WebSocket message", () => { + expect(isTransportConnectionErrorMessage("Unable to connect to the T3 server WebSocket.")).toBe( + true, + ); + }); + + it("returns true for ping timeout", () => { + expect(isTransportConnectionErrorMessage("ping timeout")).toBe(true); + }); + + it("returns false for business logic errors", () => { + expect(isTransportConnectionErrorMessage("Thread not found")).toBe(false); + expect(isTransportConnectionErrorMessage("Invalid model selection")).toBe(false); + }); + + it("returns false for null, undefined, and empty strings", () => { + expect(isTransportConnectionErrorMessage(null)).toBe(false); + expect(isTransportConnectionErrorMessage(undefined)).toBe(false); + expect(isTransportConnectionErrorMessage("")).toBe(false); + expect(isTransportConnectionErrorMessage(" ")).toBe(false); + }); +}); + +describe("sanitizeThreadErrorMessage", () => { + it("strips transport errors", () => { + expect(sanitizeThreadErrorMessage("SocketCloseError: oops")).toBeNull(); + }); + + it("preserves non-transport errors", () => { + expect(sanitizeThreadErrorMessage("Thread not found")).toBe("Thread not found"); + }); + + it("returns null for null/undefined", () => { + expect(sanitizeThreadErrorMessage(null)).toBeNull(); + expect(sanitizeThreadErrorMessage(undefined)).toBeNull(); + }); +}); diff --git a/packages/client-runtime/src/transportError.ts b/packages/client-runtime/src/transportError.ts new file mode 100644 index 0000000000..93adfad99d --- /dev/null +++ b/packages/client-runtime/src/transportError.ts @@ -0,0 +1,33 @@ +const TRANSPORT_ERROR_PATTERNS = [ + /\bSocketCloseError\b/i, + /\bSocketOpenError\b/i, + /Unable to connect to the T3 server WebSocket\./i, + /\bping timeout\b/i, +] as const; + +/** + * Test whether an error message originates from a transport-level connection + * failure (socket close, socket open, ping timeout, etc.) rather than a + * business-logic error. + */ +export function isTransportConnectionErrorMessage(message: string | null | undefined): boolean { + if (typeof message !== "string") { + return false; + } + + const normalizedMessage = message.trim(); + if (normalizedMessage.length === 0) { + return false; + } + + return TRANSPORT_ERROR_PATTERNS.some((pattern) => pattern.test(normalizedMessage)); +} + +/** + * Strip transport connection errors from user-facing error messages. + * Returns `null` for transport errors so the UI can distinguish between + * real errors and transient connection issues. + */ +export function sanitizeThreadErrorMessage(message: string | null | undefined): string | null { + return isTransportConnectionErrorMessage(message) ? null : (message ?? null); +} diff --git a/packages/client-runtime/src/wsRpcClient.ts b/packages/client-runtime/src/wsRpcClient.ts index 238e395016..33745cf934 100644 --- a/packages/client-runtime/src/wsRpcClient.ts +++ b/packages/client-runtime/src/wsRpcClient.ts @@ -1,7 +1,5 @@ import { type GitActionProgressEvent, - type GitStatusLocalResult, - type GitStatusRemoteResult, type GitRunStackedActionInput, type GitRunStackedActionResult, type GitStatusResult, @@ -11,76 +9,12 @@ import { type ServerSettingsPatch, WS_METHODS, } from "@t3tools/contracts"; +import { applyGitStatusStreamEvent } from "@t3tools/shared/git"; import { Effect, Stream } from "effect"; import { type WsRpcProtocolClient } from "./wsRpcProtocol"; import { WsTransport } from "./wsTransport"; -const EMPTY_GIT_STATUS_REMOTE: GitStatusRemoteResult = { - hasUpstream: false, - aheadCount: 0, - behindCount: 0, - pr: null, -}; - -function mergeGitStatusParts( - local: GitStatusLocalResult, - remote: GitStatusRemoteResult | null, -): GitStatusResult { - return { - ...local, - ...(remote ?? EMPTY_GIT_STATUS_REMOTE), - }; -} - -function toRemoteStatusPart(status: GitStatusResult): GitStatusRemoteResult { - return { - hasUpstream: status.hasUpstream, - aheadCount: status.aheadCount, - behindCount: status.behindCount, - pr: status.pr, - }; -} - -function toLocalStatusPart(status: GitStatusResult): GitStatusLocalResult { - return { - isRepo: status.isRepo, - ...(status.hostingProvider ? { hostingProvider: status.hostingProvider } : {}), - hasOriginRemote: status.hasOriginRemote, - isDefaultBranch: status.isDefaultBranch, - branch: status.branch, - hasWorkingTreeChanges: status.hasWorkingTreeChanges, - workingTree: status.workingTree, - }; -} - -function applyGitStatusStreamEvent( - current: GitStatusResult | null, - event: GitStatusStreamEvent, -): GitStatusResult { - switch (event._tag) { - case "snapshot": - return mergeGitStatusParts(event.local, event.remote); - case "localUpdated": - return mergeGitStatusParts(event.local, current ? toRemoteStatusPart(current) : null); - case "remoteUpdated": - if (current === null) { - return mergeGitStatusParts( - { - isRepo: true, - hasOriginRemote: false, - isDefaultBranch: false, - branch: null, - hasWorkingTreeChanges: false, - workingTree: { files: [], insertions: 0, deletions: 0 }, - }, - event.remote, - ); - } - return mergeGitStatusParts(toLocalStatusPart(current), event.remote); - } -} - type RpcTag = keyof WsRpcProtocolClient & string; type RpcMethod = WsRpcProtocolClient[TTag]; type RpcInput = Parameters>[0]; @@ -104,6 +38,15 @@ type RpcStreamMethod = ? (listener: (event: TEvent) => void, options?: StreamSubscriptionOptions) => () => void : never; +type RpcInputStreamMethod = + RpcMethod extends (input: any, options?: any) => Stream.Stream + ? ( + input: RpcInput, + listener: (event: TEvent) => void, + options?: StreamSubscriptionOptions, + ) => () => void + : never; + interface GitRunStackedActionOptions { readonly onProgress?: (event: GitActionProgressEvent) => void; } @@ -166,12 +109,11 @@ export interface WsRpcClient { readonly subscribeAuthAccess: RpcStreamMethod; }; readonly orchestration: { - readonly getSnapshot: RpcUnaryNoArgMethod; readonly dispatchCommand: RpcUnaryMethod; readonly getTurnDiff: RpcUnaryMethod; readonly getFullThreadDiff: RpcUnaryMethod; - readonly replayEvents: RpcUnaryMethod; - readonly onDomainEvent: RpcStreamMethod; + readonly subscribeShell: RpcStreamMethod; + readonly subscribeThread: RpcInputStreamMethod; }; } @@ -281,21 +223,21 @@ export function createWsRpcClient(transport: WsTransport): WsRpcClient { ), }, orchestration: { - getSnapshot: () => - transport.request((client) => client[ORCHESTRATION_WS_METHODS.getSnapshot]({})), dispatchCommand: (input) => transport.request((client) => client[ORCHESTRATION_WS_METHODS.dispatchCommand](input)), getTurnDiff: (input) => transport.request((client) => client[ORCHESTRATION_WS_METHODS.getTurnDiff](input)), getFullThreadDiff: (input) => transport.request((client) => client[ORCHESTRATION_WS_METHODS.getFullThreadDiff](input)), - replayEvents: (input) => - transport - .request((client) => client[ORCHESTRATION_WS_METHODS.replayEvents](input)) - .then((events) => [...events]), - onDomainEvent: (listener, options) => + subscribeShell: (listener, options) => transport.subscribe( - (client) => client[WS_METHODS.subscribeOrchestrationDomainEvents]({}), + (client) => client[ORCHESTRATION_WS_METHODS.subscribeShell]({}), + listener, + options, + ), + subscribeThread: (input, listener, options) => + transport.subscribe( + (client) => client[ORCHESTRATION_WS_METHODS.subscribeThread](input), listener, options, ), diff --git a/packages/client-runtime/src/wsRpcProtocol.ts b/packages/client-runtime/src/wsRpcProtocol.ts index e8ad1ae5c7..6293dc30f1 100644 --- a/packages/client-runtime/src/wsRpcProtocol.ts +++ b/packages/client-runtime/src/wsRpcProtocol.ts @@ -3,6 +3,12 @@ import { Duration, Effect, Layer, Schedule } from "effect"; import { RpcClient, RpcSerialization } from "effect/unstable/rpc"; import * as Socket from "effect/unstable/socket/Socket"; +import { + DEFAULT_RECONNECT_BACKOFF, + getReconnectDelayMs, + type ReconnectBackoffConfig, +} from "./reconnectBackoff"; + export interface WsProtocolLifecycleHandlers { readonly onAttempt?: (socketUrl: string) => void; readonly onOpen?: () => void; @@ -10,14 +16,17 @@ export interface WsProtocolLifecycleHandlers { readonly onClose?: (details: { readonly code: number; readonly reason: string }) => void; } +export interface WsRpcProtocolOptions { + /** Backoff configuration for reconnect retries. */ + readonly backoff?: ReconnectBackoffConfig; +} + export const makeWsRpcProtocolClient = RpcClient.make(WsRpcGroup); type RpcClientFactory = typeof makeWsRpcProtocolClient; export type WsRpcProtocolClient = RpcClientFactory extends Effect.Effect ? Client : never; export type WsRpcProtocolSocketUrlProvider = string | (() => Promise); -const WS_RECONNECT_DELAYS_MS = [250, 500, 1_000, 2_000, 4_000] as const; - function formatSocketErrorMessage(error: unknown): string { if (error instanceof Error && error.message.trim().length > 0) { return error.message; @@ -36,10 +45,6 @@ function resolveWsRpcSocketUrl(rawUrl: string): string { return resolved.toString(); } -function getWsReconnectDelayMsForRetry(retryCount: number): number | null { - return WS_RECONNECT_DELAYS_MS[retryCount] ?? null; -} - function defaultLifecycleHandlers(): Required { return { onAttempt: () => undefined, @@ -52,11 +57,14 @@ function defaultLifecycleHandlers(): Required { export function createWsRpcProtocolLayer( url: WsRpcProtocolSocketUrlProvider, handlers?: WsProtocolLifecycleHandlers, + options?: WsRpcProtocolOptions, ) { const lifecycle = { ...defaultLifecycleHandlers(), ...handlers, }; + const backoff = options?.backoff ?? DEFAULT_RECONNECT_BACKOFF; + const resolvedUrl = typeof url === "function" ? Effect.promise(() => url()).pipe( @@ -107,8 +115,11 @@ export function createWsRpcProtocolLayer( const socketLayer = Socket.layerWebSocket(resolvedUrl).pipe( Layer.provide(trackingWebSocketConstructorLayer), ); - const retryPolicy = Schedule.addDelay(Schedule.forever, (retryCount) => - Effect.succeed(Duration.millis(getWsReconnectDelayMsForRetry(retryCount) ?? 0)), + + const baseSchedule = + backoff.maxRetries === null ? Schedule.forever : Schedule.recurs(backoff.maxRetries); + const retryPolicy = Schedule.addDelay(baseSchedule, (retryCount) => + Effect.succeed(Duration.millis(getReconnectDelayMs(retryCount, backoff) ?? 0)), ); const protocolLayer = Layer.effect( RpcClient.Protocol, diff --git a/packages/client-runtime/src/wsTransport.ts b/packages/client-runtime/src/wsTransport.ts index 1f5e04402e..78fbe9094f 100644 --- a/packages/client-runtime/src/wsTransport.ts +++ b/packages/client-runtime/src/wsTransport.ts @@ -1,6 +1,7 @@ import { Cause, Duration, Effect, Exit, ManagedRuntime, Scope, Stream } from "effect"; import { RpcClient } from "effect/unstable/rpc"; +import { isTransportConnectionErrorMessage } from "./transportError"; import { createWsRpcProtocolLayer, makeWsRpcProtocolClient, @@ -31,22 +32,11 @@ function formatErrorMessage(error: unknown): string { return String(error); } -function isTransportConnectionError(error: unknown): boolean { - const message = formatErrorMessage(error).toLowerCase(); - return ( - message.includes("connect") || - message.includes("socket") || - message.includes("websocket") || - message.includes("closed") || - message.includes("econn") || - message.includes("network") - ); -} - export class WsTransport { private readonly url: WsRpcProtocolSocketUrlProvider; private readonly lifecycleHandlers: WsProtocolLifecycleHandlers | undefined; private disposed = false; + private hasReportedTransportDisconnect = false; private reconnectChain: Promise = Promise.resolve(); private session: TransportSession; @@ -116,6 +106,7 @@ export class WsTransport { return; } + const session = this.session; try { if (hasReceivedValue) { try { @@ -125,13 +116,13 @@ export class WsTransport { } } - const session = this.session; const runningStream = this.runStreamOnSession( session, connect, listener, () => active, () => { + this.hasReportedTransportDisconnect = false; hasReceivedValue = true; }, ); @@ -144,13 +135,25 @@ export class WsTransport { return; } - if (!isTransportConnectionError(error)) { + // Skip retry if the session has already been replaced by a reconnect. + if (session !== this.session) { + continue; + } + + const formattedError = formatErrorMessage(error); + if (!isTransportConnectionErrorMessage(formattedError)) { console.warn("WebSocket RPC subscription failed", { - error: formatErrorMessage(error), + error: formattedError, }); return; } + if (!this.hasReportedTransportDisconnect) { + console.warn("WebSocket RPC subscription disconnected", { + error: formattedError, + }); + } + this.hasReportedTransportDisconnect = true; await sleep(retryDelayMs); } }