From 5ad0e23e5f8a46d7a12f2c3595f46aa2fe964c1d Mon Sep 17 00:00:00 2001 From: Lautaro Caballero Date: Fri, 13 Nov 2026 16:51:39 -0300 Subject: [PATCH 01/16] feat(web): show thread and subagent tasks and usage --- apps/server/src/auth/RpcAuthorization.test.ts | 7 +- apps/server/src/auth/RpcAuthorization.ts | 1 + .../src/environment/ServerEnvironment.ts | 1 + .../src/observability/RpcInstrumentation.ts | 1 + .../src/orchestration-v2/ProjectionStore.ts | 101 +++--- .../ProviderTurnControlService.test.ts | 1 + .../ThreadInsightsQuery.test.ts | 321 ++++++++++++++++++ .../orchestration-v2/ThreadInsightsQuery.ts | 253 ++++++++++++++ apps/server/src/server.ts | 4 +- .../src/telemetry/ProviderUsageAnalytics.ts | 29 +- apps/server/src/usage/UsageService.ts | 27 +- apps/server/src/ws.test.ts | 2 + apps/server/src/ws.ts | 4 + apps/web/src/closedViewStore.ts | 6 + apps/web/src/components/RightPanelTabs.tsx | 4 + .../chat/RightPanelSurfaceContent.tsx | 9 + .../components/chat/ThreadDetailsPanel.tsx | 2 + .../components/chat/ThreadInsightsMenu.tsx | 38 +++ .../components/chat/ThreadInsightsPanel.tsx | 242 +++++++++++++ .../chat/ThreadLineageWorkflowRow.tsx | 16 +- ...hreadRelationshipsControl.browser.test.tsx | 1 + .../chat/ThreadRelationshipsControl.tsx | 10 + .../chat/TimelineUserMessageRow.tsx | 1 + .../src/components/chat/V2LifecycleRow.tsx | 92 +++-- .../components/chat/WorkflowOpeningBlock.tsx | 13 +- .../src/components/threadActionMenu.logic.ts | 11 + .../web/src/hooks/useThreadActionMenu.test.ts | 4 + apps/web/src/hooks/useThreadActionMenu.ts | 18 + apps/web/src/reopenClosedView.ts | 7 + apps/web/src/rightPanelStore.ts | 45 ++- apps/web/src/state/threadInsights.ts | 44 +++ docs/user/usage.md | 18 + packages/client-runtime/package.json | 4 + .../client-runtime/src/state/orchestration.ts | 6 + .../src/state/threadInsights.test.ts | 102 ++++++ .../src/state/threadInsights.ts | 89 +++++ packages/contracts/src/environment.ts | 1 + packages/contracts/src/orchestrationV2.ts | 48 +++ packages/contracts/src/rpc.ts | 10 + packages/contracts/src/server.ts | 1 + packages/shared/package.json | 4 + packages/shared/src/turnTokenUsage.ts | 31 ++ 42 files changed, 1515 insertions(+), 114 deletions(-) create mode 100644 apps/server/src/orchestration-v2/ThreadInsightsQuery.test.ts create mode 100644 apps/server/src/orchestration-v2/ThreadInsightsQuery.ts create mode 100644 apps/web/src/components/chat/ThreadInsightsMenu.tsx create mode 100644 apps/web/src/components/chat/ThreadInsightsPanel.tsx create mode 100644 apps/web/src/state/threadInsights.ts create mode 100644 packages/client-runtime/src/state/threadInsights.test.ts create mode 100644 packages/client-runtime/src/state/threadInsights.ts create mode 100644 packages/shared/src/turnTokenUsage.ts diff --git a/apps/server/src/auth/RpcAuthorization.test.ts b/apps/server/src/auth/RpcAuthorization.test.ts index 88596577db3c6..1cf2eefae4a9e 100644 --- a/apps/server/src/auth/RpcAuthorization.test.ts +++ b/apps/server/src/auth/RpcAuthorization.test.ts @@ -14,6 +14,7 @@ import { AuthSourceControlWriteScope, AuthTerminalReadScope, AuthTerminalOperateScope, + ORCHESTRATION_V2_WS_METHODS, WS_METHODS, WsRpcGroup, } from "@t3tools/contracts"; @@ -69,7 +70,11 @@ describe("RPC authorization scopes", () => { }); it("lets thread readers observe and refresh checkout branches", () => { - for (const method of [WS_METHODS.subscribeVcsBranch, WS_METHODS.vcsRefreshBranch]) { + for (const method of [ + WS_METHODS.subscribeVcsBranch, + WS_METHODS.vcsRefreshBranch, + ORCHESTRATION_V2_WS_METHODS.getThreadInsights, + ]) { expect(requiredScopeForRpcMethod(method)).toBe(AuthOrchestrationReadScope); } }); diff --git a/apps/server/src/auth/RpcAuthorization.ts b/apps/server/src/auth/RpcAuthorization.ts index 7823c3a146228..bc1288ebb40b8 100644 --- a/apps/server/src/auth/RpcAuthorization.ts +++ b/apps/server/src/auth/RpcAuthorization.ts @@ -42,6 +42,7 @@ export const RPC_REQUIRED_SCOPES = { [ORCHESTRATION_V2_WS_METHODS.dispatchCommand]: AuthOrchestrationOperateScope, [ORCHESTRATION_V2_WS_METHODS.getWorkflowScript]: AuthOrchestrationReadScope, [ORCHESTRATION_V2_WS_METHODS.getNativeChildWork]: AuthOrchestrationReadScope, + [ORCHESTRATION_V2_WS_METHODS.getThreadInsights]: AuthOrchestrationReadScope, [ORCHESTRATION_V2_WS_METHODS.stopWorkflow]: AuthOrchestrationOperateScope, [ORCHESTRATION_V2_WS_METHODS.forceStopThread]: AuthOrchestrationOperateScope, [ORCHESTRATION_V2_WS_METHODS.getTurnDiff]: AuthOrchestrationReadScope, diff --git a/apps/server/src/environment/ServerEnvironment.ts b/apps/server/src/environment/ServerEnvironment.ts index 2c79189878e8a..ff4ae6d343ccd 100644 --- a/apps/server/src/environment/ServerEnvironment.ts +++ b/apps/server/src/environment/ServerEnvironment.ts @@ -294,6 +294,7 @@ export const make = Effect.gen(function* () { linkFence: true, mcpApprovalCodes: true, mcpHostedApproval: true, + threadInsights: true, shellThreadFamilies: true, shellOlderSettled: true, }, diff --git a/apps/server/src/observability/RpcInstrumentation.ts b/apps/server/src/observability/RpcInstrumentation.ts index 3f120a39f1870..2e924f2017644 100644 --- a/apps/server/src/observability/RpcInstrumentation.ts +++ b/apps/server/src/observability/RpcInstrumentation.ts @@ -14,6 +14,7 @@ const RPC_AGGREGATES = { [ORCHESTRATION_V2_WS_METHODS.dispatchCommand]: "orchestrationV2", [ORCHESTRATION_V2_WS_METHODS.getWorkflowScript]: "orchestration", [ORCHESTRATION_V2_WS_METHODS.getNativeChildWork]: "orchestration", + [ORCHESTRATION_V2_WS_METHODS.getThreadInsights]: "orchestration", [ORCHESTRATION_V2_WS_METHODS.stopWorkflow]: "orchestration", [ORCHESTRATION_V2_WS_METHODS.forceStopThread]: "orchestration", [ORCHESTRATION_V2_WS_METHODS.getTurnItem]: "orchestration", diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index e90a82786953f..41798c3497d66 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -1,3 +1,4 @@ +import { PlanId } from "@t3tools/contracts"; import type { ProjectThreadAwarenessV2Input } from "@t3tools/shared/agentAwareness"; import { applyOrchestrationV2ThreadVisit, pendingGuestMessageCount } from "@t3tools/contracts"; import { applyThreadPullRequestLinkUpdate } from "../sourceControl/threadPullRequests.ts"; @@ -25,7 +26,6 @@ import type { OrchestrationV2ExecutionNode, OrchestrationV2PlanArtifact, OrchestrationV2PendingRuntimeRequestSummary, - PlanId, OrchestrationV2ConversationMessage, OrchestrationV2ContextTransfer, OrchestrationV2DomainEvent, @@ -665,6 +665,9 @@ export interface ProjectionStoreV2Shape { threadId: ThreadId, providerTurnId: ProviderTurnId, ) => Effect.Effect; + readonly getLatestTodoList: ( + threadId: ThreadId, + ) => Effect.Effect; readonly getPlan: ( threadId: ThreadId, planId: PlanId, @@ -3736,46 +3739,7 @@ export const layer: Layer.Layer = (field) => field === "plans" || field === "runs" || field === "providerThreads", )) ? [] - : yield* sql<{ - readonly plan_id: string; - readonly run_id: string; - readonly provider_thread_id: string | null; - readonly last_plan_id: string; - }>` - WITH latest_owner AS MATERIALIZED ( - SELECT plan.plan_id, owner.run_id, owner.provider_thread_id - FROM orchestration_v2_projection_plans AS plan - INNER JOIN orchestration_v2_projection_runs AS owner - ON owner.thread_id = plan.thread_id AND owner.run_id = plan.run_id - WHERE plan.thread_id = ${threadId} - AND plan.kind = 'todo_list' AND plan.status <> 'superseded' - ORDER BY owner.ordinal DESC, plan.plan_id DESC - LIMIT 1 - ) - SELECT COALESCE(CASE WHEN EXISTS ( - SELECT 1 FROM orchestration_v2_projection_plans - WHERE thread_id = ${threadId} AND run_id = owner.run_id - AND kind = 'todo_list' AND status <> 'superseded' - AND plan_id <> owner.plan_id - ) THEN ( - -- Plan UUIDs cannot order replacements within a run. - SELECT plan.plan_id - FROM orchestration_v2_projection_turn_items AS item - CROSS JOIN orchestration_v2_projection_plans AS plan - ON plan.plan_id = json_extract(item.payload_json, '$.planId') - WHERE item.run_id = owner.run_id AND item.thread_id = ${threadId} - AND item.type = 'todo_list' - AND plan.run_id = owner.run_id AND plan.thread_id = ${threadId} - AND plan.kind = 'todo_list' AND plan.status <> 'superseded' - ORDER BY item.ordinal DESC - LIMIT 1 - ) END, owner.plan_id) AS plan_id, owner.run_id, owner.provider_thread_id, - ( - SELECT MAX(plan_id) FROM orchestration_v2_projection_plans - WHERE thread_id = ${threadId} AND run_id = owner.run_id - ) AS last_plan_id - FROM latest_owner AS owner - `; + : yield* latestTodoOwner(threadId); const [ thread, @@ -5584,6 +5548,60 @@ export const layer: Layer.Layer = ) .pipe(Effect.mapError(controlReadError(threadId))); + const getLatestTodoList: ProjectionStoreV2Shape["getLatestTodoList"] = Effect.fn( + "ProjectionStore.getLatestTodoList", + )( + function* (threadId) { + const owners = yield* latestTodoOwner(threadId); + return owners[0] === undefined + ? undefined + : yield* getPlan(threadId, PlanId.make(owners[0].plan_id)); + }, + (effect, threadId) => effect.pipe(Effect.mapError(controlReadError(threadId))), + ); + + const latestTodoOwner = (threadId: ThreadId) => sql<{ + readonly plan_id: string; + readonly run_id: string; + readonly provider_thread_id: string | null; + readonly last_plan_id: string; + }>` + WITH latest_owner AS MATERIALIZED ( + SELECT plan.plan_id, owner.run_id, owner.provider_thread_id + FROM orchestration_v2_projection_plans AS plan + INNER JOIN orchestration_v2_projection_runs AS owner + ON owner.thread_id = plan.thread_id AND owner.run_id = plan.run_id + WHERE plan.thread_id = ${threadId} + AND plan.kind = 'todo_list' AND plan.status <> 'superseded' + AND owner.status <> 'rolled_back' + ORDER BY owner.ordinal DESC, plan.plan_id DESC + LIMIT 1 + ) + SELECT COALESCE(CASE WHEN EXISTS ( + SELECT 1 FROM orchestration_v2_projection_plans + WHERE thread_id = ${threadId} AND run_id = owner.run_id + AND kind = 'todo_list' AND status <> 'superseded' + AND plan_id <> owner.plan_id + ) THEN ( + -- Plan UUIDs cannot order replacements within a run. + SELECT plan.plan_id + FROM orchestration_v2_projection_turn_items AS item + CROSS JOIN orchestration_v2_projection_plans AS plan + ON plan.plan_id = json_extract(item.payload_json, '$.planId') + WHERE item.run_id = owner.run_id AND item.thread_id = ${threadId} + AND item.type = 'todo_list' + AND plan.run_id = owner.run_id AND plan.thread_id = ${threadId} + AND plan.kind = 'todo_list' AND plan.status <> 'superseded' + ORDER BY item.ordinal DESC + LIMIT 1 + ) END, owner.plan_id) AS plan_id, owner.run_id, owner.provider_thread_id, + ( + SELECT MAX(plan_id) FROM orchestration_v2_projection_plans + WHERE thread_id = ${threadId} AND run_id = owner.run_id + ) AS last_plan_id + FROM latest_owner AS owner + `; + const getPlan: ProjectionStoreV2Shape["getPlan"] = (threadId, planId) => sql .withTransaction( @@ -9019,6 +9037,7 @@ export const layer: Layer.Layer = getThreadRecords(threadId, fields, filter).pipe(NodeSqliteClient.readOnly), getRuntimeRequest: readOnReader(getRuntimeRequest), getPlan: readOnReader(getPlan), + getLatestTodoList: readOnReader(getLatestTodoList), getProviderControlContext: readOnReader(getProviderControlContext), getLimitRecoveryCandidates: readOnReader(getLimitRecoveryCandidates), getLimitRecoveryWakeAt: readOnReader(getLimitRecoveryWakeAt), diff --git a/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts b/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts index 3ede421ad72ab..cf7a075f7e904 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts @@ -232,6 +232,7 @@ it.effect( getTurnStartContext: () => Effect.die("unused"), getTurnStartHistory: () => Effect.die("unused"), getRuntimeRecoveryProjection: () => Effect.die("unused getRuntimeRecoveryProjection"), + getLatestTodoList: () => Effect.undefined, getPlan: () => Effect.die("unused"), hasUnpairedRunInterruptRequest: () => Effect.die("unused interrupt read"), getThreadAttachmentIds: () => Effect.die("Unused attachment lookup"), diff --git a/apps/server/src/orchestration-v2/ThreadInsightsQuery.test.ts b/apps/server/src/orchestration-v2/ThreadInsightsQuery.test.ts new file mode 100644 index 0000000000000..dc94aaca8b7c2 --- /dev/null +++ b/apps/server/src/orchestration-v2/ThreadInsightsQuery.test.ts @@ -0,0 +1,321 @@ +import { expect, it } from "@effect/vitest"; +import { + EnvironmentId, + EventId, + MessageId, + NodeId, + PlanId, + ProjectId, + ProviderDriverKind, + ProviderInstanceId, + ProviderThreadId, + ProviderTurnId, + RunId, + ThreadId, + TurnItemId, + type OrchestrationV2DomainEvent, + type OrchestrationV2Subagent, + type OrchestrationV2Run, + type TurnTokenUsage, +} from "@t3tools/contracts"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as ProjectionStore from "./ProjectionStore.ts"; +import * as SqlitePersistence from "../persistence/Sqlite.ts"; +import * as UsageService from "../usage/UsageService.ts"; +import * as ThreadInsightsQuery from "./ThreadInsightsQuery.ts"; + +const now = DateTime.makeUnsafe("2026-11-13T12:00:00Z"); +const instance = ProviderInstanceId.make("codex"); +const driver = ProviderDriverKind.make("codex"); +const selection = { instanceId: instance, model: "gpt-6.1-sol" }; +const layerStore = ProjectionStore.layer.pipe(Layer.provideMerge(SqlitePersistence.layerMemory)); +const layer = ThreadInsightsQuery.layer.pipe( + Layer.provideMerge(layerStore), + Layer.provide( + Layer.mock(UsageService.UsageService)({ + priceRecords: (records) => Effect.succeed(records.map(() => 0.1)), + }), + ), +); + +const apply = Effect.fn("test.insights.apply")(function* (event: OrchestrationV2DomainEvent) { + yield* (yield* ProjectionStore.ProjectionStoreV2).apply(event); +}); +const thread = Effect.fn("test.insights.thread")(function* ( + name: string, + parent: ThreadId | null = null, + relationship: "fork" | "subagent" | null = null, +) { + const id = ThreadId.make(name); + yield* apply({ + id: EventId.make(`thread:${name}`), + type: "thread.created", + threadId: id, + occurredAt: now, + payload: { + id, + projectId: ProjectId.make("project"), + title: name, + createdBy: "user", + creationSource: "web", + providerInstanceId: instance, + modelSelection: selection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + activeProviderThreadId: null, + lineage: { + parentThreadId: parent, + relationshipToParent: relationship, + rootThreadId: parent ?? id, + }, + forkedFrom: null, + createdAt: now, + updatedAt: now, + archivedAt: null, + settledOverride: null, + settledAt: null, + lastVisitedAt: null, + deletedAt: null, + }, + }); + return id; +}); +const run = Effect.fn("test.insights.run")(function* ( + threadId: ThreadId, + ordinal: number, + status: OrchestrationV2Run["status"] = "completed", +) { + const id = RunId.make(`${threadId}:run:${ordinal}`); + const payload: OrchestrationV2Run = { + id, + threadId, + ordinal, + providerInstanceId: instance, + modelSelection: selection, + providerThreadId: null, + userMessageId: MessageId.make(`${id}:message`), + rootNodeId: NodeId.make(`${id}:node`), + activeAttemptId: null, + status, + requestedAt: now, + startedAt: now, + completedAt: now, + checkpointId: null, + contextHandoffId: null, + }; + yield* apply({ + id: EventId.make(`${id}:event`), + type: "run.created", + threadId, + occurredAt: now, + payload, + }); + return payload; +}); +const agent = Effect.fn("test.insights.agent")(function* ( + parent: ThreadId, + child: ThreadId, + origin: OrchestrationV2Subagent["origin"] = "app_owned", + remote = false, +) { + const id = NodeId.make(`${parent}:${child}:agent`); + yield* apply({ + id: EventId.make(`${id}:event`), + type: "subagent.updated", + threadId: parent, + occurredAt: now, + payload: { + id, + threadId: parent, + runId: null, + parentNodeId: NodeId.make(`${parent}:node`), + origin, + createdBy: "agent", + driver, + providerInstanceId: instance, + providerThreadId: ProviderThreadId.make(`${child}:provider`), + childThreadId: remote ? null : child, + ...(remote + ? { + remoteChild: { + environmentId: EnvironmentId.make("remote"), + threadId: child, + label: "Remote", + }, + } + : {}), + nativeTaskRef: null, + prompt: "", + title: child, + model: selection.model, + status: "completed", + result: null, + startedAt: now, + completedAt: now, + updatedAt: now, + }, + }); +}); +const usage = (inputTokens: number): TurnTokenUsage => ({ + usageScope: "main_agent", + usageStatus: "complete", + inputTokens, + outputTokens: 10, + cachedInputTokens: 20, + cacheCreationTokens: 0, + hasSubagents: true, + models: [selection.model], + otherUsage: { inputTokens: 9000, outputTokens: 9000 }, +}); +const turn = Effect.fn("test.insights.turn")(function* ( + threadId: ThreadId, + name: string, + owner: ThreadId, + counters?: TurnTokenUsage, +) { + yield* apply({ + id: EventId.make(`${name}:event`), + type: "provider-turn.updated", + threadId, + occurredAt: now, + payload: { + id: ProviderTurnId.make(name), + providerThreadId: ProviderThreadId.make(`${owner}:provider`), + nodeId: NodeId.make(`${name}:node`), + runAttemptId: null, + nativeTurnRef: null, + ordinal: 1, + status: "completed", + startedAt: now, + completedAt: now, + ...(counters === undefined ? {} : { turnTokenUsage: counters }), + }, + }); +}); +const plan = Effect.fn("test.insights.plan")(function* ( + owner: OrchestrationV2Run, + name: string, + completed: boolean, + status: "active" | "superseded" = "active", +) { + const planId = PlanId.make(name); + const nodeId = NodeId.make(`${name}:node`); + const steps = [ + { id: "step", text: name, status: completed ? ("completed" as const) : ("running" as const) }, + ]; + yield* apply({ + id: EventId.make(`${name}:plan`), + type: "plan.updated", + threadId: owner.threadId, + occurredAt: now, + payload: { + id: planId, + threadId: owner.threadId, + runId: owner.id, + nodeId, + status, + kind: "todo_list", + steps, + }, + }); + yield* apply({ + id: EventId.make(`${name}:item`), + type: "turn-item.updated", + threadId: owner.threadId, + occurredAt: now, + payload: { + id: TurnItemId.make(`${name}:item`), + threadId: owner.threadId, + runId: owner.id, + nodeId, + providerThreadId: null, + providerTurnId: null, + nativeItemRef: null, + status: "completed", + startedAt: now, + completedAt: now, + parentItemId: null, + ordinal: name === "z-first" ? 1 : 2, + title: name, + updatedAt: now, + type: "todo_list", + planId, + steps, + }, + }); +}); + +it.layer(layer)("ThreadInsightsQuery", (it) => { + it.effect( + "counts spent own turns once, attributes native children, excludes forks, and keeps missing and remote usage explicit", + () => + Effect.gen(function* () { + const root = yield* thread("root"); + const child = yield* thread("child", root, "subagent"); + const native = yield* thread("native", child, "subagent"); + yield* thread("fork", root, "fork"); + yield* run(root, 1, "rolled_back"); + yield* agent(root, child); + yield* agent(child, native, "provider_native"); + yield* agent(native, root); + yield* agent(root, ThreadId.make("remote-child"), "app_owned", true); + yield* agent(root, ThreadId.make("deleted-child")); + yield* turn(root, "root-turn", root, usage(100)); + yield* turn(child, "native-turn", native, usage(50)); + + yield* turn(child, "unreported-turn", child); + const result = yield* (yield* ThreadInsightsQuery.ThreadInsightsQuery).read({ + threadId: root, + }); + expect(result.rows.map((row) => row.threadId)).toEqual([root, child, native]); + expect(result.rows.map((row) => row.usage.inputTokens)).toEqual([100, undefined, 50]); + expect(result.rows.map((row) => row.usage.turns)).toEqual([1, 1, 1]); + expect(result.rows[1]?.usage.status).toBe("unavailable"); + expect(result.rows[0]?.usage.hasOtherUsage).toBe(true); + expect(result.remotes[0]?.threadId).toBe("remote-child"); + expect(result.unavailableThreadIds).toEqual(["deleted-child"]); + expect(result.truncated).toBe(false); + const direct = yield* (yield* ThreadInsightsQuery.ThreadInsightsQuery).read({ + threadId: native, + }); + expect(direct.rows.find((row) => row.threadId === native)?.usage.inputTokens).toBe(50); + }), + ); + + it.effect("selects todo lists by item order, ignores superseded lists and rolled-back runs", () => + Effect.gen(function* () { + const root = yield* thread("plans"); + const store = yield* ProjectionStore.ProjectionStoreV2; + expect(yield* store.getLatestTodoList(root)).toBeUndefined(); + const initial = yield* run(root, 1); + yield* plan(initial, "z-first", false); + yield* plan(initial, "a-second", true); + yield* plan(initial, "superseded", false, "superseded"); + const rolledBack = yield* run(root, 2, "rolled_back"); + yield* plan(rolledBack, "rolled-back", false); + const result = yield* (yield* ThreadInsightsQuery.ThreadInsightsQuery).read({ + threadId: root, + }); + expect(result.rows[0]?.steps?.[0]?.text).toBe("a-second"); + expect(result.rows[0]?.steps?.[0]?.status).toBe("completed"); + }), + ); + it.effect("bounds wide families and reports omitted children", () => + Effect.gen(function* () { + const root = yield* thread("wide"); + for (let index = 0; index < 201; index++) { + const child = yield* thread(`wide-child-${index}`, root, "subagent"); + yield* agent(root, child); + } + const result = yield* (yield* ThreadInsightsQuery.ThreadInsightsQuery).read({ + threadId: root, + }); + expect(result.rows).toHaveLength(200); + expect(result.truncated).toBe(true); + }), + ); +}); diff --git a/apps/server/src/orchestration-v2/ThreadInsightsQuery.ts b/apps/server/src/orchestration-v2/ThreadInsightsQuery.ts new file mode 100644 index 0000000000000..3c60303b2a8a7 --- /dev/null +++ b/apps/server/src/orchestration-v2/ThreadInsightsQuery.ts @@ -0,0 +1,253 @@ +import { + OrchestrationV2GetThreadProjectionError, + type OrchestrationV2GetThreadInsightsResult, + type OrchestrationV2ThreadInsightsRow, + type OrchestrationV2ProviderTurn, + type ThreadId, +} from "@t3tools/contracts"; +import { combinedStatus, sumOf } from "@t3tools/shared/turnTokenUsage"; +import * as Context from "effect/Context"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as ProjectionStore from "./ProjectionStore.ts"; +import * as UsageService from "../usage/UsageService.ts"; +import type { PricedRecord } from "../usage/usagePricing.ts"; + +const MAX_THREADS = 200; +const MAX_TURNS = 20_000; + +export class ThreadInsightsQuery extends Context.Service< + ThreadInsightsQuery, + { + readonly read: (input: { + readonly threadId: ThreadId; + }) => Effect.Effect< + OrchestrationV2GetThreadInsightsResult, + OrchestrationV2GetThreadProjectionError + >; + } +>()("t3/orchestration-v2/ThreadInsightsQuery") {} + +const make = Effect.gen(function* () { + const store = yield* ProjectionStore.ProjectionStoreV2; + const pricing = yield* UsageService.UsageService; + const read = Effect.fn("ThreadInsightsQuery.read")( + function* (input: { readonly threadId: ThreadId }) { + const rows: OrchestrationV2ThreadInsightsRow[] = []; + const remotes: OrchestrationV2GetThreadInsightsResult["remotes"][number][] = []; + const unavailableThreadIds: ThreadId[] = []; + const queue = [ + { + threadId: input.threadId, + parentThreadId: null as ThreadId | null, + status: null as string | null, + }, + ]; + const queued = new Set([input.threadId]); + const remoteKeys = new Set(); + const turns = new Map(); + const childOwners = new Map(); + let truncated = false; + for (let index = 0; index < queue.length; index++) { + const target = queue[index]!; + const snapshot = yield* store + .getThreadRecords(target.threadId, [ + "runs", + "subagents", + "providerTurns", + "providerThreads", + ]) + .pipe( + Effect.catch((cause) => + target.threadId === input.threadId ? Effect.fail(cause) : Effect.succeed(null), + ), + ); + if (snapshot === null) { + unavailableThreadIds.push(target.threadId); + continue; + } + const plan = yield* store.getLatestTodoList(target.threadId); + const latestRun = snapshot.runs.reduce<(typeof snapshot.runs)[number] | null>( + (held, run) => (held === null || run.ordinal > held.ordinal ? run : held), + null, + ); + rows.push({ + threadId: target.threadId, + parentThreadId: target.parentThreadId, + title: snapshot.thread.title, + status: target.status ?? latestRun?.status ?? "idle", + providerInstanceIds: [ + ...new Set(snapshot.providerThreads.map((thread) => thread.providerInstanceId)), + ], + steps: plan?.kind === "todo_list" ? plan.steps : null, + usage: { + status: "unavailable", + turns: 0, + measuredTurns: 0, + costUsd: null, + unpricedTurns: 0, + hasOtherUsage: false, + }, + }); + for (const agent of snapshot.subagents) { + if (agent.remoteChild !== undefined) { + const remote = agent.remoteChild; + const key = `${remote.environmentId.length}:${remote.environmentId}${remote.threadId}`; + if (remoteKeys.has(key)) continue; + if (queue.length + remotes.length >= MAX_THREADS) { + truncated = true; + continue; + } + remoteKeys.add(key); + remotes.push({ + environmentId: remote.environmentId, + threadId: remote.threadId, + parentThreadId: target.threadId, + title: remote.title ?? agent.title ?? "Subagent", + status: agent.status, + }); + } else if (agent.childThreadId !== null) { + if (agent.providerThreadId !== null) + childOwners.set(agent.providerThreadId, agent.childThreadId); + if (queued.has(agent.childThreadId)) continue; + if (queue.length + remotes.length >= MAX_THREADS) { + truncated = true; + continue; + } + queued.add(agent.childThreadId); + queue.push({ + threadId: agent.childThreadId, + parentThreadId: target.threadId, + status: agent.status, + }); + } + } + // Some adapters keep native-child turns on the parent projection. Opening the + // child directly must still find those turns without charging the parent's own work. + let inheritedNativeTurns: readonly OrchestrationV2ProviderTurn[] = []; + if ( + target.threadId === input.threadId && + snapshot.thread.lineage.relationshipToParent === "subagent" && + snapshot.thread.lineage.parentThreadId !== null + ) { + const parentId = snapshot.thread.lineage.parentThreadId; + const parent = yield* store + .getThreadRecords(parentId, ["subagents"]) + .pipe(Effect.orElseSucceed(() => null)); + const nativeOwner = parent?.subagents.find( + (agent) => + agent.childThreadId === target.threadId && agent.origin === "provider_native", + ); + if (nativeOwner?.providerThreadId != null) { + const recorded = yield* store + .getThreadRecords(parentId, ["providerTurns"], { + providerTurnThreadIds: [nativeOwner.providerThreadId], + }) + .pipe(Effect.orElseSucceed(() => null)); + if (recorded === null) unavailableThreadIds.push(target.threadId); + else inheritedNativeTurns = recorded.providerTurns; + } + } + for (const turn of [...snapshot.providerTurns, ...inheritedNativeTurns]) { + const held = turns.get(turn.id); + if (held === undefined && turns.size >= MAX_TURNS) { + truncated = true; + continue; + } + // Copies are routed between parent and child projections. Prefer the final counters. + const rank = (value: OrchestrationV2ProviderTurn) => + value.turnTokenUsage?.usageStatus === "complete" + ? 2 + : value.turnTokenUsage === undefined + ? 0 + : 1; + if (held === undefined || rank(turn) > rank(held.turn)) + turns.set(turn.id, { turn, owner: target.threadId }); + } + } + const rowsById = new Map(rows.map((row) => [row.threadId, row])); + const owned = new Map(); + for (const entry of turns.values()) { + const child = childOwners.get(entry.turn.providerThreadId); + const owner = child !== undefined && rowsById.has(child) ? child : entry.owner; + const list = owned.get(owner) ?? []; + list.push(entry.turn); + owned.set(owner, list); + } + const priced: PricedRecord[] = []; + const priceIds: string[] = []; + for (const { turn } of turns.values()) { + const usage = turn.turnTokenUsage; + if (usage?.usageStatus !== "complete" || usage.models?.length !== 1) continue; + priceIds.push(turn.id); + priced.push({ + model: usage.models[0]!, + totals: { + uncachedInputTokens: Math.max( + 0, + usage.inputTokens - (usage.cachedInputTokens ?? 0) - (usage.cacheCreationTokens ?? 0), + ), + cachedInputTokens: usage.cachedInputTokens ?? 0, + cacheCreationTokens: usage.cacheCreationTokens ?? 0, + outputTokens: usage.outputTokens, + reasoningTokens: usage.reasoningTokens ?? 0, + }, + reportedCostUsd: null, + speed: "standard", + }); + } + const costs = yield* pricing.priceRecords(priced); + const byTurn = new Map(priceIds.map((id, index) => [id, costs[index] ?? null])); + const resultRows = rows.map((row) => { + const rowTurns = owned.get(row.threadId) ?? []; + const usages = rowTurns.map((turn) => turn.turnTokenUsage); + const measured = usages.filter((usage) => usage !== undefined); + const costValues = rowTurns.map((turn) => byTurn.get(turn.id) ?? null); + const knownCosts = costValues.filter((cost) => cost !== null); + const usage = { + status: combinedStatus(usages), + turns: rowTurns.length, + measuredTurns: measured.filter((value) => value.usageStatus !== "unavailable").length, + costUsd: knownCosts.length === 0 ? null : knownCosts.reduce((a, b) => a + b, 0), + unpricedTurns: rowTurns.length - knownCosts.length, + hasOtherUsage: measured.some( + (value) => + (value.otherUsage?.inputTokens ?? 0) > 0 || (value.otherUsage?.outputTokens ?? 0) > 0, + ), + }; + const totals: { + inputTokens?: number; + cachedInputTokens?: number; + cacheCreationTokens?: number; + outputTokens?: number; + reasoningTokens?: number; + } = {}; + for (const field of [ + "inputTokens", + "cachedInputTokens", + "cacheCreationTokens", + "outputTokens", + "reasoningTokens", + ] as const) { + const sum = sumOf(measured, field, false); + if (sum !== undefined) totals[field] = sum; + } + return { ...row, usage: { ...usage, ...totals } }; + }); + return { rows: resultRows, remotes, unavailableThreadIds, truncated }; + }, + (effect, input) => + effect.pipe( + Effect.mapError( + (cause) => + new OrchestrationV2GetThreadProjectionError({ + threadId: input.threadId, + message: "Failed to read thread tasks and usage.", + cause, + }), + ), + ), + ); + return ThreadInsightsQuery.of({ read }); +}); +export const layer = Layer.effect(ThreadInsightsQuery, make); diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index 9353fa2f508a8..9530bde09669b 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -1,3 +1,4 @@ +import * as ThreadInsightsQuery from "./orchestration-v2/ThreadInsightsQuery.ts"; import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers"; import type { RelayManagedEndpointRuntimeConfig } from "@t3tools/contracts/relay"; import * as Random from "effect/Random"; @@ -588,9 +589,10 @@ const layerOrchestrationV2Runtime = RuntimeLayer.layerProduction.pipe( ), ); -const layerOrchestrationApplication = Layer.merge( +const layerOrchestrationApplication = Layer.mergeAll( CheckpointDiffQuery.layer, NativeChildWorkQuery.layer, + ThreadInsightsQuery.layer.pipe(Layer.provide(layerUsage), Layer.provide(ProjectionStoreV2.layer)), ).pipe(Layer.provideMerge(layerCheckpointStore), Layer.provideMerge(layerOrchestrationV2Runtime)); const layerThreadSettlementWorker = Layer.effectDiscard( diff --git a/apps/server/src/telemetry/ProviderUsageAnalytics.ts b/apps/server/src/telemetry/ProviderUsageAnalytics.ts index ce7f29ba1f8d5..14fc8dbac2a1d 100644 --- a/apps/server/src/telemetry/ProviderUsageAnalytics.ts +++ b/apps/server/src/telemetry/ProviderUsageAnalytics.ts @@ -1,3 +1,4 @@ +import { sumOf, combinedStatus } from "@t3tools/shared/turnTokenUsage"; /** * Provider token reporting: one `provider.turn.completed` per provider turn and one * `provider.request.completed` per run, built from the same turns so each counts once. @@ -214,34 +215,6 @@ function requestKind(origin: ProviderTurnOrigin | undefined) { return origin.createdBy; } -function sumOf( - usages: ReadonlyArray, - field: - | "inputTokens" - | "cachedInputTokens" - | "cacheCreationTokens" - | "outputTokens" - | "reasoningTokens", - requireAll: boolean, -): number | undefined { - const values = usages.map((usage) => usage[field]); - const known = values.filter((value) => value !== undefined); - if (known.length === 0 || (requireAll && known.length < values.length)) return undefined; - return known.reduce((sum, value) => sum + value, 0); -} - -/** complete only when every turn is complete; partial when any turn has counts. */ -function combinedStatus(usages: ReadonlyArray) { - if (usages.length > 0 && usages.every((usage) => usage?.usageStatus === "complete")) { - return "complete"; - } - return usages.some( - (usage) => usage?.inputTokens !== undefined || usage?.outputTokens !== undefined, - ) - ? "partial" - : "unavailable"; -} - interface RequestTurn { readonly child: boolean; readonly segment: ProviderTurnSegment | undefined; diff --git a/apps/server/src/usage/UsageService.ts b/apps/server/src/usage/UsageService.ts index a55532913c3c6..17254d8610d59 100644 --- a/apps/server/src/usage/UsageService.ts +++ b/apps/server/src/usage/UsageService.ts @@ -40,7 +40,13 @@ import type { UsageRecord, } from "@t3tools/provider-core/server/usage"; import { canonicalModelFilter, resolveModelAliases, UsageAggregator } from "./usageAggregation.ts"; -import { createOverrideRateTable, parseRateTable, type RateTable } from "./usagePricing.ts"; +import { + createOverrideRateTable, + parseRateTable, + type RateTable, + priceUsage, + type PricedRecord, +} from "./usagePricing.ts"; import { listTranscriptFiles, readDirectoryVolumeId, @@ -148,6 +154,9 @@ export class UsageService extends Context.Service< { readonly readSummary: (input: UsageSummaryInput) => Effect.Effect; readonly refreshRates: Effect.Effect; + readonly priceRecords: ( + records: readonly PricedRecord[], + ) => Effect.Effect; } >()("t3/usage/UsageService") {} @@ -1140,7 +1149,21 @@ export const make = Effect.gen(function* () { return yield* Deferred.await(deferred); }); - return { readSummary, refreshRates, awaitPersisted } as const; + const priceRecords = Effect.fn("UsageService.priceRecords")(function* ( + records: readonly PricedRecord[], + ) { + if (records.length === 0) return []; + yield* ensureRates(false); + const settings = yield* readSettings; + const overrides = createOverrideRateTable(settings.usagePriceOverrides); + const aliases = resolveModelAliases(settings.usageModelAliases); + return records.map((record) => { + const model = aliases.get(record.model) ?? record.model; + const priced = priceUsage(rates, { ...record, model }, overrides); + return priced.costSource === "unpriced" ? null : priced.costUsd; + }); + }); + return { readSummary, refreshRates, priceRecords, awaitPersisted } as const; }); export const layer = Layer.effect(UsageService, make); diff --git a/apps/server/src/ws.test.ts b/apps/server/src/ws.test.ts index c4470e0905c8a..b04c560931314 100644 --- a/apps/server/src/ws.test.ts +++ b/apps/server/src/ws.test.ts @@ -1,3 +1,4 @@ +import * as ThreadInsightsQuery from "./orchestration-v2/ThreadInsightsQuery.ts"; import * as SecretResolver from "@t3tools/secret-provider-core/server/SecretResolver"; import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; @@ -814,6 +815,7 @@ const layerUnusedConfigRpcServices = Layer.mergeAll( Layer.mock(BackgroundPolicy.BackgroundPolicy)({}), Layer.mock(CheckpointDiffQuery.CheckpointDiffQuery)({}), Layer.mock(NativeChildWorkQuery.NativeChildWorkQuery)({}), + Layer.mock(ThreadInsightsQuery.ThreadInsightsQuery)({}), Layer.mock(CommandOutputHub.CommandOutputHub)({}), Layer.mock(CodexInstallation.CodexInstallation)({ managedDirectory: "/unused" }), Layer.mock(DeviceService.DeviceService)({}), diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index 1f2a148734d4e..cc49048d6d072 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -1,3 +1,4 @@ +import * as ThreadInsightsQuery from "./orchestration-v2/ThreadInsightsQuery.ts"; import { OrchestrationDispatchCommandError } from "@t3tools/contracts"; // @effect-diagnostics-next-line nodeBuiltinImport:off -- A synchronous digest inside the pure provider mapping. import * as NodeCrypto from "node:crypto"; @@ -1504,6 +1505,7 @@ export const layerWsRpc = ( const agentSessionScanner = yield* AgentSessionScanner.AgentSessionScanner; const agentSessionImporter = yield* AgentSessionImporter.AgentSessionImporter; const checkpointDiffQuery = yield* CheckpointDiffQuery.CheckpointDiffQuery; + const threadInsights = yield* ThreadInsightsQuery.ThreadInsightsQuery; const nativeChildWork = yield* NativeChildWorkQuery.NativeChildWorkQuery; const keybindings = yield* Keybindings.Keybindings; const environmentTheme = yield* EnvironmentTheme.EnvironmentThemeService; @@ -1869,6 +1871,7 @@ export const layerWsRpc = ( ? {} : { managedPolicy: serverSettings.managedPolicy }), shellResumeCompletionMarker: true, + threadInsights: true, shellThreadFamilies: true, threadLinkMetadata: true, shellOlderSettled: true, @@ -2001,6 +2004,7 @@ export const layerWsRpc = ( threadManagement.forceStopThread(input), [ORCHESTRATION_V2_WS_METHODS.getWorkflowScript]: (input) => readWorkflowScript({ scriptPath: input.scriptPath }), + [ORCHESTRATION_V2_WS_METHODS.getThreadInsights]: (input) => threadInsights.read(input), [ORCHESTRATION_V2_WS_METHODS.getNativeChildWork]: (input) => nativeChildWork.getNativeChildWork(input), [ORCHESTRATION_V2_WS_METHODS.getTurnItem]: (input) => diff --git a/apps/web/src/closedViewStore.ts b/apps/web/src/closedViewStore.ts index b5db7bd741bef..60c88c49c30fc 100644 --- a/apps/web/src/closedViewStore.ts +++ b/apps/web/src/closedViewStore.ts @@ -83,6 +83,12 @@ const isClosedViewEntry = (entry: unknown): entry is ClosedViewEntry => { typeof surface.target.name === "string" && (surface.target.platform === "ios" || surface.target.platform === "android"))) ); + case "thread-insights": + return ( + typeof surface.environmentId === "string" && + typeof surface.threadId === "string" && + (surface.section === "tasks" || surface.section === "usage") + ); case "side-chat": return typeof surface.threadId === "string" && surface.id === `side-chat:${surface.threadId}`; case "pull-request": diff --git a/apps/web/src/components/RightPanelTabs.tsx b/apps/web/src/components/RightPanelTabs.tsx index d220385e28142..32aeb87204bc2 100644 --- a/apps/web/src/components/RightPanelTabs.tsx +++ b/apps/web/src/components/RightPanelTabs.tsx @@ -594,6 +594,8 @@ function surfaceTitle( return "Pull requests"; case "device": return surface.title ?? surface.target?.name ?? "Device"; + case "thread-insights": + return "Tasks & usage"; case "side-chat": return "Side chat"; case "preview": { @@ -684,6 +686,8 @@ function SurfaceIcon({ ); case "pull-requests": return ; + case "thread-insights": + return ; case "side-chat": return ; case "device": diff --git a/apps/web/src/components/chat/RightPanelSurfaceContent.tsx b/apps/web/src/components/chat/RightPanelSurfaceContent.tsx index 5ba6985e19d21..3346513b912b1 100644 --- a/apps/web/src/components/chat/RightPanelSurfaceContent.tsx +++ b/apps/web/src/components/chat/RightPanelSurfaceContent.tsx @@ -1,3 +1,4 @@ +import { ThreadInsightsPanel } from "./ThreadInsightsPanel"; import type { EditorId, EnvironmentId, @@ -173,6 +174,14 @@ export function RightPanelSurfaceContent(props: { } case "pull-requests": return ; + case "thread-insights": + return visible ? ( + + ) : null; case "side-chat": // Not lazy: revealing a suspended tiptap editor tears down its view and crashes the composer. return ( diff --git a/apps/web/src/components/chat/ThreadDetailsPanel.tsx b/apps/web/src/components/chat/ThreadDetailsPanel.tsx index 4942080dbb2d2..a11e9940828f7 100644 --- a/apps/web/src/components/chat/ThreadDetailsPanel.tsx +++ b/apps/web/src/components/chat/ThreadDetailsPanel.tsx @@ -1,3 +1,4 @@ +import { ThreadInsightsMenu } from "./ThreadInsightsMenu"; import type { EditorId, EnvironmentId, @@ -179,6 +180,7 @@ export function ThreadDetailsPanel(props: ThreadDetailsPanelProps) { }; return ( <> +
{show.environment || show.openIn || show.scripts ? ( + useRightPanelStore.getState().openThreadInsights(parent, target, section); + return ( + + }> + + + + open("tasks")}> + + View tasks + + open("usage")}> + + View usage + + + + ); +} diff --git a/apps/web/src/components/chat/ThreadInsightsPanel.tsx b/apps/web/src/components/chat/ThreadInsightsPanel.tsx new file mode 100644 index 0000000000000..5d9d8d88200cf --- /dev/null +++ b/apps/web/src/components/chat/ThreadInsightsPanel.tsx @@ -0,0 +1,242 @@ +import type { ScopedThreadRef, UsageLimitSourceSnapshots } from "@t3tools/contracts"; +import { scopedThreadKey } from "@t3tools/client-runtime/environment"; +import { useAtomValue, RegistryContext } from "@effect/atom-react"; +import { useContext, useEffect, useRef } from "react"; +import { threadInsightsViewAtom } from "../../state/threadInsights"; +import { RefreshCwIcon, ChevronDownIcon } from "lucide-react"; +import { useServerConfigs, useThreadShells } from "../../state/entities"; +import { useEnvironmentProviders } from "../../state/environments"; +import { Button } from "../ui/button"; +import { Collapsible, CollapsibleTrigger, CollapsibleContent } from "../ui/collapsible"; +import { ThreadDetailsUsage } from "./ThreadDetailsUsage"; + +const EMPTY_SOURCES: UsageLimitSourceSnapshots = []; +const number = (value: number | null | undefined) => + value === null || value === undefined ? "Not reported" : value.toLocaleString(); +const dollars = (value: number | null) => + value === null + ? "Unpriced" + : new Intl.NumberFormat(undefined, { + style: "currency", + currency: "USD", + maximumFractionDigits: 4, + }).format(value); + +export function ThreadInsightsPanel({ + target, + section, +}: { + target: ScopedThreadRef; + section: "tasks" | "usage"; +}) { + const merged = useAtomValue(threadInsightsViewAtom(scopedThreadKey(target))); + const registry = useContext(RegistryContext); + const configs = useServerConfigs(); + const providersByEnvironment = useEnvironmentProviders(); + const shells = useThreadShells(); + const keys = new Set( + merged.rows.map((row) => + scopedThreadKey({ environmentId: row.environmentId, threadId: row.threadId }), + ), + ); + const signature = shells + .filter((shell) => + keys.has(scopedThreadKey({ environmentId: shell.environmentId, threadId: shell.id })), + ) + .map((shell) => `${shell.id}:${shell.updatedAt}`) + .join("|"); + const previous = useRef(signature); + const queries = merged.queries; + const refresh = () => { + for (const query of queries) registry.refresh(query); + }; + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Debounce shell changes into the mounted RPC query cache; no timer survives panel closure. + useEffect(() => { + if (previous.current === signature) return; + const timer = setTimeout(() => { + previous.current = signature; + for (const query of queries) registry.refresh(query); + }, 500); + return () => clearTimeout(timer); + }, [signature, queries, registry]); + return ( +
+
+

Tasks & usage

+ +
+ {merged.errors.map((error) => ( +

+ {error} +

+ ))} + {merged.pending.map((ref) => ( +

+ {ref.title}:{" "} + {configs.get(ref.environmentId)?.threadInsights === true + ? "Loading or unavailable" + : "Environment unavailable or server update required"}{" "} + · not included +

+ ))} + {merged.truncated ? ( +

Partial view: the family limit was reached.

+ ) : null} + {merged.unavailable > 0 ? ( +

+ {merged.unavailable} thread records unavailable · not included +

+ ) : null} + + + + Tasks ·{" "} + {merged.tasks.lists === 0 + ? "No task lists reported" + : `${merged.tasks.done}/${merged.tasks.total} reported steps`} + + + {merged.tasks.total > 0 ? ( + + ) : null} +

+ Reported steps across this thread and its subagents. Lists may describe overlapping + work. +

+ {merged.rows.map((row) => ( + + + + + {row.title} + + {row.status} ·{" "} + {row.steps === null + ? "No task list reported" + : `${row.steps.filter((step) => step.status === "completed").length}/${row.steps.length} steps`} + + + + + {row.steps === null ? ( +

No task list reported

+ ) : row.steps.length === 0 ? ( +

No steps in this list

+ ) : ( +
    + {row.steps.map((step) => ( +
  • + + {step.status === "completed" + ? "✓" + : step.status === "running" + ? "◉" + : "○"} + + {step.text} +
  • + ))} +
+ )} +
+
+ ))} +
+
+ + + + Usage · {merged.partial ? "Partial recorded usage" : "Recorded usage"} + + +
+
Input (includes cache)
+
{number(merged.inputTokens)}
+
Cache read
+
{number(merged.cachedInputTokens)}
+
Cache write
+
{number(merged.cacheCreationTokens)}
+
Output (includes reasoning)
+
{number(merged.outputTokens)}
+
API-equivalent estimate
+
{dollars(merged.costUsd)}
+
+

+ Standard-rate estimate, not your subscription bill. Unreported cache tokens are priced + as uncached input.{" "} + {merged.unpricedTurns > 0 + ? `${merged.unpricedTurns} turns unpriced or missing a complete breakdown.` + : ""} +

+ {merged.rows.map((row) => ( +
+

{row.title}

+

+ {row.usage.status} · {row.usage.measuredTurns}/{row.usage.turns} turns reported +

+

+ {number(row.usage.inputTokens)} input · {number(row.usage.outputTokens)} output ·{" "} + {dollars(row.usage.costUsd)} +

+ {row.usage.hasOtherUsage ? ( +

+ Provider extra usage is not added: it may overlap subagent usage. +

+ ) : null} +
+ ))} +

Subscription limits

+

+ Account-wide, across all threads and devices. Per-chat quota: not reported by providers. +

+ {[ + ...new Map( + merged.rows.flatMap((row) => + row.providerInstanceIds.map( + (instanceId) => + [ + `${row.environmentId}:${instanceId}`, + { environmentId: row.environmentId, instanceId }, + ] as const, + ), + ), + ).values(), + ].map(({ environmentId, instanceId }) => ( +
+

+ {providersByEnvironment + .get(environmentId) + ?.find((provider) => provider.instanceId === instanceId)?.displayName ?? + instanceId} +

+ +
+ ))} +
+
+
+ ); +} diff --git a/apps/web/src/components/chat/ThreadLineageWorkflowRow.tsx b/apps/web/src/components/chat/ThreadLineageWorkflowRow.tsx index 4cfb23350e912..5d28814aa0bb6 100644 --- a/apps/web/src/components/chat/ThreadLineageWorkflowRow.tsx +++ b/apps/web/src/components/chat/ThreadLineageWorkflowRow.tsx @@ -1,3 +1,5 @@ +import { ThreadInsightsMenu } from "./ThreadInsightsMenu"; +import { ThreadId, type ScopedThreadRef } from "@t3tools/contracts"; import { workflowMemberModelSelection, type SubagentWorkflowGroup, @@ -50,6 +52,7 @@ function phaseStatusLabel(phase: SubagentWorkflowGroup["phases"][number]) { } function WorkflowMemberRow({ + parentRef, member, providerInstanceId, provider, @@ -58,6 +61,7 @@ function WorkflowMemberRow({ driver, onOpen, }: { + parentRef: ScopedThreadRef; member: RuntimeSubagent; providerInstanceId: ProviderInstanceId; provider: ServerProvider | undefined; @@ -69,7 +73,13 @@ function WorkflowMemberRow({ const threadId = member.childThreadId; const canOpen = threadId !== null; return ( -
  • +
  • + {threadId !== null ? ( + + ) : null} {phase.members.map((member) => ( ( ({ })); vi.mock(import("../../state/entities"), () => ({ + useServerConfigs: (() => new Map()) as never, useQuietThreadShell: (() => null) as never, useThreadProjection: ((ref: unknown) => ref === null ? null : { projection: state.projection }) as never, diff --git a/apps/web/src/components/chat/ThreadRelationshipsControl.tsx b/apps/web/src/components/chat/ThreadRelationshipsControl.tsx index 49c69ff4fadee..e8187e1cee2b0 100644 --- a/apps/web/src/components/chat/ThreadRelationshipsControl.tsx +++ b/apps/web/src/components/chat/ThreadRelationshipsControl.tsx @@ -1,3 +1,5 @@ +import type { ScopedThreadRef } from "@t3tools/contracts"; +import { ThreadInsightsMenu } from "./ThreadInsightsMenu"; import { useAtomValue } from "@effect/atom-react"; import { threadKey } from "@t3tools/client-runtime/state/entities"; import { ThreadDetailsControl } from "./ThreadDetailsControl"; @@ -261,6 +263,7 @@ function currentSubagent( * the thread there, when this client is connected to that environment. */ function RemoteSubagentRow(props: { + readonly parentRef: ScopedThreadRef; readonly agent: RemoteSubagent; readonly provider: ServerProvider | undefined; }) { @@ -275,6 +278,10 @@ function RemoteSubagentRow(props: { }); return (
  • + + {isMergeTarget ? (
    @@ -1023,6 +1032,7 @@ export function ThreadRelationshipsPanel(props: { visibleRows.map((row) => "remote" in row ? ( ctx.onOpenThread(ThreadId.make(threadId))} diff --git a/apps/web/src/components/chat/V2LifecycleRow.tsx b/apps/web/src/components/chat/V2LifecycleRow.tsx index 40fffaf608412..96e9ffaaf695b 100644 --- a/apps/web/src/components/chat/V2LifecycleRow.tsx +++ b/apps/web/src/components/chat/V2LifecycleRow.tsx @@ -1,3 +1,4 @@ +import { ThreadInsightsMenu } from "./ThreadInsightsMenu"; import { ThreadHoverCardPopup } from "../ThreadHoverCard"; import { AgentElapsed } from "./AgentElapsed"; import { projectedSubagentsToRuntime } from "@t3tools/client-runtime/state/subagentRuntime"; @@ -504,43 +505,62 @@ function SubagentTimelineLink(props: { const className = "group/subagent flex w-full min-w-0 items-center gap-2.5 rounded-md px-2 py-1.5 text-left"; return ( - - - {content} -
    - ) : ( - - ) - } - /> - - : null} - model={agent?.model ?? null} - modelSelection={agent?.modelSelection} - status={liveStatus} - result={agent?.result ?? props.result} - progress={agent?.progress ?? props.progress} +
    +
    + + + {content} +
    + ) : ( + + ) + } + /> + + : null + } + model={agent?.model ?? null} + modelSelection={agent?.modelSelection} + status={liveStatus} + result={agent?.result ?? props.result} + progress={agent?.progress ?? props.progress} + /> + + +
    + {(remote?.threadId ?? threadId) ? ( + -
    -
    + ) : null} +
  • ); } diff --git a/apps/web/src/components/chat/WorkflowOpeningBlock.tsx b/apps/web/src/components/chat/WorkflowOpeningBlock.tsx index 3526bbf931a3a..18ec34c179069 100644 --- a/apps/web/src/components/chat/WorkflowOpeningBlock.tsx +++ b/apps/web/src/components/chat/WorkflowOpeningBlock.tsx @@ -1,3 +1,5 @@ +import { ThreadInsightsMenu } from "./ThreadInsightsMenu"; +import { ThreadId, type ScopedThreadRef } from "@t3tools/contracts"; import { useAtomValue } from "@effect/atom-react"; import { isTerminalSubagentStatus, @@ -36,6 +38,7 @@ function scriptMarkdown(script: string) { } export function WorkflowOpeningBlock(props: { + readonly parentRef?: ScopedThreadRef | null | undefined; readonly opening: WorkflowOpening; readonly environmentId: EnvironmentId; readonly onOpenThread: (threadId: string) => void; @@ -49,6 +52,7 @@ export function WorkflowOpeningBlock(props: { +
  • + {props.parentRef && threadId !== null ? ( + + ) : null} > { const items: ReadonlyArray> = [ + ...(state.canViewInsights + ? [ + { id: "view-tasks" as const, label: "View tasks", icon: "list-todo" }, + { id: "view-usage" as const, label: "View usage", icon: "chart-no-axes-combined" }, + ] + : []), ...(state.canFind ? [{ id: "find" as const, label: "Find in thread", icon: "text-search" }] : []), diff --git a/apps/web/src/hooks/useThreadActionMenu.test.ts b/apps/web/src/hooks/useThreadActionMenu.test.ts index 3c8255b04c088..e152983e00500 100644 --- a/apps/web/src/hooks/useThreadActionMenu.test.ts +++ b/apps/web/src/hooks/useThreadActionMenu.test.ts @@ -46,7 +46,11 @@ vi.mock("../state/session", () => ({ readEnvironmentScope: (environmentId: string, scope: string) => scope === AuthOrchestrationOperateScope && state.granted.has(environmentId), })); +vi.mock("../rightPanelStore", () => ({ + useRightPanelStore: { getState: () => ({ openThreadInsights: () => {} }) }, +})); vi.mock("../state/entities", () => ({ + useServerConfigs: () => new Map(), readEnvironmentServerConfigLoaded: () => true, readEnvironmentSupportsAutoSettleOptOut: () => true, readThreadShell: () => ({ diff --git a/apps/web/src/hooks/useThreadActionMenu.ts b/apps/web/src/hooks/useThreadActionMenu.ts index bf22bd066b9a4..a2b20d923030f 100644 --- a/apps/web/src/hooks/useThreadActionMenu.ts +++ b/apps/web/src/hooks/useThreadActionMenu.ts @@ -1,3 +1,6 @@ +import { buildThreadRouteParams } from "../threadRoutes"; +import { useServerConfigs } from "../state/entities"; +import { useRightPanelStore } from "../rightPanelStore"; import { scopeProjectRef } from "@t3tools/client-runtime/environment"; import { requestCustomSnooze } from "../components/CustomSnoozeDialog"; import { openGuestShareDialog } from "../components/chat/guestShareDialogState"; @@ -10,6 +13,7 @@ import { import { canSnooze, effectiveSnoozed } from "@t3tools/client-runtime/state/thread-settled"; import { AuthOrchestrationOperateScope, + AuthOrchestrationReadScope, type ScopedThreadRef, type ThreadId, } from "@t3tools/contracts"; @@ -67,6 +71,7 @@ export function useThreadActionMenu(input: { readonly canShareWithGuest: boolean; }) { const { threadRef, projectCwd, onStartRename, onFind, canShareWithGuest } = input; + const serverConfigs = useServerConfigs(); const router = useRouter(); const projects = useProjects(); const primaryEnvironmentId = usePrimaryEnvironmentId(); @@ -138,6 +143,9 @@ export function useThreadActionMenu(input: { const isRegeneratingTitle = thread.titleRegeneration != null; const snoozePresets = resolveSnoozePresets(now, timestampFormat, threadRef.environmentId); const items = buildThreadActionMenuItems({ + canViewInsights: + serverConfigs.get(threadRef.environmentId)?.threadInsights === true && + readEnvironmentScope(threadRef.environmentId, AuthOrchestrationReadScope), canOperate: readEnvironmentScope(threadRef.environmentId, AuthOrchestrationOperateScope), canFind: onFind !== undefined, branch: thread.branch ?? null, @@ -194,6 +202,16 @@ export function useThreadActionMenu(input: { } }; switch (action) { + case "view-tasks": + case "view-usage": + useRightPanelStore + .getState() + .openThreadInsights(threadRef, threadRef, action === "view-tasks" ? "tasks" : "usage"); + void router.navigate({ + to: "/$environmentId/$threadId", + params: buildThreadRouteParams(threadRef), + }); + return; case "find": onFind?.(threadRef); return; diff --git a/apps/web/src/reopenClosedView.ts b/apps/web/src/reopenClosedView.ts index 899a1b223ec71..2368673f4bad7 100644 --- a/apps/web/src/reopenClosedView.ts +++ b/apps/web/src/reopenClosedView.ts @@ -154,6 +154,13 @@ export async function reopenClosedView( case "pull-request": panels.openPullRequest(ref, surface); break; + case "thread-insights": + panels.openThreadInsights( + ref, + { environmentId: surface.environmentId, threadId: surface.threadId }, + surface.section, + ); + break; case "side-chat": panels.openSideChat(ref, surface.threadId); break; diff --git a/apps/web/src/rightPanelStore.ts b/apps/web/src/rightPanelStore.ts index 7de186174d348..e8b5fc476692f 100644 --- a/apps/web/src/rightPanelStore.ts +++ b/apps/web/src/rightPanelStore.ts @@ -22,6 +22,7 @@ const RIGHT_PANEL_KINDS = [ "pull-request", "pull-requests", "side-chat", + "thread-insights", ] as const; export type RightPanelKind = (typeof RIGHT_PANEL_KINDS)[number]; @@ -77,6 +78,13 @@ export type RightPanelSurface = revealUrl?: string; detailTab?: PullRequestDetailTab; } + | { + id: `thread-insights:${string}`; + kind: "thread-insights"; + environmentId: EnvironmentId; + threadId: ThreadId; + section: "tasks" | "usage"; + } | { id: "pull-requests"; kind: "pull-requests" } | { id: `side-chat:${string}`; kind: "side-chat"; threadId: ThreadId }; @@ -125,7 +133,15 @@ interface RightPanelStoreState { ) => boolean; open: ( ref: ScopedThreadRef, - kind: Exclude, + kind: Exclude< + RightPanelKind, + "file" | "terminal" | "pull-request" | "side-chat" | "thread-insights" + >, + ) => void; + openThreadInsights: ( + ref: ScopedThreadRef, + target: ScopedThreadRef, + section: "tasks" | "usage", ) => void; openSideChat: (ref: ScopedThreadRef, threadId: ThreadId) => void; openDevice: (ref: ScopedThreadRef, target: DeviceTabTarget, automatic?: boolean) => void; @@ -191,7 +207,10 @@ interface RightPanelStoreState { toggleVisibility: (ref: ScopedThreadRef) => void; toggle: ( ref: ScopedThreadRef, - kind: Exclude, + kind: Exclude< + RightPanelKind, + "file" | "terminal" | "pull-request" | "side-chat" | "thread-insights" + >, ) => void; setThreadPanelOpen: ( ref: ScopedThreadRef, @@ -214,7 +233,10 @@ const DEFAULT_THREAD_PANEL_VISIBILITY: ThreadPanelVisibility = { }; const singletonSurface = ( - kind: Exclude, + kind: Exclude< + RightPanelKind, + "file" | "preview" | "terminal" | "pull-request" | "side-chat" | "thread-insights" + >, ): RightPanelSurface => { switch (kind) { case "diff": @@ -733,6 +755,23 @@ export const useRightPanelStore = create()( ); }), ), + openThreadInsights: (ref, target, section) => + set((state) => + userAction(state, scopedThreadKey(ref), (current) => { + const surface: RightPanelSurface = { + id: `thread-insights:${scopedThreadKey(target)}`, + kind: "thread-insights", + environmentId: target.environmentId, + threadId: target.threadId, + section, + }; + const next = upsertSurface(current, surface); + return { + ...next, + surfaces: next.surfaces.map((entry) => (entry.id === surface.id ? surface : entry)), + }; + }), + ), openSideChat: (ref, threadId) => set((state) => userAction(state, scopedThreadKey(ref), (current) => diff --git a/apps/web/src/state/threadInsights.ts b/apps/web/src/state/threadInsights.ts new file mode 100644 index 0000000000000..0413e8ea64bd8 --- /dev/null +++ b/apps/web/src/state/threadInsights.ts @@ -0,0 +1,44 @@ +import { Atom, AsyncResult } from "effect/reactivity"; +import * as Option from "effect/Option"; +import { parseScopedThreadKey, scopedThreadKey } from "@t3tools/client-runtime/environment"; +import { + mergeThreadInsights, + type ThreadInsightsAnswer, +} from "@t3tools/client-runtime/state/thread-insights"; +import { orchestrationEnvironment } from "./orchestration"; +import { environmentPresentations } from "./presentation"; + +export const threadInsightsViewAtom = Atom.family((key: string) => + Atom.make((get) => { + const target = parseScopedThreadKey(key); + if (target === null) throw new Error("Invalid thread insights target"); + const configs = get(environmentPresentations.serverConfigsAtom); + const answers = new Map(); + const queue = [target]; + const visited = new Set(); + const queries: ReturnType[] = []; + const errors = new Set(); + for (let index = 0; index < queue.length && visited.size < 200; index++) { + const ref = queue[index]!; + const nextKey = scopedThreadKey(ref); + if (visited.has(nextKey)) continue; + visited.add(nextKey); + if (configs.get(ref.environmentId)?.threadInsights !== true) continue; + const query = orchestrationEnvironment.threadInsights({ + environmentId: ref.environmentId, + input: { threadId: ref.threadId }, + }); + queries.push(query); + const result = get(query); + if (AsyncResult.isFailure(result)) { + errors.add("An environment could not report tasks and usage."); + continue; + } + const data = Option.getOrNull(AsyncResult.value(result)); + if (data === null) continue; + answers.set(nextKey, { target: ref, data }); + queue.push(...data.remotes); + } + return { ...mergeThreadInsights(target, answers), queries, errors: [...errors] }; + }), +); diff --git a/docs/user/usage.md b/docs/user/usage.md index e6b3a46d5a14e..4336d0690b1dd 100644 --- a/docs/user/usage.md +++ b/docs/user/usage.md @@ -57,6 +57,24 @@ saved totals first, then updates them when Cursor's API responds. If recent work is missing or a new model shows no cost, refresh to rescan session history and update model pricing. +## Inspect one thread + +On web and desktop, choose **View usage** in a thread's menu, or in the menu beside a +subagent in the work log or Lineage. The **Tasks & usage** side panel combines the thread +and its subagents, including descendants on connected environments. Forks and side chats +are separate. Expand a row to inspect its tasks, or open **View tasks** to start there. +The progress count describes reported steps; different agents' lists can overlap. + +Usage comes from recorded turns. Missing provider reports, unavailable children, and limits on +large families are marked as partial. Input includes cache tokens, and output includes reasoning. +Extra provider usage that may overlap child turns is shown without adding it again. + +Cost is an estimate at standard API rates for turns with one reported model. Missing cache +breakdowns are treated as uncached input; mixed or unknown models stay unpriced. This estimate +can differ from Usage's transcript-based history and does not represent a subscription charge. +Subscription limits are account-wide across threads and devices. Providers do not report how +much of a subscription's quota an individual thread consumed. + ## Set custom model prices On web or desktop, open the environment dropdown on **Usage**, then choose **Model prices** to add, diff --git a/packages/client-runtime/package.json b/packages/client-runtime/package.json index d1e74151e53e3..4a6b2f00c68bb 100644 --- a/packages/client-runtime/package.json +++ b/packages/client-runtime/package.json @@ -566,6 +566,10 @@ "./provider-instance-ids": { "types": "./src/providerInstanceIds.ts", "default": "./src/providerInstanceIds.ts" + }, + "./state/thread-insights": { + "types": "./src/state/threadInsights.ts", + "import": "./src/state/threadInsights.ts" } }, "scripts": { diff --git a/packages/client-runtime/src/state/orchestration.ts b/packages/client-runtime/src/state/orchestration.ts index 657a9cd62dab1..dbf707fd8819b 100644 --- a/packages/client-runtime/src/state/orchestration.ts +++ b/packages/client-runtime/src/state/orchestration.ts @@ -192,6 +192,12 @@ export function createOrchestrationEnvironmentAtoms( idleTtlMs: 300_000, }), // Mounted only while a subagent inspector is open; running children change between opens. + threadInsights: createEnvironmentRpcQueryAtomFamily(runtime, { + label: "environment-data:orchestration:thread-insights", + tag: ORCHESTRATION_V2_WS_METHODS.getThreadInsights, + staleTimeMs: 0, + idleTtlMs: 0, + }), nativeChildWork: createEnvironmentRpcQueryAtomFamily(runtime, { label: "environment-data:orchestration:native-child-work", tag: ORCHESTRATION_V2_WS_METHODS.getNativeChildWork, diff --git a/packages/client-runtime/src/state/threadInsights.test.ts b/packages/client-runtime/src/state/threadInsights.test.ts new file mode 100644 index 0000000000000..2689734744604 --- /dev/null +++ b/packages/client-runtime/src/state/threadInsights.test.ts @@ -0,0 +1,102 @@ +import { describe, expect, it } from "vite-plus/test"; +import { + EnvironmentId, + ThreadId, + type OrchestrationV2GetThreadInsightsResult, + type ScopedThreadRef, +} from "@t3tools/contracts"; +import { scopedThreadKey } from "../environment/scoped.ts"; +import { mergeThreadInsights, type ThreadInsightsAnswer } from "./threadInsights.ts"; + +const ref = (environment: string, thread: string): ScopedThreadRef => ({ + environmentId: EnvironmentId.make(environment), + threadId: ThreadId.make(thread), +}); +const row = ( + threadId: string, + inputTokens: number, +): OrchestrationV2GetThreadInsightsResult["rows"][number] => ({ + threadId: ThreadId.make(threadId), + parentThreadId: null, + title: threadId, + status: "completed", + providerInstanceIds: [], + steps: [{ id: "a", text: "Step", status: "completed" }], + usage: { + status: "complete", + turns: 1, + measuredTurns: 1, + inputTokens, + outputTokens: 10, + costUsd: null, + unpricedTurns: 1, + hasOtherUsage: false, + }, +}); +const answer = ( + target: ScopedThreadRef, + overrides: Partial = {}, +): ThreadInsightsAnswer => ({ + target, + data: { rows: [], remotes: [], unavailableThreadIds: [], truncated: false, ...overrides }, +}); + +describe("mergeThreadInsights", () => { + it("keeps missing remote usage partial, scopes duplicate thread IDs by environment, and discards unreachable old answers", () => { + const root = ref("local", "root"); + const remote = ref("remote", "root"); + const stale = ref("stale", "old"); + const localAnswer = answer(root, { + rows: [row("root", 100)], + remotes: [{ ...remote, parentThreadId: root.threadId, title: "Remote", status: "completed" }], + }); + const answers = new Map([ + [scopedThreadKey(root), localAnswer], + [scopedThreadKey(stale), answer(stale, { rows: [row("old", 9000)] })], + ]); + const pending = mergeThreadInsights(root, answers); + expect(pending.inputTokens).toBe(100); + expect(pending.partial).toBe(true); + expect(pending.pending).toEqual([ + { ...remote, parentThreadId: root.threadId, title: "Remote", status: "completed" }, + ]); + answers.set( + scopedThreadKey(remote), + answer(remote, { + rows: [row("root", 300)], + remotes: [ + { ...root, parentThreadId: remote.threadId, title: "Cycle", status: "completed" }, + ], + }), + ); + const complete = mergeThreadInsights(root, answers); + expect(complete.rows).toHaveLength(2); + expect(complete.inputTokens).toBe(400); + expect(complete.tasks).toEqual({ done: 2, total: 2, lists: 2 }); + expect(complete.partial).toBe(false); + answers.set(scopedThreadKey(root), answer(root, { rows: [row("root", 100)] })); + expect(mergeThreadInsights(root, answers).inputTokens).toBe(100); + }); + + it("preserves unreported counters and incomplete local coverage", () => { + const root = ref("local", "root"); + const result = mergeThreadInsights( + root, + new Map([ + [ + scopedThreadKey(root), + answer(root, { + rows: [{ ...row("root", 100), steps: null }], + truncated: true, + unavailableThreadIds: [ThreadId.make("deleted")], + }), + ], + ]), + ); + expect(result.cachedInputTokens).toBeNull(); + expect(result.costUsd).toBeNull(); + expect(result.tasks).toEqual({ done: 0, total: 0, lists: 0 }); + expect(result.partial).toBe(true); + expect(result.unavailable).toBe(1); + }); +}); diff --git a/packages/client-runtime/src/state/threadInsights.ts b/packages/client-runtime/src/state/threadInsights.ts new file mode 100644 index 0000000000000..06d49e722dea6 --- /dev/null +++ b/packages/client-runtime/src/state/threadInsights.ts @@ -0,0 +1,89 @@ +import type { + EnvironmentId, + OrchestrationV2GetThreadInsightsResult, + ScopedThreadRef, +} from "@t3tools/contracts"; +import { scopedThreadKey } from "../environment/scoped.ts"; + +export interface ThreadInsightsAnswer { + readonly target: ScopedThreadRef; + readonly data: OrchestrationV2GetThreadInsightsResult; +} + +/** Only reachable answers contribute; a removed remote child must not leave stale spend behind. */ +export function mergeThreadInsights( + root: ScopedThreadRef, + answers: ReadonlyMap, +) { + const pending: (ScopedThreadRef & { title: string })[] = []; + const rows = new Map< + string, + OrchestrationV2GetThreadInsightsResult["rows"][number] & { environmentId: EnvironmentId } + >(); + const queue = [{ ...root, title: "This thread" }]; + const visited = new Set(); + let truncated = false; + let unavailable = 0; + for (let index = 0; index < queue.length; index++) { + const target = queue[index]!; + const key = scopedThreadKey(target); + if (visited.has(key)) continue; + if (visited.size >= 200) { + truncated = true; + break; + } + visited.add(key); + const answer = answers.get(key)?.data; + if (answer === undefined) { + pending.push(target); + continue; + } + truncated ||= answer.truncated; + unavailable += answer.unavailableThreadIds.length; + for (const row of answer.rows) { + const rowKey = scopedThreadKey({ + environmentId: target.environmentId, + threadId: row.threadId, + }); + if (rows.size >= 200 && !rows.has(rowKey)) { + truncated = true; + continue; + } + rows.set(rowKey, { ...row, environmentId: target.environmentId }); + } + queue.push(...answer.remotes); + } + const values = [...rows.values()]; + const lists = values.flatMap((row) => (row.steps === null ? [] : [row.steps])); + const sum = ( + field: "inputTokens" | "cachedInputTokens" | "cacheCreationTokens" | "outputTokens", + ) => { + const known = values.flatMap((row) => + row.usage[field] === undefined ? [] : [row.usage[field]!], + ); + return known.length === 0 ? null : known.reduce((a, b) => a + b, 0); + }; + const costs = values.flatMap((row) => (row.usage.costUsd === null ? [] : [row.usage.costUsd])); + return { + rows: values, + pending, + truncated, + unavailable, + partial: + truncated || + unavailable > 0 || + pending.length > 0 || + values.some((row) => row.usage.status !== "complete" || row.usage.hasOtherUsage), + tasks: { + lists: lists.length, + done: lists.flat().filter((step) => step.status === "completed").length, + total: lists.flat().length, + }, + inputTokens: sum("inputTokens"), + cachedInputTokens: sum("cachedInputTokens"), + cacheCreationTokens: sum("cacheCreationTokens"), + outputTokens: sum("outputTokens"), + costUsd: costs.length === 0 ? null : costs.reduce((a, b) => a + b, 0), + unpricedTurns: values.reduce((sum, row) => sum + row.usage.unpricedTurns, 0), + }; +} diff --git a/packages/contracts/src/environment.ts b/packages/contracts/src/environment.ts index e305efb51f838..757f5e9df52a5 100644 --- a/packages/contracts/src/environment.ts +++ b/packages/contracts/src/environment.ts @@ -201,6 +201,7 @@ export const ExecutionEnvironmentCapabilities = Schema.Struct({ * The server config's flags of the same names. A server that names them here lets a client * load the shell snapshot before the socket opens, and answers its `resumeFrom`. */ + threadInsights: Schema.optionalKey(Schema.Boolean), shellThreadFamilies: Schema.optionalKey(Schema.Boolean), shellOlderSettled: Schema.optionalKey(Schema.Boolean), /** Publishes a pull request refresh when linked-thread answers change; older servers need polling. */ diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts index bf6b53666f4d7..d01f5ff648c5a 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -3767,6 +3767,49 @@ export type OrchestrationV2InternalCommand = typeof OrchestrationV2InternalComma export type OrchestrationV2ServerCommand = OrchestrationV2Command | OrchestrationV2InternalCommand; +export const OrchestrationV2ThreadInsightsUsage = Schema.Struct({ + status: Schema.Literals(["complete", "partial", "unavailable"]), + turns: NonNegativeInt, + measuredTurns: NonNegativeInt, + inputTokens: Schema.optionalKey(NonNegativeInt), + cachedInputTokens: Schema.optionalKey(NonNegativeInt), + cacheCreationTokens: Schema.optionalKey(NonNegativeInt), + outputTokens: Schema.optionalKey(NonNegativeInt), + reasoningTokens: Schema.optionalKey(NonNegativeInt), + costUsd: Schema.NullOr(Schema.Number), + unpricedTurns: NonNegativeInt, + hasOtherUsage: Schema.Boolean, +}); +export type OrchestrationV2ThreadInsightsUsage = typeof OrchestrationV2ThreadInsightsUsage.Type; + +export const OrchestrationV2ThreadInsightsRow = Schema.Struct({ + threadId: ThreadId, + parentThreadId: Schema.NullOr(ThreadId), + title: Schema.String, + status: Schema.String, + providerInstanceIds: Schema.Array(ProviderInstanceId), + steps: Schema.NullOr(Schema.Array(OrchestrationV2PlanStep)), + usage: OrchestrationV2ThreadInsightsUsage, +}); +export type OrchestrationV2ThreadInsightsRow = typeof OrchestrationV2ThreadInsightsRow.Type; + +export const OrchestrationV2GetThreadInsightsResult = Schema.Struct({ + rows: Schema.Array(OrchestrationV2ThreadInsightsRow), + remotes: Schema.Array( + Schema.Struct({ + environmentId: EnvironmentId, + threadId: ThreadId, + parentThreadId: ThreadId, + title: Schema.String, + status: Schema.String, + }), + ), + unavailableThreadIds: Schema.Array(ThreadId), + truncated: Schema.Boolean, +}); +export type OrchestrationV2GetThreadInsightsResult = + typeof OrchestrationV2GetThreadInsightsResult.Type; + export const ORCHESTRATION_V2_WS_METHODS = { dispatchCommand: "orchestration.dispatchCommand", getTurnDiff: "orchestration.getTurnDiff", @@ -3783,6 +3826,7 @@ export const ORCHESTRATION_V2_WS_METHODS = { getThreadProjection: "orchestration.getThreadProjection", getWorkflowScript: "orchestration.getWorkflowScript", getNativeChildWork: "orchestration.getNativeChildWork", + getThreadInsights: "orchestration.getThreadInsights", stopWorkflow: "orchestration.stopWorkflow", forceStopThread: "orchestration.forceStopThread", getTurnItem: "orchestration.getTurnItem", @@ -4490,6 +4534,10 @@ export const OrchestrationV2RpcSchemas = { input: OrchestrationV2GetWorkflowScriptInput, output: OrchestrationV2GetWorkflowScriptResult, }, + getThreadInsights: { + input: Schema.Struct({ threadId: ThreadId }), + output: OrchestrationV2GetThreadInsightsResult, + }, getNativeChildWork: { input: OrchestrationV2GetNativeChildWorkInput, output: OrchestrationV2GetNativeChildWorkResult, diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.ts index adba6dbaca71b..16a3a874342b0 100644 --- a/packages/contracts/src/rpc.ts +++ b/packages/contracts/src/rpc.ts @@ -1921,6 +1921,15 @@ const WsOrchestrationV2GetWorkflowScriptRpc = Rpc.make( }, ); +const WsOrchestrationV2GetThreadInsightsRpc = Rpc.make( + ORCHESTRATION_V2_WS_METHODS.getThreadInsights, + { + payload: OrchestrationV2RpcSchemas.getThreadInsights.input, + success: OrchestrationV2RpcSchemas.getThreadInsights.output, + error: Schema.Union([OrchestrationV2GetThreadProjectionError, EnvironmentAuthorizationError]), + }, +); + const WsOrchestrationV2GetNativeChildWorkRpc = Rpc.make( ORCHESTRATION_V2_WS_METHODS.getNativeChildWork, { @@ -2303,6 +2312,7 @@ export const WsRpcGroup = RpcGroup.make( WsOrchestrationV2DispatchCommandRpc, WsOrchestrationV2GetWorkflowScriptRpc, WsOrchestrationV2GetNativeChildWorkRpc, + WsOrchestrationV2GetThreadInsightsRpc, WsOrchestrationV2StopWorkflowRpc, WsOrchestrationV2ForceStopThreadRpc, WsOrchestrationV2GetTurnItemRpc, diff --git a/packages/contracts/src/server.ts b/packages/contracts/src/server.ts index e8bcda3a76f5d..21fe2422fdf6e 100644 --- a/packages/contracts/src/server.ts +++ b/packages/contracts/src/server.ts @@ -698,6 +698,7 @@ export const ServerConfig = Schema.Struct({ * The shell can leave idle subagent children out of snapshots (`omitIdleSubagents`), and * `getThreadFamily` and `getWorktreeThreadIds` serve the rows it leaves out. */ + threadInsights: Schema.optionalKey(Schema.Boolean), shellThreadFamilies: Schema.optionalKey(Schema.Boolean), threadLinkMetadata: Schema.optionalKey(Schema.Boolean), /** diff --git a/packages/shared/package.json b/packages/shared/package.json index ba0b394f26d0c..b7c4a4637f80f 100644 --- a/packages/shared/package.json +++ b/packages/shared/package.json @@ -554,6 +554,10 @@ "./speech": { "types": "./src/speech.ts", "import": "./src/speech.ts" + }, + "./turnTokenUsage": { + "types": "./src/turnTokenUsage.ts", + "import": "./src/turnTokenUsage.ts" } }, "scripts": { diff --git a/packages/shared/src/turnTokenUsage.ts b/packages/shared/src/turnTokenUsage.ts new file mode 100644 index 0000000000000..96fad8c8f9c0b --- /dev/null +++ b/packages/shared/src/turnTokenUsage.ts @@ -0,0 +1,31 @@ +import type { TurnTokenUsage } from "@t3tools/contracts"; + +export function sumOf( + usages: ReadonlyArray, + field: + | "inputTokens" + | "cachedInputTokens" + | "cacheCreationTokens" + | "outputTokens" + | "reasoningTokens", + requireAll: boolean, +): number | undefined { + const values = usages.map((usage) => usage[field]); + const known = values.filter((value) => value !== undefined); + if (known.length === 0 || (requireAll && known.length < values.length)) return undefined; + return known.reduce((sum, value) => sum + value, 0); +} + +/** complete only when every turn is complete; partial when any turn has counts. */ +export function combinedStatus( + usages: ReadonlyArray, +): "complete" | "partial" | "unavailable" { + if (usages.length > 0 && usages.every((usage) => usage?.usageStatus === "complete")) { + return "complete"; + } + return usages.some( + (usage) => usage?.inputTokens !== undefined || usage?.outputTokens !== undefined, + ) + ? "partial" + : "unavailable"; +} From a2243dfa885c3c3cf614849bd41ba78d647c4ed8 Mon Sep 17 00:00:00 2001 From: Lautaro Caballero Date: Fri, 13 Nov 2026 17:08:01 -0300 Subject: [PATCH 02/16] fix(web): correct native tasks and bound thread usage reads --- .../src/orchestration-v2/ProjectionStore.ts | 57 +++++++++++++++++- .../ProviderTurnControlService.test.ts | 1 + .../ThreadInsightsQuery.test.ts | 58 ++++++++++++++++++- .../orchestration-v2/ThreadInsightsQuery.ts | 50 ++++++++++------ apps/server/src/usage/UsageService.ts | 11 ++-- apps/server/src/usage/usagePricing.test.ts | 35 +++++++++++ apps/server/src/usage/usagePricing.ts | 16 +++++ apps/web/src/components/RightPanelTabs.tsx | 10 +++- docs/user/usage.md | 3 +- 9 files changed, 209 insertions(+), 32 deletions(-) diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index 41798c3497d66..eb1a591dccb6a 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -534,6 +534,14 @@ export interface ProjectionStoreV2Shape { filter?: ProjectionRecordFilter, ) => Effect.Effect, ProjectionStoreV2Error>; + readonly getThreadProviderTurns: ( + threadId: ThreadId, + options: { readonly limit: number; readonly providerThreadIds?: readonly ProviderThreadId[] }, + ) => Effect.Effect< + { readonly providerTurns: readonly OrchestrationV2ProviderTurn[]; readonly truncated: boolean }, + ProjectionStoreV2Error + >; + readonly apply: ( event: OrchestrationV2DomainEvent, ) => Effect.Effect; @@ -5553,9 +5561,25 @@ export const layer: Layer.Layer = )( function* (threadId) { const owners = yield* latestTodoOwner(threadId); - return owners[0] === undefined + if (owners[0] !== undefined) + return yield* getPlan(threadId, PlanId.make(owners[0].plan_id)); + // Native children have provider turns and items but no orchestration run. + const runless = yield* sql<{ readonly plan_id: string }>` + SELECT plan.plan_id + FROM orchestration_v2_projection_plans AS plan + INNER JOIN orchestration_v2_projection_turn_items AS item + ON item.thread_id = plan.thread_id + AND json_extract(item.payload_json, '$.planId') = plan.plan_id + WHERE plan.thread_id = ${threadId} AND plan.run_id IS NULL + AND plan.kind = 'todo_list' AND plan.status <> 'superseded' + AND item.type = 'todo_list' AND item.run_id IS NULL + ORDER BY json_extract(item.payload_json, '$.startedAt') DESC, + item.ordinal DESC, plan.plan_id DESC + LIMIT 1 + `; + return runless[0] === undefined ? undefined - : yield* getPlan(threadId, PlanId.make(owners[0].plan_id)); + : yield* getPlan(threadId, PlanId.make(runless[0].plan_id)); }, (effect, threadId) => effect.pipe(Effect.mapError(controlReadError(threadId))), ); @@ -6324,6 +6348,34 @@ export const layer: Layer.Layer = Effect.mapError(controlReadError(threadId)), ); + const getThreadProviderTurns: ProjectionStoreV2Shape["getThreadProviderTurns"] = Effect.fn( + "ProjectionStore.getThreadProviderTurns", + )( + function* (threadId, options) { + yield* requireThread(threadId); + // Limit IDs before fetching bodies so historical payloads never enter the sort. + const rows = yield* sql` + SELECT payload_json FROM orchestration_v2_projection_provider_turns + WHERE rowid IN ( + SELECT rowid FROM orchestration_v2_projection_provider_turns + WHERE thread_id = ${threadId} + ${options.providerThreadIds === undefined ? sql`` : sql`AND provider_thread_id IN (SELECT value FROM json_each(${encodeIdList(options.providerThreadIds)}))`} + ORDER BY provider_thread_id ASC, ordinal ASC + LIMIT ${options.limit + 1} + ) + ORDER BY provider_thread_id ASC, ordinal ASC + `; + return { + providerTurns: yield* decodeRows( + decodeProviderTurnPayload, + threadId, + )(rows.slice(0, options.limit)), + truncated: rows.length > options.limit, + }; + }, + (effect, threadId) => effect.pipe(Effect.mapError(controlReadError(threadId))), + ); + const getThreadSnapshot: ProjectionStoreV2Shape["getThreadSnapshot"] = (threadId) => sql .withTransaction( @@ -9033,6 +9085,7 @@ export const layer: Layer.Layer = getNextTurnItemOrdinal: readOnReader(getNextTurnItemOrdinal), getTurnItem: readOnReader(getTurnItem), getMessagesById: readOnReader(getMessagesById), + getThreadProviderTurns: readOnReader(getThreadProviderTurns), getThreadRecords: (threadId, fields, filter) => getThreadRecords(threadId, fields, filter).pipe(NodeSqliteClient.readOnly), getRuntimeRequest: readOnReader(getRuntimeRequest), diff --git a/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts b/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts index cf7a075f7e904..1d0c723f2d4ad 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts @@ -233,6 +233,7 @@ it.effect( getTurnStartHistory: () => Effect.die("unused"), getRuntimeRecoveryProjection: () => Effect.die("unused getRuntimeRecoveryProjection"), getLatestTodoList: () => Effect.undefined, + getThreadProviderTurns: () => Effect.succeed({ providerTurns: [], truncated: false }), getPlan: () => Effect.die("unused"), hasUnpairedRunInterruptRequest: () => Effect.die("unused interrupt read"), getThreadAttachmentIds: () => Effect.die("Unused attachment lookup"), diff --git a/apps/server/src/orchestration-v2/ThreadInsightsQuery.test.ts b/apps/server/src/orchestration-v2/ThreadInsightsQuery.test.ts index dc94aaca8b7c2..b3e1f83570dcd 100644 --- a/apps/server/src/orchestration-v2/ThreadInsightsQuery.test.ts +++ b/apps/server/src/orchestration-v2/ThreadInsightsQuery.test.ts @@ -35,7 +35,7 @@ const layer = ThreadInsightsQuery.layer.pipe( Layer.provideMerge(layerStore), Layer.provide( Layer.mock(UsageService.UsageService)({ - priceRecords: (records) => Effect.succeed(records.map(() => 0.1)), + priceTurnRecords: (records) => Effect.succeed(records.map(() => 0.1)), }), ), ); @@ -197,10 +197,11 @@ const turn = Effect.fn("test.insights.turn")(function* ( }); }); const plan = Effect.fn("test.insights.plan")(function* ( - owner: OrchestrationV2Run, + owner: { readonly threadId: ThreadId; readonly id: RunId | null }, name: string, completed: boolean, status: "active" | "superseded" = "active", + ordinal = name === "z-first" ? 1 : 2, ) { const planId = PlanId.make(name); const nodeId = NodeId.make(`${name}:node`); @@ -239,7 +240,7 @@ const plan = Effect.fn("test.insights.plan")(function* ( startedAt: now, completedAt: now, parentItemId: null, - ordinal: name === "z-first" ? 1 : 2, + ordinal, title: name, updatedAt: now, type: "todo_list", @@ -304,6 +305,57 @@ it.layer(layer)("ThreadInsightsQuery", (it) => { expect(result.rows[0]?.steps?.[0]?.status).toBe("completed"); }), ); + it.effect("includes the latest runless native-child list in direct and family reads", () => + Effect.gen(function* () { + const root = yield* thread("native-plans-root"); + const child = yield* thread("native-plans-child", root, "subagent"); + yield* agent(root, child, "provider_native"); + const owner = { threadId: child, id: null }; + yield* plan(owner, "z-first", false, "active", 1); + yield* plan(owner, "a-latest", true, "active", 2); + yield* plan(owner, "superseded-native", false, "superseded", 3); + const query = yield* ThreadInsightsQuery.ThreadInsightsQuery; + for (const threadId of [root, child]) { + const result = yield* query.read({ threadId }); + expect(result.rows.find((row) => row.threadId === child)?.steps).toEqual([ + { id: "step", text: "a-latest", status: "completed" }, + ]); + } + }), + ); + it.effect("bounds provider-turn reads and exposes omitted rows before decoding", () => + Effect.gen(function* () { + const root = yield* thread("bounded-turns"); + const child = yield* thread("bounded-child", root, "subagent"); + yield* turn(root, "first", root, usage(10)); + yield* turn(root, "second", child, usage(20)); + const store = yield* ProjectionStore.ProjectionStoreV2; + const bounded = yield* store.getThreadProviderTurns(root, { limit: 1 }); + expect(bounded.providerTurns.map((item) => item.id)).toEqual(["second"]); + expect(bounded.truncated).toBe(true); + const filtered = yield* store.getThreadProviderTurns(root, { + limit: 1, + providerThreadIds: [ProviderThreadId.make(`${root}:provider`)], + }); + expect(filtered.providerTurns.map((item) => item.id)).toEqual(["first"]); + expect(filtered.truncated).toBe(false); + const exhausted = yield* store.getThreadProviderTurns(root, { limit: 0 }); + expect(exhausted.providerTurns).toEqual([]); + expect(exhausted.truncated).toBe(true); + }), + ); + it.effect("preserves native-child counters but marks a failed parent lookup partial", () => + Effect.gen(function* () { + const child = yield* thread("orphan-native", ThreadId.make("missing-parent"), "subagent"); + yield* turn(child, "local-native-turn", child, usage(50)); + const result = yield* (yield* ThreadInsightsQuery.ThreadInsightsQuery).read({ + threadId: child, + }); + expect(result.rows[0]?.usage.inputTokens).toBe(50); + expect(result.rows[0]?.usage.status).toBe("partial"); + expect(result.unavailableThreadIds).toEqual([child]); + }), + ); it.effect("bounds wide families and reports omitted children", () => Effect.gen(function* () { const root = yield* thread("wide"); diff --git a/apps/server/src/orchestration-v2/ThreadInsightsQuery.ts b/apps/server/src/orchestration-v2/ThreadInsightsQuery.ts index 3c60303b2a8a7..f546ae20652f0 100644 --- a/apps/server/src/orchestration-v2/ThreadInsightsQuery.ts +++ b/apps/server/src/orchestration-v2/ThreadInsightsQuery.ts @@ -4,6 +4,7 @@ import { type OrchestrationV2ThreadInsightsRow, type OrchestrationV2ProviderTurn, type ThreadId, + type ProviderThreadId, } from "@t3tools/contracts"; import { combinedStatus, sumOf } from "@t3tools/shared/turnTokenUsage"; import * as Context from "effect/Context"; @@ -48,15 +49,26 @@ const make = Effect.gen(function* () { const turns = new Map(); const childOwners = new Map(); let truncated = false; + let remainingTurns = MAX_TURNS; + const readTurns = Effect.fn("ThreadInsightsQuery.readTurns")(function* ( + threadId: ThreadId, + providerThreadIds?: readonly ProviderThreadId[], + ) { + const result = yield* store.getThreadProviderTurns(threadId, { + limit: remainingTurns, + ...(providerThreadIds === undefined ? {} : { providerThreadIds }), + }); + remainingTurns -= result.providerTurns.length; + truncated ||= result.truncated; + return result.providerTurns; + }); for (let index = 0; index < queue.length; index++) { const target = queue[index]!; const snapshot = yield* store - .getThreadRecords(target.threadId, [ - "runs", - "subagents", - "providerTurns", - "providerThreads", - ]) + .getThreadRecords(target.threadId, ["runs", "subagents", "providerThreads"], { + runStatuses: [], + includeLatestRun: true, + }) .pipe( Effect.catch((cause) => target.threadId === input.threadId ? Effect.fail(cause) : Effect.succeed(null), @@ -66,6 +78,7 @@ const make = Effect.gen(function* () { unavailableThreadIds.push(target.threadId); continue; } + const ownTurns = yield* readTurns(target.threadId); const plan = yield* store.getLatestTodoList(target.threadId); const latestRun = snapshot.runs.reduce<(typeof snapshot.runs)[number] | null>( (held, run) => (held === null || run.ordinal > held.ordinal ? run : held), @@ -134,26 +147,21 @@ const make = Effect.gen(function* () { const parent = yield* store .getThreadRecords(parentId, ["subagents"]) .pipe(Effect.orElseSucceed(() => null)); + if (parent === null) unavailableThreadIds.push(target.threadId); const nativeOwner = parent?.subagents.find( (agent) => agent.childThreadId === target.threadId && agent.origin === "provider_native", ); if (nativeOwner?.providerThreadId != null) { - const recorded = yield* store - .getThreadRecords(parentId, ["providerTurns"], { - providerTurnThreadIds: [nativeOwner.providerThreadId], - }) - .pipe(Effect.orElseSucceed(() => null)); + const recorded = yield* readTurns(parentId, [nativeOwner.providerThreadId]).pipe( + Effect.orElseSucceed(() => null), + ); if (recorded === null) unavailableThreadIds.push(target.threadId); - else inheritedNativeTurns = recorded.providerTurns; + else inheritedNativeTurns = recorded; } } - for (const turn of [...snapshot.providerTurns, ...inheritedNativeTurns]) { + for (const turn of [...ownTurns, ...inheritedNativeTurns]) { const held = turns.get(turn.id); - if (held === undefined && turns.size >= MAX_TURNS) { - truncated = true; - continue; - } // Copies are routed between parent and child projections. Prefer the final counters. const rank = (value: OrchestrationV2ProviderTurn) => value.turnTokenUsage?.usageStatus === "complete" @@ -196,7 +204,7 @@ const make = Effect.gen(function* () { speed: "standard", }); } - const costs = yield* pricing.priceRecords(priced); + const costs = yield* pricing.priceTurnRecords(priced); const byTurn = new Map(priceIds.map((id, index) => [id, costs[index] ?? null])); const resultRows = rows.map((row) => { const rowTurns = owned.get(row.threadId) ?? []; @@ -204,8 +212,12 @@ const make = Effect.gen(function* () { const measured = usages.filter((usage) => usage !== undefined); const costValues = rowTurns.map((turn) => byTurn.get(turn.id) ?? null); const knownCosts = costValues.filter((cost) => cost !== null); + const status = combinedStatus(usages); const usage = { - status: combinedStatus(usages), + status: + unavailableThreadIds.includes(row.threadId) && status === "complete" + ? ("partial" as const) + : status, turns: rowTurns.length, measuredTurns: measured.filter((value) => value.usageStatus !== "unavailable").length, costUsd: knownCosts.length === 0 ? null : knownCosts.reduce((a, b) => a + b, 0), diff --git a/apps/server/src/usage/UsageService.ts b/apps/server/src/usage/UsageService.ts index 17254d8610d59..6945ad74cc7d5 100644 --- a/apps/server/src/usage/UsageService.ts +++ b/apps/server/src/usage/UsageService.ts @@ -44,7 +44,7 @@ import { createOverrideRateTable, parseRateTable, type RateTable, - priceUsage, + priceTurnUsage, type PricedRecord, } from "./usagePricing.ts"; import { @@ -154,7 +154,7 @@ export class UsageService extends Context.Service< { readonly readSummary: (input: UsageSummaryInput) => Effect.Effect; readonly refreshRates: Effect.Effect; - readonly priceRecords: ( + readonly priceTurnRecords: ( records: readonly PricedRecord[], ) => Effect.Effect; } @@ -1149,7 +1149,7 @@ export const make = Effect.gen(function* () { return yield* Deferred.await(deferred); }); - const priceRecords = Effect.fn("UsageService.priceRecords")(function* ( + const priceTurnRecords = Effect.fn("UsageService.priceTurnRecords")(function* ( records: readonly PricedRecord[], ) { if (records.length === 0) return []; @@ -1159,11 +1159,10 @@ export const make = Effect.gen(function* () { const aliases = resolveModelAliases(settings.usageModelAliases); return records.map((record) => { const model = aliases.get(record.model) ?? record.model; - const priced = priceUsage(rates, { ...record, model }, overrides); - return priced.costSource === "unpriced" ? null : priced.costUsd; + return priceTurnUsage(rates, { ...record, model }, overrides); }); }); - return { readSummary, refreshRates, priceRecords, awaitPersisted } as const; + return { readSummary, refreshRates, priceTurnRecords, awaitPersisted } as const; }); export const layer = Layer.effect(UsageService, make); diff --git a/apps/server/src/usage/usagePricing.test.ts b/apps/server/src/usage/usagePricing.test.ts index 9aff0eb194766..1752ada0aab26 100644 --- a/apps/server/src/usage/usagePricing.test.ts +++ b/apps/server/src/usage/usagePricing.test.ts @@ -8,6 +8,7 @@ import { lookupRate, parseRateTable, priceUsage, + priceTurnUsage, } from "./usagePricing.ts"; const rate = (input: number, cacheRead?: number) => ({ @@ -269,6 +270,40 @@ describe("usage pricing", () => { ).toBeCloseTo(20_000 * 8e-6 + 280_000 * 8e-7 + 1_000 * 3e-5, 12); }); + it("leaves aggregated turns unpriced when requests may cross a context threshold", () => { + const table = parseRateTable({ + "tiered-model": { + ...rate(1e-6), + input_cost_per_token_above_100k_tokens: 2e-6, + output_cost_per_token_above_100k_tokens: 7.5e-6, + }, + "flat-model": rate(1e-6), + }); + const aggregate = (input: number, model = "tiered-model") => ({ + model, + speed: "standard" as const, + reportedCostUsd: null, + totals: { + uncachedInputTokens: input, + cachedInputTokens: 0, + cacheCreationTokens: 0, + outputTokens: 100, + reasoningTokens: 0, + }, + }); + // Two 60K requests each use the base rate, unlike a single 120K request. + expect(priceTurnUsage(table, aggregate(60_000))).toBeCloseTo(0.0605); + expect(priceTurnUsage(table, aggregate(100_000))).toBeCloseTo(0.1005); + expect(priceTurnUsage(table, aggregate(120_000))).toBeNull(); + expect(priceUsage(table, aggregate(120_000)).costUsd).toBeCloseTo(0.24075); + expect(priceTurnUsage(table, aggregate(120_000, "flat-model"))).toBeCloseTo(0.1205); + expect(priceTurnUsage(table, aggregate(120_000, "unknown-model"))).toBeNull(); + const overrides = createOverrideRateTable({ + "tiered-model": { inputCostPerMillionTokens: 1, outputCostPerMillionTokens: 5 }, + }); + expect(priceTurnUsage(table, aggregate(120_000), overrides)).toBeCloseTo(0.1205); + }); + it("bills the long-context tier only above its threshold, filling missing tier fields from base", () => { const table = parseRateTable({ "gpt-6-sol": { diff --git a/apps/server/src/usage/usagePricing.ts b/apps/server/src/usage/usagePricing.ts index 21a1bd02bb178..c4365f44e2953 100644 --- a/apps/server/src/usage/usagePricing.ts +++ b/apps/server/src/usage/usagePricing.ts @@ -395,6 +395,22 @@ export function priceUsage( }; } +/** Turn totals can combine requests on either side of a context-price threshold. */ +export function priceTurnUsage( + table: RateTable, + record: PricedRecord, + overrides?: RateTable, +): number | null { + const rate = overrides?.get(record.model.trim()) ?? recordRate(table, record); + if ( + rate === null || + rate.contextTiers.some((tier) => promptTokens(record.totals) > tier.thresholdTokens) + ) + return null; + const priced = priceUsage(table, record, overrides); + return priced.costSource === "unpriced" ? null : priced.costUsd; +} + export function cacheSavingsUsd( table: RateTable, record: PricedRecord, diff --git a/apps/web/src/components/RightPanelTabs.tsx b/apps/web/src/components/RightPanelTabs.tsx index 32aeb87204bc2..59766d12c6d14 100644 --- a/apps/web/src/components/RightPanelTabs.tsx +++ b/apps/web/src/components/RightPanelTabs.tsx @@ -911,7 +911,15 @@ function RightPanelTab( ? scopeThreadRef(props.environmentId, surface.threadId) : null, ); - const title = sideChatShell?.title ?? props.title; + const insightsShell = useQuietThreadShell( + surface.kind === "thread-insights" + ? scopeThreadRef(surface.environmentId, surface.threadId) + : null, + ); + const title = + surface.kind === "thread-insights" + ? `Tasks & usage: ${insightsShell?.title ?? surface.threadId}` + : (sideChatShell?.title ?? props.title); const sideChatState = sideChatTabState(sideChatShell); const content = ( <> diff --git a/docs/user/usage.md b/docs/user/usage.md index 4336d0690b1dd..c540e867186ab 100644 --- a/docs/user/usage.md +++ b/docs/user/usage.md @@ -70,7 +70,8 @@ large families are marked as partial. Input includes cache tokens, and output in Extra provider usage that may overlap child turns is shown without adding it again. Cost is an estimate at standard API rates for turns with one reported model. Missing cache -breakdowns are treated as uncached input; mixed or unknown models stay unpriced. This estimate +breakdowns are treated as uncached input. Mixed or unknown models and turns whose aggregate +cannot establish the context pricing tier stay unpriced. This estimate can differ from Usage's transcript-based history and does not represent a subscription charge. Subscription limits are account-wide across threads and devices. Providers do not report how much of a subscription's quota an individual thread consumed. From 125463f78706d2585822f004582e9d1628b3ee9a Mon Sep 17 00:00:00 2001 From: Lautaro Caballero Date: Fri, 13 Nov 2026 17:20:09 -0300 Subject: [PATCH 03/16] fix(server): preserve insights when descendant turn reads fail --- .../ThreadInsightsQuery.test.ts | 30 +++++++++++++++++++ .../orchestration-v2/ThreadInsightsQuery.ts | 8 ++++- 2 files changed, 37 insertions(+), 1 deletion(-) diff --git a/apps/server/src/orchestration-v2/ThreadInsightsQuery.test.ts b/apps/server/src/orchestration-v2/ThreadInsightsQuery.test.ts index b3e1f83570dcd..e8aeb06907654 100644 --- a/apps/server/src/orchestration-v2/ThreadInsightsQuery.test.ts +++ b/apps/server/src/orchestration-v2/ThreadInsightsQuery.test.ts @@ -21,6 +21,7 @@ import { import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; +import * as SqlClient from "effect/sql/SqlClient"; import * as ProjectionStore from "./ProjectionStore.ts"; import * as SqlitePersistence from "../persistence/Sqlite.ts"; import * as UsageService from "../usage/UsageService.ts"; @@ -356,6 +357,35 @@ it.layer(layer)("ThreadInsightsQuery", (it) => { expect(result.unavailableThreadIds).toEqual([child]); }), ); + it.effect("retains valid family rows when a descendant has a malformed provider turn", () => + Effect.gen(function* () { + const root = yield* thread("failure-root"); + const broken = yield* thread("failure-child", root, "subagent"); + const healthy = yield* thread("healthy-child", root, "subagent"); + yield* agent(root, broken); + yield* agent(root, healthy); + yield* plan(yield* run(root, 1), "root-task", true); + yield* plan(yield* run(broken, 1), "child-task", false); + yield* turn(root, "valid-root-turn", root, usage(100)); + yield* turn(broken, "malformed-turn", broken, usage(50)); + yield* turn(healthy, "valid-child-turn", healthy, usage(25)); + const sql = yield* SqlClient.SqlClient; + yield* sql`UPDATE orchestration_v2_projection_provider_turns + SET payload_json = '{}' WHERE provider_turn_id = 'malformed-turn'`; + const query = yield* ThreadInsightsQuery.ThreadInsightsQuery; + const result = yield* query.read({ threadId: root }); + expect(result.rows.find((row) => row.threadId === root)?.usage.inputTokens).toBe(100); + expect(result.rows.find((row) => row.threadId === root)?.steps?.[0]?.text).toBe("root-task"); + expect(result.rows.find((row) => row.threadId === healthy)?.usage.inputTokens).toBe(25); + expect(result.rows.find((row) => row.threadId === broken)?.usage.status).toBe("unavailable"); + expect(result.rows.find((row) => row.threadId === broken)?.steps?.[0]?.text).toBe( + "child-task", + ); + expect(result.unavailableThreadIds).toEqual([broken]); + const error = yield* query.read({ threadId: broken }).pipe(Effect.flip); + expect(error._tag).toBe("OrchestrationV2GetThreadProjectionError"); + }), + ); it.effect("bounds wide families and reports omitted children", () => Effect.gen(function* () { const root = yield* thread("wide"); diff --git a/apps/server/src/orchestration-v2/ThreadInsightsQuery.ts b/apps/server/src/orchestration-v2/ThreadInsightsQuery.ts index f546ae20652f0..1283069d16f74 100644 --- a/apps/server/src/orchestration-v2/ThreadInsightsQuery.ts +++ b/apps/server/src/orchestration-v2/ThreadInsightsQuery.ts @@ -78,7 +78,13 @@ const make = Effect.gen(function* () { unavailableThreadIds.push(target.threadId); continue; } - const ownTurns = yield* readTurns(target.threadId); + const ownTurns = yield* readTurns(target.threadId).pipe( + Effect.catch((cause) => { + if (target.threadId === input.threadId) return Effect.fail(cause); + unavailableThreadIds.push(target.threadId); + return Effect.succeed([]); + }), + ); const plan = yield* store.getLatestTodoList(target.threadId); const latestRun = snapshot.runs.reduce<(typeof snapshot.runs)[number] | null>( (held, run) => (held === null || run.ordinal > held.ordinal ? run : held), From 1b0526563e7121fab02d292b854a8aff1ce7fc93 Mon Sep 17 00:00:00 2001 From: Lautaro Caballero Date: Sat, 14 Nov 2026 13:56:58 -0300 Subject: [PATCH 04/16] ci(fork): sync upstream and build desktop installers --- .github/workflows/fork-build.yml | 129 +++++++++++++++++++++++++++++++ .github/workflows/fork-sync.yml | 24 ++++++ 2 files changed, 153 insertions(+) create mode 100644 .github/workflows/fork-build.yml create mode 100644 .github/workflows/fork-sync.yml diff --git a/.github/workflows/fork-build.yml b/.github/workflows/fork-build.yml new file mode 100644 index 0000000000000..c97815bd6f6b3 --- /dev/null +++ b/.github/workflows/fork-build.yml @@ -0,0 +1,129 @@ +name: Fork desktop builds +on: + push: + branches: [main] + workflow_dispatch: +permissions: + contents: read +concurrency: + group: fork-desktop-builds + cancel-in-progress: false +jobs: + linux: + if: github.repository == 'LaMarCab76/t3code' + runs-on: ubuntu-24.04 + outputs: + version: ${{ steps.meta.outputs.version }} + env: + T3CODE_DESKTOP_UPDATE_REPOSITORY: LaMarCab76/t3code + T3CODE_TELEMETRY_CHANNEL: dev + CSC_IDENTITY_AUTO_DISCOVERY: "false" + steps: + - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 + with: + sparse-checkout: | + /* + !/.repos/ + sparse-checkout-cone-mode: false + persist-credentials: false + - uses: voidzero-dev/setup-vp@250f29ce396baf5e8f24498e17c0dfdebabc26eb + with: + node-version-file: package.json + run-install: false + - run: sudo apt-get update && sudo apt-get install -y libsecret-1-dev pkg-config libfuse2 imagemagick + - run: vp install --frozen-lockfile --filter=t3... --filter=@t3tools/web... --filter=@t3tools/desktop... --filter=@t3tools/scripts... + - id: meta + run: echo "version=$(node -p 'require("./apps/desktop/package.json").version')-fork.${GITHUB_RUN_NUMBER}" >> "$GITHUB_OUTPUT" + - run: node scripts/update-release-package-versions.ts "${{ steps.meta.outputs.version }}" + - run: node scripts/build-desktop-artifact.ts --platform linux --target AppImage --arch x64 --build-version "${{ steps.meta.outputs.version }}" --output-dir release + - run: | + node apps/server/scripts/cli.ts build-exe + mkdir -p cli-monitor/linux-x64 + cp native/resource-monitor/target/x86_64-unknown-linux-gnu/release/t3-resource-monitor cli-monitor/linux-x64/ + node scripts/build-cli-archive.ts --platform linux --arch x64 --version "${{ steps.meta.outputs.version }}" --resource-monitor-dir "$PWD/cli-monitor" --output-dir release-cli + node scripts/smoke-cli-archive.ts --archive release-cli/*.tar.gz --expect-version "${{ steps.meta.outputs.version }}" + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 + with: + name: wsl-runtime + path: release-cli/*.tar.gz + if-no-files-found: error + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 + with: + name: desktop-linux + path: | + release/*.AppImage + release/*.deb + release/*.yml + if-no-files-found: error + desktop: + needs: linux + strategy: + fail-fast: false + matrix: + include: + - runner: macos-15 + platform: mac + target: dmg + arch: arm64 + - runner: windows-2025 + platform: win + target: nsis + arch: x64 + runs-on: ${{ matrix.runner }} + defaults: + run: + shell: bash + env: + T3CODE_DESKTOP_UPDATE_REPOSITORY: LaMarCab76/t3code + T3CODE_TELEMETRY_CHANNEL: dev + CSC_IDENTITY_AUTO_DISCOVERY: "false" + steps: + - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 + with: + sparse-checkout: | + /* + !/.repos/ + sparse-checkout-cone-mode: false + persist-credentials: false + - uses: voidzero-dev/setup-vp@250f29ce396baf5e8f24498e17c0dfdebabc26eb + with: + node-version-file: package.json + run-install: false + - run: vp install --frozen-lockfile --filter=t3... --filter=@t3tools/web... --filter=@t3tools/desktop... --filter=@t3tools/scripts... + - run: node scripts/update-release-package-versions.ts "${{ needs.linux.outputs.version }}" + - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 + if: matrix.platform == 'win' + with: + name: wsl-runtime + path: wsl-runtime + - run: | + args=() + if [[ "${{ matrix.platform }}" == win ]]; then args+=(--wsl-runtime "$PWD"/wsl-runtime/*.tar.gz); fi + node scripts/build-desktop-artifact.ts --platform "${{ matrix.platform }}" --target "${{ matrix.target }}" --arch "${{ matrix.arch }}" --build-version "${{ needs.linux.outputs.version }}" --output-dir release "${args[@]}" + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 + with: + name: desktop-${{ matrix.platform }} + path: | + release/*.dmg + release/*.zip + release/*.exe + release/*.yml + release/*.blockmap + if-no-files-found: error + publish: + needs: [linux, desktop] + runs-on: ubuntu-latest + permissions: + contents: write + steps: + - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 + with: + path: artifacts + merge-multiple: true + - env: + GH_TOKEN: ${{ github.token }} + VERSION: ${{ needs.linux.outputs.version }} + run: | + cd artifacts + sha256sum * > SHA256SUMS + gh release create "fork-v$VERSION" * --repo "$GITHUB_REPOSITORY" --target "$GITHUB_SHA" --title "T3 Code fork $VERSION" --notes "macOS arm64, Windows x64 and Linux x64. Personal unsigned builds; source $GITHUB_SHA." diff --git a/.github/workflows/fork-sync.yml b/.github/workflows/fork-sync.yml new file mode 100644 index 0000000000000..9ba5d881e6531 --- /dev/null +++ b/.github/workflows/fork-sync.yml @@ -0,0 +1,24 @@ +name: Fork upstream sync +on: + schedule: + - cron: "23 */6 * * *" + workflow_dispatch: +permissions: + contents: write + actions: write +concurrency: + group: fork-upstream-sync + cancel-in-progress: false +jobs: + sync: + if: github.repository == 'LaMarCab76/t3code' + runs-on: ubuntu-latest + steps: + - uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd + with: + script: | + const { owner, repo } = context.repo; + const upstream = await github.rest.repos.getBranch({ owner: 'pingdotgg', repo: 't3code', branch: 'main' }); + const result = await github.rest.repos.merge({ owner, repo, base: 'main', head: upstream.data.commit.sha, commit_message: 'chore(fork): sync upstream main' }); + if (result.status === 204) return; + await github.rest.actions.createWorkflowDispatch({ owner, repo, workflow_id: 'fork-build.yml', ref: 'main' }); From 9920fd0634059f39971234b63e1b058655d89e5e Mon Sep 17 00:00:00 2001 From: Lautaro Caballero Date: Sat, 14 Nov 2026 16:40:16 -0300 Subject: [PATCH 05/16] feat(threads): optionally snooze a thread until its next scheduled task run When a turn ends in a thread that has an upcoming scheduled task, the thread stays in Active even though nothing needs the user until the task runs. Add an opt-in server setting, snoozeThreadsUntilScheduledTask. A reactor listens for completed runs and, under the thread's dispatch lock, snoozes the thread until the soonest future run of an enabled task bound to it. The task's own run and automatic follow-ups (notifications, delegated completions) never trigger it, and neither does a turn that ends on a pending request or with other work queued. The existing dispatch wake brings the thread back when the task starts. Older servers hide the switch through the scheduledTaskSnooze capability. Co-Authored-By: Claude Opus 5.5 --- .../SettingsServerControlsRouteScreen.tsx | 1 + .../settings/ThreadSettingsSections.tsx | 17 ++ .../src/environment/ServerEnvironment.ts | 1 + .../src/orchestration-v2/Orchestrator.ts | 46 ++++ .../scheduledTasks/ScheduledTaskService.ts | 20 ++ .../ScheduledTaskSnoozeReactor.test.ts | 242 ++++++++++++++++++ .../ScheduledTaskSnoozeReactor.ts | 85 ++++++ apps/server/src/server.ts | 7 + .../components/settings/SettingsPanels.tsx | 28 ++ .../src/components/settings/settingsSearch.ts | 8 + docs/user/thread-sidebar.md | 6 + .../src/state/sharedSettings.ts | 1 + packages/contracts/src/environment.ts | 2 + packages/contracts/src/settings.ts | 4 + 14 files changed, 468 insertions(+) create mode 100644 apps/server/src/scheduledTasks/ScheduledTaskSnoozeReactor.test.ts create mode 100644 apps/server/src/scheduledTasks/ScheduledTaskSnoozeReactor.ts diff --git a/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.tsx index 5026a90e13b9a..08d54ad6e30ea 100644 --- a/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.tsx +++ b/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.tsx @@ -139,6 +139,7 @@ const AUTO_SETTLE_SETTING_KEYS: ReadonlySet = new Set([ "sidebarAutoSettleAfterDays", "autoResumeLimitedThreads", "snoozeLimitedThreads", + "snoozeThreadsUntilScheduledTask", ]); function planServerSettingsWrites( diff --git a/apps/mobile/src/features/settings/ThreadSettingsSections.tsx b/apps/mobile/src/features/settings/ThreadSettingsSections.tsx index 41600619b3a47..a85176ad24ae6 100644 --- a/apps/mobile/src/features/settings/ThreadSettingsSections.tsx +++ b/apps/mobile/src/features/settings/ThreadSettingsSections.tsx @@ -101,6 +101,7 @@ export function AutoSettleSettingsRows(props: { patch: Partial & { autoResumeLimitedThreads?: boolean; snoozeLimitedThreads?: boolean; + snoozeThreadsUntilScheduledTask?: boolean; }, ) => props.write(patch); @@ -122,6 +123,10 @@ export function AutoSettleSettingsRows(props: { const disabledFor = (...keys: string[]) => disabled || managedSettingReason(displayTargets, ...keys) !== undefined; const afterDays = referenceSettings.sidebarAutoSettleAfterDays; + const supportsScheduledTaskSnooze = displayTargets.every( + (target) => + target.environment.serverConfig.environment.capabilities.scheduledTaskSnooze === true, + ); return ( @@ -145,6 +150,18 @@ export function AutoSettleSettingsRows(props: { /> ) : null} + {!projectSelected && supportsScheduledTaskSnooze ? ( + + writeToAll({ snoozeThreadsUntilScheduledTask: value })} + /> + + ) : null} Effect.Effect; + /** Snoozes only while `runId` is still the thread's last run and nothing else needs the user. */ + readonly autoSnoozeAfterRun: (input: { + readonly commandId: CommandId; + readonly threadId: ThreadId; + readonly runId: RunId; + readonly snoozedUntil: DateTime.Utc; + }) => Effect.Effect; readonly searchThreadStream: ( input: OrchestrationV2SearchThreadInput, ) => Stream.Stream; @@ -16124,6 +16131,45 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio }), ); }), + autoSnoozeAfterRun: Effect.fn("OrchestratorV2.autoSnoozeAfterRun")(function (input) { + return threadDispatch.withLock( + input.threadId, + Effect.gen(function* () { + const { thread, runs, runtimeRequests } = yield* projectionStore + .getThreadRecords(input.threadId, ["runs", "runtimeRequests"]) + .pipe( + Effect.mapError( + (cause) => new OrchestratorProjectionError({ threadId: input.threadId, cause }), + ), + ); + const now = yield* DateTime.now; + const latest = runs.reduce( + (found, run) => (found === undefined || run.ordinal > found.ordinal ? run : found), + undefined, + ); + // The caller read the thread before this lock; a message sent since then wins. + if ( + latest?.id !== input.runId || + latest.status !== "completed" || + runs.some((run) => run.status === "queued" || isActiveRun(run)) || + runtimeRequests.some((request) => request.status === "pending") || + thread.archivedAt !== null || + thread.deletedAt !== null || + thread.settledOverride === "settled" || + (thread.snoozedUntil != null && + DateTime.toEpochMillis(thread.snoozedUntil) > DateTime.toEpochMillis(now)) || + DateTime.toEpochMillis(input.snoozedUntil) <= DateTime.toEpochMillis(now) + ) + return; + yield* dispatchWithReceiptEffect({ + type: "thread.snooze", + commandId: input.commandId, + threadId: input.threadId, + snoozedUntil: DateTime.formatIso(input.snoozedUntil), + }); + }), + ); + }), searchThreadStream: (input) => projectionStore .searchThreadStream(input) diff --git a/apps/server/src/scheduledTasks/ScheduledTaskService.ts b/apps/server/src/scheduledTasks/ScheduledTaskService.ts index 05fdbe8b08992..a771a64e03843 100644 --- a/apps/server/src/scheduledTasks/ScheduledTaskService.ts +++ b/apps/server/src/scheduledTasks/ScheduledTaskService.ts @@ -425,6 +425,26 @@ const decodeRow = Effect.fnUntraced( ), ); +/** The soonest future run of an enabled task bound to this thread, or null. */ +export const nextRunForThread = Effect.fn("ScheduledTaskService.nextRunForThread")(function* ( + threadId: ThreadId, + now: DateTime.DateTime, +) { + const sql = yield* SqlClient.SqlClient; + const rows = yield* sql<{ next_run_at: string }>` + SELECT next_run_at FROM scheduled_tasks + WHERE thread_id = ${threadId} AND enabled = 1 + AND next_run_at IS NOT NULL AND next_run_at > ${iso(now)} + ORDER BY next_run_at ASC + `.pipe(NodeSqliteClient.readOnly); + // next_run_at is freeform; the soonest parseable value wins. + for (const row of rows) { + const parsed = DateTime.make(row.next_run_at); + if (Option.isSome(parsed)) return DateTime.toUtc(parsed.value); + } + return null; +}); + export const listDueTasks = Effect.fn("ScheduledTaskService.listDueTasks")(function* ( now: DateTime.DateTime, ) { diff --git a/apps/server/src/scheduledTasks/ScheduledTaskSnoozeReactor.test.ts b/apps/server/src/scheduledTasks/ScheduledTaskSnoozeReactor.test.ts new file mode 100644 index 0000000000000..da1b0e562993d --- /dev/null +++ b/apps/server/src/scheduledTasks/ScheduledTaskSnoozeReactor.test.ts @@ -0,0 +1,242 @@ +import { assert, it } from "@effect/vitest"; +import { + CommandId, + EventId, + MessageId, + type OrchestrationV2DomainEvent, + ProjectId, + ProviderDriverKind, + ProviderInstanceId, + RuntimeRequestId, + ScheduledTaskId, + ThreadId, +} from "@t3tools/contracts"; +import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as SqlClient from "effect/sql/SqlClient"; + +import { CodexProviderCapabilitiesV2 } from "../orchestration-v2/Adapters/CodexAdapterV2.ts"; +import * as EventSink from "../orchestration-v2/EventSink.ts"; +import * as Orchestrator from "../orchestration-v2/Orchestrator.ts"; +import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts"; +import * as ProviderAdapterRegistry from "../orchestration-v2/ProviderAdapterRegistry.ts"; +import * as ProviderReplayHarness from "../orchestration-v2/testkit/ProviderReplayHarness.ts"; +import * as SqlitePersistence from "../persistence/Sqlite.ts"; +import * as ServerSettings from "../serverSettings.ts"; +import * as ScheduledTaskSnoozeReactor from "./ScheduledTaskSnoozeReactor.ts"; + +const instanceId = ProviderInstanceId.make("codex"); +const modelSelection = { instanceId, model: "gpt-5.1-codex" }; +const adapter = { + instanceId, + driver: ProviderDriverKind.make("codex"), + getCapabilities: () => Effect.succeed(CodexProviderCapabilitiesV2), + planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" as const }), + openSession: () => Effect.die("No provider process needed"), +} as ProviderAdapter.ProviderAdapterV2["Service"]; +const layerDatabase = SqlitePersistence.layerMemory; +const layerTest = (snoozeThreadsUntilScheduledTask: boolean) => + ScheduledTaskSnoozeReactor.layer.pipe( + Layer.provideMerge( + Layer.mergeAll( + layerDatabase, + ProjectionStore.layer.pipe(Layer.provide(layerDatabase)), + ServerSettings.layerTest({ snoozeThreadsUntilScheduledTask }), + ProviderReplayHarness.layerWithRegistry( + { name: "scheduled-task-snooze" }, + ProviderAdapterRegistry.layerFromAdapters([adapter]), + { databaseLayer: layerDatabase, runEffectWorker: false }, + ), + ), + ), + ); + +const threadId = ThreadId.make("thread:scheduled-snooze"); +const NEXT_RUN = "2030-01-01T09:00:00.000Z"; + +const insertTask = ( + sql: SqlClient.SqlClient, + task: { id: string; threadId: string; next: string | null; enabled?: number }, +) => + sql`INSERT INTO scheduled_tasks ${sql.insert({ + task_id: task.id, + title: "task", + prompt: "Run task", + enabled: task.enabled ?? 1, + schedule_json: '{"type":"interval","everyMs":60000}', + project_id: "project:scheduled-snooze", + thread_id: task.threadId, + workspace_strategy_json: '{"type":"root"}', + model_selection_json: '{"instanceId":"codex","model":"gpt-5"}', + runtime_mode: "full-access", + interaction_mode: "default", + created_by: "user", + creation_source: "web", + created_at: "2026-01-01T00:00:00.000Z", + updated_at: "2026-01-01T00:00:00.000Z", + next_run_at: task.next, + last_run_at: null, + last_run_status: "never", + last_run_error: null, + run_count: 0, + })}`; + +/** Starts a turn from `message`, writes its completion, and lets the reactor see it. */ +const completeTurn = Effect.fn("test.completeTurn")(function* ( + message: { scheduledTaskId?: ScheduledTaskId } = {}, + options: { queueAnother?: boolean; pendingQuestion?: boolean; sendBeforeHandle?: boolean } = {}, +) { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const projections = yield* ProjectionStore.ProjectionStoreV2; + const eventSink = yield* EventSink.EventSinkV2; + const reactor = yield* ScheduledTaskSnoozeReactor.ScheduledTaskSnoozeReactor; + yield* orchestrator.dispatch({ + type: "thread.create", + commandId: CommandId.make("create-scheduled-snooze"), + threadId, + projectId: ProjectId.make("project:scheduled-snooze"), + title: "Scheduled snooze", + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + createdBy: "user", + creationSource: "web", + }); + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make("send-scheduled-snooze"), + threadId, + messageId: MessageId.make("message:scheduled-snooze"), + text: "Schedule a daily check", + attachments: [], + dispatchMode: { type: "start_immediately" }, + createdBy: "user", + creationSource: "web", + ...message, + }); + if (options.queueAnother === true) { + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make("queue-scheduled-snooze"), + threadId, + messageId: MessageId.make("message:scheduled-snooze-queued"), + text: "And another thing", + attachments: [], + dispatchMode: { type: "queue_after_active" }, + createdBy: "user", + creationSource: "web", + }); + } + const { runs } = yield* projections.getThreadRecords(threadId, ["runs"]); + const run = runs.find((candidate) => candidate.ordinal === 1)!; + const now = yield* DateTime.now; + const events: OrchestrationV2DomainEvent[] = []; + if (options.pendingQuestion === true) { + events.push({ + id: EventId.make("event:scheduled-snooze-question"), + type: "runtime-request.updated", + threadId, + runId: run.id, + occurredAt: now, + payload: { + id: RuntimeRequestId.make("request:scheduled-snooze"), + nodeId: run.rootNodeId!, + providerTurnId: null, + nativeRequestRef: null, + kind: "user_input", + status: "pending", + responseCapability: { type: "message" }, + createdAt: now, + resolvedAt: null, + }, + }); + } + const completed = { + id: EventId.make("event:scheduled-snooze-completed"), + type: "run.updated", + threadId, + runId: run.id, + occurredAt: now, + payload: { ...run, status: "completed", startedAt: now, completedAt: now }, + } satisfies OrchestrationV2DomainEvent; + events.push(completed); + yield* eventSink.write({ events }); + if (options.sendBeforeHandle === true) { + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make("follow-up-scheduled-snooze"), + threadId, + messageId: MessageId.make("message:scheduled-snooze-follow-up"), + text: "One more thing", + attachments: [], + dispatchMode: { type: "start_immediately" }, + createdBy: "user", + creationSource: "web", + }); + } + yield* reactor.handle(completed); + return completed; +}); + +const snoozedUntil = Effect.gen(function* () { + const projections = yield* ProjectionStore.ProjectionStoreV2; + const thread = yield* projections.getThread(threadId); + return thread.snoozedUntil == null ? null : DateTime.formatIso(thread.snoozedUntil); +}); + +it.effect("snoozes until the soonest future run of an enabled task bound to the thread", () => + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + yield* insertTask(sql, { id: "later", threadId, next: "2030-02-01T00:00:00.000Z" }); + yield* insertTask(sql, { id: "soonest", threadId, next: NEXT_RUN }); + yield* insertTask(sql, { + id: "paused", + threadId, + next: "2029-06-01T00:00:00.000Z", + enabled: 0, + }); + yield* insertTask(sql, { id: "overdue", threadId, next: "1969-01-01T00:00:00.000Z" }); + yield* insertTask(sql, { id: "webhook", threadId, next: null }); + yield* insertTask(sql, { + id: "other", + threadId: "thread:other", + next: "2029-06-01T00:00:00.000Z", + }); + const completed = yield* completeTurn(); + assert.strictEqual(yield* snoozedUntil, NEXT_RUN); + + // A re-emitted completion must not undo a manual wake. + const orchestrator = yield* Orchestrator.OrchestratorV2; + yield* orchestrator.dispatch({ + type: "thread.unsnooze", + commandId: CommandId.make("wake-scheduled-snooze"), + threadId, + reason: "user", + }); + const reactor = yield* ScheduledTaskSnoozeReactor.ScheduledTaskSnoozeReactor; + yield* reactor.handle(completed); + assert.strictEqual(yield* snoozedUntil, null); + }).pipe(Effect.provide(layerTest(true))), +); + +it.effect.each([ + { name: "the setting is off", setting: false }, + { name: "the run is the task's own", setting: true, fromTask: true }, + { name: "another run is still queued", setting: true, queueAnother: true }, + { name: "the turn ended on a question", setting: true, pendingQuestion: true }, + { name: "a message arrives before the snooze", setting: true, sendBeforeHandle: true }, +])("leaves the thread awake when $name", (scenario) => + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + yield* insertTask(sql, { id: "soonest", threadId, next: NEXT_RUN }); + yield* completeTurn( + scenario.fromTask === true ? { scheduledTaskId: ScheduledTaskId.make("soonest") } : {}, + scenario, + ); + assert.strictEqual(yield* snoozedUntil, null); + }).pipe(Effect.provide(layerTest(scenario.setting))), +); diff --git a/apps/server/src/scheduledTasks/ScheduledTaskSnoozeReactor.ts b/apps/server/src/scheduledTasks/ScheduledTaskSnoozeReactor.ts new file mode 100644 index 0000000000000..cf43273bf1b71 --- /dev/null +++ b/apps/server/src/scheduledTasks/ScheduledTaskSnoozeReactor.ts @@ -0,0 +1,85 @@ +import { CommandId, type OrchestrationV2DomainEvent } from "@t3tools/contracts"; +import * as Context from "effect/Context"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as SqlClient from "effect/sql/SqlClient"; +import type * as Scope from "effect/Scope"; +import * as Stream from "effect/Stream"; + +import * as Orchestrator from "../orchestration-v2/Orchestrator.ts"; +import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts"; +import { forkParked } from "../serverActivation.ts"; +import * as ServerSettings from "../serverSettings.ts"; +import { nextRunForThread } from "./ScheduledTaskService.ts"; + +export class ScheduledTaskSnoozeReactor extends Context.Service< + ScheduledTaskSnoozeReactor, + { + readonly start: () => Effect.Effect; + readonly handle: (event: OrchestrationV2DomainEvent) => Effect.Effect; + } +>()("t3/scheduledTasks/ScheduledTaskSnoozeReactor") {} + +const make = Effect.gen(function* () { + const engine = yield* Orchestrator.OrchestratorV2; + const projections = yield* ProjectionStore.ProjectionStoreV2; + const settings = yield* ServerSettings.ServerSettingsService; + const sql = yield* SqlClient.SqlClient; + + // Runs for every domain event; most events return before any work is needed. + const handle: ScheduledTaskSnoozeReactor["Service"]["handle"] = Effect.fnUntraced( + function* (event) { + if (event.type !== "run.updated" || event.payload.status !== "completed") return; + const { snoozeThreadsUntilScheduledTask } = yield* settings.getSettings; + if (!snoozeThreadsUntilScheduledTask) return; + const run = event.payload; + // The task's own run and its automatic follow-ups leave their result visible. + const { messages } = yield* projections.getThreadRecords(event.threadId, ["messages"], { + messageIds: [run.userMessageId], + }); + const message = messages.find((candidate) => candidate.id === run.userMessageId); + if ( + message?.scheduledTaskId !== undefined || + message?.notification !== undefined || + message?.delegatedCompletion !== undefined + ) { + return; + } + const nextRun = yield* nextRunForThread(event.threadId, yield* DateTime.now).pipe( + Effect.provideService(SqlClient.SqlClient, sql), + ); + if (nextRun === null) return; + // Completion is re-emitted (checkpoints, delegated rewrites); one id per run keeps a + // later manual wake from being undone. + yield* engine.autoSnoozeAfterRun({ + commandId: CommandId.make(`server:scheduled-task-snooze:${run.id}`), + threadId: event.threadId, + runId: run.id, + snoozedUntil: nextRun, + }); + }, + (effect, event) => + effect.pipe( + Effect.catchCause((cause) => + Effect.logWarning("snoozing a thread until its scheduled task failed", { + threadId: event.threadId, + cause, + }), + ), + ), + ); + + const start: ScheduledTaskSnoozeReactor["Service"]["start"] = () => + forkParked( + Stream.runForEach(engine.streamDomainEvents, handle).pipe( + Effect.catchCause((cause) => + Effect.logWarning("scheduled task snooze event stream failed", { cause }), + ), + ), + ); + + return { start, handle } satisfies ScheduledTaskSnoozeReactor["Service"]; +}); + +export const layer = Layer.effect(ScheduledTaskSnoozeReactor, make); diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index 8b1cce579162f..76250b12ffc56 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -8,6 +8,7 @@ import * as StorageCleanup from "./storageCleanup.ts"; import * as PullRequestSyncReactor from "./orchestration-v2/PullRequestSyncReactor.ts"; import * as PullRequestWatchReactor from "./orchestration-v2/PullRequestWatchReactor.ts"; import * as DelegatedTaskQuestionReactor from "./orchestration-v2/DelegatedTaskQuestionReactor.ts"; +import * as ScheduledTaskSnoozeReactor from "./scheduledTasks/ScheduledTaskSnoozeReactor.ts"; // Effect wraps this raw Node HTTP server after its startup and write-error guards attach. // @effect-diagnostics nodeBuiltinImport:off import * as NodeHttp from "node:http"; @@ -706,6 +707,12 @@ const layerRuntimeCoreDependenciesBase = Layer.mergeAll( yield* service.start(); }), ).pipe(Layer.provide(DelegatedTaskQuestionReactor.layer), Layer.provide(ProjectionStoreV2.layer)), + Layer.effectDiscard( + Effect.gen(function* () { + const service = yield* ScheduledTaskSnoozeReactor.ScheduledTaskSnoozeReactor; + yield* service.start(); + }), + ).pipe(Layer.provide(ScheduledTaskSnoozeReactor.layer), Layer.provide(ProjectionStoreV2.layer)), ProviderUsageLimitsIngestion.layer, layerProviderInstallationRefresh, ProviderInstallation.layer, diff --git a/apps/web/src/components/settings/SettingsPanels.tsx b/apps/web/src/components/settings/SettingsPanels.tsx index 633e18a567b2f..96deb2b8e66a1 100644 --- a/apps/web/src/components/settings/SettingsPanels.tsx +++ b/apps/web/src/components/settings/SettingsPanels.tsx @@ -515,6 +515,10 @@ export function useSettingsRestore(onRestored?: () => void) { ...(!Equal.equals(settings.snoozePresets, DEFAULT_UNIFIED_SETTINGS.snoozePresets) ? ["Snooze options"] : []), + ...(settings.snoozeThreadsUntilScheduledTask !== + DEFAULT_UNIFIED_SETTINGS.snoozeThreadsUntilScheduledTask + ? ["Snooze until scheduled task runs"] + : []), ...(settings.wordWrap !== DEFAULT_UNIFIED_SETTINGS.wordWrap ? ["Word wrap"] : []), ...(settings.persistComposerContextStrip !== DEFAULT_UNIFIED_SETTINGS.persistComposerContextStrip @@ -683,6 +687,7 @@ export function useSettingsRestore(onRestored?: () => void) { autoResumeLimitedThreads: DEFAULT_UNIFIED_SETTINGS.autoResumeLimitedThreads, snoozeLimitedThreads: DEFAULT_UNIFIED_SETTINGS.snoozeLimitedThreads, snoozePresets: DEFAULT_UNIFIED_SETTINGS.snoozePresets, + snoozeThreadsUntilScheduledTask: DEFAULT_UNIFIED_SETTINGS.snoozeThreadsUntilScheduledTask, responseStreamingMode: DEFAULT_UNIFIED_SETTINGS.responseStreamingMode, enableProviderUpdateChecks: DEFAULT_UNIFIED_SETTINGS.enableProviderUpdateChecks, continueThreadsAfterServerUpdate: DEFAULT_UNIFIED_SETTINGS.continueThreadsAfterServerUpdate, @@ -1735,6 +1740,11 @@ export function ThreadsSettingsPanel() { const supportsAutoSettlementScope = connectedEnvironments.every( (target) => target.serverConfig?.environment.capabilities.threadAutoSettlementScope === true, ); + const supportsScheduledTaskSnooze = + hasServerTargets && + connectedEnvironments.every( + (target) => target.serverConfig?.environment.capabilities.scheduledTaskSnooze === true, + ); const textGenerationTargets = useTextGenerationTargets({ environmentId, @@ -1843,6 +1853,24 @@ export function ThreadsSettingsPanel() { {!isProjectScope ? ( + {supportsScheduledTaskSnooze ? ( + + updateSettings({ snoozeThreadsUntilScheduledTask: Boolean(checked) }) + } + aria-label="Snooze until scheduled task runs" + /> + } + /> + ) : null} ) : null} diff --git a/apps/web/src/components/settings/settingsSearch.ts b/apps/web/src/components/settings/settingsSearch.ts index 7d7939e7f21f9..ac6ae7f912ce2 100644 --- a/apps/web/src/components/settings/settingsSearch.ts +++ b/apps/web/src/components/settings/settingsSearch.ts @@ -453,6 +453,14 @@ export const SETTINGS_SEARCH_ITEMS = [ to: "/settings/threads", searchTerms: ["usage quota rate limit reset wake recover continue"], }, + { + id: "snooze-until-scheduled-task", + title: "Snooze until scheduled task runs", + to: "/settings/threads", + searchTerms: ["scheduled task schedule automation recurring wake hide next run"], + environmentOnly: true, + scope: "environment-defaults", + }, { id: "auto-resume-limited-threads", title: "Resume after usage limits", diff --git a/docs/user/thread-sidebar.md b/docs/user/thread-sidebar.md index 4c02f1c79baee..254eeb7d84f87 100644 --- a/docs/user/thread-sidebar.md +++ b/docs/user/thread-sidebar.md @@ -339,3 +339,9 @@ A snoozed thread keeps working and stays hidden until its wake time, even while its agent wakes itself for background work. It comes back early for an approval, a new question, a failed run, or a message or answer you send. You can snooze an existing question and answer when the thread wakes; the question stays unanswered. + +To hide a thread while it waits for its own scheduled task, turn on **Settings → Threads → +Snooze until scheduled task runs**. When a turn ends and the thread has an enabled scheduled task +coming up, the thread snoozes until that task's next run, then wakes when the task starts. The +task's own turn leaves its result visible. Pausing or rescheduling the task does not move the wake +time; choose **Wake thread** to bring the thread back sooner. diff --git a/packages/client-runtime/src/state/sharedSettings.ts b/packages/client-runtime/src/state/sharedSettings.ts index 77dbddadb6bbb..244353a3ce8e3 100644 --- a/packages/client-runtime/src/state/sharedSettings.ts +++ b/packages/client-runtime/src/state/sharedSettings.ts @@ -11,6 +11,7 @@ const SHARED_SERVER_SETTING_KEYS = [ "autoResumeLimitedThreads", "snoozeLimitedThreads", "snoozePresets", + "snoozeThreadsUntilScheduledTask", "newWorktreesStartFromOrigin", "sourceControlWritingStyle", "textGenerationModelSelection", diff --git a/packages/contracts/src/environment.ts b/packages/contracts/src/environment.ts index ad1cfe30b0214..cfd44c6168a3d 100644 --- a/packages/contracts/src/environment.ts +++ b/packages/contracts/src/environment.ts @@ -195,6 +195,8 @@ export const ExecutionEnvironmentCapabilities = Schema.Struct({ freshContext: Schema.optionalKey(Schema.Boolean), /** Server saves and runs scheduled task `threadMode`; older servers ignore it. */ scheduledTaskThreadModes: Schema.optionalKey(Schema.Boolean), + /** Server honors `snoozeThreadsUntilScheduledTask`; older servers ignore it. */ + scheduledTaskSnooze: Schema.optionalKey(Schema.Boolean), /** Server can transcribe 16 kHz mono PCM audio on the environment machine. */ voiceTranscription: Schema.optionalKey(Schema.Boolean), cloudVoiceTranscription: Schema.optionalKey(Schema.Boolean), diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts index 7bbb03595d4bb..35a4eed5350e1 100644 --- a/packages/contracts/src/settings.ts +++ b/packages/contracts/src/settings.ts @@ -1452,6 +1452,9 @@ export const ServerSettings = Schema.Struct({ ), idleCompaction: Schema.optionalKey(IdleCompactionMode), snoozeLimitedThreads: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))), + snoozeThreadsUntilScheduledTask: Schema.Boolean.pipe( + Schema.withDecodingDefault(Effect.succeed(false)), + ), autoResumeLimitedThreads: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))), snoozePresets: SnoozePresetSettings.pipe( Schema.withDecodingDefault(Effect.succeed(DEFAULT_SNOOZE_PRESETS)), @@ -1901,6 +1904,7 @@ export const ServerSettingsPatch = Schema.Struct({ sidebarAutoSettleOnMerge: Schema.optionalKey(Schema.Boolean), autoResumeLimitedThreads: Schema.optionalKey(Schema.Boolean), snoozeLimitedThreads: Schema.optionalKey(Schema.Boolean), + snoozeThreadsUntilScheduledTask: Schema.optionalKey(Schema.Boolean), snoozePresets: Schema.optionalKey(SnoozePresetSettings), hiddenThreadTags: Schema.optionalKey(Schema.Array(Schema.String)), hideTaggedThreads: Schema.optionalKey(Schema.Boolean), From ee834429e65d67648b9f034d9bfb7e4df915545d Mon Sep 17 00:00:00 2001 From: Lautaro Caballero Date: Sat, 14 Nov 2026 16:53:44 -0300 Subject: [PATCH 06/16] ci(fork): build personal releases as T3 Code L with the nightly logo Co-Authored-By: Claude Opus 5.5 --- .github/fork/brand-l.mjs | 54 ++++++++++++++++++++++++++++++++ .github/workflows/fork-build.yml | 4 ++- 2 files changed, 57 insertions(+), 1 deletion(-) create mode 100644 .github/fork/brand-l.mjs diff --git a/.github/fork/brand-l.mjs b/.github/fork/brand-l.mjs new file mode 100644 index 0000000000000..392db37865e68 --- /dev/null +++ b/.github/fork/brand-l.mjs @@ -0,0 +1,54 @@ +// Personal fork branding: "T3 Code L" with the nightly logo, sharing the official app's data +// (~/.t3 and the t3code-v2 Chromium profile). Run from the repo root on a throwaway checkout +// before `scripts/build-desktop-artifact.ts`; it rewrites tracked files and must not be committed. +import * as NodeFS from "node:fs"; + +const NAME = "T3 Code L"; +const APP_ID = "com.lamarcab76.t3code.l"; + +function replaceOnce(path, from, to) { + const text = NodeFS.readFileSync(path, "utf8"); + if (text.split(from).length !== 2) throw new Error(`${path}: expected exactly one "${from}"`); + NodeFS.writeFileSync(path, text.replace(from, to)); +} + +replaceOnce( + "apps/desktop/src/app/DesktopEnvironment.ts", + 'const APP_BASE_NAME = "T3 Code";', + `const APP_BASE_NAME = "${NAME}";`, +); +replaceOnce( + "apps/desktop/src/app/DesktopEnvironment.ts", + "displayName: `${APP_BASE_NAME} (${stageLabel})`,", + "displayName: APP_BASE_NAME,", +); +replaceOnce( + "apps/desktop/src/app/DesktopAppIdentity.ts", + "`${environment.branding.baseName} ${environment.branding.stageLabel}`,", + "environment.displayName,", +); +replaceOnce( + "scripts/build-desktop-artifact.ts", + 'const DESKTOP_APP_ID = "com.t3tools.t3code";', + `const DESKTOP_APP_ID = "${APP_ID}";`, +); +replaceOnce( + "apps/desktop/package.json", + '"productName": "T3 Code (Beta)"', + `"productName": "${NAME}"`, +); + +const icons = [ + ["nightly-macos-1024.png", "black-macos-1024.png"], + ["nightly-universal-1024.png", "black-universal-1024.png"], + ["nightly-windows.ico", "t3-black-windows.ico"], + ["nightly-web-favicon.ico", "t3-black-web-favicon.ico"], + ["nightly-web-favicon-16x16.png", "t3-black-web-favicon-16x16.png"], + ["nightly-web-favicon-32x32.png", "t3-black-web-favicon-32x32.png"], + ["nightly-web-apple-touch-180.png", "t3-black-web-apple-touch-180.png"], + ["nightly-web-icon-192x192.png", "t3-black-web-icon-192x192.png"], + ["nightly-web-icon-512x512.png", "t3-black-web-icon-512x512.png"], +]; +for (const [from, to] of icons) NodeFS.copyFileSync(`assets/nightly/${from}`, `assets/prod/${to}`); + +console.log(`Branded as ${NAME} (${APP_ID}) with the nightly logo.`); diff --git a/.github/workflows/fork-build.yml b/.github/workflows/fork-build.yml index c97815bd6f6b3..615df6610a5bc 100644 --- a/.github/workflows/fork-build.yml +++ b/.github/workflows/fork-build.yml @@ -32,6 +32,7 @@ jobs: run-install: false - run: sudo apt-get update && sudo apt-get install -y libsecret-1-dev pkg-config libfuse2 imagemagick - run: vp install --frozen-lockfile --filter=t3... --filter=@t3tools/web... --filter=@t3tools/desktop... --filter=@t3tools/scripts... + - run: node .github/fork/brand-l.mjs - id: meta run: echo "version=$(node -p 'require("./apps/desktop/package.json").version')-fork.${GITHUB_RUN_NUMBER}" >> "$GITHUB_OUTPUT" - run: node scripts/update-release-package-versions.ts "${{ steps.meta.outputs.version }}" @@ -90,6 +91,7 @@ jobs: node-version-file: package.json run-install: false - run: vp install --frozen-lockfile --filter=t3... --filter=@t3tools/web... --filter=@t3tools/desktop... --filter=@t3tools/scripts... + - run: node .github/fork/brand-l.mjs - run: node scripts/update-release-package-versions.ts "${{ needs.linux.outputs.version }}" - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 if: matrix.platform == 'win' @@ -126,4 +128,4 @@ jobs: run: | cd artifacts sha256sum * > SHA256SUMS - gh release create "fork-v$VERSION" * --repo "$GITHUB_REPOSITORY" --target "$GITHUB_SHA" --title "T3 Code fork $VERSION" --notes "macOS arm64, Windows x64 and Linux x64. Personal unsigned builds; source $GITHUB_SHA." + gh release create "fork-v$VERSION" * --repo "$GITHUB_REPOSITORY" --target "$GITHUB_SHA" --title "T3 Code L $VERSION" --notes "macOS arm64, Windows x64 and Linux x64. Personal unsigned builds; source $GITHUB_SHA." From b24b6382992213e67aced6d65b12c15f220a9129 Mon Sep 17 00:00:00 2001 From: Lautaro Caballero Date: Sun, 15 Nov 2026 09:55:09 -0300 Subject: [PATCH 07/16] fix(fork): publish increasing versions with updater-compatible tags --- .github/workflows/fork-build.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/fork-build.yml b/.github/workflows/fork-build.yml index 615df6610a5bc..fb856d4236099 100644 --- a/.github/workflows/fork-build.yml +++ b/.github/workflows/fork-build.yml @@ -34,7 +34,7 @@ jobs: - run: vp install --frozen-lockfile --filter=t3... --filter=@t3tools/web... --filter=@t3tools/desktop... --filter=@t3tools/scripts... - run: node .github/fork/brand-l.mjs - id: meta - run: echo "version=$(node -p 'require("./apps/desktop/package.json").version')-fork.${GITHUB_RUN_NUMBER}" >> "$GITHUB_OUTPUT" + run: echo "version=$(node -p 'require("./apps/desktop/package.json").version')-fork.$(date -u +%Y%m%d).${GITHUB_RUN_NUMBER}" >> "$GITHUB_OUTPUT" - run: node scripts/update-release-package-versions.ts "${{ steps.meta.outputs.version }}" - run: node scripts/build-desktop-artifact.ts --platform linux --target AppImage --arch x64 --build-version "${{ steps.meta.outputs.version }}" --output-dir release - run: | @@ -128,4 +128,4 @@ jobs: run: | cd artifacts sha256sum * > SHA256SUMS - gh release create "fork-v$VERSION" * --repo "$GITHUB_REPOSITORY" --target "$GITHUB_SHA" --title "T3 Code L $VERSION" --notes "macOS arm64, Windows x64 and Linux x64. Personal unsigned builds; source $GITHUB_SHA." + gh release create "v$VERSION" * --repo "$GITHUB_REPOSITORY" --target "$GITHUB_SHA" --title "T3 Code L $VERSION" --notes "macOS arm64, Windows x64 and Linux x64. Personal unsigned builds; source $GITHUB_SHA." From 75aa7e85a85fb933aa35b9e8a5111e5e80e8603c Mon Sep 17 00:00:00 2001 From: Lautaro Caballero Date: Sun, 15 Nov 2026 10:38:50 -0300 Subject: [PATCH 08/16] fix(fork): include update feed in local installer builds [skip ci] --- scripts/build-desktop-artifact.test.ts | 24 ++++++++++++++++++++++++ scripts/build-desktop-artifact.ts | 2 +- 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/scripts/build-desktop-artifact.test.ts b/scripts/build-desktop-artifact.test.ts index c9180ec3d3ae6..6d3fa22c2c92a 100644 --- a/scripts/build-desktop-artifact.test.ts +++ b/scripts/build-desktop-artifact.test.ts @@ -537,6 +537,30 @@ it.layer(NodeServices.layer)("build-desktop-artifact", (it) => { assert.isNull(preview.publish); assert.isNull(previewChannel.publish); + + for (const [platform, target] of [ + ["mac", "dmg"], + ["win", "nsis"], + ["linux", "AppImage"], + ] as const) { + const forkRelease = yield* createBuildConfig( + platform, + target, + "0.1.9-fork.20261115.2", + false, + false, + undefined, + undefined, + ).pipe(Effect.provide(ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} })))); + assert.deepStrictEqual(forkRelease.publish, [ + { + provider: "github", + owner: "LaMarCab76", + repo: "t3code", + releaseType: "release", + }, + ]); + } assert.deepStrictEqual(release.publish, [ { provider: "github", diff --git a/scripts/build-desktop-artifact.ts b/scripts/build-desktop-artifact.ts index 9d34e2412b327..05df5454b6eac 100644 --- a/scripts/build-desktop-artifact.ts +++ b/scripts/build-desktop-artifact.ts @@ -2706,7 +2706,7 @@ export const resolveGitHubPublishConfig = Effect.fn("resolveGitHubPublishConfig" const rawRepo = ( Option.getOrUndefined(env.updateRepository)?.trim() || Option.getOrUndefined(env.githubRepository)?.trim() || - "" + "LaMarCab76/t3code" ).trim(); if (!rawRepo) return undefined; From c016bd75dee3a20e703776c9aed75dd550d350f0 Mon Sep 17 00:00:00 2001 From: Lautaro Caballero Date: Sun, 15 Nov 2026 22:17:29 -0300 Subject: [PATCH 09/16] feat(web): command progress, thread details in the sidebar, and wallpapers MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Running commands gave no sense of how far along they were, thread details covered part of the chat, and the app had no way to show a picture behind it. - Command progress: the output hub reads the count a running command last printed (`24/31`, `[3/10]`, `42%`) from the tail it already keeps, and a new `subscribeCommandProgress` stream sends just those counts for the open thread, so no output crosses the wire. Command rows, the live work row, and the Scroll to end button show it. - Thread details in the sidebar: the existing details card renders through a portal under the open thread's sidebar row, on by default. It moves back over the chat while the sidebar is hidden, and Settings → Appearance turns it off. - Wallpaper: Settings → Appearance can show an F1 race picture behind the sidebar and chat, with blur and dimming sliders. The blur is a filter on one fixed layer, not a backdrop-filter, so scrolling never re-blurs it. Co-Authored-By: Claude Opus 5.5 --- apps/server/src/auth/RpcAuthorization.ts | 1 + .../src/observability/RpcInstrumentation.ts | 1 + .../orchestration-v2/CommandOutputHub.test.ts | 28 ++++ .../src/orchestration-v2/CommandOutputHub.ts | 90 +++++++++- .../commandOutputProgress.test.ts | 45 +++++ .../orchestration-v2/commandOutputProgress.ts | 56 +++++++ apps/server/src/ws.ts | 6 + apps/web/src/appInit.tsx | 8 + apps/web/src/appearanceWallpaper.ts | 24 +++ apps/web/src/assets/wallpapers/f1-race.svg | 88 ++++++++++ apps/web/src/components/ChatView.tsx | 34 +++- apps/web/src/components/Sidebar.tsx | 18 +- apps/web/src/components/chat/ChatCanvas.tsx | 14 +- .../components/chat/CommandProgressMeter.tsx | 24 +++ .../src/components/chat/ThreadDetailsCard.tsx | 21 ++- .../chat/ThreadDetailsItemsMenu.tsx | 10 ++ .../components/chat/TimelineWorkEntryRow.tsx | 12 ++ .../components/chat/TimelineWorkGroupRows.tsx | 26 ++- .../chat/threadDetailsSidebarSlot.ts | 42 +++++ .../src/components/chat/useCommandProgress.ts | 40 +++++ .../settings/AppearanceSettingsPanel.tsx | 6 +- .../components/settings/SettingsPanels.tsx | 14 ++ .../settings/ThreadDetailsItemsRow.tsx | 33 ++++ .../settings/WallpaperSettingsRows.tsx | 158 ++++++++++++++++++ .../src/components/settings/settingsSearch.ts | 26 +++ .../sidebar/ThreadDetailsSidebarSlot.tsx | 39 +++++ apps/web/src/index.css | 31 ++++ docs/user/activity-log.md | 5 + docs/user/appearance.md | 7 + docs/user/thread-sidebar.md | 5 + packages/client-runtime/src/rpc/client.ts | 1 + .../client-runtime/src/state/orchestration.ts | 6 + packages/contracts/src/orchestrationV2.ts | 25 +++ packages/contracts/src/rpc.ts | 11 ++ packages/contracts/src/settings.ts | 27 +++ 35 files changed, 960 insertions(+), 22 deletions(-) create mode 100644 apps/server/src/orchestration-v2/commandOutputProgress.test.ts create mode 100644 apps/server/src/orchestration-v2/commandOutputProgress.ts create mode 100644 apps/web/src/appearanceWallpaper.ts create mode 100644 apps/web/src/assets/wallpapers/f1-race.svg create mode 100644 apps/web/src/components/chat/CommandProgressMeter.tsx create mode 100644 apps/web/src/components/chat/threadDetailsSidebarSlot.ts create mode 100644 apps/web/src/components/chat/useCommandProgress.ts create mode 100644 apps/web/src/components/settings/WallpaperSettingsRows.tsx create mode 100644 apps/web/src/components/sidebar/ThreadDetailsSidebarSlot.tsx diff --git a/apps/server/src/auth/RpcAuthorization.ts b/apps/server/src/auth/RpcAuthorization.ts index 9c2d16c25c807..ca15e58b89cad 100644 --- a/apps/server/src/auth/RpcAuthorization.ts +++ b/apps/server/src/auth/RpcAuthorization.ts @@ -62,6 +62,7 @@ export const RPC_REQUIRED_SCOPES = { [ORCHESTRATION_V2_WS_METHODS.subscribeShell]: AuthOrchestrationReadScope, [ORCHESTRATION_V2_WS_METHODS.subscribeThread]: AuthOrchestrationReadScope, [ORCHESTRATION_V2_WS_METHODS.subscribeCommandOutput]: AuthOrchestrationReadScope, + [ORCHESTRATION_V2_WS_METHODS.subscribeCommandProgress]: AuthOrchestrationReadScope, [ORCHESTRATION_V2_WS_METHODS.subscribePromptSuggestion]: AuthOrchestrationReadScope, [WS_METHODS.projectsMutate]: AuthOrchestrationOperateScope, [WS_METHODS.serverProbe]: AuthOrchestrationReadScope, diff --git a/apps/server/src/observability/RpcInstrumentation.ts b/apps/server/src/observability/RpcInstrumentation.ts index 5e7e9dd709fca..cf9a94580553a 100644 --- a/apps/server/src/observability/RpcInstrumentation.ts +++ b/apps/server/src/observability/RpcInstrumentation.ts @@ -35,6 +35,7 @@ const RPC_AGGREGATES = { [ORCHESTRATION_V2_WS_METHODS.subscribeShell]: "orchestrationV2", [ORCHESTRATION_V2_WS_METHODS.subscribeThread]: "orchestrationV2", [ORCHESTRATION_V2_WS_METHODS.subscribeCommandOutput]: "orchestrationV2", + [ORCHESTRATION_V2_WS_METHODS.subscribeCommandProgress]: "orchestrationV2", [ORCHESTRATION_V2_WS_METHODS.subscribePromptSuggestion]: "orchestrationV2", [WS_METHODS.projectsMutate]: "orchestration", [WS_METHODS.serverProbe]: "server", diff --git a/apps/server/src/orchestration-v2/CommandOutputHub.test.ts b/apps/server/src/orchestration-v2/CommandOutputHub.test.ts index 442726379df5c..f77283e179a3f 100644 --- a/apps/server/src/orchestration-v2/CommandOutputHub.test.ts +++ b/apps/server/src/orchestration-v2/CommandOutputHub.test.ts @@ -3,6 +3,7 @@ import { type ModelSelection, type OrchestrationV2AppThread, type OrchestrationV2CommandOutputFrame, + type OrchestrationV2CommandProgressFrame, type OrchestrationV2TurnItem, ProviderDriverKind, ProviderInstanceId, @@ -264,6 +265,33 @@ layer("CommandOutputHub", (it) => { }), ); + it.effect("a thread's progress follows the counts its running commands print", () => + Effect.gen(function* () { + const hub = yield* CommandOutputHub.CommandOutputHub; + const threadId = yield* seedThread; + const frames = yield* Queue.unbounded(); + yield* hub.subscribeProgress(threadId).pipe( + Stream.runForEach((frame) => Queue.offer(frames, frame)), + Effect.forkScoped, + ); + assert.deepStrictEqual(yield* Queue.take(frames), { items: [] }); + + yield* TestClock.adjust("1 second"); + yield* hub.append({ + threadId, + itemId: ITEM_ID, + chunk: " ✓ guard.spec.ts (4)\n❯ refresh.spec.ts 24/31", + }); + assert.deepStrictEqual(yield* Queue.take(frames), { + items: [{ itemId: ITEM_ID, completed: 24, total: 31 }], + }); + + yield* TestClock.adjust("1 second"); + yield* hub.finish({ threadId, itemId: ITEM_ID }); + assert.deepStrictEqual(yield* Queue.take(frames), { items: [] }); + }), + ); + it.effect("a finished command sends only its bounded final output", () => Effect.gen(function* () { const threadId = yield* seedThread; diff --git a/apps/server/src/orchestration-v2/CommandOutputHub.ts b/apps/server/src/orchestration-v2/CommandOutputHub.ts index b6b5b634c179c..cf2dfaf22d16e 100644 --- a/apps/server/src/orchestration-v2/CommandOutputHub.ts +++ b/apps/server/src/orchestration-v2/CommandOutputHub.ts @@ -2,8 +2,12 @@ import { isOrchestrationV2WorkActive, OrchestrationV2CommandOutputError, type OrchestrationV2CommandOutputFrame, + type OrchestrationV2CommandProgress, + type OrchestrationV2CommandProgressFrame, type OrchestrationV2SubscribeCommandOutputInput, type OrchestrationV2TurnItem, + type ThreadId, + TurnItemId, } from "@t3tools/contracts"; import { appendTerminalOutput, @@ -25,9 +29,12 @@ import * as Stream from "effect/Stream"; import * as EventSink from "./EventSink.ts"; import * as ProjectionStore from "./ProjectionStore.ts"; +import { commandOutputProgress } from "./commandOutputProgress.ts"; /** Output bypasses orchestration events; expanded rows receive tails, coalesced appends, then persisted output. */ +/** Fastest a thread's progress subscriber re-reads its commands' tails. */ +const COMMAND_PROGRESS_FRAME_INTERVAL_MS = 250; /** Fastest a subscriber receives frames while output flows. */ const COMMAND_OUTPUT_FRAME_INTERVAL_MS = 100; /** After a subscriber falls behind and is sent the whole tail, it waits this long. */ @@ -57,6 +64,10 @@ export interface CommandOutputHubShape { readonly subscribe: ( input: CommandOutputTarget, ) => Stream.Stream; + /** Counts the thread's running commands print, read from the same tails, so no output crosses the wire. */ + readonly subscribeProgress: ( + threadId: ThreadId, + ) => Stream.Stream; } export class CommandOutputHub extends Context.Service()( @@ -65,8 +76,12 @@ export class CommandOutputHub extends Context.Service(); const finished = new Map(); const subscribers = new Map>(); + const progressSubscribers = new Map>>(); + + const wakeProgress = (threadId: ThreadId) => + Effect.forEach( + progressSubscribers.get(threadId) ?? [], + (wake) => Queue.offer(wake, undefined), + { + discard: true, + }, + ); + + const threadProgress = (threadId: ThreadId): Array => { + const prefix = threadKeyPrefix(threadId); + const items: Array = []; + for (const [key, tail] of tails) { + if (!key.startsWith(prefix)) continue; + const progress = commandOutputProgress(tail.text); + if (progress) items.push({ itemId: TurnItemId.make(key.slice(prefix.length)), ...progress }); + } + return items; + }; const wakeAll = (key: string, chunk: string) => Effect.forEach( @@ -139,18 +175,62 @@ export const make = Effect.gen(function* () { subscriber.pendingAppend = ""; } }); - return wakeAll(key, chunk); + return wakeAll(key, chunk).pipe(Effect.andThen(wakeProgress(target.threadId))); }); const finish: CommandOutputHubShape["finish"] = (target) => - Effect.sync(() => { + Effect.suspend(() => { const key = commandKey(target); const tail = tails.get(key); - if (tail === undefined) return; + if (tail === undefined) return Effect.void; tails.delete(key); setBounded(finished, key, tail, MAX_FINISHED_COMMANDS); + return wakeProgress(target.threadId); }); + const subscribeProgress: CommandOutputHubShape["subscribeProgress"] = (threadId) => + Stream.unwrap( + Effect.gen(function* () { + const wake = yield* Queue.sliding(1); + const threadSubscribers = progressSubscribers.get(threadId) ?? new Set>(); + threadSubscribers.add(wake); + progressSubscribers.set(threadId, threadSubscribers); + yield* Effect.addFinalizer(() => + Effect.sync(() => { + threadSubscribers.delete(wake); + if ( + threadSubscribers.size === 0 && + progressSubscribers.get(threadId) === threadSubscribers + ) { + progressSubscribers.delete(threadId); + } + }), + ); + yield* Queue.offer(wake, undefined); + let sent: string | undefined; + let lastReadAt: number | undefined; + const nextFrame = Effect.gen(function* () { + while (true) { + yield* Queue.take(wake); + const now = yield* Clock.currentTimeMillis; + if (lastReadAt !== undefined && now - lastReadAt < COMMAND_PROGRESS_FRAME_INTERVAL_MS) { + yield* Effect.sleep(COMMAND_PROGRESS_FRAME_INTERVAL_MS - (now - lastReadAt)); + } + lastReadAt = yield* Clock.currentTimeMillis; + const items = threadProgress(threadId); + const signature = items + .map((item) => `${item.itemId}:${item.completed}/${item.total}`) + .join("\n"); + if (signature !== sent) { + sent = signature; + return { items } satisfies OrchestrationV2CommandProgressFrame; + } + } + }); + return Stream.fromEffectRepeat(nextFrame); + }), + ); + const subscribe: CommandOutputHubShape["subscribe"] = (target) => Stream.unwrap( Effect.gen(function* () { @@ -297,7 +377,7 @@ export const make = Effect.gen(function* () { ), ); - return CommandOutputHub.of({ append, finish, subscribe }); + return CommandOutputHub.of({ append, finish, subscribe, subscribeProgress }); }); export const layer: Layer.Layer< diff --git a/apps/server/src/orchestration-v2/commandOutputProgress.test.ts b/apps/server/src/orchestration-v2/commandOutputProgress.test.ts new file mode 100644 index 0000000000000..f8b4feac1eba6 --- /dev/null +++ b/apps/server/src/orchestration-v2/commandOutputProgress.test.ts @@ -0,0 +1,45 @@ +import { describe, expect, it } from "@effect/vitest"; + +import { commandOutputProgress } from "./commandOutputProgress.ts"; + +describe("commandOutputProgress", () => { + it.each([ + [ + "a test runner count", + " ✓ guard.spec.ts (4)\n❯ refresh.spec.ts 24/31", + { completed: 24, total: 31 }, + ], + ["a bracketed step", "[3/10] RUN pnpm install\n", { completed: 3, total: 10 }], + ["a spaced count", "Building (120 / 300) crates", { completed: 120, total: 300 }], + ["a percentage", "webpack 42% building modules", { completed: 42, total: 100 }], + ["a pytest percentage", "tests/test_auth.py .... [ 87%]", { completed: 87, total: 100 }], + [ + "the last redraw of a carriage-return progress bar", + "Downloading 10%\rDownloading 55%\rDownloading 73%\r\n", + { completed: 73, total: 100 }, + ], + [ + "colored output", + "\u001b[32m✓\u001b[0m \u001b[1m17/40\u001b[0m tests", + { completed: 17, total: 40 }, + ], + [ + "the newest of several lines", + "1/10 setup\n2/10 build\n7/10 test\n", + { completed: 7, total: 10 }, + ], + ])("reads %s", (_name, output, expected) => { + expect(commandOutputProgress(output)).toEqual(expected); + }); + + it.each([ + ["no output", undefined], + ["a path", "wrote dist/assets/12/34.js"], + ["a date", "Released 2024/11/05"], + ["a version range", "react 18.3/19.0 compatible"], + ["a count past its total", "retry 5/3"], + ["a count that scrolled out of the tail", "3/10 build\n" + "log line\n".repeat(10)], + ])("ignores %s", (_name, output) => { + expect(commandOutputProgress(output)).toBeUndefined(); + }); +}); diff --git a/apps/server/src/orchestration-v2/commandOutputProgress.ts b/apps/server/src/orchestration-v2/commandOutputProgress.ts new file mode 100644 index 0000000000000..efad1e9f28858 --- /dev/null +++ b/apps/server/src/orchestration-v2/commandOutputProgress.ts @@ -0,0 +1,56 @@ +import type { OrchestrationV2CommandProgress } from "@t3tools/contracts"; + +type CommandProgressCount = Omit; + +const TAIL_CHARS = 4096; +const TAIL_LINES = 6; +const ANSI_ESCAPE = /\u001b\[[0-9;?]*[ -/]*[@-~]/g; +// A slash count that is not part of a path, a date, or a version: `24/31`, `[3/10]`, `(120 / 300)`. +const FRACTION = /(?= 0; index -= 1) { + const completed = Number(fractions[index]![1]); + const total = Number(fractions[index]![2]); + if (total >= 2 && completed <= total) return { completed, total }; + } + const percents = [...line.matchAll(PERCENT)]; + for (let index = percents.length - 1; index >= 0; index -= 1) { + const value = Number(percents[index]![1]); + if (value <= 100) return { completed: Math.floor(value), total: 100 }; + } + return undefined; +} + +/** + * Reads the count a running command last printed, such as a test runner's `24/31` or a + * build's `42%`. Progress bars redraw with carriage returns, so only each line's last + * redraw counts. + */ +export function commandOutputProgress( + output: string | undefined, +): CommandProgressCount | undefined { + if (!output) return undefined; + const lines = output + .slice(-TAIL_CHARS) + .split("\n") + .map((line) => + ( + line + .split("\r") + .filter((redraw) => redraw.trim().length > 0) + .at(-1) ?? "" + ) + .replace(ANSI_ESCAPE, "") + .trim(), + ) + .filter((line) => line.length > 0) + .slice(-TAIL_LINES); + for (let index = lines.length - 1; index >= 0; index -= 1) { + const progress = lineProgress(lines[index]!); + if (progress) return progress; + } + return undefined; +} diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index 63c2b9c999453..b41edb8bf16c7 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -2295,6 +2295,12 @@ export const layerWsRpc = ( Effect.as(commandOutputHub.subscribe(input)), ), ), + [ORCHESTRATION_V2_WS_METHODS.subscribeCommandProgress]: (input) => + Stream.unwrap( + Effect.annotateCurrentSpan({ "orchestration_v2.thread_id": input.threadId }).pipe( + Effect.as(commandOutputHub.subscribeProgress(input.threadId)), + ), + ), [ORCHESTRATION_V2_WS_METHODS.subscribePromptSuggestion]: (input) => providerSessionManager.subscribePromptSuggestion(input.threadId), [WS_METHODS.scheduledTasksSubscribe]: (_input) => diff --git a/apps/web/src/appInit.tsx b/apps/web/src/appInit.tsx index faa71137db049..75876a805521a 100644 --- a/apps/web/src/appInit.tsx +++ b/apps/web/src/appInit.tsx @@ -9,6 +9,7 @@ import { createBrowserHistory, createHashHistory } from "@tanstack/react-router" import * as Schema from "effect/Schema"; import { applyAppearanceContrast } from "./appearanceContrast"; +import { applyWallpaper } from "./appearanceWallpaper"; import { applyAppearanceFontVariables, TYPOGRAPHY_ADVANCED_STORAGE_KEY } from "./appearanceFonts"; import { startElectronBrowserHost } from "./browser/ElectronBrowserHost"; import { startBrowserProfileReporting } from "./browser/BrowserProfileReporter"; @@ -98,6 +99,13 @@ function startClientAppearance(): void { root.style.removeProperty("--glass-blur"); } } + if ( + previous?.wallpaper !== settings.wallpaper || + previous.wallpaperBlur !== settings.wallpaperBlur || + previous.wallpaperDim !== settings.wallpaperDim + ) { + applyWallpaper(root, settings); + } if ( previous?.fontFamilySans !== settings.fontFamilySans || previous.fontFamilyCode !== settings.fontFamilyCode || diff --git a/apps/web/src/appearanceWallpaper.ts b/apps/web/src/appearanceWallpaper.ts new file mode 100644 index 0000000000000..bb2170ddeab43 --- /dev/null +++ b/apps/web/src/appearanceWallpaper.ts @@ -0,0 +1,24 @@ +import type { ClientSettings } from "@t3tools/contracts/settings"; + +import f1RaceWallpaperUrl from "./assets/wallpapers/f1-race.svg"; + +type WallpaperSettings = Pick; + +const WALLPAPER_URLS: Record, string> = { + "f1-race": f1RaceWallpaperUrl, +}; + +/** index.css paints the wallpaper from these variables while `data-wallpaper` is set. */ +export function applyWallpaper(root: HTMLElement, settings: WallpaperSettings): void { + if (settings.wallpaper === "none") { + delete root.dataset.wallpaper; + root.style.removeProperty("--wallpaper-image"); + root.style.removeProperty("--wallpaper-blur"); + root.style.removeProperty("--wallpaper-dim"); + return; + } + root.dataset.wallpaper = settings.wallpaper; + root.style.setProperty("--wallpaper-image", `url("${WALLPAPER_URLS[settings.wallpaper]}")`); + root.style.setProperty("--wallpaper-blur", `${settings.wallpaperBlur}px`); + root.style.setProperty("--wallpaper-dim", `${settings.wallpaperDim}%`); +} diff --git a/apps/web/src/assets/wallpapers/f1-race.svg b/apps/web/src/assets/wallpapers/f1-race.svg new file mode 100644 index 0000000000000..e0c7adb3309e8 --- /dev/null +++ b/apps/web/src/assets/wallpapers/f1-race.svg @@ -0,0 +1,88 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 67638fc4e63ca..b9b2aed21d731 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -314,6 +314,12 @@ import { } from "./chat/PanelLayoutControls"; import type { ExpandedImagePreview } from "./chat/ExpandedImagePreview"; import { ThreadDetailsPanel } from "./chat/ThreadDetailsPanel"; +import { useThreadDetailsSidebarSlot } from "./chat/threadDetailsSidebarSlot"; +import { + formatCommandProgress, + truncateCommandLabel, + useCommandProgress, +} from "./chat/useCommandProgress"; import { NoActiveThreadState } from "./NoActiveThreadState"; import { resolveEffectiveEnvMode, @@ -1976,9 +1982,10 @@ export default function ChatView(props: ChatViewProps) { const threadPanelInlineOpen = useRightPanelStore((state) => selectThreadPanelOpen(state.threadPanelVisibilityByThreadKey, activeThreadRef, "inline"), ); + const threadDetailsSidebarSlot = useThreadDetailsSidebarSlot(activeThreadRef); // Selects only the mode, so canvas resizes rerender the chat view only when the // card switches presentation. - const threadPanelPresentation = useStore( + const threadPanelCanvasPresentation = useStore( chatCanvasStore, (state) => resolveChatCanvasModel({ @@ -1986,9 +1993,12 @@ export default function ChatView(props: ChatViewProps) { detailsCardMeasurement: state.detailsCardMeasurement, threadRef: activeThreadRef, preview: canvasPreview, - detailsCardInlineOpen: threadPanelInlineOpen, + detailsCardInlineOpen: threadPanelInlineOpen && threadDetailsSidebarSlot === null, }).detailsCardMode, ); + // Details in the sidebar open and close with the inline flag, whatever room the canvas has. + const threadPanelPresentation = + threadDetailsSidebarSlot === null ? threadPanelCanvasPresentation : "inline"; const threadPanelOpen = useRightPanelStore((state) => selectThreadPanelOpen( state.threadPanelVisibilityByThreadKey, @@ -3137,8 +3147,24 @@ export default function ChatView(props: ChatViewProps) { message.inputIntent === "queued_turn" && !serverProjection?.messages.some((committed) => committed.id === message.id), ); + const runningCommands = (serverProjection?.turnItems ?? []).filter( + (item) => item.type === "command_execution" && item.status === "running", + ); + const runningCommandProgress = useCommandProgress( + activeThreadRef, + isServerThread && runningCommands.length > 0, + ).find((progress) => runningCommands.some((item) => item.id === progress.itemId)); + const runningCommand = runningCommands.find((item) => item.id === runningCommandProgress?.itemId); + const commandProgressSummary = + runningCommand?.type === "command_execution" && runningCommandProgress + ? `${truncateCommandLabel(runningCommand.input)} ${formatCommandProgress(runningCommandProgress)}` + : null; const scrollToEndSummary = - [childInputNow?.waitingLabel ?? null, queuedRunCount === 0 ? null : `${queuedRunCount} queued`] + [ + commandProgressSummary, + childInputNow?.waitingLabel ?? null, + queuedRunCount === 0 ? null : `${queuedRunCount} queued`, + ] .filter((part) => part !== null) .join(" · ") || null; // The end of the timeline holds the thread's present and next turns: what it is doing now, @@ -3326,6 +3352,7 @@ export default function ChatView(props: ChatViewProps) {
    {embedded ? null : ( s.confirmThreadDelete); const confirmThreadArchive = useClientSettings((s) => s.confirmThreadArchive); const timestampFormat = useClientSettings((s) => s.timestampFormat); + const sidebarVisible = useSidebarVisibility(); + const showDetailsInSidebar = useClientSettings((s) => s.threadDetailsInSidebar) && sidebarVisible; const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings); const { settleThread, @@ -3368,7 +3372,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve : isCard ? "card" : "slim"; - return ( + const row = ( ); + return showDetailsInSidebar && routeThreadKey === threadKey ? ( + + {row} + + + ) : ( + row + ); }; const from = isContextDrag ? null : (dragState?.activeSection ?? null); const items: ReactNode[] = [ diff --git a/apps/web/src/components/chat/ChatCanvas.tsx b/apps/web/src/components/chat/ChatCanvas.tsx index 7848009308750..aac168f12b5ef 100644 --- a/apps/web/src/components/chat/ChatCanvas.tsx +++ b/apps/web/src/components/chat/ChatCanvas.tsx @@ -6,6 +6,7 @@ import { resolveChatCanvasModel, type ChatCanvasStore } from "./canvasStore"; import { selectThreadPanelOpen, useRightPanelStore } from "../../rightPanelStore"; import { observeResize } from "../../lib/observeResize"; import type { ScopedThreadRef } from "@t3tools/contracts"; +import { useThreadDetailsSidebarSlot } from "./threadDetailsSidebarSlot"; function panelWidthTransitions(element: HTMLElement) { const panels = element @@ -134,11 +135,14 @@ export function ChatCanvas({ stopObserving(); }; }, [store, composerOverlayElement, timelineElement, detailsCardTopInset]); - const detailsCardInlineOpen = useRightPanelStore((state) => - threadRef === null - ? false - : selectThreadPanelOpen(state.threadPanelVisibilityByThreadKey, threadRef, "inline"), - ); + const detailsSidebarSlot = useThreadDetailsSidebarSlot(threadRef); + // Details shown in the sidebar take no room in the canvas. + const detailsCardInlineOpen = + useRightPanelStore((state) => + threadRef === null + ? false + : selectThreadPanelOpen(state.threadPanelVisibilityByThreadKey, threadRef, "inline"), + ) && detailsSidebarSlot === null; const model = resolveChatCanvasModel({ measurements, detailsCardMeasurement, diff --git a/apps/web/src/components/chat/CommandProgressMeter.tsx b/apps/web/src/components/chat/CommandProgressMeter.tsx new file mode 100644 index 0000000000000..e0b8559edff5c --- /dev/null +++ b/apps/web/src/components/chat/CommandProgressMeter.tsx @@ -0,0 +1,24 @@ +import type { OrchestrationV2CommandProgress } from "@t3tools/contracts"; + +import { formatCommandProgress } from "./useCommandProgress"; + +export function CommandProgressMeter({ progress }: { progress: OrchestrationV2CommandProgress }) { + return ( + + + + + {formatCommandProgress(progress)} + + ); +} diff --git a/apps/web/src/components/chat/ThreadDetailsCard.tsx b/apps/web/src/components/chat/ThreadDetailsCard.tsx index 4e8a47a39791a..d8f8f60a94633 100644 --- a/apps/web/src/components/chat/ThreadDetailsCard.tsx +++ b/apps/web/src/components/chat/ThreadDetailsCard.tsx @@ -17,6 +17,8 @@ import { resolveThreadDetailsCardDensity, } from "./threadDetailsCardLayout"; import { observeResize } from "../../lib/observeResize"; +import { createPortal } from "react-dom"; +import { useThreadDetailsSidebarSlot } from "./threadDetailsSidebarSlot"; import { requestWorkspaceFocus } from "../../lib/workspaceFocus"; export function ThreadDetailsCard({ @@ -47,6 +49,7 @@ export function ThreadDetailsCard({ const popoverOpen = useRightPanelStore((state) => selectThreadPanelOpen(state.threadPanelVisibilityByThreadKey, threadRef, "popover"), ); + const sidebarSlot = useThreadDetailsSidebarSlot(threadRef); const measurementKey = `${threadRef.environmentId}:${threadRef.threadId}:${preferredPlacement?.width ?? "popup"}:${contentKey}`; const [measurements, setMeasurements] = useState({ key: measurementKey, @@ -131,7 +134,7 @@ export function ThreadDetailsCard({ return ( { const target = details.reason === "focus-out" @@ -146,7 +149,21 @@ export function ThreadDetailsCard({ useRightPanelStore.getState().setThreadPanelOpen(threadRef, "popover", open); }} > - {placement && inlineOpen ? ( + {sidebarSlot && inlineOpen + ? createPortal( +
    + {children("full")} +
    , + sidebarSlot, + ) + : null} + {placement && inlineOpen && sidebarSlot === null ? (