From 8fe2b57bf4347554fe0fde14e777f1c4be7a5f07 Mon Sep 17 00:00:00 2001 From: JJ Eaton <58495321+oldbettie@users.noreply.github.com> Date: Tue, 17 Nov 2026 11:55:31 +0800 Subject: [PATCH 1/4] feat(server): idle threads drop old tool output and reasoning to save space Threads nobody has used for 30 days (setting, 0 turns it off) keep their messages, plans, file changes, runs, checkpoints and handoffs, and lose finished tool output and reasoning. A notice marks where detail was removed. Running, pinned, snoozed, open-PR and side-chat threads are skipped. The sweep logs a dry run at start, runs an hour later, then every six hours. Settings > Maintenance has the setting, a preview and "Trim now". Co-Authored-By: Claude Fable 5.2 --- .../SettingsServerControlsRouteScreen.tsx | 1 + .../settings/ThreadSettingsSections.tsx | 37 ++ .../settings/autoSettleSettingsSync.test.ts | 1 + .../settings/autoSettleSettingsSync.ts | 19 +- .../components/AutoSettleDurationField.tsx | 7 + apps/server/src/auth/RpcAuthorization.ts | 1 + .../src/environment/ServerEnvironment.ts | 1 + .../src/observability/RpcInstrumentation.ts | 2 + .../ThreadHistoryTrim.test.ts | 402 +++++++++++++++ .../src/orchestration-v2/ThreadHistoryTrim.ts | 470 ++++++++++++++++++ .../src/orchestration-v2/runtimeLayer.ts | 2 + .../server/src/persistence/DatabaseStorage.ts | 10 +- apps/server/src/ws.test.ts | 2 + apps/server/src/ws.ts | 5 + .../settings/SettingIntegerInput.tsx | 44 ++ .../components/settings/SettingsPanels.tsx | 46 +- .../components/settings/StorageSettings.tsx | 237 ++++++++- .../src/components/settings/settingsSearch.ts | 25 +- .../useAvailableSettingsSearchItems.ts | 4 + docs/user/background-service.md | 18 + packages/client-runtime/src/state/server.ts | 10 + .../contracts/src/clientRpcPermissions.ts | 2 + packages/contracts/src/environment.ts | 2 + packages/contracts/src/rpc.ts | 17 + packages/contracts/src/settings.ts | 22 + 25 files changed, 1336 insertions(+), 51 deletions(-) create mode 100644 apps/server/src/orchestration-v2/ThreadHistoryTrim.test.ts create mode 100644 apps/server/src/orchestration-v2/ThreadHistoryTrim.ts create mode 100644 apps/web/src/components/settings/SettingIntegerInput.tsx diff --git a/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.tsx index 4a6a56e15f375..794f026b16498 100644 --- a/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.tsx +++ b/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.tsx @@ -140,6 +140,7 @@ const AUTO_SETTLE_SETTING_KEYS: ReadonlySet = new Set([ "sidebarAutoSettleAfterDays", "autoSettleFinishedChildrenAfterHours", "autoArchiveSettledAfterDays", + "threadHistoryTrimAfterDays", "autoResumeLimitedThreads", "snoozeLimitedThreads", ]); diff --git a/apps/mobile/src/features/settings/ThreadSettingsSections.tsx b/apps/mobile/src/features/settings/ThreadSettingsSections.tsx index ddaf9c62d231c..a99e7a9955dee 100644 --- a/apps/mobile/src/features/settings/ThreadSettingsSections.tsx +++ b/apps/mobile/src/features/settings/ThreadSettingsSections.tsx @@ -17,6 +17,7 @@ import { DEFAULT_AUTO_ARCHIVE_SETTLED_AFTER_DAYS, DEFAULT_AUTO_SETTLE_FINISHED_CHILDREN_AFTER_HOURS, DEFAULT_SERVER_SETTINGS, + DEFAULT_THREAD_HISTORY_TRIM_AFTER_DAYS, } from "@t3tools/contracts"; import { supportsSharedSettingsSync } from "@t3tools/client-runtime/state/shared-settings"; import { AppText as Text } from "../../components/ui/AppText"; @@ -114,6 +115,12 @@ export function AutoSettleSettingsRows(props: { (target) => target.environment.serverConfig.environment.capabilities.threadAutoArchive === true, ); + const supportsHistoryTrim = + !projectSelected && + displayTargets.every( + (target) => + target.environment.serverConfig.environment.capabilities.threadHistoryTrim === true, + ); const { patch: autoSettlePatch, mismatches } = planAutoSettleSettingsSync( { environmentId: reference.environment.environmentId, @@ -129,6 +136,7 @@ export function AutoSettleSettingsRows(props: { { includeFinishedChildren: supportsFinishedChildAutoSettlement, includeAutoArchive: supportsAutoArchive, + includeHistoryTrim: supportsHistoryTrim, }, ); @@ -138,6 +146,7 @@ export function AutoSettleSettingsRows(props: { const afterDays = referenceSettings.sidebarAutoSettleAfterDays; const childAfterHours = referenceSettings.autoSettleFinishedChildrenAfterHours; const archiveAfterDays = referenceSettings.autoArchiveSettledAfterDays; + const trimAfterDays = referenceSettings.threadHistoryTrimAfterDays; return ( @@ -242,6 +251,34 @@ export function AutoSettleSettingsRows(props: { ) : null} ) : null} + {supportsHistoryTrim ? ( + + 0} + disabled={disabledFor("threadHistoryTrimAfterDays")} + onValueChange={(value) => + writeToAll({ + threadHistoryTrimAfterDays: value ? DEFAULT_THREAD_HISTORY_TRIM_AFTER_DAYS : 0, + }) + } + /> + {trimAfterDays > 0 ? ( + + + Unused days + writeToAll({ threadHistoryTrimAfterDays: value })} + /> + + ) : null} + + ) : null} {!props.pending && mismatches.length > 0 ? ( diff --git a/apps/mobile/src/features/settings/autoSettleSettingsSync.test.ts b/apps/mobile/src/features/settings/autoSettleSettingsSync.test.ts index aa0e1965cd5da..6959d15b25cb1 100644 --- a/apps/mobile/src/features/settings/autoSettleSettingsSync.test.ts +++ b/apps/mobile/src/features/settings/autoSettleSettingsSync.test.ts @@ -86,6 +86,7 @@ describe("auto-settle settings sync", () => { key: "autoSettleFinishedChildrenAfterHours", }, { option: "includeAutoArchive", key: "autoArchiveSettledAfterDays" }, + { option: "includeHistoryTrim", key: "threadHistoryTrimAfterDays" }, ] as const)("syncs $key only when the caller includes it", ({ option, key }) => { const target = { environmentId: EnvironmentId.make("remote"), diff --git a/apps/mobile/src/features/settings/autoSettleSettingsSync.ts b/apps/mobile/src/features/settings/autoSettleSettingsSync.ts index 00cb36026ae5f..e736f77fd499e 100644 --- a/apps/mobile/src/features/settings/autoSettleSettingsSync.ts +++ b/apps/mobile/src/features/settings/autoSettleSettingsSync.ts @@ -5,6 +5,7 @@ export type AutoSettleSettings = Pick< | "sidebarAutoSettleAfterDays" | "autoSettleFinishedChildrenAfterHours" | "autoArchiveSettledAfterDays" + | "threadHistoryTrimAfterDays" >; interface AutoSettleSyncTarget { @@ -21,12 +22,17 @@ export function planAutoSettleSettingsSync( readonly settings: AutoSettleSettings; }, targets: readonly AutoSettleSyncTarget[], - // Child auto-settle and auto-archive are environment-wide and unknown to older servers, so - // callers include them only outside project scope and when every target supports them. + // Child auto-settle, auto-archive and trimming are environment-wide and unknown to older servers, + // so callers include them only outside project scope and when every target supports them. { includeFinishedChildren = false, includeAutoArchive = false, - }: { readonly includeFinishedChildren?: boolean; readonly includeAutoArchive?: boolean } = {}, + includeHistoryTrim = false, + }: { + readonly includeFinishedChildren?: boolean; + readonly includeAutoArchive?: boolean; + readonly includeHistoryTrim?: boolean; + } = {}, ) { const patch: Partial = { sidebarAutoSettleAfterDays: reference.settings.sidebarAutoSettleAfterDays, @@ -39,6 +45,9 @@ export function planAutoSettleSettingsSync( ...(includeAutoArchive ? { autoArchiveSettledAfterDays: reference.settings.autoArchiveSettledAfterDays } : {}), + ...(includeHistoryTrim + ? { threadHistoryTrimAfterDays: reference.settings.threadHistoryTrimAfterDays } + : {}), }; const mismatches = targets.filter( (target) => @@ -50,7 +59,9 @@ export function planAutoSettleSettingsSync( target.settings.autoSettleFinishedChildrenAfterHours !== patch.autoSettleFinishedChildrenAfterHours) || (includeAutoArchive && - target.settings.autoArchiveSettledAfterDays !== patch.autoArchiveSettledAfterDays)), + target.settings.autoArchiveSettledAfterDays !== patch.autoArchiveSettledAfterDays) || + (includeHistoryTrim && + target.settings.threadHistoryTrimAfterDays !== patch.threadHistoryTrimAfterDays)), ); return { patch, mismatches }; } diff --git a/apps/mobile/src/features/settings/components/AutoSettleDurationField.tsx b/apps/mobile/src/features/settings/components/AutoSettleDurationField.tsx index 10b7161bc5002..c335095b4c6b8 100644 --- a/apps/mobile/src/features/settings/components/AutoSettleDurationField.tsx +++ b/apps/mobile/src/features/settings/components/AutoSettleDurationField.tsx @@ -2,6 +2,7 @@ import { MAX_AUTO_ARCHIVE_SETTLED_AFTER_DAYS, MAX_AUTO_SETTLE_FINISHED_CHILDREN_AFTER_HOURS, MAX_SIDEBAR_AUTO_SETTLE_AFTER_DAYS, + MAX_THREAD_HISTORY_TRIM_AFTER_DAYS, MIN_SIDEBAR_AUTO_SETTLE_AFTER_DAYS, } from "@t3tools/contracts"; import type { ComponentProps } from "react"; @@ -28,6 +29,12 @@ const UNITS = { noun: "day", label: "Days settled before a thread is archived", }, + trimDay: { + min: 1, + max: MAX_THREAD_HISTORY_TRIM_AFTER_DAYS, + noun: "day", + label: "Days unused before a thread is trimmed", + }, } as const; export type AutoSettleDurationFieldProps = Pick< diff --git a/apps/server/src/auth/RpcAuthorization.ts b/apps/server/src/auth/RpcAuthorization.ts index c033762c60269..0412abafa6473 100644 --- a/apps/server/src/auth/RpcAuthorization.ts +++ b/apps/server/src/auth/RpcAuthorization.ts @@ -95,6 +95,7 @@ export const RPC_REQUIRED_SCOPES = { [WS_METHODS.serverGetStorageCleanupReport]: AuthOrchestrationReadScope, [WS_METHODS.serverGetDatabaseStorage]: AuthOrchestrationReadScope, [WS_METHODS.serverGetSettings]: AuthOrchestrationReadScope, + [WS_METHODS.serverPreviewThreadHistoryTrim]: AuthOrchestrationReadScope, [WS_METHODS.peerLinksList]: AuthAccessReadScope, [WS_METHODS.serverGetAgentGateway]: AuthAccessReadScope, [WS_METHODS.tailnetDevicesList]: AuthAccessReadScope, diff --git a/apps/server/src/environment/ServerEnvironment.ts b/apps/server/src/environment/ServerEnvironment.ts index d97edd0895174..2674403749071 100644 --- a/apps/server/src/environment/ServerEnvironment.ts +++ b/apps/server/src/environment/ServerEnvironment.ts @@ -266,6 +266,7 @@ export const make = Effect.gen(function* () { threadAutoSettleOptOut: true, threadAutoSettleFinishedChildren: true, threadAutoArchive: true, + threadHistoryTrim: true, threadProjectFromScratch: true, threadTitleRegeneration: true, commandOutputStreaming: true, diff --git a/apps/server/src/observability/RpcInstrumentation.ts b/apps/server/src/observability/RpcInstrumentation.ts index 158b5e521064c..8bc68bc6bbfb0 100644 --- a/apps/server/src/observability/RpcInstrumentation.ts +++ b/apps/server/src/observability/RpcInstrumentation.ts @@ -66,6 +66,8 @@ const RPC_AGGREGATES = { [WS_METHODS.serverGetStorageCleanupReport]: "server", [WS_METHODS.serverGetDatabaseStorage]: "server", [WS_METHODS.serverReclaimDatabaseSpace]: "server", + [WS_METHODS.serverPreviewThreadHistoryTrim]: "server", + [WS_METHODS.serverTrimThreadHistory]: "server", [WS_METHODS.serverGetAgentGateway]: "server", [WS_METHODS.serverUpdateAgentGateway]: "server", [WS_METHODS.serverRevealAgentGatewayToken]: "server", diff --git a/apps/server/src/orchestration-v2/ThreadHistoryTrim.test.ts b/apps/server/src/orchestration-v2/ThreadHistoryTrim.test.ts new file mode 100644 index 0000000000000..91eace2ca2f2b --- /dev/null +++ b/apps/server/src/orchestration-v2/ThreadHistoryTrim.test.ts @@ -0,0 +1,402 @@ +import { assert, it } from "@effect/vitest"; +import { + EventId, + MessageId, + NodeId, + type OrchestrationV2AppThread, + type OrchestrationV2DomainEvent, + type OrchestrationV2Run, + type OrchestrationV2TurnItem, + ProjectId, + ProviderInstanceId, + RunId, + ThreadId, + TurnItemId, +} from "@t3tools/contracts"; +import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as TestClock from "effect/testing/TestClock"; +import * as SqlClient from "effect/sql/SqlClient"; + +import * as OrchestrationEventStore from "../persistence/OrchestrationEventStore.ts"; +import * as SqlitePersistence from "../persistence/Sqlite.ts"; +import * as ServerSettings from "../serverSettings.ts"; +import * as EventSink from "./EventSink.ts"; +import * as EventStore from "./EventStore.ts"; +import * as ProjectionStore from "./ProjectionStore.ts"; +import * as ThreadHistoryTrim from "./ThreadHistoryTrim.ts"; + +const database = SqlitePersistence.layerMemory; +const stores = Layer.mergeAll( + database, + EventStore.layer.pipe(Layer.provideMerge(database)), + ProjectionStore.layer.pipe(Layer.provideMerge(database)), +); +const layerTest = (afterDays: number) => + ThreadHistoryTrim.layer.pipe( + Layer.provideMerge( + Layer.mergeAll( + stores, + OrchestrationEventStore.layer.pipe(Layer.provide(database)), + EventSink.layer.pipe(Layer.provide(stores)), + IdAllocator.layer, + ServerSettings.ServerSettingsService.layerTest({ threadHistoryTrimAfterDays: afterDays }), + ), + ), + ); + +const now = DateTime.makeUnsafe("2026-11-17T00:00:00.000Z"); +const old = DateTime.subtract(now, { days: 40 }); +const recent = DateTime.subtract(now, { days: 3 }); +const providerInstanceId = ProviderInstanceId.make("codex"); +const modelSelection = { instanceId: providerInstanceId, model: "test-model" }; + +type SeedOptions = { + readonly thread?: Partial; + readonly runStatus?: OrchestrationV2Run["status"]; + readonly userMessageAt?: DateTime.Utc; +}; + +const seedThread = Effect.fn(function* (name: string, options: SeedOptions = {}) { + const eventSink = yield* EventSink.EventSinkV2; + const threadId = ThreadId.make(`thread:trim:${name}`); + const runId = RunId.make(`run:${threadId}:1`); + const runStatus = options.runStatus ?? "completed"; + const userMessageAt = options.userMessageAt ?? old; + const rootNodeId = NodeId.make(`node:${name}:root`); + const commandNodeId = NodeId.make(`node:${name}:command`); + const editNodeId = NodeId.make(`node:${name}:edit`); + const userMessageId = MessageId.make(`message:${name}:user`); + const assistantMessageId = MessageId.make(`message:${name}:assistant`); + let sequence = 0; + const event = ( + input: Omit, + ) => + ({ + id: EventId.make(`event:${name}:${sequence++}`), + threadId, + occurredAt: old, + ...input, + }) as OrchestrationV2DomainEvent; + const node = (id: NodeId, kind: "root_turn" | "tool_call", parentNodeId: NodeId | null) => + event({ + type: "node.updated", + runId, + nodeId: id, + payload: { + id, + threadId, + runId, + rootNodeId, + parentNodeId, + kind, + status: runStatus === "completed" ? "completed" : "running", + countsForRun: kind === "root_turn", + providerThreadId: null, + providerTurnId: null, + nativeItemRef: null, + runtimeRequestId: null, + checkpointScopeId: null, + startedAt: old, + completedAt: runStatus === "completed" ? old : null, + }, + }); + const itemBase = (key: string, nodeId: NodeId | null = null, parent: string | null = null) => ({ + id: TurnItemId.make(`item:${name}:${key}`), + threadId, + runId, + nodeId, + providerThreadId: null, + providerTurnId: null, + nativeItemRef: null, + parentItemId: parent === null ? null : TurnItemId.make(`item:${name}:${parent}`), + ordinal: 0, + status: "completed" as const, + title: key, + startedAt: old, + completedAt: old, + updatedAt: old, + }); + const item = (payload: OrchestrationV2TurnItem) => + event({ type: "turn-item.updated", runId, payload }); + const thread: OrchestrationV2AppThread = { + createdBy: "user", + creationSource: "web", + id: threadId, + projectId: ProjectId.make("project:trim"), + title: name, + providerInstanceId, + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + activeProviderThreadId: null, + lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId }, + forkedFrom: null, + createdAt: old, + updatedAt: old, + archivedAt: null, + settledOverride: null, + settledAt: null, + lastVisitedAt: null, + deletedAt: null, + ...options.thread, + }; + yield* eventSink.write({ + events: [ + event({ type: "thread.created", payload: thread }), + event({ + type: "run.created", + runId, + payload: { + id: runId, + threadId, + ordinal: 1, + providerInstanceId, + modelSelection, + providerThreadId: null, + userMessageId, + rootNodeId, + activeAttemptId: null, + status: runStatus, + requestedAt: old, + startedAt: old, + completedAt: runStatus === "completed" ? old : null, + checkpointId: null, + contextHandoffId: null, + }, + }), + node(rootNodeId, "root_turn", null), + node(commandNodeId, "tool_call", rootNodeId), + node(editNodeId, "tool_call", rootNodeId), + event({ + type: "message.updated", + runId, + payload: { + id: userMessageId, + threadId, + runId, + nodeId: null, + role: "user", + text: `please fix the flaky ${name} harness`, + attachments: [], + streaming: false, + createdBy: "user", + creationSource: "web", + createdAt: userMessageAt, + updatedAt: userMessageAt, + }, + }), + item({ + ...itemBase("user"), + type: "user_message", + createdBy: "user", + creationSource: "web", + messageId: userMessageId, + inputIntent: "turn_start", + text: `please fix the flaky ${name} harness`, + attachments: [], + }), + item({ ...itemBase("reasoning"), type: "reasoning", text: "thinking", streaming: false }), + item({ + ...itemBase("command", commandNodeId), + type: "command_execution", + input: "vp test", + output: "x".repeat(4_000), + }), + item({ + ...itemBase("tool"), + type: "dynamic_tool", + toolName: "Edit", + input: null, + output: "y".repeat(4_000), + }), + item({ + ...itemBase("edit", editNodeId, "tool"), + type: "file_change", + fileName: "harness.ts", + }), + item({ + ...itemBase("assistant"), + type: "assistant_message", + messageId: assistantMessageId, + text: "Fixed the harness.", + streaming: false, + }), + ], + }); + return { threadId, runId }; +}); + +const itemTitles = Effect.fn(function* (threadId: ThreadId) { + const sql = yield* SqlClient.SqlClient; + const rows = yield* sql<{ readonly title: string }>` + SELECT json_extract(payload_json, '$.title') AS title + FROM orchestration_v2_projection_turn_items + WHERE thread_id = ${threadId} + ORDER BY ordinal ASC + `; + return rows.map((row) => row.title); +}); + +const everyItem = ["user", "reasoning", "command", "tool", "edit", "assistant"]; +const trimmedItems = ["user", "tool", "edit", "assistant", "Older detail was trimmed"]; + +const trim = Effect.gen(function* () { + const service = yield* ThreadHistoryTrim.ThreadHistoryTrim; + const report = yield* service.trimNow; + yield* service.drain; + return report; +}); + +it.layer(layerTest(30))("ThreadHistoryTrim", (it) => { + it.effect("drops tool output and reasoning, and keeps what reading and resuming use", () => + Effect.gen(function* () { + yield* TestClock.setTime(DateTime.toEpochMillis(now)); + const sql = yield* SqlClient.SqlClient; + const store = yield* ProjectionStore.ProjectionStoreV2; + const service = yield* ThreadHistoryTrim.ThreadHistoryTrim; + const { threadId } = yield* seedThread("idle"); + + const preview = yield* service.preview; + assert.deepEqual( + { dryRun: preview.dryRun, threadCount: preview.threadCount, itemCount: preview.itemCount }, + { dryRun: true, threadCount: 1, itemCount: 3 }, + ); + assert.isAbove(preview.estimatedBytes, 8_000); + assert.deepEqual(yield* itemTitles(threadId), everyItem); + + const report = yield* trim; + assert.equal(report.dryRun, false); + // `tool` stays: the kept file change hangs off it. + assert.deepEqual(yield* itemTitles(threadId), trimmedItems); + const nodes = yield* sql<{ readonly node_id: string }>` + SELECT node_id FROM orchestration_v2_projection_nodes + WHERE thread_id = ${threadId} ORDER BY node_id ASC + `; + assert.deepEqual( + nodes.map((row) => row.node_id), + ["node:idle:edit", "node:idle:root"], + ); + const positions = yield* sql<{ readonly count: number }>` + SELECT COUNT(*) AS count FROM orchestration_v2_turn_item_positions + WHERE thread_id = ${threadId} + `; + assert.equal(positions[0]?.count, trimmedItems.length); + + const { projection } = yield* store.getThreadSnapshot(threadId); + assert.equal(DateTime.formatIso(projection.thread.updatedAt), DateTime.formatIso(old)); + const notice = projection.turnItems.at(-1); + assert.equal(notice?.type, "system_notice"); + assert.include( + notice?.type === "system_notice" ? notice.message : "", + "removed to save space after 30 days", + ); + const history = yield* store.getTurnStartHistory(threadId); + assert.deepEqual( + history.map((entry) => entry.type), + ["user_message", "file_change", "assistant_message"], + ); + const found = yield* sql<{ readonly count: number }>` + SELECT COUNT(*) AS count FROM orchestration_v2_message_search + WHERE orchestration_v2_message_search MATCH 'flaky idle harness' + `; + assert.equal(found[0]?.count, 1); + + assert.equal((yield* trim).threadCount, 0); + assert.deepEqual(yield* itemTitles(threadId), trimmedItems); + }), + ); + + it.effect("leaves threads that are in use, pinned, snoozed, or waiting on a pull request", () => + Effect.gen(function* () { + yield* TestClock.setTime(DateTime.toEpochMillis(now)); + const root = yield* seedThread("live-root", { userMessageAt: recent }); + const kept = [ + root, + yield* seedThread("recent-message", { userMessageAt: recent }), + yield* seedThread("visited", { thread: { lastVisitedAt: recent } }), + yield* seedThread("running", { runStatus: "running" }), + yield* seedThread("pinned", { thread: { pinnedAt: old } }), + yield* seedThread("snoozed", { + thread: { snoozedAt: old, snoozedUntil: DateTime.add(now, { days: 1 }) }, + }), + yield* seedThread("open-pr", { + thread: { + pullRequests: [ + { + host: "github.com", + repository: "acme/app", + number: 7, + url: "https://github.com/acme/app/pull/7", + source: "agent", + linkedAt: DateTime.formatIso(old), + snapshot: { + state: "open", + title: "Fix harness", + headBranch: "fix", + baseBranch: "main", + isDraft: false, + updatedAt: null, + syncedAt: DateTime.formatIso(old), + }, + stack: null, + }, + ], + }, + }), + yield* seedThread("side-chat", { + thread: { + lineage: { + parentThreadId: root.threadId, + relationshipToParent: "fork", + rootThreadId: root.threadId, + sideChat: true, + }, + }, + }), + yield* seedThread("subagent-of-live-root", { + thread: { + lineage: { + parentThreadId: root.threadId, + relationshipToParent: "subagent", + rootThreadId: root.threadId, + }, + }, + }), + ]; + const idleRoot = yield* seedThread("idle-root"); + const idleSubagent = yield* seedThread("subagent-of-idle-root", { + thread: { + lineage: { + parentThreadId: idleRoot.threadId, + relationshipToParent: "subagent", + rootThreadId: idleRoot.threadId, + }, + }, + }); + + const report = yield* trim; + for (const thread of kept) { + assert.deepEqual(yield* itemTitles(thread.threadId), everyItem, thread.threadId); + } + assert.equal(report.threadCount, 2); + assert.deepEqual(yield* itemTitles(idleRoot.threadId), trimmedItems); + assert.deepEqual(yield* itemTitles(idleSubagent.threadId), trimmedItems); + }), + ); +}); + +it.layer(layerTest(0))("ThreadHistoryTrim turned off", (it) => { + it.effect("removes nothing", () => + Effect.gen(function* () { + yield* TestClock.setTime(DateTime.toEpochMillis(now)); + const { threadId } = yield* seedThread("off"); + assert.equal((yield* trim).threadCount, 0); + assert.deepEqual(yield* itemTitles(threadId), everyItem); + }), + ); +}); diff --git a/apps/server/src/orchestration-v2/ThreadHistoryTrim.ts b/apps/server/src/orchestration-v2/ThreadHistoryTrim.ts new file mode 100644 index 0000000000000..f64de5f21603d --- /dev/null +++ b/apps/server/src/orchestration-v2/ThreadHistoryTrim.ts @@ -0,0 +1,470 @@ +import { type RunId, type ThreadHistoryTrimReport, type ThreadId } from "@t3tools/contracts"; +import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; +import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker"; +import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient"; +import * as Cause from "effect/Cause"; +import * as Clock from "effect/Clock"; +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 Schedule from "effect/Schedule"; +import * as Schema from "effect/Schema"; +import * as SqlClient from "effect/sql/SqlClient"; + +import * as ServerSettingsModule from "../serverSettings.ts"; +import { forkParked } from "../serverActivation.ts"; +import * as EventSink from "./EventSink.ts"; + +export class ThreadHistoryTrimError extends Schema.TaggedError()( + "ThreadHistoryTrimError", + { + operation: Schema.String, + cause: Schema.optional(Schema.Defect()), + }, +) {} + +export class ThreadHistoryTrim extends Context.Service< + ThreadHistoryTrim, + { + /** What the next pass would remove under the current setting. Changes nothing. */ + readonly preview: Effect.Effect; + /** Queues a pass and returns what it is about to remove. */ + readonly trimNow: Effect.Effect; + readonly drain: Effect.Effect; + } +>()("t3/orchestration-v2/ThreadHistoryTrim") {} + +const DAY_MS = 24 * 60 * 60 * 1_000; +const DELETE_PAGE_SIZE = 200; +const NOTICE_SIGNAL = "history-trim"; +// Work the reader skips: `file_change` stays because it is small and names what a run touched. +const TRIMMED_ITEM_TYPES = [ + "command_execution", + "dynamic_tool", + "reasoning", + "file_search", + "web_search", +] as const; +const TRIMMED_NODE_KINDS = ["tool_call", "reasoning"] as const; +const LIVE_ITEM_STATUSES = ["pending", "running", "waiting"] as const; +const LIVE_NODE_STATUSES = ["pending", "starting", "running", "waiting"] as const; +const LIVE_RUN_STATUSES = ["queued", "preparing", "starting", "running", "waiting"] as const; + +type Candidate = { + readonly threadId: ThreadId; + readonly runId: RunId; + readonly runOrdinal: number; + readonly updatedAt: string; +}; +type Mode = "background" | "manual"; +type Removed = { readonly itemCount: number; readonly bytes: number }; + +function trimNoticeMessage(afterDays: number): string { + return `Tool output and reasoning above this point were removed to save space after ${afterDays} ${afterDays === 1 ? "day" : "days"} without use. Messages, plans and file changes are kept.`; +} + +/** Ids no kept row points at, following `parent` links so a kept row never loses an ancestor. */ +function unreferenced( + rows: ReadonlyArray, + removable: (row: Row) => boolean, + referenced: Iterable, +): ReadonlyArray { + const byId = new Map(rows.map((row) => [row.id, row])); + const kept = new Set(); + const keep = (id: string | null) => { + for (let current = id; current !== null && !kept.has(current);) { + kept.add(current); + current = byId.get(current)?.parent ?? null; + } + }; + for (const id of referenced) keep(id); + for (const row of rows) if (!removable(row)) keep(row.id); + return rows.filter((row) => !kept.has(row.id)); +} + +const make = Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + const eventSink = yield* EventSink.EventSinkV2; + const ids = yield* IdAllocator.IdAllocatorV2; + const settingsService = yield* ServerSettingsModule.ServerSettingsService; + + // A subagent has no user of its own, so it ages with the thread that started it. + const readCandidates = (input: { + readonly idleBefore: string; + readonly now: string; + readonly threadId?: ThreadId; + }) => sql` + SELECT + thread.thread_id AS "threadId", + run.run_id AS "runId", + run.ordinal AS "runOrdinal", + thread.updated_at AS "updatedAt" + FROM orchestration_v2_projection_threads AS thread + JOIN orchestration_v2_projection_threads AS anchor ON anchor.thread_id = CASE + WHEN json_extract(thread.payload_json, '$.lineage.relationshipToParent') = 'subagent' + THEN COALESCE(json_extract(thread.payload_json, '$.lineage.rootThreadId'), thread.thread_id) + ELSE thread.thread_id + END + JOIN orchestration_v2_projection_runs AS run ON run.run_id = ( + SELECT latest.run_id FROM orchestration_v2_projection_runs AS latest + WHERE latest.thread_id = thread.thread_id + ORDER BY latest.ordinal DESC LIMIT 1 + ) + WHERE ${input.threadId === undefined ? sql`1` : sql`thread.thread_id = ${input.threadId}`} + AND thread.deleted_at IS NULL + -- Restoring a shared worktree reads a side chat's tool items to learn whether it wrote there. + AND COALESCE(json_extract(thread.payload_json, '$.lineage.sideChat'), 0) = 0 + AND anchor.created_at < ${input.idleBefore} + AND COALESCE(json_extract(anchor.payload_json, '$.lastVisitedAt'), '') < ${input.idleBefore} + AND json_extract(anchor.payload_json, '$.pinnedAt') IS NULL + AND COALESCE(json_extract(anchor.payload_json, '$.snoozedUntil'), '') <= ${input.now} + AND NOT EXISTS ( + SELECT 1 FROM json_each(anchor.payload_json, '$.pullRequests') AS link + WHERE json_extract(link.value, '$.snapshot.state') = 'open' + AND json_extract(link.value, '$.source') <> 'stack-dismissed' + ) + AND NOT EXISTS ( + SELECT 1 FROM orchestration_v2_projection_messages AS message + WHERE message.thread_id = anchor.thread_id + AND message.role = 'user' + AND message.updated_at >= ${input.idleBefore} + ) + AND NOT EXISTS ( + SELECT 1 FROM orchestration_v2_projection_runs AS recent + WHERE recent.thread_id IN (thread.thread_id, anchor.thread_id) + AND ( + recent.status IN ${sql.in(LIVE_RUN_STATUSES)} + OR recent.requested_at >= ${input.idleBefore} + OR COALESCE(recent.completed_at, '') >= ${input.idleBefore} + ) + ) + AND EXISTS ( + SELECT 1 FROM orchestration_v2_projection_turn_items AS item + WHERE item.thread_id = thread.thread_id + AND item.type IN ${sql.in(TRIMMED_ITEM_TYPES)} + AND item.status NOT IN ${sql.in(LIVE_ITEM_STATUSES)} + -- A trimmed thread keeps the tool items its kept items hang off. + AND NOT EXISTS ( + SELECT 1 FROM orchestration_v2_projection_turn_items AS child + WHERE child.thread_id = item.thread_id AND child.parent_item_id = item.turn_item_id + ) + ) + ORDER BY thread.thread_id ASC + `; + + const window = Effect.gen(function* () { + const afterDays = (yield* settingsService.getSettings).threadHistoryTrimAfterDays; + const nowMs = yield* Clock.currentTimeMillis; + return { + afterDays, + now: DateTime.formatIso(DateTime.makeUnsafe(nowMs)), + idleBefore: DateTime.formatIso(DateTime.makeUnsafe(nowMs - afterDays * DAY_MS)), + }; + }); + + const estimate = Effect.fn("ThreadHistoryTrim.estimate")(function* (dryRun: boolean) { + const { afterDays, now, idleBefore } = yield* window; + const candidates = afterDays <= 0 ? [] : yield* readCandidates({ idleBefore, now }); + let itemCount = 0; + let estimatedBytes = 0; + for (const candidate of candidates) { + const rows = yield* sql<{ readonly items: number; readonly bytes: number }>` + SELECT + (SELECT COUNT(*) FROM orchestration_v2_projection_turn_items + WHERE thread_id = ${candidate.threadId} + AND type IN ${sql.in(TRIMMED_ITEM_TYPES)} + AND status NOT IN ${sql.in(LIVE_ITEM_STATUSES)}) AS items, + COALESCE((SELECT SUM(octet_length(payload_json)) FROM orchestration_v2_projection_turn_items + WHERE thread_id = ${candidate.threadId} + AND type IN ${sql.in(TRIMMED_ITEM_TYPES)} + AND status NOT IN ${sql.in(LIVE_ITEM_STATUSES)}), 0) + + COALESCE((SELECT SUM(octet_length(payload_json)) FROM orchestration_v2_projection_nodes + WHERE thread_id = ${candidate.threadId} + AND kind IN ${sql.in(TRIMMED_NODE_KINDS)} + AND status NOT IN ${sql.in(LIVE_NODE_STATUSES)}), 0) AS bytes + `; + itemCount += rows[0]?.items ?? 0; + estimatedBytes += rows[0]?.bytes ?? 0; + yield* Effect.yieldNow; + } + return { + dryRun, + afterDays, + threadCount: candidates.length, + itemCount, + estimatedBytes, + } satisfies ThreadHistoryTrimReport; + }); + + const writeNotice = Effect.fn("ThreadHistoryTrim.writeNotice")(function* ( + candidate: Candidate, + afterDays: number, + ) { + const now = yield* DateTime.now; + yield* eventSink.write({ + events: [ + { + id: yield* ids.allocate.event({ threadId: candidate.threadId }), + type: "turn-item.updated", + threadId: candidate.threadId, + runId: candidate.runId, + // Every event stamps the thread with its time; reusing the thread's own keeps a trimmed + // thread where it was in lists sorted by activity. + occurredAt: DateTime.makeUnsafe(candidate.updatedAt), + payload: { + id: ids.derive.runSignalTurnItem({ runId: candidate.runId, signal: NOTICE_SIGNAL }), + threadId: candidate.threadId, + runId: candidate.runId, + nodeId: null, + providerThreadId: null, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + // EventSink allocates the real position, after the run's existing items. + ordinal: 0, + status: "completed", + title: "Older detail was trimmed", + startedAt: now, + completedAt: now, + updatedAt: now, + type: "system_notice", + message: trimNoticeMessage(afterDays), + }, + }, + ], + }); + }); + + const deleteInPages = Effect.fnUntraced(function* ( + rowIds: ReadonlyArray, + deletePage: (page: ReadonlyArray) => Effect.Effect, + rest: Effect.Effect, + ) { + for (let offset = 0; offset < rowIds.length; offset += DELETE_PAGE_SIZE) { + yield* deletePage(rowIds.slice(offset, offset + DELETE_PAGE_SIZE)); + // Never hold the writer across a rest: foreground commits run between pages. + yield* rest; + } + }); + + const trimThread = Effect.fn("ThreadHistoryTrim.trimThread")(function* ( + candidate: Candidate, + afterDays: number, + rest: Effect.Effect, + ) { + const { threadId } = candidate; + const noticeId = ids.derive.runSignalTurnItem({ + runId: candidate.runId, + signal: NOTICE_SIGNAL, + }); + const readBoundary = sql<{ readonly ordinal: number }>` + SELECT ordinal FROM orchestration_v2_projection_turn_items WHERE turn_item_id = ${noticeId} + `; + // The notice goes first: a pass that stops halfway leaves a marked thread the next pass finishes. + if ((yield* readBoundary)[0] === undefined) yield* writeNotice(candidate, afterDays); + const boundary = (yield* readBoundary)[0]?.ordinal; + if (boundary === undefined) return { itemCount: 0, bytes: 0 } satisfies Removed; + + const items = yield* sql<{ + readonly id: string; + readonly parent: string | null; + readonly type: string; + readonly status: string; + readonly bytes: number; + }>` + SELECT + turn_item_id AS id, + parent_item_id AS parent, + type, + status, + octet_length(payload_json) AS bytes + FROM orchestration_v2_projection_turn_items + WHERE thread_id = ${threadId} AND ordinal < ${boundary} + `.pipe(NodeSqliteClient.readOnlyBackground); + const trimmedItemTypes: ReadonlyArray = TRIMMED_ITEM_TYPES; + const liveItemStatuses: ReadonlyArray = LIVE_ITEM_STATUSES; + const removedItems = unreferenced( + items, + (item) => trimmedItemTypes.includes(item.type) && !liveItemStatuses.includes(item.status), + [], + ); + yield* deleteInPages( + removedItems.map((item) => item.id), + (page) => + sql.withTransaction( + Effect.gen(function* () { + yield* sql` + DELETE FROM orchestration_v2_projection_turn_items + WHERE turn_item_id IN ${sql.in(page)} + AND status NOT IN ${sql.in(LIVE_ITEM_STATUSES)} + `; + yield* sql` + DELETE FROM orchestration_v2_turn_item_positions + WHERE thread_id = ${threadId} AND turn_item_id IN ${sql.in(page)} + `; + }), + ), + rest, + ); + + const nodes = yield* sql<{ + readonly id: string; + readonly parent: string | null; + readonly kind: string; + readonly status: string; + readonly settled: number; + readonly bytes: number; + }>` + SELECT + node.node_id AS id, + node.parent_node_id AS parent, + node.kind, + node.status, + COALESCE(run.ordinal <= ${candidate.runOrdinal}, 0) AS settled, + octet_length(node.payload_json) AS bytes + FROM orchestration_v2_projection_nodes AS node + LEFT JOIN orchestration_v2_projection_runs AS run ON run.run_id = node.run_id + WHERE node.thread_id = ${threadId} + `.pipe(NodeSqliteClient.readOnlyBackground); + const referencedNodes = yield* sql<{ readonly id: string }>` + SELECT node_id AS id FROM orchestration_v2_projection_turn_items + WHERE thread_id = ${threadId} AND node_id IS NOT NULL + UNION SELECT node_id FROM orchestration_v2_projection_messages + WHERE thread_id = ${threadId} AND node_id IS NOT NULL + UNION SELECT node_id FROM orchestration_v2_projection_plans + WHERE thread_id = ${threadId} AND node_id IS NOT NULL + UNION SELECT parent_node_id FROM orchestration_v2_projection_subagents + WHERE thread_id = ${threadId} + UNION SELECT node_id FROM orchestration_v2_projection_runtime_requests + WHERE thread_id = ${threadId} AND node_id IS NOT NULL + UNION SELECT node_id FROM orchestration_v2_projection_checkpoints + WHERE thread_id = ${threadId} + UNION SELECT node_id FROM orchestration_v2_projection_checkpoint_scopes + WHERE thread_id = ${threadId} AND node_id IS NOT NULL + UNION SELECT node_id FROM orchestration_v2_projection_provider_turns + WHERE thread_id = ${threadId} + UNION SELECT root_node_id FROM orchestration_v2_projection_run_attempts + WHERE thread_id = ${threadId} AND root_node_id IS NOT NULL + UNION SELECT owner_node_id FROM orchestration_v2_projection_provider_threads + WHERE thread_id = ${threadId} AND owner_node_id IS NOT NULL + `.pipe(NodeSqliteClient.readOnlyBackground); + const trimmedNodeKinds: ReadonlyArray = TRIMMED_NODE_KINDS; + const liveNodeStatuses: ReadonlyArray = LIVE_NODE_STATUSES; + const removedNodes = unreferenced( + nodes, + (node) => + node.settled === 1 && + trimmedNodeKinds.includes(node.kind) && + !liveNodeStatuses.includes(node.status), + referencedNodes.map((row) => row.id), + ); + yield* deleteInPages( + removedNodes.map((node) => node.id), + (page) => sql` + DELETE FROM orchestration_v2_projection_nodes + WHERE node_id IN ${sql.in(page)} AND status NOT IN ${sql.in(LIVE_NODE_STATUSES)} + `, + rest, + ); + + const bytes = (rows: ReadonlyArray<{ readonly bytes: number }>) => + rows.reduce((total, row) => total + row.bytes, 0); + return { + itemCount: removedItems.length, + bytes: bytes(removedItems) + bytes(removedNodes), + } satisfies Removed; + }); + + const pass = Effect.fn("ThreadHistoryTrim.pass")(function* (mode: Mode) { + const { afterDays, now, idleBefore } = yield* window; + if (afterDays <= 0) return; + let sliceStarted = yield* Clock.currentTimeMillis; + // The sweep keeps to a 10% duty so a backlog never competes with a turn; a requested trim does not wait. + const rest = + mode === "manual" + ? Effect.yieldNow + : Effect.gen(function* () { + const elapsed = (yield* Clock.currentTimeMillis) - sliceStarted; + if (elapsed <= 0) return; + yield* Effect.sleep(elapsed * 9); + sliceStarted = yield* Clock.currentTimeMillis; + }); + const candidates = yield* readCandidates({ idleBefore, now }).pipe( + NodeSqliteClient.readOnlyBackground, + ); + let threadCount = 0; + let itemCount = 0; + let estimatedBytes = 0; + for (const listed of candidates) { + // A long pass outlives its list: a thread used since is no longer one. + const current = yield* readCandidates({ idleBefore, now, threadId: listed.threadId }); + const candidate = current[0]; + if (candidate === undefined) continue; + const removed = yield* trimThread(candidate, afterDays, rest).pipe( + Effect.catchCauseIf( + (cause) => !Cause.hasInterruptsOnly(cause), + (cause) => + Effect.logWarning("Trimming a thread's history failed", { + threadId: candidate.threadId, + cause: Cause.pretty(cause), + }).pipe(Effect.as(null)), + ), + ); + if (removed === null) continue; + threadCount += 1; + itemCount += removed.itemCount; + estimatedBytes += removed.bytes; + } + if (threadCount > 0) { + yield* Effect.logInfo("Trimmed idle thread history", { + mode, + afterDays, + threadCount, + itemCount, + estimatedBytes, + }); + } + }); + + const worker = yield* makeDrainableWorker((mode: Mode) => pass(mode)); + + const mapError = + (operation: string) => + (effect: Effect.Effect) => + effect.pipe(Effect.mapError((cause) => new ThreadHistoryTrimError({ operation, cause }))); + + // Dry run first: the first pass after a start reports what it would remove, and removes it an + // hour later, so an upgrade never deletes history before the setting can be seen. + yield* forkParked( + estimate(true).pipe( + NodeSqliteClient.readOnlyBackground, + Effect.tap((report) => + report.threadCount > 0 + ? Effect.logInfo("Idle thread history due for trimming", report) + : Effect.void, + ), + Effect.catchCause((cause) => + Effect.logWarning("Thread history trim preview failed", { cause: Cause.pretty(cause) }), + ), + Effect.andThen(Effect.sleep("1 hour")), + Effect.andThen( + worker + .enqueue("background") + .pipe(Effect.andThen(worker.drain), Effect.repeat(Schedule.spaced("6 hours"))), + ), + ), + ); + + return ThreadHistoryTrim.of({ + preview: estimate(true).pipe(NodeSqliteClient.readOnlyBackground, mapError("preview")), + trimNow: estimate(false).pipe( + NodeSqliteClient.readOnlyBackground, + Effect.tap(() => worker.enqueue("manual")), + mapError("trim"), + ), + drain: worker.drain, + }); +}); + +export const layer = Layer.effect(ThreadHistoryTrim, make); diff --git a/apps/server/src/orchestration-v2/runtimeLayer.ts b/apps/server/src/orchestration-v2/runtimeLayer.ts index 0618fffbe6a58..9ac19ddfd4041 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.ts @@ -56,6 +56,7 @@ import * as ResourceCleanupService from "./ResourceCleanupService.ts"; import * as RuntimePolicy from "./RuntimePolicy.ts"; import * as RuntimeRequestService from "./RuntimeRequestService.ts"; import * as ThreadManagementService from "./ThreadManagementService.ts"; +import * as ThreadHistoryTrim from "./ThreadHistoryTrim.ts"; import * as ThreadLaunchService from "./ThreadLaunchService.ts"; import * as ThreadForkService from "./ThreadForkService.ts"; import * as TurnItemPositionStore from "./TurnItemPositionStore.ts"; @@ -439,6 +440,7 @@ export const layerProduction = Layer.mergeAll( layerAgentSessionScannerProvided, layerAgentSessionImporterProvided, EffectOutbox.layerPruneWorker.pipe(Layer.provide(EffectOutbox.layer)), + ThreadHistoryTrim.layer.pipe(Layer.provide(Layer.merge(layerEventSink, IdAllocator.layer))), RemoteParentSettlement.layer.pipe( Layer.provide(Layer.mergeAll(ProjectionStore.layer, layerEventSink, layerOrchestratorProvided)), ), diff --git a/apps/server/src/persistence/DatabaseStorage.ts b/apps/server/src/persistence/DatabaseStorage.ts index f82c1b439bb75..2402d19f3f2fe 100644 --- a/apps/server/src/persistence/DatabaseStorage.ts +++ b/apps/server/src/persistence/DatabaseStorage.ts @@ -187,7 +187,15 @@ const make = Effect.gen(function* () { publishStatus.pipe( Effect.andThen(Effect.sleep("1 minute")), Effect.andThen( - reclaim.pipe(Effect.andThen(publishStatus), Effect.repeat(Schedule.spaced("1 minute"))), + reclaim.pipe( + Effect.andThen(publishStatus), + Effect.andThen(readPages), + // A pass that leaves pages behind has a backlog, as a history trim does; drain it in minutes. + Effect.map((pages) => pages.incrementalVacuum && pages.reclaimableBytes > 0), + Effect.orElseSucceed(() => false), + Effect.flatMap((backlog) => Effect.sleep(backlog ? "5 seconds" : "1 minute")), + Effect.forever, + ), ), ), ); diff --git a/apps/server/src/ws.test.ts b/apps/server/src/ws.test.ts index d43882d878048..1c37de19c34a9 100644 --- a/apps/server/src/ws.test.ts +++ b/apps/server/src/ws.test.ts @@ -134,6 +134,7 @@ import * as SourceControlRepositoryService from "./sourceControl/SourceControlRe import * as SourceControlSignIn from "./sourceControl/SourceControlSignIn.ts"; import * as StorageCleanup from "./storageCleanup.ts"; import * as DatabaseStorage from "./persistence/DatabaseStorage.ts"; +import * as ThreadHistoryTrim from "./orchestration-v2/ThreadHistoryTrim.ts"; import * as HeadlessGatewayHost from "./mcp/agents/HeadlessGatewayHost.ts"; import * as TerminalManager from "./terminal/Manager.ts"; import * as ThreadLaunchService from "./orchestration-v2/ThreadLaunchService.ts"; @@ -883,6 +884,7 @@ const layerUnusedConfigRpcServices = Layer.mergeAll( Layer.mock(SourceControlSignIn.SourceControlSignIn)({}), Layer.mock(StorageCleanup.StorageCleanup)({}), Layer.mock(DatabaseStorage.DatabaseStorage)({}), + Layer.mock(ThreadHistoryTrim.ThreadHistoryTrim)({}), Layer.mock(HeadlessGatewayHost.HeadlessGatewayHost)({}), Layer.mock(TerminalManager.TerminalManager)({}), Layer.mock(ThreadLaunchService.ThreadLaunchService)({}), diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index 7a8385052c075..d380c692415ed 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -191,6 +191,7 @@ import * as ServerSettings from "./serverSettings.ts"; import { invalidateSettingsSecrets } from "./sourceControl/sourceControlHostSecrets.ts"; import * as DatabaseStorage from "./persistence/DatabaseStorage.ts"; import * as StorageCleanup from "./storageCleanup.ts"; +import * as ThreadHistoryTrim from "./orchestration-v2/ThreadHistoryTrim.ts"; import * as TerminalManager from "./terminal/Manager.ts"; import { makePrepareTerminalLaunch } from "./workspace/restoreMissingWorktree.ts"; import { terminalOutputStream, withOutputWindow } from "./terminal/OutputProtocol.ts"; @@ -1466,6 +1467,7 @@ export const layerWsRpc = ( const lifecycleEvents = yield* ServerLifecycleEvents.ServerLifecycleEvents; const storageCleanup = yield* StorageCleanup.StorageCleanup; const databaseStorage = yield* DatabaseStorage.DatabaseStorage; + const threadHistoryTrim = yield* ThreadHistoryTrim.ThreadHistoryTrim; const agentGateway = yield* HeadlessGatewayHost.HeadlessGatewayHost; const serverSettings = yield* ServerSettings.ServerSettingsService; const secretResolver = yield* SecretResolver.SecretResolver; @@ -2653,6 +2655,9 @@ export const layerWsRpc = ( [WS_METHODS.serverGetStorageCleanupReport]: () => storageCleanup.reports, [WS_METHODS.serverGetDatabaseStorage]: () => databaseStorage.status, [WS_METHODS.serverReclaimDatabaseSpace]: () => databaseStorage.requestReclaim, + [WS_METHODS.serverPreviewThreadHistoryTrim]: () => + threadHistoryTrim.preview.pipe(Effect.orDie), + [WS_METHODS.serverTrimThreadHistory]: () => threadHistoryTrim.trimNow.pipe(Effect.orDie), [WS_METHODS.serverGetAgentGateway]: () => agentGateway.status, [WS_METHODS.serverUpdateAgentGateway]: (input) => agentGateway.update(input), [WS_METHODS.serverRevealAgentGatewayToken]: () => diff --git a/apps/web/src/components/settings/SettingIntegerInput.tsx b/apps/web/src/components/settings/SettingIntegerInput.tsx new file mode 100644 index 0000000000000..5d7caa40def81 --- /dev/null +++ b/apps/web/src/components/settings/SettingIntegerInput.tsx @@ -0,0 +1,44 @@ +import { useState } from "react"; + +import { Input } from "../ui/input"; + +export function SettingIntegerInput({ + value, + min, + max, + onCommit, + "aria-label": ariaLabel, +}: { + value: number; + min: number; + max: number; + onCommit: (value: number) => void; + "aria-label": string; +}) { + const [draft, setDraft] = useState(String(value)); + const [draftSource, setDraftSource] = useState(value); + if (draftSource !== value) { + setDraftSource(value); + setDraft(String(value)); + } + + return ( + { + setDraft(event.target.value); + const parsed = Number(event.target.value); + if (Number.isInteger(parsed) && parsed >= min && parsed <= max) { + onCommit(parsed); + } + }} + onBlur={() => setDraft(String(value))} + aria-label={ariaLabel} + /> + ); +} diff --git a/apps/web/src/components/settings/SettingsPanels.tsx b/apps/web/src/components/settings/SettingsPanels.tsx index 99038af7c3a8a..3182f95416926 100644 --- a/apps/web/src/components/settings/SettingsPanels.tsx +++ b/apps/web/src/components/settings/SettingsPanels.tsx @@ -130,6 +130,7 @@ import { SUPPORTED_LOCALES } from "../../i18n/locales"; import { BackgroundActivitySettingsRow } from "./BackgroundActivitySettings"; import { AdvancedSettings } from "./AdvancedSettings"; import { PullRequestLinksOpenInAppSetting } from "./IntegrationsSettings"; +import { SettingIntegerInput } from "./SettingIntegerInput"; import { StorageCleanupSections } from "./StorageSettings"; import { UpdateTrackSwitchDialog } from "./UpdateTrackSwitchDialog"; import { environmentIdsKey } from "~/state/environmentAtomList"; @@ -534,6 +535,9 @@ export function useSettingsRestore(onRestored?: () => void) { DEFAULT_UNIFIED_SETTINGS.autoArchiveSettledAfterDays ? ["Auto-archive settled threads"] : []), + ...(settings.threadHistoryTrimAfterDays !== DEFAULT_UNIFIED_SETTINGS.threadHistoryTrimAfterDays + ? ["Trim old threads"] + : []), ...(settings.autoResumeLimitedThreads !== DEFAULT_UNIFIED_SETTINGS.autoResumeLimitedThreads ? ["Resume after usage limits"] : []), @@ -710,6 +714,7 @@ export function useSettingsRestore(onRestored?: () => void) { sidebarAutoSettleKeepPullRequests: DEFAULT_UNIFIED_SETTINGS.sidebarAutoSettleKeepPullRequests, sidebarAutoSettleOnMerge: DEFAULT_UNIFIED_SETTINGS.sidebarAutoSettleOnMerge, autoArchiveSettledAfterDays: DEFAULT_UNIFIED_SETTINGS.autoArchiveSettledAfterDays, + threadHistoryTrimAfterDays: DEFAULT_UNIFIED_SETTINGS.threadHistoryTrimAfterDays, autoResumeLimitedThreads: DEFAULT_UNIFIED_SETTINGS.autoResumeLimitedThreads, snoozeLimitedThreads: DEFAULT_UNIFIED_SETTINGS.snoozeLimitedThreads, snoozePresets: DEFAULT_UNIFIED_SETTINGS.snoozePresets, @@ -763,47 +768,6 @@ export function useSettingsRestore(onRestored?: () => void) { const AUTO_SETTLE_DEFAULT_DAYS = DEFAULT_UNIFIED_SETTINGS.sidebarAutoSettleAfterDays ?? 7; -function SettingIntegerInput({ - value, - min, - max, - onCommit, - "aria-label": ariaLabel, -}: { - value: number; - min: number; - max: number; - onCommit: (value: number) => void; - "aria-label": string; -}) { - const [draft, setDraft] = useState(String(value)); - const [draftSource, setDraftSource] = useState(value); - if (draftSource !== value) { - setDraftSource(value); - setDraft(String(value)); - } - - return ( - { - setDraft(event.target.value); - const parsed = Number(event.target.value); - if (Number.isInteger(parsed) && parsed >= min && parsed <= max) { - onCommit(parsed); - } - }} - onBlur={() => setDraft(String(value))} - aria-label={ariaLabel} - /> - ); -} - function AutoSettleDaysInput({ value, onCommit, diff --git a/apps/web/src/components/settings/StorageSettings.tsx b/apps/web/src/components/settings/StorageSettings.tsx index 666fb1a3fd40b..dc4224307eb15 100644 --- a/apps/web/src/components/settings/StorageSettings.tsx +++ b/apps/web/src/components/settings/StorageSettings.tsx @@ -1,7 +1,12 @@ -import type { - StorageCleanupReport, - StorageCleanupSettings, - WorktreeCleanupRules, +import { + DEFAULT_THREAD_HISTORY_TRIM_AFTER_DAYS, + DEFAULT_UNIFIED_SETTINGS, + MAX_THREAD_HISTORY_TRIM_AFTER_DAYS, + type EnvironmentId, + type StorageCleanupReport, + type StorageCleanupSettings, + type ThreadHistoryTrimReport, + type WorktreeCleanupRules, } from "@t3tools/contracts"; import { resolvePastedPath } from "@t3tools/shared/path"; import { resolveWorktreeCleanup } from "@t3tools/shared/projectSettings"; @@ -19,6 +24,15 @@ import { formatRelativeTimeLabel } from "../../timestampFormat"; import { useNowMinute } from "../../hooks/useNowMinute"; import { useDebouncedValue } from "../../state/queries"; import { AnimatedHeight } from "../AnimatedHeight"; +import { + AlertDialog, + AlertDialogClose, + AlertDialogDescription, + AlertDialogFooter, + AlertDialogHeader, + AlertDialogPopup, + AlertDialogTitle, +} from "../ui/alert-dialog"; import { Button } from "../ui/button"; import { toastManager } from "../ui/toast"; @@ -36,6 +50,8 @@ import { SettingResetButton, SettingsRow, SettingsSection } from "./settingsLayo import { DatabaseStorageNotice } from "./DatabaseStorageNotice"; import { AdvancedSettings } from "./AdvancedSettings"; import { FoldedSettingsSection } from "./FoldedSettingsSection"; +import { ScopedSwitch } from "./ScopedSwitch"; +import { SettingIntegerInput } from "./SettingIntegerInput"; import { SettingsScopeNotice } from "./SettingsScopeNotice"; import { SettingsGroup } from "./SettingsGroup"; import type { ScopedSettingsTarget } from "./scopedSettings"; @@ -514,6 +530,209 @@ function CleanupSection() { ); } +const threadHistoryTrimPermissionsAtom = environmentAtomList( + "web-thread-history-trim-permissions", + serverEnvironment.trimThreadHistory.permissionAtom, +); + +interface TrimTarget { + readonly environmentId: EnvironmentId; + readonly label: string; +} + +function summarizeTrim(results: ReadonlyArray<{ readonly report: ThreadHistoryTrimReport }>) { + const days = new Set(results.map(({ report }) => report.afterDays)); + const threadCount = results.reduce((sum, { report }) => sum + report.threadCount, 0); + return { + threadCount, + threads: `${threadCount.toLocaleString()} ${threadCount === 1 ? "thread" : "threads"}`, + size: formatBytes(results.reduce((sum, { report }) => sum + report.estimatedBytes, 0)), + idle: + days.size === 1 + ? `idle for ${[...days][0]}+ days` + : "idle longer than their machine's trim setting", + }; +} + +function ThreadHistoryTrimSection() { + const { connectedEnvironments } = useSettingsScope(); + const settings = useScopedSettings(); + const updateSettings = useUpdateScopedSettings(); + const preview = useAtomCommand(serverEnvironment.previewThreadHistoryTrim); + const trim = useAtomCommand(serverEnvironment.trimThreadHistory); + const permissions = useAtomValue( + threadHistoryTrimPermissionsAtom( + environmentIdsKey(connectedEnvironments.map(({ environmentId }) => environmentId)), + ), + ); + const [pending, setPending] = useState<"preview" | "trim" | null>(null); + const [confirmOpen, setConfirmOpen] = useState(false); + const [confirming, setConfirming] = useState | null>(null); + const on = settings.threadHistoryTrimAfterDays > 0; + const runnable = connectedEnvironments.filter( + (environment, index) => + permissions[index] === true && + (environment.serverConfig?.settings.threadHistoryTrimAfterDays ?? 0) > 0, + ); + + const runOn = async ( + command: typeof trim, + targets: ReadonlyArray, + failureTitle: string, + ) => { + const results = await Promise.all( + targets.map(async (target) => { + const result = await command({ environmentId: target.environmentId, input: {} }); + if (result._tag === "Success") return { target, report: result.value }; + if (!isAtomCommandInterrupted(result)) { + const error = squashAtomCommandFailure(result); + toastManager.add({ + type: "error", + title: `${failureTitle} on ${target.label}`, + description: error instanceof Error ? error.message : "An error occurred.", + }); + } + return null; + }), + ); + return results.filter((result) => result !== null); + }; + + const checkTrim = async () => { + setPending("preview"); + const results = await runOn(preview, runnable, "Could not check old threads").finally(() => + setPending(null), + ); + if (results.length === 0) return; + setConfirming(results); + setConfirmOpen(true); + }; + + const confirmTrim = async () => { + const targets = (confirming ?? []) + .filter(({ report }) => report.threadCount > 0) + .map(({ target }) => target); + setConfirmOpen(false); + setPending("trim"); + const results = await runOn(trim, targets, "Could not trim threads").finally(() => + setPending(null), + ); + if (results.length === 0) return; + const { threads, size } = summarizeTrim(results); + toastManager.add({ + type: "success", + title: `Trimming ${threads}`, + description: `About ${size} of tool output and reasoning is being removed.`, + }); + }; + + const summary = confirming ? summarizeTrim(confirming) : null; + + return ( + + + updateSettings({ + threadHistoryTrimAfterDays: DEFAULT_UNIFIED_SETTINGS.threadHistoryTrimAfterDays, + }) + } + /> + ) : null + } + control={ +
+ + + updateSettings({ + threadHistoryTrimAfterDays: checked ? DEFAULT_THREAD_HISTORY_TRIM_AFTER_DAYS : 0, + }) + } + aria-label="Trim old threads" + /> + + + {summary && summary.threadCount > 0 ? ( + <> + + Trim old threads? + + Remove tool output and reasoning from {summary.threads} {summary.idle}, + about {summary.size}? Messages, plans and file changes are kept. This + can't be undone. + + + + }> + Cancel + + + + + ) : ( + <> + + Nothing to trim + + No threads are {summary?.idle ?? "old enough"} yet. + + + + }> + Close + + + + )} + + +
+ } + /> + {on ? ( + updateSettings({ threadHistoryTrimAfterDays: days })} + aria-label="Days unused before a thread is trimmed" + /> + } + /> + ) : null} +
+ ); +} + function supportsStorageCleanup( environments: ReadonlyArray<{ readonly serverConfig: { @@ -836,10 +1055,19 @@ export function StorageCleanupSections() { )} /> ); + const threadHistoryTrim = + connectedEnvironments.length > 0 && + connectedEnvironments.every( + (environment) => + environment.serverConfig?.environment.capabilities.threadHistoryTrim === true, + ) ? ( + + ) : null; if (!supportsStorageCleanup(connectedEnvironments)) { return ( <> {databaseStorageNotice} + {threadHistoryTrim} @@ -850,6 +1078,7 @@ export function StorageCleanupSections() { return ( <> {databaseStorageNotice} + {threadHistoryTrim} 0; + const hasThreadHistoryTrim = + getThreadAutoSettlementSearchAvailability(environments, undefined, "threadHistoryTrim") + .eligibleEnvironmentIds.length > 0; const primaryEnvironmentId = usePrimaryEnvironmentId(); const canMaintain = useEnvironmentScope(primaryEnvironmentId, AuthEnvironmentMaintainScope); const localEnvironmentDisabled = isLocalEnvironmentDisabled() === true; @@ -68,6 +71,7 @@ export function useAvailableSettingsSearchItems() { hasThreadAutoSettlement, hasThreadAutoSettleFinishedChildren, hasThreadAutoArchive, + hasThreadHistoryTrim, hasFastWorktreeCheckoutEnvironment, hasTextGeneratorsEnvironment, hasPrimaryEnvironment: primaryEnvironmentId !== null, diff --git a/docs/user/background-service.md b/docs/user/background-service.md index 4da4fafe8c80f..3abb9a6d73eec 100644 --- a/docs/user/background-service.md +++ b/docs/user/background-service.md @@ -167,6 +167,24 @@ Downloads, it may need Full Disk Access for the `ada` executable listed in `ProgramArguments` in `~/Library/LaunchAgents/com.t3tools.t3code.service.plist`. +## Trim old threads + +Tool output and agent reasoning take up most of the space a thread uses. After a +thread goes 30 days without use, Ada removes them and adds a short note to the +thread saying older detail was trimmed. Messages, plans, file changes and +checkpoints stay, so you can still read, search and continue the thread. +Running, pinned and snoozed threads and threads with an open pull request are +never trimmed. + +Change the days or turn trimming off with **Trim old threads** in Settings > +Maintenance (web and desktop) or Settings > Threads (mobile). It applies to the +whole environment. On web and desktop, **Trim now** shows how many threads +qualify and about how much space they use, and trims them once you confirm. +Trimming can't be undone. + +On databases created before automatic shrinking, the database file keeps its +size until you [reclaim database space](#reclaim-database-space). + ## Reclaim database space Ada removes internal history older than a day on its own while it runs; diff --git a/packages/client-runtime/src/state/server.ts b/packages/client-runtime/src/state/server.ts index 1a88fb9267ad0..315c31193f940 100644 --- a/packages/client-runtime/src/state/server.ts +++ b/packages/client-runtime/src/state/server.ts @@ -1399,6 +1399,16 @@ export function createServerEnvironmentAtoms( tag: WS_METHODS.serverReclaimDatabaseSpace, concurrency: { mode: "singleFlight", key: ({ environmentId }) => environmentId }, }), + previewThreadHistoryTrim: createEnvironmentRpcCommand(runtime, { + label: "environment-data:server:preview-thread-history-trim", + tag: WS_METHODS.serverPreviewThreadHistoryTrim, + concurrency: { mode: "singleFlight", key: ({ environmentId }) => environmentId }, + }), + trimThreadHistory: createEnvironmentRpcCommand(runtime, { + label: "environment-data:server:trim-thread-history", + tag: WS_METHODS.serverTrimThreadHistory, + concurrency: { mode: "singleFlight", key: ({ environmentId }) => environmentId }, + }), agentGateway: createEnvironmentRpcSubscriptionAtomFamily(runtime, { label: "environment-data:server:agent-gateway", tag: WS_METHODS.serverGetAgentGateway, diff --git a/packages/contracts/src/clientRpcPermissions.ts b/packages/contracts/src/clientRpcPermissions.ts index 5f9b0e286e671..e8c0b8c998d90 100644 --- a/packages/contracts/src/clientRpcPermissions.ts +++ b/packages/contracts/src/clientRpcPermissions.ts @@ -26,6 +26,8 @@ export const CLIENT_GUARDED_RPC_SCOPES = { [WS_METHODS.serverMutateAgentLibrary]: AuthSettingsWriteScope, // Restarts the server, as an update does. [WS_METHODS.serverReclaimDatabaseSpace]: AuthEnvironmentMaintainScope, + // Deletes stored history, which no settings write can undo. + [WS_METHODS.serverTrimThreadHistory]: AuthEnvironmentMaintainScope, [WS_METHODS.serverCheckOtlpEndpoint]: AuthSettingsWriteScope, [WS_METHODS.serverCheckSecretSource]: AuthSettingsWriteScope, // Listing models spends the stored API key, so only those who can choose a model may. diff --git a/packages/contracts/src/environment.ts b/packages/contracts/src/environment.ts index ab729a15b8ef9..49609bf9d92ce 100644 --- a/packages/contracts/src/environment.ts +++ b/packages/contracts/src/environment.ts @@ -156,6 +156,8 @@ export const ExecutionEnvironmentCapabilities = Schema.Struct({ threadAutoSettleFinishedChildren: Schema.optionalKey(Schema.Boolean), /** Server archives threads settled for `autoArchiveSettledAfterDays`. */ threadAutoArchive: Schema.optionalKey(Schema.Boolean), + /** Server trims threads idle for `threadHistoryTrimAfterDays`. */ + threadHistoryTrim: Schema.optionalKey(Schema.Boolean), threadProjectFromScratch: Schema.optionalKey(Schema.Boolean), threadTitleRegeneration: Schema.optionalKey(Schema.Boolean), threadVisitedTracking: Schema.optionalKey(Schema.Boolean), diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.ts index 4976d45b14903..26d77c5c597a5 100644 --- a/packages/contracts/src/rpc.ts +++ b/packages/contracts/src/rpc.ts @@ -399,6 +399,7 @@ import { import { UsagePricing, UsageReadError, UsageSummary, UsageSummaryInput } from "./usage.ts"; import { StorageCleanupReport, + ThreadHistoryTrimReport, DatabaseReclaimError, DatabaseStorageStatus, ServerSettings, @@ -598,6 +599,8 @@ export const WS_METHODS = { serverGetStorageCleanupReport: "server.getStorageCleanupReport", serverGetDatabaseStorage: "server.getDatabaseStorage", serverReclaimDatabaseSpace: "server.reclaimDatabaseSpace", + serverPreviewThreadHistoryTrim: "server.previewThreadHistoryTrim", + serverTrimThreadHistory: "server.trimThreadHistory", serverGetAgentGateway: "server.getAgentGateway", serverUpdateAgentGateway: "server.updateAgentGateway", serverRevealAgentGatewayToken: "server.revealAgentGatewayToken", @@ -963,6 +966,18 @@ const WsServerReclaimDatabaseSpaceRpc = Rpc.make(WS_METHODS.serverReclaimDatabas error: Schema.Union([DatabaseReclaimError, EnvironmentAuthorizationError]), }); +const WsServerPreviewThreadHistoryTrimRpc = Rpc.make(WS_METHODS.serverPreviewThreadHistoryTrim, { + payload: Schema.Struct({}), + success: ThreadHistoryTrimReport, + error: EnvironmentAuthorizationError, +}); + +const WsServerTrimThreadHistoryRpc = Rpc.make(WS_METHODS.serverTrimThreadHistory, { + payload: Schema.Struct({}), + success: ThreadHistoryTrimReport, + error: EnvironmentAuthorizationError, +}); + const WsServerGetAgentGatewayRpc = Rpc.make(WS_METHODS.serverGetAgentGateway, { payload: Schema.Struct({}), success: AgentGatewayStatus, @@ -2520,6 +2535,8 @@ export const WsRpcGroup = RpcGroup.make( WsServerGetDatabaseStorageRpc, WsServerGetSettingsRpc, WsServerReclaimDatabaseSpaceRpc, + WsServerPreviewThreadHistoryTrimRpc, + WsServerTrimThreadHistoryRpc, WsServerGetAgentGatewayRpc, WsServerUpdateAgentGatewayRpc, WsServerRevealAgentGatewayTokenRpc, diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts index e2b81f4aed6fc..b8d9d43e82aec 100644 --- a/packages/contracts/src/settings.ts +++ b/packages/contracts/src/settings.ts @@ -134,6 +134,24 @@ export const AutoArchiveSettledAfterDays = Schema.Int.check( ); export type AutoArchiveSettledAfterDays = typeof AutoArchiveSettledAfterDays.Type; export const DEFAULT_AUTO_ARCHIVE_SETTLED_AFTER_DAYS: AutoArchiveSettledAfterDays = 10; +export const MAX_THREAD_HISTORY_TRIM_AFTER_DAYS = 365; +/** Days without user interaction before a thread's tool output and reasoning are deleted; 0 turns the rule off. */ +export const ThreadHistoryTrimAfterDays = Schema.Int.check( + Schema.isBetween({ minimum: 0, maximum: MAX_THREAD_HISTORY_TRIM_AFTER_DAYS }), +); +export type ThreadHistoryTrimAfterDays = typeof ThreadHistoryTrimAfterDays.Type; +export const DEFAULT_THREAD_HISTORY_TRIM_AFTER_DAYS: ThreadHistoryTrimAfterDays = 30; + +/** What a trim pass removes, or would remove when `dryRun`. */ +export const ThreadHistoryTrimReport = Schema.Struct({ + dryRun: Schema.Boolean, + afterDays: ThreadHistoryTrimAfterDays, + threadCount: Schema.Int, + itemCount: Schema.Int, + /** Stored size of the removed rows; the file shrinks by about this once free pages are reclaimed. */ + estimatedBytes: Schema.Number, +}); +export type ThreadHistoryTrimReport = typeof ThreadHistoryTrimReport.Type; export const MAX_SNOOZE_PRESET_MINUTES = 30 * 24 * 60; export const MAX_SNOOZE_PRESETS = 8; @@ -1637,6 +1655,9 @@ export const ServerSettings = Schema.Struct({ autoArchiveSettledAfterDays: AutoArchiveSettledAfterDays.pipe( Schema.withDecodingDefault(Effect.succeed(DEFAULT_AUTO_ARCHIVE_SETTLED_AFTER_DAYS)), ), + threadHistoryTrimAfterDays: ThreadHistoryTrimAfterDays.pipe( + Schema.withDecodingDefault(Effect.succeed(DEFAULT_THREAD_HISTORY_TRIM_AFTER_DAYS)), + ), // Legacy field accepted from deployed clients; settlement now uses only idle age. sidebarAutoSettleOnMerge: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))), backgroundActivity: BackgroundActivitySettings, @@ -2071,6 +2092,7 @@ export const ServerSettingsPatch = Schema.Struct({ sidebarAutoSettleOnMerge: Schema.optionalKey(Schema.Boolean), autoSettleFinishedChildrenAfterHours: Schema.optionalKey(AutoSettleFinishedChildrenAfterHours), autoArchiveSettledAfterDays: Schema.optionalKey(AutoArchiveSettledAfterDays), + threadHistoryTrimAfterDays: Schema.optionalKey(ThreadHistoryTrimAfterDays), autoResumeLimitedThreads: Schema.optionalKey(Schema.Boolean), snoozeLimitedThreads: Schema.optionalKey(Schema.Boolean), snoozePresets: Schema.optionalKey(SnoozePresetSettings), From dbbd151877190b44f2b0347f367e719a3effb992 Mon Sep 17 00:00:00 2001 From: JJ Eaton <58495321+oldbettie@users.noreply.github.com> Date: Tue, 17 Nov 2026 12:13:12 +0800 Subject: [PATCH 2/4] fix(server): trim preview counts the whole stored row, not just its payload The estimate read about half the real saving because it ignored the ids each row repeats in its table, indexes and position row. It now reads about 80% (411 MB estimated, 505 MB freed on a seeded copy). Co-Authored-By: Claude Fable 5.2 --- .../src/orchestration-v2/ThreadHistoryTrim.ts | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/apps/server/src/orchestration-v2/ThreadHistoryTrim.ts b/apps/server/src/orchestration-v2/ThreadHistoryTrim.ts index f64de5f21603d..69714bb2ac8d6 100644 --- a/apps/server/src/orchestration-v2/ThreadHistoryTrim.ts +++ b/apps/server/src/orchestration-v2/ThreadHistoryTrim.ts @@ -60,6 +60,17 @@ type Candidate = { type Mode = "background" | "manual"; type Removed = { readonly itemCount: number; readonly bytes: number }; +// Space a row gives back: its payload plus each copy of its ids in the row, its indexes and its position row. +const ITEM_BYTES = `(octet_length(payload_json) + 5 * length(turn_item_id) + 8 * length(thread_id) + + 3 * COALESCE(length(run_id), 0) + 2 * COALESCE(length(node_id), 0) + + 2 * COALESCE(length(provider_turn_id), 0) + COALESCE(length(provider_thread_id), 0) + + COALESCE(length(parent_item_id), 0))`; +const nodeBytes = (alias: string) => + `(octet_length(${alias}payload_json) + 2 * length(${alias}node_id) + 3 * length(${alias}thread_id) + + length(${alias}root_node_id) + 2 * COALESCE(length(${alias}run_id), 0) + + 2 * COALESCE(length(${alias}parent_node_id), 0) + 2 * COALESCE(length(${alias}provider_turn_id), 0) + + COALESCE(length(${alias}provider_thread_id), 0))`; + function trimNoticeMessage(afterDays: number): string { return `Tool output and reasoning above this point were removed to save space after ${afterDays} ${afterDays === 1 ? "day" : "days"} without use. Messages, plans and file changes are kept.`; } @@ -175,11 +186,11 @@ const make = Effect.gen(function* () { WHERE thread_id = ${candidate.threadId} AND type IN ${sql.in(TRIMMED_ITEM_TYPES)} AND status NOT IN ${sql.in(LIVE_ITEM_STATUSES)}) AS items, - COALESCE((SELECT SUM(octet_length(payload_json)) FROM orchestration_v2_projection_turn_items + COALESCE((SELECT SUM(${sql.literal(ITEM_BYTES)}) FROM orchestration_v2_projection_turn_items WHERE thread_id = ${candidate.threadId} AND type IN ${sql.in(TRIMMED_ITEM_TYPES)} AND status NOT IN ${sql.in(LIVE_ITEM_STATUSES)}), 0) - + COALESCE((SELECT SUM(octet_length(payload_json)) FROM orchestration_v2_projection_nodes + + COALESCE((SELECT SUM(${sql.literal(nodeBytes(""))}) FROM orchestration_v2_projection_nodes WHERE thread_id = ${candidate.threadId} AND kind IN ${sql.in(TRIMMED_NODE_KINDS)} AND status NOT IN ${sql.in(LIVE_NODE_STATUSES)}), 0) AS bytes @@ -278,7 +289,7 @@ const make = Effect.gen(function* () { parent_item_id AS parent, type, status, - octet_length(payload_json) AS bytes + ${sql.literal(ITEM_BYTES)} AS bytes FROM orchestration_v2_projection_turn_items WHERE thread_id = ${threadId} AND ordinal < ${boundary} `.pipe(NodeSqliteClient.readOnlyBackground); @@ -322,7 +333,7 @@ const make = Effect.gen(function* () { node.kind, node.status, COALESCE(run.ordinal <= ${candidate.runOrdinal}, 0) AS settled, - octet_length(node.payload_json) AS bytes + ${sql.literal(nodeBytes("node."))} AS bytes FROM orchestration_v2_projection_nodes AS node LEFT JOIN orchestration_v2_projection_runs AS run ON run.run_id = node.run_id WHERE node.thread_id = ${threadId} From 6a18bc4107099a06a7dc09c0129f656af2b4b811 Mon Sep 17 00:00:00 2001 From: JJ Eaton <58495321+oldbettie@users.noreply.github.com> Date: Tue, 17 Nov 2026 13:00:18 +0800 Subject: [PATCH 3/4] feat(server): thread trimming runs once every 30 days, or at the next start The server stores when the last trim pass finished. A pass runs when that is 30 or more days ago: while running, within six hours of coming due; after a missed due date, five minutes after the next start. "Trim now" always runs and resets the clock. Settings > Maintenance shows the last and next pass. Co-Authored-By: Claude Fable 5.2 --- apps/server/src/auth/RpcAuthorization.ts | 1 + .../src/observability/RpcInstrumentation.ts | 1 + .../ThreadHistoryTrim.test.ts | 79 ++++++++++++++++--- .../src/orchestration-v2/ThreadHistoryTrim.ts | 69 ++++++++++++---- apps/server/src/ws.ts | 1 + .../components/settings/StorageSettings.tsx | 45 ++++++++++- docs/user/background-service.md | 8 +- packages/client-runtime/src/rpc/client.ts | 1 + packages/client-runtime/src/state/server.ts | 5 ++ packages/contracts/src/rpc.ts | 10 +++ packages/contracts/src/settings.ts | 7 ++ 11 files changed, 199 insertions(+), 28 deletions(-) diff --git a/apps/server/src/auth/RpcAuthorization.ts b/apps/server/src/auth/RpcAuthorization.ts index 0412abafa6473..a057d9f9e4223 100644 --- a/apps/server/src/auth/RpcAuthorization.ts +++ b/apps/server/src/auth/RpcAuthorization.ts @@ -95,6 +95,7 @@ export const RPC_REQUIRED_SCOPES = { [WS_METHODS.serverGetStorageCleanupReport]: AuthOrchestrationReadScope, [WS_METHODS.serverGetDatabaseStorage]: AuthOrchestrationReadScope, [WS_METHODS.serverGetSettings]: AuthOrchestrationReadScope, + [WS_METHODS.serverGetThreadHistoryTrim]: AuthOrchestrationReadScope, [WS_METHODS.serverPreviewThreadHistoryTrim]: AuthOrchestrationReadScope, [WS_METHODS.peerLinksList]: AuthAccessReadScope, [WS_METHODS.serverGetAgentGateway]: AuthAccessReadScope, diff --git a/apps/server/src/observability/RpcInstrumentation.ts b/apps/server/src/observability/RpcInstrumentation.ts index 8bc68bc6bbfb0..0c48e375d87c9 100644 --- a/apps/server/src/observability/RpcInstrumentation.ts +++ b/apps/server/src/observability/RpcInstrumentation.ts @@ -66,6 +66,7 @@ const RPC_AGGREGATES = { [WS_METHODS.serverGetStorageCleanupReport]: "server", [WS_METHODS.serverGetDatabaseStorage]: "server", [WS_METHODS.serverReclaimDatabaseSpace]: "server", + [WS_METHODS.serverGetThreadHistoryTrim]: "server", [WS_METHODS.serverPreviewThreadHistoryTrim]: "server", [WS_METHODS.serverTrimThreadHistory]: "server", [WS_METHODS.serverGetAgentGateway]: "server", diff --git a/apps/server/src/orchestration-v2/ThreadHistoryTrim.test.ts b/apps/server/src/orchestration-v2/ThreadHistoryTrim.test.ts index 91eace2ca2f2b..9a0e02e17c0f1 100644 --- a/apps/server/src/orchestration-v2/ThreadHistoryTrim.test.ts +++ b/apps/server/src/orchestration-v2/ThreadHistoryTrim.test.ts @@ -17,6 +17,8 @@ import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Stream from "effect/Stream"; import * as TestClock from "effect/testing/TestClock"; import * as SqlClient from "effect/sql/SqlClient"; @@ -34,18 +36,16 @@ const stores = Layer.mergeAll( EventStore.layer.pipe(Layer.provideMerge(database)), ProjectionStore.layer.pipe(Layer.provideMerge(database)), ); -const layerTest = (afterDays: number) => - ThreadHistoryTrim.layer.pipe( - Layer.provideMerge( - Layer.mergeAll( - stores, - OrchestrationEventStore.layer.pipe(Layer.provide(database)), - EventSink.layer.pipe(Layer.provide(stores)), - IdAllocator.layer, - ServerSettings.ServerSettingsService.layerTest({ threadHistoryTrimAfterDays: afterDays }), - ), - ), +const dependencies = (afterDays: number) => + Layer.mergeAll( + stores, + OrchestrationEventStore.layer.pipe(Layer.provide(database)), + EventSink.layer.pipe(Layer.provide(stores)), + IdAllocator.layer, + ServerSettings.ServerSettingsService.layerTest({ threadHistoryTrimAfterDays: afterDays }), ); +const layerTest = (afterDays: number) => + ThreadHistoryTrim.layer.pipe(Layer.provideMerge(dependencies(afterDays))); const now = DateTime.makeUnsafe("2026-11-17T00:00:00.000Z"); const old = DateTime.subtract(now, { days: 40 }); @@ -400,3 +400,60 @@ it.layer(layerTest(0))("ThreadHistoryTrim turned off", (it) => { }), ); }); + +const lastTrimmedAt = Effect.gen(function* () { + const service = yield* ThreadHistoryTrim.ThreadHistoryTrim; + return Option.getOrThrow(yield* Stream.runHead(service.status)).lastTrimmedAt; +}); +const afterWaiting = Effect.fn(function* (duration: Parameters[0]) { + yield* TestClock.adjust(duration); + yield* (yield* ThreadHistoryTrim.ThreadHistoryTrim).drain; +}); +// Each provide is one server run: the layer's scope closes with it, and the database outlives it. +const whileRunning = Effect.provide(ThreadHistoryTrim.layer); + +it.layer(dependencies(30))("ThreadHistoryTrim schedule", (it) => { + it.effect("runs a pass every 30 days, and at the next start when one was missed", () => + Effect.gen(function* () { + yield* TestClock.setTime(DateTime.toEpochMillis(now)); + const first = yield* seedThread("first"); + + yield* Effect.gen(function* () { + assert.isNull(yield* lastTrimmedAt); + yield* afterWaiting("5 minutes"); + assert.deepEqual(yield* itemTitles(first.threadId), trimmedItems); + const ranAt = yield* lastTrimmedAt; + assert.equal(ranAt, DateTime.formatIso(DateTime.add(now, { minutes: 5 }))); + + const second = yield* seedThread("second"); + yield* afterWaiting("29 days"); + assert.deepEqual(yield* itemTitles(second.threadId), everyItem); + assert.equal(yield* lastTrimmedAt, ranAt); + + yield* afterWaiting("1 day"); + assert.deepEqual(yield* itemTitles(second.threadId), trimmedItems); + }).pipe(whileRunning); + + const missed = yield* seedThread("missed"); + yield* TestClock.adjust("45 days"); + assert.deepEqual(yield* itemTitles(missed.threadId), everyItem); + + yield* Effect.gen(function* () { + yield* afterWaiting("5 minutes"); + assert.deepEqual(yield* itemTitles(missed.threadId), trimmedItems); + + yield* TestClock.adjust("10 days"); + const requested = yield* seedThread("requested"); + yield* trim; + assert.deepEqual(yield* itemTitles(requested.threadId), trimmedItems); + + // The requested trim reset the clock: 35 days after the last scheduled pass is too soon. + const later = yield* seedThread("later"); + yield* afterWaiting("25 days"); + assert.deepEqual(yield* itemTitles(later.threadId), everyItem); + yield* afterWaiting("5 days"); + assert.deepEqual(yield* itemTitles(later.threadId), trimmedItems); + }).pipe(whileRunning); + }), + ); +}); diff --git a/apps/server/src/orchestration-v2/ThreadHistoryTrim.ts b/apps/server/src/orchestration-v2/ThreadHistoryTrim.ts index 69714bb2ac8d6..93d78e76d9282 100644 --- a/apps/server/src/orchestration-v2/ThreadHistoryTrim.ts +++ b/apps/server/src/orchestration-v2/ThreadHistoryTrim.ts @@ -1,4 +1,9 @@ -import { type RunId, type ThreadHistoryTrimReport, type ThreadId } from "@t3tools/contracts"; +import { + type RunId, + type ThreadHistoryTrimReport, + type ThreadHistoryTrimStatus, + type ThreadId, +} from "@t3tools/contracts"; import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker"; import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient"; @@ -10,11 +15,14 @@ import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Schedule from "effect/Schedule"; import * as Schema from "effect/Schema"; +import * as Stream from "effect/Stream"; +import * as SubscriptionRef from "effect/SubscriptionRef"; import * as SqlClient from "effect/sql/SqlClient"; import * as ServerSettingsModule from "../serverSettings.ts"; import { forkParked } from "../serverActivation.ts"; import * as EventSink from "./EventSink.ts"; +import * as ProjectionStore from "./ProjectionStore.ts"; export class ThreadHistoryTrimError extends Schema.TaggedError()( "ThreadHistoryTrimError", @@ -31,11 +39,15 @@ export class ThreadHistoryTrim extends Context.Service< readonly preview: Effect.Effect; /** Queues a pass and returns what it is about to remove. */ readonly trimNow: Effect.Effect; + /** When the last pass finished and when the next one is due. */ + readonly status: Stream.Stream; readonly drain: Effect.Effect; } >()("t3/orchestration-v2/ThreadHistoryTrim") {} const DAY_MS = 24 * 60 * 60 * 1_000; +const PASS_INTERVAL_MS = 30 * DAY_MS; +const LAST_PASS = "thread-history-trim-last-pass"; const DELETE_PAGE_SIZE = 200; const NOTICE_SIGNAL = "history-trim"; // Work the reader skips: `file_change` stays because it is small and names what a run touched. @@ -387,9 +399,45 @@ const make = Effect.gen(function* () { } satisfies Removed; }); + const readLastPass = sql<{ readonly updated_at: string }>` + SELECT updated_at FROM orchestration_v2_projection_metadata WHERE projection_name = ${LAST_PASS} + `.pipe(Effect.map((rows) => rows[0]?.updated_at ?? null)); + const statusOf = (lastTrimmedAt: string | null): ThreadHistoryTrimStatus => ({ + lastTrimmedAt, + nextTrimAt: + lastTrimmedAt === null + ? null + : DateTime.formatIso(DateTime.makeUnsafe(Date.parse(lastTrimmedAt) + PASS_INTERVAL_MS)), + }); + const statusRef = yield* SubscriptionRef.make( + statusOf(yield* readLastPass.pipe(Effect.orElseSucceed(() => null))), + ); + const recordPass = Effect.gen(function* () { + const finishedAt = DateTime.formatIso(yield* DateTime.now); + yield* sql` + INSERT INTO orchestration_v2_projection_metadata ( + projection_name, schema_version, last_sequence, updated_at + ) + VALUES ( + ${LAST_PASS}, ${ProjectionStore.ORCHESTRATION_V2_PROJECTION_SCHEMA_VERSION}, 0, ${finishedAt} + ) + ON CONFLICT(projection_name) DO UPDATE SET updated_at = excluded.updated_at + `; + yield* SubscriptionRef.set(statusRef, statusOf(finishedAt)); + }); + const pass = Effect.fn("ThreadHistoryTrim.pass")(function* (mode: Mode) { const { afterDays, now, idleBefore } = yield* window; if (afterDays <= 0) return; + if (mode === "background") { + // Checked here, behind the queue, so a requested trim that just finished counts. + const last = yield* readLastPass; + if (last !== null && Date.parse(now) - Date.parse(last) < PASS_INTERVAL_MS) return; + const report = yield* estimate(true).pipe(NodeSqliteClient.readOnlyBackground); + if (report.threadCount > 0) { + yield* Effect.logInfo("Idle thread history due for trimming", report); + } + } let sliceStarted = yield* Clock.currentTimeMillis; // The sweep keeps to a 10% duty so a backlog never competes with a turn; a requested trim does not wait. const rest = @@ -436,6 +484,7 @@ const make = Effect.gen(function* () { estimatedBytes, }); } + yield* recordPass; }); const worker = yield* makeDrainableWorker((mode: Mode) => pass(mode)); @@ -445,20 +494,11 @@ const make = Effect.gen(function* () { (effect: Effect.Effect) => effect.pipe(Effect.mapError((cause) => new ThreadHistoryTrimError({ operation, cause }))); - // Dry run first: the first pass after a start reports what it would remove, and removes it an - // hour later, so an upgrade never deletes history before the setting can be seen. + // A pass is due 30 days after the last one finished, or at once when none has. Checking every + // six hours catches a due date that passes while running; one long timer overflows and drifts + // across machine sleep. yield* forkParked( - estimate(true).pipe( - NodeSqliteClient.readOnlyBackground, - Effect.tap((report) => - report.threadCount > 0 - ? Effect.logInfo("Idle thread history due for trimming", report) - : Effect.void, - ), - Effect.catchCause((cause) => - Effect.logWarning("Thread history trim preview failed", { cause: Cause.pretty(cause) }), - ), - Effect.andThen(Effect.sleep("1 hour")), + Effect.sleep("5 minutes").pipe( Effect.andThen( worker .enqueue("background") @@ -474,6 +514,7 @@ const make = Effect.gen(function* () { Effect.tap(() => worker.enqueue("manual")), mapError("trim"), ), + status: SubscriptionRef.changes(statusRef), drain: worker.drain, }); }); diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index d380c692415ed..186c6b1040733 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -2655,6 +2655,7 @@ export const layerWsRpc = ( [WS_METHODS.serverGetStorageCleanupReport]: () => storageCleanup.reports, [WS_METHODS.serverGetDatabaseStorage]: () => databaseStorage.status, [WS_METHODS.serverReclaimDatabaseSpace]: () => databaseStorage.requestReclaim, + [WS_METHODS.serverGetThreadHistoryTrim]: () => threadHistoryTrim.status, [WS_METHODS.serverPreviewThreadHistoryTrim]: () => threadHistoryTrim.preview.pipe(Effect.orDie), [WS_METHODS.serverTrimThreadHistory]: () => threadHistoryTrim.trimNow.pipe(Effect.orDie), diff --git a/apps/web/src/components/settings/StorageSettings.tsx b/apps/web/src/components/settings/StorageSettings.tsx index dc4224307eb15..1f3b02abf0808 100644 --- a/apps/web/src/components/settings/StorageSettings.tsx +++ b/apps/web/src/components/settings/StorageSettings.tsx @@ -535,6 +535,14 @@ const threadHistoryTrimPermissionsAtom = environmentAtomList( serverEnvironment.trimThreadHistory.permissionAtom, ); +const threadHistoryTrimStatusAtom = environmentAtomList( + "web-thread-history-trim-status", + (environmentId) => serverEnvironment.threadHistoryTrim({ environmentId, input: {} }), +); + +const formatTrimDate = (iso: string) => + new Date(iso).toLocaleDateString(undefined, { dateStyle: "medium" }); + interface TrimTarget { readonly environmentId: EnvironmentId; readonly label: string; @@ -572,6 +580,31 @@ function ThreadHistoryTrimSection() { readonly report: ThreadHistoryTrimReport; }> | null>(null); const on = settings.threadHistoryTrimAfterDays > 0; + const nowMs = Date.parse(`${useNowMinute()}Z`); + const statuses = useAtomValue( + threadHistoryTrimStatusAtom( + environmentIdsKey(connectedEnvironments.map(({ environmentId }) => environmentId)), + ), + ); + const schedule = connectedEnvironments.flatMap((environment, index) => { + const query = statuses[index]; + if (query?._tag !== "Success") return []; + if ((environment.serverConfig?.settings.threadHistoryTrimAfterDays ?? 0) <= 0) return []; + const { lastTrimmedAt, nextTrimAt } = query.value; + const text = + lastTrimmedAt === null || nextTrimAt === null + ? "Not trimmed yet · first pass runs a few minutes after start" + : `Last trimmed ${formatTrimDate(lastTrimmedAt)} · next ${ + Date.parse(nextTrimAt) <= nowMs ? "today" : formatTrimDate(nextTrimAt) + }`; + const label = settingsScopeEnvironmentLabel(environment, connectedEnvironments); + return [ + { + environmentId: environment.environmentId, + text: connectedEnvironments.length > 1 ? `${label}: ${text}` : text, + }, + ]; + }); const runnable = connectedEnvironments.filter( (environment, index) => permissions[index] === true && @@ -717,7 +750,17 @@ function ThreadHistoryTrimSection() { serverScoped settingKeys={["threadHistoryTrimAfterDays"]} title={searchableSetting("days-before-thread-trim").title} - description="Running, pinned and snoozed threads and threads with an open pull request are skipped." + description={ + <> + A pass runs every 30 days. Running, pinned and snoozed threads and threads with an + open pull request are skipped. + {schedule.map(({ environmentId, text }) => ( + + {text} + + ))} + + } control={ Maintenance shows when the last +pass ran and when the next is due. + Change the days or turn trimming off with **Trim old threads** in Settings > Maintenance (web and desktop) or Settings > Threads (mobile). It applies to the whole environment. On web and desktop, **Trim now** shows how many threads -qualify and about how much space they use, and trims them once you confirm. -Trimming can't be undone. +qualify and about how much space they use, and trims them once you confirm. The +next automatic pass is then 30 days after that. Trimming can't be undone. On databases created before automatic shrinking, the database file keeps its size until you [reclaim database space](#reclaim-database-space). diff --git a/packages/client-runtime/src/rpc/client.ts b/packages/client-runtime/src/rpc/client.ts index 71f1206b2c8ad..de8c1167075f1 100644 --- a/packages/client-runtime/src/rpc/client.ts +++ b/packages/client-runtime/src/rpc/client.ts @@ -63,6 +63,7 @@ export type EnvironmentSubscriptionRpcTag = | typeof WS_METHODS.todosSubscribe | typeof WS_METHODS.serverGetStorageCleanupReport | typeof WS_METHODS.serverGetDatabaseStorage + | typeof WS_METHODS.serverGetThreadHistoryTrim | typeof WS_METHODS.serverGetAgentGateway | typeof WS_METHODS.subscribeTerminalMetadata | typeof WS_METHODS.subscribePreviewEvents diff --git a/packages/client-runtime/src/state/server.ts b/packages/client-runtime/src/state/server.ts index 315c31193f940..814945f44b3ea 100644 --- a/packages/client-runtime/src/state/server.ts +++ b/packages/client-runtime/src/state/server.ts @@ -1399,6 +1399,11 @@ export function createServerEnvironmentAtoms( tag: WS_METHODS.serverReclaimDatabaseSpace, concurrency: { mode: "singleFlight", key: ({ environmentId }) => environmentId }, }), + threadHistoryTrim: createEnvironmentRpcSubscriptionAtomFamily(runtime, { + label: "environment-data:server:thread-history-trim", + tag: WS_METHODS.serverGetThreadHistoryTrim, + idleTtlMs: 0, + }), previewThreadHistoryTrim: createEnvironmentRpcCommand(runtime, { label: "environment-data:server:preview-thread-history-trim", tag: WS_METHODS.serverPreviewThreadHistoryTrim, diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.ts index 26d77c5c597a5..086c42eb6bf88 100644 --- a/packages/contracts/src/rpc.ts +++ b/packages/contracts/src/rpc.ts @@ -400,6 +400,7 @@ import { UsagePricing, UsageReadError, UsageSummary, UsageSummaryInput } from ". import { StorageCleanupReport, ThreadHistoryTrimReport, + ThreadHistoryTrimStatus, DatabaseReclaimError, DatabaseStorageStatus, ServerSettings, @@ -599,6 +600,7 @@ export const WS_METHODS = { serverGetStorageCleanupReport: "server.getStorageCleanupReport", serverGetDatabaseStorage: "server.getDatabaseStorage", serverReclaimDatabaseSpace: "server.reclaimDatabaseSpace", + serverGetThreadHistoryTrim: "server.getThreadHistoryTrim", serverPreviewThreadHistoryTrim: "server.previewThreadHistoryTrim", serverTrimThreadHistory: "server.trimThreadHistory", serverGetAgentGateway: "server.getAgentGateway", @@ -966,6 +968,13 @@ const WsServerReclaimDatabaseSpaceRpc = Rpc.make(WS_METHODS.serverReclaimDatabas error: Schema.Union([DatabaseReclaimError, EnvironmentAuthorizationError]), }); +const WsServerGetThreadHistoryTrimRpc = Rpc.make(WS_METHODS.serverGetThreadHistoryTrim, { + payload: Schema.Struct({}), + success: ThreadHistoryTrimStatus, + stream: true, + error: EnvironmentAuthorizationError, +}); + const WsServerPreviewThreadHistoryTrimRpc = Rpc.make(WS_METHODS.serverPreviewThreadHistoryTrim, { payload: Schema.Struct({}), success: ThreadHistoryTrimReport, @@ -2535,6 +2544,7 @@ export const WsRpcGroup = RpcGroup.make( WsServerGetDatabaseStorageRpc, WsServerGetSettingsRpc, WsServerReclaimDatabaseSpaceRpc, + WsServerGetThreadHistoryTrimRpc, WsServerPreviewThreadHistoryTrimRpc, WsServerTrimThreadHistoryRpc, WsServerGetAgentGatewayRpc, diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts index b8d9d43e82aec..9e7bcd0922013 100644 --- a/packages/contracts/src/settings.ts +++ b/packages/contracts/src/settings.ts @@ -153,6 +153,13 @@ export const ThreadHistoryTrimReport = Schema.Struct({ }); export type ThreadHistoryTrimReport = typeof ThreadHistoryTrimReport.Type; +/** ISO times. A pass runs every 30 days; both are null until the first one finishes. */ +export const ThreadHistoryTrimStatus = Schema.Struct({ + lastTrimmedAt: Schema.NullOr(Schema.String), + nextTrimAt: Schema.NullOr(Schema.String), +}); +export type ThreadHistoryTrimStatus = typeof ThreadHistoryTrimStatus.Type; + export const MAX_SNOOZE_PRESET_MINUTES = 30 * 24 * 60; export const MAX_SNOOZE_PRESETS = 8; export const SnoozePresetDay = Schema.Literals([ From 75a06b56efe0d661d54743f73f0b6d3fca99131b Mon Sep 17 00:00:00 2001 From: JJ Eaton <58495321+oldbettie@users.noreply.github.com> Date: Tue, 17 Nov 2026 13:12:55 +0800 Subject: [PATCH 4/4] fix(server): trimming keeps tool output the timeline always shows inline The upstream sync marks HTML renders, viewed images, sent messages and delegated tasks with inline_work_output. Those are part of what a reader sees, so a trim pass leaves them and their parents in place. Co-Authored-By: Claude Fable 5.2 --- .../src/orchestration-v2/ThreadHistoryTrim.test.ts | 12 ++++++++++-- .../src/orchestration-v2/ThreadHistoryTrim.ts | 14 ++++++++++++-- 2 files changed, 22 insertions(+), 4 deletions(-) diff --git a/apps/server/src/orchestration-v2/ThreadHistoryTrim.test.ts b/apps/server/src/orchestration-v2/ThreadHistoryTrim.test.ts index 9a0e02e17c0f1..667a6e8e2ef0f 100644 --- a/apps/server/src/orchestration-v2/ThreadHistoryTrim.test.ts +++ b/apps/server/src/orchestration-v2/ThreadHistoryTrim.test.ts @@ -219,6 +219,13 @@ const seedThread = Effect.fn(function* (name: string, options: SeedOptions = {}) type: "file_change", fileName: "harness.ts", }), + item({ + ...itemBase("sent"), + type: "dynamic_tool", + toolName: "mcp__t3-code__send_to_user", + input: null, + output: "The draft the user was asked to read.", + }), item({ ...itemBase("assistant"), type: "assistant_message", @@ -242,8 +249,9 @@ const itemTitles = Effect.fn(function* (threadId: ThreadId) { return rows.map((row) => row.title); }); -const everyItem = ["user", "reasoning", "command", "tool", "edit", "assistant"]; -const trimmedItems = ["user", "tool", "edit", "assistant", "Older detail was trimmed"]; +const everyItem = ["user", "reasoning", "command", "tool", "edit", "sent", "assistant"]; +// `sent` stays: the timeline always shows that output inline. +const trimmedItems = ["user", "tool", "edit", "sent", "assistant", "Older detail was trimmed"]; const trim = Effect.gen(function* () { const service = yield* ThreadHistoryTrim.ThreadHistoryTrim; diff --git a/apps/server/src/orchestration-v2/ThreadHistoryTrim.ts b/apps/server/src/orchestration-v2/ThreadHistoryTrim.ts index 93d78e76d9282..0d84c25d15e41 100644 --- a/apps/server/src/orchestration-v2/ThreadHistoryTrim.ts +++ b/apps/server/src/orchestration-v2/ThreadHistoryTrim.ts @@ -50,7 +50,8 @@ const PASS_INTERVAL_MS = 30 * DAY_MS; const LAST_PASS = "thread-history-trim-last-pass"; const DELETE_PAGE_SIZE = 200; const NOTICE_SIGNAL = "history-trim"; -// Work the reader skips: `file_change` stays because it is small and names what a run touched. +// Work the reader skips: `file_change` stays because it is small and names what a run touched, +// and so does output the timeline always shows inline (`inline_work_output`). const TRIMMED_ITEM_TYPES = [ "command_execution", "dynamic_tool", @@ -166,6 +167,7 @@ const make = Effect.gen(function* () { SELECT 1 FROM orchestration_v2_projection_turn_items AS item WHERE item.thread_id = thread.thread_id AND item.type IN ${sql.in(TRIMMED_ITEM_TYPES)} + AND item.inline_work_output = 0 AND item.status NOT IN ${sql.in(LIVE_ITEM_STATUSES)} -- A trimmed thread keeps the tool items its kept items hang off. AND NOT EXISTS ( @@ -197,10 +199,12 @@ const make = Effect.gen(function* () { (SELECT COUNT(*) FROM orchestration_v2_projection_turn_items WHERE thread_id = ${candidate.threadId} AND type IN ${sql.in(TRIMMED_ITEM_TYPES)} + AND inline_work_output = 0 AND status NOT IN ${sql.in(LIVE_ITEM_STATUSES)}) AS items, COALESCE((SELECT SUM(${sql.literal(ITEM_BYTES)}) FROM orchestration_v2_projection_turn_items WHERE thread_id = ${candidate.threadId} AND type IN ${sql.in(TRIMMED_ITEM_TYPES)} + AND inline_work_output = 0 AND status NOT IN ${sql.in(LIVE_ITEM_STATUSES)}), 0) + COALESCE((SELECT SUM(${sql.literal(nodeBytes(""))}) FROM orchestration_v2_projection_nodes WHERE thread_id = ${candidate.threadId} @@ -294,6 +298,7 @@ const make = Effect.gen(function* () { readonly parent: string | null; readonly type: string; readonly status: string; + readonly inline: number; readonly bytes: number; }>` SELECT @@ -301,6 +306,7 @@ const make = Effect.gen(function* () { parent_item_id AS parent, type, status, + inline_work_output AS inline, ${sql.literal(ITEM_BYTES)} AS bytes FROM orchestration_v2_projection_turn_items WHERE thread_id = ${threadId} AND ordinal < ${boundary} @@ -309,7 +315,10 @@ const make = Effect.gen(function* () { const liveItemStatuses: ReadonlyArray = LIVE_ITEM_STATUSES; const removedItems = unreferenced( items, - (item) => trimmedItemTypes.includes(item.type) && !liveItemStatuses.includes(item.status), + (item) => + trimmedItemTypes.includes(item.type) && + item.inline === 0 && + !liveItemStatuses.includes(item.status), [], ); yield* deleteInPages( @@ -321,6 +330,7 @@ const make = Effect.gen(function* () { DELETE FROM orchestration_v2_projection_turn_items WHERE turn_item_id IN ${sql.in(page)} AND status NOT IN ${sql.in(LIVE_ITEM_STATUSES)} + AND inline_work_output = 0 `; yield* sql` DELETE FROM orchestration_v2_turn_item_positions