Expose V2 thread workflows on mobile

Co-authored-by: codex <[email protected]>
This commit is contained in:
Julius Marmingeandcodex authored and maria-rcks committed 2026-08-03 11:45:06 -04:00
1 parent 2fde64e80f
commit beab58b45b
16 files changed
+1025 -218

No files matched your search

@@ -0,0 +1,154 @@
import { describe, expect, it } from "vite-plus/test";
import { ThreadId } from "@t3tools/contracts";
import {
deriveThreadRelationshipGraph,
immediateThreadRelationships,
relatedThreadIds,
resolveMergeBackTargetThreadId,
walkThreadRelationships,
} from "./threadRelationships.ts";
describe("thread relationships", () => {
it("keeps missing parents and cycles navigable without recursive traversal", () => {
const root = ThreadId.make("thread-root");
const child = ThreadId.make("thread-child");
const missing = ThreadId.make("thread-missing");
const graph = deriveThreadRelationshipGraph({
threads: [
{
id: root,
title: "Root",
status: "completed",
forkedFrom: { type: "run", threadId: child, runId: "run-cycle" },
lineage: { rootThreadId: root, parentThreadId: child, relationshipToParent: "fork" },
},
{
id: child,
title: "Child",
status: "completed",
forkedFrom: { type: "run", threadId: missing, runId: "run-missing" },
lineage: { rootThreadId: root, parentThreadId: missing, relationshipToParent: "fork" },
},
] as never,
projection: null,
});
expect(graph.nodes.get(missing)?.missing).toBe(true);
expect(relatedThreadIds(graph, root)).toEqual([child]);
expect(relatedThreadIds(graph, child)).toEqual([root, missing]);
expect(
walkThreadRelationships(graph, root).map(({ threadId, depth }) => [threadId, depth]),
).toEqual([
[child, 1],
[missing, 2],
]);
expect(immediateThreadRelationships(graph, root).map(({ threadId }) => threadId)).toEqual([
child,
]);
});
it("combines subagent and transfer edges with archived shell state", () => {
const parent = ThreadId.make("thread-parent");
const child = ThreadId.make("thread-child");
const transferTarget = ThreadId.make("thread-transfer");
const graph = deriveThreadRelationshipGraph({
threads: [
{
id: parent,
title: "Parent",
status: "completed",
archivedAt: null,
forkedFrom: null,
lineage: { rootThreadId: parent, parentThreadId: null, relationshipToParent: null },
},
{
id: child,
title: "Subagent",
status: "completed",
archivedAt: "2026-06-24T00:00:00.000Z",
forkedFrom: null,
lineage: {
rootThreadId: parent,
parentThreadId: parent,
relationshipToParent: "subagent",
},
},
] as never,
projection: {
thread: { id: parent },
subagents: [{ childThreadId: child, status: "completed" }],
contextTransfers: [
{
sourceThreadId: child,
targetThreadId: transferTarget,
status: "completed",
},
],
} as never,
});
expect(graph.nodes.get(child)?.thread?.archivedAt).not.toBeNull();
expect(graph.nodes.get(transferTarget)?.missing).toBe(true);
expect(graph.edges).toEqual(
expect.arrayContaining([
expect.objectContaining({
sourceThreadId: parent,
targetThreadId: child,
kind: "subagent",
}),
expect.objectContaining({
sourceThreadId: child,
targetThreadId: transferTarget,
kind: "transfer",
}),
]),
);
});
it("resolves merge-back only for forks and prefers the recorded fork source", () => {
const source = ThreadId.make("thread-source");
const fallbackParent = ThreadId.make("thread-parent");
const fork = ThreadId.make("thread-fork");
expect(
resolveMergeBackTargetThreadId({
thread: {
id: fork,
forkedFrom: { type: "run", threadId: source, runId: "run-source" },
lineage: {
rootThreadId: source,
parentThreadId: fallbackParent,
relationshipToParent: "fork",
},
},
} as never),
).toBe(source);
expect(
resolveMergeBackTargetThreadId({
thread: {
id: fork,
forkedFrom: null,
lineage: {
rootThreadId: source,
parentThreadId: fallbackParent,
relationshipToParent: "fork",
},
},
} as never),
).toBe(fallbackParent);
expect(
resolveMergeBackTargetThreadId({
thread: {
id: fork,
forkedFrom: null,
lineage: {
rootThreadId: source,
parentThreadId: fallbackParent,
relationshipToParent: "subagent",
},
},
} as never),
).toBeNull();
});
});
@@ -0,0 +1,170 @@
import type {
OrchestrationV2ThreadProjection,
OrchestrationV2ThreadShell,
ThreadId,
} from "@t3tools/contracts";
export type ThreadRelationshipKind = "parent" | "fork" | "subagent" | "transfer";
export interface ThreadRelationshipNode {
readonly threadId: ThreadId;
readonly thread: OrchestrationV2ThreadShell | null;
readonly missing: boolean;
}
export interface ThreadRelationshipEdge {
readonly sourceThreadId: ThreadId;
readonly targetThreadId: ThreadId;
readonly kind: ThreadRelationshipKind;
readonly status: string | null;
}
export interface ThreadRelationshipGraph {
readonly nodes: ReadonlyMap<ThreadId, ThreadRelationshipNode>;
readonly edges: ReadonlyArray<ThreadRelationshipEdge>;
}
export interface ThreadRelationshipWalkRow {
readonly threadId: ThreadId;
readonly fromThreadId: ThreadId;
readonly depth: number;
readonly edge: ThreadRelationshipEdge;
}
export function resolveMergeBackTargetThreadId(
projection: Pick<OrchestrationV2ThreadProjection, "thread"> | null,
): ThreadId | null {
if (projection?.thread.lineage.relationshipToParent !== "fork") return null;
return projection.thread.forkedFrom?.type === "run"
? projection.thread.forkedFrom.threadId
: projection.thread.lineage.parentThreadId;
}
function edgeKey(edge: ThreadRelationshipEdge): string {
return `${edge.sourceThreadId}\u001f${edge.targetThreadId}\u001f${edge.kind}`;
}
export function deriveThreadRelationshipGraph(input: {
readonly threads: ReadonlyArray<OrchestrationV2ThreadShell>;
readonly projection: OrchestrationV2ThreadProjection | null;
}): ThreadRelationshipGraph {
const nodes = new Map<ThreadId, ThreadRelationshipNode>(
input.threads.map(
(thread) => [thread.id, { threadId: thread.id, thread, missing: false }] as const,
),
);
const edgesByKey = new Map<string, ThreadRelationshipEdge>();
const ensureNode = (threadId: ThreadId) => {
if (!nodes.has(threadId)) {
nodes.set(threadId, { threadId, thread: null, missing: true });
}
};
const addEdge = (edge: ThreadRelationshipEdge) => {
ensureNode(edge.sourceThreadId);
ensureNode(edge.targetThreadId);
edgesByKey.set(edgeKey(edge), edge);
};
for (const thread of input.threads) {
const parentThreadId =
thread.forkedFrom?.type === "run"
? thread.forkedFrom.threadId
: thread.lineage.parentThreadId;
if (parentThreadId === null) continue;
addEdge({
sourceThreadId: parentThreadId,
targetThreadId: thread.id,
kind: thread.lineage.relationshipToParent === "subagent" ? "subagent" : "fork",
status: thread.status,
});
}
if (input.projection !== null) {
const ownerThreadId = input.projection.thread.id;
for (const subagent of input.projection.subagents) {
if (subagent.childThreadId === null) continue;
addEdge({
sourceThreadId: ownerThreadId,
targetThreadId: subagent.childThreadId,
kind: "subagent",
status: subagent.status,
});
}
for (const transfer of input.projection.contextTransfers) {
if (transfer.sourceThreadId === transfer.targetThreadId) continue;
addEdge({
sourceThreadId: transfer.sourceThreadId,
targetThreadId: transfer.targetThreadId,
kind: "transfer",
status: transfer.status,
});
}
}
return { nodes, edges: [...edgesByKey.values()] };
}
export function relatedThreadIds(
graph: ThreadRelationshipGraph,
threadId: ThreadId,
): ReadonlyArray<ThreadId> {
const ids = new Set<ThreadId>();
for (const edge of graph.edges) {
if (edge.sourceThreadId === threadId) ids.add(edge.targetThreadId);
if (edge.targetThreadId === threadId) ids.add(edge.sourceThreadId);
}
return [...ids];
}
export function walkThreadRelationships(
graph: ThreadRelationshipGraph,
threadId: ThreadId,
): ReadonlyArray<ThreadRelationshipWalkRow> {
const visited = new Set<ThreadId>([threadId]);
const pending: Array<{ readonly threadId: ThreadId; readonly depth: number }> = [
{ threadId, depth: 0 },
];
const rows: ThreadRelationshipWalkRow[] = [];
for (let index = 0; index < pending.length; index += 1) {
const current = pending[index];
if (current === undefined) continue;
for (const edge of graph.edges) {
const relatedId =
edge.sourceThreadId === current.threadId
? edge.targetThreadId
: edge.targetThreadId === current.threadId
? edge.sourceThreadId
: null;
if (relatedId === null || visited.has(relatedId)) continue;
visited.add(relatedId);
const depth = current.depth + 1;
rows.push({ threadId: relatedId, fromThreadId: current.threadId, depth, edge });
pending.push({ threadId: relatedId, depth });
}
}
return rows;
}
export function immediateThreadRelationships(
graph: ThreadRelationshipGraph,
threadId: ThreadId,
): ReadonlyArray<ThreadRelationshipWalkRow> {
const visited = new Set<ThreadId>();
const rows: ThreadRelationshipWalkRow[] = [];
for (const edge of graph.edges) {
const relatedId =
edge.sourceThreadId === threadId
? edge.targetThreadId
: edge.targetThreadId === threadId
? edge.sourceThreadId
: null;
if (relatedId === null || visited.has(relatedId)) continue;
visited.add(relatedId);
rows.push({ threadId: relatedId, fromThreadId: threadId, depth: 1, edge });
}
return rows;
}
@@ -0,0 +1,133 @@
import { describe, expect, it } from "vite-plus/test";
import {
canDetachThreadProviderSession,
canForkProjectedAssistantItem,
deriveThreadQueueWorkflowState,
} from "./threadWorkflows.ts";
const capabilities = (input?: {
readonly queued?: boolean;
readonly steer?: boolean;
readonly restartSteer?: boolean;
readonly nativeFork?: boolean;
readonly portableFork?: boolean;
}) =>
({
turns: {
supportsQueuedMessages: input?.queued ?? false,
supportsActiveSteering: input?.steer ?? false,
supportsSteeringByInterruptRestart: input?.restartSteer ?? false,
},
threads: {
canForkThread: input?.nativeFork ?? false,
canForkFromTurn: input?.nativeFork ?? false,
},
identity: { nativeThreadIds: input?.nativeFork ? "strong" : "none" },
context: { supportsFullThreadHandoff: input?.portableFork ?? false },
}) as never;
describe("thread workflows", () => {
it("sorts queued messages and gates reorder and promotion from capabilities", () => {
const state = deriveThreadQueueWorkflowState({
thread: { id: "thread", activeProviderThreadId: "provider-thread" },
runs: [
{ id: "active", status: "running", providerThreadId: "provider-thread", ordinal: 1 },
{ id: "later", status: "queued", userMessageId: "message-later", ordinal: 3 },
{
id: "first",
status: "queued",
userMessageId: "message-first",
ordinal: 2,
queuePosition: 1,
},
],
messages: [
{ id: "message-first", text: "First" },
{ id: "message-later", text: "Later" },
],
providerThreads: [
{
id: "provider-thread",
appThreadId: "thread",
providerSessionId: "provider-session",
},
],
providerSessions: [
{
id: "provider-session",
status: "running",
capabilities: capabilities({ queued: true, restartSteer: true }),
},
],
} as never);
expect(state.queuedRuns.map(({ run, text }) => [run.id, text])).toEqual([
["first", "First"],
["later", "Later"],
]);
expect(state.activeRun?.id).toBe("active");
expect(state.canReorder).toBe(true);
expect(state.canPromoteToSteer).toBe(true);
});
it("does not expose known unsupported queue or fork actions", () => {
const projection = {
thread: { id: "thread", activeProviderThreadId: "provider-thread" },
runs: [{ id: "queued", status: "queued", userMessageId: "message", ordinal: 1 }],
messages: [],
providerThreads: [
{
id: "provider-thread",
appThreadId: "thread",
providerSessionId: "provider-session",
},
],
providerSessions: [
{
id: "provider-session",
status: "ready",
capabilities: capabilities(),
},
],
} as never;
const queue = deriveThreadQueueWorkflowState(projection);
const projectedItem = {
item: { type: "assistant_message", runId: "run", status: "completed" },
} as never;
expect(queue.canReorder).toBe(false);
expect(queue.canPromoteToSteer).toBe(false);
expect(canForkProjectedAssistantItem({ projectedItem, capabilities: capabilities() })).toBe(
false,
);
expect(canDetachThreadProviderSession(projection)).toBe(true);
});
it("allows native, portable, and capability-unknown exact-run forks", () => {
const projectedItem = {
item: { type: "assistant_message", runId: "run", status: "completed" },
} as never;
expect(
canForkProjectedAssistantItem({
projectedItem,
capabilities: capabilities({ nativeFork: true }),
}),
).toBe(true);
expect(
canForkProjectedAssistantItem({
projectedItem,
capabilities: capabilities({ portableFork: true }),
}),
).toBe(true);
expect(canForkProjectedAssistantItem({ projectedItem })).toBe(true);
expect(
canForkProjectedAssistantItem({
projectedItem: {
item: { type: "assistant_message", runId: "run", status: "running" },
} as never,
}),
).toBe(false);
});
});
@@ -0,0 +1,107 @@
import type {
OrchestrationV2ProjectedTurnItem,
OrchestrationV2ProviderCapabilities,
OrchestrationV2ThreadProjection,
} from "@t3tools/contracts";
type Projection = OrchestrationV2ThreadProjection;
type Run = Projection["runs"][number];
type ProviderSession = Projection["providerSessions"][number];
const ACTIVE_RUN_STATUSES = new Set<Run["status"]>(["preparing", "starting", "running", "waiting"]);
export interface QueuedThreadRun {
readonly run: Run;
readonly text: string;
}
export interface ThreadQueueWorkflowState {
readonly activeRun: Run | null;
readonly queuedRuns: ReadonlyArray<QueuedThreadRun>;
readonly canReorder: boolean;
readonly canPromoteToSteer: boolean;
}
export function resolveActiveThreadRun(projection: Projection): Run | null {
return projection.runs.findLast((run) => ACTIVE_RUN_STATUSES.has(run.status)) ?? null;
}
export function resolveThreadProviderSession(projection: Projection): ProviderSession | null {
const activeRun = resolveActiveThreadRun(projection);
const providerThreadId = activeRun?.providerThreadId ?? projection.thread.activeProviderThreadId;
const activeProviderThread =
providerThreadId === null
? null
: (projection.providerThreads.find((thread) => thread.id === providerThreadId) ?? null);
const attachedProviderThread =
activeProviderThread ??
projection.providerThreads.find(
(thread) => thread.appThreadId === projection.thread.id && thread.providerSessionId !== null,
) ??
null;
const sessionId = attachedProviderThread?.providerSessionId ?? null;
if (sessionId !== null) {
return projection.providerSessions.find((session) => session.id === sessionId) ?? null;
}
return (
projection.providerSessions.findLast(
(session) => session.status !== "stopped" && session.status !== "error",
) ?? null
);
}
export function deriveThreadQueueWorkflowState(projection: Projection): ThreadQueueWorkflowState {
const activeRun = resolveActiveThreadRun(projection);
const session = resolveThreadProviderSession(projection);
const capabilities = session?.capabilities.turns;
const queuedRuns = projection.runs
.filter((run) => run.status === "queued")
.toSorted(
(left, right) =>
(left.queuePosition ?? left.ordinal) - (right.queuePosition ?? right.ordinal) ||
left.ordinal - right.ordinal,
)
.map((run) => ({
run,
text:
projection.messages.find((message) => message.id === run.userMessageId)?.text ??
"Queued message",
}));
return {
activeRun,
queuedRuns,
canReorder: capabilities?.supportsQueuedMessages === true,
canPromoteToSteer:
activeRun !== null &&
(capabilities?.supportsActiveSteering === true ||
capabilities?.supportsSteeringByInterruptRestart === true),
};
}
export function canForkProjectedAssistantItem(input: {
readonly projectedItem: OrchestrationV2ProjectedTurnItem;
readonly capabilities?: OrchestrationV2ProviderCapabilities | undefined;
}): boolean {
const item = input.projectedItem.item;
if (item.type !== "assistant_message" || item.runId === null || item.status !== "completed") {
return false;
}
if (input.capabilities === undefined) {
// Historical and inherited rows may outlive their provider-session record.
// Keep the portable server-side fallback available when capability evidence
// is absent; a known incapable provider is rejected below.
return true;
}
const capabilities = input.capabilities;
const canForkNatively =
capabilities.threads.canForkThread &&
capabilities.threads.canForkFromTurn &&
capabilities.identity.nativeThreadIds === "strong";
return canForkNatively || capabilities.context.supportsFullThreadHandoff;
}
export function canDetachThreadProviderSession(projection: Projection): boolean {
const session = resolveThreadProviderSession(projection);
return session !== null && session.status !== "stopped" && session.status !== "error";
}