diff --git a/.github/fork/brand-l.mjs b/.github/fork/brand-l.mjs new file mode 100644 index 0000000000000..95a4f33e9b4ff --- /dev/null +++ b/.github/fork/brand-l.mjs @@ -0,0 +1,55 @@ +// 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/src/app/DesktopEnvironment.ts", '"com.t3tools.t3code"', `"${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 new file mode 100644 index 0000000000000..fb856d4236099 --- /dev/null +++ b/.github/workflows/fork-build.yml @@ -0,0 +1,131 @@ +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... + - run: node .github/fork/brand-l.mjs + - id: meta + 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: | + 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 .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' + 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 "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." diff --git a/.github/workflows/fork-coderabbit-gate.yml b/.github/workflows/fork-coderabbit-gate.yml new file mode 100644 index 0000000000000..e1ebe7850a773 --- /dev/null +++ b/.github/workflows/fork-coderabbit-gate.yml @@ -0,0 +1,50 @@ +name: Fork CodeRabbit gate +on: + pull_request: + types: [opened, synchronize, reopened, ready_for_review] + pull_request_review: + types: [submitted, dismissed] + pull_request_review_thread: + types: [resolved, unresolved] +permissions: + contents: read + pull-requests: read +concurrency: + group: fork-coderabbit-gate-${{ github.event.pull_request.number }} + cancel-in-progress: true +jobs: + threads: + name: CodeRabbit threads + if: github.repository == 'LaMarCab76/t3code' + runs-on: ubuntu-latest + steps: + - uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd + with: + script: | + const { owner, repo } = context.repo; + const number = context.payload.pull_request.number; + const open = []; + let cursor = null; + do { + const { repository } = await github.graphql( + `query($owner: String!, $repo: String!, $number: Int!, $cursor: String) { + repository(owner: $owner, name: $repo) { + pullRequest(number: $number) { + reviewThreads(first: 100, after: $cursor) { + pageInfo { hasNextPage endCursor } + nodes { isResolved path line comments(first: 1) { nodes { author { login } url } } } + } + } + } + }`, + { owner, repo, number, cursor }, + ); + const threads = repository.pullRequest.reviewThreads; + for (const thread of threads.nodes) { + const first = thread.comments.nodes[0]; + if (!thread.isResolved && first?.author?.login.startsWith('coderabbitai')) open.push({ ...thread, url: first.url }); + } + cursor = threads.pageInfo.hasNextPage ? threads.pageInfo.endCursor : null; + } while (cursor); + for (const thread of open) core.error(`${thread.path}:${thread.line ?? '?'} ${thread.url}`); + if (open.length > 0) core.setFailed(`${open.length} unresolved CodeRabbit thread(s)`); 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' }); 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} { }); 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 7925fd869799f..ca15e58b89cad 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, @@ -61,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/environment/ServerEnvironment.ts b/apps/server/src/environment/ServerEnvironment.ts index 813efbe53ea30..c19da780b4fd6 100644 --- a/apps/server/src/environment/ServerEnvironment.ts +++ b/apps/server/src/environment/ServerEnvironment.ts @@ -279,6 +279,7 @@ export const make = Effect.gen(function* () { oneTimeSchedules: true, freshContext: true, scheduledTaskThreadModes: true, + scheduledTaskSnooze: true, npmReleaseLookup: true, voiceTranscription: isSpeechPlatformSupported(hostPlatform, hostArchitecture, hostLibc), cloudVoiceTranscription: true, @@ -295,6 +296,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 4549ee8a33c10..cf9a94580553a 100644 --- a/apps/server/src/observability/RpcInstrumentation.ts +++ b/apps/server/src/observability/RpcInstrumentation.ts @@ -15,6 +15,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", @@ -34,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..e71bfe8501c43 100644 --- a/apps/server/src/orchestration-v2/CommandOutputHub.test.ts +++ b/apps/server/src/orchestration-v2/CommandOutputHub.test.ts @@ -3,10 +3,11 @@ import { type ModelSelection, type OrchestrationV2AppThread, type OrchestrationV2CommandOutputFrame, + type OrchestrationV2CommandProgressFrame, type OrchestrationV2TurnItem, ProviderDriverKind, ProviderInstanceId, - type ThreadId, + ThreadId, TurnItemId, } from "@t3tools/contracts"; import { @@ -264,6 +265,51 @@ 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: [] }); + + yield* TestClock.adjust("1 second"); + yield* hub.append({ threadId, itemId: ITEM_ID, chunk: "❯ refresh.spec.ts 25/31" }); + assert.deepStrictEqual(yield* Queue.take(frames), { + items: [{ itemId: ITEM_ID, completed: 25, total: 31 }], + }); + + // Newer commands in another thread evict this one's tail, and its count with it. + yield* TestClock.adjust("1 second"); + const otherThreadId = ThreadId.make("thread-other"); + for (let index = 0; index < 64; index += 1) { + yield* hub.append({ + threadId: otherThreadId, + itemId: TurnItemId.make(`turn-item:other-${index}`), + chunk: "x", + }); + } + 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..719703d6832bd 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, + 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,16 @@ 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 }); + } + // Appends reorder `tails`, so sort to keep unchanged counts from looking like a new frame. + return items.toSorted((left, right) => left.itemId.localeCompare(right.itemId)); + }; const wakeAll = (key: string, chunk: string) => Effect.forEach( @@ -132,25 +173,78 @@ export const make = Effect.gen(function* () { if (chunk.length === 0) return Effect.void; const key = commandKey(target); const tail = appendTerminalOutput(tails.get(key) ?? EMPTY_TERMINAL_OUTPUT, chunk); + let evictedThreadId: ThreadId | undefined; setBounded(tails, key, tail, MAX_LIVE_COMMANDS, (oldest) => { + evictedThreadId = commandKeyThreadId(oldest); // Eviction invalidates viewers' state; resync on their next frame. for (const subscriber of subscribers.get(oldest) ?? []) { subscriber.needsReplace = true; subscriber.pendingAppend = ""; } }); - return wakeAll(key, chunk); + return wakeAll(key, chunk).pipe( + Effect.andThen(wakeProgress(target.threadId)), + Effect.andThen( + evictedThreadId === undefined || evictedThreadId === target.threadId + ? Effect.void + : wakeProgress(evictedThreadId), + ), + ); }); 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 +391,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/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 27f7aa82fd25c..505efce165037 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -417,6 +417,13 @@ export interface OrchestratorV2Shape { readonly threadId: ThreadId; readonly limitRecovery: OrchestrationV2LimitRecoveryUpdate; }) => 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; @@ -16239,6 +16246,49 @@ 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.lastSnoozeWakeAt != null && + latest.completedAt !== null && + DateTime.toEpochMillis(thread.lastSnoozeWakeAt) >= + DateTime.toEpochMillis(latest.completedAt)) || + (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/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index 5b71a6ac042f1..5a6ba99580cae 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"; @@ -26,7 +27,6 @@ import type { OrchestrationV2ExecutionNode, OrchestrationV2PlanArtifact, OrchestrationV2PendingRuntimeRequestSummary, - PlanId, OrchestrationV2ConversationMessage, OrchestrationV2ContextTransfer, OrchestrationV2DomainEvent, @@ -563,6 +563,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; @@ -698,6 +706,9 @@ export interface ProjectionStoreV2Shape { threadId: ThreadId, providerTurnId: ProviderTurnId, ) => Effect.Effect; + readonly getLatestTodoList: ( + threadId: ThreadId, + ) => Effect.Effect; readonly getPlan: ( threadId: ThreadId, planId: PlanId, @@ -3813,46 +3824,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, @@ -5686,6 +5658,76 @@ 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); + 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(runless[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( @@ -6515,6 +6557,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 getRunProviderRecords: ProjectionStoreV2Shape["getRunProviderRecords"] = Effect.fn( "ProjectionStore.getRunProviderRecords", )( @@ -9325,10 +9395,12 @@ 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), 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 532d019ddd6fb..2b0060b05a55c 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts @@ -233,6 +233,8 @@ it.effect( getTurnStartContext: () => Effect.die("unused"), 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"), hasRunInterruptRequest: () => Effect.die("unused stop read"), 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..6f0a95c08aacb --- /dev/null +++ b/apps/server/src/orchestration-v2/ThreadInsightsQuery.test.ts @@ -0,0 +1,418 @@ +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 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"; +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)({ + priceTurnRecords: (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: { 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`); + 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, + 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* run(child, 1); + yield* run(child, 2, "running"); + 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.find((row) => row.threadId === child)?.status).toBe("running"); + expect(result.rows.find((row) => row.threadId === native)?.status).toBe("completed"); + 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("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("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"); + yield* sql`UPDATE orchestration_v2_projection_plans + SET payload_json = '{}' WHERE plan_id = 'child-task'`; + const missingPlan = yield* query.read({ threadId: root }); + expect(missingPlan.rows.find((row) => row.threadId === broken)?.steps).toBeNull(); + expect(missingPlan.rows.find((row) => row.threadId === root)?.usage.inputTokens).toBe(100); + expect(missingPlan.rows.find((row) => row.threadId === healthy)?.usage.inputTokens).toBe(25); + expect(missingPlan.unavailableThreadIds).toEqual([broken]); + yield* sql`UPDATE orchestration_v2_projection_plans + SET payload_json = '{}' WHERE plan_id = 'root-task'`; + const planError = yield* query.read({ threadId: root }).pipe(Effect.flip); + expect(planError._tag).toBe("OrchestrationV2GetThreadProjectionError"); + }), + ); + 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..4dc6d3e8f350a --- /dev/null +++ b/apps/server/src/orchestration-v2/ThreadInsightsQuery.ts @@ -0,0 +1,282 @@ +import { + OrchestrationV2GetThreadProjectionError, + type OrchestrationV2GetThreadInsightsResult, + type OrchestrationV2ThreadInsightsRow, + type OrchestrationV2ProviderTurn, + type ThreadId, + type ProviderThreadId, +} 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; + 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", "providerThreads"], { + runStatuses: [], + includeLatestRun: true, + }) + .pipe( + Effect.catch((cause) => + target.threadId === input.threadId ? Effect.fail(cause) : Effect.succeed(null), + ), + ); + if (snapshot === null) { + unavailableThreadIds.push(target.threadId); + continue; + } + 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).pipe( + Effect.catch((cause) => { + if (target.threadId === input.threadId) return Effect.fail(cause); + unavailableThreadIds.push(target.threadId); + return Effect.undefined; + }), + ); + 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: latestRun?.status ?? target.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)); + 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* readTurns(parentId, [nativeOwner.providerThreadId]).pipe( + Effect.orElseSucceed(() => null), + ); + if (recorded === null) unavailableThreadIds.push(target.threadId); + else inheritedNativeTurns = recorded; + } + } + for (const turn of [...ownTurns, ...inheritedNativeTurns]) { + const held = turns.get(turn.id); + // 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.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) ?? []; + 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 status = combinedStatus(usages); + const usage = { + 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), + 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: [...new Set(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/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/scheduledTasks/ScheduledTaskService.ts b/apps/server/src/scheduledTasks/ScheduledTaskService.ts index 9ed134be2da5a..5dce6ca03157a 100644 --- a/apps/server/src/scheduledTasks/ScheduledTaskService.ts +++ b/apps/server/src/scheduledTasks/ScheduledTaskService.ts @@ -436,6 +436,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..a7799577ade8b --- /dev/null +++ b/apps/server/src/scheduledTasks/ScheduledTaskSnoozeReactor.test.ts @@ -0,0 +1,260 @@ +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; + snoozeBeforeComplete?: 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; + if (options.snoozeBeforeComplete) { + yield* orchestrator.dispatch({ + type: "thread.snooze", + commandId: CommandId.make("manual-scheduled-snooze"), + threadId, + snoozedUntil: "2031-01-01T00:00:00.000Z", + }); + } + 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.each([false, true])( + "preserves manual wakes after completion with prior snooze %s", + (snoozeBeforeComplete) => + 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({}, { snoozeBeforeComplete }); + assert.strictEqual( + yield* snoozedUntil, + snoozeBeforeComplete ? "2031-01-01T00:00:00.000Z" : 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 47c4a4c9a20ec..300293a1ca9d6 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"; @@ -8,6 +9,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"; @@ -611,9 +613,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( @@ -713,6 +716,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/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 a59fbc66a02ca..60204b449cbb9 100644 --- a/apps/server/src/usage/UsageService.ts +++ b/apps/server/src/usage/UsageService.ts @@ -45,6 +45,8 @@ import { isUnlistedModel, parseRateTable, type RateTable, + priceTurnUsage, + type PricedRecord, } from "./usagePricing.ts"; import { DESKTOP_HOST_SCOPE_ENV, @@ -162,6 +164,9 @@ export class UsageService extends Context.Service< { readonly readSummary: (input: UsageSummaryInput) => Effect.Effect; readonly refreshRates: Effect.Effect; + readonly priceTurnRecords: ( + records: readonly PricedRecord[], + ) => Effect.Effect; } >()("t3/usage/UsageService") {} @@ -1238,7 +1243,20 @@ export const make = Effect.gen(function* () { return yield* Deferred.await(deferred); }); - return { readSummary, refreshRates, awaitPersisted } as const; + const priceTurnRecords = Effect.fn("UsageService.priceTurnRecords")(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; + return priceTurnUsage(rates, { ...record, model }, overrides); + }); + }); + 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 a9ffc691643fd..cb35670fe685b 100644 --- a/apps/server/src/usage/usagePricing.ts +++ b/apps/server/src/usage/usagePricing.ts @@ -403,6 +403,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/server/src/ws.test.ts b/apps/server/src/ws.test.ts index f8ad4d3229bab..b998d21c36e34 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 NodeHttpServer from "@effect/platform-node/NodeHttpServer"; import { WebSocket } from "@effect/platform-node/NodeWS"; @@ -828,6 +829,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 8e8b30bab3270..b41edb8bf16c7 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"; @@ -1509,6 +1510,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; @@ -1884,6 +1886,7 @@ export const layerWsRpc = ( ? {} : { managedPolicy: serverSettings.managedPolicy }), shellResumeCompletionMarker: true, + threadInsights: true, shellThreadFamilies: true, threadLinkMetadata: true, shellOlderSettled: true, @@ -2017,6 +2020,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) => @@ -2291,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/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/ChatView.tsx b/apps/web/src/components/ChatView.tsx index fbec56205975c..78b839f866235 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -314,6 +314,11 @@ import { } from "./chat/PanelLayoutControls"; import type { ExpandedImagePreview } from "./chat/ExpandedImagePreview"; import { ThreadDetailsPanel } from "./chat/ThreadDetailsPanel"; +import { + formatCommandProgress, + truncateCommandLabel, + useCommandProgress, +} from "./chat/useCommandProgress"; import { NoActiveThreadState } from "./NoActiveThreadState"; import { resolveEffectiveEnvMode, @@ -3138,8 +3143,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, @@ -3327,6 +3348,7 @@ export default function ChatView(props: ChatViewProps) {
{embedded ? null : ( ; + case "thread-insights": + return ; case "side-chat": return ; case "device": @@ -902,7 +906,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/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index 3cb77464473b4..a8be643d974b1 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -3365,7 +3365,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve : isCard ? "card" : "slim"; - return ( + const row = ( ); + return row; }; const from = isContextDrag ? null : (dragState?.activeSection ?? null); const items: ReactNode[] = [ 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/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/ThreadDetailsCost.tsx b/apps/web/src/components/chat/ThreadDetailsCost.tsx new file mode 100644 index 0000000000000..5002a266fb3b3 --- /dev/null +++ b/apps/web/src/components/chat/ThreadDetailsCost.tsx @@ -0,0 +1,108 @@ +import { AuthOrchestrationReadScope, type ScopedThreadRef } from "@t3tools/contracts"; +import { scopedThreadKey } from "@t3tools/client-runtime/environment"; +import { useAtomValue } from "@effect/atom-react"; +import { ChevronDownIcon, InfoIcon } from "lucide-react"; + +import { useServerConfigs } from "../../state/entities"; +import { useEnvironmentScope } from "../../state/session"; +import { threadInsightsViewAtom } from "../../state/threadInsights"; +import { useRightPanelStore } from "../../rightPanelStore"; +import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; +import { ThreadDetailsSection } from "./ThreadDetailsSection"; + +const currency = new Intl.NumberFormat(undefined, { + style: "currency", + currency: "USD", + maximumFractionDigits: 4, +}); + +export function ThreadDetailsCost({ target }: { readonly target: ScopedThreadRef }) { + const supported = useServerConfigs().get(target.environmentId)?.threadInsights === true; + const canRead = useEnvironmentScope(target.environmentId, AuthOrchestrationReadScope); + return supported && canRead ? ( + + ) : ( + + ); +} + +function ThreadCost({ target }: { readonly target: ScopedThreadRef }) { + const usage = useAtomValue(threadInsightsViewAtom(scopedThreadKey(target))); + const partial = usage.partial || usage.unpricedTurns > 0 || usage.errors.length > 0; + const value = + usage.costUsd === null + ? usage.loading + ? "Calculating…" + : "Unavailable" + : `≈ ${currency.format(usage.costUsd)}${partial ? " · partial" : ""}`; + return ( + 0 + ? "Some usage could not be refreshed. The last reported estimate may be incomplete." + : partial && usage.costUsd !== null + ? "Some turns or subagents are missing usage or prices." + : usage.costUsd === null && !usage.loading + ? "No priced usage has been reported." + : undefined + } + onClick={() => useRightPanelStore.getState().openThreadInsights(target, target, "usage")} + /> + ); +} + +function CostRow({ + value, + reason, + onClick, +}: { + readonly value: string; + readonly reason?: string | undefined; + readonly onClick?: () => void; +}) { + return ( + +
+ + + } + > + Est. cost + + {value} + + + +
+ API-equivalent estimate, including subagents. + + Standard API rates, not your subscription bill. + + {reason ? {reason} : null} +
+
+
+
+
+ ); +} diff --git a/apps/web/src/components/chat/ThreadDetailsPanel.tsx b/apps/web/src/components/chat/ThreadDetailsPanel.tsx index 4942080dbb2d2..9fe0f67c411c9 100644 --- a/apps/web/src/components/chat/ThreadDetailsPanel.tsx +++ b/apps/web/src/components/chat/ThreadDetailsPanel.tsx @@ -1,3 +1,5 @@ +import { ThreadDetailsCost } from "./ThreadDetailsCost"; +import { ThreadInsightsMenu } from "./ThreadInsightsMenu"; import type { EditorId, EnvironmentId, @@ -179,6 +181,7 @@ export function ThreadDetailsPanel(props: ThreadDetailsPanelProps) { }; return ( <> +
{show.environment || show.openIn || show.scripts ? ( ) : null} + {visible.cost && props.isServerThread && !props.draftId ? ( + + ) : null} + {/* Shown only when no section above has content, so an emptied card can be refilled. */}
+ useRightPanelStore.getState().openThreadInsights(parent, target, section); + const menu = ( + + + ) : ( + + ); + return placement === "overlay" ? ( +
+ {menu} +
+ ) : ( + menu + ); +} diff --git a/apps/web/src/components/chat/ThreadInsightsPanel.tsx b/apps/web/src/components/chat/ThreadInsightsPanel.tsx new file mode 100644 index 0000000000000..e30ae6602a89f --- /dev/null +++ b/apps/web/src/components/chat/ThreadInsightsPanel.tsx @@ -0,0 +1,220 @@ +import type { ScopedThreadRef, UsageLimitSourceSnapshots } from "@t3tools/contracts"; +import { scopedThreadKey } from "@t3tools/client-runtime/environment"; +import { useAtomValue, RegistryContext } from "@effect/atom-react"; +import { useContext } from "react"; +import { threadInsightsViewAtom } from "../../state/threadInsights"; +import { RefreshCwIcon, ChevronDownIcon } from "lucide-react"; +import { useServerConfigs } 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 queries = merged.queries; + const refresh = () => { + for (const query of queries) registry.refresh(query); + }; + 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..db2c6655e7140 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, @@ -18,6 +20,7 @@ import { CollapsibleSectionHeader, SectionHeaderStatus } from "../ui/collapsible import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import { Spinner } from "../ui/spinner"; import { + THREAD_LINEAGE_ROW_CLASS, THREAD_DETAILS_PANEL_SPLIT_GROUP_CLASS, THREAD_DETAILS_PANEL_SPLIT_SEPARATOR_CLASS, } from "./threadDetailsPanelStyles"; @@ -50,6 +53,7 @@ function phaseStatusLabel(phase: SubagentWorkflowGroup["phases"][number]) { } function WorkflowMemberRow({ + parentRef, member, providerInstanceId, provider, @@ -58,6 +62,7 @@ function WorkflowMemberRow({ driver, onOpen, }: { + parentRef: ScopedThreadRef; member: RuntimeSubagent; providerInstanceId: ProviderInstanceId; provider: ServerProvider | undefined; @@ -69,7 +74,14 @@ function WorkflowMemberRow({ const threadId = member.childThreadId; const canOpen = threadId !== null; return ( -
  • +
  • + {threadId !== null ? ( + + ) : null} {member.title} {member.status} {member.startedAt ? ( - + ) : null} @@ -118,6 +133,7 @@ function WorkflowMemberRow({ } export function ThreadLineageWorkflowRow({ + parentRef, group, header, providerInstanceId, @@ -130,6 +146,7 @@ export function ThreadLineageWorkflowRow({ stopping, stopDisabled, }: { + readonly parentRef: ScopedThreadRef; readonly group: SubagentWorkflowGroup; readonly header: ReactNode; readonly providerInstanceId: ProviderInstanceId; @@ -228,6 +245,7 @@ export function ThreadLineageWorkflowRow({
      {phase.members.map((member) => ( ( ({ })); vi.mock(import("../../state/entities"), () => ({ + useServerConfigs: (() => new Map()) as never, useQuietThreadShell: (() => null) as never, useQuietThreadProjection: ((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 16882da3f2a17..51217fd9731dc 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"; @@ -90,6 +92,7 @@ import { toastManager } from "../ui/toast"; import { Spinner } from "../ui/spinner"; import { cn } from "~/lib/utils"; import { + THREAD_LINEAGE_ROW_CLASS, THREAD_DETAILS_PANEL_CHEVRON_CLASS, THREAD_DETAILS_PANEL_ICON_CLASS, THREAD_DETAILS_PANEL_LABEL_CLASS, @@ -119,7 +122,7 @@ function ThreadLineageRowList(props: { {/* ScrollArea's max-height viewport measures badly inside this scrolling panel. */}
        {props.children}
      @@ -262,6 +265,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; readonly anyInstanceBadge: boolean; @@ -276,7 +280,12 @@ function RemoteSubagentRow(props: { isSubagent: true, }); return ( -
    • +
    • + on {remoteChild.label} @@ -836,12 +846,14 @@ export function ThreadRelationshipsPanel(props: { )} {agent && !failed && (deriveSubagentElapsedMs(agent, 0) !== null || canStopWorkflow) ? ( ) : !isMergeTarget ? ( +
    • + {isMergeTarget ? (
      @@ -942,7 +963,10 @@ export function ThreadRelationshipsPanel(props: { : "Merge this conversation back into its source"} - + {threadRelationshipStatusLabel(rowStatus)}
      @@ -950,7 +974,7 @@ export function ThreadRelationshipsPanel(props: { relationshipLink )} {canStop && agent ? ( -
      +
      "remote" in row ? ( ctx.onOpenThread(ThreadId.make(threadId))} diff --git a/apps/web/src/components/chat/TimelineWorkEntryRow.tsx b/apps/web/src/components/chat/TimelineWorkEntryRow.tsx index eecd3c50bdd7c..1cbe4b61ea53e 100644 --- a/apps/web/src/components/chat/TimelineWorkEntryRow.tsx +++ b/apps/web/src/components/chat/TimelineWorkEntryRow.tsx @@ -57,6 +57,8 @@ import { type TimelineWorkEntry, } from "./timelineRowContext"; import { MESSAGE_HEADING_LEVEL, TimelineRowTimestamp } from "./TimelineRowParts"; +import { CommandProgressMeter } from "./CommandProgressMeter"; +import { useCommandProgress } from "./useCommandProgress"; import { failedToolIconClassName, toolIconAcceptsTint, @@ -241,6 +243,15 @@ function WorkEntryLogRow(props: WorkEntryRowProps) { setExpanded(next); }; const failureItem = workEntry.projectedItem?.item; + const runningCommandId = + failureItem?.type === "command_execution" && failureItem.status === "running" + ? failureItem.id + : null; + // Guest pages read turn items over HTTP and cannot subscribe. + const commandProgress = useCommandProgress( + threadRef, + runningCommandId !== null && ctx.turnItemSource === undefined, + ).find((progress) => progress.itemId === runningCommandId); const pendingApproval = failureItem?.type === "approval_request" ? ctx.pendingApprovals.get(failureItem.requestId) @@ -539,6 +550,7 @@ function WorkEntryLogRow(props: WorkEntryRowProps) { Open subagent ) : null} + {commandProgress ? : null} {showFailedIndicator && !showDestructiveRowStyle && !toolIconAcceptsTint(entryToolIcon) ? ( diff --git a/apps/web/src/components/chat/TimelineWorkGroupRows.tsx b/apps/web/src/components/chat/TimelineWorkGroupRows.tsx index 1784f38da4557..421a1366c08fa 100644 --- a/apps/web/src/components/chat/TimelineWorkGroupRows.tsx +++ b/apps/web/src/components/chat/TimelineWorkGroupRows.tsx @@ -1,6 +1,6 @@ import { TimelinePendingApprovalRow } from "./TimelinePendingApprovalRow"; import { WorkLogButton, WorkLogList, WorkLogRow } from "./WorkLog"; -import type { WorktreeSetupSnapshot } from "@t3tools/contracts"; +import type { OrchestrationV2CommandProgress, WorktreeSetupSnapshot } from "@t3tools/contracts"; import { type ToolActivityIcon } from "@t3tools/contracts"; import { liveThoughtLine, @@ -62,6 +62,8 @@ import { workEntryIconName, } from "./TimelineWorkEntryRow.logic"; import { formatWorkingTimerNow } from "./TimelineWorkGroupRows.logic"; +import { CommandProgressMeter } from "./CommandProgressMeter"; +import { useCommandProgress } from "./useCommandProgress"; export const WorkGroupSection = memo(function WorkGroupSection({ anchorKey, @@ -463,6 +465,7 @@ function LiveActivityRow({ failed = false, active = false, shimmer = false, + progress = undefined, }: { label: ReactNode; iconName?: WorkEntryIconName; @@ -470,6 +473,7 @@ function LiveActivityRow({ failed?: boolean; active?: boolean; shimmer?: boolean; + progress?: OrchestrationV2CommandProgress | undefined; }) { const animated = active && !failed; const showShimmer = animated && shimmer; @@ -485,6 +489,7 @@ function LiveActivityRow({ failed={failed} announceFailure={failed} active={animated && !shimmer} + progress={progress} /> {showShimmer ? ( @@ -503,6 +508,7 @@ function LiveActivityContent({ announceFailure = false, active = false, highlighted = false, + progress = undefined, }: { label: ReactNode; iconName: WorkEntryIconName | undefined; @@ -511,6 +517,7 @@ function LiveActivityContent({ announceFailure?: boolean; active?: boolean; highlighted?: boolean; + progress?: OrchestrationV2CommandProgress | undefined; }) { const showTrailingFailureMark = failed && iconName !== undefined && !toolIconAcceptsTint(toolIcon); @@ -552,9 +559,12 @@ function LiveActivityContent({ } trailing={ - showTrailingFailureMark ? ( - - ) : null + <> + {progress ? : null} + {showTrailingFailureMark ? ( + + ) : null} + } /> ); @@ -571,6 +581,13 @@ export function LiveWorkEntryTimelineRow({ const threadLabel = threadReadLabel(label, threadTarget); const item = row.entry.projectedItem?.item; + const runningCommandId = + item?.type === "command_execution" && item.status === "running" ? item.id : null; + // Guest pages read turn items over HTTP and cannot subscribe. + const commandProgress = useCommandProgress( + ctx.threadRef, + runningCommandId !== null && ctx.turnItemSource === undefined, + ).find((progress) => progress.itemId === runningCommandId); const pendingApproval = item?.type === "approval_request" ? ctx.pendingApprovals.get(item.requestId) : undefined; if (pendingApproval) return ; @@ -653,6 +670,7 @@ export function LiveWorkEntryTimelineRow({ toolIcon={row.entry.toolIcon ?? row.entry.toolSource?.icon} failed={failed} active={row.active} + progress={commandProgress} /> ); diff --git a/apps/web/src/components/chat/V2LifecycleRow.tsx b/apps/web/src/components/chat/V2LifecycleRow.tsx index 920586f6d1dbb..20ef876302faf 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"; @@ -502,43 +503,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} { expect(visibility.usage).toBe(row.usage); expect(visibility.context).toBe(row.context); expect(visibility.servers).toBe(true); + expect(visibility.cost).toBe(true); }); it("stores only choices that differ from the default", () => { @@ -32,5 +33,14 @@ describe("thread details items", () => { const hidden = { threadDetailsItems: { servers: false }, threadDetailsUsageEnabled: false }; expect(setThreadDetailsItem(hidden, servers, true)).toEqual({}); + + const cost = THREAD_DETAILS_ITEMS.find((item) => item.id === "cost")!; + expect(setThreadDetailsItem(legacyOn, cost, false)).toEqual({ cost: false }); + expect( + resolveThreadDetailsVisibility({ ...legacyOn, threadDetailsItems: { cost: false } }).cost, + ).toBe(false); + expect( + setThreadDetailsItem({ ...legacyOn, threadDetailsItems: { cost: false } }, cost, true), + ).toEqual({}); }); }); diff --git a/apps/web/src/components/chat/threadDetailsItems.ts b/apps/web/src/components/chat/threadDetailsItems.ts index e6f94cc4e11c8..37663be2e3da2 100644 --- a/apps/web/src/components/chat/threadDetailsItems.ts +++ b/apps/web/src/components/chat/threadDetailsItems.ts @@ -14,6 +14,7 @@ export const THREAD_DETAILS_ITEMS = [ { id: "sideChats", label: "Side chats", defaultVisible: true }, { id: "usage", label: "Usage limits", defaultVisible: false }, { id: "context", label: "Context window", defaultVisible: false }, + { id: "cost", label: "Estimated cost", defaultVisible: true }, ] as const; export type ThreadDetailsItemId = (typeof THREAD_DETAILS_ITEMS)[number]["id"]; diff --git a/apps/web/src/components/chat/threadDetailsPanelStyles.ts b/apps/web/src/components/chat/threadDetailsPanelStyles.ts index edc5b81c65bc1..ab3587308a381 100644 --- a/apps/web/src/components/chat/threadDetailsPanelStyles.ts +++ b/apps/web/src/components/chat/threadDetailsPanelStyles.ts @@ -45,3 +45,6 @@ export const THREAD_DETAILS_PANEL_SPLIT_SECONDARY_CLASS = `${THREAD_DETAILS_PANE // The split hairline shows only while the pair is in use, so resting rows read as plain rows. export const THREAD_DETAILS_PANEL_SPLIT_SEPARATOR_CLASS = "h-4 w-px shrink-0 bg-transparent group-hover/details-split:bg-border/65 group-has-[[data-popup-open]]/details-split:bg-border/65"; + +export const THREAD_LINEAGE_ROW_CLASS = + "group/lineage relative has-[[data-slot=thread-insights-menu]]:hover:[&_[data-slot=lineage-meta]]:invisible has-[[data-slot=thread-insights-menu]]:focus-within:[&_[data-slot=lineage-meta]]:invisible has-[[data-slot=thread-insights-menu]_[data-popup-open]]:[&_[data-slot=lineage-meta]]:invisible pointer-coarse:has-[[data-slot=thread-insights-menu]]:[&_[data-slot=lineage-meta]]:invisible [@media(hover:none)]:has-[[data-slot=thread-insights-menu]]:[&_[data-slot=lineage-meta]]:invisible"; diff --git a/apps/web/src/components/chat/useCommandProgress.ts b/apps/web/src/components/chat/useCommandProgress.ts new file mode 100644 index 0000000000000..cc190ab8ed904 --- /dev/null +++ b/apps/web/src/components/chat/useCommandProgress.ts @@ -0,0 +1,40 @@ +import type { OrchestrationV2CommandProgress, ScopedThreadRef } from "@t3tools/contracts"; + +import { orchestrationEnvironment } from "../../state/orchestration"; +import { useEnvironmentQuery } from "../../state/query"; + +const NO_PROGRESS: ReadonlyArray = []; + +/** + * Counts the thread's running commands print, such as `24/31` or `42%`. Rows and the + * scroll-to-end button share one subscription, held only while a caller passes `enabled`. + */ +export function useCommandProgress( + threadRef: ScopedThreadRef | null, + enabled: boolean, +): ReadonlyArray { + const { data } = useEnvironmentQuery( + enabled && threadRef + ? orchestrationEnvironment.v2.commandProgress({ + environmentId: threadRef.environmentId, + input: { threadId: threadRef.threadId }, + }) + : null, + ); + return data?.items ?? NO_PROGRESS; +} + +export function formatCommandProgress(progress: OrchestrationV2CommandProgress): string { + return progress.total === 100 + ? `${progress.completed}%` + : `${progress.completed}/${progress.total}`; +} + +const COMMAND_LABEL_MAX_CHARS = 32; + +export function truncateCommandLabel(command: string): string { + const label = command.trim().replace(/\s+/g, " "); + return label.length > COMMAND_LABEL_MAX_CHARS + ? `${label.slice(0, COMMAND_LABEL_MAX_CHARS - 1)}…` + : label; +} diff --git a/apps/web/src/components/settings/AppearanceSettingsPanel.tsx b/apps/web/src/components/settings/AppearanceSettingsPanel.tsx index 00783b085d609..db79455013623 100644 --- a/apps/web/src/components/settings/AppearanceSettingsPanel.tsx +++ b/apps/web/src/components/settings/AppearanceSettingsPanel.tsx @@ -36,6 +36,7 @@ import { AdvancedSettings } from "./AdvancedSettings"; import { PanelAnimationsPreview } from "./PanelAnimationsPreview"; import { TypographySection } from "./TypographySettings"; import { ThreadDetailsItemsRow } from "./ThreadDetailsItemsRow"; +import { WallpaperSettingsRows } from "./WallpaperSettingsRows"; const ENVIRONMENT_IDENTIFICATION_LABELS: Record = { artwork: "Artwork", @@ -257,6 +258,8 @@ export function AppearanceSettingsPanel() { } /> + + void) { ? ["Contrast"] : []), ...(settings.glassOpacity !== DEFAULT_UNIFIED_SETTINGS.glassOpacity ? ["Glass opacity"] : []), + ...(settings.wallpaper !== DEFAULT_UNIFIED_SETTINGS.wallpaper ? ["Wallpaper"] : []), + ...(settings.wallpaperBlur !== DEFAULT_UNIFIED_SETTINGS.wallpaperBlur + ? ["Wallpaper blur"] + : []), + ...(settings.wallpaperDim !== DEFAULT_UNIFIED_SETTINGS.wallpaperDim + ? ["Wallpaper dimming"] + : []), ...(settings.diffColorScheme !== DEFAULT_UNIFIED_SETTINGS.diffColorScheme ? ["Diff colors"] : []), @@ -515,6 +522,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 @@ -673,6 +684,9 @@ export function useSettingsRestore(onRestored?: () => void) { screenReaderWindowTitle: DEFAULT_UNIFIED_SETTINGS.screenReaderWindowTitle, environmentIdentificationMode: DEFAULT_UNIFIED_SETTINGS.environmentIdentificationMode, glassOpacity: DEFAULT_UNIFIED_SETTINGS.glassOpacity, + wallpaper: DEFAULT_UNIFIED_SETTINGS.wallpaper, + wallpaperBlur: DEFAULT_UNIFIED_SETTINGS.wallpaperBlur, + wallpaperDim: DEFAULT_UNIFIED_SETTINGS.wallpaperDim, panelAnimationDurationMs: DEFAULT_UNIFIED_SETTINGS.panelAnimationDurationMs, sidebarProjectGroupingMode: DEFAULT_UNIFIED_SETTINGS.sidebarProjectGroupingMode, sidebarProjectSortOrder: DEFAULT_UNIFIED_SETTINGS.sidebarProjectSortOrder, @@ -683,6 +697,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 +1750,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 +1863,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/WallpaperSettingsRows.tsx b/apps/web/src/components/settings/WallpaperSettingsRows.tsx new file mode 100644 index 0000000000000..3cdae4b5c157c --- /dev/null +++ b/apps/web/src/components/settings/WallpaperSettingsRows.tsx @@ -0,0 +1,161 @@ +import { + type AppWallpaper, + DEFAULT_UNIFIED_SETTINGS, + MAX_WALLPAPER_BLUR, + MAX_WALLPAPER_DIM, +} from "@t3tools/contracts/settings"; +import type { CSSProperties } from "react"; + +import { updateClientSettings, useClientSettings } from "../../hooks/useSettings"; +import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select"; +import { SettingResetButton, SettingsRow } from "./settingsLayout"; +import { searchableSetting } from "./settingsSearch"; + +const WALLPAPER_LABELS: Record = { + none: "None", + "f1-race": "F1 race", +}; + +function sliderStyle(value: number, max: number): CSSProperties { + const ratio = value / max; + return { + "--settings-slider-progress": `${ratio * 100}%`, + "--settings-slider-fill-offset": `${0.5 - ratio}rem`, + } as CSSProperties; +} + +function WallpaperSlider(props: { + id: "wallpaper-blur" | "wallpaper-dim"; + label: string; + value: number; + max: number; + unit: string; + onChange: (value: number) => void; +}) { + return ( +
      + + {props.value} + {props.unit} + + { + const value = Number(event.currentTarget.value); + if (Number.isInteger(value) && value >= 0 && value <= props.max) props.onChange(value); + }} + step={1} + style={sliderStyle(props.value, props.max)} + type="range" + value={props.value} + /> +
      + ); +} + +/** Picks a picture behind the app, and how much it is blurred and darkened so text stays readable. */ +export function WallpaperSettingsRows() { + const wallpaper = useClientSettings((settings) => settings.wallpaper); + const blur = useClientSettings((settings) => settings.wallpaperBlur); + const dim = useClientSettings((settings) => settings.wallpaperDim); + return ( + <> + + updateClientSettings({ wallpaper: DEFAULT_UNIFIED_SETTINGS.wallpaper }) + } + /> + ) : null + } + control={ +
      + +
      + } + /> + {wallpaper === "none" ? null : ( + <> + + updateClientSettings({ wallpaperBlur: DEFAULT_UNIFIED_SETTINGS.wallpaperBlur }) + } + /> + ) : null + } + control={ + updateClientSettings({ wallpaperBlur })} + /> + } + /> + + updateClientSettings({ wallpaperDim: DEFAULT_UNIFIED_SETTINGS.wallpaperDim }) + } + /> + ) : null + } + control={ + updateClientSettings({ wallpaperDim })} + /> + } + /> + + )} + + ); +} diff --git a/apps/web/src/components/settings/settingsSearch.test.ts b/apps/web/src/components/settings/settingsSearch.test.ts index bac40332a2770..5fa7c08c0cc30 100644 --- a/apps/web/src/components/settings/settingsSearch.test.ts +++ b/apps/web/src/components/settings/settingsSearch.test.ts @@ -10,7 +10,7 @@ import * as Schema from "effect/Schema"; import { filterAvailableSettingsSearchItems, getSettingsSearchTargetScope, - getThreadAutoSettlementSearchAvailability, + getThreadSettingsSearchAvailability, isSettingsSearchScopeAvailable, movedSettingsPath, searchSettings, @@ -130,6 +130,30 @@ describe("searchSettings", () => { hasThreadAutoSettlement: false, }); + const connectedWithoutSnooze = filterAvailableSettingsSearchItems({ + hasCloudPublicConfig: false, + hasEnvironment: true, + hasProviderSettingsEnvironment: true, + canManageLocalBackend: false, + isWslSettingsRowVisible: false, + hasThreadAutoSettlement: true, + }); + expect(connectedWithoutSnooze.map((item) => item.id)).not.toContain( + "snooze-until-scheduled-task", + ); + const connectedWithSnooze = filterAvailableSettingsSearchItems({ + hasCloudPublicConfig: false, + hasEnvironment: true, + hasProviderSettingsEnvironment: true, + canManageLocalBackend: false, + isWslSettingsRowVisible: false, + hasThreadAutoSettlement: true, + hasScheduledTaskSnooze: true, + }); + expect(connectedWithSnooze.map((item) => item.id)).toContain("snooze-until-scheduled-task"); + expect(getSettingsSearchTargetScope("snooze-until-scheduled-task")).toMatchObject({ + requiresScheduledTaskSnooze: true, + }); const gatedIds = new Set([ "follow-change-request-templates", "git-fetch-interval", @@ -270,11 +294,14 @@ describe("settings search targets", () => { }); describe("auto-settlement search availability", () => { - function environment(id: string, { connected = true, loaded = true } = {}) { + function environment( + id: string, + { connected = true, loaded = true, scheduledTaskSnooze = true } = {}, + ) { return { environmentId: EnvironmentId.make(id), connection: { phase: connected ? ("connected" as const) : ("offline" as const) }, - serverConfig: loaded ? { environment: { capabilities: {} } } : null, + serverConfig: loaded ? { environment: { capabilities: { scheduledTaskSnooze } } } : null, }; } @@ -284,8 +311,31 @@ describe("auto-settlement search availability", () => { const environments = [capable, offline, loading]; it("keeps results discoverable when one connected environment supports them", () => { - const availability = getThreadAutoSettlementSearchAvailability(environments); + const availability = getThreadSettingsSearchAvailability(environments); expect(availability.eligibleEnvironmentIds).toEqual([capable.environmentId]); + const unsupported = environment("unsupported", { scheduledTaskSnooze: false }); + const mixed = [capable, unsupported, offline, loading]; + expect( + getThreadSettingsSearchAvailability( + mixed, + { kind: "all", environmentIds: mixed.map((entry) => entry.environmentId) }, + "scheduledTaskSnooze", + ), + ).toEqual({ eligibleEnvironmentIds: [capable.environmentId], isTargetAvailable: false }); + expect( + getThreadSettingsSearchAvailability( + mixed, + { kind: "environment", environmentIds: [capable.environmentId] }, + "scheduledTaskSnooze", + ).isTargetAvailable, + ).toBe(true); + expect( + getThreadSettingsSearchAvailability( + mixed, + { kind: "environment", environmentIds: [unsupported.environmentId] }, + "scheduledTaskSnooze", + ).isTargetAvailable, + ).toBe(false); const items = filterAvailableSettingsSearchItems({ hasCloudPublicConfig: false, hasEnvironment: true, @@ -306,7 +356,7 @@ describe("auto-settlement search availability", () => { "does not render the target on $environmentId or silently fall back", (selected) => { expect( - getThreadAutoSettlementSearchAvailability(environments, { + getThreadSettingsSearchAvailability(environments, { kind: "environment", environmentIds: [selected.environmentId], }), @@ -317,7 +367,7 @@ describe("auto-settlement search availability", () => { it("ignores offline and unloaded targets when all connected targets support the setting", () => { const selected = [capable, offline, loading]; expect( - getThreadAutoSettlementSearchAvailability(selected, { + getThreadSettingsSearchAvailability(selected, { kind: "all", environmentIds: selected.map((entry) => entry.environmentId), }).isTargetAvailable, diff --git a/apps/web/src/components/settings/settingsSearch.ts b/apps/web/src/components/settings/settingsSearch.ts index 7d7939e7f21f9..7066ceb7448f4 100644 --- a/apps/web/src/components/settings/settingsSearch.ts +++ b/apps/web/src/components/settings/settingsSearch.ts @@ -74,6 +74,7 @@ export interface SettingsSearchItem { readonly textGeneratorsOnly?: boolean; readonly secondary?: boolean; readonly requiresThreadAutoSettlement?: boolean; + readonly requiresScheduledTaskSnooze?: boolean; } export interface SettingsSearchAvailability { @@ -84,6 +85,7 @@ export interface SettingsSearchAvailability { readonly canManageLocalBackend: boolean; readonly isWslSettingsRowVisible: boolean; readonly hasThreadAutoSettlement: boolean; + readonly hasScheduledTaskSnooze?: boolean; readonly managedTunnelActive?: boolean; readonly hasPeerLinkHost?: boolean; readonly hasFastWorktreeCheckoutEnvironment?: boolean; @@ -335,6 +337,29 @@ export const SETTINGS_SEARCH_ITEMS = [ to: "/settings/appearance", searchTerms: ["transparent transparency solid menus dialogs composer"], }, + { + id: "wallpaper", + title: "Wallpaper", + to: "/settings/appearance", + searchTerms: ["background image picture photo formula 1 f1 race cars"], + }, + { + // Prefixed because the slider control already owns the `wallpaper-blur` id. + id: "setting-wallpaper-blur", + // The row shows only while a wallpaper is set; the picker is always there. + targetId: "wallpaper", + title: "Wallpaper blur", + to: "/settings/appearance", + searchTerms: ["background blur difuminado soften readability"], + }, + { + // Prefixed because the slider control already owns the `wallpaper-dim` id. + id: "setting-wallpaper-dim", + targetId: "wallpaper", + title: "Wallpaper dimming", + to: "/settings/appearance", + searchTerms: ["background darken dim brightness readability"], + }, { id: "diff-color-scheme", title: "Diff colors", @@ -453,6 +478,15 @@ export const SETTINGS_SEARCH_ITEMS = [ to: "/settings/threads", searchTerms: ["usage quota rate limit reset wake recover continue"], }, + { + id: "snooze-until-scheduled-task", + requiresScheduledTaskSnooze: true, + 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", @@ -1442,25 +1476,35 @@ export function getSettingsSearchTargetScope(targetId: string) { title: item.title, scope: item.scope ?? SETTINGS_CATEGORY_SCOPES[item.to], ...(item.requiresThreadAutoSettlement ? { requiresThreadAutoSettlement: true } : {}), + ...(item.requiresScheduledTaskSnooze ? { requiresScheduledTaskSnooze: true } : {}), } : null; } -interface AutoSettlementSearchEnvironment { +interface ThreadSettingsSearchEnvironment { readonly environmentId: EnvironmentId; readonly connection: { readonly phase: EnvironmentConnectionPhase }; - readonly serverConfig: object | null; + readonly serverConfig: { + readonly environment: { readonly capabilities: { readonly scheduledTaskSnooze?: boolean } }; + } | null; } -export function getThreadAutoSettlementSearchAvailability( - environments: readonly AutoSettlementSearchEnvironment[], +export function getThreadSettingsSearchAvailability( + environments: readonly ThreadSettingsSearchEnvironment[], scope?: Pick, + capability?: "scheduledTaskSnooze", ) { const connected = environments.filter( (environment) => environment.connection.phase === "connected" && environment.serverConfig !== null, ); - const eligibleEnvironmentIds = connected.map((environment) => environment.environmentId); + const eligibleEnvironmentIds = connected + .filter( + (environment) => + capability === undefined || + environment.serverConfig?.environment.capabilities[capability] === true, + ) + .map((environment) => environment.environmentId); const selected = connected.filter((environment) => scope?.environmentIds.includes(environment.environmentId), ); @@ -1521,6 +1565,7 @@ export function filterAvailableSettingsSearchItems( (!item.primaryEnvironmentOnly || availability.hasPrimaryEnvironment === true) && (!item.wslAvailableOnly || availability.isWslSettingsRowVisible) && (!item.requiresThreadAutoSettlement || availability.hasThreadAutoSettlement) && + (!item.requiresScheduledTaskSnooze || availability.hasScheduledTaskSnooze === true) && (!item.managedTunnelOnly || availability.managedTunnelActive === true) && (!item.peerLinksOnly || availability.hasPeerLinkHost === true) && (!item.fastWorktreeCheckoutOnly || diff --git a/apps/web/src/components/settings/useAvailableSettingsSearchItems.ts b/apps/web/src/components/settings/useAvailableSettingsSearchItems.ts index 8dc0bce3a75f0..3dd8a89daf0a0 100644 --- a/apps/web/src/components/settings/useAvailableSettingsSearchItems.ts +++ b/apps/web/src/components/settings/useAvailableSettingsSearchItems.ts @@ -13,7 +13,7 @@ import { isWslSettingsRowVisible } from "./ConnectionsSettings.logic"; import { isProviderSettingsEnvironmentAvailable } from "./ProviderSettingsPanel.logic"; import { filterAvailableSettingsSearchItems, - getThreadAutoSettlementSearchAvailability, + getThreadSettingsSearchAvailability, } from "./settingsSearch"; export function useAvailableSettingsSearchItems() { @@ -42,7 +42,10 @@ export function useAvailableSettingsSearchItems() { environment.serverConfig.managedPolicy?.limits?.providers?.allowedDrivers === undefined, ) === true; const hasThreadAutoSettlement = - getThreadAutoSettlementSearchAvailability(environments).eligibleEnvironmentIds.length > 0; + getThreadSettingsSearchAvailability(environments).eligibleEnvironmentIds.length > 0; + const hasScheduledTaskSnooze = + getThreadSettingsSearchAvailability(environments, undefined, "scheduledTaskSnooze") + .eligibleEnvironmentIds.length > 0; const primaryEnvironmentId = usePrimaryEnvironmentId(); const canMaintain = useEnvironmentScope(primaryEnvironmentId, AuthEnvironmentMaintainScope); const hasPeerLinkHost = usePeerLinkHosts().length > 0; @@ -68,6 +71,7 @@ export function useAvailableSettingsSearchItems() { canManageLocalBackend, isWslSettingsRowVisible: wslSettingsRowVisible, hasThreadAutoSettlement, + hasScheduledTaskSnooze, managedTunnelActive, hasPeerLinkHost, hasFastWorktreeCheckoutEnvironment, diff --git a/apps/web/src/components/threadActionMenu.logic.ts b/apps/web/src/components/threadActionMenu.logic.ts index 1e3eddd0b9389..546eff2406a2f 100644 --- a/apps/web/src/components/threadActionMenu.logic.ts +++ b/apps/web/src/components/threadActionMenu.logic.ts @@ -2,6 +2,8 @@ import type { ContextMenuItem } from "@t3tools/contracts"; import type { SnoozePreset } from "@t3tools/client-runtime/state/thread-settled"; export type ThreadActionMenuId = + | "view-tasks" + | "view-usage" | "find" | "new-thread-on-branch" | "filter-by-project" @@ -70,6 +72,7 @@ export function buildDraftActionMenuItems(options: { export interface ThreadActionMenuState { readonly canOperate: boolean; readonly canFind?: boolean; + readonly canViewInsights?: boolean; readonly branch: string | null; readonly projectFilter: { readonly label: string; @@ -102,6 +105,8 @@ export function threadActionRequiresOperate(action: ThreadActionMenuId): boolean return ![ "find", "new-thread-on-branch", + "view-tasks", + "view-usage", "project-settings", "mark-unread", "share-guest", @@ -117,6 +122,12 @@ export function buildThreadActionMenuItems( state: ThreadActionMenuState, ): ReadonlyArray> { 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 f96baf908b3d9..7740f71a20a39 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(); @@ -129,6 +134,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, @@ -185,6 +193,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/index.css b/apps/web/src/index.css index 771c714b1ff8a..f0f4ee5685e8d 100644 --- a/apps/web/src/index.css +++ b/apps/web/src/index.css @@ -2640,3 +2640,34 @@ code { .messages-timeline-scroll:focus-visible { outline: none; } + +/* The wallpaper paints once on a fixed layer behind the app. Its blur is a filter on that layer, + never a backdrop-filter, so scrolling and streaming never re-blur it. */ +:root[data-wallpaper] body::before { + content: ""; + position: fixed; + inset: calc(var(--wallpaper-blur) * -2); + z-index: -1; + pointer-events: none; + background: + linear-gradient( + color-mix(in srgb, var(--background) var(--wallpaper-dim), transparent), + color-mix(in srgb, var(--background) var(--wallpaper-dim), transparent) + ), + var(--wallpaper-image) center / cover no-repeat; + filter: blur(var(--wallpaper-blur)); +} + +/* The theme also writes the chrome color inline on body, for the window background. */ +:root[data-wallpaper] body { + background-color: transparent !important; +} + +:root[data-wallpaper] [data-slot="sidebar-inset"], +:root[data-wallpaper] [data-wallpaper-surface] { + background-color: transparent; +} + +:root[data-wallpaper] [data-slot="sidebar-inner"] { + background-color: color-mix(in srgb, var(--sidebar) 72%, transparent); +} diff --git a/apps/web/src/reopenClosedView.ts b/apps/web/src/reopenClosedView.ts index 4a16c40ff8f93..ccaaa78dc8cee 100644 --- a/apps/web/src/reopenClosedView.ts +++ b/apps/web/src/reopenClosedView.ts @@ -158,6 +158,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/routes/_chat.settings.tsx b/apps/web/src/routes/_chat.settings.tsx index 20f65d45c7a5b..b2a8fea2bc241 100644 --- a/apps/web/src/routes/_chat.settings.tsx +++ b/apps/web/src/routes/_chat.settings.tsx @@ -22,7 +22,7 @@ import { } from "../components/settings/settingsScopeNavigation"; import { getSettingsSearchTargetScope, - getThreadAutoSettlementSearchAvailability, + getThreadSettingsSearchAvailability, isSettingsSearchScopeAvailable, movedSettingsPath, } from "../components/settings/settingsSearch"; @@ -47,22 +47,27 @@ function SettingsScopeBoundary({ pathname, children }: { pathname: string; child const { environments } = useEnvironments(); const hash = useLocation({ select: (location) => location.hash }); const searchTarget = getSettingsSearchTargetScope(hash); - const autoSettlementAvailability = searchTarget?.requiresThreadAutoSettlement - ? getThreadAutoSettlementSearchAvailability(environments, scope) - : null; + const capabilityAvailability = + searchTarget?.requiresThreadAutoSettlement || searchTarget?.requiresScheduledTaskSnooze + ? getThreadSettingsSearchAvailability( + environments, + scope, + searchTarget.requiresScheduledTaskSnooze ? "scheduledTaskSnooze" : undefined, + ) + : null; if ( scope.kind !== "unavailable" && searchTarget && - autoSettlementAvailability && - !autoSettlementAvailability.isTargetAvailable + capabilityAvailability && + !capabilityAvailability.isTargetAvailable ) { return ( - {autoSettlementAvailability.eligibleEnvironmentIds.length > 0 + {capabilityAvailability.eligibleEnvironmentIds.length > 0 ? `${searchTarget.title} requires a supporting environment. Choose one to continue.` : `${searchTarget.title} requires a supporting environment. Connect or update an environment to continue.`} diff --git a/apps/web/src/state/threadInsights.ts b/apps/web/src/state/threadInsights.ts new file mode 100644 index 0000000000000..f2ff91fd2dbd0 --- /dev/null +++ b/apps/web/src/state/threadInsights.ts @@ -0,0 +1,64 @@ +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"; +import { environmentThreadShells } from "./threads"; +import { createThreadInsightsRefreshAtom } from "./threadInsightsRefresh"; + +export const threadInsightsViewAtom = Atom.family((key: string) => { + const target = parseScopedThreadKey(key); + if (target === null) throw new Error("Invalid thread insights target"); + const view = Atom.make((get) => { + const configs = get(environmentPresentations.serverConfigsAtom); + const answers = new Map(); + const queue = [target]; + const visited = new Set(); + const queries: ReturnType[] = []; + const errors = new Set(); + let loading = false; + 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); + loading ||= AsyncResult.isInitial(result) || result.waiting; + if (AsyncResult.isFailure(result)) { + errors.add("An environment could not report tasks and usage."); + } + 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], loading }; + }); + const revisions = Atom.make((get) => { + const data = get(view); + const refs = [target, ...data.rows, ...data.pending]; + return new Map( + refs.map((ref) => [ + scopedThreadKey(ref), + get(environmentThreadShells.threadShellAtom(ref))?.updatedAt, + ]), + ); + }); + const refresh = createThreadInsightsRefreshAtom(revisions, (registry) => { + for (const query of registry.get(view).queries) registry.refresh(query); + }); + return Atom.make((get) => { + get(refresh); + return get(view); + }); +}); diff --git a/apps/web/src/state/threadInsightsRefresh.test.ts b/apps/web/src/state/threadInsightsRefresh.test.ts new file mode 100644 index 0000000000000..8a1856d696153 --- /dev/null +++ b/apps/web/src/state/threadInsightsRefresh.test.ts @@ -0,0 +1,81 @@ +import { Atom, AtomRegistry } from "effect/reactivity"; +import { describe, expect, it, vi } from "vite-plus/test"; + +import { createThreadInsightsRefreshAtom } from "./threadInsightsRefresh"; + +function setup() { + const revisions = Atom.make>( + new Map([["local:root", "0"]]), + ); + const refresh = vi.fn(); + const atom = createThreadInsightsRefreshAtom(revisions, refresh); + const registry = AtomRegistry.make(); + return { revisions, refresh, atom, registry }; +} + +describe("thread insights refresh", () => { + it("shares one refresh deadline across readers without starving on continuous updates", () => { + vi.useFakeTimers(); + try { + const { revisions, refresh, atom, registry } = setup(); + const unmountRow = registry.mount(atom); + const unmountPanel = registry.mount(atom); + expect(refresh).not.toHaveBeenCalled(); + registry.set(revisions, new Map([["local:root", "1"]])); + vi.advanceTimersByTime(500); + registry.set(revisions, new Map([["local:root", "2"]])); + vi.advanceTimersByTime(500); + expect(refresh).toHaveBeenCalledTimes(1); + unmountRow(); + registry.set(revisions, new Map([["local:root", "3"]])); + vi.advanceTimersByTime(1_000); + expect(refresh).toHaveBeenCalledTimes(2); + registry.set(revisions, new Map([["local:root", "4"]])); + unmountPanel(); + vi.runAllTimers(); + expect(refresh).toHaveBeenCalledTimes(2); + registry.dispose(); + } finally { + vi.useRealTimers(); + } + }); + + it("tracks newly loaded subagents without refetching just because an answer arrived", () => { + vi.useFakeTimers(); + try { + const { revisions, refresh, atom, registry } = setup(); + const unmount = registry.mount(atom); + registry.set( + revisions, + new Map([ + ["local:root", "0"], + ["remote:child", "0"], + ]), + ); + vi.runAllTimers(); + expect(refresh).not.toHaveBeenCalled(); + registry.set( + revisions, + new Map([ + ["local:root", "0"], + ["remote:child", "1"], + ]), + ); + vi.advanceTimersByTime(1_000); + expect(refresh).toHaveBeenCalledTimes(1); + registry.set( + revisions, + new Map([ + ["local:root", "0"], + ["remote:child", undefined], + ]), + ); + vi.advanceTimersByTime(1_000); + expect(refresh).toHaveBeenCalledTimes(2); + unmount(); + registry.dispose(); + } finally { + vi.useRealTimers(); + } + }); +}); diff --git a/apps/web/src/state/threadInsightsRefresh.ts b/apps/web/src/state/threadInsightsRefresh.ts new file mode 100644 index 0000000000000..57321d83735c0 --- /dev/null +++ b/apps/web/src/state/threadInsightsRefresh.ts @@ -0,0 +1,26 @@ +import { Atom, type AtomRegistry } from "effect/reactivity"; + +export function createThreadInsightsRefreshAtom( + revisions: Atom.Atom>, + refresh: (registry: AtomRegistry.AtomRegistry) => void, +) { + return Atom.make((get) => { + let previous = get.once(revisions); + let timer: ReturnType | undefined; + get.subscribe(revisions, (next) => { + const changed = [...next].some( + ([key, value]) => previous.has(key) && previous.get(key) !== value, + ); + previous = next; + // Keep the first deadline so continuous streaming cannot postpone the refresh forever. + if (!changed || timer !== undefined) return; + timer = setTimeout(() => { + timer = undefined; + refresh(get.registry); + }, 1_000); + }); + get.addFinalizer(() => { + if (timer !== undefined) clearTimeout(timer); + }); + }); +} diff --git a/docs/user/activity-log.md b/docs/user/activity-log.md index 93b198aa18f68..eef91edeba339 100644 --- a/docs/user/activity-log.md +++ b/docs/user/activity-log.md @@ -5,6 +5,11 @@ commands, tool inputs, status, and exit codes. Expand a tool call to see its out command's output updates live, and long output shows only its most recent part. Use **Open diff** on a file change to review its contents. +When a running command prints a count, such as a test runner's `24/31` or a build's `42%`, its row +shows a progress bar. If you scroll up while it runs, **Scroll to end** shows the command and its +count. Commands that print no count, or whose provider reports output only when they finish, show no +bar. + T3 Orchestrator summaries describe the actions taken, such as **Ran 2 commands and sent messages to 3 threads**. Repeated messages to the same destinations show both counts: **Sent 5 messages to 2 threads**. Thread creation counts the threads returned by the tool, including batches. diff --git a/docs/user/appearance.md b/docs/user/appearance.md index c37855fdf3c87..80b8438727db0 100644 --- a/docs/user/appearance.md +++ b/docs/user/appearance.md @@ -29,6 +29,13 @@ The controls retreat as the composer docks after you send the first message. Turn on **Composer context** to keep those controls visible after the thread starts. This preference applies to the web and desktop clients. +## Wallpaper + +On web and desktop, choose a picture under **Wallpaper** in **Settings → Appearance** to show it +behind the sidebar and chat. If text is hard to read over it, raise **Wallpaper blur** or +**Wallpaper dimming**. Dimming darkens toward your theme's background, so it lightens the picture +in a light theme. Choose **None** to turn the wallpaper off. + ## Math Turn on **Render math** in **Settings → Appearance** to typeset LaTeX in messages and Markdown diff --git a/docs/user/thread-sidebar.md b/docs/user/thread-sidebar.md index 905f3a5bfbe9c..d00b45773c065 100644 --- a/docs/user/thread-sidebar.md +++ b/docs/user/thread-sidebar.md @@ -292,6 +292,9 @@ Select a server to open it in the browser panel. **Stop** ends the server's job and keeps the agent, the terminal, and T3 Code running. Stop needs terminal access to the environment and is not available on Windows. +Thread details appear on the right of the chat. Use the details button in the chat +header to show or hide them. On narrower windows, the button opens a popover. + To choose what the thread details card shows, right-click the card or open **Settings → Appearance → Thread details**. Hidden rows keep their keyboard shortcuts, such as Open in editor and project scripts. **Reset to default** brings @@ -339,3 +342,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/docs/user/usage.md b/docs/user/usage.md index e6b3a46d5a14e..cbe5474953eb5 100644 --- a/docs/user/usage.md +++ b/docs/user/usage.md @@ -57,6 +57,29 @@ 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, the thread details card shows an estimated cost for the thread and its +subagents. Select it to open the usage breakdown. You can hide it in **Settings → Appearance → +Thread details**. + +You can also 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 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. + ## 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 6fa96cdd493ae..aca88d5f84771 100644 --- a/packages/client-runtime/package.json +++ b/packages/client-runtime/package.json @@ -570,6 +570,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/rpc/client.ts b/packages/client-runtime/src/rpc/client.ts index ee70400ca47a5..26ba16faa2ca9 100644 --- a/packages/client-runtime/src/rpc/client.ts +++ b/packages/client-runtime/src/rpc/client.ts @@ -54,6 +54,7 @@ export type EnvironmentSubscriptionRpcTag = | typeof ORCHESTRATION_V2_WS_METHODS.subscribeShell | typeof ORCHESTRATION_V2_WS_METHODS.subscribeThread | typeof ORCHESTRATION_V2_WS_METHODS.subscribeCommandOutput + | typeof ORCHESTRATION_V2_WS_METHODS.subscribeCommandProgress | typeof ORCHESTRATION_V2_WS_METHODS.subscribePromptSuggestion | typeof ORCHESTRATION_V2_WS_METHODS.searchThreadStream | typeof WS_METHODS.subscribeAuthAccess diff --git a/packages/client-runtime/src/state/orchestration.ts b/packages/client-runtime/src/state/orchestration.ts index f22ac79383d66..745b2e8f9596b 100644 --- a/packages/client-runtime/src/state/orchestration.ts +++ b/packages/client-runtime/src/state/orchestration.ts @@ -173,6 +173,12 @@ export function createOrchestrationEnvironmentAtoms( Stream.filter((view) => view !== EMPTY_COMMAND_OUTPUT), ), }), + // Counts that the open thread's running commands print, such as `24/31` or `42%`. + commandProgress: createEnvironmentRpcSubscriptionAtomFamily(runtime, { + label: "environment-data:orchestration-v2:command-progress", + tag: ORCHESTRATION_V2_WS_METHODS.subscribeCommandProgress, + idleTtlMs: 0, + }), // The open thread's predicted next prompt, while its composer is mounted. promptSuggestion: createEnvironmentRpcSubscriptionAtomFamily(runtime, { label: "environment-data:orchestration-v2:prompt-suggestion", @@ -192,6 +198,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/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/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 603b6c6cc862d..272a3891921b2 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), @@ -202,6 +204,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 38d2e98ef72c2..58daecb2488a6 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -3816,6 +3816,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", @@ -3832,6 +3875,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", @@ -3839,6 +3883,7 @@ export const ORCHESTRATION_V2_WS_METHODS = { subscribeShell: "orchestration.subscribeShell", subscribeThread: "orchestration.subscribeThread", subscribeCommandOutput: "orchestration.subscribeCommandOutput", + subscribeCommandProgress: "orchestration.subscribeCommandProgress", subscribePromptSuggestion: "orchestration.subscribePromptSuggestion", } as const; @@ -3860,6 +3905,26 @@ export const OrchestrationV2CommandOutputFrame = Schema.Struct({ }); export type OrchestrationV2CommandOutputFrame = typeof OrchestrationV2CommandOutputFrame.Type; +export const OrchestrationV2SubscribeCommandProgressInput = Schema.Struct({ + threadId: ThreadId, +}); +export type OrchestrationV2SubscribeCommandProgressInput = + typeof OrchestrationV2SubscribeCommandProgressInput.Type; + +/** A count a running command last printed, such as a test runner's `24/31` or a build's `42%`. */ +export const OrchestrationV2CommandProgress = Schema.Struct({ + itemId: TurnItemId, + completed: NonNegativeInt, + total: PositiveInt, +}); +export type OrchestrationV2CommandProgress = typeof OrchestrationV2CommandProgress.Type; + +/** Unpersisted: every running command in the thread that printed a count, replaced whole on each frame. */ +export const OrchestrationV2CommandProgressFrame = Schema.Struct({ + items: Schema.Array(OrchestrationV2CommandProgress), +}); +export type OrchestrationV2CommandProgressFrame = typeof OrchestrationV2CommandProgressFrame.Type; + export class OrchestrationV2CommandOutputError extends Schema.TaggedError()( "OrchestrationV2CommandOutputError", { @@ -4539,6 +4604,10 @@ export const OrchestrationV2RpcSchemas = { input: OrchestrationV2GetWorkflowScriptInput, output: OrchestrationV2GetWorkflowScriptResult, }, + getThreadInsights: { + input: Schema.Struct({ threadId: ThreadId }), + output: OrchestrationV2GetThreadInsightsResult, + }, getNativeChildWork: { input: OrchestrationV2GetNativeChildWorkInput, output: OrchestrationV2GetNativeChildWorkResult, @@ -4563,6 +4632,10 @@ export const OrchestrationV2RpcSchemas = { input: OrchestrationV2SubscribeCommandOutputInput, output: OrchestrationV2CommandOutputFrame, }, + subscribeCommandProgress: { + input: OrchestrationV2SubscribeCommandProgressInput, + output: OrchestrationV2CommandProgressFrame, + }, subscribePromptSuggestion: { input: OrchestrationV2SubscribePromptSuggestionInput, output: OrchestrationV2PromptSuggestion, diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.ts index e1d392cd080b6..c555a01310de2 100644 --- a/packages/contracts/src/rpc.ts +++ b/packages/contracts/src/rpc.ts @@ -1929,6 +1929,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, { @@ -1974,6 +1983,16 @@ const WsOrchestrationV2SubscribeCommandOutputRpc = Rpc.make( }, ); +const WsOrchestrationV2SubscribeCommandProgressRpc = Rpc.make( + ORCHESTRATION_V2_WS_METHODS.subscribeCommandProgress, + { + payload: OrchestrationV2RpcSchemas.subscribeCommandProgress.input, + success: OrchestrationV2RpcSchemas.subscribeCommandProgress.output, + error: EnvironmentAuthorizationError, + stream: true, + }, +); + const WsOrchestrationV2SubscribePromptSuggestionRpc = Rpc.make( ORCHESTRATION_V2_WS_METHODS.subscribePromptSuggestion, { @@ -2312,6 +2331,7 @@ export const WsRpcGroup = RpcGroup.make( WsOrchestrationV2DispatchCommandRpc, WsOrchestrationV2GetWorkflowScriptRpc, WsOrchestrationV2GetNativeChildWorkRpc, + WsOrchestrationV2GetThreadInsightsRpc, WsOrchestrationV2StopWorkflowRpc, WsOrchestrationV2ForceStopThreadRpc, WsOrchestrationV2GetTurnItemRpc, @@ -2331,5 +2351,6 @@ export const WsRpcGroup = RpcGroup.make( WsOrchestrationV2SubscribeShellRpc, WsOrchestrationV2SubscribeThreadRpc, WsOrchestrationV2SubscribeCommandOutputRpc, + WsOrchestrationV2SubscribeCommandProgressRpc, WsOrchestrationV2SubscribePromptSuggestionRpc, ).middleware(RpcScopeAuthorization); diff --git a/packages/contracts/src/server.ts b/packages/contracts/src/server.ts index 144d2814b8804..5fb86a4c1e939 100644 --- a/packages/contracts/src/server.ts +++ b/packages/contracts/src/server.ts @@ -709,6 +709,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/contracts/src/settings.ts b/packages/contracts/src/settings.ts index 7bbb03595d4bb..cb9638fca51c6 100644 --- a/packages/contracts/src/settings.ts +++ b/packages/contracts/src/settings.ts @@ -147,6 +147,21 @@ export const GlassOpacity = Schema.Int.check( export type GlassOpacity = typeof GlassOpacity.Type; const DEFAULT_GLASS_OPACITY: GlassOpacity = 80; +export const AppWallpaper = Schema.Literals(["none", "f1-race"]); +export type AppWallpaper = typeof AppWallpaper.Type; +export const MAX_WALLPAPER_BLUR = 40; +export const WallpaperBlur = Schema.Int.check( + Schema.isBetween({ minimum: 0, maximum: MAX_WALLPAPER_BLUR }), +); +export type WallpaperBlur = typeof WallpaperBlur.Type; +const DEFAULT_WALLPAPER_BLUR: WallpaperBlur = 8; +export const MAX_WALLPAPER_DIM = 90; +export const WallpaperDim = Schema.Int.check( + Schema.isBetween({ minimum: 0, maximum: MAX_WALLPAPER_DIM }), +); +export type WallpaperDim = typeof WallpaperDim.Type; +const DEFAULT_WALLPAPER_DIM: WallpaperDim = 40; + export const MIN_APPEARANCE_CONTRAST = 50; export const MAX_APPEARANCE_CONTRAST = 200; export const AppearanceContrast = Schema.Int.check( @@ -480,6 +495,13 @@ export const ClientSettingsSchema = Schema.Struct({ glassOpacity: GlassOpacity.pipe( Schema.withDecodingDefault(Effect.succeed(DEFAULT_GLASS_OPACITY)), ), + wallpaper: AppWallpaper.pipe(Schema.withDecodingDefault(Effect.succeed("none" as const))), + wallpaperBlur: WallpaperBlur.pipe( + Schema.withDecodingDefault(Effect.succeed(DEFAULT_WALLPAPER_BLUR)), + ), + wallpaperDim: WallpaperDim.pipe( + Schema.withDecodingDefault(Effect.succeed(DEFAULT_WALLPAPER_DIM)), + ), fontSizeInterface: InterfaceFontSize.pipe( Schema.withDecodingDefault(Effect.succeed(DEFAULT_INTERFACE_FONT_SIZE)), ), @@ -1452,6 +1474,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 +1926,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), @@ -2062,6 +2088,9 @@ export const ClientSettingsPatch = Schema.Struct({ diffLayout: Schema.optionalKey(DiffLayout), environmentIdentificationMode: Schema.optionalKey(EnvironmentIdentificationMode), glassOpacity: Schema.optionalKey(GlassOpacity), + wallpaper: Schema.optionalKey(AppWallpaper), + wallpaperBlur: Schema.optionalKey(WallpaperBlur), + wallpaperDim: Schema.optionalKey(WallpaperDim), onboardingCompletedAt: Schema.optionalKey(Schema.NullOr(Schema.String)), fontSizeInterface: Schema.optionalKey(InterfaceFontSize), fontSizePrompt: Schema.optionalKey(PromptFontSize), diff --git a/packages/shared/package.json b/packages/shared/package.json index 3de18958220ef..b0b576e1447b4 100644 --- a/packages/shared/package.json +++ b/packages/shared/package.json @@ -579,6 +579,10 @@ "types": "./src/speech.ts", "import": "./src/speech.ts" }, + "./turnTokenUsage": { + "types": "./src/turnTokenUsage.ts", + "import": "./src/turnTokenUsage.ts" + }, "./pinOrderKey": { "types": "./src/pinOrderKey.ts", "import": "./src/pinOrderKey.ts" 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"; +} diff --git a/scripts/build-desktop-artifact.test.ts b/scripts/build-desktop-artifact.test.ts index c9180ec3d3ae6..5ef8687a98f93 100644 --- a/scripts/build-desktop-artifact.test.ts +++ b/scripts/build-desktop-artifact.test.ts @@ -537,6 +537,48 @@ it.layer(NodeServices.layer)("build-desktop-artifact", (it) => { assert.isNull(preview.publish); assert.isNull(previewChannel.publish); + for (const [version, channel] of [ + ["0.1.9", "latest"], + ["0.1.9-fork.20261115.3", "latest"], + ["0.1.9-nightly.20261115.3", "nightly"], + ] as const) { + const mockRelease = yield* createBuildConfig( + "win", + "nsis", + version, + false, + true, + 4567, + undefined, + ).pipe(Effect.provide(ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} })))); + assert.deepStrictEqual(mockRelease.publish, [ + { provider: "generic", url: "http://localhost:4567", channel }, + ]); + } + + 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..117b90eca2637 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; @@ -2820,16 +2820,17 @@ export const createBuildConfig = Effect.fn("createBuildConfig")(function* ( // Missing publish config infers a GitHub feed from tokens; staging has no repository, so manifest generation would crash. buildConfig.publish = null; if (!isDesktopPreviewVersion(version)) { - const publishConfig = yield* resolveGitHubPublishConfig(updateChannel); - if (publishConfig) { - buildConfig.publish = [publishConfig]; - } else if (mockUpdates) { + if (mockUpdates) { buildConfig.publish = [ { provider: "generic", url: resolveMockUpdateServerUrl(mockUpdateServerPort), + channel: updateChannel, }, ]; + } else { + const publishConfig = yield* resolveGitHubPublishConfig(updateChannel); + if (publishConfig) buildConfig.publish = [publishConfig]; } }