Retire V1 client orchestration parity
Co-authored-by: codex <[email protected]>
This commit is contained in:
1 parent
86941636d7
commit
25862ffc34
92 files changed
+1371
-6669
No files matched your search
@@ -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
|
||||
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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";
|
||||
|
||||
@@ -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(
|
||||
() =>
|
||||
|
||||
@@ -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(() => ({
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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<A>(value: A, delayMs: number): A {
|
||||
return debounced;
|
||||
}
|
||||
|
||||
export function useThreadSearch(
|
||||
environmentIds: ReadonlyArray<EnvironmentId>,
|
||||
query: string,
|
||||
): {
|
||||
readonly matches: ReadonlyArray<EnvironmentThreadSearchMatch>;
|
||||
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;
|
||||
|
||||
@@ -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<EnvironmentThreadState, "data"> & { readonly data: Option.Option<EnvironmentThread> } {
|
||||
): 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;
|
||||
}
|
||||
@@ -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<RuntimeRequestId | null>(null);
|
||||
const [respondingUserInputId, setRespondingUserInputId] = useState<RuntimeRequestId | null>(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
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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) => {
|
||||
|
||||
@@ -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<ScopedThreadProjection | null>(null).pipe(
|
||||
const EMPTY_THREAD_PROJECTION_ATOM = Atom.make<EnvironmentThread | null>(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,
|
||||
|
||||
@@ -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> = {}): 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,
|
||||
};
|
||||
}
|
||||
@@ -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 },
|
||||
],
|
||||
|
||||
@@ -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";
|
||||
|
||||
@@ -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";
|
||||
|
||||
@@ -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";
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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";
|
||||
|
||||
@@ -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";
|
||||
|
||||
|
||||
@@ -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";
|
||||
|
||||
@@ -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";
|
||||
|
||||
@@ -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";
|
||||
|
||||
@@ -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";
|
||||
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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";
|
||||
|
||||
@@ -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";
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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";
|
||||
|
||||
@@ -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";
|
||||
|
||||
@@ -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";
|
||||
|
||||
@@ -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";
|
||||
|
||||
@@ -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";
|
||||
|
||||
@@ -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";
|
||||
|
||||
@@ -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";
|
||||
|
||||
@@ -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";
|
||||
|
||||
@@ -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";
|
||||
|
||||
+1
-10
@@ -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<string, AuthEnvironmentScope>([
|
||||
[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,
|
||||
|
||||
@@ -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),
|
||||
);
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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<boolean> {
|
||||
const threadAtom = environmentThreadDetails.detailAtom(threadRef);
|
||||
const threadAtom = environmentThreadShells.threadShellAtom(threadRef);
|
||||
return waitForAtomValue({
|
||||
registry: appAtomRegistry,
|
||||
atom: threadAtom,
|
||||
|
||||
@@ -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<string, PendingUserInputDraftAnswer> = {};
|
||||
function useDraftHeroLayoutTransition(isDraftHeroState: boolean) {
|
||||
const transitionGroupRef = useRef<HTMLDivElement | null>(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<string>([...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<ThreadPlanCatalogEntry[]>(() => {
|
||||
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<string>();
|
||||
for (const row of serverVisibleTurnItems) {
|
||||
@@ -2232,16 +2263,7 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
}
|
||||
return [...attachmentIds];
|
||||
}, [serverVisibleTurnItems]);
|
||||
const draftAttachmentIds = useMemo(() => {
|
||||
const attachmentIds = new Set<string>();
|
||||
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<ReadonlyArray<ChatMessage>>(() => {
|
||||
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<string, ChatMessage>(
|
||||
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<MessageId, TurnDiffSummary>();
|
||||
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<unknown, unknown> | 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<unknown, unknown> | 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}
|
||||
|
||||
@@ -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) => {
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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> = {}): Project {
|
||||
};
|
||||
}
|
||||
|
||||
function makeThread(overrides: Partial<Thread> = {}): Thread {
|
||||
function makeThread(overrides: ThreadFixtureOverrides = {}): Thread {
|
||||
return makeThreadFixture({
|
||||
id: ThreadId.make("thread-1"),
|
||||
environmentId: localEnvironmentId,
|
||||
|
||||
@@ -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<OrchestrationV2ProjectedTurnItem> | 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;
|
||||
|
||||
@@ -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<LegendListRef | null>;
|
||||
timelineEntries: ReturnType<typeof deriveTimelineEntries>;
|
||||
timelineEntries: ReadonlyArray<TimelineEntry>;
|
||||
latestRun: TimelineLatestRun | null;
|
||||
turnDiffSummaryByAssistantMessageId: Map<MessageId, TurnDiffSummary>;
|
||||
routeThreadKey: string;
|
||||
@@ -923,7 +923,6 @@ function TimelineMinimap({
|
||||
// TimelineRowContent — the actual row component
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
type TimelineEntry = ReturnType<typeof deriveTimelineEntries>[number];
|
||||
type TimelineMessage = Extract<TimelineEntry, { kind: "message" }>["message"];
|
||||
type TimelineWorkEntry = Extract<MessagesTimelineRow, { kind: "work" }>["groupedEntries"][number];
|
||||
type TimelineRow = MessagesTimelineRow;
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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<ReadonlyArray<TurnDiffSummary>>(() => {
|
||||
if (!activeThread) {
|
||||
if (projection === null) {
|
||||
return [];
|
||||
}
|
||||
return activeThread.checkpoints;
|
||||
}, [activeThread]);
|
||||
return deriveThreadCheckpointSummaries(projection);
|
||||
}, [projection]);
|
||||
|
||||
const inferredCheckpointTurnCountByRunId = useMemo(
|
||||
() => inferCheckpointTurnCountByRunId(turnDiffSummaries),
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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<ThreadWorkEntry>,
|
||||
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),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -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> = {}): Thread {
|
||||
function makeThread(overrides: ThreadFixtureOverrides = {}): Thread {
|
||||
return makeThreadFixture({
|
||||
id: ThreadId.make("thread-1"),
|
||||
environmentId: LOCAL_ENVIRONMENT_ID,
|
||||
|
||||
@@ -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<T extends OrchestrationEvent["type"]>(
|
||||
type: T,
|
||||
payload: Extract<OrchestrationEvent, { type: T }>["payload"],
|
||||
overrides: Partial<Extract<OrchestrationEvent, { type: T }>> = {},
|
||||
): Extract<OrchestrationEvent, { type: T }> {
|
||||
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<OrchestrationEvent, { type: T }>;
|
||||
}
|
||||
|
||||
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([]);
|
||||
});
|
||||
});
|
||||
@@ -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,
|
||||
};
|
||||
}
|
||||
@@ -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]);
|
||||
});
|
||||
});
|
||||
@@ -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<Record<string, unknown>> {
|
||||
return config !== null && typeof config === "object" && !Array.isArray(config)
|
||||
? (config as Readonly<Record<string, unknown>>)
|
||||
: {};
|
||||
}
|
||||
|
||||
function configuredModels(
|
||||
config: Readonly<Record<string, unknown>>,
|
||||
): ReadonlyArray<ServerProviderModel> {
|
||||
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<ServerProvider>;
|
||||
readonly providerInstances: ProviderInstanceConfigMap;
|
||||
}): ReadonlyArray<ServerProvider> {
|
||||
const snapshots = [...input.providers];
|
||||
const indexByInstanceId = new Map<ProviderInstanceId, number>(
|
||||
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;
|
||||
}
|
||||
@@ -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)
|
||||
|
||||
@@ -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(() => {
|
||||
|
||||
@@ -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;
|
||||
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -17,12 +17,14 @@ import * as DateTime from "effect/DateTime";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
deriveTimelineEntries,
|
||||
deriveTimelineEntriesFromVisibleTurnItems,
|
||||
deriveRevertTurnCountByUserMessageId,
|
||||
findLatestProposedPlan,
|
||||
isLatestRunSettled,
|
||||
type TimelineEntry,
|
||||
} from "./session-logic";
|
||||
import { makeThreadProjectionFixture } from "./test-fixtures";
|
||||
import type { ChatMessage } from "./types";
|
||||
|
||||
describe("V2 session presentation", () => {
|
||||
it("uses run status as the settlement boundary", () => {
|
||||
@@ -48,82 +50,96 @@ describe("V2 session presentation", () => {
|
||||
|
||||
it("selects the latest proposed plan for a run", () => {
|
||||
const runId = RunId.make("run-1");
|
||||
const planId = PlanId.make("plan-1");
|
||||
const nodeId = NodeId.make("node-plan");
|
||||
const now = DateTime.makeUnsafe("2026-06-20T00:00:01.000Z");
|
||||
const baseProjection = makeThreadProjectionFixture();
|
||||
const plan = findLatestProposedPlan(
|
||||
[
|
||||
{
|
||||
id: PlanId.make("plan-1"),
|
||||
runId,
|
||||
planMarkdown: "Plan",
|
||||
status: "active",
|
||||
implementedAt: null,
|
||||
implementationThreadId: ThreadId.make("thread-implementation"),
|
||||
createdAt: "2026-06-20T00:00:00.000Z",
|
||||
updatedAt: "2026-06-20T00:00:01.000Z",
|
||||
},
|
||||
],
|
||||
{
|
||||
...baseProjection,
|
||||
plans: [
|
||||
{
|
||||
id: planId,
|
||||
threadId: baseProjection.thread.id,
|
||||
nodeId,
|
||||
kind: "proposed_plan" as const,
|
||||
markdown: "Plan",
|
||||
status: "active" as const,
|
||||
runId,
|
||||
},
|
||||
],
|
||||
turnItems: [
|
||||
{
|
||||
id: TurnItemId.make("item-plan"),
|
||||
threadId: baseProjection.thread.id,
|
||||
nodeId,
|
||||
providerThreadId: null,
|
||||
providerTurnId: null,
|
||||
nativeItemRef: null,
|
||||
parentItemId: null,
|
||||
ordinal: 0,
|
||||
status: "completed" as const,
|
||||
title: null,
|
||||
startedAt: now,
|
||||
completedAt: now,
|
||||
updatedAt: now,
|
||||
type: "proposed_plan" as const,
|
||||
planId,
|
||||
markdown: "Plan",
|
||||
streaming: false,
|
||||
runId,
|
||||
},
|
||||
],
|
||||
updatedAt: now,
|
||||
},
|
||||
runId,
|
||||
);
|
||||
expect(plan?.planMarkdown).toBe("Plan");
|
||||
});
|
||||
|
||||
it("orders conversation and generic V2 work entries", () => {
|
||||
const entries = deriveTimelineEntries(
|
||||
[
|
||||
{
|
||||
id: "message-1" as never,
|
||||
role: "user",
|
||||
text: "Hello",
|
||||
runId: null,
|
||||
streaming: false,
|
||||
createdAt: "2026-06-20T00:00:00.000Z",
|
||||
updatedAt: "2026-06-20T00:00:00.000Z",
|
||||
},
|
||||
],
|
||||
[],
|
||||
[],
|
||||
);
|
||||
expect(entries.map((entry) => entry.kind)).toEqual(["message"]);
|
||||
});
|
||||
|
||||
it("assigns run rollback to the turn-start message instead of a later steer", () => {
|
||||
const runId = RunId.make("run-steered");
|
||||
const turnStartMessageId = MessageId.make("message-turn-start");
|
||||
const steerMessageId = MessageId.make("message-steer");
|
||||
const assistantMessageId = MessageId.make("message-assistant");
|
||||
const timelineEntries = deriveTimelineEntries(
|
||||
[
|
||||
{
|
||||
id: turnStartMessageId,
|
||||
role: "user",
|
||||
text: "Start",
|
||||
runId,
|
||||
inputIntent: "turn_start",
|
||||
streaming: false,
|
||||
createdAt: "2026-06-20T00:00:00.000Z",
|
||||
updatedAt: "2026-06-20T00:00:00.000Z",
|
||||
},
|
||||
{
|
||||
id: steerMessageId,
|
||||
role: "user",
|
||||
text: "Steer",
|
||||
runId,
|
||||
inputIntent: "steer",
|
||||
streaming: false,
|
||||
createdAt: "2026-06-20T00:00:01.000Z",
|
||||
updatedAt: "2026-06-20T00:00:01.000Z",
|
||||
},
|
||||
{
|
||||
id: assistantMessageId,
|
||||
role: "assistant",
|
||||
text: "Done",
|
||||
runId,
|
||||
streaming: false,
|
||||
createdAt: "2026-06-20T00:00:02.000Z",
|
||||
updatedAt: "2026-06-20T00:00:02.000Z",
|
||||
},
|
||||
],
|
||||
[],
|
||||
[],
|
||||
const messages: ChatMessage[] = [
|
||||
{
|
||||
id: turnStartMessageId,
|
||||
role: "user",
|
||||
text: "Start",
|
||||
runId,
|
||||
inputIntent: "turn_start",
|
||||
streaming: false,
|
||||
createdAt: "2026-06-20T00:00:00.000Z",
|
||||
updatedAt: "2026-06-20T00:00:00.000Z",
|
||||
},
|
||||
{
|
||||
id: steerMessageId,
|
||||
role: "user",
|
||||
text: "Steer",
|
||||
runId,
|
||||
inputIntent: "steer",
|
||||
streaming: false,
|
||||
createdAt: "2026-06-20T00:00:01.000Z",
|
||||
updatedAt: "2026-06-20T00:00:01.000Z",
|
||||
},
|
||||
{
|
||||
id: assistantMessageId,
|
||||
role: "assistant",
|
||||
text: "Done",
|
||||
runId,
|
||||
streaming: false,
|
||||
createdAt: "2026-06-20T00:00:02.000Z",
|
||||
updatedAt: "2026-06-20T00:00:02.000Z",
|
||||
},
|
||||
];
|
||||
const timelineEntries: TimelineEntry[] = messages.map(
|
||||
(message): TimelineEntry => ({
|
||||
id: message.id,
|
||||
kind: "message",
|
||||
createdAt: message.createdAt,
|
||||
message,
|
||||
}),
|
||||
);
|
||||
|
||||
const targets = deriveRevertTurnCountByUserMessageId({
|
||||
|
||||
@@ -1,23 +1,21 @@
|
||||
import {
|
||||
ProviderDriverKind,
|
||||
type OrchestrationV2ExecutionNode,
|
||||
type OrchestrationV2PlanArtifact,
|
||||
type OrchestrationV2ProjectedTurnItem,
|
||||
type OrchestrationV2RunAttempt,
|
||||
type OrchestrationV2ThreadProjection,
|
||||
type OrchestrationV2TurnItem,
|
||||
type PlanId,
|
||||
type RunId,
|
||||
type ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import type { ThreadCheckpointSummary } from "@t3tools/client-runtime/state/thread-checkpoints";
|
||||
import type {
|
||||
ThreadCheckpointSummary,
|
||||
ThreadPendingApproval,
|
||||
ThreadPendingUserInput,
|
||||
ThreadProposedPlan,
|
||||
ThreadRunSummary,
|
||||
ThreadRuntimeSummary,
|
||||
ThreadTodoPlan,
|
||||
ThreadWorkEntry,
|
||||
} from "@t3tools/client-runtime/state/shell";
|
||||
} from "@t3tools/client-runtime/state/thread-requests";
|
||||
import type { ThreadRunSummary, ThreadRuntimeSummary } from "@t3tools/client-runtime/state/shell";
|
||||
|
||||
import type { ChatMessage, ProposedPlan, SessionPhase, TurnDiffSummary } from "./types";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
@@ -47,17 +45,30 @@ export const PROVIDER_OPTIONS: Array<{
|
||||
{ value: ProviderDriverKind.make("grok"), label: "Grok", available: true },
|
||||
];
|
||||
|
||||
export type WorkLogToolLifecycleStatus = ThreadWorkEntry["toolLifecycleStatus"];
|
||||
export type WorkLogToolLifecycleStatus =
|
||||
| "inProgress"
|
||||
| "completed"
|
||||
| "failed"
|
||||
| "declined"
|
||||
| "stopped";
|
||||
|
||||
export interface WorkLogEntry extends Omit<
|
||||
ThreadWorkEntry,
|
||||
"structuredPayload" | "runId" | "itemType" | "toolLifecycleStatus"
|
||||
> {
|
||||
export interface WorkLogEntry {
|
||||
readonly id: string;
|
||||
readonly createdAt: string;
|
||||
readonly runId?: RunId | null;
|
||||
readonly itemType?: ThreadWorkEntry["itemType"];
|
||||
readonly toolLifecycleStatus?: ThreadWorkEntry["toolLifecycleStatus"];
|
||||
readonly structuredPayload?: ThreadWorkEntry["structuredPayload"];
|
||||
readonly sourceItemType?: ThreadWorkEntry["itemType"];
|
||||
readonly label: string;
|
||||
readonly detail?: string;
|
||||
readonly command?: string;
|
||||
readonly rawCommand?: string;
|
||||
readonly changedFiles?: ReadonlyArray<string>;
|
||||
readonly tone: "thinking" | "tool" | "info" | "error";
|
||||
readonly toolTitle?: string;
|
||||
readonly toolData?: unknown;
|
||||
readonly requestKind?: string;
|
||||
readonly itemType?: OrchestrationV2TurnItem["type"];
|
||||
readonly toolLifecycleStatus?: WorkLogToolLifecycleStatus;
|
||||
readonly structuredPayload?: OrchestrationV2TurnItem;
|
||||
readonly sourceItemType?: OrchestrationV2TurnItem["type"];
|
||||
readonly projectedItem?: OrchestrationV2ProjectedTurnItem;
|
||||
}
|
||||
|
||||
@@ -80,9 +91,7 @@ export interface LatestProposedPlanState {
|
||||
readonly updatedAt: string;
|
||||
readonly runId: RunId | null;
|
||||
readonly planMarkdown: string;
|
||||
readonly implementedAt: string | null;
|
||||
readonly implementationThreadId: ThreadId | null;
|
||||
readonly status: ThreadProposedPlan["status"];
|
||||
readonly status: OrchestrationV2PlanArtifact["status"];
|
||||
}
|
||||
|
||||
export type TimelineAttempt = Pick<
|
||||
@@ -217,31 +226,47 @@ export function derivePendingUserInputs(
|
||||
}
|
||||
|
||||
export function deriveActivePlanState(
|
||||
plans: ReadonlyArray<ThreadTodoPlan>,
|
||||
projection: OrchestrationV2ThreadProjection | null,
|
||||
latestRunId: RunId | undefined,
|
||||
): ActivePlanState | null {
|
||||
if (projection === null) return null;
|
||||
const plans = projection.plans.filter((plan) => plan.kind === "todo_list");
|
||||
const plan =
|
||||
[...plans].toReversed().find((candidate) => candidate.runId === latestRunId) ??
|
||||
plans.at(-1) ??
|
||||
null;
|
||||
if (plan === null || plan.steps.length === 0) return null;
|
||||
return {
|
||||
createdAt: plan.updatedAt,
|
||||
createdAt: planItemTime(projection, plan.id),
|
||||
runId: plan.runId,
|
||||
explanation: plan.explanation,
|
||||
steps: plan.steps.map(({ step, status }) => ({ step, status })),
|
||||
explanation: plan.explanation ?? null,
|
||||
steps: plan.steps.map(({ text, status }) => ({
|
||||
step: text,
|
||||
status: status === "running" ? "inProgress" : status,
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
function toLatestProposedPlanState(plan: ThreadProposedPlan): LatestProposedPlanState {
|
||||
function planItemTime(projection: OrchestrationV2ThreadProjection, planId: PlanId): string {
|
||||
const item = projection.turnItems.findLast(
|
||||
(candidate) =>
|
||||
(candidate.type === "proposed_plan" || candidate.type === "todo_list") &&
|
||||
candidate.planId === planId,
|
||||
);
|
||||
return DateTime.formatIso(item?.updatedAt ?? projection.updatedAt);
|
||||
}
|
||||
|
||||
function toLatestProposedPlanState(
|
||||
projection: OrchestrationV2ThreadProjection,
|
||||
plan: Extract<OrchestrationV2PlanArtifact, { readonly kind: "proposed_plan" }>,
|
||||
): LatestProposedPlanState {
|
||||
const updatedAt = planItemTime(projection, plan.id);
|
||||
return {
|
||||
id: plan.id,
|
||||
createdAt: plan.createdAt,
|
||||
updatedAt: plan.updatedAt,
|
||||
createdAt: updatedAt,
|
||||
updatedAt,
|
||||
runId: plan.runId,
|
||||
planMarkdown: plan.planMarkdown,
|
||||
implementedAt: plan.implementedAt,
|
||||
implementationThreadId: plan.implementationThreadId,
|
||||
planMarkdown: plan.markdown,
|
||||
status: plan.status,
|
||||
};
|
||||
}
|
||||
@@ -313,87 +338,49 @@ export function deriveTurnPlans(
|
||||
}
|
||||
|
||||
export function findLatestProposedPlan(
|
||||
plans: ReadonlyArray<ThreadProposedPlan>,
|
||||
projection: OrchestrationV2ThreadProjection | null,
|
||||
latestRunId: RunId | string | null | undefined,
|
||||
): LatestProposedPlanState | null {
|
||||
if (projection === null) return null;
|
||||
const plans = projection.plans.filter((plan) => plan.kind === "proposed_plan");
|
||||
const candidates = latestRunId ? plans.filter((plan) => plan.runId === latestRunId) : plans;
|
||||
const plan = [...(candidates.length > 0 ? candidates : plans)]
|
||||
.toSorted(
|
||||
(left, right) =>
|
||||
left.updatedAt.localeCompare(right.updatedAt) || left.id.localeCompare(right.id),
|
||||
planItemTime(projection, left.id).localeCompare(planItemTime(projection, right.id)) ||
|
||||
left.id.localeCompare(right.id),
|
||||
)
|
||||
.at(-1);
|
||||
return plan === undefined ? null : toLatestProposedPlanState(plan);
|
||||
return plan === undefined ? null : toLatestProposedPlanState(projection, plan);
|
||||
}
|
||||
|
||||
export function findSidebarProposedPlan(input: {
|
||||
readonly threads: ReadonlyArray<
|
||||
Pick<
|
||||
{ readonly id: ThreadId; readonly proposedPlans: ReadonlyArray<ThreadProposedPlan> },
|
||||
"id" | "proposedPlans"
|
||||
>
|
||||
>;
|
||||
readonly threads: ReadonlyArray<{
|
||||
readonly id: ThreadId;
|
||||
readonly projection: OrchestrationV2ThreadProjection;
|
||||
}>;
|
||||
readonly latestRun: Pick<ThreadRunSummary, "runId" | "sourcePlanRef"> | null;
|
||||
readonly latestRunSettled: boolean;
|
||||
readonly threadId: ThreadId | string | null | undefined;
|
||||
}): LatestProposedPlanState | null {
|
||||
if (!input.latestRunSettled && input.latestRun?.sourcePlanRef !== undefined) {
|
||||
const source = input.latestRun.sourcePlanRef;
|
||||
const plan = input.threads
|
||||
.find((thread) => thread.id === source.threadId)
|
||||
?.proposedPlans.find((candidate) => candidate.id === source.planId);
|
||||
if (plan !== undefined) return toLatestProposedPlanState(plan);
|
||||
const sourceProjection = input.threads.find(
|
||||
(thread) => thread.id === source.threadId,
|
||||
)?.projection;
|
||||
const plan = sourceProjection?.plans.find(
|
||||
(candidate) => candidate.kind === "proposed_plan" && candidate.id === source.planId,
|
||||
);
|
||||
if (sourceProjection !== undefined && plan?.kind === "proposed_plan") {
|
||||
return toLatestProposedPlanState(sourceProjection, plan);
|
||||
}
|
||||
}
|
||||
const activePlans =
|
||||
input.threads.find((thread) => thread.id === input.threadId)?.proposedPlans ?? [];
|
||||
return findLatestProposedPlan(activePlans, input.latestRun?.runId);
|
||||
const activeProjection = input.threads.find((thread) => thread.id === input.threadId)?.projection;
|
||||
return findLatestProposedPlan(activeProjection ?? null, input.latestRun?.runId);
|
||||
}
|
||||
|
||||
export function hasActionableProposedPlan(
|
||||
plan: LatestProposedPlanState | Pick<ThreadProposedPlan, "implementedAt"> | null,
|
||||
): boolean {
|
||||
return plan !== null && plan.implementedAt === null;
|
||||
}
|
||||
|
||||
export function deriveWorkLogEntries(entries: ReadonlyArray<ThreadWorkEntry>): WorkLogEntry[] {
|
||||
return entries.map((entry) => ({ ...entry, sourceItemType: entry.itemType }));
|
||||
}
|
||||
|
||||
export function deriveTimelineEntries(
|
||||
messages: ReadonlyArray<ChatMessage>,
|
||||
proposedPlans: ReadonlyArray<ThreadProposedPlan>,
|
||||
workEntries: ReadonlyArray<WorkLogEntry>,
|
||||
turnPlans: ReadonlyArray<TurnPlanEntry> = [],
|
||||
): TimelineEntry[] {
|
||||
return [
|
||||
...messages.map(
|
||||
(message): TimelineEntry => ({
|
||||
id: message.id,
|
||||
kind: "message",
|
||||
createdAt: message.createdAt,
|
||||
message,
|
||||
}),
|
||||
),
|
||||
...proposedPlans.map(
|
||||
(proposedPlan): TimelineEntry => ({
|
||||
id: proposedPlan.id,
|
||||
kind: "proposed-plan",
|
||||
createdAt: proposedPlan.createdAt,
|
||||
proposedPlan,
|
||||
}),
|
||||
),
|
||||
...workEntries.map(
|
||||
(entry): TimelineEntry => ({
|
||||
id: entry.id,
|
||||
kind: "work",
|
||||
createdAt: entry.createdAt,
|
||||
entry,
|
||||
}),
|
||||
),
|
||||
].toSorted(
|
||||
(left, right) =>
|
||||
left.createdAt.localeCompare(right.createdAt) || left.id.localeCompare(right.id),
|
||||
);
|
||||
export function hasActionableProposedPlan(plan: LatestProposedPlanState | null): boolean {
|
||||
return plan?.status === "active";
|
||||
}
|
||||
|
||||
const STANDALONE_V2_ITEM_TYPES = new Set<OrchestrationV2ProjectedTurnItem["item"]["type"]>([
|
||||
@@ -635,8 +622,6 @@ export function deriveTimelineEntriesFromVisibleTurnItems(input: {
|
||||
runId: item.runId,
|
||||
planMarkdown: item.markdown,
|
||||
status: "active" as const,
|
||||
implementedAt: null,
|
||||
implementationThreadId: null,
|
||||
createdAt,
|
||||
updatedAt: DateTime.formatIso(item.updatedAt),
|
||||
};
|
||||
|
||||
@@ -3,17 +3,10 @@ import type {
|
||||
EnvironmentProject,
|
||||
EnvironmentThread,
|
||||
EnvironmentThreadShell,
|
||||
ScopedThreadProjection,
|
||||
ThreadConversationMessage,
|
||||
ThreadProposedPlan,
|
||||
ThreadRuntimeSummary,
|
||||
ThreadWorkEntry,
|
||||
} from "@t3tools/client-runtime/state/shell";
|
||||
import { mergeEnvironmentThread } from "@t3tools/client-runtime/state/threads";
|
||||
import type { ScopedProjectRef, ScopedThreadRef, ServerConfig } from "@t3tools/contracts";
|
||||
import type { EnvironmentId, OrchestrationV2ProjectedTurnItem, ThreadId } from "@t3tools/contracts";
|
||||
import { Atom } from "effect/unstable/reactivity";
|
||||
import { useMemo } from "react";
|
||||
import { appAtomRegistry } from "../rpc/atomRegistry";
|
||||
import { environmentProjects } from "./projects";
|
||||
import { environmentServerConfigsAtom } from "./server";
|
||||
@@ -23,9 +16,6 @@ import { waitForAtomValue } from "./waitForAtomValue";
|
||||
|
||||
const EMPTY_PROJECT_REFS: ReadonlyArray<ScopedProjectRef> = Object.freeze([]);
|
||||
const EMPTY_THREAD_REFS: ReadonlyArray<ScopedThreadRef> = Object.freeze([]);
|
||||
const EMPTY_MESSAGES: ReadonlyArray<ThreadConversationMessage> = Object.freeze([]);
|
||||
const EMPTY_WORK_ENTRIES: ReadonlyArray<ThreadWorkEntry> = Object.freeze([]);
|
||||
const EMPTY_PROPOSED_PLANS: ReadonlyArray<ThreadProposedPlan> = Object.freeze([]);
|
||||
const EMPTY_VISIBLE_TURN_ITEMS: ReadonlyArray<OrchestrationV2ProjectedTurnItem> = Object.freeze([]);
|
||||
|
||||
const EMPTY_PROJECT_ATOM = Atom.make<EnvironmentProject | null>(null).pipe(
|
||||
@@ -40,27 +30,12 @@ const EMPTY_THREAD_REFS_ATOM = Atom.make(EMPTY_THREAD_REFS).pipe(
|
||||
const EMPTY_THREAD_SHELL_ATOM = Atom.make<EnvironmentThreadShell | null>(null).pipe(
|
||||
Atom.withLabel("web-thread-shell:empty"),
|
||||
);
|
||||
const EMPTY_THREAD_DETAIL_ATOM = Atom.make<EnvironmentThread | null>(null).pipe(
|
||||
Atom.withLabel("web-thread-detail:empty"),
|
||||
);
|
||||
const EMPTY_SCOPED_THREAD_PROJECTION_ATOM = Atom.make<ScopedThreadProjection | null>(null).pipe(
|
||||
Atom.withLabel("web-scoped-thread-projection:empty"),
|
||||
);
|
||||
const EMPTY_MESSAGES_ATOM = Atom.make(EMPTY_MESSAGES).pipe(
|
||||
Atom.withLabel("web-thread-messages:empty"),
|
||||
);
|
||||
const EMPTY_WORK_ENTRIES_ATOM = Atom.make(EMPTY_WORK_ENTRIES).pipe(
|
||||
Atom.withLabel("web-thread-work-entries:empty"),
|
||||
);
|
||||
const EMPTY_PROPOSED_PLANS_ATOM = Atom.make(EMPTY_PROPOSED_PLANS).pipe(
|
||||
Atom.withLabel("web-thread-proposed-plans:empty"),
|
||||
const EMPTY_THREAD_PROJECTION_ATOM = Atom.make<EnvironmentThread | null>(null).pipe(
|
||||
Atom.withLabel("web-thread-projection:empty"),
|
||||
);
|
||||
const EMPTY_VISIBLE_TURN_ITEMS_ATOM = Atom.make(EMPTY_VISIBLE_TURN_ITEMS).pipe(
|
||||
Atom.withLabel("web-thread-visible-turn-items:empty"),
|
||||
);
|
||||
const EMPTY_RUNTIME_ATOM = Atom.make<ThreadRuntimeSummary | null>(null).pipe(
|
||||
Atom.withLabel("web-thread-runtime:empty"),
|
||||
);
|
||||
|
||||
export const activeEnvironmentIdAtom = Atom.make<EnvironmentId | null>(null).pipe(
|
||||
Atom.keepAlive,
|
||||
@@ -139,59 +114,9 @@ export function useThreadShell(ref: ScopedThreadRef | null): EnvironmentThreadSh
|
||||
);
|
||||
}
|
||||
|
||||
export function useThreadDetail(ref: ScopedThreadRef | null): EnvironmentThread | null {
|
||||
export function useThreadProjection(ref: ScopedThreadRef | null): EnvironmentThread | null {
|
||||
return useAtomValue(
|
||||
ref === null ? EMPTY_THREAD_DETAIL_ATOM : environmentThreadDetails.detailAtom(ref),
|
||||
);
|
||||
}
|
||||
|
||||
export function useThreadProjection(ref: ScopedThreadRef | null): ScopedThreadProjection | null {
|
||||
return useAtomValue(
|
||||
ref === null ? EMPTY_SCOPED_THREAD_PROJECTION_ATOM : environmentThreadDetails.threadAtom(ref),
|
||||
);
|
||||
}
|
||||
|
||||
/** Detail collections composed with shell-authoritative thread/workspace metadata. */
|
||||
export function useThread(
|
||||
ref: ScopedThreadRef | null,
|
||||
options?: {
|
||||
/**
|
||||
* Client-reserved draft thread ids do not exist on the server until the
|
||||
* first send. Waiting for the shell index avoids polling the detail
|
||||
* endpoint for an intentionally missing thread during that window.
|
||||
*/
|
||||
waitForShell?: boolean;
|
||||
},
|
||||
): EnvironmentThread | null {
|
||||
const shell = useThreadShell(ref);
|
||||
const detail = useThreadDetail(
|
||||
resolveThreadDetailRef(ref, {
|
||||
shellExists: shell !== null,
|
||||
waitForShell: options?.waitForShell === true,
|
||||
}),
|
||||
);
|
||||
return useMemo(() => mergeEnvironmentThread(detail, shell), [detail, shell]);
|
||||
}
|
||||
|
||||
export function useThreadMessages(
|
||||
ref: ScopedThreadRef | null,
|
||||
): ReadonlyArray<ThreadConversationMessage> {
|
||||
return useAtomValue(
|
||||
ref === null ? EMPTY_MESSAGES_ATOM : environmentThreadDetails.messagesAtom(ref),
|
||||
);
|
||||
}
|
||||
|
||||
export function useThreadWorkEntries(ref: ScopedThreadRef | null): ReadonlyArray<ThreadWorkEntry> {
|
||||
return useAtomValue(
|
||||
ref === null ? EMPTY_WORK_ENTRIES_ATOM : environmentThreadDetails.workEntriesAtom(ref),
|
||||
);
|
||||
}
|
||||
|
||||
export function useThreadProposedPlans(
|
||||
ref: ScopedThreadRef | null,
|
||||
): ReadonlyArray<ThreadProposedPlan> {
|
||||
return useAtomValue(
|
||||
ref === null ? EMPTY_PROPOSED_PLANS_ATOM : environmentThreadDetails.proposedPlansAtom(ref),
|
||||
ref === null ? EMPTY_THREAD_PROJECTION_ATOM : environmentThreadDetails.threadAtom(ref),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -205,12 +130,6 @@ export function useThreadVisibleTurnItems(
|
||||
);
|
||||
}
|
||||
|
||||
export function useThreadRuntime(ref: ScopedThreadRef | null): ThreadRuntimeSummary | null {
|
||||
return useAtomValue(
|
||||
ref === null ? EMPTY_RUNTIME_ATOM : environmentThreadDetails.runtimeAtom(ref),
|
||||
);
|
||||
}
|
||||
|
||||
export function readProject(ref: ScopedProjectRef): EnvironmentProject | null {
|
||||
return appAtomRegistry.get(environmentProjects.projectAtom(ref));
|
||||
}
|
||||
@@ -246,6 +165,7 @@ export function readEnvironmentSupportsTitleRegeneration(environmentId: Environm
|
||||
);
|
||||
}
|
||||
|
||||
<<<<<<< HEAD
|
||||
/** Whether the environment's server understands thread.pin.reorder (and
|
||||
orderKey on thread.pin). Same version-skew contract as settlement. */
|
||||
export function readEnvironmentSupportsPinReorder(environmentId: EnvironmentId): boolean {
|
||||
@@ -257,6 +177,10 @@ export function readEnvironmentSupportsPinReorder(environmentId: EnvironmentId):
|
||||
|
||||
export function readThreadDetail(ref: ScopedThreadRef): EnvironmentThread | null {
|
||||
return appAtomRegistry.get(environmentThreadDetails.detailAtom(ref));
|
||||
=======
|
||||
export function readThreadProjection(ref: ScopedThreadRef): EnvironmentThread | null {
|
||||
return appAtomRegistry.get(environmentThreadDetails.threadAtom(ref));
|
||||
>>>>>>> d849d1caf9 (Retire V1 client orchestration parity)
|
||||
}
|
||||
|
||||
export function readEnvironmentThreadRefs(
|
||||
|
||||
@@ -9,8 +9,7 @@ import {
|
||||
type EnvironmentThreadSearchMatch,
|
||||
} from "@t3tools/client-runtime/state/thread-search";
|
||||
import { type VcsRefTarget } from "@t3tools/client-runtime/state/vcs";
|
||||
import type { EnvironmentId, ThreadId, VcsListRefsResult, VcsRef } from "@t3tools/contracts";
|
||||
import type { EnvironmentThread } from "@t3tools/client-runtime/state/shell";
|
||||
import type { VcsListRefsResult, VcsRef } from "@t3tools/contracts";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Option from "effect/Option";
|
||||
import { AsyncResult, Atom } from "effect/unstable/reactivity";
|
||||
@@ -21,7 +20,6 @@ import { orchestrationEnvironment } from "./orchestration";
|
||||
import { isPaginatedBranchesNextPagePending } from "./paginatedBranches";
|
||||
import { projectContentSearch, projectEnvironment } from "./projects";
|
||||
import { useEnvironmentQuery } from "./query";
|
||||
import { useEnvironmentThread } from "./threads";
|
||||
import { vcsEnvironment } from "./vcs";
|
||||
|
||||
const PROJECT_PATH_SEARCH_DEBOUNCE_MS = 120;
|
||||
@@ -48,15 +46,7 @@ const threadSearchResultsAtom = createThreadSearchResultsAtomFamily({
|
||||
labelPrefix: "web:thread-search",
|
||||
});
|
||||
|
||||
export interface ThreadDetailView {
|
||||
readonly data: EnvironmentThread | null;
|
||||
readonly error: string | null;
|
||||
readonly isPending: boolean;
|
||||
readonly isDeleted: boolean;
|
||||
}
|
||||
|
||||
/** Shared with the pull requests page, which debounces its search the same way. */
|
||||
export function useDebouncedValue<A>(value: A, delayMs: number): A {
|
||||
function useDebouncedValue<A>(value: A, delayMs: number): A {
|
||||
const [debounced, setDebounced] = useState(value);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -71,44 +61,6 @@ export function useDebouncedValue<A>(value: A, delayMs: number): A {
|
||||
return debounced;
|
||||
}
|
||||
|
||||
export function useThreadSearch(
|
||||
environmentIds: ReadonlyArray<EnvironmentId>,
|
||||
query: string,
|
||||
): {
|
||||
readonly matches: ReadonlyArray<EnvironmentThreadSearchMatch>;
|
||||
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(target: VcsRefTarget) {
|
||||
const query = target.query?.trim() ?? "";
|
||||
return useEnvironmentQuery(
|
||||
|
||||
@@ -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<EnvironmentThreadState, "data"> & { readonly data: Option.Option<EnvironmentThread> } {
|
||||
): 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;
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { presentThread } from "@t3tools/client-runtime/state/shell";
|
||||
import { presentThreadShell } from "@t3tools/client-runtime/state/shell";
|
||||
import {
|
||||
EnvironmentId,
|
||||
ProjectId,
|
||||
@@ -8,60 +8,41 @@ import {
|
||||
} from "@t3tools/contracts";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
|
||||
import type { Thread } from "./types";
|
||||
import type { ChatMessage, Thread } from "./types";
|
||||
|
||||
const DEFAULT_TIMESTAMP = "2026-01-01T00:00:00.000Z";
|
||||
|
||||
/** Creates a structurally complete V2 thread for UI unit tests. */
|
||||
export function makeThreadFixture(overrides: Partial<Thread> = {}): Thread {
|
||||
const environmentId = overrides.environmentId ?? EnvironmentId.make("environment-test");
|
||||
const id = overrides.id ?? ThreadId.make("thread-test");
|
||||
const projectId = overrides.projectId ?? ProjectId.make("project-test");
|
||||
const providerInstanceId =
|
||||
overrides.providerInstanceId ??
|
||||
overrides.modelSelection?.instanceId ??
|
||||
ProviderInstanceId.make("codex");
|
||||
const modelSelection = overrides.modelSelection ?? {
|
||||
instanceId: providerInstanceId,
|
||||
model: "gpt-5.4",
|
||||
};
|
||||
// Presentation-level overrides are applied after projection. Keep the source
|
||||
// projection valid so tests can deliberately exercise malformed persisted
|
||||
// timestamps without failing inside Effect's DateTime constructor first.
|
||||
const createdAt = DateTime.makeUnsafe(DEFAULT_TIMESTAMP);
|
||||
const updatedAt = DateTime.makeUnsafe(DEFAULT_TIMESTAMP);
|
||||
const archivedAt =
|
||||
overrides.archivedAt === null || overrides.archivedAt === undefined
|
||||
? null
|
||||
: DateTime.makeUnsafe(overrides.archivedAt);
|
||||
const deletedAt =
|
||||
overrides.deletedAt === null || overrides.deletedAt === undefined
|
||||
? null
|
||||
: DateTime.makeUnsafe(overrides.deletedAt);
|
||||
const projection: OrchestrationV2ThreadProjection = {
|
||||
export type ThreadFixtureOverrides = Partial<Thread> & {
|
||||
/** Test-only fallback data for the generic thread-sort contract. */
|
||||
readonly messages?: ReadonlyArray<ChatMessage>;
|
||||
/** Accepted while older unit cases are migrated; never consumed by production code. */
|
||||
readonly proposedPlans?: ReadonlyArray<unknown>;
|
||||
};
|
||||
|
||||
export function makeThreadProjectionFixture(): OrchestrationV2ThreadProjection {
|
||||
const now = DateTime.makeUnsafe(DEFAULT_TIMESTAMP);
|
||||
const id = ThreadId.make("thread-test");
|
||||
const providerInstanceId = ProviderInstanceId.make("codex");
|
||||
return {
|
||||
thread: {
|
||||
id,
|
||||
projectId,
|
||||
title: overrides.title ?? "Thread",
|
||||
projectId: ProjectId.make("project-test"),
|
||||
title: "Thread",
|
||||
providerInstanceId,
|
||||
modelSelection,
|
||||
runtimeMode: overrides.runtimeMode ?? "full-access",
|
||||
interactionMode: overrides.interactionMode ?? "default",
|
||||
branch: overrides.branch ?? null,
|
||||
worktreePath: overrides.worktreePath ?? null,
|
||||
activeProviderThreadId: overrides.activeProviderThreadId ?? null,
|
||||
lineage: overrides.lineage ?? {
|
||||
rootThreadId: id,
|
||||
parentThreadId: null,
|
||||
relationshipToParent: null,
|
||||
},
|
||||
forkedFrom: overrides.forkedFrom ?? null,
|
||||
modelSelection: { instanceId: providerInstanceId, model: "gpt-5.4" },
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
activeProviderThreadId: null,
|
||||
lineage: { rootThreadId: id, parentThreadId: null, relationshipToParent: null },
|
||||
forkedFrom: null,
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
createdAt,
|
||||
updatedAt,
|
||||
archivedAt,
|
||||
deletedAt,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
archivedAt: null,
|
||||
deletedAt: null,
|
||||
},
|
||||
runs: [],
|
||||
attempts: [],
|
||||
@@ -79,11 +60,69 @@ export function makeThreadFixture(overrides: Partial<Thread> = {}): Thread {
|
||||
contextHandoffs: [],
|
||||
contextTransfers: [],
|
||||
visibleTurnItems: [],
|
||||
updatedAt,
|
||||
};
|
||||
|
||||
return {
|
||||
...presentThread(environmentId, projection),
|
||||
...overrides,
|
||||
updatedAt: now,
|
||||
};
|
||||
}
|
||||
|
||||
/** Creates a structurally complete V2 shell for UI unit tests. */
|
||||
export function makeThreadFixture(overrides: ThreadFixtureOverrides = {}): Thread {
|
||||
const environmentId = overrides.environmentId ?? EnvironmentId.make("environment-test");
|
||||
const id = overrides.id ?? ThreadId.make("thread-test");
|
||||
const projectId = overrides.projectId ?? ProjectId.make("project-test");
|
||||
const providerInstanceId =
|
||||
overrides.providerInstanceId ??
|
||||
overrides.modelSelection?.instanceId ??
|
||||
ProviderInstanceId.make("codex");
|
||||
const modelSelection = overrides.modelSelection ?? {
|
||||
instanceId: providerInstanceId,
|
||||
model: "gpt-5.4",
|
||||
};
|
||||
const createdAt = DateTime.makeUnsafe(DEFAULT_TIMESTAMP);
|
||||
const updatedAt = DateTime.makeUnsafe(DEFAULT_TIMESTAMP);
|
||||
const archivedAt =
|
||||
overrides.archivedAt === null || overrides.archivedAt === undefined
|
||||
? null
|
||||
: DateTime.makeUnsafe(overrides.archivedAt);
|
||||
const deletedAt =
|
||||
overrides.deletedAt === null || overrides.deletedAt === undefined
|
||||
? null
|
||||
: DateTime.makeUnsafe(overrides.deletedAt);
|
||||
const shell = presentThreadShell(environmentId, {
|
||||
id,
|
||||
projectId,
|
||||
title: overrides.title ?? "Thread",
|
||||
providerInstanceId,
|
||||
modelSelection,
|
||||
runtimeMode: overrides.runtimeMode ?? "full-access",
|
||||
interactionMode: overrides.interactionMode ?? "default",
|
||||
branch: overrides.branch ?? null,
|
||||
worktreePath: overrides.worktreePath ?? null,
|
||||
activeProviderThreadId: overrides.activeProviderThreadId ?? null,
|
||||
lineage: overrides.lineage ?? {
|
||||
rootThreadId: id,
|
||||
parentThreadId: null,
|
||||
relationshipToParent: null,
|
||||
},
|
||||
forkedFrom: overrides.forkedFrom ?? null,
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
latestRunId: overrides.latestRun?.runId ?? null,
|
||||
activeRunId: overrides.runtime?.activeRunId ?? null,
|
||||
status: overrides.runtime?.status ?? "idle",
|
||||
pendingRuntimeRequest: null,
|
||||
latestVisibleMessage: null,
|
||||
latestUserMessageAt:
|
||||
overrides.latestUserMessageAt === null || overrides.latestUserMessageAt === undefined
|
||||
? null
|
||||
: DateTime.makeUnsafe(overrides.latestUserMessageAt),
|
||||
hasActionableProposedPlan: overrides.hasActionableProposedPlan ?? false,
|
||||
itemCount: overrides.itemCount ?? 0,
|
||||
visibleItemCount: overrides.visibleItemCount ?? 0,
|
||||
createdAt,
|
||||
updatedAt,
|
||||
archivedAt,
|
||||
deletedAt,
|
||||
});
|
||||
|
||||
return { ...shell, ...overrides };
|
||||
}
|
||||
+26
-7
@@ -1,20 +1,23 @@
|
||||
import type {
|
||||
ChatImageAttachment as ContractChatImageAttachment,
|
||||
MessageId,
|
||||
OrchestrationV2Actor,
|
||||
OrchestrationV2CreationSource,
|
||||
OrchestrationV2PlanArtifact,
|
||||
OrchestrationV2UserMessageInputIntent,
|
||||
PlanId,
|
||||
ProjectScript as ContractProjectScript,
|
||||
ProviderInteractionMode,
|
||||
RunId,
|
||||
RuntimeMode,
|
||||
} from "@t3tools/contracts";
|
||||
import type {
|
||||
EnvironmentProject,
|
||||
EnvironmentThread,
|
||||
EnvironmentThreadShell,
|
||||
ThreadCheckpointSummary,
|
||||
ThreadConversationMessage,
|
||||
ThreadProposedPlan,
|
||||
ThreadRunSummary,
|
||||
ThreadRuntimeSummary,
|
||||
} from "@t3tools/client-runtime/state/shell";
|
||||
import type { ThreadCheckpointSummary } from "@t3tools/client-runtime/state/thread-checkpoints";
|
||||
|
||||
export type SessionPhase = "disconnected" | "connecting" | "ready" | "running";
|
||||
export const DEFAULT_RUNTIME_MODE: RuntimeMode = "full-access";
|
||||
@@ -37,17 +40,33 @@ export interface ChatImageAttachment extends ContractChatImageAttachment {
|
||||
|
||||
export type ChatAttachment = ChatImageAttachment;
|
||||
|
||||
export interface ChatMessage extends Omit<ThreadConversationMessage, "attachments"> {
|
||||
export interface ChatMessage {
|
||||
readonly id: MessageId;
|
||||
readonly role: "user" | "assistant" | "system";
|
||||
readonly text: string;
|
||||
readonly attachments?: ReadonlyArray<ChatAttachment> | undefined;
|
||||
readonly runId: RunId | null;
|
||||
readonly streaming: boolean;
|
||||
readonly createdBy?: OrchestrationV2Actor;
|
||||
readonly creationSource?: OrchestrationV2CreationSource;
|
||||
readonly createdAt: string;
|
||||
readonly updatedAt: string;
|
||||
readonly inputIntent?: OrchestrationV2UserMessageInputIntent | undefined;
|
||||
}
|
||||
|
||||
export type ProposedPlan = ThreadProposedPlan;
|
||||
export interface ProposedPlan {
|
||||
readonly id: PlanId;
|
||||
readonly runId: RunId | null;
|
||||
readonly planMarkdown: string;
|
||||
readonly status: OrchestrationV2PlanArtifact["status"];
|
||||
readonly createdAt: string;
|
||||
readonly updatedAt: string;
|
||||
}
|
||||
export type TurnDiffFileChange = ThreadCheckpointSummary["files"][number];
|
||||
export type TurnDiffSummary = ThreadCheckpointSummary;
|
||||
|
||||
export type Project = EnvironmentProject;
|
||||
export type Thread = EnvironmentThread;
|
||||
export type Thread = EnvironmentThreadShell;
|
||||
export type ThreadShell = EnvironmentThreadShell;
|
||||
|
||||
export interface ThreadTurnState {
|
||||
|
||||
@@ -147,6 +147,18 @@
|
||||
"types": "./src/state/threadRelationships.ts",
|
||||
"default": "./src/state/threadRelationships.ts"
|
||||
},
|
||||
"./state/thread-checkpoints": {
|
||||
"types": "./src/state/threadCheckpoints.ts",
|
||||
"default": "./src/state/threadCheckpoints.ts"
|
||||
},
|
||||
"./state/thread-execution": {
|
||||
"types": "./src/state/threadExecution.ts",
|
||||
"default": "./src/state/threadExecution.ts"
|
||||
},
|
||||
"./state/thread-requests": {
|
||||
"types": "./src/state/threadRequests.ts",
|
||||
"default": "./src/state/threadRequests.ts"
|
||||
},
|
||||
"./state/thread-workflows": {
|
||||
"types": "./src/state/threadWorkflows.ts",
|
||||
"default": "./src/state/threadWorkflows.ts"
|
||||
|
||||
@@ -208,13 +208,12 @@ describe("add project shared logic", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it("builds the existing project.create command shape", () => {
|
||||
it("builds the V2 project.create mutation", () => {
|
||||
expect(
|
||||
buildProjectCreateCommand({
|
||||
commandId: CommandId.make("command"),
|
||||
projectId: ProjectId.make("project"),
|
||||
workspaceRoot: "/work/repo",
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
}),
|
||||
).toMatchObject({
|
||||
type: "project.create",
|
||||
|
||||
@@ -2,7 +2,7 @@ import type { EnvironmentConnectionPhase } from "../connection/presentation.ts";
|
||||
import type {
|
||||
CommandId,
|
||||
EnvironmentId,
|
||||
OrchestrationCommand,
|
||||
ProjectMutation,
|
||||
ProjectId,
|
||||
SourceControlDiscoveryResult,
|
||||
SourceControlProviderKind,
|
||||
@@ -283,8 +283,7 @@ export function buildProjectCreateCommand(input: {
|
||||
readonly commandId: CommandId;
|
||||
readonly projectId: ProjectId;
|
||||
readonly workspaceRoot: string;
|
||||
readonly createdAt: string;
|
||||
}): Extract<OrchestrationCommand, { type: "project.create" }> {
|
||||
}): Extract<ProjectMutation, { type: "project.create" }> {
|
||||
return {
|
||||
type: "project.create",
|
||||
commandId: input.commandId,
|
||||
@@ -292,7 +291,9 @@ export function buildProjectCreateCommand(input: {
|
||||
title: inferProjectTitleFromPath(input.workspaceRoot),
|
||||
workspaceRoot: input.workspaceRoot,
|
||||
createWorkspaceRootIfMissing: true,
|
||||
defaultModelSelection: null,
|
||||
createdAt: input.createdAt,
|
||||
defaultModelSelection: {
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
model: DEFAULT_MODEL,
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -1,8 +1,17 @@
|
||||
import { EnvironmentId, MessageId, RunId, TurnItemId } from "@t3tools/contracts";
|
||||
import {
|
||||
EnvironmentId,
|
||||
MessageId,
|
||||
NodeId,
|
||||
RunId,
|
||||
RuntimeRequestId,
|
||||
TurnItemId,
|
||||
} from "@t3tools/contracts";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { presentThread, presentThreadShell } from "./models.ts";
|
||||
import { presentThreadShell } from "./models.ts";
|
||||
import { deriveLatestThreadRun, deriveThreadRuntime } from "./threadExecution.ts";
|
||||
import { derivePendingThreadRequests } from "./threadRequests.ts";
|
||||
import { v2Projection, v2ThreadShell } from "./orchestrationV2TestFixtures.ts";
|
||||
|
||||
const environmentId = EnvironmentId.make("environment-v2");
|
||||
@@ -16,7 +25,7 @@ describe("V2 client presentation", () => {
|
||||
expect(shell.source).toBe(v2ThreadShell);
|
||||
});
|
||||
|
||||
it("retains the complete projection while deriving conversation parity", () => {
|
||||
it("derives execution summaries without wrapping or copying the projection", () => {
|
||||
const runId = RunId.make("run-1");
|
||||
const now = DateTime.makeUnsafe("2026-06-20T01:00:00.000Z");
|
||||
const projection = {
|
||||
@@ -59,27 +68,27 @@ describe("V2 client presentation", () => {
|
||||
updatedAt: now,
|
||||
};
|
||||
|
||||
const thread = presentThread(environmentId, projection);
|
||||
expect(thread.projection).toBe(projection);
|
||||
expect(thread.latestRun?.runId).toBe(runId);
|
||||
expect(thread.runtime?.status).toBe("running");
|
||||
expect(thread.runs).toHaveLength(1);
|
||||
expect(thread.availableActions.canInterrupt).toBe(true);
|
||||
expect(thread.messages[0]).toMatchObject({
|
||||
text: "Hello",
|
||||
expect(deriveLatestThreadRun(projection)).toMatchObject({
|
||||
runId,
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
status: "running",
|
||||
requestedAt: "2026-06-20T01:00:00.000Z",
|
||||
assistantMessageId: null,
|
||||
});
|
||||
expect(deriveThreadRuntime(projection)).toMatchObject({
|
||||
status: "running",
|
||||
activeRunId: runId,
|
||||
providerInstanceId: projection.thread.providerInstanceId,
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps the complete payload for generic V2 work-item rendering", () => {
|
||||
it("joins pending request entities to their native turn-item display data", () => {
|
||||
const now = DateTime.makeUnsafe("2026-06-20T01:00:00.000Z");
|
||||
const requestId = RuntimeRequestId.make("request-approval");
|
||||
const item = {
|
||||
id: TurnItemId.make("item-dynamic"),
|
||||
id: TurnItemId.make("item-approval"),
|
||||
threadId: v2Projection.thread.id,
|
||||
runId: null,
|
||||
nodeId: null,
|
||||
nodeId: NodeId.make("node-root"),
|
||||
providerThreadId: null,
|
||||
providerTurnId: null,
|
||||
nativeItemRef: null,
|
||||
@@ -90,31 +99,42 @@ describe("V2 client presentation", () => {
|
||||
startedAt: now,
|
||||
completedAt: now,
|
||||
updatedAt: now,
|
||||
type: "dynamic_tool" as const,
|
||||
toolName: "custom_tool",
|
||||
input: { nested: { value: 1 } },
|
||||
output: { ok: true },
|
||||
type: "approval_request" as const,
|
||||
requestId,
|
||||
requestKind: "command" as const,
|
||||
prompt: "Allow command?",
|
||||
};
|
||||
const projection = {
|
||||
...v2Projection,
|
||||
turnItems: [item],
|
||||
visibleTurnItems: [
|
||||
runtimeRequests: [
|
||||
{
|
||||
position: 0,
|
||||
visibility: "local" as const,
|
||||
sourceThreadId: v2Projection.thread.id,
|
||||
sourceItemId: item.id,
|
||||
item,
|
||||
id: requestId,
|
||||
nodeId: NodeId.make("node-root"),
|
||||
providerTurnId: null,
|
||||
nativeRequestRef: null,
|
||||
kind: "command" as const,
|
||||
status: "pending" as const,
|
||||
responseCapability: {
|
||||
type: "not_resumable" as const,
|
||||
reason: "provider disconnected",
|
||||
},
|
||||
createdAt: now,
|
||||
resolvedAt: null,
|
||||
},
|
||||
],
|
||||
turnItems: [item],
|
||||
updatedAt: now,
|
||||
};
|
||||
|
||||
const thread = presentThread(environmentId, projection);
|
||||
expect(thread.workEntries[0]).toMatchObject({
|
||||
itemType: "dynamic_tool",
|
||||
label: "custom_tool",
|
||||
structuredPayload: item,
|
||||
});
|
||||
expect(derivePendingThreadRequests(projection).approvals).toEqual([
|
||||
{
|
||||
requestId,
|
||||
requestKind: "command",
|
||||
createdAt: "2026-06-20T01:00:00.000Z",
|
||||
detail: "Allow command?",
|
||||
responseCapability: "not_resumable",
|
||||
},
|
||||
]);
|
||||
expect(derivePendingThreadRequests(projection).userInputs).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -1,27 +1,15 @@
|
||||
import type {
|
||||
ChatAttachment,
|
||||
CheckpointId,
|
||||
CheckpointRef,
|
||||
CheckpointScopeId,
|
||||
EnvironmentId,
|
||||
MessageId,
|
||||
OrchestrationProjectShell,
|
||||
OrchestrationV2PlanArtifact,
|
||||
OrchestrationV2Actor,
|
||||
OrchestrationV2CreationSource,
|
||||
OrchestrationV2ProviderCapabilities,
|
||||
OrchestrationV2RunStatus,
|
||||
OrchestrationV2ShellSnapshot,
|
||||
OrchestrationV2ThreadProjection,
|
||||
OrchestrationV2ThreadShell,
|
||||
OrchestrationV2TurnItem,
|
||||
PlanId,
|
||||
ProjectId,
|
||||
ProviderApprovalDecision,
|
||||
ProviderInstanceId,
|
||||
ProviderRequestKind,
|
||||
RunId,
|
||||
RuntimeRequestId,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
@@ -33,11 +21,11 @@ export interface EnvironmentProject extends OrchestrationProjectShell {
|
||||
/**
|
||||
* A pristine V2 thread projection paired with the environment that produced it.
|
||||
*
|
||||
* Keep the projection nested so its identity and every structurally shared
|
||||
* collection remain intact. This is the scoped detail boundary for rich V2
|
||||
* consumers; it is intentionally not another presentation-shaped thread.
|
||||
* The projection stays nested so the server projection and all structurally
|
||||
* shared collections retain their identities. Rich consumers read V2 state
|
||||
* directly instead of a second presentation-shaped thread graph.
|
||||
*/
|
||||
export interface ScopedThreadProjection {
|
||||
export interface EnvironmentThread {
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly projection: OrchestrationV2ThreadProjection;
|
||||
}
|
||||
@@ -78,112 +66,6 @@ export function threadRunStatusIsActive(status: ThreadRuntimeSummary["status"]):
|
||||
);
|
||||
}
|
||||
|
||||
export interface ThreadConversationMessage {
|
||||
readonly id: MessageId;
|
||||
readonly role: "user" | "assistant" | "system";
|
||||
readonly text: string;
|
||||
readonly attachments?: ReadonlyArray<ChatAttachment>;
|
||||
readonly runId: RunId | null;
|
||||
readonly streaming: boolean;
|
||||
readonly createdBy?: OrchestrationV2Actor;
|
||||
readonly creationSource?: OrchestrationV2CreationSource;
|
||||
readonly createdAt: string;
|
||||
readonly updatedAt: string;
|
||||
}
|
||||
|
||||
export interface ThreadProposedPlan {
|
||||
readonly id: PlanId;
|
||||
readonly runId: RunId | null;
|
||||
readonly planMarkdown: string;
|
||||
readonly status: OrchestrationV2PlanArtifact["status"];
|
||||
readonly implementedAt: string | null;
|
||||
readonly implementationThreadId: ThreadId | null;
|
||||
readonly createdAt: string;
|
||||
readonly updatedAt: string;
|
||||
}
|
||||
|
||||
export interface ThreadTodoPlan {
|
||||
readonly id: PlanId;
|
||||
readonly runId: RunId | null;
|
||||
readonly status: OrchestrationV2PlanArtifact["status"];
|
||||
readonly explanation: string | null;
|
||||
readonly steps: ReadonlyArray<{
|
||||
readonly id: string;
|
||||
readonly step: string;
|
||||
readonly status: "pending" | "inProgress" | "completed";
|
||||
}>;
|
||||
readonly updatedAt: string;
|
||||
}
|
||||
|
||||
export interface ThreadCheckpointSummary {
|
||||
readonly checkpointId?: CheckpointId;
|
||||
readonly scopeId?: CheckpointScopeId;
|
||||
readonly runId: RunId;
|
||||
readonly checkpointTurnCount: number;
|
||||
readonly checkpointRef: CheckpointRef;
|
||||
readonly status: "ready" | "missing" | "error" | "stale";
|
||||
readonly files: ReadonlyArray<{
|
||||
readonly path: string;
|
||||
readonly kind: string;
|
||||
readonly additions: number;
|
||||
readonly deletions: number;
|
||||
}>;
|
||||
readonly assistantMessageId: MessageId | null;
|
||||
readonly completedAt: string;
|
||||
}
|
||||
|
||||
export interface ThreadPendingApproval {
|
||||
readonly requestId: RuntimeRequestId;
|
||||
readonly requestKind: ProviderRequestKind;
|
||||
readonly createdAt: string;
|
||||
readonly detail?: string;
|
||||
readonly responseCapability: "live" | "not_resumable";
|
||||
}
|
||||
|
||||
export interface ThreadUserInputQuestion {
|
||||
readonly id: string;
|
||||
readonly header: string;
|
||||
readonly question: string;
|
||||
readonly options: ReadonlyArray<{
|
||||
readonly label: string;
|
||||
readonly description: string;
|
||||
}>;
|
||||
readonly multiSelect: boolean;
|
||||
}
|
||||
|
||||
export interface ThreadPendingUserInput {
|
||||
readonly requestId: RuntimeRequestId;
|
||||
readonly createdAt: string;
|
||||
readonly questions: ReadonlyArray<ThreadUserInputQuestion>;
|
||||
readonly responseCapability: "live" | "not_resumable";
|
||||
}
|
||||
|
||||
export type ThreadWorkEntryTone = "thinking" | "tool" | "info" | "error";
|
||||
export type ThreadWorkEntryStatus = "inProgress" | "completed" | "failed" | "declined" | "stopped";
|
||||
|
||||
/**
|
||||
* Stable parity presentation for a V2 turn item. `structuredPayload` always
|
||||
* retains the complete source item so generic rendering never loses provider
|
||||
* or tool data.
|
||||
*/
|
||||
export interface ThreadWorkEntry {
|
||||
readonly id: string;
|
||||
readonly createdAt: string;
|
||||
readonly runId: RunId | null;
|
||||
readonly label: string;
|
||||
readonly detail?: string;
|
||||
readonly command?: string;
|
||||
readonly rawCommand?: string;
|
||||
readonly changedFiles?: ReadonlyArray<string>;
|
||||
readonly tone: ThreadWorkEntryTone;
|
||||
readonly toolTitle?: string;
|
||||
readonly toolData?: unknown;
|
||||
readonly itemType: OrchestrationV2TurnItem["type"];
|
||||
readonly requestKind?: ProviderRequestKind;
|
||||
readonly toolLifecycleStatus: ThreadWorkEntryStatus;
|
||||
readonly structuredPayload: OrchestrationV2TurnItem;
|
||||
}
|
||||
|
||||
export interface EnvironmentThreadShell {
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly id: ThreadId;
|
||||
@@ -213,30 +95,6 @@ export interface EnvironmentThreadShell {
|
||||
readonly source: OrchestrationV2ThreadShell;
|
||||
}
|
||||
|
||||
export interface EnvironmentThread extends EnvironmentThreadShell {
|
||||
readonly projection: OrchestrationV2ThreadProjection;
|
||||
readonly runs: ReadonlyArray<ThreadRunSummary>;
|
||||
readonly capabilities: OrchestrationV2ProviderCapabilities | null;
|
||||
readonly availableActions: {
|
||||
readonly canSendMessage: boolean;
|
||||
readonly canInterrupt: boolean;
|
||||
readonly canRespondToApproval: boolean;
|
||||
readonly canRespondToUserInput: boolean;
|
||||
readonly canRollback: boolean;
|
||||
readonly canArchive: boolean;
|
||||
readonly canUnarchive: boolean;
|
||||
readonly canDelete: boolean;
|
||||
readonly canUpdateSettings: boolean;
|
||||
};
|
||||
readonly messages: ReadonlyArray<ThreadConversationMessage>;
|
||||
readonly workEntries: ReadonlyArray<ThreadWorkEntry>;
|
||||
readonly proposedPlans: ReadonlyArray<ThreadProposedPlan>;
|
||||
readonly todoPlans: ReadonlyArray<ThreadTodoPlan>;
|
||||
readonly pendingApprovals: ReadonlyArray<ThreadPendingApproval>;
|
||||
readonly pendingUserInputs: ReadonlyArray<ThreadPendingUserInput>;
|
||||
readonly checkpoints: ReadonlyArray<ThreadCheckpointSummary>;
|
||||
}
|
||||
|
||||
function iso(value: DateTime.Utc): string {
|
||||
return DateTime.formatIso(value);
|
||||
}
|
||||
@@ -255,224 +113,15 @@ function terminalRunStatus(status: OrchestrationV2RunStatus): boolean {
|
||||
);
|
||||
}
|
||||
|
||||
function workEntryStatus(item: OrchestrationV2TurnItem): ThreadWorkEntryStatus {
|
||||
switch (item.status) {
|
||||
case "pending":
|
||||
case "running":
|
||||
case "waiting":
|
||||
return "inProgress";
|
||||
case "completed":
|
||||
return "completed";
|
||||
case "failed":
|
||||
return "failed";
|
||||
case "cancelled":
|
||||
case "interrupted":
|
||||
return "stopped";
|
||||
}
|
||||
}
|
||||
|
||||
function workEntryTone(item: OrchestrationV2TurnItem): ThreadWorkEntryTone {
|
||||
if (item.status === "failed") return "error";
|
||||
if (item.type === "reasoning") return "thinking";
|
||||
switch (item.type) {
|
||||
case "command_execution":
|
||||
case "file_change":
|
||||
case "file_search":
|
||||
case "web_search":
|
||||
case "dynamic_tool":
|
||||
case "subagent":
|
||||
return "tool";
|
||||
default:
|
||||
return "info";
|
||||
}
|
||||
}
|
||||
|
||||
function summarizeWorkItem(item: OrchestrationV2TurnItem): {
|
||||
readonly label: string;
|
||||
readonly detail?: string;
|
||||
readonly command?: string;
|
||||
readonly rawCommand?: string;
|
||||
readonly changedFiles?: ReadonlyArray<string>;
|
||||
readonly toolTitle?: string;
|
||||
readonly toolData?: unknown;
|
||||
readonly requestKind?: ProviderRequestKind;
|
||||
} {
|
||||
const title = item.title?.trim() || null;
|
||||
switch (item.type) {
|
||||
case "reasoning":
|
||||
return { label: title ?? "Thinking", ...(item.text ? { detail: item.text } : {}) };
|
||||
case "command_execution":
|
||||
return {
|
||||
label: title ?? "Ran command",
|
||||
command: item.input,
|
||||
rawCommand: item.input,
|
||||
...(item.output ? { detail: item.output } : {}),
|
||||
toolTitle: title ?? "Command",
|
||||
toolData: item,
|
||||
};
|
||||
case "file_change":
|
||||
return {
|
||||
label: title ?? `Changed ${item.fileName}`,
|
||||
changedFiles: [item.fileName],
|
||||
...(item.diffStr ? { detail: item.diffStr } : {}),
|
||||
toolTitle: title ?? "File change",
|
||||
toolData: item,
|
||||
};
|
||||
case "file_search":
|
||||
return {
|
||||
label: title ?? "Searched files",
|
||||
...(item.pattern ? { detail: item.pattern } : {}),
|
||||
toolTitle: title ?? "File search",
|
||||
toolData: item,
|
||||
};
|
||||
case "web_search":
|
||||
return {
|
||||
label: title ?? "Searched the web",
|
||||
...(item.patterns?.length ? { detail: item.patterns.join(", ") } : {}),
|
||||
toolTitle: title ?? "Web search",
|
||||
toolData: item,
|
||||
};
|
||||
case "approval_request":
|
||||
return {
|
||||
label: title ?? "Approval requested",
|
||||
...(item.prompt ? { detail: item.prompt } : {}),
|
||||
requestKind: item.requestKind,
|
||||
toolData: item,
|
||||
};
|
||||
case "user_input_request":
|
||||
return {
|
||||
label: title ?? "Input requested",
|
||||
detail: item.questions.map((question) => question.question).join("\n"),
|
||||
toolData: item,
|
||||
};
|
||||
case "checkpoint":
|
||||
return {
|
||||
label: title ?? "Checkpoint captured",
|
||||
changedFiles: item.files.map((file) => file.path),
|
||||
toolData: item,
|
||||
};
|
||||
case "run_interrupt_request":
|
||||
return { label: title ?? "Interrupt requested", detail: item.message, toolData: item };
|
||||
case "run_interrupt_result":
|
||||
return { label: title ?? "Run interrupted", detail: item.message, toolData: item };
|
||||
case "error":
|
||||
return {
|
||||
label: title ?? "Provider error",
|
||||
detail: item.failure.message,
|
||||
toolData: item,
|
||||
};
|
||||
case "compaction":
|
||||
return {
|
||||
label: title ?? "Context compacted",
|
||||
...(item.summary ? { detail: item.summary } : {}),
|
||||
toolData: item,
|
||||
};
|
||||
case "handoff":
|
||||
return {
|
||||
label: title ?? "Context handed off",
|
||||
...(item.summary ? { detail: item.summary } : {}),
|
||||
toolData: item,
|
||||
};
|
||||
case "fork":
|
||||
return { label: title ?? "Thread forked", detail: item.targetThreadId, toolData: item };
|
||||
case "thread_created":
|
||||
return {
|
||||
label: title ?? "Thread created",
|
||||
detail: `${item.targetProviderInstanceId} · ${item.targetModel}`,
|
||||
toolData: item,
|
||||
};
|
||||
case "subagent":
|
||||
return {
|
||||
label: title ?? "Subagent",
|
||||
detail: item.result ?? item.progress ?? item.prompt,
|
||||
toolTitle: title ?? "Subagent",
|
||||
toolData: item,
|
||||
};
|
||||
case "dynamic_tool":
|
||||
return {
|
||||
label: title ?? item.toolName ?? "Tool call",
|
||||
toolTitle: title ?? item.toolName ?? "Tool",
|
||||
toolData: { input: item.input, output: item.output },
|
||||
};
|
||||
case "user_message":
|
||||
return { label: title ?? "User message", detail: item.text, toolData: item };
|
||||
case "assistant_message":
|
||||
return { label: title ?? "Assistant message", detail: item.text, toolData: item };
|
||||
case "proposed_plan":
|
||||
return { label: title ?? "Proposed plan", detail: item.markdown, toolData: item };
|
||||
case "todo_list":
|
||||
return {
|
||||
label: title ?? "Plan updated",
|
||||
detail: item.steps.map((step) => step.text).join("\n"),
|
||||
toolData: item,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
function presentWorkEntries(
|
||||
projection: OrchestrationV2ThreadProjection,
|
||||
): ReadonlyArray<ThreadWorkEntry> {
|
||||
return projection.visibleTurnItems
|
||||
.filter(
|
||||
({ item }) =>
|
||||
item.type !== "user_message" &&
|
||||
item.type !== "assistant_message" &&
|
||||
item.type !== "proposed_plan" &&
|
||||
item.type !== "todo_list",
|
||||
)
|
||||
.map(({ item }) => {
|
||||
const summary = summarizeWorkItem(item);
|
||||
return {
|
||||
id: item.id,
|
||||
createdAt: iso(item.startedAt ?? item.updatedAt),
|
||||
runId: item.runId,
|
||||
...summary,
|
||||
tone: workEntryTone(item),
|
||||
itemType: item.type,
|
||||
toolLifecycleStatus: workEntryStatus(item),
|
||||
structuredPayload: item,
|
||||
} satisfies ThreadWorkEntry;
|
||||
});
|
||||
}
|
||||
|
||||
function presentRuns(projection: OrchestrationV2ThreadProjection): ReadonlyArray<ThreadRunSummary> {
|
||||
return projection.runs
|
||||
.toSorted((left, right) => left.ordinal - right.ordinal)
|
||||
.map((run) => ({
|
||||
runId: run.id,
|
||||
status: run.status,
|
||||
requestedAt: iso(run.requestedAt),
|
||||
startedAt: nullableIso(run.startedAt),
|
||||
completedAt: nullableIso(run.completedAt),
|
||||
assistantMessageId:
|
||||
projection.messages.findLast(
|
||||
(message) => message.runId === run.id && message.role === "assistant",
|
||||
)?.id ?? null,
|
||||
...(run.sourcePlanRef === undefined ? {} : { sourcePlanRef: run.sourcePlanRef }),
|
||||
}));
|
||||
}
|
||||
|
||||
function presentLatestRun(projection: OrchestrationV2ThreadProjection): ThreadRunSummary | null {
|
||||
return presentRuns(projection).at(-1) ?? null;
|
||||
}
|
||||
|
||||
function presentRuntime(
|
||||
shell: OrchestrationV2ThreadShell,
|
||||
projection?: OrchestrationV2ThreadProjection,
|
||||
): ThreadRuntimeSummary | null {
|
||||
const latestRun = projection === undefined ? null : presentLatestRun(projection);
|
||||
const hasRuntime = shell.latestRunId !== null || shell.activeProviderThreadId !== null;
|
||||
if (!hasRuntime && latestRun === null) return null;
|
||||
const providerSession = projection?.providerSessions.findLast(
|
||||
(session) => session.providerInstanceId === shell.providerInstanceId,
|
||||
);
|
||||
function shellRuntime(thread: OrchestrationV2ThreadShell): ThreadRuntimeSummary | null {
|
||||
if (thread.latestRunId === null && thread.activeProviderThreadId === null) return null;
|
||||
return {
|
||||
status: latestRun?.status ?? shell.status,
|
||||
activeRunId: shell.activeRunId,
|
||||
providerInstanceId: shell.providerInstanceId,
|
||||
providerName: providerSession?.driver ?? null,
|
||||
lastError: providerSession?.lastError ?? null,
|
||||
updatedAt: iso(projection?.updatedAt ?? shell.updatedAt),
|
||||
status: thread.status,
|
||||
activeRunId: thread.activeRunId,
|
||||
providerInstanceId: thread.providerInstanceId,
|
||||
providerName: null,
|
||||
lastError: null,
|
||||
updatedAt: iso(thread.updatedAt),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -515,7 +164,7 @@ export function presentThreadShell(
|
||||
forkedFrom: thread.forkedFrom,
|
||||
activeProviderThreadId: thread.activeProviderThreadId,
|
||||
latestRun,
|
||||
runtime: presentRuntime(thread),
|
||||
runtime: shellRuntime(thread),
|
||||
latestUserMessageAt: nullableIso(thread.latestUserMessageAt),
|
||||
hasPendingApprovals:
|
||||
thread.pendingRuntimeRequest !== null &&
|
||||
@@ -535,226 +184,6 @@ export function presentThreadShell(
|
||||
|
||||
export const scopeThreadShell = presentThreadShell;
|
||||
|
||||
function presentMessages(
|
||||
projection: OrchestrationV2ThreadProjection,
|
||||
): ReadonlyArray<ThreadConversationMessage> {
|
||||
return projection.messages.map((message) => ({
|
||||
id: message.id,
|
||||
role: message.role,
|
||||
text: message.text,
|
||||
attachments: message.attachments,
|
||||
runId: message.runId,
|
||||
streaming: message.streaming,
|
||||
createdBy: message.createdBy,
|
||||
creationSource: message.creationSource,
|
||||
createdAt: iso(message.createdAt),
|
||||
updatedAt: iso(message.updatedAt),
|
||||
}));
|
||||
}
|
||||
|
||||
function planItemTime(projection: OrchestrationV2ThreadProjection, planId: PlanId): string {
|
||||
const item = projection.turnItems.findLast(
|
||||
(candidate) =>
|
||||
(candidate.type === "proposed_plan" || candidate.type === "todo_list") &&
|
||||
candidate.planId === planId,
|
||||
);
|
||||
return iso(item?.updatedAt ?? projection.updatedAt);
|
||||
}
|
||||
|
||||
function presentProposedPlans(
|
||||
projection: OrchestrationV2ThreadProjection,
|
||||
): ReadonlyArray<ThreadProposedPlan> {
|
||||
return projection.plans.flatMap((plan) => {
|
||||
if (plan.kind !== "proposed_plan") return [];
|
||||
const updatedAt = planItemTime(projection, plan.id);
|
||||
return [
|
||||
{
|
||||
id: plan.id,
|
||||
runId: plan.runId,
|
||||
planMarkdown: plan.markdown,
|
||||
status: plan.status,
|
||||
implementedAt: plan.status === "completed" ? updatedAt : null,
|
||||
implementationThreadId: null,
|
||||
createdAt: updatedAt,
|
||||
updatedAt,
|
||||
} satisfies ThreadProposedPlan,
|
||||
];
|
||||
});
|
||||
}
|
||||
|
||||
function presentTodoPlans(
|
||||
projection: OrchestrationV2ThreadProjection,
|
||||
): ReadonlyArray<ThreadTodoPlan> {
|
||||
return projection.plans.flatMap((plan) => {
|
||||
if (plan.kind !== "todo_list") return [];
|
||||
return [
|
||||
{
|
||||
id: plan.id,
|
||||
runId: plan.runId,
|
||||
status: plan.status,
|
||||
explanation: plan.explanation ?? null,
|
||||
steps: plan.steps.map((step) => ({
|
||||
id: step.id,
|
||||
step: step.text,
|
||||
status: step.status === "running" ? "inProgress" : step.status,
|
||||
})),
|
||||
updatedAt: planItemTime(projection, plan.id),
|
||||
} satisfies ThreadTodoPlan,
|
||||
];
|
||||
});
|
||||
}
|
||||
|
||||
function presentPendingRequests(projection: OrchestrationV2ThreadProjection): {
|
||||
readonly approvals: ReadonlyArray<ThreadPendingApproval>;
|
||||
readonly userInputs: ReadonlyArray<ThreadPendingUserInput>;
|
||||
} {
|
||||
const approvals: ThreadPendingApproval[] = [];
|
||||
const userInputs: ThreadPendingUserInput[] = [];
|
||||
for (const request of projection.runtimeRequests) {
|
||||
if (request.status !== "pending") continue;
|
||||
const responseCapability = request.responseCapability.type;
|
||||
if (request.kind === "user_input") {
|
||||
const item = projection.turnItems.findLast(
|
||||
(candidate) =>
|
||||
candidate.type === "user_input_request" && candidate.requestId === request.id,
|
||||
);
|
||||
if (item === undefined || item.type !== "user_input_request") continue;
|
||||
userInputs.push({
|
||||
requestId: request.id,
|
||||
createdAt: iso(request.createdAt),
|
||||
questions: item.questions.map((question) => ({ ...question, multiSelect: false })),
|
||||
responseCapability,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
if (request.kind === "auth_refresh" || request.kind === "dynamic_tool_call") continue;
|
||||
const item = projection.turnItems.findLast(
|
||||
(candidate) => candidate.type === "approval_request" && candidate.requestId === request.id,
|
||||
);
|
||||
approvals.push({
|
||||
requestId: request.id,
|
||||
requestKind: request.kind,
|
||||
createdAt: iso(request.createdAt),
|
||||
...(item?.type === "approval_request" && item.prompt ? { detail: item.prompt } : {}),
|
||||
responseCapability,
|
||||
});
|
||||
}
|
||||
return { approvals, userInputs };
|
||||
}
|
||||
|
||||
function presentCheckpoints(
|
||||
projection: OrchestrationV2ThreadProjection,
|
||||
): ReadonlyArray<ThreadCheckpointSummary> {
|
||||
return projection.checkpoints.flatMap((checkpoint) => {
|
||||
if (checkpoint.appRunOrdinal === null || checkpoint.runId === null) return [];
|
||||
const assistantMessageId =
|
||||
projection.messages.findLast(
|
||||
(message) => message.runId === checkpoint.runId && message.role === "assistant",
|
||||
)?.id ?? null;
|
||||
return [
|
||||
{
|
||||
checkpointId: checkpoint.id,
|
||||
scopeId: checkpoint.scopeId,
|
||||
runId: checkpoint.runId,
|
||||
checkpointTurnCount: checkpoint.appRunOrdinal,
|
||||
checkpointRef: checkpoint.ref,
|
||||
status: checkpoint.status,
|
||||
files: checkpoint.files,
|
||||
assistantMessageId,
|
||||
completedAt: iso(checkpoint.capturedAt),
|
||||
} satisfies ThreadCheckpointSummary,
|
||||
];
|
||||
});
|
||||
}
|
||||
|
||||
export function presentThread(
|
||||
environmentId: EnvironmentId,
|
||||
projection: OrchestrationV2ThreadProjection,
|
||||
): EnvironmentThread {
|
||||
const shell = presentThreadShell(environmentId, {
|
||||
...projection.thread,
|
||||
latestRunId:
|
||||
projection.runs.reduce<(typeof projection.runs)[number] | null>(
|
||||
(latest, candidate) =>
|
||||
latest === null || candidate.ordinal > latest.ordinal ? candidate : latest,
|
||||
null,
|
||||
)?.id ?? null,
|
||||
activeRunId:
|
||||
projection.runs.findLast(
|
||||
(run) =>
|
||||
run.status === "preparing" ||
|
||||
run.status === "starting" ||
|
||||
run.status === "running" ||
|
||||
run.status === "waiting",
|
||||
)?.id ?? null,
|
||||
status: presentLatestRun(projection)?.status ?? "idle",
|
||||
pendingRuntimeRequest:
|
||||
projection.runtimeRequests.findLast((request) => request.status === "pending") ?? null,
|
||||
latestVisibleMessage:
|
||||
projection.messages.length === 0
|
||||
? null
|
||||
: (() => {
|
||||
const message = projection.messages.at(-1)!;
|
||||
return {
|
||||
id: message.id,
|
||||
role: message.role,
|
||||
text: message.text,
|
||||
updatedAt: message.updatedAt,
|
||||
};
|
||||
})(),
|
||||
latestUserMessageAt:
|
||||
projection.messages.findLast((message) => message.role === "user")?.updatedAt ?? null,
|
||||
hasActionableProposedPlan: projection.plans.some(
|
||||
(plan) => plan.kind === "proposed_plan" && plan.status === "active",
|
||||
),
|
||||
itemCount: projection.turnItems.length,
|
||||
visibleItemCount: projection.visibleTurnItems.length,
|
||||
});
|
||||
const requests = presentPendingRequests(projection);
|
||||
const proposedPlans = presentProposedPlans(projection);
|
||||
const checkpoints = presentCheckpoints(projection);
|
||||
const runs = presentRuns(projection);
|
||||
const capabilities =
|
||||
projection.providerSessions.findLast(
|
||||
(session) => session.providerInstanceId === projection.thread.providerInstanceId,
|
||||
)?.capabilities ?? null;
|
||||
const active = runs.some((run) => threadRunStatusIsActive(run.status));
|
||||
const mutable = projection.thread.archivedAt === null && projection.thread.deletedAt === null;
|
||||
return {
|
||||
...shell,
|
||||
latestRun: presentLatestRun(projection),
|
||||
runtime: presentRuntime(shell.source, projection),
|
||||
hasPendingApprovals: requests.approvals.length > 0,
|
||||
hasPendingUserInput: requests.userInputs.length > 0,
|
||||
hasActionableProposedPlan: proposedPlans.some((plan) => plan.status === "active"),
|
||||
projection,
|
||||
runs,
|
||||
capabilities,
|
||||
availableActions: {
|
||||
canSendMessage: mutable,
|
||||
canInterrupt: mutable && active && (capabilities?.turns.supportsInterrupt ?? true),
|
||||
canRespondToApproval: requests.approvals.some(
|
||||
(request) => request.responseCapability === "live",
|
||||
),
|
||||
canRespondToUserInput: requests.userInputs.some(
|
||||
(request) => request.responseCapability === "live",
|
||||
),
|
||||
canRollback: mutable && checkpoints.some((checkpoint) => checkpoint.status === "ready"),
|
||||
canArchive: projection.thread.archivedAt === null && projection.thread.deletedAt === null,
|
||||
canUnarchive: projection.thread.archivedAt !== null && projection.thread.deletedAt === null,
|
||||
canDelete: projection.thread.deletedAt === null,
|
||||
canUpdateSettings: mutable,
|
||||
},
|
||||
messages: presentMessages(projection),
|
||||
workEntries: presentWorkEntries(projection),
|
||||
proposedPlans,
|
||||
todoPlans: presentTodoPlans(projection),
|
||||
pendingApprovals: requests.approvals,
|
||||
pendingUserInputs: requests.userInputs,
|
||||
checkpoints,
|
||||
};
|
||||
}
|
||||
|
||||
export function selectEnvironmentThreadShell(
|
||||
snapshot: OrchestrationV2ShellSnapshot | null,
|
||||
environmentId: EnvironmentId,
|
||||
@@ -763,7 +192,3 @@ export function selectEnvironmentThreadShell(
|
||||
const thread = snapshot?.threads.find((candidate) => candidate.id === threadId) ?? null;
|
||||
return thread ? presentThreadShell(environmentId, thread) : null;
|
||||
}
|
||||
|
||||
export function providerApprovalDecisionIsFinal(_decision: ProviderApprovalDecision): boolean {
|
||||
return true;
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import type {
|
||||
CheckpointId,
|
||||
CheckpointRef,
|
||||
CheckpointScopeId,
|
||||
MessageId,
|
||||
OrchestrationV2ThreadProjection,
|
||||
RunId,
|
||||
} from "@t3tools/contracts";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
|
||||
export interface ThreadCheckpointSummary {
|
||||
readonly checkpointId?: CheckpointId;
|
||||
readonly scopeId?: CheckpointScopeId;
|
||||
readonly runId: RunId;
|
||||
readonly checkpointTurnCount: number;
|
||||
readonly checkpointRef: CheckpointRef;
|
||||
readonly status: "ready" | "missing" | "error" | "stale";
|
||||
readonly files: ReadonlyArray<{
|
||||
readonly path: string;
|
||||
readonly kind: string;
|
||||
readonly additions: number;
|
||||
readonly deletions: number;
|
||||
}>;
|
||||
readonly assistantMessageId: MessageId | null;
|
||||
readonly completedAt: string;
|
||||
}
|
||||
|
||||
/** Derives the checkpoint/diff rows needed by review UIs from native V2 entities. */
|
||||
export function deriveThreadCheckpointSummaries(
|
||||
projection: OrchestrationV2ThreadProjection,
|
||||
): ReadonlyArray<ThreadCheckpointSummary> {
|
||||
return projection.checkpoints.flatMap((checkpoint) => {
|
||||
if (checkpoint.appRunOrdinal === null || checkpoint.runId === null) return [];
|
||||
const assistantMessageId =
|
||||
projection.messages.findLast(
|
||||
(message) => message.runId === checkpoint.runId && message.role === "assistant",
|
||||
)?.id ?? null;
|
||||
return [
|
||||
{
|
||||
checkpointId: checkpoint.id,
|
||||
scopeId: checkpoint.scopeId,
|
||||
runId: checkpoint.runId,
|
||||
checkpointTurnCount: checkpoint.appRunOrdinal,
|
||||
checkpointRef: checkpoint.ref,
|
||||
status: checkpoint.status,
|
||||
files: checkpoint.files,
|
||||
assistantMessageId,
|
||||
completedAt: DateTime.formatIso(checkpoint.capturedAt),
|
||||
},
|
||||
];
|
||||
});
|
||||
}
|
||||
@@ -40,6 +40,34 @@ describe("createEnvironmentThreadDetailAtoms", () => {
|
||||
|
||||
expect(registry.get(details.threadAtom(ref))).toBe(thread);
|
||||
expect(registry.get(details.statusAtom(ref))).toBe("synchronizing");
|
||||
|
||||
registry.set(
|
||||
sourceAtom,
|
||||
AsyncResult.success({
|
||||
data: Option.some(v2Projection),
|
||||
status: "live",
|
||||
error: Option.some("Stream interrupted."),
|
||||
}),
|
||||
);
|
||||
|
||||
expect(registry.get(details.threadAtom(ref))).toBe(thread);
|
||||
expect(registry.get(details.visibleTurnItemsAtom(ref))).toBe(v2Projection.visibleTurnItems);
|
||||
expect(registry.get(details.statusAtom(ref))).toBe("live");
|
||||
expect(registry.get(details.errorAtom(ref))).toBe("Stream interrupted.");
|
||||
|
||||
registry.set(
|
||||
sourceAtom,
|
||||
AsyncResult.success({
|
||||
data: Option.none(),
|
||||
status: "deleted",
|
||||
error: Option.none(),
|
||||
}),
|
||||
);
|
||||
|
||||
expect(registry.get(details.threadAtom(ref))).toBeNull();
|
||||
expect(registry.get(details.visibleTurnItemsAtom(ref))).toEqual([]);
|
||||
expect(registry.get(details.statusAtom(ref))).toBe("deleted");
|
||||
expect(registry.get(details.errorAtom(ref))).toBeNull();
|
||||
registry.dispose();
|
||||
});
|
||||
});
|
||||
@@ -2,50 +2,15 @@ import type { OrchestrationV2ThreadProjection, ScopedThreadRef } from "@t3tools/
|
||||
import * as Option from "effect/Option";
|
||||
import { AsyncResult, Atom } from "effect/unstable/reactivity";
|
||||
|
||||
import type {
|
||||
EnvironmentThread,
|
||||
EnvironmentThreadShell,
|
||||
ThreadCheckpointSummary,
|
||||
ThreadConversationMessage,
|
||||
ThreadPendingApproval,
|
||||
ThreadPendingUserInput,
|
||||
ThreadProposedPlan,
|
||||
ThreadRunSummary,
|
||||
ThreadRuntimeSummary,
|
||||
ScopedThreadProjection,
|
||||
ThreadWorkEntry,
|
||||
} from "./models.ts";
|
||||
import { presentThread } from "./models.ts";
|
||||
import type { EnvironmentThread } from "./models.ts";
|
||||
import { EMPTY_ENVIRONMENT_THREAD_STATE, type EnvironmentThreadState } from "./threads.ts";
|
||||
import { parseThreadKey, threadKey } from "./entities.ts";
|
||||
import { THREAD_STATE_IDLE_TTL_MS } from "./threadRetention.ts";
|
||||
|
||||
const EMPTY_MESSAGES: ReadonlyArray<ThreadConversationMessage> = Object.freeze([]);
|
||||
const EMPTY_WORK_ENTRIES: ReadonlyArray<ThreadWorkEntry> = Object.freeze([]);
|
||||
const EMPTY_PROPOSED_PLANS: ReadonlyArray<ThreadProposedPlan> = Object.freeze([]);
|
||||
const EMPTY_CHECKPOINTS: ReadonlyArray<ThreadCheckpointSummary> = Object.freeze([]);
|
||||
const EMPTY_APPROVALS: ReadonlyArray<ThreadPendingApproval> = Object.freeze([]);
|
||||
const EMPTY_USER_INPUTS: ReadonlyArray<ThreadPendingUserInput> = Object.freeze([]);
|
||||
const EMPTY_VISIBLE_TURN_ITEMS: OrchestrationV2ThreadProjection["visibleTurnItems"] = Object.freeze(
|
||||
[],
|
||||
);
|
||||
|
||||
/** Shell metadata wins over an independently cached detail projection. */
|
||||
export function mergeEnvironmentThread(
|
||||
detail: EnvironmentThread | null,
|
||||
shell: EnvironmentThreadShell | null,
|
||||
): EnvironmentThread | null {
|
||||
if (detail === null || shell === null) return detail;
|
||||
if (detail.environmentId !== shell.environmentId || detail.id !== shell.id) return detail;
|
||||
return {
|
||||
...detail,
|
||||
...shell,
|
||||
latestRun: detail.latestRun,
|
||||
runtime: detail.runtime,
|
||||
source: shell.source,
|
||||
};
|
||||
}
|
||||
|
||||
export function createEnvironmentThreadDetailAtoms<E>(
|
||||
threadStateAtom: (
|
||||
environmentId: ScopedThreadRef["environmentId"],
|
||||
@@ -65,36 +30,17 @@ export function createEnvironmentThreadDetailAtoms<E>(
|
||||
);
|
||||
});
|
||||
|
||||
const threadDetailAtomFamily = Atom.family((key: string) => {
|
||||
const ref = parseThreadKey(key);
|
||||
let previousSource: OrchestrationV2ThreadProjection | null = null;
|
||||
let previousValue: EnvironmentThread | null = null;
|
||||
return Atom.make((get) => {
|
||||
const source = Option.getOrNull(get(threadStateValueAtomFamily(key)).data);
|
||||
if (source === previousSource) return previousValue;
|
||||
previousSource = source;
|
||||
previousValue = source === null ? null : presentThread(ref.environmentId, source);
|
||||
return previousValue;
|
||||
}).pipe(
|
||||
Atom.setIdleTTL(THREAD_STATE_IDLE_TTL_MS),
|
||||
Atom.withLabel(`environment-thread-detail:${key}`),
|
||||
);
|
||||
});
|
||||
|
||||
const scopedThreadProjectionAtomFamily = Atom.family((key: string) => {
|
||||
const threadAtomFamily = Atom.family((key: string) => {
|
||||
const ref = parseThreadKey(key);
|
||||
let previousProjection: OrchestrationV2ThreadProjection | null = null;
|
||||
let previousValue: ScopedThreadProjection | null = null;
|
||||
let previousValue: EnvironmentThread | null = null;
|
||||
return Atom.make((get) => {
|
||||
const projection = Option.getOrNull(get(threadStateValueAtomFamily(key)).data);
|
||||
if (projection === previousProjection) return previousValue;
|
||||
previousProjection = projection;
|
||||
previousValue = projection === null ? null : { environmentId: ref.environmentId, projection };
|
||||
return previousValue;
|
||||
}).pipe(
|
||||
Atom.setIdleTTL(THREAD_STATE_IDLE_TTL_MS),
|
||||
Atom.withLabel(`scoped-thread-projection:${key}`),
|
||||
);
|
||||
}).pipe(Atom.setIdleTTL(THREAD_STATE_IDLE_TTL_MS), Atom.withLabel(`environment-thread:${key}`));
|
||||
});
|
||||
|
||||
const visibleTurnItemsAtomFamily = Atom.family((key: string) =>
|
||||
@@ -108,49 +54,13 @@ export function createEnvironmentThreadDetailAtoms<E>(
|
||||
),
|
||||
);
|
||||
|
||||
const family = <A>(label: string, select: (thread: EnvironmentThread) => A, empty: A) =>
|
||||
Atom.family((key: string) =>
|
||||
Atom.make((get): A => {
|
||||
const thread = get(threadDetailAtomFamily(key));
|
||||
return thread === null ? empty : select(thread);
|
||||
}).pipe(
|
||||
Atom.setIdleTTL(THREAD_STATE_IDLE_TTL_MS),
|
||||
Atom.withLabel(`environment-thread-${label}:${key}`),
|
||||
),
|
||||
);
|
||||
|
||||
const messages = family("messages", (thread) => thread.messages, EMPTY_MESSAGES);
|
||||
const workEntries = family("work-entries", (thread) => thread.workEntries, EMPTY_WORK_ENTRIES);
|
||||
const proposedPlans = family(
|
||||
"proposed-plans",
|
||||
(thread) => thread.proposedPlans,
|
||||
EMPTY_PROPOSED_PLANS,
|
||||
);
|
||||
const checkpoints = family("checkpoints", (thread) => thread.checkpoints, EMPTY_CHECKPOINTS);
|
||||
const pendingApprovals = family(
|
||||
"pending-approvals",
|
||||
(thread) => thread.pendingApprovals,
|
||||
EMPTY_APPROVALS,
|
||||
);
|
||||
const pendingUserInputs = family(
|
||||
"pending-user-inputs",
|
||||
(thread) => thread.pendingUserInputs,
|
||||
EMPTY_USER_INPUTS,
|
||||
);
|
||||
const runtime = family<ThreadRuntimeSummary | null>("runtime", (thread) => thread.runtime, null);
|
||||
const latestRun = family<ThreadRunSummary | null>(
|
||||
"latest-run",
|
||||
(thread) => thread.latestRun,
|
||||
null,
|
||||
);
|
||||
|
||||
const status = Atom.family((key: string) =>
|
||||
const statusAtomFamily = Atom.family((key: string) =>
|
||||
Atom.make((get) => get(threadStateValueAtomFamily(key)).status).pipe(
|
||||
Atom.setIdleTTL(THREAD_STATE_IDLE_TTL_MS),
|
||||
Atom.withLabel(`environment-thread-status:${key}`),
|
||||
),
|
||||
);
|
||||
const error = Atom.family((key: string) =>
|
||||
const errorAtomFamily = Atom.family((key: string) =>
|
||||
Atom.make((get) => Option.getOrNull(get(threadStateValueAtomFamily(key)).error)).pipe(
|
||||
Atom.setIdleTTL(THREAD_STATE_IDLE_TTL_MS),
|
||||
Atom.withLabel(`environment-thread-error:${key}`),
|
||||
@@ -159,18 +69,9 @@ export function createEnvironmentThreadDetailAtoms<E>(
|
||||
|
||||
return {
|
||||
stateAtom: (ref: ScopedThreadRef) => threadStateValueAtomFamily(threadKey(ref)),
|
||||
threadAtom: (ref: ScopedThreadRef) => scopedThreadProjectionAtomFamily(threadKey(ref)),
|
||||
threadAtom: (ref: ScopedThreadRef) => threadAtomFamily(threadKey(ref)),
|
||||
visibleTurnItemsAtom: (ref: ScopedThreadRef) => visibleTurnItemsAtomFamily(threadKey(ref)),
|
||||
detailAtom: (ref: ScopedThreadRef) => threadDetailAtomFamily(threadKey(ref)),
|
||||
statusAtom: (ref: ScopedThreadRef) => status(threadKey(ref)),
|
||||
errorAtom: (ref: ScopedThreadRef) => error(threadKey(ref)),
|
||||
messagesAtom: (ref: ScopedThreadRef) => messages(threadKey(ref)),
|
||||
workEntriesAtom: (ref: ScopedThreadRef) => workEntries(threadKey(ref)),
|
||||
proposedPlansAtom: (ref: ScopedThreadRef) => proposedPlans(threadKey(ref)),
|
||||
checkpointsAtom: (ref: ScopedThreadRef) => checkpoints(threadKey(ref)),
|
||||
pendingApprovalsAtom: (ref: ScopedThreadRef) => pendingApprovals(threadKey(ref)),
|
||||
pendingUserInputsAtom: (ref: ScopedThreadRef) => pendingUserInputs(threadKey(ref)),
|
||||
runtimeAtom: (ref: ScopedThreadRef) => runtime(threadKey(ref)),
|
||||
latestRunAtom: (ref: ScopedThreadRef) => latestRun(threadKey(ref)),
|
||||
statusAtom: (ref: ScopedThreadRef) => statusAtomFamily(threadKey(ref)),
|
||||
errorAtom: (ref: ScopedThreadRef) => errorAtomFamily(threadKey(ref)),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import type { OrchestrationV2ThreadProjection } from "@t3tools/contracts";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
|
||||
import type { ThreadRunSummary, ThreadRuntimeSummary } from "./models.ts";
|
||||
|
||||
const ACTIVE_RUN_STATUSES = new Set(["preparing", "queued", "starting", "running", "waiting"]);
|
||||
|
||||
export function deriveLatestThreadRun(
|
||||
projection: OrchestrationV2ThreadProjection,
|
||||
): ThreadRunSummary | null {
|
||||
const run = projection.runs.reduce<(typeof projection.runs)[number] | null>(
|
||||
(latest, candidate) =>
|
||||
latest === null || candidate.ordinal > latest.ordinal ? candidate : latest,
|
||||
null,
|
||||
);
|
||||
if (run === null) return null;
|
||||
return {
|
||||
runId: run.id,
|
||||
status: run.status,
|
||||
requestedAt: DateTime.formatIso(run.requestedAt),
|
||||
startedAt: run.startedAt === null ? null : DateTime.formatIso(run.startedAt),
|
||||
completedAt: run.completedAt === null ? null : DateTime.formatIso(run.completedAt),
|
||||
assistantMessageId:
|
||||
projection.messages.findLast(
|
||||
(message) => message.runId === run.id && message.role === "assistant",
|
||||
)?.id ?? null,
|
||||
...(run.sourcePlanRef === undefined ? {} : { sourcePlanRef: run.sourcePlanRef }),
|
||||
};
|
||||
}
|
||||
|
||||
export function deriveThreadRuntime(
|
||||
projection: OrchestrationV2ThreadProjection,
|
||||
): ThreadRuntimeSummary | null {
|
||||
const latestRun = deriveLatestThreadRun(projection);
|
||||
const providerSession = projection.providerSessions.findLast(
|
||||
(session) => session.providerInstanceId === projection.thread.providerInstanceId,
|
||||
);
|
||||
if (latestRun === null && projection.thread.activeProviderThreadId === null) return null;
|
||||
const activeRunId =
|
||||
projection.runs.findLast((run) => ACTIVE_RUN_STATUSES.has(run.status))?.id ?? null;
|
||||
return {
|
||||
status: latestRun?.status ?? "idle",
|
||||
activeRunId,
|
||||
providerInstanceId: projection.thread.providerInstanceId,
|
||||
providerName: providerSession?.driver ?? null,
|
||||
lastError: providerSession?.lastError ?? null,
|
||||
updatedAt: DateTime.formatIso(projection.updatedAt),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
import type {
|
||||
OrchestrationV2ThreadProjection,
|
||||
ProviderRequestKind,
|
||||
RuntimeRequestId,
|
||||
} from "@t3tools/contracts";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
|
||||
export interface ThreadPendingApproval {
|
||||
readonly requestId: RuntimeRequestId;
|
||||
readonly requestKind: ProviderRequestKind;
|
||||
readonly createdAt: string;
|
||||
readonly detail?: string;
|
||||
readonly responseCapability: "live" | "not_resumable";
|
||||
}
|
||||
|
||||
export interface ThreadUserInputQuestion {
|
||||
readonly id: string;
|
||||
readonly header: string;
|
||||
readonly question: string;
|
||||
readonly options: ReadonlyArray<{
|
||||
readonly label: string;
|
||||
readonly description: string;
|
||||
}>;
|
||||
readonly multiSelect: boolean;
|
||||
}
|
||||
|
||||
export interface ThreadPendingUserInput {
|
||||
readonly requestId: RuntimeRequestId;
|
||||
readonly createdAt: string;
|
||||
readonly questions: ReadonlyArray<ThreadUserInputQuestion>;
|
||||
readonly responseCapability: "live" | "not_resumable";
|
||||
}
|
||||
|
||||
export interface PendingThreadRequests {
|
||||
readonly approvals: ReadonlyArray<ThreadPendingApproval>;
|
||||
readonly userInputs: ReadonlyArray<ThreadPendingUserInput>;
|
||||
}
|
||||
|
||||
/** Joins pending request entities to the request items that carry display data. */
|
||||
export function derivePendingThreadRequests(
|
||||
projection: OrchestrationV2ThreadProjection,
|
||||
): PendingThreadRequests {
|
||||
const approvals: ThreadPendingApproval[] = [];
|
||||
const userInputs: ThreadPendingUserInput[] = [];
|
||||
|
||||
for (const request of projection.runtimeRequests) {
|
||||
if (request.status !== "pending") continue;
|
||||
const responseCapability = request.responseCapability.type;
|
||||
if (request.kind === "user_input") {
|
||||
const item = projection.turnItems.findLast(
|
||||
(candidate) =>
|
||||
candidate.type === "user_input_request" && candidate.requestId === request.id,
|
||||
);
|
||||
if (item === undefined || item.type !== "user_input_request") continue;
|
||||
userInputs.push({
|
||||
requestId: request.id,
|
||||
createdAt: DateTime.formatIso(request.createdAt),
|
||||
questions: item.questions.map((question) => ({ ...question, multiSelect: false })),
|
||||
responseCapability,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
if (request.kind === "auth_refresh" || request.kind === "dynamic_tool_call") continue;
|
||||
const item = projection.turnItems.findLast(
|
||||
(candidate) => candidate.type === "approval_request" && candidate.requestId === request.id,
|
||||
);
|
||||
approvals.push({
|
||||
requestId: request.id,
|
||||
requestKind: request.kind,
|
||||
createdAt: DateTime.formatIso(request.createdAt),
|
||||
...(item?.type === "approval_request" && item.prompt ? { detail: item.prompt } : {}),
|
||||
responseCapability,
|
||||
});
|
||||
}
|
||||
|
||||
return { approvals, userInputs };
|
||||
}
|
||||
@@ -18,6 +18,10 @@
|
||||
"./relay": {
|
||||
"types": "./src/relay.ts",
|
||||
"import": "./src/relay.ts"
|
||||
},
|
||||
"./legacy-orchestration": {
|
||||
"types": "./src/orchestration.ts",
|
||||
"import": "./src/orchestration.ts"
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import { ApplicationProjectEvent } from "./applicationEvent.ts";
|
||||
|
||||
const decodeApplicationProjectEvent = Schema.decodeUnknownEffect(ApplicationProjectEvent);
|
||||
|
||||
describe("application project events", () => {
|
||||
it.effect("decodes project events without the legacy thread event contract", () =>
|
||||
Effect.gen(function* () {
|
||||
const event = yield* decodeApplicationProjectEvent({
|
||||
sequence: 12,
|
||||
eventId: "event-project-12",
|
||||
aggregateKind: "project",
|
||||
aggregateId: "project-1",
|
||||
occurredAt: "2026-06-24T12:00:00.000Z",
|
||||
commandId: "command-project-12",
|
||||
causationEventId: null,
|
||||
correlationId: "command-project-12",
|
||||
metadata: {},
|
||||
type: "project.created",
|
||||
payload: {
|
||||
projectId: "project-1",
|
||||
title: "Project",
|
||||
workspaceRoot: "/tmp/project",
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: "2026-06-24T12:00:00.000Z",
|
||||
updatedAt: "2026-06-24T12:00:00.000Z",
|
||||
},
|
||||
});
|
||||
|
||||
expect(event.type).toBe("project.created");
|
||||
expect(event.payload.projectId).toBe("project-1");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rejects a project event carrying a thread aggregate", () =>
|
||||
Effect.gen(function* () {
|
||||
const result = yield* Effect.result(
|
||||
decodeApplicationProjectEvent({
|
||||
sequence: 12,
|
||||
eventId: "event-project-12",
|
||||
aggregateKind: "thread",
|
||||
aggregateId: "project-1",
|
||||
occurredAt: "2026-06-24T12:00:00.000Z",
|
||||
commandId: null,
|
||||
causationEventId: null,
|
||||
correlationId: null,
|
||||
metadata: {},
|
||||
type: "project.deleted",
|
||||
payload: {
|
||||
projectId: "project-1",
|
||||
deletedAt: "2026-06-24T12:00:00.000Z",
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
expect(result._tag).toBe("Failure");
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -1,12 +1,98 @@
|
||||
import type { OrchestrationEvent } from "./orchestration.ts";
|
||||
import type { OrchestrationV2StoredEvent } from "./orchestrationV2.ts";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
export type ApplicationProjectEvent = Extract<
|
||||
OrchestrationEvent,
|
||||
{
|
||||
readonly type: "project.created" | "project.meta-updated" | "project.deleted";
|
||||
}
|
||||
>;
|
||||
import {
|
||||
ApprovalRequestId,
|
||||
CommandId,
|
||||
EventId,
|
||||
IsoDateTime,
|
||||
NonNegativeInt,
|
||||
ProjectId,
|
||||
ProviderItemId,
|
||||
TrimmedNonEmptyString,
|
||||
} from "./baseSchemas.ts";
|
||||
import { RepositoryIdentity } from "./environment.ts";
|
||||
import { ModelSelection } from "./modelSelection.ts";
|
||||
import type { OrchestrationV2StoredEvent } from "./orchestrationV2.ts";
|
||||
import { ProjectScript } from "./project.ts";
|
||||
|
||||
/** Metadata retained by the shared application event source. */
|
||||
export const ApplicationEventMetadata = Schema.Struct({
|
||||
providerTurnId: Schema.optional(TrimmedNonEmptyString),
|
||||
providerItemId: Schema.optional(ProviderItemId),
|
||||
adapterKey: Schema.optional(TrimmedNonEmptyString),
|
||||
requestId: Schema.optional(ApprovalRequestId),
|
||||
ingestedAt: Schema.optional(IsoDateTime),
|
||||
});
|
||||
export type ApplicationEventMetadata = typeof ApplicationEventMetadata.Type;
|
||||
|
||||
export const ApplicationProjectCreatedPayload = Schema.Struct({
|
||||
projectId: ProjectId,
|
||||
title: TrimmedNonEmptyString,
|
||||
workspaceRoot: TrimmedNonEmptyString,
|
||||
repositoryIdentity: Schema.optional(Schema.NullOr(RepositoryIdentity)),
|
||||
defaultModelSelection: Schema.NullOr(ModelSelection),
|
||||
scripts: Schema.Array(ProjectScript),
|
||||
createdAt: IsoDateTime,
|
||||
updatedAt: IsoDateTime,
|
||||
});
|
||||
export type ApplicationProjectCreatedPayload = typeof ApplicationProjectCreatedPayload.Type;
|
||||
|
||||
export const ApplicationProjectMetaUpdatedPayload = Schema.Struct({
|
||||
projectId: ProjectId,
|
||||
title: Schema.optional(TrimmedNonEmptyString),
|
||||
workspaceRoot: Schema.optional(TrimmedNonEmptyString),
|
||||
repositoryIdentity: Schema.optional(Schema.NullOr(RepositoryIdentity)),
|
||||
defaultModelSelection: Schema.optional(Schema.NullOr(ModelSelection)),
|
||||
scripts: Schema.optional(Schema.Array(ProjectScript)),
|
||||
updatedAt: IsoDateTime,
|
||||
});
|
||||
export type ApplicationProjectMetaUpdatedPayload = typeof ApplicationProjectMetaUpdatedPayload.Type;
|
||||
|
||||
export const ApplicationProjectDeletedPayload = Schema.Struct({
|
||||
projectId: ProjectId,
|
||||
deletedAt: IsoDateTime,
|
||||
});
|
||||
export type ApplicationProjectDeletedPayload = typeof ApplicationProjectDeletedPayload.Type;
|
||||
|
||||
const ApplicationProjectEventBaseFields = {
|
||||
sequence: NonNegativeInt,
|
||||
eventId: EventId,
|
||||
aggregateKind: Schema.Literal("project"),
|
||||
aggregateId: ProjectId,
|
||||
occurredAt: IsoDateTime,
|
||||
commandId: Schema.NullOr(CommandId),
|
||||
causationEventId: Schema.NullOr(EventId),
|
||||
correlationId: Schema.NullOr(CommandId),
|
||||
metadata: ApplicationEventMetadata,
|
||||
} as const;
|
||||
|
||||
export const ApplicationProjectCreatedEvent = Schema.Struct({
|
||||
...ApplicationProjectEventBaseFields,
|
||||
type: Schema.Literal("project.created"),
|
||||
payload: ApplicationProjectCreatedPayload,
|
||||
});
|
||||
export type ApplicationProjectCreatedEvent = typeof ApplicationProjectCreatedEvent.Type;
|
||||
|
||||
export const ApplicationProjectMetaUpdatedEvent = Schema.Struct({
|
||||
...ApplicationProjectEventBaseFields,
|
||||
type: Schema.Literal("project.meta-updated"),
|
||||
payload: ApplicationProjectMetaUpdatedPayload,
|
||||
});
|
||||
export type ApplicationProjectMetaUpdatedEvent = typeof ApplicationProjectMetaUpdatedEvent.Type;
|
||||
|
||||
export const ApplicationProjectDeletedEvent = Schema.Struct({
|
||||
...ApplicationProjectEventBaseFields,
|
||||
type: Schema.Literal("project.deleted"),
|
||||
payload: ApplicationProjectDeletedPayload,
|
||||
});
|
||||
export type ApplicationProjectDeletedEvent = typeof ApplicationProjectDeletedEvent.Type;
|
||||
|
||||
export const ApplicationProjectEvent = Schema.Union([
|
||||
ApplicationProjectCreatedEvent,
|
||||
ApplicationProjectMetaUpdatedEvent,
|
||||
ApplicationProjectDeletedEvent,
|
||||
]);
|
||||
export type ApplicationProjectEvent = typeof ApplicationProjectEvent.Type;
|
||||
|
||||
/** Events exposed by the retained application event source. */
|
||||
export type ApplicationStoredEvent = ApplicationProjectEvent | OrchestrationV2StoredEvent;
|
||||
@@ -14,6 +14,7 @@ export * from "./providerRuntime.ts";
|
||||
export * from "./providerPolicy.ts";
|
||||
export * from "./modelSelection.ts";
|
||||
export * from "./chatAttachment.ts";
|
||||
export * from "./checkpointDiff.ts";
|
||||
export * from "./model.ts";
|
||||
export * from "./keybindings.ts";
|
||||
export * from "./server.ts";
|
||||
@@ -23,6 +24,7 @@ export * from "./vcs.ts";
|
||||
export * from "./sourceControl.ts";
|
||||
export * from "./pullRequest.ts";
|
||||
export * from "./orchestration.ts";
|
||||
export * from "./orchestrationProject.ts";
|
||||
export * from "./orchestrationV2.ts";
|
||||
export * from "./applicationEvent.ts";
|
||||
export * from "./orchestratorMcp.ts";
|
||||
|
||||
@@ -76,17 +76,6 @@ import {
|
||||
PreviewAutomationTypeInput,
|
||||
PreviewAutomationWaitForInput,
|
||||
} from "./previewAutomation.ts";
|
||||
import type {
|
||||
ClientOrchestrationCommand,
|
||||
OrchestrationGetFullThreadDiffInput,
|
||||
OrchestrationGetFullThreadDiffResult,
|
||||
OrchestrationGetTurnDiffInput,
|
||||
OrchestrationGetTurnDiffResult,
|
||||
OrchestrationShellSnapshot,
|
||||
OrchestrationShellStreamItem,
|
||||
OrchestrationSubscribeThreadInput,
|
||||
OrchestrationThreadStreamItem,
|
||||
} from "./orchestration.ts";
|
||||
import type {
|
||||
OrchestrationV2Command,
|
||||
OrchestrationV2DispatchCommandResult,
|
||||
@@ -1278,29 +1267,6 @@ export interface EnvironmentApi {
|
||||
input: ReviewDiffFileContentsInput,
|
||||
) => Promise<ReviewDiffFileContentsResult>;
|
||||
};
|
||||
orchestration: {
|
||||
dispatchCommand: (command: ClientOrchestrationCommand) => Promise<{ sequence: number }>;
|
||||
getTurnDiff: (input: OrchestrationGetTurnDiffInput) => Promise<OrchestrationGetTurnDiffResult>;
|
||||
getFullThreadDiff: (
|
||||
input: OrchestrationGetFullThreadDiffInput,
|
||||
) => Promise<OrchestrationGetFullThreadDiffResult>;
|
||||
getArchivedShellSnapshot: () => Promise<OrchestrationShellSnapshot>;
|
||||
subscribeShell: (
|
||||
callback: (event: OrchestrationShellStreamItem) => void,
|
||||
options?: {
|
||||
onResubscribe?: () => void;
|
||||
onError?: (message: string) => void;
|
||||
},
|
||||
) => () => void;
|
||||
subscribeThread: (
|
||||
input: OrchestrationSubscribeThreadInput,
|
||||
callback: (event: OrchestrationThreadStreamItem) => void,
|
||||
options?: {
|
||||
onResubscribe?: () => void;
|
||||
onError?: (message: string) => void;
|
||||
},
|
||||
) => () => void;
|
||||
};
|
||||
orchestrationV2: {
|
||||
dispatchCommand: (
|
||||
command: OrchestrationV2Command,
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Struct from "effect/Struct";
|
||||
import { ProviderOptionSelections } from "./model.ts";
|
||||
import { RepositoryIdentity, ThreadEnvMode } from "./environment.ts";
|
||||
import {
|
||||
ApprovalRequestId,
|
||||
CheckpointRef,
|
||||
@@ -13,19 +11,12 @@ import {
|
||||
NonNegativeInt,
|
||||
PositiveInt,
|
||||
ProjectId,
|
||||
ProviderItemId,
|
||||
ThreadId,
|
||||
TrimmedNonEmptyString,
|
||||
TrimmedString,
|
||||
TurnId,
|
||||
} from "./baseSchemas.ts";
|
||||
import { ChatAttachment, UploadChatAttachment } from "./chatAttachment.ts";
|
||||
import {
|
||||
OrchestrationGetFullThreadDiffInput,
|
||||
OrchestrationGetFullThreadDiffResult,
|
||||
OrchestrationGetTurnDiffInput,
|
||||
OrchestrationGetTurnDiffResult,
|
||||
} from "./checkpointDiff.ts";
|
||||
import { ModelSelection } from "./modelSelection.ts";
|
||||
import {
|
||||
DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
@@ -37,6 +28,21 @@ import {
|
||||
} from "./providerPolicy.ts";
|
||||
import { ProviderInstanceId } from "./providerInstance.ts";
|
||||
import { Project, ProjectScript } from "./project.ts";
|
||||
import { OrchestrationProjectShell } from "./orchestrationProject.ts";
|
||||
import {
|
||||
ApplicationEventMetadata,
|
||||
ApplicationProjectCreatedEvent,
|
||||
ApplicationProjectDeletedEvent,
|
||||
ApplicationProjectMetaUpdatedEvent,
|
||||
} from "./applicationEvent.ts";
|
||||
|
||||
export { OrchestrationProjectShell } from "./orchestrationProject.ts";
|
||||
|
||||
export {
|
||||
ApplicationProjectCreatedPayload as ProjectCreatedPayload,
|
||||
ApplicationProjectDeletedPayload as ProjectDeletedPayload,
|
||||
ApplicationProjectMetaUpdatedPayload as ProjectMetaUpdatedPayload,
|
||||
} from "./applicationEvent.ts";
|
||||
|
||||
export {
|
||||
OrchestrationGetFullThreadDiffError,
|
||||
@@ -49,16 +55,6 @@ export {
|
||||
TurnCountRange,
|
||||
} from "./checkpointDiff.ts";
|
||||
|
||||
export const ORCHESTRATION_WS_METHODS = {
|
||||
dispatchCommand: "orchestrationV1.dispatchCommand",
|
||||
getTurnDiff: "orchestrationV1.getTurnDiff",
|
||||
getFullThreadDiff: "orchestrationV1.getFullThreadDiff",
|
||||
replayEvents: "orchestrationV1.replayEvents",
|
||||
getArchivedShellSnapshot: "orchestrationV1.getArchivedShellSnapshot",
|
||||
subscribeShell: "orchestrationV1.subscribeShell",
|
||||
subscribeThread: "orchestrationV1.subscribeThread",
|
||||
} as const;
|
||||
|
||||
// Correlation id is command id by design in this model.
|
||||
export const CorrelationId = CommandId;
|
||||
export type CorrelationId = typeof CorrelationId.Type;
|
||||
@@ -298,21 +294,6 @@ export const OrchestrationReadModel = Schema.Struct({
|
||||
});
|
||||
export type OrchestrationReadModel = typeof OrchestrationReadModel.Type;
|
||||
|
||||
export const OrchestrationProjectShell = Schema.Struct({
|
||||
id: ProjectId,
|
||||
title: TrimmedNonEmptyString,
|
||||
workspaceRoot: TrimmedNonEmptyString,
|
||||
repositoryIdentity: Schema.optional(Schema.NullOr(RepositoryIdentity)),
|
||||
defaultModelSelection: Schema.NullOr(ModelSelection),
|
||||
defaultThreadEnvMode: Schema.optional(Schema.NullOr(ThreadEnvMode)),
|
||||
// Optional on the wire so cached snapshots from older servers still decode.
|
||||
faviconPath: Schema.optional(Schema.NullOr(ProjectFaviconPath)),
|
||||
scripts: Schema.Array(ProjectScript),
|
||||
createdAt: IsoDateTime,
|
||||
updatedAt: IsoDateTime,
|
||||
});
|
||||
export type OrchestrationProjectShell = typeof OrchestrationProjectShell.Type;
|
||||
|
||||
export const OrchestrationThreadShell = Schema.Struct({
|
||||
id: ThreadId,
|
||||
projectId: ProjectId,
|
||||
@@ -968,36 +949,6 @@ export const OrchestrationAggregateKind = Schema.Literals(["project", "thread"])
|
||||
export type OrchestrationAggregateKind = typeof OrchestrationAggregateKind.Type;
|
||||
export const OrchestrationActorKind = Schema.Literals(["client", "server", "provider"]);
|
||||
|
||||
export const ProjectCreatedPayload = Schema.Struct({
|
||||
projectId: ProjectId,
|
||||
title: TrimmedNonEmptyString,
|
||||
workspaceRoot: TrimmedNonEmptyString,
|
||||
repositoryIdentity: Schema.optional(Schema.NullOr(RepositoryIdentity)),
|
||||
defaultModelSelection: Schema.NullOr(ModelSelection),
|
||||
// Optional so persisted events from older servers still decode.
|
||||
faviconPath: Schema.optional(Schema.NullOr(ProjectFaviconPath)),
|
||||
scripts: Schema.Array(ProjectScript),
|
||||
createdAt: IsoDateTime,
|
||||
updatedAt: IsoDateTime,
|
||||
});
|
||||
|
||||
export const ProjectMetaUpdatedPayload = Schema.Struct({
|
||||
projectId: ProjectId,
|
||||
title: Schema.optional(TrimmedNonEmptyString),
|
||||
workspaceRoot: Schema.optional(TrimmedNonEmptyString),
|
||||
repositoryIdentity: Schema.optional(Schema.NullOr(RepositoryIdentity)),
|
||||
defaultModelSelection: Schema.optional(Schema.NullOr(ModelSelection)),
|
||||
defaultThreadEnvMode: Schema.optional(Schema.NullOr(ThreadEnvMode)),
|
||||
faviconPath: Schema.optional(Schema.NullOr(ProjectFaviconPath)),
|
||||
scripts: Schema.optional(Schema.Array(ProjectScript)),
|
||||
updatedAt: IsoDateTime,
|
||||
});
|
||||
|
||||
export const ProjectDeletedPayload = Schema.Struct({
|
||||
projectId: ProjectId,
|
||||
deletedAt: IsoDateTime,
|
||||
});
|
||||
|
||||
export const ThreadCreatedPayload = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
projectId: ProjectId,
|
||||
@@ -1195,13 +1146,7 @@ export const ThreadActivityAppendedPayload = Schema.Struct({
|
||||
activity: OrchestrationThreadActivity,
|
||||
});
|
||||
|
||||
export const OrchestrationEventMetadata = Schema.Struct({
|
||||
providerTurnId: Schema.optional(TrimmedNonEmptyString),
|
||||
providerItemId: Schema.optional(ProviderItemId),
|
||||
adapterKey: Schema.optional(TrimmedNonEmptyString),
|
||||
requestId: Schema.optional(ApprovalRequestId),
|
||||
ingestedAt: Schema.optional(IsoDateTime),
|
||||
});
|
||||
export const OrchestrationEventMetadata = ApplicationEventMetadata;
|
||||
export type OrchestrationEventMetadata = typeof OrchestrationEventMetadata.Type;
|
||||
|
||||
const EventBaseFields = {
|
||||
@@ -1217,21 +1162,9 @@ const EventBaseFields = {
|
||||
} as const;
|
||||
|
||||
export const OrchestrationEvent = Schema.Union([
|
||||
Schema.Struct({
|
||||
...EventBaseFields,
|
||||
type: Schema.Literal("project.created"),
|
||||
payload: ProjectCreatedPayload,
|
||||
}),
|
||||
Schema.Struct({
|
||||
...EventBaseFields,
|
||||
type: Schema.Literal("project.meta-updated"),
|
||||
payload: ProjectMetaUpdatedPayload,
|
||||
}),
|
||||
Schema.Struct({
|
||||
...EventBaseFields,
|
||||
type: Schema.Literal("project.deleted"),
|
||||
payload: ProjectDeletedPayload,
|
||||
}),
|
||||
ApplicationProjectCreatedEvent,
|
||||
ApplicationProjectMetaUpdatedEvent,
|
||||
ApplicationProjectDeletedEvent,
|
||||
Schema.Struct({
|
||||
...EventBaseFields,
|
||||
type: Schema.Literal("thread.created"),
|
||||
@@ -1416,142 +1349,3 @@ export type ProjectionPendingApprovalStatus = typeof ProjectionPendingApprovalSt
|
||||
|
||||
export const ProjectionPendingApprovalDecision = Schema.NullOr(ProviderApprovalDecision);
|
||||
export type ProjectionPendingApprovalDecision = typeof ProjectionPendingApprovalDecision.Type;
|
||||
|
||||
export const DispatchResult = Schema.Struct({
|
||||
sequence: NonNegativeInt,
|
||||
});
|
||||
export type DispatchResult = typeof DispatchResult.Type;
|
||||
|
||||
export const OrchestrationReplayEventsInput = Schema.Struct({
|
||||
fromSequenceExclusive: NonNegativeInt,
|
||||
});
|
||||
export type OrchestrationReplayEventsInput = typeof OrchestrationReplayEventsInput.Type;
|
||||
|
||||
// The server's SQLite client is synchronous and single-connection. Bound both
|
||||
// scan input and response size so a search cannot monopolize that connection.
|
||||
export const OrchestrationSearchThreadsInput = Schema.Struct({
|
||||
query: TrimmedString.check(Schema.isMinLength(2), Schema.isMaxLength(200)),
|
||||
limit: Schema.optionalKey(Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 50 }))),
|
||||
});
|
||||
export type OrchestrationSearchThreadsInput = typeof OrchestrationSearchThreadsInput.Type;
|
||||
|
||||
export const OrchestrationThreadSearchMatch = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
projectId: ProjectId,
|
||||
source: OrchestrationThreadSearchSource,
|
||||
snippet: Schema.String.check(Schema.isMaxLength(240)),
|
||||
messageCreatedAt: Schema.NullOr(IsoDateTime),
|
||||
});
|
||||
export type OrchestrationThreadSearchMatch = typeof OrchestrationThreadSearchMatch.Type;
|
||||
|
||||
export const OrchestrationSearchThreadsResult = Schema.Struct({
|
||||
matches: Schema.Array(OrchestrationThreadSearchMatch),
|
||||
});
|
||||
export type OrchestrationSearchThreadsResult = typeof OrchestrationSearchThreadsResult.Type;
|
||||
|
||||
export const OrchestrationGetWorkflowScriptInput = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
/** Absolute path from the workflow's runHandles.scriptPath. The server
|
||||
* re-derives containment; the client value is a hint, never trusted. */
|
||||
scriptPath: TrimmedNonEmptyString,
|
||||
});
|
||||
export type OrchestrationGetWorkflowScriptInput = typeof OrchestrationGetWorkflowScriptInput.Type;
|
||||
|
||||
export const OrchestrationGetWorkflowScriptResult = Schema.Struct({
|
||||
scriptPath: TrimmedNonEmptyString,
|
||||
contents: Schema.String,
|
||||
truncated: Schema.Boolean,
|
||||
});
|
||||
export type OrchestrationGetWorkflowScriptResult = typeof OrchestrationGetWorkflowScriptResult.Type;
|
||||
|
||||
const WORKFLOW_SCRIPT_ERROR_MESSAGES = {
|
||||
"invalid-path": "Workflow scripts must be absolute .js paths.",
|
||||
"root-unavailable": "Script root unavailable.",
|
||||
"not-found": "Script not found.",
|
||||
"outside-root": "Script path is outside the workflow scripts root.",
|
||||
"not-js": "Resolved script is not a .js file.",
|
||||
"not-regular-file": "Script is not a regular file.",
|
||||
"changed-during-read": "Script changed between resolution and open.",
|
||||
"read-failed": "Script read failed.",
|
||||
} as const;
|
||||
|
||||
export class OrchestrationGetWorkflowScriptError extends Schema.TaggedErrorClass<OrchestrationGetWorkflowScriptError>()(
|
||||
"OrchestrationGetWorkflowScriptError",
|
||||
{
|
||||
reason: Schema.Literals([
|
||||
"invalid-path",
|
||||
"root-unavailable",
|
||||
"not-found",
|
||||
"outside-root",
|
||||
"not-js",
|
||||
"not-regular-file",
|
||||
"changed-during-read",
|
||||
"read-failed",
|
||||
]),
|
||||
scriptPath: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect()),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return WORKFLOW_SCRIPT_ERROR_MESSAGES[this.reason];
|
||||
}
|
||||
}
|
||||
|
||||
export const OrchestrationRpcSchemas = {
|
||||
dispatchCommand: {
|
||||
input: ClientOrchestrationCommand,
|
||||
output: DispatchResult,
|
||||
},
|
||||
getWorkflowScript: {
|
||||
input: OrchestrationGetWorkflowScriptInput,
|
||||
output: OrchestrationGetWorkflowScriptResult,
|
||||
},
|
||||
getTurnDiff: {
|
||||
input: OrchestrationGetTurnDiffInput,
|
||||
output: OrchestrationGetTurnDiffResult,
|
||||
},
|
||||
getFullThreadDiff: {
|
||||
input: OrchestrationGetFullThreadDiffInput,
|
||||
output: OrchestrationGetFullThreadDiffResult,
|
||||
},
|
||||
searchThreads: {
|
||||
input: OrchestrationSearchThreadsInput,
|
||||
output: OrchestrationSearchThreadsResult,
|
||||
},
|
||||
getArchivedShellSnapshot: {
|
||||
input: Schema.Struct({}),
|
||||
output: OrchestrationShellSnapshot,
|
||||
},
|
||||
subscribeThread: {
|
||||
input: OrchestrationSubscribeThreadInput,
|
||||
output: OrchestrationThreadStreamItem,
|
||||
},
|
||||
subscribeShell: {
|
||||
input: OrchestrationSubscribeShellInput,
|
||||
output: OrchestrationShellStreamItem,
|
||||
},
|
||||
} as const;
|
||||
|
||||
export class OrchestrationGetSnapshotError extends Schema.TaggedErrorClass<OrchestrationGetSnapshotError>()(
|
||||
"OrchestrationGetSnapshotError",
|
||||
{
|
||||
message: TrimmedNonEmptyString,
|
||||
cause: Schema.optional(Schema.Defect()),
|
||||
},
|
||||
) {}
|
||||
|
||||
export class OrchestrationDispatchCommandError extends Schema.TaggedErrorClass<OrchestrationDispatchCommandError>()(
|
||||
"OrchestrationDispatchCommandError",
|
||||
{
|
||||
message: TrimmedNonEmptyString,
|
||||
cause: Schema.optional(Schema.Defect()),
|
||||
},
|
||||
) {}
|
||||
|
||||
export class OrchestrationReplayEventsError extends Schema.TaggedErrorClass<OrchestrationReplayEventsError>()(
|
||||
"OrchestrationReplayEventsError",
|
||||
{
|
||||
message: TrimmedNonEmptyString,
|
||||
cause: Schema.optional(Schema.Defect()),
|
||||
},
|
||||
) {}
|
||||
@@ -0,0 +1,19 @@
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import { IsoDateTime, ProjectId, TrimmedNonEmptyString } from "./baseSchemas.ts";
|
||||
import { RepositoryIdentity } from "./environment.ts";
|
||||
import { ModelSelection } from "./modelSelection.ts";
|
||||
import { ProjectScript } from "./project.ts";
|
||||
|
||||
/** Project summary shared by the V2 shell and application project APIs. */
|
||||
export const OrchestrationProjectShell = Schema.Struct({
|
||||
id: ProjectId,
|
||||
title: TrimmedNonEmptyString,
|
||||
workspaceRoot: TrimmedNonEmptyString,
|
||||
repositoryIdentity: Schema.optional(Schema.NullOr(RepositoryIdentity)),
|
||||
defaultModelSelection: Schema.NullOr(ModelSelection),
|
||||
scripts: Schema.Array(ProjectScript),
|
||||
createdAt: IsoDateTime,
|
||||
updatedAt: IsoDateTime,
|
||||
});
|
||||
export type OrchestrationProjectShell = typeof OrchestrationProjectShell.Type;
|
||||
@@ -42,7 +42,7 @@ import {
|
||||
RuntimeMode,
|
||||
} from "./providerPolicy.ts";
|
||||
import { ProviderDriverKind, ProviderInstanceId } from "./providerInstance.ts";
|
||||
import { OrchestrationProjectShell } from "./orchestration.ts";
|
||||
import { OrchestrationProjectShell } from "./orchestrationProject.ts";
|
||||
|
||||
export const OrchestrationV2Actor = Schema.Literals(["user", "agent", "system"]);
|
||||
export type OrchestrationV2Actor = typeof OrchestrationV2Actor.Type;
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
|
||||
import { ORCHESTRATION_V2_WS_METHODS } from "./orchestrationV2.ts";
|
||||
import { WsRpcGroup } from "./rpc.ts";
|
||||
|
||||
describe("WebSocket RPC contracts", () => {
|
||||
it("exposes only the V2 orchestration transport surface", () => {
|
||||
const methods = [...WsRpcGroup.requests.keys()];
|
||||
|
||||
expect(methods).toEqual(expect.arrayContaining(Object.values(ORCHESTRATION_V2_WS_METHODS)));
|
||||
expect(methods.filter((method) => method.startsWith("orchestrationV1."))).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -26,9 +26,7 @@ import {
|
||||
} from "./chatAttachment.ts";
|
||||
import {
|
||||
OrchestrationGetFullThreadDiffError,
|
||||
OrchestrationGetFullThreadDiffInput,
|
||||
OrchestrationGetTurnDiffError,
|
||||
OrchestrationGetTurnDiffInput,
|
||||
} from "./checkpointDiff.ts";
|
||||
import {
|
||||
GitActionProgressEvent,
|
||||
@@ -63,16 +61,6 @@ import {
|
||||
ReviewDiffPreviewResult,
|
||||
} from "./review.ts";
|
||||
import { KeybindingsConfigError } from "./keybindings.ts";
|
||||
import {
|
||||
ClientOrchestrationCommand,
|
||||
ORCHESTRATION_WS_METHODS,
|
||||
OrchestrationDispatchCommandError,
|
||||
OrchestrationGetSnapshotError,
|
||||
OrchestrationReplayEventsError,
|
||||
OrchestrationReplayEventsInput,
|
||||
OrchestrationRpcSchemas,
|
||||
OrchestrationGetWorkflowScriptError,
|
||||
} from "./orchestration.ts";
|
||||
import { ProviderInstanceId } from "./providerInstance.ts";
|
||||
import {
|
||||
PullRequestActionInput,
|
||||
@@ -879,71 +867,6 @@ export const WsSubscribeDiscoveredLocalServersRpc = Rpc.make(
|
||||
},
|
||||
);
|
||||
|
||||
export const WsOrchestrationDispatchCommandRpc = Rpc.make(
|
||||
ORCHESTRATION_WS_METHODS.dispatchCommand,
|
||||
{
|
||||
payload: ClientOrchestrationCommand,
|
||||
success: OrchestrationRpcSchemas.dispatchCommand.output,
|
||||
error: Schema.Union([OrchestrationDispatchCommandError, EnvironmentAuthorizationError]),
|
||||
},
|
||||
);
|
||||
|
||||
export const WsOrchestrationGetWorkflowScriptRpc = Rpc.make(
|
||||
ORCHESTRATION_WS_METHODS.getWorkflowScript,
|
||||
{
|
||||
payload: OrchestrationRpcSchemas.getWorkflowScript.input,
|
||||
success: OrchestrationRpcSchemas.getWorkflowScript.output,
|
||||
error: Schema.Union([OrchestrationGetWorkflowScriptError, EnvironmentAuthorizationError]),
|
||||
},
|
||||
);
|
||||
|
||||
export const WsOrchestrationGetTurnDiffRpc = Rpc.make(ORCHESTRATION_WS_METHODS.getTurnDiff, {
|
||||
payload: OrchestrationGetTurnDiffInput,
|
||||
success: OrchestrationRpcSchemas.getTurnDiff.output,
|
||||
error: Schema.Union([OrchestrationGetTurnDiffError, EnvironmentAuthorizationError]),
|
||||
});
|
||||
|
||||
export const WsOrchestrationGetFullThreadDiffRpc = Rpc.make(
|
||||
ORCHESTRATION_WS_METHODS.getFullThreadDiff,
|
||||
{
|
||||
payload: OrchestrationGetFullThreadDiffInput,
|
||||
success: OrchestrationRpcSchemas.getFullThreadDiff.output,
|
||||
error: Schema.Union([OrchestrationGetFullThreadDiffError, EnvironmentAuthorizationError]),
|
||||
},
|
||||
);
|
||||
|
||||
export const WsOrchestrationSearchThreadsRpc = Rpc.make(ORCHESTRATION_WS_METHODS.searchThreads, {
|
||||
payload: OrchestrationSearchThreadsInput,
|
||||
success: OrchestrationRpcSchemas.searchThreads.output,
|
||||
error: Schema.Union([OrchestrationSearchThreadsError, EnvironmentAuthorizationError]),
|
||||
});
|
||||
|
||||
export const WsOrchestrationGetArchivedShellSnapshotRpc = Rpc.make(
|
||||
ORCHESTRATION_WS_METHODS.getArchivedShellSnapshot,
|
||||
{
|
||||
payload: OrchestrationRpcSchemas.getArchivedShellSnapshot.input,
|
||||
success: OrchestrationRpcSchemas.getArchivedShellSnapshot.output,
|
||||
error: Schema.Union([OrchestrationGetSnapshotError, EnvironmentAuthorizationError]),
|
||||
},
|
||||
);
|
||||
|
||||
export const WsOrchestrationSubscribeShellRpc = Rpc.make(ORCHESTRATION_WS_METHODS.subscribeShell, {
|
||||
payload: OrchestrationRpcSchemas.subscribeShell.input,
|
||||
success: OrchestrationRpcSchemas.subscribeShell.output,
|
||||
error: Schema.Union([OrchestrationGetSnapshotError, EnvironmentAuthorizationError]),
|
||||
stream: true,
|
||||
});
|
||||
|
||||
export const WsOrchestrationSubscribeThreadRpc = Rpc.make(
|
||||
ORCHESTRATION_WS_METHODS.subscribeThread,
|
||||
{
|
||||
payload: OrchestrationRpcSchemas.subscribeThread.input,
|
||||
success: OrchestrationRpcSchemas.subscribeThread.output,
|
||||
error: Schema.Union([OrchestrationGetSnapshotError, EnvironmentAuthorizationError]),
|
||||
stream: true,
|
||||
},
|
||||
);
|
||||
|
||||
export const WsOrchestrationV2DispatchCommandRpc = Rpc.make(
|
||||
ORCHESTRATION_V2_WS_METHODS.dispatchCommand,
|
||||
{
|
||||
@@ -1162,16 +1085,6 @@ export const WsRpcGroup = RpcGroup.make(
|
||||
WsSubscribeServerConfigRpc,
|
||||
WsSubscribeServerLifecycleRpc,
|
||||
WsSubscribeAuthAccessRpc,
|
||||
WsSubscribeBackgroundPolicyRpc,
|
||||
WsSubscribeResourceTelemetryRpc,
|
||||
WsOrchestrationDispatchCommandRpc,
|
||||
WsOrchestrationGetWorkflowScriptRpc,
|
||||
WsOrchestrationGetTurnDiffRpc,
|
||||
WsOrchestrationGetFullThreadDiffRpc,
|
||||
WsOrchestrationSearchThreadsRpc,
|
||||
WsOrchestrationGetArchivedShellSnapshotRpc,
|
||||
WsOrchestrationSubscribeShellRpc,
|
||||
WsOrchestrationSubscribeThreadRpc,
|
||||
WsOrchestrationV2DispatchCommandRpc,
|
||||
WsOrchestrationV2GetTurnDiffRpc,
|
||||
WsOrchestrationV2GetFullThreadDiffRpc,
|
||||
|
||||
@@ -3,183 +3,19 @@ import { describe, expect, it } from "@effect/vitest";
|
||||
import type {
|
||||
EnvironmentId,
|
||||
OrchestrationV2ThreadShell,
|
||||
OrchestrationProjectShell,
|
||||
OrchestrationThreadShell,
|
||||
Project,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
} from "@t3tools/contracts";
|
||||
import { ProviderInstanceId, RuntimeRequestId } from "@t3tools/contracts";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
|
||||
import { projectThreadAwareness, projectThreadAwarenessV2 } from "./agentAwareness.ts";
|
||||
import { projectThreadAwarenessV2 } from "./agentAwareness.ts";
|
||||
|
||||
const NOW = "2026-05-22T12:00:00.000Z";
|
||||
|
||||
const project = {
|
||||
title: "t3code",
|
||||
} satisfies Pick<OrchestrationProjectShell, "title">;
|
||||
|
||||
function thread(
|
||||
overrides: Partial<OrchestrationThreadShell> = {},
|
||||
): Pick<
|
||||
OrchestrationThreadShell,
|
||||
| "id"
|
||||
| "title"
|
||||
| "modelSelection"
|
||||
| "session"
|
||||
| "latestTurn"
|
||||
| "updatedAt"
|
||||
| "hasPendingApprovals"
|
||||
| "hasPendingUserInput"
|
||||
> {
|
||||
return {
|
||||
id: "thread-1" as ThreadId,
|
||||
title: "Fix failing CI",
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
|
||||
session: null,
|
||||
latestTurn: null,
|
||||
updatedAt: NOW,
|
||||
hasPendingApprovals: false,
|
||||
hasPendingUserInput: false,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("projectThreadAwareness", () => {
|
||||
it("returns null for idle threads without an active awareness state", () => {
|
||||
expect(
|
||||
projectThreadAwareness({
|
||||
environmentId: "env-1" as EnvironmentId,
|
||||
project,
|
||||
thread: thread(),
|
||||
}),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it("prioritizes approval requests over running state", () => {
|
||||
const state = projectThreadAwareness({
|
||||
environmentId: "env-1" as EnvironmentId,
|
||||
project,
|
||||
thread: thread({
|
||||
hasPendingApprovals: true,
|
||||
session: {
|
||||
threadId: "thread-1" as ThreadId,
|
||||
status: "running",
|
||||
providerName: "Codex",
|
||||
runtimeMode: "full-access",
|
||||
activeTurnId: "turn-1" as TurnId,
|
||||
lastError: null,
|
||||
updatedAt: NOW,
|
||||
},
|
||||
}),
|
||||
});
|
||||
|
||||
expect(state?.phase).toBe("waiting_for_approval");
|
||||
expect(state?.headline).toBe("Approval needed");
|
||||
});
|
||||
|
||||
it("projects running provider sessions", () => {
|
||||
const state = projectThreadAwareness({
|
||||
environmentId: "env-1" as EnvironmentId,
|
||||
project,
|
||||
thread: thread({
|
||||
session: {
|
||||
threadId: "thread-1" as ThreadId,
|
||||
status: "running",
|
||||
providerName: "Codex",
|
||||
runtimeMode: "full-access",
|
||||
activeTurnId: "turn-1" as TurnId,
|
||||
lastError: null,
|
||||
updatedAt: NOW,
|
||||
},
|
||||
}),
|
||||
});
|
||||
|
||||
expect(state).toMatchObject({
|
||||
phase: "running",
|
||||
headline: "Agent is working",
|
||||
detail: "Codex is active.",
|
||||
modelTitle: "gpt-5.4",
|
||||
deepLink: "/threads/env-1/thread-1",
|
||||
});
|
||||
});
|
||||
|
||||
it("projects completed turns as completed even when teardown settled them as interrupted", () => {
|
||||
const finishedTurn = {
|
||||
turnId: "turn-1" as TurnId,
|
||||
state: "interrupted" as const,
|
||||
requestedAt: NOW,
|
||||
startedAt: NOW,
|
||||
completedAt: NOW,
|
||||
assistantMessageId: null,
|
||||
};
|
||||
const state = projectThreadAwareness({
|
||||
environmentId: "env-1" as EnvironmentId,
|
||||
project,
|
||||
thread: thread({ latestTurn: finishedTurn }),
|
||||
});
|
||||
|
||||
// Session teardown settles still-running turns by session status, and
|
||||
// that write can race turn.completed; the completion timestamp is the
|
||||
// durable signal. Without this the thread resolves to null persistently
|
||||
// and gets tombstoned off the lock-screen card instead of showing Done.
|
||||
expect(state?.phase).toBe("completed");
|
||||
|
||||
const trulyInterrupted = projectThreadAwareness({
|
||||
environmentId: "env-1" as EnvironmentId,
|
||||
project,
|
||||
thread: thread({ latestTurn: { ...finishedTurn, completedAt: null } }),
|
||||
});
|
||||
expect(trulyInterrupted).toBeNull();
|
||||
});
|
||||
|
||||
it("projects ready sessions with no materialized turn as completed", () => {
|
||||
// Quick threads without code changes never get a checkpoint, so the SQL
|
||||
// shell has no latestTurn row and latest_turn_id is cleared when the
|
||||
// session settles; the ready session is the only completion signal left.
|
||||
const state = projectThreadAwareness({
|
||||
environmentId: "env-1" as EnvironmentId,
|
||||
project,
|
||||
thread: thread({
|
||||
session: {
|
||||
threadId: "thread-1" as ThreadId,
|
||||
status: "ready",
|
||||
providerName: "Codex",
|
||||
runtimeMode: "full-access",
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: NOW,
|
||||
},
|
||||
}),
|
||||
});
|
||||
|
||||
expect(state?.phase).toBe("completed");
|
||||
});
|
||||
|
||||
it("projects failures with the session error detail", () => {
|
||||
const state = projectThreadAwareness({
|
||||
environmentId: "env-1" as EnvironmentId,
|
||||
project,
|
||||
thread: thread({
|
||||
session: {
|
||||
threadId: "thread-1" as ThreadId,
|
||||
status: "error",
|
||||
providerName: "Codex",
|
||||
runtimeMode: "full-access",
|
||||
activeTurnId: null,
|
||||
lastError: "Provider process exited.",
|
||||
updatedAt: NOW,
|
||||
},
|
||||
}),
|
||||
});
|
||||
|
||||
expect(state).toMatchObject({
|
||||
phase: "failed",
|
||||
headline: "Agent failed",
|
||||
detail: "Provider process exited.",
|
||||
});
|
||||
});
|
||||
});
|
||||
} satisfies Pick<Project, "title">;
|
||||
|
||||
describe("projectThreadAwarenessV2", () => {
|
||||
const updatedAt = DateTime.makeUnsafe(NOW);
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
import type {
|
||||
EnvironmentId,
|
||||
OrchestrationV2ThreadShell,
|
||||
OrchestrationProjectShell,
|
||||
OrchestrationThreadShell,
|
||||
Project,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
@@ -30,22 +28,6 @@ export interface AgentAwarenessState {
|
||||
readonly deepLink: string;
|
||||
}
|
||||
|
||||
export interface ProjectThreadAwarenessInput {
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly project: Pick<OrchestrationProjectShell, "title">;
|
||||
readonly thread: Pick<
|
||||
OrchestrationThreadShell,
|
||||
| "id"
|
||||
| "title"
|
||||
| "modelSelection"
|
||||
| "session"
|
||||
| "latestTurn"
|
||||
| "updatedAt"
|
||||
| "hasPendingApprovals"
|
||||
| "hasPendingUserInput"
|
||||
>;
|
||||
}
|
||||
|
||||
export function buildAgentAwarenessDeepLink(input: {
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly threadId: ThreadId;
|
||||
@@ -53,28 +35,12 @@ export function buildAgentAwarenessDeepLink(input: {
|
||||
return `/threads/${encodeURIComponent(input.environmentId)}/${encodeURIComponent(input.threadId)}`;
|
||||
}
|
||||
|
||||
export function projectThreadAwareness(
|
||||
input: ProjectThreadAwarenessInput,
|
||||
): AgentAwarenessState | null {
|
||||
const { environmentId, project, thread } = input;
|
||||
const phase = resolveThreadAwarenessPhase(thread);
|
||||
if (!phase) {
|
||||
return null;
|
||||
}
|
||||
export function isTerminalAgentAwarenessPhase(phase: AgentAwarenessPhase): boolean {
|
||||
return phase === "completed" || phase === "failed";
|
||||
}
|
||||
|
||||
const detail = detailForPhase(phase, thread);
|
||||
return {
|
||||
environmentId,
|
||||
threadId: thread.id,
|
||||
projectTitle: project.title,
|
||||
threadTitle: thread.title,
|
||||
phase,
|
||||
headline: headlineForPhase(phase),
|
||||
...(detail === undefined ? {} : { detail }),
|
||||
modelTitle: thread.modelSelection.model,
|
||||
updatedAt: thread.updatedAt,
|
||||
deepLink: buildAgentAwarenessDeepLink({ environmentId, threadId: thread.id }),
|
||||
};
|
||||
export function isInterruptiveAgentAwarenessPhase(phase: AgentAwarenessPhase): boolean {
|
||||
return phase === "waiting_for_approval" || phase === "waiting_for_input" || phase === "failed";
|
||||
}
|
||||
|
||||
export interface ProjectThreadAwarenessV2Input {
|
||||
@@ -144,48 +110,6 @@ function resolveThreadAwarenessPhaseV2(
|
||||
}
|
||||
}
|
||||
|
||||
function resolveThreadAwarenessPhase(
|
||||
thread: ProjectThreadAwarenessInput["thread"],
|
||||
): AgentAwarenessPhase | null {
|
||||
if (thread.hasPendingApprovals) {
|
||||
return "waiting_for_approval";
|
||||
}
|
||||
if (thread.hasPendingUserInput) {
|
||||
return "waiting_for_input";
|
||||
}
|
||||
if (thread.session?.status === "error" || thread.latestTurn?.state === "error") {
|
||||
return "failed";
|
||||
}
|
||||
if (thread.session?.status === "starting") {
|
||||
return "starting";
|
||||
}
|
||||
if (thread.session?.status === "running" || thread.latestTurn?.state === "running") {
|
||||
return "running";
|
||||
}
|
||||
if (thread.latestTurn?.state === "completed") {
|
||||
return "completed";
|
||||
}
|
||||
// A turn that finished can still read as "interrupted" here: session
|
||||
// teardown settles still-running turns by session status, and that write
|
||||
// can race the turn.completed one. completedAt survives the race — a turn
|
||||
// that has a completion timestamp finished, whatever the state column says.
|
||||
// Without this, quick finish-then-teardown threads resolve to null
|
||||
// persistently and get tombstoned instead of published as completed.
|
||||
if (thread.latestTurn?.state === "interrupted" && thread.latestTurn.completedAt !== null) {
|
||||
return "completed";
|
||||
}
|
||||
// Threads whose turns never produce a checkpoint (no code changes) have no
|
||||
// materialized latestTurn in the shell at all, and the session-set
|
||||
// projection clears latest_turn_id the moment the session settles. The
|
||||
// session status is then the only surviving completion signal: a live
|
||||
// session at "ready"/"idle" with nothing pending and nothing running means
|
||||
// the agent finished and is waiting for the next prompt — Done.
|
||||
if (thread.session?.status === "ready" || thread.session?.status === "idle") {
|
||||
return "completed";
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function headlineForPhase(phase: AgentAwarenessPhase): string {
|
||||
switch (phase) {
|
||||
case "starting":
|
||||
@@ -204,19 +128,3 @@ function headlineForPhase(phase: AgentAwarenessPhase): string {
|
||||
return "Update delayed";
|
||||
}
|
||||
}
|
||||
|
||||
function detailForPhase(
|
||||
phase: AgentAwarenessPhase,
|
||||
thread: ProjectThreadAwarenessInput["thread"],
|
||||
): string | undefined {
|
||||
if (phase === "failed") {
|
||||
return thread.session?.lastError ?? undefined;
|
||||
}
|
||||
if (phase === "completed") {
|
||||
return "Review the completed task.";
|
||||
}
|
||||
if (phase === "running" && thread.session?.providerName) {
|
||||
return `${thread.session.providerName} is active.`;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
@@ -12,6 +12,7 @@ export default defineConfig({
|
||||
environment: "node",
|
||||
exclude: [
|
||||
"**/.repos/**",
|
||||
"**/.t3/**",
|
||||
"**/node_modules/**",
|
||||
"**/dist/**",
|
||||
"**/dist-electron/**",
|
||||
|
||||
Reference in new issue
Block a user