From 25862ffc34939e82b7ccccb092e6fb67733c3f02 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 25 Jun 2026 04:22:25 -0700 Subject: [PATCH] Retire V1 client orchestration parity Co-authored-by: codex --- ...rchestration-v2-application-integration.md | 8 +- .../features/projects/AddProjectScreen.tsx | 1 - .../src/features/review/reviewModel.test.ts | 2 +- .../mobile/src/features/review/reviewModel.ts | 2 +- .../src/features/review/useReviewSections.ts | 16 +- .../terminal/ThreadTerminalRouteScreen.tsx | 10 +- .../features/threads/ThreadRouteScreen.tsx | 2 +- apps/mobile/src/lib/threadActivity.ts | 2 +- apps/mobile/src/state/queries.ts | 51 +- apps/mobile/src/state/threads.ts | 11 +- .../src/state/use-selected-thread-requests.ts | 22 +- .../src/state/use-selected-thread-worktree.ts | 9 +- .../src/state/use-thread-composer-state.ts | 51 +- apps/mobile/src/state/use-thread-detail.ts | 13 +- apps/mobile/src/test-fixtures.ts | 60 - .../testkit/ThreadFork.integration.test.ts | 8 + .../Layers/OrchestrationEngine.ts | 4 +- .../Layers/ProjectionPipeline.ts | 12 +- .../Layers/ProjectionSnapshotQuery.ts | 15 +- apps/server/src/orchestration/Schemas.ts | 2 +- .../Services/OrchestrationEngine.ts | 5 +- .../Services/ProjectionPipeline.ts | 2 +- .../Services/ProjectionSnapshotQuery.ts | 6 +- .../src/orchestration/commandInvariants.ts | 6 +- apps/server/src/orchestration/decider.ts | 4 +- apps/server/src/orchestration/projector.ts | 8 +- .../Layers/OrchestrationEventStore.ts | 24 +- .../Layers/ProjectionCheckpoints.ts | 2 +- .../src/persistence/Layers/ProjectionTurns.ts | 2 +- .../src/persistence/ProviderSessionRuntime.ts | 9 +- .../Services/OrchestrationCommandReceipts.ts | 8 +- .../Services/OrchestrationEventStore.ts | 2 +- .../Services/ProjectionCheckpoints.ts | 6 +- .../Services/ProjectionPendingApprovals.ts | 7 +- .../Services/ProjectionThreadActivities.ts | 10 +- .../Services/ProjectionThreadMessages.ts | 10 +- .../Services/ProjectionThreadProposedPlans.ts | 9 +- .../Services/ProjectionThreadSessions.ts | 10 +- .../persistence/Services/ProjectionTurns.ts | 8 +- apps/server/src/ws.ts | 11 +- apps/web/src/components/BranchToolbar.tsx | 3 +- .../BranchToolbarBranchSelector.tsx | 6 +- apps/web/src/components/ChatView.logic.ts | 74 +- apps/web/src/components/ChatView.tsx | 505 ++- apps/web/src/components/DiffPanel.tsx | 7 +- apps/web/src/components/GitActionsControl.tsx | 3 +- apps/web/src/components/Sidebar.logic.test.ts | 4 +- apps/web/src/components/chat/ChatComposer.tsx | 19 +- .../src/components/chat/MessagesTimeline.tsx | 5 +- apps/web/src/hooks/useHandleNewThread.ts | 6 +- apps/web/src/hooks/useTurnDiffSummaries.ts | 12 +- apps/web/src/lib/contextWindow.test.ts | 12 +- apps/web/src/lib/contextWindow.ts | 14 +- apps/web/src/lib/threadSort.test.ts | 4 +- .../web/src/orchestrationEventEffects.test.ts | 135 - apps/web/src/orchestrationEventEffects.ts | 94 - .../src/orchestrationV2DebugProviders.test.ts | 82 - apps/web/src/orchestrationV2DebugProviders.ts | 88 - apps/web/src/routeTree.gen.ts | 33 + .../routes/_chat.$environmentId.$threadId.tsx | 25 +- apps/web/src/routes/_chat.draft.$draftId.tsx | 4 +- .../web/src/routes/debug.orchestration-v2.tsx | 3923 ----------------- apps/web/src/session-logic.test.ts | 148 +- apps/web/src/session-logic.ts | 169 +- apps/web/src/state/entities.ts | 94 +- apps/web/src/state/queries.ts | 52 +- apps/web/src/state/threads.ts | 11 +- apps/web/src/test-fixtures.ts | 145 +- apps/web/src/types.ts | 33 +- packages/client-runtime/package.json | 12 + .../src/operations/projects.test.ts | 3 +- .../client-runtime/src/operations/projects.ts | 11 +- .../client-runtime/src/state/entities.test.ts | 86 +- packages/client-runtime/src/state/models.ts | 601 +-- .../src/state/threadCheckpoints.ts | 52 + .../src/state/threadDetail.test.ts | 28 + .../client-runtime/src/state/threadDetail.ts | 117 +- .../src/state/threadExecution.ts | 49 + .../src/state/threadRequests.ts | 78 + packages/contracts/package.json | 4 + .../contracts/src/applicationEvent.test.ts | 63 + packages/contracts/src/applicationEvent.ts | 102 +- packages/contracts/src/index.ts | 2 + packages/contracts/src/ipc.ts | 34 - packages/contracts/src/orchestration.ts | 244 +- .../contracts/src/orchestrationProject.ts | 19 + packages/contracts/src/orchestrationV2.ts | 2 +- packages/contracts/src/rpc.test.ts | 13 + packages/contracts/src/rpc.ts | 87 - packages/shared/src/agentAwareness.test.ts | 170 +- packages/shared/src/agentAwareness.ts | 102 +- vite.config.ts | 1 + 92 files changed, 1371 insertions(+), 6669 deletions(-) delete mode 100644 apps/web/src/orchestrationEventEffects.test.ts delete mode 100644 apps/web/src/orchestrationEventEffects.ts delete mode 100644 apps/web/src/orchestrationV2DebugProviders.test.ts delete mode 100644 apps/web/src/orchestrationV2DebugProviders.ts delete mode 100644 apps/web/src/routes/debug.orchestration-v2.tsx create mode 100644 packages/client-runtime/src/state/threadCheckpoints.ts create mode 100644 packages/client-runtime/src/state/threadExecution.ts create mode 100644 packages/client-runtime/src/state/threadRequests.ts create mode 100644 packages/contracts/src/applicationEvent.test.ts create mode 100644 packages/contracts/src/orchestrationProject.ts create mode 100644 packages/contracts/src/rpc.test.ts diff --git a/.plans/21-orchestration-v2-application-integration.md b/.plans/21-orchestration-v2-application-integration.md index 152fb66f2b..4a958d290d 100644 --- a/.plans/21-orchestration-v2-application-integration.md +++ b/.plans/21-orchestration-v2-application-integration.md @@ -880,9 +880,9 @@ Add web and mobile integration coverage for: ## Shape 4.5: V2-Native Frontend Enrichment -Implementation status: in progress. The web-first pass through Sections 1, 2, 4, and 5 is implemented. Mobile remains on the Shape 4.0 presentation path; shared selector extraction and parity-facade removal are intentionally deferred until the mobile port demonstrates what is actually shared. +Implementation status: complete. Production web and mobile now consume the scoped V2 projection directly, and the temporary Shape 4.0 parity facade, V1 client RPC surface, and V2 debug route have been removed. -Web-first implementation outcome: +Completion outcome: - Production web continues to render the server-authoritative `visibleTurnItems` sequence and now joins individual rows to narrowly selected V2 run, attempt, node, provider, request, checkpoint, subagent, handoff, and transfer state. - Expandable production inspectors expose command input/output and exit state, file changes and diff navigation, search provenance, dynamic/provider-native structured payloads, checkpoint rollback, subagent/fork navigation, provider identity, attempts, and context handoff state. @@ -892,7 +892,9 @@ Web-first implementation outcome: - While a run is active, an empty composer keeps the Stop action. Entering content replaces it with Send, whose current default is explicit steering; `Mod+Enter` explicitly queues. The default action is isolated behind a small policy seam for a future user setting, without adding an action menu now. - Interrupt request/result, compaction, handoff, fork, and subagent lifecycle items use polished production-native dividers or compact rows. Todo updates remain ordinary work-log items because the Tasks right-panel surface owns rich task progress. - Shutdown now blocks new mutations, stops the effect worker, closes provider sessions and MCP capabilities, and best-effort reconciles durable state. Startup repeats that repair authoritatively, atomically cancels the complete provider-bound in-flight execution subtree plus its non-replayable effects, allows a waiting run to finish only through its durable replay-safe checkpoint capture, leaves idle provider processes closed, and resumes genuinely queued turns after repair. A development-server restart therefore leaves the interrupted thread terminal and sendable instead of failing projection startup. -- No mobile binding or shared presentation abstraction was introduced during this pass. The existing projection reducer and command semantics remain the shared substrate. +- Mobile renders the same server-authoritative `visibleTurnItems` sequence and derives only the runtime, request, and checkpoint summaries required by its concrete surfaces. +- Shared client-runtime selectors cover only demonstrated cross-platform domain needs. Platform-specific presentation remains local to web and mobile; there is no second complete thread presentation model. +- Frozen V1 persistence/event-store decoders remain isolated behind the explicit `legacy-orchestration` contract subpath for the later data-migration stage. No production client imports the legacy thread model or calls a V1 endpoint. ### Goal diff --git a/apps/mobile/src/features/projects/AddProjectScreen.tsx b/apps/mobile/src/features/projects/AddProjectScreen.tsx index c7e6b534a7..4b0935a1b2 100644 --- a/apps/mobile/src/features/projects/AddProjectScreen.tsx +++ b/apps/mobile/src/features/projects/AddProjectScreen.tsx @@ -604,7 +604,6 @@ function useCreateProject(environment: EnvironmentOption | null) { commandId: CommandId.make(uuidv4()), projectId, workspaceRoot, - createdAt: new Date().toISOString(), }); const result = await createProject({ environmentId: environment.environmentId, diff --git a/apps/mobile/src/features/review/reviewModel.test.ts b/apps/mobile/src/features/review/reviewModel.test.ts index 3543b4de89..770a656136 100644 --- a/apps/mobile/src/features/review/reviewModel.test.ts +++ b/apps/mobile/src/features/review/reviewModel.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from "vite-plus/test"; import { MessageId, RunId, type ReviewDiffPreviewSource } from "@t3tools/contracts"; -import type { ThreadCheckpointSummary } from "@t3tools/client-runtime/state/shell"; +import type { ThreadCheckpointSummary } from "@t3tools/client-runtime/state/thread-checkpoints"; import { buildReviewListItems, diff --git a/apps/mobile/src/features/review/reviewModel.ts b/apps/mobile/src/features/review/reviewModel.ts index 1704f9c52a..5e1ae6bac5 100644 --- a/apps/mobile/src/features/review/reviewModel.ts +++ b/apps/mobile/src/features/review/reviewModel.ts @@ -1,6 +1,6 @@ import { parsePatchFiles } from "@pierre/diffs/utils/parsePatchFiles"; import type { ChangeTypes, FileDiffMetadata } from "@pierre/diffs/types"; -import type { ThreadCheckpointSummary } from "@t3tools/client-runtime/state/shell"; +import type { ThreadCheckpointSummary } from "@t3tools/client-runtime/state/thread-checkpoints"; import type { ReviewDiffPreviewSource } from "@t3tools/contracts"; import * as Arr from "effect/Array"; import { pipe } from "effect/Function"; diff --git a/apps/mobile/src/features/review/useReviewSections.ts b/apps/mobile/src/features/review/useReviewSections.ts index 7c725e2583..b8a0028019 100644 --- a/apps/mobile/src/features/review/useReviewSections.ts +++ b/apps/mobile/src/features/review/useReviewSections.ts @@ -1,12 +1,15 @@ import { useCallback, useEffect, useMemo } from "react"; -import type { ThreadCheckpointSummary } from "@t3tools/client-runtime/state/shell"; +import { + deriveThreadCheckpointSummaries, + type ThreadCheckpointSummary, +} from "@t3tools/client-runtime/state/thread-checkpoints"; import type { EnvironmentId, ThreadId } from "@t3tools/contracts"; import { useCheckpointDiff } from "../../state/queries"; import { useEnvironmentQuery } from "../../state/query"; import { reviewEnvironment } from "../../state/review"; -import { useSelectedThreadDetail } from "../../state/use-thread-detail"; +import { useSelectedThreadProjection } from "../../state/use-thread-detail"; import { useSelectedThreadWorktree } from "../../state/use-selected-thread-worktree"; import { buildReviewSectionItems, @@ -31,7 +34,7 @@ export function useReviewSections(input: { }) { const { environmentId, reviewCache, threadId } = input; const enabled = input.enabled ?? true; - const selectedThread = useSelectedThreadDetail(); + const selectedThread = useSelectedThreadProjection(); const { selectedThreadCwd } = useSelectedThreadWorktree(); const diffPreview = useEnvironmentQuery( enabled && environmentId !== undefined && selectedThreadCwd !== null @@ -50,8 +53,11 @@ export function useReviewSections(input: { }, [diffPreview.data, reviewCache.threadKey]); const readyCheckpoints = useMemo( - () => getReadyReviewCheckpoints(selectedThread?.checkpoints ?? []), - [selectedThread?.checkpoints], + () => + getReadyReviewCheckpoints( + selectedThread === null ? [] : deriveThreadCheckpointSummaries(selectedThread.projection), + ), + [selectedThread], ); const checkpointBySectionId = useMemo( () => diff --git a/apps/mobile/src/features/terminal/ThreadTerminalRouteScreen.tsx b/apps/mobile/src/features/terminal/ThreadTerminalRouteScreen.tsx index a80d90d82c..4232218dc4 100644 --- a/apps/mobile/src/features/terminal/ThreadTerminalRouteScreen.tsx +++ b/apps/mobile/src/features/terminal/ThreadTerminalRouteScreen.tsx @@ -40,7 +40,7 @@ import { useKnownTerminalSessions, } from "../../state/use-terminal-session"; import { useThreadSelection } from "../../state/use-thread-selection"; -import { useSelectedThreadDetail } from "../../state/use-thread-detail"; +import { useSelectedThreadProjection } from "../../state/use-thread-detail"; import { EnvironmentConnectionNotice } from "../connection/EnvironmentConnectionNotice"; import { useAdaptiveWorkspaceLayout } from "../layout/AdaptiveWorkspaceLayout"; import { TerminalSurface } from "./NativeTerminalSurface"; @@ -172,7 +172,9 @@ export function ThreadTerminalRouteScreen(props: ThreadTerminalRouteScreenProps) const params = props.route.params; const { selectedThread, selectedThreadProject, selectedEnvironmentConnection } = useThreadSelection(); - const selectedThreadDetail = useSelectedThreadDetail(); + const selectedThreadDetail = useSelectedThreadProjection(); + const selectedThreadDetailWorktreePath = + selectedThreadDetail?.projection.thread.worktreePath ?? null; const routeEnvironmentIdRaw = firstRouteParam(params.environmentId); const routeThreadIdRaw = firstRouteParam(params.threadId); const routeEnvironmentId = routeEnvironmentIdRaw @@ -283,13 +285,13 @@ export function ThreadTerminalRouteScreen(props: ThreadTerminalRouteScreenProps) activeSessionLocation: activeKnownSession?.state.summary ?? null, workspaceRoot: selectedThreadProject.workspaceRoot, threadShellWorktreePath: selectedThread.worktreePath ?? null, - threadDetailWorktreePath: selectedThreadDetail?.worktreePath ?? null, + threadDetailWorktreePath: selectedThreadDetailWorktreePath, }); }, [ activeKnownSession?.state.summary, pendingLaunch, selectedThread, - selectedThreadDetail?.worktreePath, + selectedThreadDetailWorktreePath, selectedThreadProject?.workspaceRoot, ]); const [initialLaunchLocationEntry, setInitialLaunchLocationEntry] = useState(() => ({ diff --git a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx index 2e2eeb264c..524ec5b3fd 100644 --- a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx +++ b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx @@ -320,7 +320,7 @@ function ThreadRouteContent( }), [knownTerminalSessions, selectedThreadProject?.workspaceRoot], ); - const selectedThreadDetailWorktreePath = selectedThreadDetail?.worktreePath ?? null; + const selectedThreadDetailWorktreePath = selectedThreadDetail?.thread.worktreePath ?? null; const handleReconnectEnvironment = useCallback(() => { if (!environmentId) { return; diff --git a/apps/mobile/src/lib/threadActivity.ts b/apps/mobile/src/lib/threadActivity.ts index 391e80cff1..f6d335b51c 100644 --- a/apps/mobile/src/lib/threadActivity.ts +++ b/apps/mobile/src/lib/threadActivity.ts @@ -2,7 +2,7 @@ import type { ThreadPendingApproval, ThreadPendingUserInput, ThreadUserInputQuestion, -} from "@t3tools/client-runtime/state/shell"; +} from "@t3tools/client-runtime/state/thread-requests"; import type { ChatAttachment, MessageId, diff --git a/apps/mobile/src/state/queries.ts b/apps/mobile/src/state/queries.ts index 47d93f98fb..65478d9a93 100644 --- a/apps/mobile/src/state/queries.ts +++ b/apps/mobile/src/state/queries.ts @@ -1,13 +1,9 @@ -import type { EnvironmentThread } from "@t3tools/client-runtime/state/shell"; -import type { EnvironmentId, ThreadId } from "@t3tools/contracts"; -import * as Option from "effect/Option"; -import { Atom } from "effect/unstable/reactivity"; +import type { EnvironmentId } from "@t3tools/contracts"; import { useEffect, useMemo, useState } from "react"; import { orchestrationEnvironment } from "./orchestration"; import { projectEnvironment } from "./projects"; import { useEnvironmentQuery } from "./query"; -import { useEnvironmentThread } from "./threads"; import { vcsEnvironment } from "./vcs"; import { buildCheckpointDiffTargets, @@ -34,13 +30,6 @@ const threadSearchResultsAtom = createThreadSearchResultsAtomFamily({ labelPrefix: "mobile:thread-search", }); -export interface ThreadDetailView { - readonly data: EnvironmentThread | null; - readonly error: string | null; - readonly isPending: boolean; - readonly isDeleted: boolean; -} - export interface ComposerPathSearchTarget { readonly environmentId: EnvironmentId | null; readonly cwd: string | null; @@ -62,44 +51,6 @@ function useDebouncedValue(value: A, delayMs: number): A { return debounced; } -export function useThreadSearch( - environmentIds: ReadonlyArray, - query: string, -): { - readonly matches: ReadonlyArray; - readonly isPending: boolean; -} { - const normalizedQuery = query.trim(); - const debouncedQuery = useDebouncedValue(normalizedQuery, THREAD_SEARCH_DEBOUNCE_MS); - const canSearch = environmentIds.length > 0 && normalizedQuery.length >= 2; - const settledQuery = canSearch && normalizedQuery === debouncedQuery ? debouncedQuery : null; - const searchKey = useMemo( - () => (settledQuery === null ? null : makeThreadSearchKey(environmentIds, settledQuery)), - [environmentIds, settledQuery], - ); - const result = useAtomValue( - searchKey === null ? EMPTY_THREAD_SEARCH_ATOM : threadSearchResultsAtom(searchKey), - ); - const isDebouncing = canSearch && normalizedQuery !== debouncedQuery; - return { - matches: isDebouncing ? EMPTY_THREAD_SEARCH_MATCHES : result.matches, - isPending: canSearch && (isDebouncing || result.isLoading), - }; -} - -export function useThreadDetail( - environmentId: EnvironmentId | null, - threadId: ThreadId | null, -): ThreadDetailView { - const state = useEnvironmentThread(environmentId, threadId); - return { - data: Option.getOrNull(state.data), - error: Option.getOrNull(state.error), - isPending: state.status === "synchronizing", - isDeleted: state.status === "deleted", - }; -} - export function useBranches(input: { readonly environmentId: EnvironmentId | null; readonly cwd: string | null; diff --git a/apps/mobile/src/state/threads.ts b/apps/mobile/src/state/threads.ts index 09aa68a6fe..34dc85f168 100644 --- a/apps/mobile/src/state/threads.ts +++ b/apps/mobile/src/state/threads.ts @@ -7,7 +7,6 @@ import { type EnvironmentThreadState, createThreadEnvironmentAtoms, } from "@t3tools/client-runtime/state/threads"; -import { presentThread, type EnvironmentThread } from "@t3tools/client-runtime/state/shell"; import type { EnvironmentId, ThreadId } from "@t3tools/contracts"; import * as Option from "effect/Option"; import { AsyncResult, Atom } from "effect/unstable/reactivity"; @@ -33,7 +32,7 @@ const EMPTY_THREAD_STATE_ATOM = Atom.make(AsyncResult.success(EMPTY_ENVIRONMENT_ export function useEnvironmentThread( environmentId: EnvironmentId | null, threadId: ThreadId | null, -): Omit & { readonly data: Option.Option } { +): EnvironmentThreadState { const result = useAtomValue( environmentId !== null && threadId !== null ? environmentThreads.stateAtom(environmentId, threadId) @@ -43,11 +42,5 @@ export function useEnvironmentThread( AsyncResult.value(result), () => EMPTY_ENVIRONMENT_THREAD_STATE, ) as EnvironmentThreadState; - return { - ...state, - data: - environmentId === null - ? Option.none() - : Option.map(state.data, (projection) => presentThread(environmentId, projection)), - }; + return state; } diff --git a/apps/mobile/src/state/use-selected-thread-requests.ts b/apps/mobile/src/state/use-selected-thread-requests.ts index fa3e336625..3e7354e12d 100644 --- a/apps/mobile/src/state/use-selected-thread-requests.ts +++ b/apps/mobile/src/state/use-selected-thread-requests.ts @@ -2,6 +2,7 @@ import { useAtomValue } from "@effect/atom-react"; import { useCallback, useMemo, useState } from "react"; import { type ProviderApprovalDecision, type RuntimeRequestId } from "@t3tools/contracts"; +import { derivePendingThreadRequests } from "@t3tools/client-runtime/state/thread-requests"; import { Atom } from "effect/unstable/reactivity"; import { threadEnvironment } from "../state/threads"; @@ -13,7 +14,7 @@ import { type PendingUserInputDraftAnswer, } from "../lib/threadActivity"; import { appAtomRegistry } from "./atom-registry"; -import { useSelectedThreadDetail } from "./use-thread-detail"; +import { useSelectedThreadProjection } from "./use-thread-detail"; import { useThreadSelection } from "./use-thread-selection"; import { useAtomCommand } from "./use-atom-command"; @@ -62,24 +63,21 @@ export function useSelectedThreadRequests() { "thread user input response", ); const { selectedThread: selectedThreadShell } = useThreadSelection(); - const selectedThread = useSelectedThreadDetail(); + const selectedThread = useSelectedThreadProjection(); const userInputDraftsByRequestKey = useAtomValue(userInputDraftsByRequestKeyAtom); const [respondingApprovalId, setRespondingApprovalId] = useState(null); const [respondingUserInputId, setRespondingUserInputId] = useState(null); - const activePendingApprovals = useMemo( - () => selectedThread?.pendingApprovals ?? [], + const pendingRequests = useMemo( + () => + selectedThread === null + ? { approvals: [], userInputs: [] } + : derivePendingThreadRequests(selectedThread.projection), [selectedThread], ); - const activePendingApprovals = useMemo( - () => derivePendingApprovals(sortedActivities), - [sortedActivities], - ); + const activePendingApprovals = pendingRequests.approvals; const activePendingApproval = activePendingApprovals[0] ?? null; - const activePendingUserInputs = useMemo( - () => selectedThread?.pendingUserInputs ?? [], - [selectedThread], - ); + const activePendingUserInputs = pendingRequests.userInputs; const activePendingUserInput = activePendingUserInputs[0] ?? null; const activePendingUserInputDrafts = activePendingUserInput && selectedThreadShell diff --git a/apps/mobile/src/state/use-selected-thread-worktree.ts b/apps/mobile/src/state/use-selected-thread-worktree.ts index c5046c5b13..d39df1d772 100644 --- a/apps/mobile/src/state/use-selected-thread-worktree.ts +++ b/apps/mobile/src/state/use-selected-thread-worktree.ts @@ -1,20 +1,21 @@ import { useMemo } from "react"; -import { useSelectedThreadDetail } from "./use-thread-detail"; +import { useSelectedThreadProjection } from "./use-thread-detail"; import { useThreadSelection } from "./use-thread-selection"; import { resolvePreferredThreadWorktreePath } from "../features/terminal/terminalLaunchContext"; export function useSelectedThreadWorktree() { const { selectedThread, selectedThreadProject } = useThreadSelection(); - const selectedThreadDetail = useSelectedThreadDetail(); + const selectedThreadDetail = useSelectedThreadProjection(); + const detailWorktreePath = selectedThreadDetail?.projection.thread.worktreePath ?? null; const selectedThreadWorktreePath = useMemo( () => resolvePreferredThreadWorktreePath({ threadShellWorktreePath: selectedThread?.worktreePath ?? null, - threadDetailWorktreePath: selectedThreadDetail?.worktreePath ?? null, + threadDetailWorktreePath: detailWorktreePath, }), - [selectedThread?.worktreePath, selectedThreadDetail?.worktreePath], + [detailWorktreePath, selectedThread?.worktreePath], ); return { diff --git a/apps/mobile/src/state/use-thread-composer-state.ts b/apps/mobile/src/state/use-thread-composer-state.ts index d9bc15d33b..694cc7d44e 100644 --- a/apps/mobile/src/state/use-thread-composer-state.ts +++ b/apps/mobile/src/state/use-thread-composer-state.ts @@ -1,5 +1,9 @@ import { useAtomValue } from "@effect/atom-react"; import { threadRuntimeIsActive } from "@t3tools/client-runtime/state/shell"; +import { + deriveLatestThreadRun, + deriveThreadRuntime, +} from "@t3tools/client-runtime/state/thread-execution"; import { useCallback, useEffect, useMemo } from "react"; import { @@ -39,7 +43,7 @@ import { } from "./use-composer-drafts"; import { setPendingConnectionError } from "../state/use-remote-environment-registry"; import { - useSelectedThreadDetail, + useSelectedThreadProjection, useSelectedThreadVisibleTurnItems, } from "../state/use-thread-detail"; import { useThreadSelection } from "../state/use-thread-selection"; @@ -79,7 +83,7 @@ export function useThreadDraftForThread(input: { export function useThreadComposerState() { const { selectedThread: selectedThreadShell } = useThreadSelection(); - const selectedThreadDetail = useSelectedThreadDetail(); + const selectedThreadProjection = useSelectedThreadProjection(); const selectedThreadVisibleTurnItems = useSelectedThreadVisibleTurnItems(); const composerDrafts = useAtomValue(composerDraftsAtom); const queuedMessagesByThreadKey = useThreadOutboxMessages(); @@ -104,33 +108,44 @@ export function useThreadComposerState() { const draftMessage = selectedDraft?.text ?? ""; const draftAttachments = selectedDraft?.attachments ?? []; const selectedThreadQueueCount = selectedThreadQueuedMessages.length; - const selectedThread = selectedThreadDetail ?? selectedThreadShell; + const selectedThread = selectedThreadShell; const modelSelection = selectedDraft?.modelSelection ?? selectedThread?.modelSelection ?? null; const runtimeMode = selectedDraft?.runtimeMode ?? selectedThread?.runtimeMode ?? null; const interactionMode = selectedDraft?.interactionMode ?? selectedThread?.interactionMode ?? null; + const selectedThreadRuntime = useMemo( + () => + selectedThreadProjection + ? deriveThreadRuntime(selectedThreadProjection.projection) + : (selectedThreadShell?.runtime ?? null), + [selectedThreadProjection, selectedThreadShell?.runtime], + ); + const selectedThreadLatestRun = useMemo( + () => + selectedThreadProjection + ? deriveLatestThreadRun(selectedThreadProjection.projection) + : (selectedThreadShell?.latestRun ?? null), + [selectedThreadProjection, selectedThreadShell?.latestRun], + ); const selectedThreadSessionActivity = useMemo(() => { - const selectedThread = selectedThreadDetail ?? selectedThreadShell; - if (!selectedThread?.runtime) { + if (!selectedThreadRuntime) { return null; } return { - orchestrationStatus: selectedThread.runtime.status, - activeRunId: selectedThread.runtime.activeRunId ?? undefined, + orchestrationStatus: selectedThreadRuntime.status, + activeRunId: selectedThreadRuntime.activeRunId ?? undefined, }; - }, [selectedThreadDetail, selectedThreadShell]); + }, [selectedThreadRuntime]); const activeWorkStartedAt = useMemo(() => { - const selectedThread = selectedThreadDetail ?? selectedThreadShell; - if (!selectedThread) { + if (!selectedThreadShell) { return null; } + return deriveActiveWorkStartedAt(selectedThreadLatestRun, selectedThreadSessionActivity, null); + }, [selectedThreadLatestRun, selectedThreadSessionActivity, selectedThreadShell]); - return deriveActiveWorkStartedAt(selectedThread.latestRun, selectedThreadSessionActivity, null); - }, [selectedThreadDetail, selectedThreadSessionActivity, selectedThreadShell]); - - const activeThreadBusy = !!selectedThread && threadRuntimeIsActive(selectedThread.runtime); + const activeThreadBusy = threadRuntimeIsActive(selectedThreadRuntime); const onSendMessage = useCallback(async () => { if (!selectedThreadShell) { @@ -139,7 +154,7 @@ export function useThreadComposerState() { const threadKey = scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id); const draft = getComposerDraftSnapshot(threadKey); - const thread = selectedThreadDetail ?? selectedThreadShell; + const thread = selectedThreadShell; const text = draft.text.trim(); const attachments = draft.attachments; if (text.length === 0 && attachments.length === 0) { @@ -176,9 +191,9 @@ export function useThreadComposerState() { setPendingConnectionError( error instanceof Error ? error.message : "Failed to save the queued message.", ); - }); - return messageId; - }, [selectedThreadDetail, selectedThreadShell]); + return null; + } + }, [selectedThreadShell]); const onChangeDraftMessage = useCallback( (value: string) => { diff --git a/apps/mobile/src/state/use-thread-detail.ts b/apps/mobile/src/state/use-thread-detail.ts index 9e3bac3ae6..8c48aa880e 100644 --- a/apps/mobile/src/state/use-thread-detail.ts +++ b/apps/mobile/src/state/use-thread-detail.ts @@ -1,13 +1,12 @@ import { useAtomValue } from "@effect/atom-react"; -import type { ScopedThreadProjection } from "@t3tools/client-runtime/state/shell"; +import type { EnvironmentThread } from "@t3tools/client-runtime/state/shell"; import type { EnvironmentId, OrchestrationV2ThreadProjection, ThreadId } from "@t3tools/contracts"; -import * as Option from "effect/Option"; import { Atom } from "effect/unstable/reactivity"; import { environmentThreadDetails, useEnvironmentThread } from "./threads"; import { useThreadSelection } from "./use-thread-selection"; -const EMPTY_THREAD_PROJECTION_ATOM = Atom.make(null).pipe( +const EMPTY_THREAD_PROJECTION_ATOM = Atom.make(null).pipe( Atom.withLabel("mobile-thread-projection:empty"), ); const EMPTY_VISIBLE_TURN_ITEMS_ATOM = Atom.make< @@ -31,11 +30,7 @@ export function useSelectedThreadDetailState() { }); } -export function useSelectedThreadDetail() { - return Option.getOrNull(useSelectedThreadDetailState().data); -} - -export function useThreadProjection(target: ThreadDetailTarget): ScopedThreadProjection | null { +export function useThreadProjection(target: ThreadDetailTarget): EnvironmentThread | null { return useAtomValue( target.environmentId === null || target.threadId === null ? EMPTY_THREAD_PROJECTION_ATOM @@ -46,7 +41,7 @@ export function useThreadProjection(target: ThreadDetailTarget): ScopedThreadPro ); } -export function useSelectedThreadProjection(): ScopedThreadProjection | null { +export function useSelectedThreadProjection(): EnvironmentThread | null { const { selectedThread } = useThreadSelection(); return useThreadProjection({ environmentId: selectedThread?.environmentId ?? null, diff --git a/apps/mobile/src/test-fixtures.ts b/apps/mobile/src/test-fixtures.ts index 9b6b6ee08f..10aab98b40 100644 --- a/apps/mobile/src/test-fixtures.ts +++ b/apps/mobile/src/test-fixtures.ts @@ -1,7 +1,5 @@ import { - presentThread, presentThreadShell, - type EnvironmentThread, type EnvironmentThreadShell, } from "@t3tools/client-runtime/state/shell"; import { @@ -9,7 +7,6 @@ import { ProjectId, ProviderInstanceId, ThreadId, - type OrchestrationV2ThreadProjection, type OrchestrationV2ThreadShell, } from "@t3tools/contracts"; import * as DateTime from "effect/DateTime"; @@ -71,60 +68,3 @@ export function makeThreadShellFixture( }); return { ...presentThreadShell(environmentId, raw), ...overrides }; } - -export function makeThreadFixture(overrides: Partial = {}): EnvironmentThread { - const shell = makeRawThreadShell({ - id: overrides.id, - projectId: overrides.projectId, - title: overrides.title, - providerInstanceId: overrides.providerInstanceId, - modelSelection: overrides.modelSelection, - runtimeMode: overrides.runtimeMode, - interactionMode: overrides.interactionMode, - branch: overrides.branch, - worktreePath: overrides.worktreePath, - }); - const projection: OrchestrationV2ThreadProjection = { - thread: { - id: shell.id, - projectId: shell.projectId, - title: shell.title, - providerInstanceId: shell.providerInstanceId, - modelSelection: shell.modelSelection, - runtimeMode: shell.runtimeMode, - interactionMode: shell.interactionMode, - branch: shell.branch, - worktreePath: shell.worktreePath, - activeProviderThreadId: shell.activeProviderThreadId, - lineage: shell.lineage, - forkedFrom: shell.forkedFrom, - createdBy: shell.createdBy, - creationSource: shell.creationSource, - createdAt: shell.createdAt, - updatedAt: shell.updatedAt, - archivedAt: shell.archivedAt, - deletedAt: shell.deletedAt, - }, - runs: [], - attempts: [], - nodes: [], - subagents: [], - providerSessions: [], - providerThreads: [], - providerTurns: [], - runtimeRequests: [], - messages: [], - plans: [], - turnItems: [], - checkpointScopes: [], - checkpoints: [], - contextHandoffs: [], - contextTransfers: [], - visibleTurnItems: [], - updatedAt: shell.updatedAt, - }; - return { - ...presentThread(overrides.environmentId ?? EnvironmentId.make("environment-test"), projection), - ...overrides, - }; -} diff --git a/apps/server/src/orchestration-v2/testkit/ThreadFork.integration.test.ts b/apps/server/src/orchestration-v2/testkit/ThreadFork.integration.test.ts index 063011b657..92d9b1693b 100644 --- a/apps/server/src/orchestration-v2/testkit/ThreadFork.integration.test.ts +++ b/apps/server/src/orchestration-v2/testkit/ThreadFork.integration.test.ts @@ -1280,6 +1280,7 @@ describe("orchestration V2 thread fork", () => { projectId, }); const targetThreadId = ThreadId.make("thread-fork-native-fork-local-rollback-target"); + const targetSecondRunId = ids.derive.run({ threadId: targetThreadId, ordinal: 2 }); const targetCheckpointScopeId = yield* ids.allocate.checkpointScope({ threadId: targetThreadId, name: "root", @@ -1392,6 +1393,7 @@ describe("orchestration V2 thread fork", () => { return { sourceThreadId, targetThreadId, + targetSecondRunId, commands, }; }).pipe(Effect.provide(idAllocatorLayer), provideDeterministicTestRuntime); @@ -1412,6 +1414,12 @@ describe("orchestration V2 thread fork", () => { { type: "dispatch", command: materialized.commands[4]!, await: true }, { type: "await_thread_idle", threadId: materialized.targetThreadId }, { type: "dispatch", command: materialized.commands[5]!, await: true }, + { + type: "await_run_status", + threadId: materialized.targetThreadId, + runId: materialized.targetSecondRunId, + status: "rolled_back", + }, { type: "dispatch", command: materialized.commands[6]!, await: true }, { type: "await_thread_idle", threadId: materialized.targetThreadId }, ], diff --git a/apps/server/src/orchestration/Layers/OrchestrationEngine.ts b/apps/server/src/orchestration/Layers/OrchestrationEngine.ts index 0c8345fbbc..7b15cd4497 100644 --- a/apps/server/src/orchestration/Layers/OrchestrationEngine.ts +++ b/apps/server/src/orchestration/Layers/OrchestrationEngine.ts @@ -1,9 +1,9 @@ +import type { ProjectId } from "@t3tools/contracts"; import type { OrchestrationEvent, OrchestrationReadModel, - ProjectId, ProjectOrchestrationCommand, -} from "@t3tools/contracts"; +} from "@t3tools/contracts/legacy-orchestration"; import * as Cause from "effect/Cause"; import * as Clock from "effect/Clock"; import * as Crypto from "effect/Crypto"; diff --git a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts b/apps/server/src/orchestration/Layers/ProjectionPipeline.ts index e9a625dd91..8f831c31bc 100644 --- a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts +++ b/apps/server/src/orchestration/Layers/ProjectionPipeline.ts @@ -1,10 +1,8 @@ -import { - ApprovalRequestId, - type ChatAttachment, - type OrchestrationEvent, - type OrchestrationSessionStatus, - ThreadId, -} from "@t3tools/contracts"; +import { ApprovalRequestId, type ChatAttachment, ThreadId } from "@t3tools/contracts"; +import type { + OrchestrationEvent, + OrchestrationSessionStatus, +} from "@t3tools/contracts/legacy-orchestration"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; diff --git a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts index 17ba5dd608..9033cda4fa 100644 --- a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts +++ b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts @@ -4,15 +4,19 @@ import { IsoDateTime, MessageId, NonNegativeInt, + ProjectScript, + TurnId, + ModelSelection, + ProjectId, + ThreadId, +} from "@t3tools/contracts"; +import { OrchestrationCheckpointFile, OrchestrationProposedPlanId, OrchestrationReadModel, OrchestrationThreadSearchSource, OrchestrationShellSnapshot, OrchestrationThread, - OrchestrationThreadDetailSnapshot, - ProjectScript, - TurnId, type OrchestrationCheckpointSummary, type OrchestrationLatestTurn, type OrchestrationMessage, @@ -22,10 +26,7 @@ import { type OrchestrationSession, type OrchestrationThreadActivity, type OrchestrationThreadShell, - ModelSelection, - ProjectId, - ThreadId, -} from "@t3tools/contracts"; +} from "@t3tools/contracts/legacy-orchestration"; import * as Arr from "effect/Array"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; diff --git a/apps/server/src/orchestration/Schemas.ts b/apps/server/src/orchestration/Schemas.ts index 7e866cf895..84613fce02 100644 --- a/apps/server/src/orchestration/Schemas.ts +++ b/apps/server/src/orchestration/Schemas.ts @@ -27,7 +27,7 @@ import { ThreadApprovalResponseRequestedPayload as ContractsThreadApprovalResponseRequestedPayloadSchema, ThreadCheckpointRevertRequestedPayload as ContractsThreadCheckpointRevertRequestedPayloadSchema, ThreadSessionStopRequestedPayload as ContractsThreadSessionStopRequestedPayloadSchema, -} from "@t3tools/contracts"; +} from "@t3tools/contracts/legacy-orchestration"; // Server-internal alias surface, backed by contract schemas as the source of truth. export const ProjectCreatedPayload = ContractsProjectCreatedPayloadSchema; diff --git a/apps/server/src/orchestration/Services/OrchestrationEngine.ts b/apps/server/src/orchestration/Services/OrchestrationEngine.ts index 035aba9418..fbb827c5a8 100644 --- a/apps/server/src/orchestration/Services/OrchestrationEngine.ts +++ b/apps/server/src/orchestration/Services/OrchestrationEngine.ts @@ -10,7 +10,10 @@ * * @module OrchestrationEngineService */ -import type { OrchestrationEvent, ProjectOrchestrationCommand } from "@t3tools/contracts"; +import type { + OrchestrationEvent, + ProjectOrchestrationCommand, +} from "@t3tools/contracts/legacy-orchestration"; import * as Context from "effect/Context"; import type * as Effect from "effect/Effect"; import type * as Stream from "effect/Stream"; diff --git a/apps/server/src/orchestration/Services/ProjectionPipeline.ts b/apps/server/src/orchestration/Services/ProjectionPipeline.ts index bb4736ca57..b9a60ab45e 100644 --- a/apps/server/src/orchestration/Services/ProjectionPipeline.ts +++ b/apps/server/src/orchestration/Services/ProjectionPipeline.ts @@ -6,7 +6,7 @@ * * @module OrchestrationProjectionPipeline */ -import type { OrchestrationEvent } from "@t3tools/contracts"; +import type { OrchestrationEvent } from "@t3tools/contracts/legacy-orchestration"; import * as Context from "effect/Context"; import type * as Effect from "effect/Effect"; diff --git a/apps/server/src/orchestration/Services/ProjectionSnapshotQuery.ts b/apps/server/src/orchestration/Services/ProjectionSnapshotQuery.ts index 014384003e..7eaee65623 100644 --- a/apps/server/src/orchestration/Services/ProjectionSnapshotQuery.ts +++ b/apps/server/src/orchestration/Services/ProjectionSnapshotQuery.ts @@ -6,8 +6,8 @@ * * @module ProjectionSnapshotQuery */ +import type { CheckpointRef, ProjectId, ThreadId } from "@t3tools/contracts"; import type { - CheckpointRef, OrchestrationCheckpointSummary, OrchestrationProject, OrchestrationProjectShell, @@ -19,9 +19,7 @@ import type { OrchestrationThreadDetailSnapshot, OrchestrationThreadDetailWindow, OrchestrationThreadShell, - ProjectId, - ThreadId, -} from "@t3tools/contracts"; +} from "@t3tools/contracts/legacy-orchestration"; import * as Context from "effect/Context"; import type * as Option from "effect/Option"; import type * as Effect from "effect/Effect"; diff --git a/apps/server/src/orchestration/commandInvariants.ts b/apps/server/src/orchestration/commandInvariants.ts index b59ded77f4..15153225cc 100644 --- a/apps/server/src/orchestration/commandInvariants.ts +++ b/apps/server/src/orchestration/commandInvariants.ts @@ -1,12 +1,10 @@ +import type { ProjectId, ThreadId } from "@t3tools/contracts"; import type { OrchestrationCommand, OrchestrationProject, OrchestrationReadModel, OrchestrationThread, - ProjectId, - ThreadId, -} from "@t3tools/contracts"; -import { normalizeProjectPathForComparison } from "@t3tools/shared/path"; +} from "@t3tools/contracts/legacy-orchestration"; import * as Effect from "effect/Effect"; import { OrchestrationCommandInvariantError } from "./Errors.ts"; diff --git a/apps/server/src/orchestration/decider.ts b/apps/server/src/orchestration/decider.ts index 79a96ef4aa..53727fc43a 100644 --- a/apps/server/src/orchestration/decider.ts +++ b/apps/server/src/orchestration/decider.ts @@ -1,9 +1,9 @@ +import { EventId } from "@t3tools/contracts"; import { - EventId, type OrchestrationCommand, type OrchestrationEvent, type OrchestrationReadModel, -} from "@t3tools/contracts"; +} from "@t3tools/contracts/legacy-orchestration"; import * as DateTime from "effect/DateTime"; import * as Crypto from "effect/Crypto"; import * as Effect from "effect/Effect"; diff --git a/apps/server/src/orchestration/projector.ts b/apps/server/src/orchestration/projector.ts index f486dcb2bc..6d4bfee907 100644 --- a/apps/server/src/orchestration/projector.ts +++ b/apps/server/src/orchestration/projector.ts @@ -1,10 +1,14 @@ -import type { OrchestrationEvent, OrchestrationReadModel, ThreadId } from "@t3tools/contracts"; +import type { ThreadId } from "@t3tools/contracts"; +import type { + OrchestrationEvent, + OrchestrationReadModel, +} from "@t3tools/contracts/legacy-orchestration"; import { OrchestrationCheckpointSummary, OrchestrationMessage, OrchestrationSession, OrchestrationThread, -} from "@t3tools/contracts"; +} from "@t3tools/contracts/legacy-orchestration"; import * as Effect from "effect/Effect"; import * as Schema from "effect/Schema"; diff --git a/apps/server/src/persistence/Layers/OrchestrationEventStore.ts b/apps/server/src/persistence/Layers/OrchestrationEventStore.ts index e303b84a60..cf7db447d1 100644 --- a/apps/server/src/persistence/Layers/OrchestrationEventStore.ts +++ b/apps/server/src/persistence/Layers/OrchestrationEventStore.ts @@ -1,20 +1,23 @@ import { + ApplicationProjectEvent, type ApplicationStoredEvent, CommandId, EventId, IsoDateTime, NonNegativeInt, - OrchestrationActorKind, - OrchestrationAggregateKind, - OrchestrationEvent, - OrchestrationEventMetadata, - OrchestrationEventType, OrchestrationV2DomainEventJson, OrchestrationV2StoredEvent, ProjectId, ThreadId, type OrchestrationV2DomainEvent, } from "@t3tools/contracts"; +import { + OrchestrationActorKind, + OrchestrationAggregateKind, + OrchestrationEvent, + OrchestrationEventMetadata, + OrchestrationEventType, +} from "@t3tools/contracts/legacy-orchestration"; import * as SqlClient from "effect/unstable/sql/SqlClient"; import * as SqlSchema from "effect/unstable/sql/SqlSchema"; import * as Effect from "effect/Effect"; @@ -34,6 +37,7 @@ import { } from "../Services/OrchestrationEventStore.ts"; const decodeEvent = Schema.decodeUnknownEffect(OrchestrationEvent); +const decodeProjectEvent = Schema.decodeUnknownEffect(ApplicationProjectEvent); const UnknownFromJsonString = Schema.fromJsonString(Schema.Unknown); const EventMetadataFromJsonString = Schema.fromJsonString(OrchestrationEventMetadata); @@ -137,7 +141,7 @@ const rowToV2StoredEvent = Effect.fn("OrchestrationEventStore.rowToV2StoredEvent const rowToProjectEvent = Effect.fn("OrchestrationEventStore.rowToProjectEvent")(function* ( row: ApplicationEventRow, ) { - const event = yield* decodeEvent({ + return yield* decodeProjectEvent({ sequence: row.sequence, eventId: row.event_id, type: row.event_type, @@ -150,14 +154,6 @@ const rowToProjectEvent = Effect.fn("OrchestrationEventStore.rowToProjectEvent") payload: yield* decodeJson(row.payload_json), metadata: yield* decodeJson(row.metadata_json), }); - switch (event.type) { - case "project.created": - case "project.meta-updated": - case "project.deleted": - return event; - default: - return yield* Effect.die(`Expected a project event, received '${event.type}'.`); - } }); function rowToApplicationStoredEvent( diff --git a/apps/server/src/persistence/Layers/ProjectionCheckpoints.ts b/apps/server/src/persistence/Layers/ProjectionCheckpoints.ts index cfa5658d0e..42bd3e93bc 100644 --- a/apps/server/src/persistence/Layers/ProjectionCheckpoints.ts +++ b/apps/server/src/persistence/Layers/ProjectionCheckpoints.ts @@ -1,4 +1,4 @@ -import { OrchestrationCheckpointFile } from "@t3tools/contracts"; +import { OrchestrationCheckpointFile } from "@t3tools/contracts/legacy-orchestration"; import * as SqlClient from "effect/unstable/sql/SqlClient"; import * as SqlSchema from "effect/unstable/sql/SqlSchema"; import * as Effect from "effect/Effect"; diff --git a/apps/server/src/persistence/Layers/ProjectionTurns.ts b/apps/server/src/persistence/Layers/ProjectionTurns.ts index bd57a4eaa3..db25b007ed 100644 --- a/apps/server/src/persistence/Layers/ProjectionTurns.ts +++ b/apps/server/src/persistence/Layers/ProjectionTurns.ts @@ -1,4 +1,4 @@ -import { OrchestrationCheckpointFile } from "@t3tools/contracts"; +import { OrchestrationCheckpointFile } from "@t3tools/contracts/legacy-orchestration"; import * as SqlClient from "effect/unstable/sql/SqlClient"; import * as SqlSchema from "effect/unstable/sql/SqlSchema"; import * as Effect from "effect/Effect"; diff --git a/apps/server/src/persistence/ProviderSessionRuntime.ts b/apps/server/src/persistence/ProviderSessionRuntime.ts index 2ccdd86252..bffdac594f 100644 --- a/apps/server/src/persistence/ProviderSessionRuntime.ts +++ b/apps/server/src/persistence/ProviderSessionRuntime.ts @@ -9,13 +9,8 @@ import * as Struct from "effect/Struct"; import * as SqlClient from "effect/unstable/sql/SqlClient"; import * as SqlSchema from "effect/unstable/sql/SqlSchema"; -import { - IsoDateTime, - ProviderInstanceId, - ProviderSessionRuntimeStatus, - RuntimeMode, - ThreadId, -} from "@t3tools/contracts"; +import { IsoDateTime, ProviderInstanceId, RuntimeMode, ThreadId } from "@t3tools/contracts"; +import { ProviderSessionRuntimeStatus } from "@t3tools/contracts/legacy-orchestration"; import { PersistenceDecodeError, diff --git a/apps/server/src/persistence/Services/OrchestrationCommandReceipts.ts b/apps/server/src/persistence/Services/OrchestrationCommandReceipts.ts index 5c4eef2cc5..8586b39279 100644 --- a/apps/server/src/persistence/Services/OrchestrationCommandReceipts.ts +++ b/apps/server/src/persistence/Services/OrchestrationCommandReceipts.ts @@ -6,15 +6,11 @@ * * @module OrchestrationCommandReceiptRepository */ +import { CommandId, IsoDateTime, NonNegativeInt, ProjectId, ThreadId } from "@t3tools/contracts"; import { - CommandId, - IsoDateTime, - NonNegativeInt, OrchestrationAggregateKind, OrchestrationCommandReceiptStatus, - ProjectId, - ThreadId, -} from "@t3tools/contracts"; +} from "@t3tools/contracts/legacy-orchestration"; import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; import * as Context from "effect/Context"; diff --git a/apps/server/src/persistence/Services/OrchestrationEventStore.ts b/apps/server/src/persistence/Services/OrchestrationEventStore.ts index 85f108bae5..801d4137a0 100644 --- a/apps/server/src/persistence/Services/OrchestrationEventStore.ts +++ b/apps/server/src/persistence/Services/OrchestrationEventStore.ts @@ -13,11 +13,11 @@ import type { ApplicationStoredEvent, CommandId, - OrchestrationEvent, OrchestrationV2DomainEvent, OrchestrationV2StoredEvent, ThreadId, } from "@t3tools/contracts"; +import type { OrchestrationEvent } from "@t3tools/contracts/legacy-orchestration"; import * as Context from "effect/Context"; import type * as Effect from "effect/Effect"; import type * as Stream from "effect/Stream"; diff --git a/apps/server/src/persistence/Services/ProjectionCheckpoints.ts b/apps/server/src/persistence/Services/ProjectionCheckpoints.ts index 7796ebec2a..81f98c5cce 100644 --- a/apps/server/src/persistence/Services/ProjectionCheckpoints.ts +++ b/apps/server/src/persistence/Services/ProjectionCheckpoints.ts @@ -11,11 +11,13 @@ import { IsoDateTime, MessageId, NonNegativeInt, - OrchestrationCheckpointFile, - OrchestrationCheckpointStatus, ThreadId, TurnId, } from "@t3tools/contracts"; +import { + OrchestrationCheckpointFile, + OrchestrationCheckpointStatus, +} from "@t3tools/contracts/legacy-orchestration"; import * as Option from "effect/Option"; import * as Context from "effect/Context"; import * as Schema from "effect/Schema"; diff --git a/apps/server/src/persistence/Services/ProjectionPendingApprovals.ts b/apps/server/src/persistence/Services/ProjectionPendingApprovals.ts index 967e6da9d3..8e4ad68583 100644 --- a/apps/server/src/persistence/Services/ProjectionPendingApprovals.ts +++ b/apps/server/src/persistence/Services/ProjectionPendingApprovals.ts @@ -6,14 +6,11 @@ * * @module ProjectionPendingApprovalRepository */ +import { ApprovalRequestId, IsoDateTime, ThreadId, TurnId } from "@t3tools/contracts"; import { - ApprovalRequestId, - IsoDateTime, ProjectionPendingApprovalDecision, ProjectionPendingApprovalStatus, - ThreadId, - TurnId, -} from "@t3tools/contracts"; +} from "@t3tools/contracts/legacy-orchestration"; import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; import * as Context from "effect/Context"; diff --git a/apps/server/src/persistence/Services/ProjectionThreadActivities.ts b/apps/server/src/persistence/Services/ProjectionThreadActivities.ts index 47cb6073c4..41a4e2955c 100644 --- a/apps/server/src/persistence/Services/ProjectionThreadActivities.ts +++ b/apps/server/src/persistence/Services/ProjectionThreadActivities.ts @@ -6,14 +6,8 @@ * * @module ProjectionThreadActivityRepository */ -import { - EventId, - IsoDateTime, - NonNegativeInt, - OrchestrationThreadActivityTone, - ThreadId, - TurnId, -} from "@t3tools/contracts"; +import { EventId, IsoDateTime, NonNegativeInt, ThreadId, TurnId } from "@t3tools/contracts"; +import { OrchestrationThreadActivityTone } from "@t3tools/contracts/legacy-orchestration"; import * as Schema from "effect/Schema"; import * as Context from "effect/Context"; import type * as Effect from "effect/Effect"; diff --git a/apps/server/src/persistence/Services/ProjectionThreadMessages.ts b/apps/server/src/persistence/Services/ProjectionThreadMessages.ts index d50ff32025..8316016a0b 100644 --- a/apps/server/src/persistence/Services/ProjectionThreadMessages.ts +++ b/apps/server/src/persistence/Services/ProjectionThreadMessages.ts @@ -6,14 +6,8 @@ * * @module ProjectionThreadMessageRepository */ -import { - ChatAttachment, - MessageId, - OrchestrationMessageRole, - ThreadId, - TurnId, - IsoDateTime, -} from "@t3tools/contracts"; +import { ChatAttachment, MessageId, ThreadId, TurnId, IsoDateTime } from "@t3tools/contracts"; +import { OrchestrationMessageRole } from "@t3tools/contracts/legacy-orchestration"; import * as Schema from "effect/Schema"; import * as Context from "effect/Context"; import type * as Option from "effect/Option"; diff --git a/apps/server/src/persistence/Services/ProjectionThreadProposedPlans.ts b/apps/server/src/persistence/Services/ProjectionThreadProposedPlans.ts index b4bc2bcc32..98403b7c2d 100644 --- a/apps/server/src/persistence/Services/ProjectionThreadProposedPlans.ts +++ b/apps/server/src/persistence/Services/ProjectionThreadProposedPlans.ts @@ -1,10 +1,5 @@ -import { - IsoDateTime, - OrchestrationProposedPlanId, - ThreadId, - TrimmedNonEmptyString, - TurnId, -} from "@t3tools/contracts"; +import { IsoDateTime, ThreadId, TrimmedNonEmptyString, TurnId } from "@t3tools/contracts"; +import { OrchestrationProposedPlanId } from "@t3tools/contracts/legacy-orchestration"; import * as Schema from "effect/Schema"; import * as Context from "effect/Context"; import type * as Effect from "effect/Effect"; diff --git a/apps/server/src/persistence/Services/ProjectionThreadSessions.ts b/apps/server/src/persistence/Services/ProjectionThreadSessions.ts index 7cecac33eb..e459800d24 100644 --- a/apps/server/src/persistence/Services/ProjectionThreadSessions.ts +++ b/apps/server/src/persistence/Services/ProjectionThreadSessions.ts @@ -6,14 +6,8 @@ * * @module ProjectionThreadSessionRepository */ -import { - RuntimeMode, - IsoDateTime, - OrchestrationSessionStatus, - ProviderInstanceId, - ThreadId, - TurnId, -} from "@t3tools/contracts"; +import { RuntimeMode, IsoDateTime, ProviderInstanceId, ThreadId, TurnId } from "@t3tools/contracts"; +import { OrchestrationSessionStatus } from "@t3tools/contracts/legacy-orchestration"; import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; import * as Context from "effect/Context"; diff --git a/apps/server/src/persistence/Services/ProjectionTurns.ts b/apps/server/src/persistence/Services/ProjectionTurns.ts index f3d5d5e470..81b43001af 100644 --- a/apps/server/src/persistence/Services/ProjectionTurns.ts +++ b/apps/server/src/persistence/Services/ProjectionTurns.ts @@ -11,12 +11,14 @@ import { IsoDateTime, MessageId, NonNegativeInt, - OrchestrationProposedPlanId, - OrchestrationCheckpointFile, - OrchestrationCheckpointStatus, ThreadId, TurnId, } from "@t3tools/contracts"; +import { + OrchestrationCheckpointFile, + OrchestrationCheckpointStatus, + OrchestrationProposedPlanId, +} from "@t3tools/contracts/legacy-orchestration"; import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; import * as Context from "effect/Context"; diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index 801bb757bb..62fbc68991 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -28,7 +28,6 @@ import { OrchestrationV2GetShellSnapshotError, OrchestrationV2GetThreadProjectionError, OrchestrationV2ThreadLaunchError, - ORCHESTRATION_WS_METHODS, type OrchestrationProjectShell, type ProjectEntriesFailure, type ProjectFileFailure, @@ -366,15 +365,7 @@ const RPC_REQUIRED_SCOPE = new Map([ [WS_METHODS.subscribeAuthAccess, AuthAccessReadScope], ]); -const ServerWsRpcGroup = WsRpcGroup.omit( - ORCHESTRATION_WS_METHODS.dispatchCommand, - ORCHESTRATION_WS_METHODS.getTurnDiff, - ORCHESTRATION_WS_METHODS.getFullThreadDiff, - ORCHESTRATION_WS_METHODS.replayEvents, - ORCHESTRATION_WS_METHODS.getArchivedShellSnapshot, - ORCHESTRATION_WS_METHODS.subscribeShell, - ORCHESTRATION_WS_METHODS.subscribeThread, -); +const ServerWsRpcGroup = WsRpcGroup; function toAuthAccessStreamEvent( change: PairingGrantStore.BootstrapCredentialChange | SessionStore.SessionCredentialChange, diff --git a/apps/web/src/components/BranchToolbar.tsx b/apps/web/src/components/BranchToolbar.tsx index c0be2df8e3..4d10ec29d8 100644 --- a/apps/web/src/components/BranchToolbar.tsx +++ b/apps/web/src/components/BranchToolbar.tsx @@ -12,7 +12,7 @@ import { import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react"; import { useComposerDraftStore, type DraftId } from "../composerDraftStore"; -import { useProject, useThread, useThreadShellsForProjectRefs } from "../state/entities"; +import { useProject, useThreadShell } from "../state/entities"; import { useIsMobile } from "../hooks/useMediaQuery"; import { type EnvMode, @@ -398,6 +398,7 @@ export const BranchToolbar = memo(function BranchToolbar({ () => scopeThreadRef(environmentId, threadId), [environmentId, threadId], ); + const serverThread = useThreadShell(threadRef); const draftThread = useComposerDraftStore((store) => draftId ? store.getDraftSession(draftId) : store.getDraftThreadByRef(threadRef), ); diff --git a/apps/web/src/components/BranchToolbarBranchSelector.tsx b/apps/web/src/components/BranchToolbarBranchSelector.tsx index b4d82af4c1..dd2b3b9236 100644 --- a/apps/web/src/components/BranchToolbarBranchSelector.tsx +++ b/apps/web/src/components/BranchToolbarBranchSelector.tsx @@ -26,7 +26,7 @@ import { readLocalApi } from "../localApi"; import { useOpenPrLink } from "../lib/openPullRequestLink"; import { shouldLoadNextBranchPageAfterScroll } from "../state/paginatedBranches"; import { usePaginatedBranches } from "../state/queries"; -import { useProject, useThread } from "../state/entities"; +import { useProject, useThreadShell } from "../state/entities"; import { useEnvironmentQuery } from "../state/query"; import { threadEnvironment } from "../state/threads"; import { useAtomCommand } from "../state/use-atom-command"; @@ -125,13 +125,11 @@ export function BranchToolbarBranchSelector({ () => scopeThreadRef(environmentId, threadId), [environmentId, threadId], ); - const serverThread = useThread(threadRef); + const serverThread = useThreadShell(threadRef); const serverSession = serverThread?.runtime ?? null; const draftThread = useComposerDraftStore((store) => draftId ? store.getDraftSession(draftId) : store.getDraftThreadByRef(threadRef), ); - const serverThread = useThread(threadRef, { waitForShell: draftThread !== null }); - const serverSession = serverThread?.session ?? null; const setDraftThreadContext = useComposerDraftStore((store) => store.setDraftThreadContext); const activeProjectRef = serverThread diff --git a/apps/web/src/components/ChatView.logic.ts b/apps/web/src/components/ChatView.logic.ts index 4a8386f914..63101e7046 100644 --- a/apps/web/src/components/ChatView.logic.ts +++ b/apps/web/src/components/ChatView.logic.ts @@ -11,12 +11,12 @@ import { type RunId, } from "@t3tools/contracts"; import * as DateTime from "effect/DateTime"; -import { presentThread } from "@t3tools/client-runtime/state/shell"; +import { presentThreadShell } from "@t3tools/client-runtime/state/shell"; import { type ChatMessage, type SessionPhase, type Thread } from "../types"; import { type ComposerImageAttachment, type DraftThreadState } from "../composerDraftStore"; import * as Schema from "effect/Schema"; import { appAtomRegistry } from "../rpc/atomRegistry"; -import { environmentThreadDetails } from "../state/threads"; +import { environmentThreadShells } from "../state/threads"; import { waitForAtomValue } from "../state/waitForAtomValue"; import { filterTerminalContextsWithText, @@ -87,44 +87,34 @@ export function buildLocalDraftThread( fallbackModelSelection: ModelSelection, ): Thread { const timestamp = DateTime.makeUnsafe(draftThread.createdAt); - return presentThread(draftThread.environmentId, { - thread: { - id: threadId, - projectId: draftThread.projectId, - title: "New thread", - providerInstanceId: fallbackModelSelection.instanceId, - modelSelection: fallbackModelSelection, - runtimeMode: draftThread.runtimeMode, - interactionMode: draftThread.interactionMode, - branch: draftThread.branch, - worktreePath: draftThread.worktreePath, - activeProviderThreadId: null, - lineage: { rootThreadId: threadId, parentThreadId: null, relationshipToParent: null }, - forkedFrom: null, - createdBy: "user", - creationSource: "web", - createdAt: timestamp, - updatedAt: timestamp, - archivedAt: null, - deletedAt: null, - }, - runs: [], - attempts: [], - nodes: [], - subagents: [], - providerSessions: [], - providerThreads: [], - providerTurns: [], - runtimeRequests: [], - messages: [], - plans: [], - turnItems: [], - checkpointScopes: [], - checkpoints: [], - contextHandoffs: [], - contextTransfers: [], - visibleTurnItems: [], + return presentThreadShell(draftThread.environmentId, { + id: threadId, + projectId: draftThread.projectId, + title: "New thread", + providerInstanceId: fallbackModelSelection.instanceId, + modelSelection: fallbackModelSelection, + runtimeMode: draftThread.runtimeMode, + interactionMode: draftThread.interactionMode, + branch: draftThread.branch, + worktreePath: draftThread.worktreePath, + activeProviderThreadId: null, + lineage: { rootThreadId: threadId, parentThreadId: null, relationshipToParent: null }, + forkedFrom: null, + createdBy: "user", + creationSource: "web", + latestRunId: null, + activeRunId: null, + status: "idle", + pendingRuntimeRequest: null, + latestVisibleMessage: null, + latestUserMessageAt: null, + hasActionableProposedPlan: false, + itemCount: 0, + visibleItemCount: 0, + createdAt: timestamp, updatedAt: timestamp, + archivedAt: null, + deletedAt: null, }); } @@ -385,9 +375,7 @@ export function isBranchMismatchDismissedForSession(key: string | null): boolean } export function threadHasStarted(thread: Thread | null | undefined): boolean { - return Boolean( - thread && (thread.latestRun !== null || thread.messages.length > 0 || thread.runtime !== null), - ); + return Boolean(thread && (thread.latestRun !== null || thread.itemCount > 0 || thread.runtime)); } // `threadProvider` is the open branded driver kind carried by the session. @@ -467,7 +455,7 @@ export async function waitForStartedServerThread( threadRef: ScopedThreadRef, timeoutMs = 1_000, ): Promise { - const threadAtom = environmentThreadDetails.detailAtom(threadRef); + const threadAtom = environmentThreadShells.threadShellAtom(threadRef); return waitForAtomValue({ registry: appAtomRegistry, atom: threadAtom, diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 2b6357ade4..cac2a6834c 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -4,6 +4,7 @@ import { type EnvironmentId, type MessageId, type ModelSelection, + type OrchestrationV2ThreadProjection, type ProjectScript, type ProjectId, type ProviderApprovalDecision, @@ -21,8 +22,12 @@ import { RuntimeMode, TerminalOpenInput, } from "@t3tools/contracts"; -import type { ThreadWorkEntry } from "@t3tools/client-runtime/state/shell"; import { type EnvironmentConnectionPresentation } from "@t3tools/client-runtime/connection"; +import { + deriveLatestThreadRun, + deriveThreadRuntime, +} from "@t3tools/client-runtime/state/thread-execution"; +import { derivePendingThreadRequests } from "@t3tools/client-runtime/state/thread-requests"; import { parseScopedThreadKey, scopedThreadKey, @@ -74,14 +79,12 @@ import { derivePendingApprovals, derivePendingUserInputs, derivePhase, - deriveTimelineEntries, deriveTimelineEntriesFromVisibleTurnItems, deriveRevertTurnCountByUserMessageId, deriveActiveWorkStartedAt, deriveActivePlanState, deriveTurnPlans, findLatestProposedPlan, - deriveWorkLogEntries, hasActionableProposedPlan, isLatestRunSettled, } from "../session-logic"; @@ -231,9 +234,8 @@ import { useEnvironments, usePrimaryEnvironment } from "../state/environments"; import { useProject, useProjects, - useThread, + useThreadProjection, useThreadShell, - useThreadProposedPlans, useThreadRefs, useThreadVisibleTurnItems, waitForThreadShell, @@ -341,9 +343,9 @@ import { useAssetUrls } from "../assets/assetUrls"; const IMAGE_ONLY_BOOTSTRAP_PROMPT = "[User attached one or more images without additional text. Respond using the conversation context and the attached image(s).]"; -const EMPTY_WORK_ENTRIES: ThreadWorkEntry[] = []; const EMPTY_PROVIDERS: ServerProvider[] = []; const EMPTY_PROVIDER_SKILLS: ServerProvider["skills"] = []; +const EMPTY_ATTACHMENT_IDS: string[] = []; const EMPTY_PENDING_USER_INPUT_ANSWERS: Record = {}; function useDraftHeroLayoutTransition(isDraftHeroState: boolean) { const transitionGroupRef = useRef(null); @@ -458,6 +460,14 @@ type EnvironmentUnavailableState = { readonly connection: EnvironmentConnectionPresentation; }; +<<<<<<< HEAD +======= +type ThreadPlanCatalogEntry = { + readonly id: ThreadId; + readonly projection: OrchestrationV2ThreadProjection; +}; + +>>>>>>> d454b3880e (Retire V1 client orchestration parity) function eventPathContainsSelector(event: Event, selector: string): boolean { const path = event.composedPath(); if (path.length === 0 && event.target) { @@ -663,6 +673,7 @@ const PersistentThreadTerminalDrawer = memo(function PersistentThreadTerminalDra const openTerminal = useAtomCommand(terminalEnvironment.open, "terminal open"); const writeTerminal = useAtomCommand(terminalEnvironment.write, "terminal write"); const closeTerminalMutation = useAtomCommand(terminalEnvironment.close, "terminal close"); + const serverThread = useThreadShell(threadRef); const draftThread = useComposerDraftStore((store) => store.getDraftThreadByRef(threadRef)); const serverThread = useThread(threadRef, { waitForShell: draftThread !== null }); const projectRef = serverThread @@ -1032,6 +1043,7 @@ const PersistentThreadTerminalPanel = memo(function PersistentThreadTerminalPane newShortcutLabel, closeShortcutLabel, }: PersistentThreadTerminalPanelProps) { + const serverThread = useThreadShell(threadRef); const draftThread = useComposerDraftStore((store) => store.getDraftThreadByRef(threadRef)); const serverThread = useThread(threadRef, { waitForShell: draftThread !== null }); const projectRef = serverThread @@ -1242,10 +1254,18 @@ function ChatViewContent(props: ChatViewProps) { ); const composerDraftTarget: ScopedThreadRef | DraftId = routeKind === "server" ? routeThreadRef : props.draftId; - const serverThread = useThread(routeKind === "server" ? routeThreadRef : null); + const serverThread = useThreadShell(routeKind === "server" ? routeThreadRef : null); + const serverThreadProjection = useThreadProjection( + routeKind === "server" ? routeThreadRef : null, + ); + const serverProjection = serverThreadProjection?.projection ?? null; const serverVisibleTurnItems = useThreadVisibleTurnItems( routeKind === "server" ? routeThreadRef : null, ); + const committedServerMessageIds = useMemo( + () => new Set(serverProjection?.messages.map((message) => message.id) ?? []), + [serverProjection], + ); const markThreadVisited = useUiStateStore((store) => store.markThreadVisited); const activeThreadLastVisitedAt = useUiStateStore( (store) => store.threadLastVisitedAtById[routeThreadKey], @@ -1491,6 +1511,16 @@ function ChatViewContent(props: ChatViewProps) { ); const isServerThread = routeKind === "server" && serverThread !== null; const activeThread = isServerThread ? serverThread : localDraftThread; + const serverLatestRun = useMemo( + () => (serverProjection === null ? null : deriveLatestThreadRun(serverProjection)), + [serverProjection], + ); + const serverRuntime = useMemo( + () => (serverProjection === null ? null : deriveThreadRuntime(serverProjection)), + [serverProjection], + ); + const activeLatestRun = isServerThread ? serverLatestRun : (activeThread?.latestRun ?? null); + const activeRuntime = isServerThread ? serverRuntime : (activeThread?.runtime ?? null); const parentSubagentThreadId = activeThread?.lineage.relationshipToParent === "subagent" ? activeThread.lineage.parentThreadId @@ -1514,7 +1544,7 @@ function ChatViewContent(props: ChatViewProps) { [parentSubagentThread?.title, parentSubagentThreadRef], ); const threadError = isServerThread - ? (localServerError ?? serverThread?.runtime?.lastError ?? null) + ? (localServerError ?? serverRuntime?.lastError ?? null) : localDraftError; // Dismissals can only mask the shown error, never clear it: a server thread // keeps its error in session.lastError, so clearing the local shadow would @@ -1545,7 +1575,11 @@ function ChatViewContent(props: ChatViewProps) { const isLocalDraftThread = !isServerThread && localDraftThread !== undefined; const canCheckoutPullRequestIntoThread = isLocalDraftThread; const activeThreadId = activeThread?.id ?? null; +<<<<<<< HEAD const activeThreadEnvironmentId = activeThread?.environmentId ?? null; +======= + const activeMessageCount = isServerThread ? committedServerMessageIds.size : 0; +>>>>>>> d849d1caf9 (Retire V1 client orchestration parity) const runningTerminalIds = useThreadRunningTerminalIds({ environmentId: activeThread?.environmentId ?? null, threadId: activeThreadId, @@ -1689,7 +1723,6 @@ function ChatViewContent(props: ChatViewProps) { const existingThreadKeys = new Set([...serverThreadKeys, ...draftThreadKeys]); return openTerminalThreadKeys.filter((nextThreadKey) => existingThreadKeys.has(nextThreadKey)); }, [draftThreadKeys, openTerminalThreadKeys, serverThreadKeys]); - const activeLatestRun = activeThread?.latestRun ?? null; const sourcePlanThreadRef = useMemo(() => { const sourceThreadId = activeLatestRun?.sourcePlanRef?.threadId; if (!activeThread || !sourceThreadId || sourceThreadId === activeThread.id) { @@ -1697,22 +1730,22 @@ function ChatViewContent(props: ChatViewProps) { } return scopeThreadRef(activeThread.environmentId, sourceThreadId); }, [activeLatestRun?.sourcePlanRef?.threadId, activeThread]); - const sourceThreadProposedPlans = useThreadProposedPlans(sourcePlanThreadRef); + const sourceThreadProjection = useThreadProjection(sourcePlanThreadRef); const threadPlanCatalog = useMemo(() => { - if (!activeThread) { + if (!activeThread || serverProjection === null) { return []; } const entries: ThreadPlanCatalogEntry[] = [ - { id: activeThread.id, proposedPlans: activeThread.proposedPlans }, + { id: activeThread.id, projection: serverProjection }, ]; - if (sourcePlanThreadRef) { + if (sourcePlanThreadRef && sourceThreadProjection !== null) { entries.push({ id: sourcePlanThreadRef.threadId, - proposedPlans: sourceThreadProposedPlans, + projection: sourceThreadProjection.projection, }); } return entries; - }, [activeThread, sourcePlanThreadRef, sourceThreadProposedPlans]); + }, [activeThread, serverProjection, sourcePlanThreadRef, sourceThreadProjection]); useEffect(() => { setMountedTerminalThreadKeys((currentThreadIds) => { const nextThreadIds = reconcileMountedTerminalThreadIds({ @@ -1728,7 +1761,7 @@ function ChatViewContent(props: ChatViewProps) { : nextThreadIds; }); }, [activeThreadKey, existingOpenTerminalThreadKeys, terminalUiState.terminalOpen]); - const latestRunSettled = isLatestRunSettled(activeLatestRun, activeThread?.runtime ?? null); + const latestRunSettled = isLatestRunSettled(activeLatestRun, activeRuntime); const activeProjectRef = activeThread ? scopeProjectRef(activeThread.environmentId, activeThread.projectId) : null; @@ -2049,19 +2082,21 @@ function ChatViewContent(props: ChatViewProps) { selectedProviderByThreadId ?? threadProvider, ); const selectedProvider: ProviderDriverKind = lockedProvider ?? unlockedSelectedProvider; - const phase = derivePhase(activeThread?.runtime ?? null); - const threadWorkEntries = activeThread?.workEntries ?? EMPTY_WORK_ENTRIES; - const workLogEntries = useMemo( - () => deriveWorkLogEntries(threadWorkEntries), - [threadWorkEntries], + const phase = derivePhase(activeRuntime); + const pendingRequests = useMemo( + () => + serverProjection === null + ? { approvals: [], userInputs: [] } + : derivePendingThreadRequests(serverProjection), + [serverProjection], ); const pendingApprovals = useMemo( - () => derivePendingApprovals(activeThread?.pendingApprovals ?? []), - [activeThread?.pendingApprovals], + () => derivePendingApprovals(pendingRequests.approvals), + [pendingRequests.approvals], ); const pendingUserInputs = useMemo( - () => derivePendingUserInputs(activeThread?.pendingUserInputs ?? []), - [activeThread?.pendingUserInputs], + () => derivePendingUserInputs(pendingRequests.userInputs), + [pendingRequests.userInputs], ); const activePendingUserInput = pendingUserInputs[0] ?? null; const activePendingDraftAnswers = useMemo( @@ -2101,11 +2136,8 @@ function ChatViewContent(props: ChatViewProps) { if (!latestRunSettled) { return null; } - return findLatestProposedPlan( - activeThread?.proposedPlans ?? [], - activeLatestRun?.runId ?? null, - ); - }, [activeLatestRun?.runId, activeThread?.proposedPlans, latestRunSettled]); + return findLatestProposedPlan(serverProjection, activeLatestRun?.runId ?? null); + }, [activeLatestRun?.runId, latestRunSettled, serverProjection]); const sidebarProposedPlan = useMemo( () => findSidebarProposedPlan({ @@ -2117,8 +2149,8 @@ function ChatViewContent(props: ChatViewProps) { [activeLatestRun, activeThread?.id, latestRunSettled, threadPlanCatalog], ); const activePlan = useMemo( - () => deriveActivePlanState(activeThread?.todoPlans ?? [], activeLatestRun?.runId ?? undefined), - [activeLatestRun?.runId, activeThread?.todoPlans], + () => deriveActivePlanState(serverProjection, activeLatestRun?.runId ?? undefined), + [activeLatestRun?.runId, serverProjection], ); // Current step for the in-chat working row: only for the running turn's own // plan (deriveActivePlanState falls back to older turns' plans, which must @@ -2158,7 +2190,7 @@ function ChatViewContent(props: ChatViewProps) { const isWorking = phase === "running" || isSendBusy || isConnecting || isRevertingCheckpoint; const activeWorkStartedAt = deriveActiveWorkStartedAt( activeLatestRun, - activeThread?.runtime ?? null, + activeRuntime, localDispatchStartedAt, ); useEffect(() => { @@ -2221,7 +2253,6 @@ function ChatViewContent(props: ChatViewProps) { return next; }); }, []); - const serverMessages = activeThread?.messages; const committedServerAttachmentIds = useMemo(() => { const attachmentIds = new Set(); for (const row of serverVisibleTurnItems) { @@ -2232,16 +2263,7 @@ function ChatViewContent(props: ChatViewProps) { } return [...attachmentIds]; }, [serverVisibleTurnItems]); - const draftAttachmentIds = useMemo(() => { - const attachmentIds = new Set(); - for (const message of serverMessages ?? []) { - for (const attachment of message.attachments ?? []) { - attachmentIds.add(attachment.id); - } - } - return [...attachmentIds]; - }, [serverMessages]); - const serverAttachmentIds = isServerThread ? committedServerAttachmentIds : draftAttachmentIds; + const serverAttachmentIds = isServerThread ? committedServerAttachmentIds : EMPTY_ATTACHMENT_IDS; const serverAttachmentResources = useMemo( () => serverAttachmentIds.map((attachmentId) => ({ @@ -2261,31 +2283,16 @@ function ChatViewContent(props: ChatViewProps) { ), [serverAttachmentIds, serverAttachmentUrls], ); - const displayServerMessages = useMemo>(() => { - if (!serverMessages) return []; - return serverMessages.map((message) => { - if (!message.attachments || message.attachments.length === 0) { - return message; - } - return { - ...message, - attachments: message.attachments.map((attachment) => { - const previewUrl = serverAttachmentUrlById.get(attachment.id); - return previewUrl ? { ...attachment, previewUrl } : attachment; - }), - }; - }); - }, [serverAttachmentUrlById, serverMessages]); useEffect(() => { - if (typeof Image === "undefined" || displayServerMessages.length === 0) { + if (typeof Image === "undefined" || serverVisibleTurnItems.length === 0) { return; } const cleanups: Array<() => void> = []; - const userMessagesById = new Map( - displayServerMessages - .filter((message) => message.role === "user") - .map((message) => [String(message.id), message] as const), + const userMessagesById = new Map( + serverVisibleTurnItems.flatMap((row) => + row.item.type === "user_message" ? [[String(row.item.messageId), row.item] as const] : [], + ), ); for (const [messageId, handoffPreviewUrls] of Object.entries( @@ -2296,12 +2303,16 @@ function ChatViewContent(props: ChatViewProps) { } const serverMessage = userMessagesById.get(messageId); - if (!serverMessage?.attachments || serverMessage.attachments.length === 0) { + if (serverMessage === undefined || serverMessage.attachments.length === 0) { continue; } const serverPreviewUrls = serverMessage.attachments.flatMap((attachment) => - attachment.type === "image" && attachment.previewUrl ? [attachment.previewUrl] : [], + attachment.type === "image" + ? [serverAttachmentUrlById.get(attachment.id)].filter( + (previewUrl): previewUrl is string => previewUrl !== undefined, + ) + : [], ); if ( serverPreviewUrls.length === 0 || @@ -2359,82 +2370,46 @@ function ChatViewContent(props: ChatViewProps) { cleanup(); } }; - }, [attachmentPreviewHandoffByMessageId, clearAttachmentPreviewHandoff, displayServerMessages]); - const timelineMessages = useMemo(() => { - const messages = displayServerMessages; - const serverMessagesWithPreviewHandoff = - Object.keys(attachmentPreviewHandoffByMessageId).length === 0 - ? messages - : // Spread only fires for the few messages that actually changed; - // unchanged ones early-return their original reference. - // In-place mutation would break React's immutable state contract. - messages.map((message) => { - if ( - message.role !== "user" || - !message.attachments || - message.attachments.length === 0 - ) { - return message; - } - const handoffPreviewUrls = attachmentPreviewHandoffByMessageId[message.id]; - if (!handoffPreviewUrls || handoffPreviewUrls.length === 0) { - return message; - } - - let changed = false; - let imageIndex = 0; - const attachments = message.attachments.map((attachment) => { - if (attachment.type !== "image") { - return attachment; - } - const handoffPreviewUrl = handoffPreviewUrls[imageIndex]; - imageIndex += 1; - if (!handoffPreviewUrl || attachment.previewUrl === handoffPreviewUrl) { - return attachment; - } - changed = true; - return { - ...attachment, - previewUrl: handoffPreviewUrl, - }; - }); - - return changed ? { ...message, attachments } : message; - }); - - if (optimisticUserMessages.length === 0) { - return serverMessagesWithPreviewHandoff; + }, [ + attachmentPreviewHandoffByMessageId, + clearAttachmentPreviewHandoff, + serverAttachmentUrlById, + serverVisibleTurnItems, + ]); + const timelineAttachmentUrlById = useMemo(() => { + const urls = new Map(serverAttachmentUrlById); + for (const row of serverVisibleTurnItems) { + if (row.item.type !== "user_message") continue; + const handoffUrls = attachmentPreviewHandoffByMessageId[row.item.messageId]; + if (handoffUrls === undefined) continue; + let imageIndex = 0; + for (const attachment of row.item.attachments) { + if (attachment.type !== "image") continue; + const handoffUrl = handoffUrls[imageIndex]; + imageIndex += 1; + if (handoffUrl !== undefined) urls.set(attachment.id, handoffUrl); + } } - const serverIds = new Set(serverMessagesWithPreviewHandoff.map((message) => message.id)); - const pendingMessages = optimisticUserMessages.filter((message) => !serverIds.has(message.id)); - if (pendingMessages.length === 0) { - return serverMessagesWithPreviewHandoff; - } - return [...serverMessagesWithPreviewHandoff, ...pendingMessages]; - }, [attachmentPreviewHandoffByMessageId, displayServerMessages, optimisticUserMessages]); + return urls; + }, [attachmentPreviewHandoffByMessageId, serverAttachmentUrlById, serverVisibleTurnItems]); const serverTimelineEntries = useMemo( () => deriveTimelineEntriesFromVisibleTurnItems({ visibleTurnItems: serverVisibleTurnItems, optimisticMessages: optimisticUserMessages, - attachmentUrlById: serverAttachmentUrlById, - ...(serverThread === null + attachmentUrlById: timelineAttachmentUrlById, + ...(serverProjection === null ? {} : { - attempts: serverThread.projection.attempts, - nodes: serverThread.projection.nodes, + attempts: serverProjection.attempts, + nodes: serverProjection.nodes, }), }), - [ - optimisticUserMessages, - serverVisibleTurnItems, - serverAttachmentUrlById, - serverThread?.projection.attempts, - serverThread?.projection.nodes, - ], + [optimisticUserMessages, serverVisibleTurnItems, serverProjection, timelineAttachmentUrlById], ); const draftTimelineEntries = useMemo( () => +<<<<<<< HEAD deriveTimelineEntries( timelineMessages, activeThread?.proposedPlans ?? [], @@ -2442,9 +2417,21 @@ function ChatViewContent(props: ChatViewProps) { turnPlans, ), [activeThread?.proposedPlans, timelineMessages, turnPlans, workLogEntries], +======= + optimisticUserMessages.map( + (message) => + ({ + id: message.id, + kind: "message", + createdAt: message.createdAt, + message, + }) as const, + ), + [optimisticUserMessages], +>>>>>>> d454b3880e (Retire V1 client orchestration parity) ); const timelineEntries = isServerThread ? serverTimelineEntries : draftTimelineEntries; - const { turnDiffSummaries } = useTurnDiffSummaries(activeThread); + const { turnDiffSummaries } = useTurnDiffSummaries(serverProjection); const turnDiffSummaryByAssistantMessageId = useMemo(() => { const byMessageId = new Map(); for (const summary of turnDiffSummaries) { @@ -2500,7 +2487,7 @@ function ChatViewContent(props: ChatViewProps) { ?.instanceId ?? null; const activeProviderInstanceId = selectedProviderInstanceId ?? - activeThread?.runtime?.providerInstanceId ?? + activeRuntime?.providerInstanceId ?? activeThread?.modelSelection.instanceId ?? activeProject?.defaultModelSelection?.instanceId ?? null; @@ -2582,9 +2569,7 @@ function ChatViewContent(props: ChatViewProps) { } }, [activeThreadRef, diffOpen, isServerThread, onDiffPanelOpen]); - const envLocked = Boolean( - activeThread && (activeThread.messages.length > 0 || activeThread.runtime !== null), - ); + const envLocked = Boolean(activeThread && (activeMessageCount > 0 || activeRuntime !== null)); // Handle environment change for draft threads. When the user picks a // different environment we update the draft context to point at the physical @@ -3936,17 +3921,18 @@ function ChatViewContent(props: ChatViewProps) { useEffect(() => { if (!activeThread?.id) return; - if (activeThread.messages.length === 0) { + if (activeMessageCount === 0) { return; } - const serverIds = new Set(activeThread.messages.map((message) => message.id)); - const removedMessages = optimisticUserMessages.filter((message) => serverIds.has(message.id)); + const removedMessages = optimisticUserMessages.filter((message) => + committedServerMessageIds.has(message.id), + ); if (removedMessages.length === 0) { return; } const timer = window.setTimeout(() => { setOptimisticUserMessages((existing) => - existing.filter((message) => !serverIds.has(message.id)), + existing.filter((message) => !committedServerMessageIds.has(message.id)), ); }, 0); for (const removedMessage of removedMessages) { @@ -3960,7 +3946,13 @@ function ChatViewContent(props: ChatViewProps) { return () => { window.clearTimeout(timer); }; - }, [activeThread?.id, activeThread?.messages, handoffAttachmentPreviews, optimisticUserMessages]); + }, [ + activeMessageCount, + activeThread?.id, + committedServerMessageIds, + handoffAttachmentPreviews, + optimisticUserMessages, + ]); useEffect(() => { setOptimisticUserMessages((existing) => { @@ -3986,7 +3978,7 @@ function ChatViewContent(props: ChatViewProps) { const canOverrideServerThreadEnvMode = Boolean( isServerThread && activeThread && - activeThread.messages.length === 0 && + activeMessageCount === 0 && activeThread.worktreePath === null && !envLocked, ); @@ -5068,7 +5060,7 @@ function ChatViewContent(props: ChatViewProps) { return; } const threadIdForSend = activeThread.id; - const isFirstMessage = !isServerThread || activeThread.messages.length === 0; + const isFirstMessage = !isServerThread || activeMessageCount === 0; const baseBranchForWorktree = isFirstMessage && sendEnvMode === "worktree" && !activeThread.worktreePath ? activeThreadBranch @@ -5561,56 +5553,50 @@ function ChatViewContent(props: ChatViewProps) { setActivePendingUserInputQuestionIndex(Math.max(activePendingProgress.questionIndex - 1, 0)); }, [activePendingProgress, setActivePendingUserInputQuestionIndex]); - const onSubmitPlanFollowUp = useCallback( - async ({ - text, - interactionMode: nextInteractionMode, - }: { - text: string; - interactionMode: "default" | "plan"; - }) => { - if ( - !activeThread || - !isServerThread || - isSendBusy || - isConnecting || - sendInFlightRef.current - ) { - return; - } + async function onSubmitPlanFollowUp({ + text, + interactionMode: nextInteractionMode, + }: { + text: string; + interactionMode: "default" | "plan"; + }) { + if (!activeThread || !isServerThread || isSendBusy || isConnecting || sendInFlightRef.current) { + return; + } - const trimmed = text.trim(); - if (!trimmed) { - return; - } + const trimmed = text.trim(); + if (!trimmed) { + return; + } - const sendCtx = composerRef.current?.getSendContext(); - if (!sendCtx?.providerAvailable) { - return; - } - const { - selectedProvider: ctxSelectedProvider, - selectedModel: ctxSelectedModel, - selectedProviderModels: ctxSelectedProviderModels, - selectedPromptEffort: ctxSelectedPromptEffort, - selectedModelSelection: ctxSelectedModelSelection, - } = sendCtx; + const sendCtx = composerRef.current?.getSendContext(); + if (!sendCtx) { + return; + } + const { + selectedProvider: ctxSelectedProvider, + selectedModel: ctxSelectedModel, + selectedProviderModels: ctxSelectedProviderModels, + selectedPromptEffort: ctxSelectedPromptEffort, + selectedModelSelection: ctxSelectedModelSelection, + } = sendCtx; - const threadIdForSend = activeThread.id; - const messageIdForSend = newMessageId(); - const messageCreatedAt = new Date().toISOString(); - const outgoingMessageText = formatOutgoingPrompt({ - provider: ctxSelectedProvider, - model: ctxSelectedModel, - models: ctxSelectedProviderModels, - effort: ctxSelectedPromptEffort, - text: trimmed, - }); + const threadIdForSend = activeThread.id; + const messageIdForSend = newMessageId(); + const messageCreatedAt = new Date().toISOString(); + const outgoingMessageText = formatOutgoingPrompt({ + provider: ctxSelectedProvider, + model: ctxSelectedModel, + models: ctxSelectedProviderModels, + effort: ctxSelectedPromptEffort, + text: trimmed, + }); - sendInFlightRef.current = true; - beginLocalDispatch({ preparingWorktree: false }); - setThreadError(threadIdForSend, null); + sendInFlightRef.current = true; + beginLocalDispatch({ preparingWorktree: false }); + setThreadError(threadIdForSend, null); +<<<<<<< HEAD // Position this sent row once LegendList has measured the anchored tail. isAtEndRef.current = true; timelineScrollModeRef.current = "anchoring-new-turn"; @@ -5624,41 +5610,38 @@ function ChatViewContent(props: ChatViewProps) { threadKey: scopedThreadKey(scopeThreadRef(activeThread.environmentId, threadIdForSend)), messageId: messageIdForSend, }); +======= + // Scroll to the current end *before* adding the optimistic message. + isAtEndRef.current = true; + showScrollDebouncer.current.cancel(); + setShowScrollToBottom(false); + await legendListRef.current?.scrollToEnd?.({ animated: false }); +>>>>>>> d454b3880e (Retire V1 client orchestration parity) - setOptimisticUserMessages((existing) => [ - ...existing, - { - id: messageIdForSend, - role: "user", - text: outgoingMessageText, - runId: null, - createdAt: messageCreatedAt, - updatedAt: messageCreatedAt, - streaming: false, - }, - ]); - - const settingsResult = await persistThreadSettingsForNextTurn({ - threadId: threadIdForSend, + setOptimisticUserMessages((existing) => [ + ...existing, + { + id: messageIdForSend, + role: "user", + text: outgoingMessageText, + runId: null, createdAt: messageCreatedAt, - modelSelection: ctxSelectedModelSelection, - ...(localCheckoutBranchMismatch - ? { branch: localCheckoutBranchMismatch.currentBranch } - : {}), - runtimeMode, - interactionMode: nextInteractionMode, - }); - let failure: AtomCommandResult | null = - settingsResult._tag === "Failure" ? settingsResult : null; + updatedAt: messageCreatedAt, + streaming: false, + }, + ]); - if (failure === null) { - // Keep the mode toggle and plan-follow-up banner in sync immediately - // while the same-thread implementation turn is starting. - setComposerDraftInteractionMode( - scopeThreadRef(activeThread.environmentId, threadIdForSend), - nextInteractionMode, - ); + const settingsResult = await persistThreadSettingsForNextTurn({ + threadId: threadIdForSend, + createdAt: messageCreatedAt, + modelSelection: ctxSelectedModelSelection, + runtimeMode, + interactionMode: nextInteractionMode, + }); + let failure: AtomCommandResult | null = + settingsResult._tag === "Failure" ? settingsResult : null; +<<<<<<< HEAD const startResult = await startThreadTurn({ environmentId, input: { @@ -5695,15 +5678,56 @@ function ChatViewContent(props: ChatViewProps) { setOptimisticUserMessages((existing) => existing.filter((message) => message.id !== messageIdForSend), +======= + if (failure === null) { + // Keep the mode toggle and plan-follow-up banner in sync immediately + // while the same-thread implementation turn is starting. + setComposerDraftInteractionMode( + scopeThreadRef(activeThread.environmentId, threadIdForSend), + nextInteractionMode, +>>>>>>> d454b3880e (Retire V1 client orchestration parity) ); - if (!isAtomCommandInterrupted(failure)) { - const error = squashAtomCommandFailure(failure); - setThreadError( - threadIdForSend, - error instanceof Error ? error.message : "Failed to send plan follow-up.", - ); + + const startResult = await startThreadTurn({ + environmentId, + input: { + threadId: threadIdForSend, + message: { + messageId: messageIdForSend, + role: "user", + text: outgoingMessageText, + attachments: [], + }, + modelSelection: ctxSelectedModelSelection, + titleSeed: activeThread.title, + runtimeMode, + interactionMode: nextInteractionMode, + ...(nextInteractionMode === "default" && activeProposedPlan + ? { + sourceProposedPlan: { + threadId: activeThread.id, + planId: activeProposedPlan.id, + }, + } + : {}), + createdAt: messageCreatedAt, + }, + }); + failure = startResult._tag === "Failure" ? startResult : null; + } + + if (failure === null) { + // Optimistically open the plan sidebar when implementing (not refining). + // "default" mode here means the agent is executing the plan, which produces + // step-tracking activities that the sidebar will display. + if (nextInteractionMode === "default" && autoOpenPlanSidebar) { + planSidebarDismissedForTurnRef.current = null; + if (activeThreadRef) { + useRightPanelStore.getState().open(activeThreadRef, "plan"); + } } sendInFlightRef.current = false; +<<<<<<< HEAD resetLocalDispatch(); }, [ @@ -5727,6 +5751,24 @@ function ChatViewContent(props: ChatViewProps) { composerRef, ], ); +======= + return; + } + + setOptimisticUserMessages((existing) => + existing.filter((message) => message.id !== messageIdForSend), + ); + if (!isAtomCommandInterrupted(failure)) { + const error = squashAtomCommandFailure(failure); + setThreadError( + threadIdForSend, + error instanceof Error ? error.message : "Failed to send plan follow-up.", + ); + } + sendInFlightRef.current = false; + resetLocalDispatch(); + } +>>>>>>> d454b3880e (Retire V1 client orchestration parity) const onImplementPlanInNewThread = useCallback(async () => { if ( @@ -5892,14 +5934,14 @@ function ChatViewContent(props: ChatViewProps) { } const reason = getStartedThreadModelChangeBlockReason({ providers: providerStatuses, - hasStartedSession: activeThread.runtime !== null, + hasStartedSession: activeRuntime !== null, currentModelSelection: activeThread.modelSelection, - currentProviderInstanceId: activeThread.runtime?.providerInstanceId ?? null, + currentProviderInstanceId: activeRuntime?.providerInstanceId ?? null, nextModelSelection: { instanceId, model }, }); return reason ? `${reason.description} Start a new thread to use this model.` : null; }, - [activeThread, providerStatuses], + [activeRuntime, activeThread, providerStatuses], ); const onProviderModelSelect = useCallback( @@ -5918,9 +5960,9 @@ function ChatViewContent(props: ChatViewProps) { scheduleComposerFocus(); return; } - if (lockedProvider !== null && activeThread.runtime?.providerInstanceId) { + if (lockedProvider !== null && activeRuntime?.providerInstanceId) { const currentEntry = providerStatuses.find( - (snapshot) => snapshot.instanceId === activeThread.runtime?.providerInstanceId, + (snapshot) => snapshot.instanceId === activeRuntime.providerInstanceId, ); if ( currentEntry?.continuation?.groupKey && @@ -5947,9 +5989,9 @@ function ChatViewContent(props: ChatViewProps) { }; const modelChangeBlockReason = getStartedThreadModelChangeBlockReason({ providers: providerStatuses, - hasStartedSession: activeThread.runtime !== null, + hasStartedSession: activeRuntime !== null, currentModelSelection: activeThread.modelSelection, - currentProviderInstanceId: activeThread.runtime?.providerInstanceId ?? null, + currentProviderInstanceId: activeRuntime?.providerInstanceId ?? null, nextModelSelection, }); if (modelChangeBlockReason) { @@ -5970,6 +6012,7 @@ function ChatViewContent(props: ChatViewProps) { }, [ activeThread, + activeRuntime, lockedProvider, scheduleComposerFocus, setComposerDraftModelSelection, @@ -6464,7 +6507,7 @@ function ChatViewContent(props: ChatViewProps) { providerStatuses={providerStatuses as ServerProvider[]} activeProjectDefaultModelSelection={activeProject?.defaultModelSelection} activeThreadModelSelection={activeThread?.modelSelection} - activeThreadWorkEntries={activeThread?.workEntries} + activeThreadVisibleTurnItems={serverVisibleTurnItems} resolvedTheme={resolvedTheme} settings={settings} keybindings={keybindings} diff --git a/apps/web/src/components/DiffPanel.tsx b/apps/web/src/components/DiffPanel.tsx index 9d545bf2dd..a85e53d985 100644 --- a/apps/web/src/components/DiffPanel.tsx +++ b/apps/web/src/components/DiffPanel.tsx @@ -39,7 +39,7 @@ import { } from "../lib/diffRendering"; import { areAllDiffFilesCollapsed, toggleAllDiffFiles } from "../lib/diffCollapse"; import { useTurnDiffSummaries } from "../hooks/useTurnDiffSummaries"; -import { useProject, useThread } from "../state/entities"; +import { useProject, useThreadProjection, useThreadShell } from "../state/entities"; import { resolveThreadRouteRef } from "../threadRoutes"; import { useClientSettings } from "../hooks/useSettings"; import { formatShortTimestamp } from "../timestampFormat"; @@ -123,7 +123,8 @@ export default function DiffPanel({ select: (params) => resolveThreadRouteRef(params), }); const activeThreadId = routeThreadRef?.threadId ?? null; - const activeThread = useThread(routeThreadRef); + const activeThread = useThreadShell(routeThreadRef); + const activeThreadProjection = useThreadProjection(routeThreadRef)?.projection ?? null; const activeProjectId = activeThread?.projectId ?? null; const activeProject = useProject( activeThread && activeProjectId @@ -162,7 +163,7 @@ export default function DiffPanel({ ); const isGitRepo = gitStatusQuery.data?.isRepo ?? true; const { turnDiffSummaries, inferredCheckpointTurnCountByRunId } = - useTurnDiffSummaries(activeThread); + useTurnDiffSummaries(activeThreadProjection); const orderedTurnDiffSummaries = useMemo( () => [...turnDiffSummaries].toSorted((left, right) => { diff --git a/apps/web/src/components/GitActionsControl.tsx b/apps/web/src/components/GitActionsControl.tsx index b97a267d99..47f95f262c 100644 --- a/apps/web/src/components/GitActionsControl.tsx +++ b/apps/web/src/components/GitActionsControl.tsx @@ -79,7 +79,7 @@ import { useVcsInitAction, useVcsPullAction, } from "~/lib/sourceControlActions"; -import { useThread } from "~/state/entities"; +import { useThreadShell } from "~/state/entities"; import { useEnvironmentQuery } from "~/state/query"; import { serverEnvironment } from "~/state/server"; import { sourceControlEnvironment } from "~/state/sourceControl"; @@ -1018,6 +1018,7 @@ export default function GitActionsControl({ () => (activeThreadRef ? { threadRef: activeThreadRef } : undefined), [activeThreadRef], ); + const activeServerThread = useThreadShell(activeThreadRef); const activeDraftThread = useComposerDraftStore((store) => draftId ? store.getDraftSession(draftId) diff --git a/apps/web/src/components/Sidebar.logic.test.ts b/apps/web/src/components/Sidebar.logic.test.ts index 5342ec3cfe..fa3de6b1e1 100644 --- a/apps/web/src/components/Sidebar.logic.test.ts +++ b/apps/web/src/components/Sidebar.logic.test.ts @@ -44,7 +44,7 @@ import { type Project, type Thread, } from "../types"; -import { makeThreadFixture } from "../test-fixtures"; +import { makeThreadFixture, type ThreadFixtureOverrides } from "../test-fixtures"; const localEnvironmentId = EnvironmentId.make("environment-local"); @@ -1304,7 +1304,7 @@ function makeProject(overrides: Partial = {}): Project { }; } -function makeThread(overrides: Partial = {}): Thread { +function makeThread(overrides: ThreadFixtureOverrides = {}): Thread { return makeThreadFixture({ id: ThreadId.make("thread-1"), environmentId: localEnvironmentId, diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index 515251bcb0..3d74ee1ebc 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -1,6 +1,7 @@ import type { EnvironmentId, ModelSelection, + OrchestrationV2ProjectedTurnItem, PreviewAnnotationPayload, ProviderApprovalDecision, ProviderInteractionMode, @@ -221,7 +222,11 @@ import { type AppModelOption, getAppModelOptionsForInstance } from "../../modelS import type { UnifiedSettings } from "@t3tools/contracts/settings"; import type { SessionPhase, Thread } from "../../types"; import type { PendingUserInputDraftAnswer } from "../../pendingUserInput"; -import type { PendingApproval, PendingUserInput } from "../../session-logic"; +import type { + LatestProposedPlanState, + PendingApproval, + PendingUserInput, +} from "../../session-logic"; import { resolveComposerDispatchMode, type ComposerDispatchMode } from "./composerDispatch"; import { deriveLatestContextWindowSnapshot, @@ -547,9 +552,13 @@ export interface ChatComposerProps { // Plan showPlanFollowUpPrompt: boolean; +<<<<<<< HEAD activeProposedPlan: Thread["proposedPlans"][number] | null; <<<<<<< HEAD ======= +======= + activeProposedPlan: LatestProposedPlanState | null; +>>>>>>> d454b3880e (Retire V1 client orchestration parity) activePlan: { runId?: RunId | null } | null; sidebarProposedPlan: { runId?: RunId | null } | null; planSidebarLabel: string; @@ -567,7 +576,7 @@ export interface ChatComposerProps { activeThreadModelSelection: ModelSelection | null | undefined; // Context window - activeThreadWorkEntries: Thread["workEntries"] | undefined; + activeThreadVisibleTurnItems: ReadonlyArray | undefined; // Misc resolvedTheme: "light" | "dark"; @@ -659,7 +668,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) providerStatuses, activeProjectDefaultModelSelection, activeThreadModelSelection, - activeThreadWorkEntries, + activeThreadVisibleTurnItems, resolvedTheme, settings, keybindings, @@ -939,8 +948,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) // Context window // ------------------------------------------------------------------ const activeContextWindow = useMemo( - () => deriveLatestContextWindowSnapshot(activeThreadWorkEntries ?? []), - [activeThreadWorkEntries], + () => deriveLatestContextWindowSnapshot(activeThreadVisibleTurnItems ?? []), + [activeThreadVisibleTurnItems], ); const activeThreadProviderDisplayName = useMemo(() => { if (!activeThreadModelSelection) return null; diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsx index f5fc029c0d..99a7a0875a 100644 --- a/apps/web/src/components/chat/MessagesTimeline.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.tsx @@ -28,7 +28,7 @@ import { import { LegendList, type LegendListRef } from "@legendapp/list/react"; import { FileDiff } from "@pierre/diffs/react"; import { - deriveTimelineEntries, + type TimelineEntry, workEntryIndicatesToolFailure, workEntryIndicatesToolNeutralStatus, workEntryIndicatesToolSuccess, @@ -216,7 +216,7 @@ interface MessagesTimelineProps { activeTurnInProgress: boolean; activeTurnStartedAt: string | null; listRef: React.RefObject; - timelineEntries: ReturnType; + timelineEntries: ReadonlyArray; latestRun: TimelineLatestRun | null; turnDiffSummaryByAssistantMessageId: Map; routeThreadKey: string; @@ -923,7 +923,6 @@ function TimelineMinimap({ // TimelineRowContent — the actual row component // --------------------------------------------------------------------------- -type TimelineEntry = ReturnType[number]; type TimelineMessage = Extract["message"]; type TimelineWorkEntry = Extract["groupedEntries"][number]; type TimelineRow = MessagesTimelineRow; diff --git a/apps/web/src/hooks/useHandleNewThread.ts b/apps/web/src/hooks/useHandleNewThread.ts index 64176c0873..7e55265481 100644 --- a/apps/web/src/hooks/useHandleNewThread.ts +++ b/apps/web/src/hooks/useHandleNewThread.ts @@ -22,8 +22,12 @@ import { getProjectOrderKey, selectProjectGroupingSettings, } from "../logicalProject"; +<<<<<<< HEAD import { resolveDefaultThreadEnvMode } from "@t3tools/shared/threadEnvMode"; import { readThreadShell, useProjects, useThread } from "../state/entities"; +======= +import { readThreadShell, useProjects, useServerConfigs, useThreadShell } from "../state/entities"; +>>>>>>> d849d1caf9 (Retire V1 client orchestration parity) import { resolveNewDraftStartFromOrigin } from "../lib/chatThreadActions"; import { readT3ProjectFileDefaultThreadEnvMode } from "../lib/t3ProjectFileDefaults"; import { primaryServerSettingsAtom } from "../state/server"; @@ -438,7 +442,7 @@ export function useHandleNewThread() { select: (params) => resolveThreadRouteTarget(params), }); const routeThreadRef = routeTarget?.kind === "server" ? routeTarget.threadRef : null; - const activeThread = useThread(routeThreadRef); + const activeThread = useThreadShell(routeThreadRef); const getDraftThread = useComposerDraftStore((store) => store.getDraftThread); const activeDraftThread = useComposerDraftStore(() => routeTarget diff --git a/apps/web/src/hooks/useTurnDiffSummaries.ts b/apps/web/src/hooks/useTurnDiffSummaries.ts index 21e28be7bb..e372020681 100644 --- a/apps/web/src/hooks/useTurnDiffSummaries.ts +++ b/apps/web/src/hooks/useTurnDiffSummaries.ts @@ -1,14 +1,16 @@ import { useMemo } from "react"; +import { deriveThreadCheckpointSummaries } from "@t3tools/client-runtime/state/thread-checkpoints"; +import type { OrchestrationV2ThreadProjection } from "@t3tools/contracts"; import { inferCheckpointTurnCountByRunId } from "../session-logic"; -import type { Thread, TurnDiffSummary } from "../types"; +import type { TurnDiffSummary } from "../types"; -export function useTurnDiffSummaries(activeThread: Thread | null | undefined) { +export function useTurnDiffSummaries(projection: OrchestrationV2ThreadProjection | null) { const turnDiffSummaries = useMemo>(() => { - if (!activeThread) { + if (projection === null) { return []; } - return activeThread.checkpoints; - }, [activeThread]); + return deriveThreadCheckpointSummaries(projection); + }, [projection]); const inferredCheckpointTurnCountByRunId = useMemo( () => inferCheckpointTurnCountByRunId(turnDiffSummaries), diff --git a/apps/web/src/lib/contextWindow.test.ts b/apps/web/src/lib/contextWindow.test.ts index 3a56d20f0d..471cfe3db3 100644 --- a/apps/web/src/lib/contextWindow.test.ts +++ b/apps/web/src/lib/contextWindow.test.ts @@ -1,18 +1,12 @@ import { describe, expect, it } from "vite-plus/test"; +import * as DateTime from "effect/DateTime"; import { deriveLatestContextWindowSnapshot, formatContextWindowTokens } from "./contextWindow"; describe("V2 context window presentation", () => { it("uses retained compaction token data when available", () => { const snapshot = deriveLatestContextWindowSnapshot([ { - id: "compaction-1", - createdAt: "2026-06-20T00:00:00.000Z", - runId: null, - label: "Context compacted", - tone: "info", - itemType: "compaction", - toolLifecycleStatus: "completed", - structuredPayload: { + item: { id: "compaction-1" as never, threadId: "thread-1" as never, runId: null, @@ -26,7 +20,7 @@ describe("V2 context window presentation", () => { title: null, startedAt: null, completedAt: null, - updatedAt: {} as never, + updatedAt: DateTime.makeUnsafe("2026-06-20T00:00:00.000Z"), type: "compaction", driver: null, beforeTokenCount: 10_000, diff --git a/apps/web/src/lib/contextWindow.ts b/apps/web/src/lib/contextWindow.ts index d7254211c8..8d60f62671 100644 --- a/apps/web/src/lib/contextWindow.ts +++ b/apps/web/src/lib/contextWindow.ts @@ -1,5 +1,5 @@ -import type { ThreadTokenUsageSnapshot } from "@t3tools/contracts"; -import type { ThreadWorkEntry } from "@t3tools/client-runtime/state/shell"; +import type { OrchestrationV2TurnItem, ThreadTokenUsageSnapshot } from "@t3tools/contracts"; +import * as DateTime from "effect/DateTime"; function asFiniteNumber(value: unknown): number | null { return typeof value === "number" && Number.isFinite(value) ? value : null; @@ -41,14 +41,16 @@ export function formatProviderDisplayName(provider: string | null | undefined): } export function deriveLatestContextWindowSnapshot( - entries: ReadonlyArray, + entries: ReadonlyArray<{ + readonly item: OrchestrationV2TurnItem; + }>, ): ContextWindowSnapshot | null { for (let index = entries.length - 1; index >= 0; index -= 1) { const entry = entries[index]; - if (!entry || entry.structuredPayload.type !== "compaction") { + if (!entry || entry.item.type !== "compaction") { continue; } - const payload = entry.structuredPayload; + const payload = entry.item; const usedTokens = asFiniteNumber(payload.afterTokenCount); if (usedTokens === null || usedTokens < 0) { continue; @@ -80,7 +82,7 @@ export function deriveLatestContextWindowSnapshot( toolUses: null, durationMs: null, compactsAutomatically: true, - updatedAt: entry.createdAt, + updatedAt: DateTime.formatIso(payload.startedAt ?? payload.updatedAt), }; } diff --git a/apps/web/src/lib/threadSort.test.ts b/apps/web/src/lib/threadSort.test.ts index 642e280ed7..9ae3c3386c 100644 --- a/apps/web/src/lib/threadSort.test.ts +++ b/apps/web/src/lib/threadSort.test.ts @@ -7,13 +7,13 @@ import { ThreadId, } from "@t3tools/contracts"; import type { Thread } from "../types"; -import { makeThreadFixture } from "../test-fixtures"; +import { makeThreadFixture, type ThreadFixtureOverrides } from "../test-fixtures"; import { getLatestThreadForProject, sortThreads } from "./threadSort"; const LOCAL_ENVIRONMENT_ID = EnvironmentId.make("environment-local"); const PROJECT_ID = ProjectId.make("project-1"); -function makeThread(overrides: Partial = {}): Thread { +function makeThread(overrides: ThreadFixtureOverrides = {}): Thread { return makeThreadFixture({ id: ThreadId.make("thread-1"), environmentId: LOCAL_ENVIRONMENT_ID, diff --git a/apps/web/src/orchestrationEventEffects.test.ts b/apps/web/src/orchestrationEventEffects.test.ts deleted file mode 100644 index 4269304dec..0000000000 --- a/apps/web/src/orchestrationEventEffects.test.ts +++ /dev/null @@ -1,135 +0,0 @@ -import { - CheckpointRef, - EventId, - MessageId, - ProjectId, - ProviderInstanceId, - ThreadId, - TurnId, - type OrchestrationEvent, -} from "@t3tools/contracts"; -import { describe, expect, it } from "vite-plus/test"; - -import { deriveOrchestrationBatchEffects } from "./orchestrationEventEffects"; - -function makeEvent( - type: T, - payload: Extract["payload"], - overrides: Partial> = {}, -): Extract { - const sequence = overrides.sequence ?? 1; - return { - sequence, - eventId: EventId.make(`event-${sequence}`), - aggregateKind: "thread", - aggregateId: - "threadId" in payload - ? payload.threadId - : "projectId" in payload - ? payload.projectId - : ProjectId.make("project-1"), - occurredAt: "2026-02-27T00:00:00.000Z", - commandId: null, - causationEventId: null, - correlationId: null, - metadata: {}, - type, - payload, - ...overrides, - } as Extract; -} - -describe("deriveOrchestrationBatchEffects", () => { - it("targets draft promotion and terminal cleanup from thread lifecycle events", () => { - const createdThreadId = ThreadId.make("thread-created"); - const deletedThreadId = ThreadId.make("thread-deleted"); - const archivedThreadId = ThreadId.make("thread-archived"); - - const effects = deriveOrchestrationBatchEffects([ - makeEvent("thread.created", { - threadId: createdThreadId, - projectId: ProjectId.make("project-1"), - title: "Created thread", - modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5-codex" }, - runtimeMode: "full-access", - interactionMode: "default", - branch: null, - worktreePath: null, - createdAt: "2026-02-27T00:00:00.000Z", - updatedAt: "2026-02-27T00:00:00.000Z", - }), - makeEvent("thread.deleted", { - threadId: deletedThreadId, - deletedAt: "2026-02-27T00:00:01.000Z", - }), - makeEvent("thread.archived", { - threadId: archivedThreadId, - archivedAt: "2026-02-27T00:00:02.000Z", - updatedAt: "2026-02-27T00:00:02.000Z", - }), - ]); - - expect(effects.promoteDraftThreadIds).toEqual([createdThreadId]); - expect(effects.clearDeletedThreadIds).toEqual([deletedThreadId]); - expect(effects.removeTerminalUiStateThreadIds).toEqual([deletedThreadId, archivedThreadId]); - expect(effects.needsProviderInvalidation).toBe(false); - }); - - it("keeps only the final lifecycle outcome for a thread within one batch", () => { - const threadId = ThreadId.make("thread-1"); - - const effects = deriveOrchestrationBatchEffects([ - makeEvent("thread.deleted", { - threadId, - deletedAt: "2026-02-27T00:00:01.000Z", - }), - makeEvent("thread.created", { - threadId, - projectId: ProjectId.make("project-1"), - title: "Recreated thread", - modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5-codex" }, - runtimeMode: "full-access", - interactionMode: "default", - branch: null, - worktreePath: null, - createdAt: "2026-02-27T00:00:02.000Z", - updatedAt: "2026-02-27T00:00:02.000Z", - }), - makeEvent("thread.turn-diff-completed", { - threadId, - turnId: TurnId.make("turn-1"), - checkpointTurnCount: 1, - checkpointRef: CheckpointRef.make("checkpoint-1"), - status: "ready", - files: [], - assistantMessageId: MessageId.make("assistant-1"), - completedAt: "2026-02-27T00:00:03.000Z", - }), - ]); - - expect(effects.promoteDraftThreadIds).toEqual([threadId]); - expect(effects.clearDeletedThreadIds).toEqual([]); - expect(effects.removeTerminalUiStateThreadIds).toEqual([]); - expect(effects.needsProviderInvalidation).toBe(true); - }); - - it("does not retain archive cleanup when a thread is unarchived later in the same batch", () => { - const threadId = ThreadId.make("thread-1"); - - const effects = deriveOrchestrationBatchEffects([ - makeEvent("thread.archived", { - threadId, - archivedAt: "2026-02-27T00:00:01.000Z", - updatedAt: "2026-02-27T00:00:01.000Z", - }), - makeEvent("thread.unarchived", { - threadId, - updatedAt: "2026-02-27T00:00:02.000Z", - }), - ]); - - expect(effects.promoteDraftThreadIds).toEqual([]); - expect(effects.clearDeletedThreadIds).toEqual([]); - expect(effects.removeTerminalUiStateThreadIds).toEqual([]); - }); -}); diff --git a/apps/web/src/orchestrationEventEffects.ts b/apps/web/src/orchestrationEventEffects.ts deleted file mode 100644 index 34e33ace83..0000000000 --- a/apps/web/src/orchestrationEventEffects.ts +++ /dev/null @@ -1,94 +0,0 @@ -import type { OrchestrationEvent, ThreadId } from "@t3tools/contracts"; - -export interface OrchestrationBatchEffects { - promoteDraftThreadIds: ThreadId[]; - clearDeletedThreadIds: ThreadId[]; - removeTerminalUiStateThreadIds: ThreadId[]; - needsProviderInvalidation: boolean; -} - -export function deriveOrchestrationBatchEffects( - events: readonly OrchestrationEvent[], -): OrchestrationBatchEffects { - const threadLifecycleEffects = new Map< - ThreadId, - { - clearPromotedDraft: boolean; - clearDeletedThread: boolean; - removeTerminalUiState: boolean; - } - >(); - let needsProviderInvalidation = false; - - for (const event of events) { - switch (event.type) { - case "thread.turn-diff-completed": - case "thread.reverted": { - needsProviderInvalidation = true; - break; - } - - case "thread.created": { - threadLifecycleEffects.set(event.payload.threadId, { - clearPromotedDraft: true, - clearDeletedThread: false, - removeTerminalUiState: false, - }); - break; - } - - case "thread.deleted": { - threadLifecycleEffects.set(event.payload.threadId, { - clearPromotedDraft: false, - clearDeletedThread: true, - removeTerminalUiState: true, - }); - break; - } - - case "thread.archived": { - threadLifecycleEffects.set(event.payload.threadId, { - clearPromotedDraft: false, - clearDeletedThread: false, - removeTerminalUiState: true, - }); - break; - } - - case "thread.unarchived": { - threadLifecycleEffects.set(event.payload.threadId, { - clearPromotedDraft: false, - clearDeletedThread: false, - removeTerminalUiState: false, - }); - break; - } - - default: { - break; - } - } - } - - const promoteDraftThreadIds: ThreadId[] = []; - const clearDeletedThreadIds: ThreadId[] = []; - const removeTerminalUiStateThreadIds: ThreadId[] = []; - for (const [threadId, effect] of threadLifecycleEffects) { - if (effect.clearPromotedDraft) { - promoteDraftThreadIds.push(threadId); - } - if (effect.clearDeletedThread) { - clearDeletedThreadIds.push(threadId); - } - if (effect.removeTerminalUiState) { - removeTerminalUiStateThreadIds.push(threadId); - } - } - - return { - promoteDraftThreadIds, - clearDeletedThreadIds, - removeTerminalUiStateThreadIds, - needsProviderInvalidation, - }; -} diff --git a/apps/web/src/orchestrationV2DebugProviders.test.ts b/apps/web/src/orchestrationV2DebugProviders.test.ts deleted file mode 100644 index 0df7d258b0..0000000000 --- a/apps/web/src/orchestrationV2DebugProviders.test.ts +++ /dev/null @@ -1,82 +0,0 @@ -import { - ProviderDriverKind, - ProviderInstanceId, - type ProviderInstanceConfigMap, - type ServerProvider, -} from "@t3tools/contracts"; -import { describe, expect, it } from "vite-plus/test"; - -import { deriveOrchestrationV2DebugProviderSnapshots } from "./orchestrationV2DebugProviders"; - -const acpRegistry = ProviderDriverKind.make("acpRegistry"); -const instanceId = ProviderInstanceId.make("acpRegistry_example"); - -const unavailable: ServerProvider = { - instanceId, - driver: acpRegistry, - displayName: "Example ACP", - enabled: false, - installed: false, - version: null, - status: "error", - auth: { status: "unknown" }, - checkedAt: "2026-01-01T00:00:00.000Z", - availability: "unavailable", - unavailableReason: "Driver is not registered in the V1 runtime.", - models: [], - slashCommands: [], - skills: [], -}; - -describe("deriveOrchestrationV2DebugProviderSnapshots", () => { - it("replaces the V1 unavailable shadow for a configured registry agent", () => { - const providerInstances = { - [instanceId]: { - driver: acpRegistry, - enabled: true, - displayName: "Example ACP", - config: { - agentId: "example-agent", - customModels: ["model-one"], - }, - }, - } satisfies ProviderInstanceConfigMap; - - expect( - deriveOrchestrationV2DebugProviderSnapshots({ - providers: [unavailable], - providerInstances, - }), - ).toEqual([ - expect.objectContaining({ - instanceId, - driver: acpRegistry, - displayName: "Example ACP", - enabled: true, - installed: true, - status: "ready", - availability: "available", - models: [ - expect.objectContaining({ slug: "default", isCustom: false }), - expect.objectContaining({ slug: "model-one", isCustom: true }), - ], - }), - ]); - }); - - it("does not make an incomplete registry instance selectable", () => { - const providerInstances = { - [instanceId]: { - driver: acpRegistry, - config: { agentId: "" }, - }, - } satisfies ProviderInstanceConfigMap; - - expect( - deriveOrchestrationV2DebugProviderSnapshots({ - providers: [unavailable], - providerInstances, - }), - ).toEqual([unavailable]); - }); -}); diff --git a/apps/web/src/orchestrationV2DebugProviders.ts b/apps/web/src/orchestrationV2DebugProviders.ts deleted file mode 100644 index 36994447dd..0000000000 --- a/apps/web/src/orchestrationV2DebugProviders.ts +++ /dev/null @@ -1,88 +0,0 @@ -import { - ProviderDriverKind, - type ProviderInstanceConfigMap, - type ProviderInstanceId, - type ServerProvider, - type ServerProviderModel, -} from "@t3tools/contracts"; - -const ACP_REGISTRY_DRIVER = ProviderDriverKind.make("acpRegistry"); -const DEBUG_CHECKED_AT = "1970-01-01T00:00:00.000Z"; - -function configRecord(config: unknown): Readonly> { - return config !== null && typeof config === "object" && !Array.isArray(config) - ? (config as Readonly>) - : {}; -} - -function configuredModels( - config: Readonly>, -): ReadonlyArray { - const customModels = Array.isArray(config.customModels) - ? config.customModels.filter( - (model): model is string => typeof model === "string" && model.trim().length > 0, - ) - : []; - const slugs = [...new Set(["default", ...customModels.map((model) => model.trim())])]; - return slugs.map((slug) => ({ - slug, - name: slug === "default" ? "Agent default" : slug, - shortName: slug === "default" ? "Default" : slug, - isCustom: slug !== "default", - capabilities: null, - })); -} - -/** - * Add V2-only ACP Registry instances to the orchestration debugger's provider catalog. - * The regular application provider catalog remains V1-owned and is intentionally untouched. - */ -export function deriveOrchestrationV2DebugProviderSnapshots(input: { - readonly providers: ReadonlyArray; - readonly providerInstances: ProviderInstanceConfigMap; -}): ReadonlyArray { - const snapshots = [...input.providers]; - const indexByInstanceId = new Map( - snapshots.map((provider, index) => [provider.instanceId, index]), - ); - - for (const [instanceId, instance] of Object.entries(input.providerInstances)) { - if (instance.driver !== ACP_REGISTRY_DRIVER) continue; - const config = configRecord(instance.config); - const agentId = typeof config.agentId === "string" ? config.agentId.trim() : ""; - if (agentId.length === 0) continue; - const id = instanceId as ProviderInstanceId; - const existingIndex = indexByInstanceId.get(id); - const existing = existingIndex === undefined ? undefined : snapshots[existingIndex]; - const enabled = - instance.enabled ?? (typeof config.enabled === "boolean" ? config.enabled : true); - const snapshot: ServerProvider = { - instanceId: id, - driver: ACP_REGISTRY_DRIVER, - displayName: instance.displayName?.trim() || `ACP: ${agentId}`, - ...(instance.accentColor ? { accentColor: instance.accentColor } : {}), - badgeLabel: "V2 Preview", - showInteractionModeToggle: true, - requiresNewThreadForModelChange: false, - enabled, - installed: true, - version: null, - status: enabled ? "ready" : "disabled", - auth: { status: "unknown" }, - checkedAt: existing?.checkedAt ?? DEBUG_CHECKED_AT, - message: `ACP Registry agent '${agentId}' is resolved when the V2 session starts.`, - availability: "available", - models: configuredModels(config), - slashCommands: [], - skills: [], - }; - if (existingIndex === undefined) { - indexByInstanceId.set(id, snapshots.length); - snapshots.push(snapshot); - } else { - snapshots[existingIndex] = snapshot; - } - } - - return snapshots; -} diff --git a/apps/web/src/routeTree.gen.ts b/apps/web/src/routeTree.gen.ts index 2125b48757..64feb1c84d 100644 --- a/apps/web/src/routeTree.gen.ts +++ b/apps/web/src/routeTree.gen.ts @@ -22,11 +22,14 @@ import { Route as SettingsGeneralRouteImport } from './routes/settings.general' import { Route as SettingsDiagnosticsRouteImport } from './routes/settings.diagnostics' import { Route as SettingsConnectionsRouteImport } from './routes/settings.connections' import { Route as SettingsArchivedRouteImport } from './routes/settings.archived' +<<<<<<< HEAD import { Route as SettingsAppearanceRouteImport } from './routes/settings.appearance' import { Route as ProjectsProjectKeyRouteImport } from './routes/projects.$projectKey' import { Route as ConnectCallbackRouteImport } from './routes/connect_.callback' import { Route as ChatPullRequestsRouteImport } from './routes/_chat.pull-requests' import { Route as DebugOrchestrationV2RouteImport } from './routes/debug.orchestration-v2' +======= +>>>>>>> d849d1caf9 (Retire V1 client orchestration parity) import { Route as ChatDraftDraftIdRouteImport } from './routes/_chat.draft.$draftId' import { Route as ChatEnvironmentIdThreadIdRouteImport } from './routes/_chat.$environmentId.$threadId' @@ -94,6 +97,7 @@ const SettingsArchivedRoute = SettingsArchivedRouteImport.update({ path: '/archived', getParentRoute: () => SettingsRoute, } as any) +<<<<<<< HEAD const SettingsAppearanceRoute = SettingsAppearanceRouteImport.update({ id: '/appearance', path: '/appearance', @@ -117,6 +121,8 @@ const ChatPullRequestsRoute = ChatPullRequestsRouteImport.update({ path: '/pull-requests', getParentRoute: () => ChatRoute, } as any) +======= +>>>>>>> d849d1caf9 (Retire V1 client orchestration parity) const ChatDraftDraftIdRoute = ChatDraftDraftIdRouteImport.update({ id: '/draft/$draftId', path: '/draft/$draftId', @@ -134,12 +140,15 @@ export interface FileRoutesByFullPath { '/connect': typeof ConnectRoute '/pair': typeof PairRoute '/settings': typeof SettingsRouteWithChildren +<<<<<<< HEAD '/usage': typeof UsageRoute '/pull-requests': typeof ChatPullRequestsRoute '/connect/callback': typeof ConnectCallbackRoute '/projects/$projectKey': typeof ProjectsProjectKeyRoute '/settings/appearance': typeof SettingsAppearanceRoute '/debug/orchestration-v2': typeof DebugOrchestrationV2Route +======= +>>>>>>> d849d1caf9 (Retire V1 client orchestration parity) '/settings/archived': typeof SettingsArchivedRoute '/settings/connections': typeof SettingsConnectionsRoute '/settings/diagnostics': typeof SettingsDiagnosticsRoute @@ -154,12 +163,15 @@ export interface FileRoutesByTo { '/connect': typeof ConnectRoute '/pair': typeof PairRoute '/settings': typeof SettingsRouteWithChildren +<<<<<<< HEAD '/usage': typeof UsageRoute '/pull-requests': typeof ChatPullRequestsRoute '/connect/callback': typeof ConnectCallbackRoute '/projects/$projectKey': typeof ProjectsProjectKeyRoute '/settings/appearance': typeof SettingsAppearanceRoute '/debug/orchestration-v2': typeof DebugOrchestrationV2Route +======= +>>>>>>> d849d1caf9 (Retire V1 client orchestration parity) '/settings/archived': typeof SettingsArchivedRoute '/settings/connections': typeof SettingsConnectionsRoute '/settings/diagnostics': typeof SettingsDiagnosticsRoute @@ -177,12 +189,15 @@ export interface FileRoutesById { '/connect': typeof ConnectRoute '/pair': typeof PairRoute '/settings': typeof SettingsRouteWithChildren +<<<<<<< HEAD '/usage': typeof UsageRoute '/_chat/pull-requests': typeof ChatPullRequestsRoute '/connect_/callback': typeof ConnectCallbackRoute '/projects/$projectKey': typeof ProjectsProjectKeyRoute '/settings/appearance': typeof SettingsAppearanceRoute '/debug/orchestration-v2': typeof DebugOrchestrationV2Route +======= +>>>>>>> d849d1caf9 (Retire V1 client orchestration parity) '/settings/archived': typeof SettingsArchivedRoute '/settings/connections': typeof SettingsConnectionsRoute '/settings/diagnostics': typeof SettingsDiagnosticsRoute @@ -201,12 +216,15 @@ export interface FileRouteTypes { | '/connect' | '/pair' | '/settings' +<<<<<<< HEAD | '/usage' | '/pull-requests' | '/connect/callback' | '/projects/$projectKey' | '/settings/appearance' | '/debug/orchestration-v2' +======= +>>>>>>> d849d1caf9 (Retire V1 client orchestration parity) | '/settings/archived' | '/settings/connections' | '/settings/diagnostics' @@ -221,12 +239,15 @@ export interface FileRouteTypes { | '/connect' | '/pair' | '/settings' +<<<<<<< HEAD | '/usage' | '/pull-requests' | '/connect/callback' | '/projects/$projectKey' | '/settings/appearance' | '/debug/orchestration-v2' +======= +>>>>>>> d849d1caf9 (Retire V1 client orchestration parity) | '/settings/archived' | '/settings/connections' | '/settings/diagnostics' @@ -243,12 +264,15 @@ export interface FileRouteTypes { | '/connect' | '/pair' | '/settings' +<<<<<<< HEAD | '/usage' | '/_chat/pull-requests' | '/connect_/callback' | '/projects/$projectKey' | '/settings/appearance' | '/debug/orchestration-v2' +======= +>>>>>>> d849d1caf9 (Retire V1 client orchestration parity) | '/settings/archived' | '/settings/connections' | '/settings/diagnostics' @@ -266,10 +290,13 @@ export interface RootRouteChildren { ConnectRoute: typeof ConnectRoute PairRoute: typeof PairRoute SettingsRoute: typeof SettingsRouteWithChildren +<<<<<<< HEAD UsageRoute: typeof UsageRoute ConnectCallbackRoute: typeof ConnectCallbackRoute ProjectsProjectKeyRoute: typeof ProjectsProjectKeyRoute DebugOrchestrationV2Route: typeof DebugOrchestrationV2Route +======= +>>>>>>> d849d1caf9 (Retire V1 client orchestration parity) } declare module '@tanstack/react-router' { @@ -365,6 +392,7 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof SettingsArchivedRouteImport parentRoute: typeof SettingsRoute } +<<<<<<< HEAD '/settings/appearance': { id: '/settings/appearance' path: '/appearance' @@ -398,6 +426,8 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof ChatPullRequestsRouteImport parentRoute: typeof ChatRoute } +======= +>>>>>>> d849d1caf9 (Retire V1 client orchestration parity) '/_chat/draft/$draftId': { id: '/_chat/draft/$draftId' path: '/draft/$draftId' @@ -462,10 +492,13 @@ const rootRouteChildren: RootRouteChildren = { ConnectRoute: ConnectRoute, PairRoute: PairRoute, SettingsRoute: SettingsRouteWithChildren, +<<<<<<< HEAD UsageRoute: UsageRoute, ConnectCallbackRoute: ConnectCallbackRoute, ProjectsProjectKeyRoute: ProjectsProjectKeyRoute, DebugOrchestrationV2Route: DebugOrchestrationV2Route, +======= +>>>>>>> d849d1caf9 (Retire V1 client orchestration parity) } export const routeTree = rootRouteImport ._addFileChildren(rootRouteChildren) diff --git a/apps/web/src/routes/_chat.$environmentId.$threadId.tsx b/apps/web/src/routes/_chat.$environmentId.$threadId.tsx index 5ac4665cf8..5de3ce58a9 100644 --- a/apps/web/src/routes/_chat.$environmentId.$threadId.tsx +++ b/apps/web/src/routes/_chat.$environmentId.$threadId.tsx @@ -7,12 +7,7 @@ import { finalizePromotedDraftThreadByRef, useComposerDraftStore } from "../comp import { resolveThreadRouteRef, resolveThreadRouteRenderState } from "../threadRoutes"; import { resolveThreadSyncPhase } from "../threadSync"; import { SidebarInset } from "~/components/ui/sidebar"; -import { - useEnvironmentThreadRefs, - useThreadDetail, - useThreadShell, - useThreadStatus, -} from "../state/entities"; +import { useEnvironmentThreadRefs, useThreadShell } from "../state/entities"; import { useEnvironmentQuery } from "../state/query"; import { environmentShell } from "../state/shell"; @@ -25,10 +20,9 @@ function ChatThreadRouteView() { threadRef === null ? null : environmentShell.stateAtom(threadRef.environmentId), ); const serverThreadShell = useThreadShell(threadRef); - const serverThreadDetail = useThreadDetail(threadRef); - const serverThreadStatus = useThreadStatus(threadRef); const environmentThreadRefs = useEnvironmentThreadRefs(threadRef?.environmentId ?? null); const bootstrapComplete = shell.data?.snapshot._tag === "Some"; + const threadExists = serverThreadShell !== null; const environmentHasServerThreads = environmentThreadRefs.length > 0; const draftThreadExists = useComposerDraftStore((store) => threadRef ? store.getDraftThreadByRef(threadRef) !== null : false, @@ -42,19 +36,8 @@ function ChatThreadRouteView() { } return store.hasDraftThreadsInEnvironment(threadRef.environmentId); }); - const renderState = resolveThreadRouteRenderState({ - bootstrapComplete, - serverThreadShellExists: serverThreadShell !== null, - serverThreadDetailExists: serverThreadDetail !== null, - serverThreadDetailDeleted: serverThreadStatus === "deleted", - draftThreadExists, - }); - const threadSyncPhase = resolveThreadSyncPhase({ - detailExists: serverThreadDetail !== null, - shellExists: serverThreadShell !== null, - status: serverThreadStatus, - }); - const serverThreadStarted = threadHasStarted(serverThreadDetail); + const routeThreadExists = threadExists || draftThreadExists; + const serverThreadStarted = threadHasStarted(serverThreadShell); const environmentHasAnyThreads = environmentHasServerThreads || environmentHasDraftThreads; useEffect(() => { diff --git a/apps/web/src/routes/_chat.draft.$draftId.tsx b/apps/web/src/routes/_chat.draft.$draftId.tsx index 74c1b15c07..ccfeee1754 100644 --- a/apps/web/src/routes/_chat.draft.$draftId.tsx +++ b/apps/web/src/routes/_chat.draft.$draftId.tsx @@ -10,7 +10,7 @@ import { import { SidebarInset } from "../components/ui/sidebar"; import { waitForDraftHeroTransition } from "../components/chat/draftHeroTransition"; import { buildThreadRouteParams } from "../threadRoutes"; -import { useThread, useThreadRefs } from "../state/entities"; +import { useThreadRefs, useThreadShell } from "../state/entities"; function DraftChatThreadRouteView() { const navigate = useNavigate(); @@ -26,7 +26,7 @@ function DraftChatThreadRouteView() { ) ?? null) : null; const serverThreadRef = draftSession?.promotedTo ?? inferredThreadRef; - const serverThread = useThread(serverThreadRef); + const serverThread = useThreadShell(serverThreadRef); const serverThreadStarted = threadHasStarted(serverThread); const canonicalThreadRef = serverThreadStarted ? serverThreadRef : null; diff --git a/apps/web/src/routes/debug.orchestration-v2.tsx b/apps/web/src/routes/debug.orchestration-v2.tsx deleted file mode 100644 index 3bd214def2..0000000000 --- a/apps/web/src/routes/debug.orchestration-v2.tsx +++ /dev/null @@ -1,3923 +0,0 @@ -import { useAtomValue } from "@effect/atom-react"; -import { applyOrchestrationV2ProjectionEvent } from "@t3tools/client-runtime/state/orchestration-v2-projection"; -import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime"; -import { - ProviderDriverKind, - ProviderInstanceId, - type CheckpointId, - type CheckpointScopeId, - type ModelSelection, - type OrchestrationV2Checkpoint, - type OrchestrationV2Command, - type OrchestrationV2PlanStep, - type OrchestrationV2Run, - type OrchestrationV2RunStatus, - type OrchestrationV2ThreadProjection, - type OrchestrationV2ThreadShell, - type OrchestrationV2ThreadStreamItem, - type OrchestrationV2TurnItem, - type OrchestrationV2TurnItemStatus, - type OrchestrationV2UserInputQuestion, - type RunId, - type RuntimeMode, - type ServerProvider, - type ThreadId, -} from "@t3tools/contracts"; -import { createModelSelection } from "@t3tools/shared/model"; -import { createFileRoute } from "@tanstack/react-router"; -import { GitMergeIcon } from "lucide-react"; -import type { CSSProperties, DragEvent, ReactNode } from "react"; -import { useCallback, useEffect, useMemo, useRef, useState } from "react"; - -import { ProviderModelPicker } from "../components/chat/ProviderModelPicker"; -import { usePrimarySettings } from "../hooks/useSettings"; -import { resolveMergeBackTargetThreadId } from "@t3tools/client-runtime/state/thread-relationships"; -import { newCommandId, newMessageId, newProjectId, newThreadId } from "../lib/utils"; -import { type AppModelOption, getAppModelOptionsForInstance } from "../modelSelection"; -import { deriveOrchestrationV2DebugProviderSnapshots } from "../orchestrationV2DebugProviders"; -import { - type ProviderInstanceEntry, - deriveProviderInstanceEntries, - sortProviderInstanceEntries, -} from "../providerInstances"; -import { useServerKeybindings, useServerProviders } from "../rpc/serverState"; - -export const Route = createFileRoute("/debug/orchestration-v2")({ - component: OrchestrationV2DebugRoute, -}); - -const DEFAULT_PROMPT = "Respond with the following text: fixture simple ok"; -const DEBUG_CODEX_DRIVER = ProviderDriverKind.make("codex"); -const DEBUG_CLAUDE_DRIVER = ProviderDriverKind.make("claudeAgent"); -const DEBUG_CODEX_INSTANCE_ID = ProviderInstanceId.make("codex"); -const DEBUG_CLAUDE_INSTANCE_ID = ProviderInstanceId.make("claudeAgent"); -const DEFAULT_MODEL_SELECTION = createModelSelection(DEBUG_CODEX_INSTANCE_ID, "gpt-5.4"); - -const DEBUG_PROVIDER_SNAPSHOTS: ReadonlyArray = [ - { - instanceId: DEBUG_CODEX_INSTANCE_ID, - driver: DEBUG_CODEX_DRIVER, - displayName: "Codex", - enabled: true, - installed: true, - version: null, - status: "ready", - auth: { status: "authenticated" }, - checkedAt: "2026-01-01T00:00:00.000Z", - models: [ - { - slug: "gpt-5.5", - name: "GPT-5.5", - shortName: "5.5", - isCustom: false, - capabilities: null, - }, - { - slug: "gpt-5.3-codex", - name: "GPT-5.3 Codex", - shortName: "5.3", - isCustom: false, - capabilities: null, - }, - { - slug: "gpt-5.4", - name: "GPT-5.4", - shortName: "5.4", - isCustom: false, - capabilities: null, - }, - { - slug: "gpt-5.4-mini", - name: "GPT-5.4 Mini", - shortName: "5.4 Mini", - isCustom: false, - capabilities: null, - }, - { - slug: "gpt-5.3-codex-spark", - name: "GPT-5.3 Codex Spark", - shortName: "Spark", - isCustom: false, - capabilities: null, - }, - { - slug: "gpt-5.2", - name: "GPT-5.2", - shortName: "5.2", - isCustom: false, - capabilities: null, - }, - ], - slashCommands: [], - skills: [], - }, - { - instanceId: DEBUG_CLAUDE_INSTANCE_ID, - driver: DEBUG_CLAUDE_DRIVER, - displayName: "Claude", - enabled: true, - installed: true, - version: null, - status: "ready", - auth: { status: "authenticated" }, - checkedAt: "2026-01-01T00:00:00.000Z", - models: [ - { - slug: "claude-opus-4-7", - name: "Claude Opus 4.7", - shortName: "Opus 4.7", - isCustom: false, - capabilities: null, - }, - { - slug: "claude-opus-4-6", - name: "Claude Opus 4.6", - shortName: "Opus 4.6", - isCustom: false, - capabilities: null, - }, - { - slug: "claude-sonnet-4-6", - name: "Claude Sonnet 4.6", - shortName: "Sonnet 4.6", - isCustom: false, - capabilities: null, - }, - { - slug: "claude-haiku-4-5", - name: "Claude Haiku 4.5", - shortName: "Haiku 4.5", - isCustom: false, - capabilities: null, - }, - ], - slashCommands: [], - skills: [], - }, -]; - -type LogEntry = - | { - readonly type: "command"; - readonly label: string; - readonly value: unknown; - } - | { - readonly type: "stream"; - readonly value: OrchestrationV2ThreadStreamItem; - } - | { - readonly type: "error"; - readonly message: string; - }; - -interface TimelineEntry { - readonly key: string; - readonly eyebrow: string; - readonly title: string; - readonly subtitle?: string | undefined; - readonly status?: string | undefined; - readonly body?: string | undefined; - readonly timestamp?: string | undefined; - readonly sequence?: number | undefined; - readonly raw: unknown; -} - -function isRecord(value: unknown): value is Record { - return typeof value === "object" && value !== null; -} - -function formatErrorMessage(error: unknown): string { - if (isRecord(error) && typeof error.detail === "string" && error.detail.trim().length > 0) { - return error.detail; - } - if (error instanceof Error && error.message.trim().length > 0) { - return error.message; - } - return String(error); -} - -function formatLabel(value: string): string { - return value - .split(/[._-]+/g) - .filter(Boolean) - .map((part) => `${part.slice(0, 1).toUpperCase()}${part.slice(1)}`) - .join(" "); -} - -function compactId(value: unknown): string | undefined { - if (typeof value !== "string" || value.length === 0) { - return undefined; - } - if (value.length <= 18) { - return value; - } - return `${value.slice(0, 10)}...${value.slice(-6)}`; -} - -function stringifyShort(value: unknown): string | undefined { - if (typeof value === "string") { - return value; - } - if (value === null || value === undefined) { - return undefined; - } - if (typeof value === "number" || typeof value === "boolean") { - return String(value); - } - try { - return JSON.stringify(value); - } catch { - return String(value); - } -} - -function formatTimestamp(value: unknown): string | undefined { - if (value === null || value === undefined) { - return undefined; - } - if (value instanceof Date) { - return Number.isNaN(value.getTime()) ? undefined : value.toISOString(); - } - const raw = typeof value === "string" ? value : String(value); - const wrapped = /^DateTime\.(?:Utc|Zoned|Local)\((.+)\)$/.exec(raw); - const iso = wrapped?.[1] ?? raw; - const parsed = new Date(iso); - return Number.isNaN(parsed.getTime()) ? iso : parsed.toISOString(); -} - -function formatRelative(fromMs: number, nowMs: number): string { - const diff = nowMs - fromMs; - const abs = Math.abs(diff); - if (abs < 1000) return "just now"; - const future = diff < 0; - const sec = Math.round(abs / 1000); - if (sec < 60) return future ? `in ${sec}s` : `${sec}s ago`; - const min = Math.round(sec / 60); - if (min < 60) return future ? `in ${min}m` : `${min}m ago`; - const hr = Math.round(min / 60); - if (hr < 24) return future ? `in ${hr}h` : `${hr}h ago`; - const day = Math.round(hr / 24); - return future ? `in ${day}d` : `${day}d ago`; -} - -function useNow(intervalMs = 10_000): number { - const [now, setNow] = useState(() => Date.now()); - useEffect(() => { - const id = setInterval(() => { - setNow(Date.now()); - }, intervalMs); - return () => { - clearInterval(id); - }; - }, [intervalMs]); - return now; -} - -function selectDebugFallbackProviderInstance( - entries: ReadonlyArray, -): ProviderInstanceEntry | undefined { - return ( - entries.find((entry) => entry.enabled && entry.isAvailable && entry.status === "ready") ?? - entries.find((entry) => entry.enabled && entry.isAvailable) ?? - entries[0] - ); -} - -function resolveDebugModelSelection( - current: ModelSelection, - entries: ReadonlyArray, - modelOptionsByInstance: ReadonlyMap>, -): ModelSelection { - const currentEntry = entries.find((entry) => entry.instanceId === current.instanceId); - const entry = currentEntry ?? selectDebugFallbackProviderInstance(entries); - if (!entry) return current; - - const modelOptions = modelOptionsByInstance.get(entry.instanceId) ?? []; - const hasCurrentModel = - currentEntry !== undefined && modelOptions.some((option) => option.slug === current.model); - if (currentEntry !== undefined && (modelOptions.length === 0 || hasCurrentModel)) { - return current; - } - - const model = modelOptions[0]?.slug ?? current.model; - return createModelSelection(entry.instanceId, model); -} - -const IS_MAC = - typeof navigator !== "undefined" && /Mac|iPhone|iPad|iPod/i.test(navigator.userAgent); - -function Timestamp(props: { readonly iso: string | undefined; readonly nowMs: number }) { - if (props.iso === undefined) return null; - const parsed = new Date(props.iso); - if (Number.isNaN(parsed.getTime())) { - return ( - - {props.iso} - - ); - } - const clock = parsed.toLocaleTimeString(undefined, { - hour12: false, - hour: "2-digit", - minute: "2-digit", - second: "2-digit", - }); - return ( - - ); -} - -function readText( - record: Record, - keys: ReadonlyArray, -): string | undefined { - for (const key of keys) { - const value = record[key]; - if (typeof value === "string" && value.trim().length > 0) { - return value; - } - } - return undefined; -} - -function buildProjectionTimeline( - projection: OrchestrationV2ThreadProjection | null, -): ReadonlyArray { - if (projection === null) { - return []; - } - - const entries: Array = [ - { - key: `thread:${projection.thread.id}`, - eyebrow: "Thread", - title: projection.thread.title, - subtitle: `${projection.thread.modelSelection.provider} / ${projection.thread.modelSelection.model}`, - status: projection.thread.archivedAt ? "archived" : "active", - timestamp: formatTimestamp(projection.thread.createdAt), - raw: projection.thread, - sort: 0, - }, - ]; - - projection.messages.forEach((message, index) => { - entries.push({ - key: `message:${message.id}`, - eyebrow: "Message", - title: formatLabel(message.role), - subtitle: compactId(message.id), - status: message.streaming ? "streaming" : "completed", - body: message.text, - timestamp: formatTimestamp(message.createdAt), - raw: message, - sort: 100 + index, - }); - }); - - projection.runs.forEach((run, index) => { - entries.push({ - key: `run:${run.id}`, - eyebrow: "Run", - title: `Run ${run.ordinal}`, - subtitle: `${run.modelSelection.instanceId} / ${run.modelSelection.model}`, - status: run.status, - timestamp: formatTimestamp(run.startedAt ?? run.requestedAt), - raw: run, - sort: 200 + index * 100, - }); - }); - - projection.turnItems.forEach((item) => { - const record = item as unknown as Record; - const body = - readText(record, ["text", "markdown", "detail", "explanation", "output"]) ?? - stringifyShort(record.input); - entries.push({ - key: `turn-item:${item.id}`, - eyebrow: "Turn Item", - title: formatLabel(item.type), - subtitle: compactId(item.providerTurnId), - status: item.status, - body, - timestamp: formatTimestamp(item.updatedAt ?? item.startedAt), - raw: item, - sort: 250 + item.ordinal, - }); - }); - - projection.runtimeRequests.forEach((request, index) => { - entries.push({ - key: `request:${request.id}`, - eyebrow: "Request", - title: formatLabel(request.kind), - subtitle: compactId(request.providerTurnId), - status: request.status, - timestamp: formatTimestamp(request.createdAt), - raw: request, - sort: 500 + index, - }); - }); - - projection.contextTransfers.forEach((transfer, index) => { - const resolution = - transfer.resolution === null - ? undefined - : `resolved by ${formatLabel(transfer.resolution.strategy)}`; - entries.push({ - key: `context-transfer:${transfer.id}`, - eyebrow: "Context Transfer", - title: formatLabel(transfer.type), - subtitle: compactId(transfer.targetThreadId), - status: transfer.status, - body: [resolution, transfer.error].filter(Boolean).join("\n") || undefined, - timestamp: formatTimestamp(transfer.updatedAt ?? transfer.createdAt), - raw: transfer, - sort: 650 + index, - }); - }); - - projection.checkpoints.forEach((checkpoint, index) => { - entries.push({ - key: `checkpoint:${checkpoint.id}`, - eyebrow: "Checkpoint", - title: compactId(checkpoint.ref) ?? compactId(checkpoint.id) ?? "Checkpoint", - subtitle: compactId(checkpoint.scopeId), - status: checkpoint.status, - timestamp: formatTimestamp(checkpoint.capturedAt), - raw: checkpoint, - sort: 700 + index, - }); - }); - - return entries.toSorted((left, right) => left.sort - right.sort); -} - -function buildStreamTimeline(logEntries: ReadonlyArray): ReadonlyArray { - return logEntries.map((entry, index) => { - if (entry.type === "error") { - return { - key: `log:${index}`, - eyebrow: "Error", - title: "Error", - status: "failed", - body: entry.message, - raw: entry, - }; - } - - if (entry.type === "command") { - return { - key: `log:${index}`, - eyebrow: "Command", - title: entry.label, - status: "sent", - raw: entry.value, - }; - } - - const value = entry.value; - if (value.kind === "snapshot") { - return { - key: `log:${index}`, - eyebrow: "Snapshot", - title: "Projection Snapshot", - subtitle: `sequence ${value.snapshotSequence}`, - sequence: value.snapshotSequence, - status: "received", - raw: value, - }; - } - - const event = value.event; - const payload: Record = isRecord(event.payload) ? event.payload : {}; - return { - key: `log:${index}`, - eyebrow: "Event", - title: event.type, - subtitle: compactId(event.threadId), - sequence: value.sequence, - status: stringifyShort(payload.status) ?? stringifyShort(event.driver) ?? "received", - body: readText(payload, ["text", "title", "detail", "markdown"]), - raw: value, - }; - }); -} - -function turnItemBody(item: OrchestrationV2TurnItem): string | undefined { - switch (item.type) { - case "user_message": - case "assistant_message": - case "reasoning": - return item.text; - case "proposed_plan": - return item.markdown; - case "todo_list": { - const steps = item.steps.map((step) => `${step.status}: ${step.text}`).join("\n"); - return [item.explanation, steps].filter(Boolean).join("\n\n") || undefined; - } - case "user_input_request": - return item.questions.map((question) => question.question).join("\n"); - case "file_change": - return [ - item.fileName, - item.additions === undefined && item.deletions === undefined - ? undefined - : `+${item.additions ?? 0} / -${item.deletions ?? 0}`, - item.diffStr, - ] - .filter(Boolean) - .join("\n"); - case "command_execution": - return [item.input, item.output].filter(Boolean).join("\n\n"); - case "file_search": - return [ - item.pattern, - item.results - ?.map((result) => - [result.fileName, result.line === undefined ? undefined : `:${result.line}`].join(""), - ) - .join("\n"), - ] - .filter(Boolean) - .join("\n"); - case "web_search": - return [ - item.patterns?.join(", "), - item.results?.map((result) => result.title ?? result.url ?? result.snippet).join("\n"), - ] - .filter(Boolean) - .join("\n"); - case "approval_request": - return item.prompt ?? formatLabel(item.requestKind); - case "checkpoint": - return item.files - .map((file) => `${file.path} +${file.additions} / -${file.deletions}`) - .join("\n"); - case "run_interrupt_request": - case "run_interrupt_result": - return item.message; - case "compaction": - return item.summary; - case "handoff": - return item.summary; - case "fork": - return `Target thread: ${compactId(item.targetThreadId) ?? item.targetThreadId}`; - case "subagent": - return [item.prompt, item.result].filter(Boolean).join("\n\n"); - case "dynamic_tool": - return [item.toolName, stringifyShort(item.output) ?? stringifyShort(item.input)] - .filter(Boolean) - .join("\n"); - } -} - -interface ItemTimelineItemRow { - readonly kind: "item"; - readonly item: OrchestrationV2TurnItem; - readonly entry: TimelineEntry; - readonly inheritedFromThreadId?: ThreadId | undefined; -} - -interface ItemTimelineForkMarkerRow { - readonly kind: "fork-marker"; - readonly entry: TimelineEntry; - readonly sourceThreadId: ThreadId; - readonly targetThreadId: ThreadId; -} - -type ItemTimelineRow = ItemTimelineItemRow | ItemTimelineForkMarkerRow; - -interface QueuedRunRow { - readonly run: OrchestrationV2Run; - readonly messageText: string; -} - -interface MergeBackCandidate { - readonly sourceThreadId: ThreadId; - readonly targetThreadId: ThreadId; - readonly latestCompletedRun: OrchestrationV2Run | null; -} - -type PendingMergeBackTransfer = OrchestrationV2ThreadProjection["contextTransfers"][number]; - -interface DebugThreadTreeNode { - readonly threadId: ThreadId; - readonly thread: OrchestrationV2ThreadShell; - readonly modelSelection: ModelSelection; - readonly children: ReadonlyArray; -} - -function buildItemTimeline(input: { - readonly projection: OrchestrationV2ThreadProjection | null; - readonly projectionsByThread: ReadonlyMap; - readonly logEntries: ReadonlyArray; -}): ReadonlyArray { - if (input.projection !== null && input.projection.visibleTurnItems.length > 0) { - return input.projection.visibleTurnItems.map((row): ItemTimelineRow => { - const item = row.item; - if (item.type === "fork" && row.visibility === "synthetic") { - return { - kind: "fork-marker", - sourceThreadId: row.sourceThreadId, - targetThreadId: item.targetThreadId, - entry: itemTimelineEntry(item, `visible:${input.projection?.thread.id}:${row.position}`), - }; - } - return { - kind: "item", - item, - inheritedFromThreadId: row.visibility === "inherited" ? row.sourceThreadId : undefined, - entry: itemTimelineEntry(item, `visible:${input.projection?.thread.id}:${row.position}`), - }; - }); - } - - const items = new Map< - string, - { - readonly item: OrchestrationV2TurnItem; - readonly sequence?: number | undefined; - } - >(); - - const upsert = (item: OrchestrationV2TurnItem, sequence?: number) => { - const existing = items.get(item.id); - items.set(item.id, { - item, - ...(sequence === undefined - ? existing?.sequence === undefined - ? {} - : { sequence: existing.sequence } - : { sequence }), - }); - }; - - for (const entry of input.logEntries) { - if (entry.type !== "stream") { - continue; - } - const value = entry.value; - if (value.kind === "snapshot") { - for (const item of value.projection.turnItems) { - upsert(item, value.snapshotSequence); - } - continue; - } - if (value.event.type === "turn-item.updated") { - upsert(value.event.payload, value.sequence); - } - } - - if (input.projection !== null) { - for (const item of input.projection.turnItems) { - upsert(item); - } - } - - const currentRows: ReadonlyArray = [...items.values()] - .toSorted((left, right) => left.item.ordinal - right.item.ordinal) - .map(({ item, sequence }) => ({ - kind: "item", - item, - entry: itemTimelineEntry(item, `item:${item.id}`, sequence), - })); - - const forkedFrom = input.projection?.thread.forkedFrom; - if (input.projection === null || forkedFrom?.type !== "run") { - return currentRows; - } - const targetProjection = input.projection; - - const sourceProjection = input.projectionsByThread.get(forkedFrom.threadId); - if (sourceProjection === undefined) { - return currentRows; - } - - const sourceRun = sourceProjection.runs.find((run) => run.id === forkedFrom.runId); - if (sourceRun === undefined) { - return currentRows; - } - - const runOrdinalById = new Map(sourceProjection.runs.map((run) => [run.id, run.ordinal])); - const inheritedRows = sourceProjection.turnItems - .filter((item) => { - if (item.runId === null) return false; - const ordinal = runOrdinalById.get(item.runId); - return ordinal !== undefined && ordinal <= sourceRun.ordinal; - }) - .toSorted((left, right) => left.ordinal - right.ordinal) - .map( - (item): ItemTimelineItemRow => ({ - kind: "item", - item, - inheritedFromThreadId: sourceProjection.thread.id, - entry: itemTimelineEntry(item, `inherited:${targetProjection.thread.id}:${item.id}`), - }), - ); - - const marker: ItemTimelineForkMarkerRow = { - kind: "fork-marker", - sourceThreadId: sourceProjection.thread.id, - targetThreadId: targetProjection.thread.id, - entry: { - key: `fork-marker:${targetProjection.thread.id}`, - eyebrow: "Fork", - title: "Forked from conversation", - subtitle: compactId(sourceProjection.thread.id), - status: "received", - timestamp: formatTimestamp(targetProjection.thread.createdAt), - raw: { - sourceThreadId: sourceProjection.thread.id, - sourceRunId: sourceRun.id, - targetThreadId: targetProjection.thread.id, - }, - }, - }; - - return [...inheritedRows, marker, ...currentRows]; -} - -function itemTimelineEntry( - item: OrchestrationV2TurnItem, - key = `item:${item.id}`, - sequence?: number, -): TimelineEntry { - return { - key, - eyebrow: `Item ${item.ordinal}`, - title: item.title?.trim() || formatLabel(item.type), - subtitle: `${formatLabel(item.type)} · ${compactId(item.id) ?? item.id}`, - status: item.status, - body: turnItemBody(item), - timestamp: formatTimestamp(item.updatedAt ?? item.completedAt ?? item.startedAt), - sequence, - raw: item, - }; -} - -function forkSourceThreadId(thread: OrchestrationV2ThreadShell): ThreadId | null { - const forkedFrom = thread.forkedFrom; - if (forkedFrom?.type === "run") return forkedFrom.threadId; - return thread.lineage.parentThreadId ?? null; -} - -function threadShellCreatedMs(thread: OrchestrationV2ThreadShell): number { - const iso = formatTimestamp(thread.createdAt); - if (iso === undefined) return 0; - const parsed = new Date(iso).getTime(); - return Number.isNaN(parsed) ? 0 : parsed; -} - -function buildThreadTree(input: { - readonly threads: ReadonlyMap; - readonly projectionsByThread: ReadonlyMap; -}): ReadonlyArray { - const childIds = new Map>(); - const rootIds: Array = []; - for (const [threadId, thread] of input.threads) { - const parentThreadId = forkSourceThreadId(thread); - if (parentThreadId !== null && input.threads.has(parentThreadId)) { - const children = childIds.get(parentThreadId) ?? []; - children.push(threadId); - childIds.set(parentThreadId, children); - } else { - rootIds.push(threadId); - } - } - - const sortThreadIds = (threadIds: Array) => - threadIds.toSorted((left, right) => { - const leftThread = input.threads.get(left); - const rightThread = input.threads.get(right); - return ( - (leftThread === undefined ? 0 : threadShellCreatedMs(leftThread)) - - (rightThread === undefined ? 0 : threadShellCreatedMs(rightThread)) || - String(left).localeCompare(String(right)) - ); - }); - - const buildNode = (threadId: ThreadId): DebugThreadTreeNode => { - const thread = input.threads.get(threadId); - if (thread === undefined) { - throw new Error(`Missing orchestration V2 shell thread ${threadId}`); - } - const latestRun = input.projectionsByThread.get(threadId)?.runs.at(-1); - const children = sortThreadIds(childIds.get(threadId) ?? []).map(buildNode); - return { - threadId, - thread, - modelSelection: latestRun?.modelSelection ?? thread.modelSelection, - children, - }; - }; - - return sortThreadIds(rootIds).map(buildNode); -} - -const PANEL_KEYS = ["tree", "projection", "item", "stream"] as const; -type PanelKey = (typeof PANEL_KEYS)[number]; -const ALL_PANEL_KEYS: ReadonlyArray = PANEL_KEYS; -const DEFAULT_VISIBLE_PANELS: ReadonlyArray = ["tree", "item", "stream"]; - -const PANEL_TITLES: Record = { - tree: "Thread Tree", - projection: "Projection Timeline", - item: "Item Timeline", - stream: "Stream Timeline", -}; - -const PANEL_DND_MIME = "application/x-t3-panel-key"; - -function readDraggedPanelKey(event: DragEvent): PanelKey | null { - const raw = event.dataTransfer.getData(PANEL_DND_MIME); - return ALL_PANEL_KEYS.includes(raw as PanelKey) ? (raw as PanelKey) : null; -} - -function computePanelDropSide(event: DragEvent): "before" | "after" { - const rect = event.currentTarget.getBoundingClientRect(); - return event.clientX - rect.left < rect.width / 2 ? "before" : "after"; -} - -function DragHandleIcon(props: { readonly className?: string }) { - return ( - - ); -} - -function CloseIcon(props: { readonly className?: string }) { - return ( - - ); -} - -function ForkIcon(props: { readonly className?: string }) { - return ( - - ); -} - -function RollbackIcon(props: { readonly className?: string }) { - return ( - - ); -} - -function PanelHost(props: { - readonly visiblePanels: ReadonlyArray; - readonly hiddenPanels: ReadonlyArray; - readonly renderPanel: (key: PanelKey) => ReactNode; - readonly onReorder: (source: PanelKey, target: PanelKey, side: "before" | "after") => void; - readonly onRestoreAtEnd: (source: PanelKey) => void; -}) { - const visibleCount = props.visiblePanels.length; - const minWidthRem = Math.max(28, 28 * visibleCount); - const gridStyle: CSSProperties = { - gridTemplateColumns: - visibleCount === 0 ? "minmax(0,1fr)" : `repeat(${visibleCount}, minmax(0, 1fr))`, - minWidth: `${minWidthRem}rem`, - }; - - const [draggingOverEnd, setDraggingOverEnd] = useState(false); - - const handleContainerDragOver = (event: DragEvent) => { - if (!event.dataTransfer.types.includes(PANEL_DND_MIME)) return; - event.preventDefault(); - event.dataTransfer.dropEffect = "move"; - setDraggingOverEnd(true); - }; - - const handleContainerDragLeave = (event: DragEvent) => { - if (event.currentTarget === event.target) { - setDraggingOverEnd(false); - } - }; - - const handleContainerDrop = (event: DragEvent) => { - const sourceKey = readDraggedPanelKey(event); - setDraggingOverEnd(false); - if (sourceKey === null) return; - event.preventDefault(); - props.onRestoreAtEnd(sourceKey); - }; - - if (visibleCount === 0) { - return ( -
-

