fix(mobile): preserve active thread state
Keep executing runs visible when newer work is queued, expose provider errors in compact shells, and preserve mobile creation metadata for fork and merge operations. Co-authored-by: codex <[email protected]>
This commit is contained in:
1 parent
ae3a25649a
commit
e56b1c3dde
16 files changed
+230
-44
No files matched your search
@@ -1,7 +1,5 @@
|
||||
import {
|
||||
threadRuntimeIsActive,
|
||||
type EnvironmentThreadShell,
|
||||
} from "@t3tools/client-runtime/state/shell";
|
||||
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
|
||||
import { threadRuntimeHasInterruptibleRun } from "@t3tools/client-runtime/state/thread-execution";
|
||||
import { canSettle } from "@t3tools/client-runtime/state/thread-settled";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Haptics from "expo-haptics";
|
||||
@@ -98,7 +96,7 @@ function useThreadActionExecutor(
|
||||
}
|
||||
// Archive keeps its original, narrower guard: never interrupt a
|
||||
// thread mid-turn.
|
||||
if (action === "archive" && threadRuntimeIsActive(thread.runtime)) {
|
||||
if (action === "archive" && threadRuntimeHasInterruptibleRun(thread.runtime)) {
|
||||
Alert.alert(
|
||||
actionFailureTitle(action),
|
||||
"This thread is working. Interrupt it first, then try again.",
|
||||
|
||||
@@ -1,8 +1,5 @@
|
||||
import { isLiquidGlassSupported, LiquidGlassView } from "@callstack/liquid-glass";
|
||||
import {
|
||||
threadRuntimeIsActive,
|
||||
type EnvironmentThreadShell,
|
||||
} from "@t3tools/client-runtime/state/shell";
|
||||
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
|
||||
import type {
|
||||
EnvironmentId,
|
||||
MessageId,
|
||||
@@ -104,6 +101,7 @@ export interface ThreadComposerProps {
|
||||
readonly serverConfig: T3ServerConfig | null;
|
||||
readonly queueCount: number;
|
||||
readonly activeThreadBusy: boolean;
|
||||
readonly canStopThread: boolean;
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly projectCwd: string | null;
|
||||
readonly editorRef?: RefObject<ComposerEditorHandle | null>;
|
||||
@@ -308,7 +306,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
|
||||
setIsFocused(false);
|
||||
onExpandedChange?.(false);
|
||||
}, [onExpandedChange]);
|
||||
const showStopAction = threadRuntimeIsActive(props.selectedThread.runtime);
|
||||
const showStopAction = props.canStopThread;
|
||||
|
||||
const sendLabel =
|
||||
props.connectionState !== "connected" || props.activeThreadBusy || props.queueCount > 0
|
||||
|
||||
@@ -31,6 +31,7 @@ import type {
|
||||
PendingUserInput,
|
||||
PendingUserInputDraftAnswer,
|
||||
ThreadFeedEntry,
|
||||
ThreadFeedLatestRun,
|
||||
} from "../../lib/threadActivity";
|
||||
import { PendingApprovalCard } from "./PendingApprovalCard";
|
||||
import { PendingUserInputCard } from "./PendingUserInputCard";
|
||||
@@ -51,6 +52,7 @@ export interface ThreadDetailScreenProps {
|
||||
readonly connectionError: string | null;
|
||||
readonly environmentLabel: string | null;
|
||||
readonly selectedThreadFeed: ReadonlyArray<ThreadFeedEntry>;
|
||||
readonly activityRun: ThreadFeedLatestRun | null;
|
||||
readonly activeWorkStartedAt: string | null;
|
||||
readonly activePendingApproval: PendingApproval | null;
|
||||
readonly respondingApprovalId: RuntimeRequestId | null;
|
||||
@@ -64,6 +66,7 @@ export interface ThreadDetailScreenProps {
|
||||
/** Message sync status for the selected thread (drives the composer status pill). */
|
||||
readonly threadSyncStatus?: EnvironmentThreadStatus;
|
||||
readonly activeThreadBusy: boolean;
|
||||
readonly canStopThread: boolean;
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly projectWorkspaceRoot: string | null;
|
||||
readonly threadCwd: string | null;
|
||||
@@ -361,7 +364,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
contentPresentation={props.contentPresentation}
|
||||
agentLabel={agentLabel}
|
||||
threadTitle={props.selectedThread.title}
|
||||
latestRun={props.selectedThread.latestRun}
|
||||
latestRun={props.activityRun}
|
||||
activeWorkStartedAt={props.activeWorkStartedAt}
|
||||
listRef={listRef}
|
||||
freeze={freeze}
|
||||
@@ -444,6 +447,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
serverConfig={props.serverConfig}
|
||||
queueCount={props.selectedThreadQueueCount}
|
||||
activeThreadBusy={props.activeThreadBusy}
|
||||
canStopThread={props.canStopThread}
|
||||
environmentId={props.environmentId}
|
||||
projectCwd={props.projectWorkspaceRoot}
|
||||
bottomInset={composerBottomInset}
|
||||
|
||||
@@ -97,6 +97,7 @@ import { markdownFileIconSource } from "@t3tools/mobile-markdown-text/file-icons
|
||||
import { resolveMarkdownLinkPresentation } from "@t3tools/mobile-markdown-text/links";
|
||||
import {
|
||||
deriveThreadFeedPresentation,
|
||||
threadFeedRunIsUnsettled,
|
||||
type ThreadFeedEntry,
|
||||
type ThreadFeedLatestRun,
|
||||
} from "../../lib/threadActivity";
|
||||
@@ -208,6 +209,7 @@ function AssistantForkButton(props: {
|
||||
targetThreadId,
|
||||
runId,
|
||||
title: `${props.sourceTitle} fork`,
|
||||
creationSource: "mobile",
|
||||
},
|
||||
})
|
||||
.then(async (result) => {
|
||||
@@ -1601,11 +1603,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
}
|
||||
return new Set(terminalIdsByTurn.values());
|
||||
}, [props.feed]);
|
||||
const unsettledTurnId =
|
||||
props.latestRun &&
|
||||
(props.latestRun.completedAt === null || props.latestRun.status === "running")
|
||||
? props.latestRun.runId
|
||||
: null;
|
||||
const unsettledTurnId = threadFeedRunIsUnsettled(props.latestRun) ? props.latestRun.runId : null;
|
||||
|
||||
useEffect(() => {
|
||||
const previous = previousLatestTurnRef.current;
|
||||
|
||||
@@ -130,6 +130,7 @@ export function ThreadRelationshipsBanner(props: {
|
||||
sourceThreadId: props.threadId,
|
||||
targetThreadId: mergeTargetThreadId,
|
||||
runId: latestCompletedRun.id,
|
||||
creationSource: "mobile",
|
||||
},
|
||||
});
|
||||
setBusyAction(null);
|
||||
|
||||
@@ -5,7 +5,6 @@ import {
|
||||
useNavigation,
|
||||
type StaticScreenProps,
|
||||
} from "@react-navigation/native";
|
||||
import { threadRuntimeIsActive } from "@t3tools/client-runtime/state/shell";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
|
||||
import * as Option from "effect/Option";
|
||||
import { EnvironmentId, ThreadId, type ProjectScript } from "@t3tools/contracts";
|
||||
@@ -462,18 +461,17 @@ function ThreadRouteContent(
|
||||
void navigation.navigate("Connections");
|
||||
}, [navigation]);
|
||||
const handleStopThread = useCallback(() => {
|
||||
const runtime = selectedThread?.runtime;
|
||||
if (!selectedThread || !runtime || !threadRuntimeIsActive(runtime)) {
|
||||
if (!selectedThread || composer.interruptibleRunId === null) {
|
||||
return;
|
||||
}
|
||||
return interruptThreadTurn({
|
||||
environmentId: selectedThread.environmentId,
|
||||
input: {
|
||||
threadId: selectedThread.id,
|
||||
...(runtime.activeRunId ? { runId: runtime.activeRunId } : {}),
|
||||
runId: composer.interruptibleRunId,
|
||||
},
|
||||
});
|
||||
}, [interruptThreadTurn, selectedThread]);
|
||||
}, [composer.interruptibleRunId, interruptThreadTurn, selectedThread]);
|
||||
|
||||
const handleOpenTerminal = useCallback(
|
||||
(nextTerminalId?: string | null) => {
|
||||
@@ -751,6 +749,7 @@ function ThreadRouteContent(
|
||||
connectionError={routeConnectionError}
|
||||
environmentLabel={selectedEnvironmentConnection?.environmentLabel ?? null}
|
||||
selectedThreadFeed={composer.selectedThreadFeed}
|
||||
activityRun={composer.selectedThreadActivityRun}
|
||||
activeWorkStartedAt={composer.activeWorkStartedAt}
|
||||
activePendingApproval={requests.activePendingApproval}
|
||||
respondingApprovalId={requests.respondingApprovalId}
|
||||
@@ -763,6 +762,7 @@ function ThreadRouteContent(
|
||||
connectionStateLabel={routeConnectionState}
|
||||
threadSyncStatus={selectedThreadDetailState.status}
|
||||
activeThreadBusy={composer.activeThreadBusy}
|
||||
canStopThread={composer.interruptibleRunId !== null}
|
||||
environmentId={selectedThread.environmentId}
|
||||
projectWorkspaceRoot={selectedThreadProject?.workspaceRoot ?? null}
|
||||
threadCwd={selectedThreadCwd}
|
||||
|
||||
@@ -12,6 +12,7 @@ import { describe, expect, it } from "vite-plus/test";
|
||||
import {
|
||||
buildThreadFeed,
|
||||
deriveThreadFeedPresentation,
|
||||
threadFeedRunIsUnsettled,
|
||||
type ThreadFeedActivity,
|
||||
type ThreadFeedEntry,
|
||||
} from "./threadActivity";
|
||||
@@ -88,6 +89,25 @@ function assistantMessage(updatedAt = "2026-06-20T00:00:03.000Z") {
|
||||
}
|
||||
|
||||
describe("buildThreadFeed", () => {
|
||||
it("does not treat a queued-only run as live feed activity", () => {
|
||||
expect(
|
||||
threadFeedRunIsUnsettled({
|
||||
runId,
|
||||
status: "queued",
|
||||
startedAt: null,
|
||||
completedAt: null,
|
||||
}),
|
||||
).toBe(false);
|
||||
expect(
|
||||
threadFeedRunIsUnsettled({
|
||||
runId,
|
||||
status: "running",
|
||||
startedAt: "2026-06-20T00:00:01.000Z",
|
||||
completedAt: null,
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("preserves authoritative V2 order instead of sorting reconstructed collections", () => {
|
||||
const rows = [
|
||||
projected(userMessage("2026-06-20T00:00:03.000Z"), 0),
|
||||
|
||||
@@ -428,14 +428,19 @@ function maxIsoTimestamp(left: string | null, right: string | null): string | nu
|
||||
}
|
||||
|
||||
function unsettledRunId(latestRun: ThreadFeedLatestRun | null): RunId | null {
|
||||
if (!latestRun) return null;
|
||||
return latestRun.completedAt === null ||
|
||||
latestRun.status === "preparing" ||
|
||||
latestRun.status === "starting" ||
|
||||
latestRun.status === "running" ||
|
||||
latestRun.status === "waiting"
|
||||
? latestRun.runId
|
||||
: null;
|
||||
return threadFeedRunIsUnsettled(latestRun) ? latestRun.runId : null;
|
||||
}
|
||||
|
||||
export function threadFeedRunIsUnsettled(
|
||||
run: ThreadFeedLatestRun | null,
|
||||
): run is ThreadFeedLatestRun {
|
||||
return (
|
||||
run !== null &&
|
||||
(run.status === "preparing" ||
|
||||
run.status === "starting" ||
|
||||
run.status === "running" ||
|
||||
run.status === "waiting")
|
||||
);
|
||||
}
|
||||
|
||||
interface ThreadFeedRunFold {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import { threadRuntimeIsActive } from "@t3tools/client-runtime/state/shell";
|
||||
import {
|
||||
deriveLatestThreadRun,
|
||||
deriveThreadActivityRun,
|
||||
deriveThreadRuntime,
|
||||
} from "@t3tools/client-runtime/state/thread-execution";
|
||||
import { useCallback, useEffect, useMemo } from "react";
|
||||
@@ -118,10 +118,10 @@ export function useThreadComposerState() {
|
||||
: (selectedThreadShell?.runtime ?? null),
|
||||
[selectedThreadProjection, selectedThreadShell?.runtime],
|
||||
);
|
||||
const selectedThreadLatestRun = useMemo(
|
||||
const selectedThreadActivityRun = useMemo(
|
||||
() =>
|
||||
selectedThreadProjection
|
||||
? deriveLatestThreadRun(selectedThreadProjection.projection)
|
||||
? deriveThreadActivityRun(selectedThreadProjection.projection)
|
||||
: (selectedThreadShell?.latestRun ?? null),
|
||||
[selectedThreadProjection, selectedThreadShell?.latestRun],
|
||||
);
|
||||
@@ -141,10 +141,15 @@ export function useThreadComposerState() {
|
||||
if (!selectedThreadShell) {
|
||||
return null;
|
||||
}
|
||||
return deriveActiveWorkStartedAt(selectedThreadLatestRun, selectedThreadSessionActivity, null);
|
||||
}, [selectedThreadLatestRun, selectedThreadSessionActivity, selectedThreadShell]);
|
||||
return deriveActiveWorkStartedAt(
|
||||
selectedThreadActivityRun,
|
||||
selectedThreadSessionActivity,
|
||||
null,
|
||||
);
|
||||
}, [selectedThreadActivityRun, selectedThreadSessionActivity, selectedThreadShell]);
|
||||
|
||||
const activeThreadBusy = threadRuntimeIsActive(selectedThreadRuntime);
|
||||
const interruptibleRunId = selectedThreadRuntime?.activeRunId ?? null;
|
||||
|
||||
const onSendMessage = useCallback(async () => {
|
||||
if (!selectedThreadShell) {
|
||||
@@ -305,6 +310,7 @@ export function useThreadComposerState() {
|
||||
|
||||
return {
|
||||
selectedThreadFeed,
|
||||
selectedThreadActivityRun,
|
||||
selectedThreadQueueCount,
|
||||
activeWorkStartedAt,
|
||||
draftMessage,
|
||||
@@ -313,6 +319,7 @@ export function useThreadComposerState() {
|
||||
runtimeMode,
|
||||
interactionMode,
|
||||
activeThreadBusy,
|
||||
interruptibleRunId,
|
||||
onChangeDraftMessage,
|
||||
onPickDraftImages,
|
||||
onPasteIntoDraft,
|
||||
|
||||
@@ -124,13 +124,13 @@ it.layer(TestLayer)("ProjectionStoreV2", (it) => {
|
||||
id: providerSessionId,
|
||||
driver,
|
||||
providerInstanceId,
|
||||
status: "ready" as const,
|
||||
status: "error" as const,
|
||||
cwd: "/workspace",
|
||||
model: modelSelection.model,
|
||||
capabilities: CodexProviderCapabilitiesV2,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
lastError: null,
|
||||
lastError: "provider process exited",
|
||||
};
|
||||
|
||||
yield* projectionStore.apply({
|
||||
@@ -174,6 +174,16 @@ it.layer(TestLayer)("ProjectionStoreV2", (it) => {
|
||||
),
|
||||
[providerSessionId],
|
||||
);
|
||||
assert.deepEqual(
|
||||
(yield* projectionStore.getShellSnapshot()).threads.map((thread) => ({
|
||||
id: thread.id,
|
||||
lastError: thread.lastError,
|
||||
})),
|
||||
[
|
||||
{ id: firstThreadId, lastError: "provider process exited" },
|
||||
{ id: secondThreadId, lastError: "provider process exited" },
|
||||
],
|
||||
);
|
||||
|
||||
yield* projectionStore.apply({
|
||||
id: EventId.make("event:projection-shared-provider-session:first-detached"),
|
||||
|
||||
@@ -390,6 +390,7 @@ type ShellThreadRow = {
|
||||
readonly latest_run_id: string | null;
|
||||
readonly latest_run_status: string | null;
|
||||
readonly active_run_id: string | null;
|
||||
readonly last_error: string | null;
|
||||
readonly pending_request_payload_json: string | null;
|
||||
readonly latest_message_payload_json: string | null;
|
||||
readonly latest_user_message_at: string | null;
|
||||
@@ -767,6 +768,13 @@ export function threadShellFromProjection(
|
||||
(left, right) =>
|
||||
DateTime.toEpochMillis(right.updatedAt) - DateTime.toEpochMillis(left.updatedAt),
|
||||
)[0] ?? null;
|
||||
const providerSession =
|
||||
projection.providerSessions
|
||||
.filter((session) => session.providerInstanceId === projection.thread.providerInstanceId)
|
||||
.toSorted(
|
||||
(left, right) =>
|
||||
DateTime.toEpochMillis(right.updatedAt) - DateTime.toEpochMillis(left.updatedAt),
|
||||
)[0] ?? null;
|
||||
return {
|
||||
createdBy: projection.thread.createdBy,
|
||||
creationSource: projection.thread.creationSource,
|
||||
@@ -788,6 +796,7 @@ export function threadShellFromProjection(
|
||||
latestRunId: latestRun?.id ?? null,
|
||||
activeRunId: activeRun?.id ?? null,
|
||||
status: latestRun?.status ?? "idle",
|
||||
lastError: providerSession?.lastError ?? null,
|
||||
pendingRuntimeRequest:
|
||||
pendingRuntimeRequest === null
|
||||
? null
|
||||
@@ -836,6 +845,7 @@ type ShellThreadState = {
|
||||
readonly latestRunId: RunId | null;
|
||||
readonly latestRunStatus: OrchestrationV2ShellThreadStatus;
|
||||
readonly activeRunId: RunId | null;
|
||||
readonly lastError: string | null;
|
||||
readonly pendingRuntimeRequest: OrchestrationV2ThreadProjection["runtimeRequests"][number] | null;
|
||||
readonly latestVisibleMessage: OrchestrationV2ConversationMessage | null;
|
||||
readonly latestUserMessageAt: DateTime.Utc | null;
|
||||
@@ -953,6 +963,7 @@ function shellFromState(input: {
|
||||
latestRunId: input.state.latestRunId,
|
||||
activeRunId: input.state.activeRunId,
|
||||
status: input.state.latestRunStatus,
|
||||
lastError: input.state.lastError,
|
||||
pendingRuntimeRequest:
|
||||
input.state.pendingRuntimeRequest === null
|
||||
? null
|
||||
@@ -2099,6 +2110,16 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
|
||||
ORDER BY r.ordinal DESC, r.run_id DESC
|
||||
LIMIT 1
|
||||
) AS active_run_id,
|
||||
(
|
||||
SELECT json_extract(session.payload_json, '$.lastError')
|
||||
FROM orchestration_v2_projection_provider_sessions session
|
||||
INNER JOIN orchestration_v2_projection_provider_session_bindings binding
|
||||
ON binding.provider_session_id = session.provider_session_id
|
||||
WHERE binding.thread_id = t.thread_id
|
||||
AND session.provider_instance_id = t.provider_instance_id
|
||||
ORDER BY session.updated_at DESC, session.provider_session_id DESC
|
||||
LIMIT 1
|
||||
) AS last_error,
|
||||
(
|
||||
SELECT request.payload_json
|
||||
FROM orchestration_v2_projection_runtime_requests request
|
||||
@@ -2193,6 +2214,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
|
||||
latestRunId: row.latest_run_id === null ? null : RunId.make(row.latest_run_id),
|
||||
latestRunStatus: shellStatusFromStoredRunStatus(row.latest_run_status),
|
||||
activeRunId: row.active_run_id === null ? null : RunId.make(row.active_run_id),
|
||||
lastError: row.last_error,
|
||||
pendingRuntimeRequest,
|
||||
latestVisibleMessage,
|
||||
latestUserMessageAt:
|
||||
|
||||
@@ -68,6 +68,21 @@ describe("V2 client presentation", () => {
|
||||
expect(shell.source).toBe(v2ThreadShell);
|
||||
});
|
||||
|
||||
it("presents provider errors carried by failed thread shells", () => {
|
||||
const runId = RunId.make("run-failed");
|
||||
const shell = presentThreadShell(environmentId, {
|
||||
...v2ThreadShell,
|
||||
latestRunId: runId,
|
||||
status: "failed",
|
||||
lastError: "provider process exited",
|
||||
});
|
||||
|
||||
expect(shell.runtime).toMatchObject({
|
||||
status: "failed",
|
||||
lastError: "provider process exited",
|
||||
});
|
||||
});
|
||||
|
||||
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");
|
||||
|
||||
@@ -124,7 +124,7 @@ function shellRuntime(thread: OrchestrationV2ThreadShell): ThreadRuntimeSummary
|
||||
activeRunId: thread.activeRunId,
|
||||
providerInstanceId: thread.providerInstanceId,
|
||||
providerName: null,
|
||||
lastError: null,
|
||||
lastError: thread.lastError ?? null,
|
||||
updatedAt: iso(thread.updatedAt),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
import { MessageId, RunId, type OrchestrationV2RunStatus } from "@t3tools/contracts";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { v2Projection } from "./orchestrationV2TestFixtures.ts";
|
||||
import {
|
||||
deriveLatestThreadRun,
|
||||
deriveThreadActivityRun,
|
||||
deriveThreadRuntime,
|
||||
threadRuntimeHasInterruptibleRun,
|
||||
} from "./threadExecution.ts";
|
||||
|
||||
const now = DateTime.makeUnsafe("2026-07-28T10:00:00.000Z");
|
||||
|
||||
function run(id: string, ordinal: number, status: OrchestrationV2RunStatus) {
|
||||
return {
|
||||
id: RunId.make(id),
|
||||
threadId: v2Projection.thread.id,
|
||||
ordinal,
|
||||
providerInstanceId: v2Projection.thread.providerInstanceId,
|
||||
modelSelection: v2Projection.thread.modelSelection,
|
||||
providerThreadId: null,
|
||||
userMessageId: MessageId.make(`message-${id}`),
|
||||
rootNodeId: null,
|
||||
activeAttemptId: null,
|
||||
status,
|
||||
requestedAt: now,
|
||||
startedAt: status === "queued" ? null : now,
|
||||
completedAt: null,
|
||||
checkpointId: null,
|
||||
contextHandoffId: null,
|
||||
};
|
||||
}
|
||||
|
||||
describe("thread execution presentation", () => {
|
||||
it("keeps live activity attached to an executing run when a newer run is queued", () => {
|
||||
const runningRun = run("run-running", 1, "running");
|
||||
const queuedRun = run("run-queued", 2, "queued");
|
||||
const projection = { ...v2Projection, runs: [queuedRun, runningRun], updatedAt: now };
|
||||
|
||||
expect(deriveLatestThreadRun(projection)?.runId).toBe(queuedRun.id);
|
||||
expect(deriveThreadActivityRun(projection)).toMatchObject({
|
||||
runId: runningRun.id,
|
||||
status: "running",
|
||||
});
|
||||
|
||||
const runtime = deriveThreadRuntime(projection);
|
||||
expect(runtime).toMatchObject({
|
||||
status: "queued",
|
||||
activeRunId: runningRun.id,
|
||||
});
|
||||
expect(threadRuntimeHasInterruptibleRun(runtime)).toBe(true);
|
||||
});
|
||||
|
||||
it("does not expose a queued-only run as interruptible", () => {
|
||||
const queuedRun = run("run-queued", 1, "queued");
|
||||
const projection = { ...v2Projection, runs: [queuedRun], updatedAt: now };
|
||||
|
||||
expect(deriveThreadActivityRun(projection)).toMatchObject({
|
||||
runId: queuedRun.id,
|
||||
status: "queued",
|
||||
});
|
||||
|
||||
const runtime = deriveThreadRuntime(projection);
|
||||
expect(runtime).toMatchObject({
|
||||
status: "queued",
|
||||
activeRunId: null,
|
||||
});
|
||||
expect(threadRuntimeHasInterruptibleRun(runtime)).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -3,17 +3,25 @@ import * as DateTime from "effect/DateTime";
|
||||
|
||||
import type { ThreadRunSummary, ThreadRuntimeSummary } from "./models.ts";
|
||||
|
||||
const ACTIVE_RUN_STATUSES = new Set(["preparing", "queued", "starting", "running", "waiting"]);
|
||||
const INTERRUPTIBLE_RUN_STATUSES = new Set(["preparing", "starting", "running", "waiting"]);
|
||||
|
||||
export function deriveLatestThreadRun(
|
||||
function latestMatchingRun(
|
||||
projection: OrchestrationV2ThreadProjection,
|
||||
): ThreadRunSummary | null {
|
||||
const run = projection.runs.reduce<(typeof projection.runs)[number] | null>(
|
||||
predicate: (run: OrchestrationV2ThreadProjection["runs"][number]) => boolean,
|
||||
): OrchestrationV2ThreadProjection["runs"][number] | null {
|
||||
return projection.runs.reduce<OrchestrationV2ThreadProjection["runs"][number] | null>(
|
||||
(latest, candidate) =>
|
||||
latest === null || candidate.ordinal > latest.ordinal ? candidate : latest,
|
||||
predicate(candidate) && (latest === null || candidate.ordinal > latest.ordinal)
|
||||
? candidate
|
||||
: latest,
|
||||
null,
|
||||
);
|
||||
if (run === null) return null;
|
||||
}
|
||||
|
||||
function summarizeThreadRun(
|
||||
projection: OrchestrationV2ThreadProjection,
|
||||
run: OrchestrationV2ThreadProjection["runs"][number],
|
||||
): ThreadRunSummary {
|
||||
return {
|
||||
runId: run.id,
|
||||
status: run.status,
|
||||
@@ -28,6 +36,28 @@ export function deriveLatestThreadRun(
|
||||
};
|
||||
}
|
||||
|
||||
export function deriveLatestThreadRun(
|
||||
projection: OrchestrationV2ThreadProjection,
|
||||
): ThreadRunSummary | null {
|
||||
const run = latestMatchingRun(projection, () => true);
|
||||
return run === null ? null : summarizeThreadRun(projection, run);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the run that owns live provider work, falling back to the newest run
|
||||
* once the thread is idle. A newer queued run must not make an older executing
|
||||
* run look settled in clients that render per-run activity.
|
||||
*/
|
||||
export function deriveThreadActivityRun(
|
||||
projection: OrchestrationV2ThreadProjection,
|
||||
): ThreadRunSummary | null {
|
||||
const run =
|
||||
latestMatchingRun(projection, (candidate) =>
|
||||
INTERRUPTIBLE_RUN_STATUSES.has(candidate.status),
|
||||
) ?? latestMatchingRun(projection, () => true);
|
||||
return run === null ? null : summarizeThreadRun(projection, run);
|
||||
}
|
||||
|
||||
export function deriveThreadRuntime(
|
||||
projection: OrchestrationV2ThreadProjection,
|
||||
): ThreadRuntimeSummary | null {
|
||||
@@ -37,7 +67,7 @@ export function deriveThreadRuntime(
|
||||
);
|
||||
if (latestRun === null && projection.thread.activeProviderThreadId === null) return null;
|
||||
const activeRunId =
|
||||
projection.runs.findLast((run) => ACTIVE_RUN_STATUSES.has(run.status))?.id ?? null;
|
||||
latestMatchingRun(projection, (run) => INTERRUPTIBLE_RUN_STATUSES.has(run.status))?.id ?? null;
|
||||
return {
|
||||
status: latestRun?.status ?? "idle",
|
||||
activeRunId,
|
||||
@@ -47,3 +77,9 @@ export function deriveThreadRuntime(
|
||||
updatedAt: DateTime.formatIso(projection.updatedAt),
|
||||
};
|
||||
}
|
||||
|
||||
export function threadRuntimeHasInterruptibleRun(
|
||||
runtime: ThreadRuntimeSummary | null | undefined,
|
||||
): boolean {
|
||||
return runtime?.activeRunId !== null && runtime?.activeRunId !== undefined;
|
||||
}
|
||||
@@ -1178,6 +1178,7 @@ export const OrchestrationV2ThreadShell = Schema.Struct({
|
||||
latestRunId: Schema.NullOr(RunId),
|
||||
activeRunId: Schema.NullOr(RunId),
|
||||
status: OrchestrationV2ShellThreadStatus,
|
||||
lastError: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
pendingRuntimeRequest: Schema.NullOr(OrchestrationV2PendingRuntimeRequestSummary),
|
||||
latestVisibleMessage: Schema.NullOr(OrchestrationV2LatestVisibleMessageSummary),
|
||||
latestUserMessageAt: Schema.NullOr(Schema.DateTimeUtc),
|
||||
|
||||
Reference in new issue
Block a user