- No panels visible. Click a pill in the header to restore it, or drag one here. -

-
- ); - } - - return ( -
-
- {props.visiblePanels.map((panelKey) => ( - - {props.renderPanel(panelKey)} - - ))} -
-
- ); -} - -function PanelDropSlot(props: { - readonly panelKey: PanelKey; - readonly onReorder: (source: PanelKey, target: PanelKey, side: "before" | "after") => void; - readonly children: ReactNode; -}) { - const [dropSide, setDropSide] = useState<"before" | "after" | null>(null); - - const handleDragOver = (event: DragEvent) => { - if (!event.dataTransfer.types.includes(PANEL_DND_MIME)) return; - event.preventDefault(); - event.stopPropagation(); - event.dataTransfer.dropEffect = "move"; - setDropSide(computePanelDropSide(event)); - }; - - const handleDragLeave = () => { - setDropSide(null); - }; - - const handleDrop = (event: DragEvent) => { - const sourceKey = readDraggedPanelKey(event); - const side = dropSide ?? computePanelDropSide(event); - setDropSide(null); - if (sourceKey === null) return; - event.preventDefault(); - event.stopPropagation(); - if (sourceKey === props.panelKey) return; - props.onReorder(sourceKey, props.panelKey, side); - }; - - return ( -
- {dropSide === "before" ? ( -
- ); -} - -function HiddenPanelPills(props: { - readonly hiddenPanels: ReadonlyArray; - readonly onRestore: (key: PanelKey) => void; -}) { - if (props.hiddenPanels.length === 0) return null; - return ( -
    - {props.hiddenPanels.map((key) => ( -
  • - -
  • - ))} -
- ); -} - -function HiddenPanelPill(props: { - readonly panelKey: PanelKey; - readonly onRestore: (key: PanelKey) => void; -}) { - const handleDragStart = (event: DragEvent) => { - event.dataTransfer.setData(PANEL_DND_MIME, props.panelKey); - event.dataTransfer.effectAllowed = "move"; - }; - return ( - - ); -} - -function countThreadTreeNodes(nodes: ReadonlyArray): number { - return nodes.reduce((count, node) => count + 1 + countThreadTreeNodes(node.children), 0); -} - -function ThreadTreePanel(props: { - readonly title: string; - readonly nodes: ReadonlyArray; - readonly activeThreadId: ThreadId | null; - readonly disabled: boolean; - readonly panelKey?: PanelKey; - readonly onClose?: () => void; - readonly onCreateThread: () => void; - readonly onOpenThread: (threadId: ThreadId) => void; -}) { - const count = countThreadTreeNodes(props.nodes); - return ( -
- - - - {count} - - - } - /> - {count === 0 ? ( -
- No threads yet. -
- ) : ( -
-
    - {props.nodes.map((node) => ( - - ))} -
-
- )} -
- ); -} - -function ThreadTreeRow(props: { - readonly node: DebugThreadTreeNode; - readonly depth: number; - readonly activeThreadId: ThreadId | null; - readonly onOpenThread: (threadId: ThreadId) => void; -}) { - const thread = props.node.thread; - const active = props.node.threadId === props.activeThreadId; - const relationship = thread.lineage.relationshipToParent ?? "source"; - const instanceId = props.node.modelSelection.instanceId; - const model = props.node.modelSelection.model; - const itemCount = thread.visibleItemCount; - const createdAt = formatTimestamp(thread.createdAt); - - return ( -
  • 0 ? true : undefined} - className="relative" - > - {props.depth === 0 ? null : ( -
  • - ); -} - -function QueueControls(props: { - readonly rows: ReadonlyArray; - readonly activeTurn: ActiveTurn | null; - readonly disabled: boolean; - readonly onPromote: (runId: RunId) => void; - readonly onReorder: (runId: RunId, beforeRunId: RunId | null) => void; -}) { - if (props.rows.length === 0) { - return null; - } - - return ( -
    -
    -

    Queue

    - - {props.rows.length} - -
    -
      - {props.rows.map((row, index) => { - const previous = props.rows[index - 1]; - const afterNext = props.rows[index + 2]; - const canPromote = props.activeTurn !== null; - return ( -
    1. - - {row.run.queuePosition ?? row.run.ordinal} - -
      -

      {row.messageText}

      -

      - Run {row.run.ordinal} · {compactId(row.run.id)} -

      -
      -
      - { - if (previous !== undefined) { - props.onReorder(row.run.id, previous.run.id); - } - }} - > - ↑ - - { - props.onReorder(row.run.id, afterNext?.run.id ?? null); - }} - > - ↓ - - -
      -
    2. - ); - })} -
    -
    - ); -} - -function MergeBackControls(props: { - readonly candidate: MergeBackCandidate | null; - readonly disabled: boolean; - readonly onMergeBack: () => void; -}) { - if (props.candidate === null) { - return null; - } - - const canMerge = props.candidate.latestCompletedRun !== null; - if (!canMerge) return null; - return ( - - ); -} - -function PendingMergeBackNotice(props: { readonly transfer: PendingMergeBackTransfer | null }) { - if (props.transfer === null) { - return null; - } - - return ( -
    - -

    - Merge back pending from{" "} - - {compactId(props.transfer.sourceThreadId) ?? props.transfer.sourceThreadId} - - . Your next message will include that fork context. -

    -
    - ); -} - -function QueueActionButton(props: { - readonly label: string; - readonly disabled: boolean; - readonly onClick: () => void; - readonly children: ReactNode; -}) { - return ( - - ); -} - -function PanelHeader(props: { - readonly title: string; - readonly panelKey?: PanelKey | undefined; - readonly onClose?: (() => void) | undefined; - readonly trailing?: ReactNode; -}) { - const { panelKey, onClose } = props; - const handleDragStart = useCallback( - (event: DragEvent) => { - if (panelKey === undefined) return; - event.dataTransfer.setData(PANEL_DND_MIME, panelKey); - event.dataTransfer.effectAllowed = "move"; - }, - [panelKey], - ); - - return ( -
    - {panelKey === undefined ? null : ( - - )} -

    {props.title}

    -
    - {props.trailing} - {onClose ? ( - - ) : null} -
    -
    - ); -} - -function OrchestrationV2DebugRoute() { - const [prompt, setPrompt] = useState(DEFAULT_PROMPT); - const [modelSelection, setModelSelection] = useState(DEFAULT_MODEL_SELECTION); - const [threadId, setThreadId] = useState(null); - const [projection, setProjection] = useState(null); - const [projectionError, setProjectionError] = useState(null); - const [logEntries, setLogEntries] = useState>([]); - const [shellThreadsById, setShellThreadsById] = useState< - ReadonlyMap - >(() => new Map()); - const [projectionByThread, setProjectionByThread] = useState< - ReadonlyMap - >(() => new Map()); - const [isBusy, setIsBusy] = useState(false); - const [visiblePanels, setVisiblePanels] = - useState>(DEFAULT_VISIBLE_PANELS); - const unsubscribeRef = useRef<(() => void) | null>(null); - const shellUnsubscribeRef = useRef<(() => void) | null>(null); - - const environmentId = usePrimaryEnvironmentId(); - const serverProviders = useAtomValue(primaryServerProvidersAtom); - const settings = usePrimarySettings(); - const keybindings = useAtomValue(primaryServerKeybindingsAtom); - const dispatchCommandMutation = useAtomCommand(orchestrationEnvironment.v2.dispatchCommand, { - reportFailure: false, - }); - const getThreadProjectionQuery = useAtomQueryRunner( - orchestrationEnvironment.v2.threadProjection, - { reportFailure: false }, - ); - const shellSubscription = useEnvironmentQuery( - environmentId === null ? null : orchestrationEnvironment.v2.shell({ environmentId, input: {} }), - ); - const threadSubscription = useEnvironmentQuery( - environmentId === null || threadId === null - ? null - : orchestrationEnvironment.v2.thread({ - environmentId, - input: { threadId }, - }), - ); - const providerSnapshots = useMemo( - () => - deriveOrchestrationV2DebugProviderSnapshots({ - providers: serverProviders.length > 0 ? serverProviders : DEBUG_PROVIDER_SNAPSHOTS, - providerInstances: settings.providerInstances, - }), - [serverProviders, settings.providerInstances], - ); - const providerInstanceEntries = useMemo>( - () => sortProviderInstanceEntries(deriveProviderInstanceEntries(providerSnapshots)), - [providerSnapshots], - ); - const modelOptionsByInstance = useMemo< - ReadonlyMap> - >(() => { - const out = new Map>(); - for (const entry of providerInstanceEntries) { - out.set(entry.instanceId, getAppModelOptionsForInstance(settings, entry)); - } - return out; - }, [providerInstanceEntries, settings]); - - useEffect(() => { - setModelSelection((current) => { - const next = resolveDebugModelSelection( - current, - providerInstanceEntries, - modelOptionsByInstance, - ); - return current.instanceId === next.instanceId && current.model === next.model - ? current - : next; - }); - }, [modelOptionsByInstance, providerInstanceEntries]); - - const hiddenPanels = useMemo( - () => ALL_PANEL_KEYS.filter((key) => !visiblePanels.includes(key)), - [visiblePanels], - ); - - const restorePanel = useCallback( - (key: PanelKey, targetKey?: PanelKey, side: "before" | "after" = "before") => { - setVisiblePanels((prev) => { - const without = prev.filter((k) => k !== key); - if (targetKey === undefined) return [...without, key]; - const targetIdx = without.indexOf(targetKey); - if (targetIdx === -1) return [...without, key]; - const insertIdx = side === "before" ? targetIdx : targetIdx + 1; - return [...without.slice(0, insertIdx), key, ...without.slice(insertIdx)]; - }); - }, - [], - ); - - const closePanel = useCallback((key: PanelKey) => { - setVisiblePanels((prev) => prev.filter((k) => k !== key)); - }, []); - - const api = useMemo(() => getPrimaryEnvironmentConnection().client.orchestrationV2, []); - const projectionTimeline = useMemo(() => buildProjectionTimeline(projection), [projection]); - const streamTimeline = useMemo(() => buildStreamTimeline(logEntries), [logEntries]); - const itemTimeline = useMemo( - () => - buildItemTimeline({ - projection, - projectionsByThread: projectionByThread, - logEntries, - }), - [logEntries, projection, projectionByThread], - ); - const threadTree = useMemo( - () => buildThreadTree({ threads: shellThreadsById, projectionsByThread: projectionByThread }), - [projectionByThread, shellThreadsById], - ); - const activeTurn = useMemo(() => deriveActiveTurn(projection), [projection]); - const queuedRuns = useMemo(() => buildQueuedRunRows(projection), [projection]); - const mergeBackCandidate = useMemo(() => deriveMergeBackCandidate(projection), [projection]); - const pendingMergeBackTransfer = useMemo( - () => derivePendingMergeBackTransfer(projection), - [projection], - ); - - const appendLog = useCallback((entry: LogEntry) => { - setLogEntries((entries) => [...entries, entry]); - }, []); - - const cacheProjection = useCallback((nextProjection: OrchestrationV2ThreadProjection) => { - setProjectionByThread((current) => { - const next = new Map(current); - next.set(nextProjection.thread.id, nextProjection); - return next; - }); - }, []); - - const clearSubscription = useCallback(() => { - unsubscribeRef.current?.(); - unsubscribeRef.current = null; - }, []); - - setShellThreadsById((current) => { - const next = new Map(current); - if (item.kind === "project.updated" || item.kind === "project.removed") { - return next; - } - if (item.kind === "thread.removed") { - next.delete(item.threadId); - return next; - } - next.set(item.thread.id, item.thread); - return next; - }); - }, [shellSubscription.data]); - - useEffect(() => { - const item = threadSubscription.data; - if (item === null) return; - appendLog({ type: "stream", value: item }); - if (item.kind === "snapshot") { - setProjectionError(null); - setProjection(item.projection); - cacheProjection(item.projection); - return; - } - - setProjection((current) => { - const nextProjection = applyOrchestrationV2ProjectionEvent(current, item.event); - if (nextProjection !== null) { - setProjectionError(null); - cacheProjection(nextProjection); - } - - setShellThreadsById((current) => { - const next = new Map(current); - next.set(item.thread.id, item.thread); - return next; - }); - }); - - return () => { - shellUnsubscribeRef.current?.(); - shellUnsubscribeRef.current = null; - }; - }, [api]); - - const refreshProjection = useCallback( - async (nextThreadId: ThreadId) => { - try { - const nextProjection = await api.getThreadProjection({ - threadId: nextThreadId, - }); - setProjectionError(null); - setProjection(nextProjection); - cacheProjection(nextProjection); - return nextProjection; - } catch (error) { - const message = formatErrorMessage(error); - setProjection(null); - setProjectionError(message); - appendLog({ type: "error", message }); - return null; - } - }, - [api, appendLog, cacheProjection], - ); - - const subscribeToThread = useCallback( - (nextThreadId: ThreadId) => { - clearSubscription(); - setLogEntries([]); - unsubscribeRef.current = api.subscribeThread( - { threadId: nextThreadId }, - (item) => { - appendLog({ type: "stream", value: item }); - if (item.kind === "snapshot") { - setProjectionError(null); - setProjection(item.projection); - cacheProjection(item.projection); - return; - } - if (item.kind === "event") { - setProjection((current) => { - const nextProjection = applyStreamEventToProjection(current, item.event); - if (nextProjection !== null) { - setProjectionError(null); - cacheProjection(nextProjection); - } - return nextProjection; - }); - } - }, - { - onResubscribe: () => { - appendLog({ - type: "command", - label: "subscription.resubscribe", - value: { threadId: nextThreadId }, - }); - }, - onError: (message) => { - setProjection(null); - setProjectionError(message); - appendLog({ type: "error", message }); - }, - }, - ); - }, - [api, appendLog, cacheProjection, clearSubscription], - ); - - const openThread = useCallback( - async (nextThreadId: ThreadId) => { - setThreadId(nextThreadId); - subscribeToThread(nextThreadId); - const nextProjection = await refreshProjection(nextThreadId); - if (nextProjection !== null) { - setModelSelection(nextProjection.thread.modelSelection); - } - }, - [refreshProjection, subscribeToThread], - ); - - const createDebugThread = useCallback(async () => { - const nextThreadId = newThreadId(); - const result = await api.dispatchCommand({ - type: "thread.create", - createdBy: "user", - creationSource: "web", - commandId: newCommandId(), - threadId: nextThreadId, - projectId: newProjectId(), - title: "V2 debug thread", - modelSelection, - runtimeMode: "full-access" satisfies RuntimeMode, - interactionMode: "default", - branch: null, - worktreePath: null, - }); - - setThreadId(nextThreadId); - subscribeToThread(nextThreadId); - appendLog({ type: "command", label: "thread.create", value: result }); - await refreshProjection(nextThreadId); - return nextThreadId; - }, [api, appendLog, modelSelection, refreshProjection, subscribeToThread]); - - const ensureThread = useCallback(async () => { - if (threadId !== null) { - return threadId; - } - - return createDebugThread(); - }, [createDebugThread, threadId]); - - const createNewThread = useCallback(async () => { - if (isBusy) return; - setIsBusy(true); - try { - await createDebugThread(); - } catch (error) { - appendLog({ - type: "error", - message: error instanceof Error ? error.message : String(error), - }); - } finally { - setIsBusy(false); - } - }, [appendLog, createDebugThread, isBusy]); - - const sendPrompt = useCallback( - async (intent: "send" | "steer" = "send") => { - const trimmedPrompt = prompt.trim(); - if (trimmedPrompt.length === 0 || isBusy) { - return; - } - - setIsBusy(true); - try { - const activeThreadId = await ensureThread(); - const targetRunId = activeTurn?.targetRunId; - const result = await api.dispatchCommand({ - type: "message.dispatch", - createdBy: "user", - creationSource: "web", - commandId: newCommandId(), - threadId: activeThreadId, - messageId: newMessageId(), - text: trimmedPrompt, - attachments: [], - modelSelection, - dispatchMode: - intent === "steer" && targetRunId !== undefined - ? { type: "steer_active", targetRunId } - : targetRunId !== undefined - ? { type: "queue_after_active" } - : { type: "start_immediately" }, - }); - appendLog({ - type: "command", - label: "message.dispatch", - value: result, - }); - await refreshProjection(activeThreadId); - } catch (error) { - appendLog({ - type: "error", - message: formatErrorMessage(error), - }); - } finally { - setIsBusy(false); - } - }, - [ - activeTurn?.targetRunId, - api, - appendLog, - ensureThread, - isBusy, - modelSelection, - prompt, - refreshProjection, - ], - ); - - const promoteQueuedRun = useCallback( - async (queuedRunId: RunId) => { - if (threadId === null || activeTurn === null || isBusy) return; - setIsBusy(true); - try { - const result = await api.dispatchCommand({ - type: "queued-message.promote-to-steer", - commandId: newCommandId(), - threadId, - queuedRunId, - targetRunId: activeTurn.targetRunId, - }); - appendLog({ - type: "command", - label: "queued-message.promote-to-steer", - value: result, - }); - await refreshProjection(threadId); - } catch (error) { - appendLog({ - type: "error", - message: formatErrorMessage(error), - }); - } finally { - setIsBusy(false); - } - }, - [activeTurn, api, appendLog, isBusy, refreshProjection, threadId], - ); - - const interruptActiveRun = useCallback(async () => { - if (threadId === null || activeTurn === null || isBusy) return; - setIsBusy(true); - try { - const result = await api.dispatchCommand({ - type: "run.interrupt", - commandId: newCommandId(), - threadId, - runId: activeTurn.targetRunId, - }); - appendLog({ type: "command", label: "run.interrupt", value: result }); - await refreshProjection(threadId); - } catch (error) { - appendLog({ - type: "error", - message: error instanceof Error ? error.message : String(error), - }); - } finally { - setIsBusy(false); - } - }, [activeTurn, api, appendLog, isBusy, refreshProjection, threadId]); - - const reorderQueuedRun = useCallback( - async (runId: RunId, beforeRunId: RunId | null) => { - if (threadId === null || isBusy) return; - setIsBusy(true); - try { - const result = await api.dispatchCommand({ - type: "queued-run.reorder", - commandId: newCommandId(), - threadId, - runId, - beforeRunId, - }); - appendLog({ - type: "command", - label: "queued-run.reorder", - value: result, - }); - await refreshProjection(threadId); - } catch (error) { - appendLog({ - type: "error", - message: formatErrorMessage(error), - }); - } finally { - setIsBusy(false); - } - }, - [api, appendLog, isBusy, refreshProjection, threadId], - ); - - const forkFromRun = useCallback( - async (input: { readonly threadId: ThreadId; readonly runId: RunId }) => { - const sourceProjection = projectionByThread.get(input.threadId); - if (sourceProjection === undefined || isBusy) return; - - setIsBusy(true); - try { - const targetThreadId = newThreadId(); - const result = await api.dispatchCommand({ - type: "thread.fork", - createdBy: "user", - creationSource: "web", - commandId: newCommandId(), - sourceThreadId: input.threadId, - targetThreadId, - sourcePoint: { type: "run", runId: input.runId }, - title: `${sourceProjection.thread.title} fork`, - }); - appendLog({ type: "command", label: "thread.fork", value: result }); - await openThread(targetThreadId); - } catch (error) { - appendLog({ - type: "error", - message: error instanceof Error ? error.message : String(error), - }); - } finally { - setIsBusy(false); - } - }, - [api, appendLog, isBusy, openThread, projectionByThread], - ); - - const mergeBackToSource = useCallback(async () => { - if (mergeBackCandidate === null || mergeBackCandidate.latestCompletedRun === null || isBusy) { - return; - } - - setIsBusy(true); - try { - const result = await api.dispatchCommand({ - type: "thread.merge_back", - createdBy: "user", - creationSource: "web", - commandId: newCommandId(), - sourceThreadId: mergeBackCandidate.sourceThreadId, - targetThreadId: mergeBackCandidate.targetThreadId, - sourcePoint: { - type: "run", - runId: mergeBackCandidate.latestCompletedRun.id, - }, - }); - appendLog({ type: "command", label: "thread.merge_back", value: result }); - await openThread(mergeBackCandidate.targetThreadId); - } catch (error) { - appendLog({ - type: "error", - message: error instanceof Error ? error.message : String(error), - }); - } finally { - setIsBusy(false); - } - }, [api, appendLog, isBusy, mergeBackCandidate, openThread]); - - const rollbackToCheckpoint = useCallback( - async (input: { readonly checkpointId: CheckpointId; readonly scopeId: CheckpointScopeId }) => { - if (threadId === null || isBusy) return; - setIsBusy(true); - try { - const result = await api.dispatchCommand({ - type: "checkpoint.rollback", - commandId: newCommandId(), - threadId, - scopeId: input.scopeId, - checkpointId: input.checkpointId, - }); - appendLog({ - type: "command", - label: "checkpoint.rollback", - value: result, - }); - await refreshProjection(threadId); - } catch (error) { - appendLog({ - type: "error", - message: formatErrorMessage(error), - }); - } finally { - setIsBusy(false); - } - }, - [api, appendLog, isBusy, refreshProjection, threadId], - ); - - const reset = useCallback(() => { - clearSubscription(); - setThreadId(null); - setProjection(null); - setProjectionError(null); - setLogEntries([]); - setProjectionByThread(new Map()); - }, [clearSubscription]); - - const renderPanel = (panelKey: PanelKey): ReactNode => { - const onClose = () => { - closePanel(panelKey); - }; - switch (panelKey) { - case "tree": - return ( - { - void createNewThread(); - }} - onOpenThread={(nextThreadId) => { - void openThread(nextThreadId); - }} - /> - ); - case "projection": - return ( - - ); - case "item": - return ( - { - void openThread(nextThreadId); - }} - onForkFromRun={(input) => { - void forkFromRun(input); - }} - onRollbackToCheckpoint={(input) => { - void rollbackToCheckpoint(input); - }} - /> - ); - case "stream": - return ( - - ); - } - }; - - return ( -
    -
    -
    - -
    -
    - { - setModelSelection(createModelSelection(instanceId, model)); - }} - /> - - -
    -
    - - { - restorePanel(key); - }} - /> - -
    -
    { - event.preventDefault(); - void sendPrompt("send"); - }} - > - -