From 6c6fa1db20675012e3ea6b6682d087606996ea67 Mon Sep 17 00:00:00 2001 From: liugddx Date: Tue, 29 Sep 2026 17:47:45 +0800 Subject: [PATCH 1/4] feat(storage): report task storage usage Add a read-only Runtime Host query, `storage.usage.query`, that reports how much space the State Root uses, and show it in Desktop Settings. Nothing here deletes, compacts or changes stored data. Storage measures cheaply without write-path counters or triggers: file sizes of runtime.sqlite (+wal/shm) and memory.sqlite, `octet_length`/`length` sums over the per-Session tables through their existing session_id indexes, artifact `sizeBytes`, context-offload usage, `PRAGMA freelist_count * page_size` for reclaimable space, and a count of subagent worktree directories. The totals are non-overlapping: transcript, runtime and usage history are logical bytes inside runtime.sqlite and `database` is the remainder of that file set. The Host shares one totals scan between concurrent callers and for 15s; per-Session figures are always read fresh. Input takes up to 100 sessionIds and the result echoes them in order. The query is admitted for remote owners like `host.resources.query`. Compatibility epoch 198 -> 199 for the new operation. Desktop adds a storage-usage feature slice: a Storage group on the Data page after the data location group, and a per-task size on archived task rows, measured only for rows that mount and batched into one query per Host. Copy notes that per-task offloaded context is logical and that usage history is kept after deletion. Co-Authored-By: Claude Opus 5.5 (1M context) --- apps/desktop/renderer-architecture.json | 13 + .../__tests__/session-storage-loader.test.ts | 62 ++++ .../__tests__/storage-usage-section.test.ts | 109 ++++++ .../main/runtime-host-renderer-ipc-main.ts | 2 + apps/desktop/src/preload/bridge-contract.d.ts | 15 +- apps/desktop/src/preload/preload.ts | 53 +++ .../runtime-host-renderer-operations.ts | 2 + .../composition/desktop-feature-services.tsx | 7 +- .../renderer/features/storage-usage/index.ts | 26 ++ .../model/format-storage-size.ts | 38 ++ .../model/session-storage-loader.ts | 90 +++++ .../renderer/features/storage-usage/ports.ts | 42 +++ .../storage-usage/services-context.tsx | 39 ++ .../features/storage-usage/testing.ts | 24 ++ .../ui/storage-usage-section.tsx | 161 +++++++++ .../storage-usage/ui/task-storage-size.tsx | 80 +++++ .../renderer/locales/storage-usage-copy.ts | 164 +++++++++ .../desktop/create-storage-usage-services.ts | 35 ++ .../renderer/settings/data-settings-page.tsx | 4 + .../renderer/settings/tasks-settings-page.tsx | 107 +++--- docs/astryx-surface-file-inventory.md | 5 +- docs/astryx-surface-file-inventory.paths | 3 + .../storage-usage-coordinator.test.ts | 135 +++++++ .../__tests__/storage-usage-protocol.test.ts | 131 +++++++ packages/runtime-host/src/protocol/index.ts | 4 +- .../runtime-host/src/protocol/operations.ts | 4 + .../src/protocol/storage-usage.ts | 218 ++++++++++++ .../src/server/execution-composition.ts | 7 + .../src/server/operation-dispatcher.ts | 3 + .../src/server/storage-usage-coordinator.ts | 115 ++++++ .../src/__tests__/storage-footprint.test.ts | 197 +++++++++++ packages/storage/src/storage-footprint.ts | 332 ++++++++++++++++++ .../storage/src/storage-writer-composition.ts | 41 ++- 33 files changed, 2212 insertions(+), 56 deletions(-) create mode 100644 apps/desktop/src/main/__tests__/session-storage-loader.test.ts create mode 100644 apps/desktop/src/main/__tests__/storage-usage-section.test.ts create mode 100644 apps/desktop/src/renderer/features/storage-usage/index.ts create mode 100644 apps/desktop/src/renderer/features/storage-usage/model/format-storage-size.ts create mode 100644 apps/desktop/src/renderer/features/storage-usage/model/session-storage-loader.ts create mode 100644 apps/desktop/src/renderer/features/storage-usage/ports.ts create mode 100644 apps/desktop/src/renderer/features/storage-usage/services-context.tsx create mode 100644 apps/desktop/src/renderer/features/storage-usage/testing.ts create mode 100644 apps/desktop/src/renderer/features/storage-usage/ui/storage-usage-section.tsx create mode 100644 apps/desktop/src/renderer/features/storage-usage/ui/task-storage-size.tsx create mode 100644 apps/desktop/src/renderer/locales/storage-usage-copy.ts create mode 100644 apps/desktop/src/renderer/platform/desktop/create-storage-usage-services.ts create mode 100644 packages/runtime-host/src/__tests__/storage-usage-coordinator.test.ts create mode 100644 packages/runtime-host/src/__tests__/storage-usage-protocol.test.ts create mode 100644 packages/runtime-host/src/protocol/storage-usage.ts create mode 100644 packages/runtime-host/src/server/storage-usage-coordinator.ts create mode 100644 packages/storage/src/__tests__/storage-footprint.test.ts create mode 100644 packages/storage/src/storage-footprint.ts diff --git a/apps/desktop/renderer-architecture.json b/apps/desktop/renderer-architecture.json index e7bf529576d..61914a9d607 100644 --- a/apps/desktop/renderer-architecture.json +++ b/apps/desktop/renderer-architecture.json @@ -76,6 +76,7 @@ "src/renderer/locales/settings-web-search-copy.ts", "src/renderer/locales/shell-copy.ts", "src/renderer/locales/shell-remaining-copy.ts", + "src/renderer/locales/storage-usage-copy.ts", "src/renderer/locales/task-readiness-copy.ts", "src/renderer/locales/work-board-error-copy.ts", "src/renderer/main.tsx", @@ -1505,6 +1506,15 @@ "actionFactories": [], "dependencyPaths": {} }, + "src/renderer/locales/storage-usage-copy.ts": { + "bridgePaths": {}, + "environmentCapabilities": {}, + "hookCalls": {}, + "lifecycleMethods": {}, + "unresolvedDependencies": 0, + "actionFactories": [], + "dependencyPaths": {} + }, "src/renderer/locales/task-readiness-copy.ts": { "bridgePaths": {}, "environmentCapabilities": {}, @@ -2107,6 +2117,7 @@ "unresolvedDependencies": 0, "actionFactories": [], "dependencyPaths": { + "../features/storage-usage/index.js": 1, "../locales/settings-data-copy": 1, "../locales/settings-shared-copy.js": 1, "../open-path": 1, @@ -3218,8 +3229,10 @@ "unresolvedDependencies": 0, "actionFactories": [], "dependencyPaths": { + "../features/storage-usage/index.js": 1, "../locales/settings-shared-copy.js": 1, "../locales/settings-tasks-copy.js": 1, + "../locales/storage-usage-copy.js": 1, "./settings-error-copy": 1, "./settings-section": 1, "./task-catalog-rows": 1, diff --git a/apps/desktop/src/main/__tests__/session-storage-loader.test.ts b/apps/desktop/src/main/__tests__/session-storage-loader.test.ts new file mode 100644 index 00000000000..d1d7cd8ebf4 --- /dev/null +++ b/apps/desktop/src/main/__tests__/session-storage-loader.test.ts @@ -0,0 +1,62 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { strict as assert } from 'node:assert'; +import { test } from 'node:test'; +import type { SessionStorageUsage } from '@maka/runtime-host/protocol'; +import { createSessionStorageLoader } from '../../renderer/features/storage-usage/testing.js'; + +function usage(sessionId: string): SessionStorageUsage { + return { sessionId, bytes: { transcript: 1, runtime: 2, artifacts: 3 }, worktreeCount: 0 }; +} + +test('rows that mount together share bounded queries and are measured once', async () => { + const queries: string[][] = []; + const loader = createSessionStorageLoader(async (sessionIds) => { + queries.push([...sessionIds]); + return Object.fromEntries(sessionIds.map((id) => [id, usage(id)])); + }); + const ids = Array.from({ length: 101 }, (_, index) => `session-${index}`); + const measured = await Promise.all([...ids, 'session-0'].map((id) => loader.load(id))); + assert.deepEqual( + queries.map((query) => query.length), + [100, 1], + ); + assert.equal(measured[0]?.sessionId, 'session-0'); + assert.equal(measured[101], measured[0]); + + await loader.load('session-5'); + assert.equal(queries.length, 2, 'a measured row is served from the list cache'); +}); + +test('a failed or missing measurement renders nothing and is retried later', async () => { + let fail = true; + const queries: string[][] = []; + const loader = createSessionStorageLoader(async (sessionIds) => { + queries.push([...sessionIds]); + if (fail) throw new Error('Runtime Host unavailable'); + return { 'session-a': usage('session-a') }; + }); + assert.equal(await loader.load('session-a'), undefined); + fail = false; + assert.equal((await loader.load('session-a'))?.sessionId, 'session-a'); + assert.equal(await loader.load('session-gone'), undefined); + assert.equal(await loader.load('session-gone'), undefined); + assert.deepEqual(queries, [['session-a'], ['session-a'], ['session-gone'], ['session-gone']]); +}); diff --git a/apps/desktop/src/main/__tests__/storage-usage-section.test.ts b/apps/desktop/src/main/__tests__/storage-usage-section.test.ts new file mode 100644 index 00000000000..c8d7928b9b6 --- /dev/null +++ b/apps/desktop/src/main/__tests__/storage-usage-section.test.ts @@ -0,0 +1,109 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { strict as assert } from 'node:assert'; +import { afterEach, test } from 'node:test'; +import { parseHTML } from 'linkedom'; +import { act, createElement } from 'react'; +import { createRoot } from 'react-dom/client'; +import { AstryxLocaleProvider, LocaleProvider, ToastProvider } from '@maka/ui'; +import type { StorageUsageQueryResult } from '@maka/runtime-host/protocol'; +import { + StorageUsageSection, + StorageUsageServicesProvider, + type StorageUsageHostTarget, +} from '../../renderer/features/storage-usage/index.js'; +import { RuntimeHostSettingsTarget } from '../../renderer/settings/runtime-host-settings-target.js'; + +const originalGlobals = { + document: globalThis.document, + window: globalThis.window, + HTMLElement: globalThis.HTMLElement, + getComputedStyle: globalThis.getComputedStyle, + IS_REACT_ACT_ENVIRONMENT: (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }) + .IS_REACT_ACT_ENVIRONMENT, +}; + +afterEach(() => { + Object.assign(globalThis, originalGlobals); +}); + +test('the Storage section reads the selected Host once and states its caveats', async () => { + const { document, window } = parseHTML('
'); + Object.assign(globalThis, { + document, + window, + HTMLElement: window.HTMLElement, + getComputedStyle: (element: Element) => + ({ color: (element as HTMLElement).style?.color || 'currentColor' }) as CSSStyleDeclaration, + IS_REACT_ACT_ENVIRONMENT: true, + }); + const host = { profileId: 'profile-1', hostId: 'host-1' }; + const requests: StorageUsageHostTarget[] = []; + const usage: StorageUsageQueryResult = { + measuredAt: 1, + totals: [ + { kind: 'database', bytes: 3 * 1024 * 1024, exact: false }, + { kind: 'artifacts', bytes: 1024 * 1024, exact: true }, + { kind: 'usage_history', bytes: 2048, exact: false }, + ], + reclaimableBytes: 512 * 1024, + worktreeCount: 2, + }; + const container = document.getElementById('root') as unknown as HTMLElement; + const root = createRoot(container); + await act(async () => { + root.render( + createElement(LocaleProvider, { + locale: 'en', + children: createElement(AstryxLocaleProvider, { + children: createElement(ToastProvider, { + children: createElement(StorageUsageServicesProvider, { + services: { + loadUsage: async (target) => { + requests.push(target); + return usage; + }, + loadSessionUsage: async () => ({}), + }, + children: createElement(RuntimeHostSettingsTarget, { + host, + children: createElement(StorageUsageSection, { hostVerified: true }), + }), + }), + }), + }), + }), + ); + }); + + const text = container.textContent ?? ''; + assert.deepEqual(requests, [host]); + assert.match(text, /Total/); + assert.match(text, /≈ 4 MB/); + assert.match(text, /Artifacts/); + assert.match(text, /Kept after a task is deleted/); + assert.match(text, /2 worktrees/); + assert.match(text, /512 kB/); + // Only measured kinds are listed; nothing offers to delete or compact. + assert.doesNotMatch(text, /Offloaded context/); + assert.doesNotMatch(text, /Delete|Compact|Vacuum/); + + await act(async () => root.unmount()); +}); diff --git a/apps/desktop/src/main/runtime-host-renderer-ipc-main.ts b/apps/desktop/src/main/runtime-host-renderer-ipc-main.ts index 611b2023a1a..9399b672ce2 100644 --- a/apps/desktop/src/main/runtime-host-renderer-ipc-main.ts +++ b/apps/desktop/src/main/runtime-host-renderer-ipc-main.ts @@ -100,6 +100,8 @@ function request( return client.request(operation, HOST_OPERATION_SPECS[operation].decodeInput(value)); case 'scheduled-task.query': return client.request(operation, HOST_OPERATION_SPECS[operation].decodeInput(value)); + case 'storage.usage.query': + return client.request(operation, HOST_OPERATION_SPECS[operation].decodeInput(value)); case 'web-search.execute': return client.request(operation, HOST_OPERATION_SPECS[operation].decodeInput(value)); } diff --git a/apps/desktop/src/preload/bridge-contract.d.ts b/apps/desktop/src/preload/bridge-contract.d.ts index d3db91690bd..8c6122825b5 100644 --- a/apps/desktop/src/preload/bridge-contract.d.ts +++ b/apps/desktop/src/preload/bridge-contract.d.ts @@ -154,7 +154,11 @@ import type { import type { SessionTrace } from '@maka/core/session-trace'; import type { UsageSummaryV2 } from '@maka/core/usage-stats/types'; import type { UsageProvenance } from '@maka/core/usage-ledger-merge'; -import type { ContextDiagnosticsResult } from '@maka/runtime-host/protocol'; +import type { + ContextDiagnosticsResult, + SessionStorageUsage, + StorageUsageQueryResult, +} from '@maka/runtime-host/protocol'; import type { TestProxyInput } from '@maka/core/settings/network-settings'; import type { ExternalSessionImportIpcResult } from './external-session-import-result.js'; /** @@ -1834,6 +1838,15 @@ export interface MakaBridge { }, host?: DesktopRuntimeHostRef): Promise; test(input: { provider?: WebSearchProvider; apiKey?: string }, host?: DesktopRuntimeHostRef): Promise; }; + storage: { + /** One Runtime Host's State Root footprint. Read-only; nothing is reclaimed. */ + usage(host?: DesktopRuntimeHostRef): Promise; + /** + * Per-task storage keyed by Desktop session id. A task whose Runtime Host is + * unavailable is absent from the result rather than failing the others. + */ + sessionUsage(sessionIds: readonly string[]): Promise>; + }; dailyReview: { day(offsetDays: number, daySpan?: number, host?: DesktopRuntimeHostRef): Promise>; getConfig?(host?: DesktopRuntimeHostRef): Promise; diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts index 58a87563bef..0232f5c6edd 100644 --- a/apps/desktop/src/preload/preload.ts +++ b/apps/desktop/src/preload/preload.ts @@ -251,12 +251,15 @@ import type { OnboardingMilestoneId } from '@maka/core/onboarding'; import { decodeSharedSessionCatalogProjection, SCHEDULED_TASK_CATALOG_MAX_ITEMS, + STORAGE_USAGE_SESSION_MAX_ITEMS, type OperationInput, type OperationOutcome, type OperationOutput, type CollaborationTurnRequestQueryResult, type CollaborationTurnRequestWithdrawResult, type SessionTurnAccessRequest, + type SessionStorageUsage, + type StorageUsageQueryResult, } from '@maka/runtime-host/protocol'; import type { PlanControlIpcResult } from '../shared/plan-mode-ipc.js'; import type { AgentGraphEpochDirectory } from '@maka/runtime-host/client'; @@ -1246,6 +1249,48 @@ const runtimeHost: MakaBridge['runtimeHost'] = { }, }; +/** + * Per-task storage keyed by Desktop session id. Tasks are grouped by the Host + * that owns them; a task whose Host is unavailable is left out rather than + * failing the rest. + */ +async function loadSessionStorageUsage( + sessionIds: readonly string[], +): Promise> { + const byScope = new Map< + RuntimeHostScopeKey, + { scope: DesktopTargetScope; desktopIds: Map } + >(); + for (const sessionId of new Set(sessionIds)) { + let ref: Awaited>; + try { + ref = await runtimeHostSessionRef(sessionId); + } catch { + continue; + } + const key = runtimeHostScopeKey(ref.scope); + const group = byScope.get(key) ?? { scope: ref.scope, desktopIds: new Map() }; + group.desktopIds.set(ref.sessionId, sessionId); + byScope.set(key, group); + } + const usage: Record = {}; + await Promise.all( + [...byScope.values()].map(async ({ scope, desktopIds }) => { + const hostIds = [...desktopIds.keys()]; + for (let offset = 0; offset < hostIds.length; offset += STORAGE_USAGE_SESSION_MAX_ITEMS) { + const result = await scopedRuntimeHost(scope).query('storage.usage.query', { + sessionIds: hostIds.slice(offset, offset + STORAGE_USAGE_SESSION_MAX_ITEMS), + }); + for (const session of result.sessions ?? []) { + const desktopId = desktopIds.get(session.sessionId); + if (desktopId) usage[desktopId] = session; + } + } + }), + ); + return usage; +} + async function listScheduledTasks(target?: DesktopRuntimeHostRef): Promise { const host = scopedRuntimeHost(await selectedRuntimeHostScope(target)); for (let attempt = 0; attempt < 3; attempt += 1) { @@ -3695,6 +3740,14 @@ const makaBridge = { ); }, }, + storage: { + async usage(host?: DesktopRuntimeHostRef): Promise { + return scopedRuntimeHost(await selectedRuntimeHostScope(host)).query('storage.usage.query', {}); + }, + sessionUsage(sessionIds: readonly string[]): Promise> { + return loadSessionStorageUsage(sessionIds); + }, + }, dailyReview: { day(offsetDays: number, daySpan?: number, host?: DesktopRuntimeHostRef): Promise> { return bridgeResult(async () => { diff --git a/apps/desktop/src/preload/runtime-host-renderer-operations.ts b/apps/desktop/src/preload/runtime-host-renderer-operations.ts index 1e6b2da5d4e..a0645d0433a 100644 --- a/apps/desktop/src/preload/runtime-host-renderer-operations.ts +++ b/apps/desktop/src/preload/runtime-host-renderer-operations.ts @@ -27,6 +27,8 @@ export const RENDERER_RUNTIME_HOST_QUERY_OPERATIONS = [ 'daily-review.query', 'execution.inspect.query', 'scheduled-task.query', + // Read-only State Root and per-task size measurement; it reclaims nothing. + 'storage.usage.query', ] as const satisfies readonly (keyof OperationSpecMap)[]; export const RENDERER_RUNTIME_HOST_COMMAND_OPERATIONS = [ diff --git a/apps/desktop/src/renderer/composition/desktop-feature-services.tsx b/apps/desktop/src/renderer/composition/desktop-feature-services.tsx index ef810943747..4f15420defe 100644 --- a/apps/desktop/src/renderer/composition/desktop-feature-services.tsx +++ b/apps/desktop/src/renderer/composition/desktop-feature-services.tsx @@ -48,6 +48,8 @@ import { createDesktopRuntimeHostManagementServices } from '../platform/desktop/ import { createDesktopSessionCollaborationServices } from '../platform/desktop/create-session-collaboration-services'; import { createDesktopSessionNavigationServices } from '../platform/desktop/create-session-navigation-services'; import { SessionBundleServicesProvider } from '../features/session-bundle'; +import { StorageUsageServicesProvider } from '../features/storage-usage'; +import { createDesktopStorageUsageServices } from '../platform/desktop/create-storage-usage-services.js'; import { createDesktopSessionBundleServices } from '../platform/desktop/create-session-bundle-services.js'; import { createDesktopSessionSettingsServices } from '../platform/desktop/create-session-settings-services'; import { createDesktopTaskEntryServices } from '../platform/desktop/create-task-entry-services'; @@ -85,6 +87,7 @@ export function createDesktopFeatureServices() { sessionNavigation: createDesktopSessionNavigationServices(), sessionBundle: createDesktopSessionBundleServices(), sessionSettings: createDesktopSessionSettingsServices(), + storageUsage: createDesktopStorageUsageServices(), taskEntry: createDesktopTaskEntryServices(), workbar: createDesktopWorkbarServices(), }; @@ -113,7 +116,9 @@ export function DesktopFeatureServicesProvider(props: { - {props.children} + + {props.children} + diff --git a/apps/desktop/src/renderer/features/storage-usage/index.ts b/apps/desktop/src/renderer/features/storage-usage/index.ts new file mode 100644 index 00000000000..7e3b987206d --- /dev/null +++ b/apps/desktop/src/renderer/features/storage-usage/index.ts @@ -0,0 +1,26 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +// Public API of the storage usage feature. Legacy Settings pages import only +// from this barrel and render these surfaces; they hold no storage state. + +export { StorageUsageSection } from './ui/storage-usage-section.js'; +export { TaskStorageSize, TaskStorageSizeScope } from './ui/task-storage-size.js'; +export { StorageUsageServicesProvider } from './services-context.js'; +export type { StorageUsageHostTarget, StorageUsageServices } from './ports.js'; diff --git a/apps/desktop/src/renderer/features/storage-usage/model/format-storage-size.ts b/apps/desktop/src/renderer/features/storage-usage/model/format-storage-size.ts new file mode 100644 index 00000000000..b3549219981 --- /dev/null +++ b/apps/desktop/src/renderer/features/storage-usage/model/format-storage-size.ts @@ -0,0 +1,38 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import type { UiLocale } from '@maka/core/ui-locale'; + +const UNITS = ['byte', 'kilobyte', 'megabyte', 'gigabyte', 'terabyte'] as const; + +/** Binary-scaled byte size in the reader's locale, e.g. "1.5 GB". */ +export function formatStorageSize(bytes: number, locale: UiLocale): string { + let value = Math.max(0, bytes); + let unit = 0; + while (value >= 1024 && unit < UNITS.length - 1) { + value /= 1024; + unit += 1; + } + return new Intl.NumberFormat(locale, { + style: 'unit', + unit: UNITS[unit], + unitDisplay: 'short', + maximumFractionDigits: unit === 0 || value >= 100 ? 0 : 1, + }).format(value); +} diff --git a/apps/desktop/src/renderer/features/storage-usage/model/session-storage-loader.ts b/apps/desktop/src/renderer/features/storage-usage/model/session-storage-loader.ts new file mode 100644 index 00000000000..a202ed3cc54 --- /dev/null +++ b/apps/desktop/src/renderer/features/storage-usage/model/session-storage-loader.ts @@ -0,0 +1,90 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import type { SessionStorageUsage } from '@maka/runtime-host/protocol'; + +/** One Host query measures at most this many Sessions. */ +const BATCH_SIZE = 100; + +export interface SessionStorageLoader { + /** Resolves undefined when the size could not be measured. */ + load(sessionId: string): Promise; +} + +/** + * Coalesces the size requests of rows that mount together into one query, so + * a list asks for exactly the rows it renders. Results live as long as the + * loader; a failed measurement is forgotten so a later row can retry it. + */ +export function createSessionStorageLoader( + loadSessionUsage: ( + sessionIds: readonly string[], + ) => Promise>>, +): SessionStorageLoader { + const results = new Map>(); + let pending = new Map void>(); + let scheduled = false; + + const flush = () => { + scheduled = false; + const batch = pending; + pending = new Map(); + const ids = [...batch.keys()]; + for (let offset = 0; offset < ids.length; offset += BATCH_SIZE) { + const chunk = ids.slice(offset, offset + BATCH_SIZE); + loadSessionUsage(chunk).then( + (usage) => { + for (const id of chunk) { + const measured = usage[id]; + if (!measured) results.delete(id); + batch.get(id)?.(measured); + } + }, + () => { + for (const id of chunk) { + results.delete(id); + batch.get(id)?.(undefined); + } + }, + ); + } + }; + + return { + load(sessionId) { + const existing = results.get(sessionId); + if (existing) return existing; + const result = new Promise((resolve) => { + pending.set(sessionId, resolve); + }); + results.set(sessionId, result); + if (!scheduled) { + scheduled = true; + void Promise.resolve().then(flush); + } + return result; + }, + }; +} + +/** Everything a task holds on the Host, counting shared context once per task. */ +export function sessionStorageBytes(usage: SessionStorageUsage): number { + const { transcript, runtime, artifacts, context = 0 } = usage.bytes; + return transcript + runtime + artifacts + context; +} diff --git a/apps/desktop/src/renderer/features/storage-usage/ports.ts b/apps/desktop/src/renderer/features/storage-usage/ports.ts new file mode 100644 index 00000000000..dbc4c7235ca --- /dev/null +++ b/apps/desktop/src/renderer/features/storage-usage/ports.ts @@ -0,0 +1,42 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import type { SessionStorageUsage, StorageUsageQueryResult } from '@maka/runtime-host/protocol'; + +/** The Runtime Host a Settings page is pointed at, stated structurally. */ +export interface StorageUsageHostTarget { + readonly profileId: string; + readonly hostId: string; +} + +/** + * What the storage usage feature needs from the Desktop: two read-only + * measurements. Nothing here reclaims or deletes data. + */ +export interface StorageUsageServices { + /** One Runtime Host's State Root footprint. */ + loadUsage(host: StorageUsageHostTarget): Promise; + /** + * Per-task storage keyed by Desktop session id. A task whose Host cannot be + * reached is absent rather than failing the rest. + */ + loadSessionUsage( + sessionIds: readonly string[], + ): Promise>>; +} diff --git a/apps/desktop/src/renderer/features/storage-usage/services-context.tsx b/apps/desktop/src/renderer/features/storage-usage/services-context.tsx new file mode 100644 index 00000000000..6dcecf05c1b --- /dev/null +++ b/apps/desktop/src/renderer/features/storage-usage/services-context.tsx @@ -0,0 +1,39 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { createContext, type ReactNode, useContext } from 'react'; +import type { StorageUsageServices } from './ports.js'; + +const StorageUsageServicesContext = createContext(undefined); + +export function StorageUsageServicesProvider(props: { + readonly services: StorageUsageServices; + readonly children?: ReactNode; +}) { + return ( + + {props.children} + + ); +} + +/** Undefined outside a Desktop composition; the surfaces then render nothing. */ +export function useOptionalStorageUsageServices(): StorageUsageServices | undefined { + return useContext(StorageUsageServicesContext); +} diff --git a/apps/desktop/src/renderer/features/storage-usage/testing.ts b/apps/desktop/src/renderer/features/storage-usage/testing.ts new file mode 100644 index 00000000000..fdc6b7b5126 --- /dev/null +++ b/apps/desktop/src/renderer/features/storage-usage/testing.ts @@ -0,0 +1,24 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +/** + * Test-only surface. The loader is where row requests become Host queries, so + * its batching and retry rules are worth checking without mounting a list. + */ +export { createSessionStorageLoader } from './model/session-storage-loader.js'; diff --git a/apps/desktop/src/renderer/features/storage-usage/ui/storage-usage-section.tsx b/apps/desktop/src/renderer/features/storage-usage/ui/storage-usage-section.tsx new file mode 100644 index 00000000000..9512b500ad8 --- /dev/null +++ b/apps/desktop/src/renderer/features/storage-usage/ui/storage-usage-section.tsx @@ -0,0 +1,161 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { useEffect, useState } from 'react'; +import { Banner } from '@astryxdesign/core/Banner'; +import { Button, useUiLocale } from '@maka/ui'; +import type { StorageUsageKind, StorageUsageQueryResult } from '@maka/runtime-host/protocol'; +import { + SettingsRow, + SettingsSection, + useOptionalRuntimeHostSettingsTarget, +} from '../../../application/contracts/settings-presentation/index.js'; +import { getStorageUsageCopy } from '../../../locales/storage-usage-copy.js'; +import { formatStorageSize } from '../model/format-storage-size.js'; +import { useOptionalStorageUsageServices } from '../services-context.js'; + +/** Largest-first would reorder between measurements; a fixed order reads the same each visit. */ +const KIND_ORDER: readonly StorageUsageKind[] = [ + 'transcript', + 'runtime', + 'artifacts', + 'context_offload', + 'memory', + 'usage_history', + 'database', +]; + +type Measurement = + | { readonly status: 'loading'; readonly previous?: StorageUsageQueryResult } + | { readonly status: 'ready'; readonly usage: StorageUsageQueryResult } + | { readonly status: 'failed' }; + +/** + * Settings · Data · Storage: what the selected Runtime Host's data occupies. + * Read-only by design; it offers no action that deletes or compacts data. + */ +export function StorageUsageSection(props: { readonly hostVerified: boolean }) { + const host = useOptionalRuntimeHostSettingsTarget(); + const services = useOptionalStorageUsageServices(); + const locale = useUiLocale(); + const copy = getStorageUsageCopy(locale); + const [measurement, setMeasurement] = useState({ status: 'loading' }); + const [attempt, setAttempt] = useState(0); + + useEffect(() => { + if (!host || !services || !props.hostVerified) return; + let current = true; + setMeasurement((previous) => ({ + status: 'loading', + ...(previous.status === 'ready' ? { previous: previous.usage } : {}), + })); + services.loadUsage(host).then( + (usage) => { + if (current) setMeasurement({ status: 'ready', usage }); + }, + () => { + if (current) setMeasurement({ status: 'failed' }); + }, + ); + return () => { + current = false; + }; + }, [attempt, host, props.hostVerified, services]); + + if (!host || !services) return null; + const usage = + measurement.status === 'ready' + ? measurement.usage + : measurement.status === 'loading' + ? measurement.previous + : undefined; + const size = (bytes: number, exact: boolean) => { + const formatted = formatStorageSize(bytes, locale); + return exact ? formatted : copy.approximately(formatted); + }; + const totals = usage + ? KIND_ORDER.flatMap((kind) => usage.totals.filter((total) => total.kind === kind)) + : []; + const totalBytes = totals.reduce((sum, total) => sum + total.bytes, 0); + const placeholder = measurement.status === 'failed' ? copy.loadFailed : copy.loading; + + return ( + setAttempt((value) => value + 1)} + /> + )} + > + {measurement.status === 'failed' ? ( + + ) : null} + + {usage ? size(totalBytes, totals.every((total) => total.exact)) : placeholder} + + )} + /> + {totals.map((total) => ( + {size(total.bytes, total.exact)}} + /> + ))} + {usage ? ( + <> + + {formatStorageSize(usage.reclaimableBytes, locale)} + + )} + /> + + {copy.worktreeCount(usage.worktreeCount)} + + )} + /> + + ) : null} + + ); +} diff --git a/apps/desktop/src/renderer/features/storage-usage/ui/task-storage-size.tsx b/apps/desktop/src/renderer/features/storage-usage/ui/task-storage-size.tsx new file mode 100644 index 00000000000..25f0d13c531 --- /dev/null +++ b/apps/desktop/src/renderer/features/storage-usage/ui/task-storage-size.tsx @@ -0,0 +1,80 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { createContext, type ReactNode, useContext, useEffect, useState } from 'react'; +import { Text } from '@astryxdesign/core/Text'; +import { useUiLocale } from '@maka/ui'; +import type { SessionStorageUsage } from '@maka/runtime-host/protocol'; +import { getStorageUsageCopy } from '../../../locales/storage-usage-copy.js'; +import { formatStorageSize } from '../model/format-storage-size.js'; +import { + createSessionStorageLoader, + sessionStorageBytes, + type SessionStorageLoader, +} from '../model/session-storage-loader.js'; +import { useOptionalStorageUsageServices } from '../services-context.js'; + +const SessionStorageLoaderContext = createContext(undefined); + +/** + * Owns the per-task size cache for one list. Rows measure themselves as they + * mount, and rows mounted together share one Host query, so only the rows on + * screen are ever measured. + */ +export function TaskStorageSizeScope(props: { readonly children?: ReactNode }) { + const services = useOptionalStorageUsageServices(); + const [loader] = useState(() => + services + ? createSessionStorageLoader((sessionIds) => services.loadSessionUsage(sessionIds)) + : undefined, + ); + return ( + + {props.children} + + ); +} + +/** A task's measured size, or nothing while unknown. Never a guess. */ +export function TaskStorageSize(props: { readonly sessionId: string }) { + const loader = useContext(SessionStorageLoaderContext); + const locale = useUiLocale(); + const [usage, setUsage] = useState(undefined); + + useEffect(() => { + if (!loader) return; + let current = true; + setUsage(undefined); + void loader.load(props.sessionId).then((measured) => { + if (current) setUsage(measured); + }); + return () => { + current = false; + }; + }, [loader, props.sessionId]); + + if (!usage) return null; + return ( + + {getStorageUsageCopy(locale).taskSize( + formatStorageSize(sessionStorageBytes(usage), locale), + )} + + ); +} diff --git a/apps/desktop/src/renderer/locales/storage-usage-copy.ts b/apps/desktop/src/renderer/locales/storage-usage-copy.ts new file mode 100644 index 00000000000..349b90b5fae --- /dev/null +++ b/apps/desktop/src/renderer/locales/storage-usage-copy.ts @@ -0,0 +1,164 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import type { UiCatalog, UiLocale } from '@maka/core/ui-locale'; + +type StorageUsageKindCopy = { label: string; detail: string }; + +export type StorageUsageCopy = { + title: string; + help: string; + loading: string; + loadFailed: string; + refresh: string; + total: string; + totalDetail: string; + kinds: Record< + | 'transcript' + | 'runtime' + | 'artifacts' + | 'context_offload' + | 'memory' + | 'usage_history' + | 'database', + StorageUsageKindCopy + >; + reclaimable: string; + reclaimableDetail: string; + worktrees: string; + worktreesDetail: string; + worktreeCount(count: number): string; + /** Prefix for a logical estimate rather than bytes on disk. */ + approximately(size: string): string; + /** Label for a task's size in the archived-task list. */ + taskSize(size: string): string; + /** Caveats under the archived-task list, which shows per-task sizes. */ + taskSizeNote: string; +}; + +const STORAGE_USAGE_COPY = { + 'zh-CN': { + title: '存储占用', + help: '当前运行时主机的数据占用。此处只读,不会删除或压缩任何内容。', + loading: '正在统计…', + loadFailed: '无法统计存储占用', + refresh: '重新统计', + total: '合计', + totalDetail: '下列各项之和。标注 ≈ 的是按记录内容估算的大小,不含索引等开销。', + kinds: { + transcript: { label: '任务对话', detail: '任务的消息记录。' }, + runtime: { label: '运行日志', detail: '任务运行过程中记录的事件。' }, + artifacts: { label: '产物文件', detail: '任务生成或导入的文件。' }, + context_offload: { + label: '卸载的上下文', + detail: '为节省上下文而移出的长内容,相同内容只保存一份。', + }, + memory: { label: '长期记忆', detail: '跨任务保留的记忆条目。' }, + usage_history: { + label: '用量历史', + detail: '模型调用与工具使用记录。删除任务后仍会保留,以保证用量统计完整。', + }, + database: { label: '其他数据与索引', detail: '其余任务记录、索引以及数据库中的空闲空间。' }, + }, + reclaimable: '可回收空间', + reclaimableDetail: '数据库中已释放但尚未归还磁盘的空间,已计入「其他数据与索引」。', + worktrees: '子代理工作树', + worktreesDetail: '只统计数量;每个工作树的大小取决于对应项目的检出内容。', + worktreeCount: (count: number) => `${count} 个`, + approximately: (size: string) => `≈ ${size}`, + taskSize: (size: string) => `占用 ${size}`, + taskSizeNote: + '任务占用为估算值。卸载的上下文按任务引用计算,多个任务共享的内容会重复计入;删除任务后用量历史仍会保留。', + }, + 'zh-TW': { + title: '儲存空間占用', + help: '目前執行階段主機的資料占用。此處唯讀,不會刪除或壓縮任何內容。', + loading: '正在統計…', + loadFailed: '無法統計儲存空間占用', + refresh: '重新統計', + total: '合計', + totalDetail: '下列各項之和。標註 ≈ 的是依記錄內容估算的大小,不含索引等開銷。', + kinds: { + transcript: { label: '任務對話', detail: '任務的訊息記錄。' }, + runtime: { label: '執行日誌', detail: '任務執行過程中記錄的事件。' }, + artifacts: { label: '產物檔案', detail: '任務生成或匯入的檔案。' }, + context_offload: { + label: '卸載的上下文', + detail: '為節省上下文而移出的長內容,相同內容只儲存一份。', + }, + memory: { label: '長期記憶', detail: '跨任務保留的記憶條目。' }, + usage_history: { + label: '用量歷史', + detail: '模型呼叫與工具使用記錄。刪除任務後仍會保留,以確保用量統計完整。', + }, + database: { label: '其他資料與索引', detail: '其餘任務記錄、索引以及資料庫中的閒置空間。' }, + }, + reclaimable: '可回收空間', + reclaimableDetail: '資料庫中已釋放但尚未歸還磁碟的空間,已計入「其他資料與索引」。', + worktrees: '子代理工作樹', + worktreesDetail: '只統計數量;每個工作樹的大小取決於對應專案的檢出內容。', + worktreeCount: (count: number) => `${count} 個`, + approximately: (size: string) => `≈ ${size}`, + taskSize: (size: string) => `占用 ${size}`, + taskSizeNote: + '任務占用為估算值。卸載的上下文依任務引用計算,多個任務共享的內容會重複計入;刪除任務後用量歷史仍會保留。', + }, + en: { + title: 'Storage', + help: 'Space used by this Runtime Host’s data. Read-only: nothing here deletes or compacts data.', + loading: 'Measuring…', + loadFailed: 'Could not measure storage', + refresh: 'Measure again', + total: 'Total', + totalDetail: + 'The sum of the rows below. Values marked ≈ are estimated from record contents and exclude index overhead.', + kinds: { + transcript: { label: 'Task conversations', detail: 'Message history of your tasks.' }, + runtime: { label: 'Run logs', detail: 'Events recorded while tasks run.' }, + artifacts: { label: 'Artifacts', detail: 'Files that tasks produced or imported.' }, + context_offload: { + label: 'Offloaded context', + detail: 'Long content moved out of the model context. Identical content is stored once.', + }, + memory: { label: 'Long-term memory', detail: 'Memories kept across tasks.' }, + usage_history: { + label: 'Usage history', + detail: 'Model call and tool usage records. Kept after a task is deleted so usage totals stay complete.', + }, + database: { + label: 'Other data and indexes', + detail: 'Remaining task records, indexes, and free space inside the database.', + }, + }, + reclaimable: 'Reclaimable space', + reclaimableDetail: + 'Space the database has freed but not returned to the disk. Included in Other data and indexes.', + worktrees: 'Subagent worktrees', + worktreesDetail: 'Counted only. Each worktree’s size depends on its project checkout.', + worktreeCount: (count: number) => (count === 1 ? '1 worktree' : `${count} worktrees`), + approximately: (size: string) => `≈ ${size}`, + taskSize: (size: string) => `Uses ${size}`, + taskSizeNote: + 'Task sizes are estimates. Offloaded context is counted for every task that references it, so shared content is counted more than once. Usage history is kept after a task is deleted.', + }, +} satisfies UiCatalog; + +export function getStorageUsageCopy(locale: UiLocale): StorageUsageCopy { + return STORAGE_USAGE_COPY[locale]; +} diff --git a/apps/desktop/src/renderer/platform/desktop/create-storage-usage-services.ts b/apps/desktop/src/renderer/platform/desktop/create-storage-usage-services.ts new file mode 100644 index 00000000000..d38bfff68bb --- /dev/null +++ b/apps/desktop/src/renderer/platform/desktop/create-storage-usage-services.ts @@ -0,0 +1,35 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import type { MakaBridge } from '../../../preload/bridge-contract.js'; +import type { StorageUsageServices } from '../../features/storage-usage'; + +export type DesktopStorageUsageBridge = Pick; + +/** Binds the storage usage feature to the Desktop bridge. */ +export function createDesktopStorageUsageServices( + bridge: DesktopStorageUsageBridge = window.maka, +): StorageUsageServices { + return { + loadUsage: (host) => bridge.storage.usage(host), + // No host argument: each task is measured by the Host that holds it, and + // the bridge routes by the projected id for exactly that reason. + loadSessionUsage: (sessionIds) => bridge.storage.sessionUsage(sessionIds), + }; +} diff --git a/apps/desktop/src/renderer/settings/data-settings-page.tsx b/apps/desktop/src/renderer/settings/data-settings-page.tsx index d4217b24dfc..d6bcb2cafb6 100644 --- a/apps/desktop/src/renderer/settings/data-settings-page.tsx +++ b/apps/desktop/src/renderer/settings/data-settings-page.tsx @@ -38,6 +38,7 @@ import { useActionGuard } from './use-action-guard'; import { getDataSettingsCopy, type DataSettingsCopy } from '../locales/settings-data-copy'; import { getSettingsSharedCopy } from '../locales/settings-shared-copy.js'; import { useOptionalRuntimeHostSettingsTarget } from './runtime-host-settings-target.js'; +import { StorageUsageSection } from '../features/storage-usage/index.js'; const CONFIG_CATEGORY_IDS: readonly ConfigCategory[] = ['connections', 'settings', 'memory', 'credentials']; @@ -305,6 +306,9 @@ export function DataSettingsPage(props: { /> + {runtimeHostAvailable ? ( + + ) : null} {runtimeHostAvailable ? - + {visible.length === 0 ? ( ) : ( - - {visible.map((session) => { - const updated = session.lastMessageAt - ? formatCompactTimestamp(session.lastMessageAt, Date.now(), locale) - : undefined; - const description = [ - isOrphanedSubagentTask(session, knownSessionIds) - ? copy.deletedParent - : undefined, - projectLabelOf(session), - updated, - ] - .filter(Boolean) - .join(' · '); - return ( - 0 ? description : undefined} - startContent={ + + + {visible.map((session) => { + const updated = session.lastMessageAt + ? formatCompactTimestamp(session.lastMessageAt, Date.now(), locale) + : undefined; + const description = [ + isOrphanedSubagentTask(session, knownSessionIds) + ? copy.deletedParent + : undefined, + projectLabelOf(session), + updated, + ] + .filter(Boolean) + .join(' · '); + return ( + 0 ? description : undefined} + startContent={ + )} diff --git a/docs/astryx-surface-file-inventory.md b/docs/astryx-surface-file-inventory.md index f2c53cd5b85..eb9f96cb152 100644 --- a/docs/astryx-surface-file-inventory.md +++ b/docs/astryx-surface-file-inventory.md @@ -6,7 +6,7 @@ Generated against `@astryxdesign/core@0.6.2` (195 component exports). Wiki bar: Design Conventions · API Use-the-System · Theming · Container Padding. -**Totals:** 308 files — blocker 0, reimplementation 0, polish 4, aligned 304. +**Totals:** 311 files — blocker 0, reimplementation 0, polish 4, aligned 307. ## Exclusions (explicit) @@ -107,6 +107,9 @@ Wiki bar: Design Conventions · API Use-the-System · Theming · Container Paddi | `apps/desktop/src/renderer/features/session-navigation/ui/session-navigation-provider.tsx` | shell-chrome-or-panel | none | aligned — no raw controls; no Astryx JSX usage | aligned | | `apps/desktop/src/renderer/features/session-settings/services-context.tsx` | shell-chrome-or-panel | none | aligned — no raw controls; no Astryx JSX usage | aligned | | `apps/desktop/src/renderer/features/session-settings/ui/session-settings-provider.tsx` | shell-chrome-or-panel | none | aligned — no raw controls; no Astryx JSX usage | aligned | +| `apps/desktop/src/renderer/features/storage-usage/services-context.tsx` | other | none | aligned — no raw controls; no Astryx JSX usage | aligned | +| `apps/desktop/src/renderer/features/storage-usage/ui/storage-usage-section.tsx` | other | Banner, Button | aligned — uses Astryx (Banner, Button) | aligned | +| `apps/desktop/src/renderer/features/storage-usage/ui/task-storage-size.tsx` | other | Text | aligned — uses Astryx (Text) | aligned | | `apps/desktop/src/renderer/features/task-entry/services-context.tsx` | other | none | aligned — no raw controls; no Astryx JSX usage | aligned | | `apps/desktop/src/renderer/features/task-entry/ui/task-entry-host.tsx` | other | none | aligned — no raw controls; no Astryx JSX usage | aligned | | `apps/desktop/src/renderer/features/task-entry/ui/task-entry-provider.tsx` | other | none | aligned — no raw controls; no Astryx JSX usage | aligned | diff --git a/docs/astryx-surface-file-inventory.paths b/docs/astryx-surface-file-inventory.paths index 80fbf020548..84fff00c1bf 100644 --- a/docs/astryx-surface-file-inventory.paths +++ b/docs/astryx-surface-file-inventory.paths @@ -77,6 +77,9 @@ apps/desktop/src/renderer/features/session-navigation/services-context.tsx apps/desktop/src/renderer/features/session-navigation/ui/session-navigation-provider.tsx apps/desktop/src/renderer/features/session-settings/services-context.tsx apps/desktop/src/renderer/features/session-settings/ui/session-settings-provider.tsx +apps/desktop/src/renderer/features/storage-usage/services-context.tsx +apps/desktop/src/renderer/features/storage-usage/ui/storage-usage-section.tsx +apps/desktop/src/renderer/features/storage-usage/ui/task-storage-size.tsx apps/desktop/src/renderer/features/task-entry/services-context.tsx apps/desktop/src/renderer/features/task-entry/ui/task-entry-host.tsx apps/desktop/src/renderer/features/task-entry/ui/task-entry-provider.tsx diff --git a/packages/runtime-host/src/__tests__/storage-usage-coordinator.test.ts b/packages/runtime-host/src/__tests__/storage-usage-coordinator.test.ts new file mode 100644 index 00000000000..aec85cb13ab --- /dev/null +++ b/packages/runtime-host/src/__tests__/storage-usage-coordinator.test.ts @@ -0,0 +1,135 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import assert from 'node:assert/strict'; +import { test } from 'node:test'; +import type { + InteractiveStorageFootprintReader, + StorageFootprint, +} from '@maka/storage/storage-writer-composition'; +import { HOST_OPERATION_SPECS } from '../protocol/index.js'; +import type { ConnectionContext } from '../server/operation-dispatcher.js'; +import { + HostStorageUsageCoordinator, + STORAGE_USAGE_TOTALS_TTL_MS, +} from '../server/storage-usage-coordinator.js'; + +const context = {} as ConnectionContext; +const footprint: StorageFootprint = { + totals: [{ kind: 'database', bytes: 4096, exact: false }], + reclaimableBytes: 1024, + worktreeCount: 1, +}; + +test('storage usage shares one totals scan and reads Sessions fresh', async () => { + let now = 1_000; + let measures = 0; + let release: (() => void) | undefined; + const sessionQueries: Array = []; + const reader: InteractiveStorageFootprintReader = { + measure: async () => { + measures += 1; + await new Promise((resolve) => { + release = resolve; + }); + return footprint; + }, + measureSessions: async (sessionIds) => { + sessionQueries.push(sessionIds); + return sessionIds.map((sessionId) => ({ + sessionId, + bytes: { transcript: 1, runtime: 2, artifacts: 3 }, + worktreeCount: 0, + })); + }, + }; + const coordinator = new HostStorageUsageCoordinator({ footprint: reader, now: () => now }); + const query = coordinator.handlers['storage.usage.query']; + + const first = query({}, context); + const second = query({ sessionIds: ['session-1'] }, context); + await new Promise((resolve) => setImmediate(resolve)); + release?.(); + const [totalsOnly, withSessions] = await Promise.all([first, second]); + assert.equal(measures, 1); + assert.deepEqual(totalsOnly, { + ok: true, + result: { measuredAt: 1_000, ...footprint }, + }); + assert.ok(withSessions.ok); + assert.deepEqual(withSessions.result.sessions, [ + { + sessionId: 'session-1', + bytes: { transcript: 1, runtime: 2, artifacts: 3 }, + worktreeCount: 0, + }, + ]); + const spec = HOST_OPERATION_SPECS['storage.usage.query']; + assert.doesNotThrow(() => + spec.assertOutputForInput?.({ sessionIds: ['session-1'] }, withSessions.result), + ); + + now += STORAGE_USAGE_TOTALS_TTL_MS - 1; + const cached = await query({ sessionIds: ['session-2'] }, context); + assert.equal(measures, 1); + assert.ok(cached.ok); + assert.equal(cached.result.measuredAt, 1_000); + assert.deepEqual(sessionQueries, [['session-1'], ['session-2']]); + + now += 1; + const refreshed = query({}, context); + await new Promise((resolve) => setImmediate(resolve)); + release?.(); + const next = await refreshed; + assert.equal(measures, 2); + assert.ok(next.ok); + assert.equal(next.result.measuredAt, now); +}); + +test('storage usage reports measurement failures and refuses work while draining', async () => { + let fail = true; + const coordinator = new HostStorageUsageCoordinator({ + footprint: { + measure: async () => { + if (fail) throw new Error('disk I/O error'); + return footprint; + }, + measureSessions: async () => [], + }, + }); + const query = coordinator.handlers['storage.usage.query']; + const originalError = console.error; + console.error = () => {}; + try { + assert.deepEqual(await query({}, context), { + ok: false, + error: { code: 'persistence_failed', message: 'Storage usage could not be measured' }, + }); + } finally { + console.error = originalError; + } + // A failed scan is not cached. + fail = false; + assert.equal((await query({}, context)).ok, true); + + coordinator.beginDrain(); + const drained = await query({}, context); + assert.equal(drained.ok, false); + assert.equal(!drained.ok && drained.error.code, 'host_draining'); +}); diff --git a/packages/runtime-host/src/__tests__/storage-usage-protocol.test.ts b/packages/runtime-host/src/__tests__/storage-usage-protocol.test.ts new file mode 100644 index 00000000000..84c6a30a5a3 --- /dev/null +++ b/packages/runtime-host/src/__tests__/storage-usage-protocol.test.ts @@ -0,0 +1,131 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import assert from 'node:assert/strict'; +import { describe, test } from 'node:test'; +import { RuntimeHostProtocolError } from '../protocol/errors.js'; +import { + decodeClientFrame, + decodeHostFrame, + HOST_OPERATION_SPECS, + STORAGE_USAGE_SESSION_MAX_ITEMS, + type StorageUsageQueryResult, +} from '../protocol/index.js'; + +const spec = HOST_OPERATION_SPECS['storage.usage.query']; + +const result: StorageUsageQueryResult = { + measuredAt: 1_700_000_000_000, + totals: [ + { kind: 'database', bytes: 4096, exact: false }, + { kind: 'artifacts', bytes: 12, exact: true }, + ], + reclaimableBytes: 8192, + worktreeCount: 2, + sessions: [ + { + sessionId: 'session-1', + bytes: { transcript: 10, runtime: 20, artifacts: 30, context: 40 }, + worktreeCount: 1, + }, + { + sessionId: 'session-2', + bytes: { transcript: 0, runtime: 0, artifacts: 0 }, + worktreeCount: 0, + }, + ], +}; + +describe('storage usage protocol', () => { + test('round-trips totals and per-Session usage through request and response frames', () => { + const request = decodeClientFrame({ + requestId: 'request-storage', + operation: 'storage.usage.query', + input: { sessionIds: ['session-1', 'session-2'] }, + }); + assert.deepEqual(request, { + requestId: 'request-storage', + operation: 'storage.usage.query', + input: { sessionIds: ['session-1', 'session-2'] }, + }); + assert.deepEqual( + decodeHostFrame( + JSON.parse( + JSON.stringify({ + requestId: 'request-storage', + operation: 'storage.usage.query', + ok: true, + result, + }), + ), + ), + { requestId: 'request-storage', operation: 'storage.usage.query', ok: true, result }, + ); + assert.deepEqual(spec.decodeInput({}), {}); + }); + + test('rejects unbounded, duplicate, or malformed input', () => { + const tooMany = Array.from( + { length: STORAGE_USAGE_SESSION_MAX_ITEMS + 1 }, + (_, index) => `session-${index}`, + ); + for (const input of [ + { sessionIds: tooMany }, + { sessionIds: ['session-1', 'session-1'] }, + { sessionIds: ['../escape'] }, + { sessionIds: 'session-1' }, + { sessionId: 'session-1' }, + ]) { + assert.throws(() => spec.decodeInput(input), isInvalidFrame, JSON.stringify(input)); + } + }); + + test('rejects results with unknown kinds, open shapes, or Sessions that were not asked for', () => { + const malformed: unknown[] = [ + { ...result, totals: [{ kind: 'worktrees', bytes: 1, exact: true }] }, + { ...result, totals: [result.totals[0], result.totals[0]] }, + { ...result, reclaimableBytes: -1 }, + { ...result, extra: true }, + { + ...result, + sessions: [ + { ...result.sessions![0], bytes: { transcript: 1, runtime: 1, artifacts: 1, other: 1 } }, + ], + }, + ]; + for (const value of malformed) { + assert.throws(() => spec.decodeOutput(value), isInvalidFrame, JSON.stringify(value)); + } + const { sessions: _sessions, ...totalsOnly } = result; + assert.throws( + () => spec.assertOutputForInput?.({ sessionIds: ['session-2', 'session-1'] }, result), + isInvalidFrame, + ); + assert.throws( + () => spec.assertOutputForInput?.({ sessionIds: ['session-1', 'session-2'] }, totalsOnly), + isInvalidFrame, + ); + assert.throws(() => spec.assertOutputForInput?.({}, result), isInvalidFrame); + assert.doesNotThrow(() => spec.assertOutputForInput?.({}, totalsOnly)); + }); +}); + +function isInvalidFrame(error: unknown): boolean { + return error instanceof RuntimeHostProtocolError && error.code === 'invalid_frame'; +} diff --git a/packages/runtime-host/src/protocol/index.ts b/packages/runtime-host/src/protocol/index.ts index 2f41d5595c1..5eb7467b0b8 100644 --- a/packages/runtime-host/src/protocol/index.ts +++ b/packages/runtime-host/src/protocol/index.ts @@ -104,7 +104,9 @@ export const RUNTIME_HOST_REGISTRATION_SCHEMA_VERSION = 1 as const; export const RUNTIME_HOST_PROTOCOL_VERSION = 0 as const; // Increment when the same protocol version no longer guarantees safe Client-Host // interoperability. Mismatches are rejected before domain commands are admitted. -export const RUNTIME_HOST_COMPATIBILITY_EPOCH = 198 as const; +export const RUNTIME_HOST_COMPATIBILITY_EPOCH = 199 as const; +// 199: `storage.usage.query` reports the State Root footprint and per-Session +// storage. An epoch-198 Host rejects the unknown operation. // 198: Executor readiness exposes explicit restore, restore-failed and history-gap states. // 197: Queue reorder requests carry the expected queue revision. Epoch-196 // peers reject the required field or send an unfenced reorder request. diff --git a/packages/runtime-host/src/protocol/operations.ts b/packages/runtime-host/src/protocol/operations.ts index f744b364de8..4faf4ad8f2a 100644 --- a/packages/runtime-host/src/protocol/operations.ts +++ b/packages/runtime-host/src/protocol/operations.ts @@ -64,6 +64,7 @@ import { SESSION_RETIREMENT_OPERATION_SPECS } from './session-retirement.js'; import { PROMPT_SUGGESTION_OPERATION_SPECS } from './prompt-suggestions.js'; import { SESSION_EFFECT_OPERATION_SPECS } from './session-effects.js'; import { SKILL_CATALOG_OPERATION_SPECS } from './skill-catalog.js'; +import { STORAGE_USAGE_OPERATION_SPECS } from './storage-usage.js'; import { TURN_OPERATION_SPECS } from './turn.js'; import { USAGE_PRICING_OPERATION_SPECS } from './usage-pricing.js'; import { WEB_SEARCH_OPERATION_SPECS } from './web-search.js'; @@ -191,6 +192,7 @@ export * from './session-todo.js'; export * from './session-effects.js'; export * from './prompt-suggestions.js'; export * from './skill-catalog.js'; +export * from './storage-usage.js'; export * from './usage-pricing.js'; export * from './web-search.js'; export * from './recall.js'; @@ -231,6 +233,7 @@ export const HOST_OPERATION_SPECS = composeOperationSpecMaps( ARTIFACT_OPERATION_SPECS, SKILL_CATALOG_OPERATION_SPECS, USAGE_PRICING_OPERATION_SPECS, + STORAGE_USAGE_OPERATION_SPECS, MEMORY_OPERATION_SPECS, OAUTH_OPERATION_SPECS, EXTERNAL_AGENT_SETUP_OPERATION_SPECS, @@ -356,6 +359,7 @@ export const REMOTE_OWNER_OPERATION_GRANTS = Object.freeze([ 'skill.catalog.mutate', 'skill.catalog.preview-update', 'skill.catalog.query', + 'storage.usage.query', 'subscription.close', 'subscription.open', 'subscription.pty_interest.set', diff --git a/packages/runtime-host/src/protocol/storage-usage.ts b/packages/runtime-host/src/protocol/storage-usage.ts new file mode 100644 index 00000000000..3c0e1193225 --- /dev/null +++ b/packages/runtime-host/src/protocol/storage-usage.ts @@ -0,0 +1,218 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { requireCount, requireEntityId, requireExactRecord, requireShapedRecord } from './codec.js'; +import { invalidProtocolFrame } from './errors.js'; +import { defineOperation } from './operation-spec.js'; + +/** Upper bound on Sessions measured by one query; a page of visible rows fits well inside it. */ +export const STORAGE_USAGE_SESSION_MAX_ITEMS = 100; + +/** + * Non-overlapping parts of the Host's State Root footprint. + * + * `transcript`, `runtime` and `usage_history` are logical payload bytes inside + * the operational database; `database` is the rest of that database's files + * (other records, indexes, free pages). `context_offload` is deduplicated blob + * bytes. Worktrees are counted separately and never sized. + */ +export const STORAGE_USAGE_KINDS = [ + 'database', + 'transcript', + 'runtime', + 'usage_history', + 'artifacts', + 'context_offload', + 'memory', +] as const; + +export type StorageUsageKind = (typeof STORAGE_USAGE_KINDS)[number]; + +export interface StorageUsageTotal { + readonly kind: StorageUsageKind; + readonly bytes: number; + /** False when the figure is a logical payload size rather than bytes on disk. */ + readonly exact: boolean; +} + +export interface SessionStorageUsage { + readonly sessionId: string; + readonly bytes: { + readonly transcript: number; + readonly runtime: number; + readonly artifacts: number; + /** + * Logical context-offload bytes referenced by the Session. Blobs are shared + * across Sessions, so this is not what deleting the Session would free. + * Absent when the Host has no context-offload Store. + */ + readonly context?: number; + }; + /** Worktrees bound to the Session or to its direct Subagent children. */ + readonly worktreeCount: number; +} + +export interface StorageUsageQueryInput { + /** Also measure these Sessions. Omit to read the State Root totals only. */ + readonly sessionIds?: readonly string[]; +} + +export interface StorageUsageQueryResult { + /** Host clock, epoch milliseconds. */ + readonly measuredAt: number; + readonly totals: readonly StorageUsageTotal[]; + /** Free pages in the operational database that compaction could release. */ + readonly reclaimableBytes: number; + readonly worktreeCount: number; + /** Present exactly when the input named Sessions, in input order. */ + readonly sessions?: readonly SessionStorageUsage[]; +} + +const STORAGE_USAGE_ERRORS = [ + 'host_not_ready', + 'host_draining', + 'operation_unavailable', + 'persistence_failed', + 'internal_failure', +] as const; + +export const STORAGE_USAGE_OPERATION_SPECS = { + 'storage.usage.query': defineOperation< + StorageUsageQueryInput, + StorageUsageQueryResult, + (typeof STORAGE_USAGE_ERRORS)[number] + >({ + mode: 'query', + availability: 'ready', + errors: STORAGE_USAGE_ERRORS, + decodeInput: decodeStorageUsageQueryInput, + decodeOutput: decodeStorageUsageQueryResult, + assertOutputForInput: (input, output) => { + const requested = input.sessionIds; + const measured = output.sessions; + if (requested === undefined) { + if (measured !== undefined) { + throw invalidProtocolFrame('Storage usage returned Sessions that were not requested'); + } + return; + } + if ( + measured === undefined || + measured.length !== requested.length || + measured.some((session, index) => session.sessionId !== requested[index]) + ) { + throw invalidProtocolFrame('Storage usage Sessions do not match the request'); + } + }, + }), +} as const; + +export function decodeStorageUsageQueryInput(value: unknown): StorageUsageQueryInput { + const input = requireShapedRecord(value, 'storage usage input', [], ['sessionIds']); + if (input.sessionIds === undefined) return {}; + return { sessionIds: decodeSessionIds(input.sessionIds) }; +} + +export function decodeStorageUsageQueryResult(value: unknown): StorageUsageQueryResult { + const result = requireShapedRecord( + value, + 'storage usage result', + ['measuredAt', 'totals', 'reclaimableBytes', 'worktreeCount'], + ['sessions'], + ); + if (!Array.isArray(result.totals) || result.totals.length > STORAGE_USAGE_KINDS.length) { + throw invalidProtocolFrame('Invalid storage usage totals'); + } + const totals = result.totals.map(decodeTotal); + if (new Set(totals.map((total) => total.kind)).size !== totals.length) { + throw invalidProtocolFrame('Duplicate storage usage kind'); + } + let sessions: SessionStorageUsage[] | undefined; + if (result.sessions !== undefined) { + if ( + !Array.isArray(result.sessions) || + result.sessions.length > STORAGE_USAGE_SESSION_MAX_ITEMS + ) { + throw invalidProtocolFrame('Invalid storage usage Sessions'); + } + sessions = result.sessions.map(decodeSessionUsage); + if (new Set(sessions.map((session) => session.sessionId)).size !== sessions.length) { + throw invalidProtocolFrame('Duplicate storage usage Session'); + } + } + return { + measuredAt: requireCount(result.measuredAt, 'storage usage measuredAt'), + totals, + reclaimableBytes: requireCount(result.reclaimableBytes, 'storage usage reclaimableBytes'), + worktreeCount: requireCount(result.worktreeCount, 'storage usage worktreeCount'), + ...(sessions === undefined ? {} : { sessions }), + }; +} + +function decodeSessionIds(value: unknown): readonly string[] { + if (!Array.isArray(value) || value.length > STORAGE_USAGE_SESSION_MAX_ITEMS) { + throw invalidProtocolFrame('Invalid storage usage sessionIds'); + } + const sessionIds = value.map((sessionId) => requireEntityId(sessionId, 'sessionId')); + if (new Set(sessionIds).size !== sessionIds.length) { + throw invalidProtocolFrame('Duplicate storage usage sessionId'); + } + return sessionIds; +} + +function decodeTotal(value: unknown): StorageUsageTotal { + const total = requireExactRecord(value, 'storage usage total', ['kind', 'bytes', 'exact']); + if (!STORAGE_USAGE_KINDS.includes(total.kind as StorageUsageKind)) { + throw invalidProtocolFrame('Invalid storage usage kind'); + } + if (typeof total.exact !== 'boolean') { + throw invalidProtocolFrame('Invalid storage usage exactness'); + } + return { + kind: total.kind as StorageUsageKind, + bytes: requireCount(total.bytes, 'storage usage bytes'), + exact: total.exact, + }; +} + +function decodeSessionUsage(value: unknown): SessionStorageUsage { + const session = requireExactRecord(value, 'storage usage Session', [ + 'sessionId', + 'bytes', + 'worktreeCount', + ]); + const bytes = requireShapedRecord( + session.bytes, + 'storage usage Session bytes', + ['transcript', 'runtime', 'artifacts'], + ['context'], + ); + return { + sessionId: requireEntityId(session.sessionId, 'sessionId'), + bytes: { + transcript: requireCount(bytes.transcript, 'storage usage transcript bytes'), + runtime: requireCount(bytes.runtime, 'storage usage runtime bytes'), + artifacts: requireCount(bytes.artifacts, 'storage usage artifact bytes'), + ...(bytes.context === undefined + ? {} + : { context: requireCount(bytes.context, 'storage usage context bytes') }), + }, + worktreeCount: requireCount(session.worktreeCount, 'storage usage worktreeCount'), + }; +} diff --git a/packages/runtime-host/src/server/execution-composition.ts b/packages/runtime-host/src/server/execution-composition.ts index 19e2f649e05..4022795336a 100644 --- a/packages/runtime-host/src/server/execution-composition.ts +++ b/packages/runtime-host/src/server/execution-composition.ts @@ -240,6 +240,7 @@ import { HostSessionCatalogCoordinator } from './session-catalog-coordinator.js' import { HostWorkspaceResolver } from './workspace-resolver.js'; import { HostSessionRetirementCoordinator } from './session-retirement-coordinator.js'; import { HostStorageMaintenance } from './storage-maintenance.js'; +import { HostStorageUsageCoordinator } from './storage-usage-coordinator.js'; import { HostSessionRevisionCoordinator } from './session-revision-coordinator.js'; import { HostSessionEffectCoordinator } from './session-effect-coordinator.js'; import { SessionContinuityCoordinator } from './session-continuity-coordinator.js'; @@ -2828,6 +2829,7 @@ export async function createExecutionRuntimeHostComposition( context.requestDrain, ); let recoverySessions: Awaited> = []; + const storageUsage = new HostStorageUsageCoordinator({ footprint: storage.footprint }); const storageMaintenance = new HostStorageMaintenance({ artifacts: openedArtifactStore, contextOffload: openedContextOffloadStore, @@ -2840,6 +2842,11 @@ export async function createExecutionRuntimeHostComposition( drain: [() => storageMaintenance.beginDrain()], close: [() => storageMaintenance.close()], }), + createRuntimeHostDomainModule({ + id: 'storage-usage', + handlers: [storageUsage.handlers], + drain: [() => storageUsage.beginDrain()], + }), createRuntimeHostDomainModule({ id: 'plugin-platform', handlers: [pluginPlatformCoordinator.handlers], diff --git a/packages/runtime-host/src/server/operation-dispatcher.ts b/packages/runtime-host/src/server/operation-dispatcher.ts index aefadd668e2..c87bc7058b4 100644 --- a/packages/runtime-host/src/server/operation-dispatcher.ts +++ b/packages/runtime-host/src/server/operation-dispatcher.ts @@ -68,6 +68,7 @@ import { SESSION_TODO_OPERATION_SPECS } from '../protocol/session-todo.js'; import { SESSION_TRANSCRIPT_OPERATION_SPECS } from '../protocol/session-transcript.js'; import { SESSION_TURNS_OPERATION_SPECS } from '../protocol/session-turns.js'; import { SKILL_CATALOG_OPERATION_SPECS } from '../protocol/skill-catalog.js'; +import { STORAGE_USAGE_OPERATION_SPECS } from '../protocol/storage-usage.js'; import { TURN_OPERATION_SPECS } from '../protocol/turn.js'; import { USAGE_PRICING_OPERATION_SPECS } from '../protocol/usage-pricing.js'; import { WEB_SEARCH_OPERATION_SPECS } from '../protocol/web-search.js'; @@ -153,6 +154,7 @@ export type SessionCatalogOperationKey = export type ArtifactOperationKey = keyof typeof ARTIFACT_OPERATION_SPECS; export type SkillCatalogOperationKey = keyof typeof SKILL_CATALOG_OPERATION_SPECS; export type UsagePricingOperationKey = keyof typeof USAGE_PRICING_OPERATION_SPECS; +export type StorageUsageOperationKey = keyof typeof STORAGE_USAGE_OPERATION_SPECS; export type MemoryOperationKey = keyof typeof MEMORY_OPERATION_SPECS; export type OAuthOperationKey = keyof typeof OAUTH_OPERATION_SPECS; export type RuntimeResourceOperationKey = keyof typeof RUNTIME_RESOURCE_OPERATION_SPECS; @@ -212,6 +214,7 @@ export type SessionTodoOperationHandlerMap = Pick; export type SkillCatalogOperationHandlerMap = Pick; export type UsagePricingOperationHandlerMap = Pick; +export type StorageUsageOperationHandlerMap = Pick; export type MemoryOperationHandlerMap = Pick; export type OAuthOperationHandlerMap = Pick; export type RuntimeResourceOperationHandlerMap = Pick< diff --git a/packages/runtime-host/src/server/storage-usage-coordinator.ts b/packages/runtime-host/src/server/storage-usage-coordinator.ts new file mode 100644 index 00000000000..a263cfce6b0 --- /dev/null +++ b/packages/runtime-host/src/server/storage-usage-coordinator.ts @@ -0,0 +1,115 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { generalizedErrorMessage } from '@maka/core/redaction'; +import type { + InteractiveStorageFootprintReader, + StorageFootprint, +} from '@maka/storage/storage-writer-composition'; +import type { + OperationOutcome, + StorageUsageQueryInput, + StorageUsageQueryResult, +} from '../protocol/index.js'; +import type { StorageUsageOperationHandlerMap } from './operation-dispatcher.js'; + +/** + * State Root totals scan whole tables, so they are shared for a short while. + * Per-Session figures are index lookups and are always read fresh. + */ +export const STORAGE_USAGE_TOTALS_TTL_MS = 15_000; + +interface MeasuredTotals { + readonly measuredAt: number; + readonly footprint: StorageFootprint; +} + +export interface HostStorageUsageCoordinatorOptions { + readonly footprint: InteractiveStorageFootprintReader; + readonly now?: () => number; +} + +/** Read-only storage visibility: measures, never reclaims or deletes. */ +export class HostStorageUsageCoordinator { + readonly handlers: StorageUsageOperationHandlerMap = { + 'storage.usage.query': (input) => this.#query(input), + }; + + readonly #footprint: InteractiveStorageFootprintReader; + readonly #now: () => number; + #totals: MeasuredTotals | undefined; + #measuring: Promise | undefined; + #draining = false; + + constructor(options: HostStorageUsageCoordinatorOptions) { + this.#footprint = options.footprint; + this.#now = options.now ?? Date.now; + } + + beginDrain(): void { + this.#draining = true; + } + + async #query(input: StorageUsageQueryInput): Promise> { + if (this.#draining) { + return { ok: false, error: { code: 'host_draining', message: 'Runtime Host is draining' } }; + } + try { + const [totals, sessions] = await Promise.all([ + this.#readTotals(), + input.sessionIds ? this.#footprint.measureSessions(input.sessionIds) : undefined, + ]); + const result: StorageUsageQueryResult = { + measuredAt: totals.measuredAt, + totals: totals.footprint.totals, + reclaimableBytes: totals.footprint.reclaimableBytes, + worktreeCount: totals.footprint.worktreeCount, + ...(sessions ? { sessions } : {}), + }; + return { ok: true, result }; + } catch (error) { + console.error( + `[runtime-host] storage usage could not be measured: ${generalizedErrorMessage(error)}`, + ); + return { + ok: false, + error: { code: 'persistence_failed', message: 'Storage usage could not be measured' }, + }; + } + } + + #readTotals(): Promise { + const cached = this.#totals; + if (cached && this.#now() - cached.measuredAt < STORAGE_USAGE_TOTALS_TTL_MS) { + return Promise.resolve(cached); + } + // Concurrent readers share one scan instead of each walking the tables. + this.#measuring ??= this.#footprint + .measure() + .then((footprint) => { + const measured = { measuredAt: this.#now(), footprint }; + this.#totals = measured; + return measured; + }) + .finally(() => { + this.#measuring = undefined; + }); + return this.#measuring; + } +} diff --git a/packages/storage/src/__tests__/storage-footprint.test.ts b/packages/storage/src/__tests__/storage-footprint.test.ts new file mode 100644 index 00000000000..4b6f6fd52f1 --- /dev/null +++ b/packages/storage/src/__tests__/storage-footprint.test.ts @@ -0,0 +1,197 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import assert from 'node:assert/strict'; +import { mkdir, mkdtemp, rm, stat, writeFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { test } from 'node:test'; +import type { DatabaseSync } from 'node:sqlite'; +import { + acquireOperationalStateDatabase, + OPERATIONAL_STATE_DATABASE_NAME, +} from '../operational-state-store.js'; +import { openStorageFootprintReader } from '../storage-footprint.js'; + +test('storage footprint measures Sessions from their rows and totals without double counting', async () => { + const root = await mkdtemp(join(tmpdir(), 'maka-storage-footprint-')); + const owner = acquireOperationalStateDatabase(root); + const contextCalls: Array = []; + const reader = openStorageFootprintReader(root, { + contextOffload: { + usage: async (sessionId?: string) => { + contextCalls.push(sessionId); + return { references: 1, logicalBytes: sessionId ? 700 : 900, physicalBytes: 400 }; + }, + }, + }); + try { + const db = owner.database; + insertSession(db, 'parent', {}); + insertSession(db, 'child', { subagentWorkspace: { kind: 'git_worktree' } }, 'parent'); + insertSession(db, 'other', {}); + insertMessage(db, 'parent', 0, 'x'.repeat(100)); + // Multi-byte text is measured in bytes, not characters. + insertMessage(db, 'parent', 1, 'é'.repeat(10)); + db.prepare('INSERT INTO session_message_payloads VALUES (?, ?, ?, ?)').run( + 'parent', + 1, + 64 * 1024 + 1, + 'a'.repeat(64), + ); + db.prepare('INSERT INTO session_message_chunks VALUES (?, ?, ?, ?, ?)').run( + 'parent', + 1, + 0, + Buffer.alloc(300), + 'b'.repeat(64), + ); + insertMessage(db, 'other', 0, 'y'.repeat(50)); + db.prepare( + `INSERT INTO runtime_events( + event_id, session_id, invocation_id, run_id, turn_id, event_seq, event_kind, + payload_json, committed_at + ) VALUES ('event-1', 'parent', 'invocation-1', 'run-1', 'turn-1', 1, 'kind', ?, 1)`, + ).run('z'.repeat(40)); + db.prepare('INSERT INTO artifact_records VALUES (?, ?, ?, ?, ?)').run( + 'artifact-1', + 'parent', + 1, + 'parent/artifact-1-file', + JSON.stringify({ sizeBytes: 1234 }), + ); + db.prepare( + 'INSERT INTO usage_llm_calls(storage_key, id, ts, record_json, session_id) VALUES (?, ?, ?, ?, ?)', + ).run('usage-1', 'usage-1', 1, 'u'.repeat(30), 'gone'); + await writeFile(join(root, 'memory.sqlite'), Buffer.alloc(2048)); + await mkdir(join(root, 'subagent-worktrees', 'lease-a'), { recursive: true }); + await mkdir(join(root, 'subagent-worktrees', 'lease-b'), { recursive: true }); + + const sessions = await reader.measureSessions(['parent', 'child', 'missing', 'parent']); + assert.deepEqual(sessions, [ + { + sessionId: 'parent', + // 'x' * 100 + JSON quotes, 'é' * 10 as 20 bytes + quotes, one 300-byte chunk. + bytes: { transcript: 102 + 22 + 300, runtime: 40, artifacts: 1234, context: 700 }, + worktreeCount: 1, + }, + { + sessionId: 'child', + bytes: { transcript: 0, runtime: 0, artifacts: 0, context: 700 }, + worktreeCount: 1, + }, + { + sessionId: 'missing', + bytes: { transcript: 0, runtime: 0, artifacts: 0, context: 700 }, + worktreeCount: 0, + }, + ]); + assert.deepEqual(contextCalls, ['parent', 'child', 'missing']); + + const footprint = await reader.measure(); + const totals = new Map(footprint.totals.map((total) => [total.kind, total])); + assert.equal(totals.get('transcript')?.bytes, 102 + 22 + 300 + 52); + assert.equal(totals.get('runtime')?.bytes, 40); + assert.equal(totals.get('usage_history')?.bytes, 30); + assert.deepEqual(totals.get('artifacts'), { kind: 'artifacts', bytes: 1234, exact: true }); + assert.deepEqual(totals.get('context_offload'), { + kind: 'context_offload', + bytes: 400, + exact: false, + }); + assert.deepEqual(totals.get('memory'), { kind: 'memory', bytes: 2048, exact: true }); + assert.equal(footprint.worktreeCount, 2); + + const databaseFiles = await databaseFileBytes(root); + const insideDatabase = ['database', 'transcript', 'runtime', 'usage_history'] as const; + assert.equal( + insideDatabase.reduce((sum, kind) => sum + (totals.get(kind)?.bytes ?? 0), 0), + databaseFiles, + ); + const pageSize = Number( + (db.prepare('PRAGMA page_size').get() as { page_size: number }).page_size, + ); + const freePages = Number( + (db.prepare('PRAGMA freelist_count').get() as { freelist_count: number }).freelist_count, + ); + assert.equal(footprint.reclaimableBytes, pageSize * freePages); + } finally { + reader.close(); + owner.close(); + await rm(root, { recursive: true, force: true }); + } +}); + +test('storage footprint omits context usage when the Store is unavailable', async () => { + const root = await mkdtemp(join(tmpdir(), 'maka-storage-footprint-no-context-')); + const owner = acquireOperationalStateDatabase(root); + const reader = openStorageFootprintReader(root); + try { + const [session] = await reader.measureSessions(['alone']); + assert.deepEqual(session?.bytes, { transcript: 0, runtime: 0, artifacts: 0 }); + const footprint = await reader.measure(); + assert.equal( + footprint.totals.some((total) => total.kind === 'context_offload'), + false, + ); + assert.equal(footprint.worktreeCount, 0); + } finally { + reader.close(); + owner.close(); + await rm(root, { recursive: true, force: true }); + } +}); + +function insertSession( + db: DatabaseSync, + sessionId: string, + header: Record, + subagentParentSessionId?: string, +): void { + db.prepare( + `INSERT INTO session_metadata( + session_id, payload_json, created_at, name, is_flagged, is_archived, has_unread, + backend, llm_connection_slug, model, metadata_version, committed_at, + subagent_parent_session_id + ) VALUES (?, ?, 1, ?, 0, 0, 0, 'backend', 'connection', 'model', 1, 1, ?)`, + ).run( + sessionId, + JSON.stringify({ id: sessionId, ...header }), + sessionId, + subagentParentSessionId ?? null, + ); +} + +function insertMessage(db: DatabaseSync, sessionId: string, sequence: number, text: string): void { + db.prepare( + `INSERT INTO session_messages( + session_id, sequence, message_id, message_type, message_ts, record_json + ) VALUES (?, ?, ?, 'user', 1, ?)`, + ).run(sessionId, sequence, `${sessionId}-${sequence}`, JSON.stringify(text)); +} + +async function databaseFileBytes(root: string): Promise { + let total = 0; + for (const suffix of ['', '-wal', '-shm']) { + try { + total += (await stat(join(root, `${OPERATIONAL_STATE_DATABASE_NAME}${suffix}`))).size; + } catch {} + } + return total; +} diff --git a/packages/storage/src/storage-footprint.ts b/packages/storage/src/storage-footprint.ts new file mode 100644 index 00000000000..7d33345cdd9 --- /dev/null +++ b/packages/storage/src/storage-footprint.ts @@ -0,0 +1,332 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { readdir, stat } from 'node:fs/promises'; +import { join } from 'node:path'; +import type { ContextOffloadStore } from '@maka/core/context-offload'; +import { LONG_TERM_MEMORY_DATABASE_NAME } from './long-term-memory-store.js'; +import { + acquireOperationalStateDatabase, + OPERATIONAL_STATE_DATABASE_NAME, + type OperationalStateDatabaseLease, +} from './operational-state-store.js'; + +/** + * Non-overlapping parts of the State Root footprint. + * + * `transcript`, `runtime` and `usage_history` are logical payload bytes stored + * inside runtime.sqlite; `database` is what remains of that file set once they + * are subtracted: other operational records, indexes, page overhead and free + * pages. The parts therefore add up to the measured files without counting a + * byte twice. + */ +export type StorageFootprintKind = + | 'database' + | 'transcript' + | 'runtime' + | 'usage_history' + | 'artifacts' + | 'context_offload' + | 'memory'; + +export interface StorageFootprintTotal { + readonly kind: StorageFootprintKind; + readonly bytes: number; + /** False when the figure is logical payload size rather than bytes on disk. */ + readonly exact: boolean; +} + +export interface StorageFootprint { + readonly totals: readonly StorageFootprintTotal[]; + /** Free pages in runtime.sqlite that a future VACUUM could return to the OS. */ + readonly reclaimableBytes: number; + /** Live Subagent worktrees; counted, never walked, because a checkout can be huge. */ + readonly worktreeCount: number; +} + +export interface SessionStorageFootprint { + readonly sessionId: string; + readonly bytes: { + readonly transcript: number; + readonly runtime: number; + readonly artifacts: number; + /** + * Logical context-offload bytes referenced by this Session. Blobs are + * deduplicated across Sessions, so this can exceed what deleting it frees. + * Absent when the context-offload Store is unavailable. + */ + readonly context?: number; + }; + /** Worktrees bound to this Session or to its direct Subagent children. */ + readonly worktreeCount: number; +} + +export interface StorageFootprintReader { + measure(): Promise; + measureSessions(sessionIds: readonly string[]): Promise; + close(): void; +} + +export interface OpenStorageFootprintReaderOptions { + readonly contextOffload?: Pick; +} + +const SUBAGENT_WORKTREE_DIRECTORY = 'subagent-worktrees'; +const SQLITE_SIDECAR_SUFFIXES = ['', '-wal', '-shm'] as const; +const SESSION_BATCH_SIZE = 100; + +/** + * Sums of logical payload bytes. `octet_length` on a TEXT column and `length` + * on a BLOB column read the record header only, so none of these loads the + * overflow pages that hold large payloads. Every table is scanned through an + * existing `session_id`-leading index when a Session filter is present. + */ +const TRANSCRIPT_SOURCES = [ + { table: 'session_messages', bytes: 'octet_length(record_json)' }, + { table: 'session_message_chunks', bytes: 'length(data)' }, +] as const; + +const RUNTIME_SOURCES = [ + { table: 'runtime_events', bytes: 'octet_length(payload_json)' }, + { + table: 'runtime_partial_snapshots', + bytes: 'octet_length(payload_json) + octet_length(text_content)', + }, + { table: 'core_agent_run_events', bytes: 'octet_length(record_json)' }, +] as const; + +const USAGE_HISTORY_SOURCES = [ + { table: 'usage_llm_calls', bytes: 'octet_length(record_json)' }, + { table: 'usage_tool_invocations', bytes: 'octet_length(record_json)' }, + { + table: 'usage_model_call_attempts', + bytes: `octet_length(attempt_id) + COALESCE(octet_length(session_id), 0) + + COALESCE(octet_length(logical_call_id), 0) + COALESCE(octet_length(turn_id), 0) + + COALESCE(octet_length(connection_slug), 0) + COALESCE(octet_length(provider_id), 0) + + COALESCE(octet_length(model_id), 0)`, + }, +] as const; + +const ARTIFACT_BYTES = "COALESCE(json_extract(record_json, '$.sizeBytes'), 0)"; +const HAS_WORKTREE = "json_extract(payload_json, '$.subagentWorkspace') IS NOT NULL"; + +/** + * Opens a read-only footprint reader over one State Root. It shares the + * process-local runtime.sqlite connection and adds no triggers or counters, so + * the write path pays nothing for it (#5038). Measurements run one statement + * at a time and yield between them rather than holding a read transaction, so + * the totals are a close estimate, not a snapshot. + */ +export function openStorageFootprintReader( + root: string, + options: OpenStorageFootprintReaderOptions = {}, +): StorageFootprintReader { + const lease = acquireOperationalStateDatabase(root, { schemaMigration: 'require_current' }); + return new SqliteStorageFootprintReader(root, lease, options.contextOffload); +} + +class SqliteStorageFootprintReader implements StorageFootprintReader { + #closed = false; + + constructor( + private readonly root: string, + private readonly lease: OperationalStateDatabaseLease, + private readonly contextOffload: Pick | undefined, + ) {} + + async measure(): Promise { + this.#assertOpen(); + const databaseBytes = await fileSetBytes(join(this.root, OPERATIONAL_STATE_DATABASE_NAME)); + const transcript = await this.#sumAll(TRANSCRIPT_SOURCES); + const runtime = await this.#sumAll(RUNTIME_SOURCES); + const usageHistory = await this.#sumAll(USAGE_HISTORY_SOURCES); + const artifacts = await this.#sumAll([{ table: 'artifact_records', bytes: ARTIFACT_BYTES }]); + const reclaimableBytes = this.#readReclaimableBytes(); + const memoryBytes = await fileSetBytes(join(this.root, LONG_TERM_MEMORY_DATABASE_NAME)); + const contextUsage = await this.contextOffload?.usage(); + const worktreeCount = await countDirectories(join(this.root, SUBAGENT_WORKTREE_DIRECTORY)); + const totals: StorageFootprintTotal[] = [ + { + kind: 'database', + bytes: Math.max(0, databaseBytes - transcript - runtime - usageHistory), + exact: false, + }, + { kind: 'transcript', bytes: transcript, exact: false }, + { kind: 'runtime', bytes: runtime, exact: false }, + { kind: 'usage_history', bytes: usageHistory, exact: false }, + { kind: 'artifacts', bytes: artifacts, exact: true }, + ...(contextUsage + ? [{ kind: 'context_offload' as const, bytes: contextUsage.physicalBytes, exact: false }] + : []), + { kind: 'memory', bytes: memoryBytes, exact: true }, + ]; + return { totals, reclaimableBytes, worktreeCount }; + } + + async measureSessions( + sessionIds: readonly string[], + ): Promise { + this.#assertOpen(); + const unique = [...new Set(sessionIds)]; + const results: SessionStorageFootprint[] = []; + for (let offset = 0; offset < unique.length; offset += SESSION_BATCH_SIZE) { + const batch = unique.slice(offset, offset + SESSION_BATCH_SIZE); + const transcript = this.#sumBySession(TRANSCRIPT_SOURCES, batch); + const runtime = this.#sumBySession(RUNTIME_SOURCES, batch); + const artifacts = this.#sumBySession( + [{ table: 'artifact_records', bytes: ARTIFACT_BYTES }], + batch, + ); + const worktrees = this.#countWorktreesBySession(batch); + for (const sessionId of batch) { + const context = this.contextOffload + ? (await this.contextOffload.usage(sessionId)).logicalBytes + : undefined; + results.push({ + sessionId, + bytes: { + transcript: transcript.get(sessionId) ?? 0, + runtime: runtime.get(sessionId) ?? 0, + artifacts: artifacts.get(sessionId) ?? 0, + ...(context === undefined ? {} : { context }), + }, + worktreeCount: worktrees.get(sessionId) ?? 0, + }); + } + await yieldToEventLoop(); + } + return results; + } + + close(): void { + if (this.#closed) return; + this.#closed = true; + this.lease.close(); + } + + async #sumAll(sources: readonly SqlByteSource[]): Promise { + let total = 0; + for (const source of sources) { + const row = this.lease.database + .prepare(`SELECT COALESCE(SUM(${source.bytes}), 0) AS bytes FROM ${source.table}`) + .get() as { bytes: number | bigint }; + total += toSafeCount(row.bytes); + await yieldToEventLoop(); + } + return total; + } + + #sumBySession( + sources: readonly SqlByteSource[], + sessionIds: readonly string[], + ): Map { + const totals = new Map(); + const placeholders = sessionIds.map(() => '?').join(', '); + for (const source of sources) { + const rows = this.lease.database + .prepare( + `SELECT session_id AS sessionId, COALESCE(SUM(${source.bytes}), 0) AS bytes + FROM ${source.table} + WHERE session_id IN (${placeholders}) + GROUP BY session_id`, + ) + .all(...sessionIds) as Array<{ sessionId: string; bytes: number | bigint }>; + for (const row of rows) { + totals.set(row.sessionId, (totals.get(row.sessionId) ?? 0) + toSafeCount(row.bytes)); + } + } + return totals; + } + + #countWorktreesBySession(sessionIds: readonly string[]): Map { + const placeholders = sessionIds.map(() => '?').join(', '); + const rows = this.lease.database + .prepare( + `SELECT owner AS sessionId, COUNT(*) AS count FROM ( + SELECT session_id AS owner FROM session_metadata + WHERE session_id IN (${placeholders}) AND ${HAS_WORKTREE} + UNION ALL + SELECT subagent_parent_session_id AS owner FROM session_metadata + WHERE subagent_parent_session_id IN (${placeholders}) AND ${HAS_WORKTREE} + ) + GROUP BY owner`, + ) + .all(...sessionIds, ...sessionIds) as Array<{ sessionId: string; count: number | bigint }>; + return new Map(rows.map((row) => [row.sessionId, toSafeCount(row.count)])); + } + + #readReclaimableBytes(): number { + const pageSize = this.lease.database.prepare('PRAGMA page_size').get() as { + page_size: number | bigint; + }; + const freelist = this.lease.database.prepare('PRAGMA freelist_count').get() as { + freelist_count: number | bigint; + }; + return toSafeCount(freelist.freelist_count) * toSafeCount(pageSize.page_size); + } + + #assertOpen(): void { + if (this.#closed) throw new Error('Storage footprint reader is closed'); + } +} + +interface SqlByteSource { + readonly table: string; + readonly bytes: string; +} + +async function fileSetBytes(databasePath: string): Promise { + let total = 0; + for (const suffix of SQLITE_SIDECAR_SUFFIXES) { + try { + total += (await stat(`${databasePath}${suffix}`)).size; + } catch (error) { + if (!isMissingFile(error)) throw error; + } + } + return total; +} + +async function countDirectories(path: string): Promise { + try { + const entries = await readdir(path, { withFileTypes: true }); + return entries.filter((entry) => entry.isDirectory()).length; + } catch (error) { + if (isMissingFile(error)) return 0; + throw error; + } +} + +function toSafeCount(value: number | bigint): number { + const count = Number(value); + if (!Number.isSafeInteger(count) || count < 0) { + throw new Error('Storage footprint measurement is out of range'); + } + return count; +} + +function isMissingFile(error: unknown): boolean { + return ( + error instanceof Error && 'code' in error && (error as NodeJS.ErrnoException).code === 'ENOENT' + ); +} + +function yieldToEventLoop(): Promise { + return new Promise((resolve) => setImmediate(resolve)); +} diff --git a/packages/storage/src/storage-writer-composition.ts b/packages/storage/src/storage-writer-composition.ts index 568b922a20e..d63e14ca1d2 100644 --- a/packages/storage/src/storage-writer-composition.ts +++ b/packages/storage/src/storage-writer-composition.ts @@ -28,13 +28,29 @@ import { openInteractiveLongTermMemoryStoreForWrite } from './long-term-memory-s import { openInteractiveMemoryBundleStoreForWrite } from './memory-bundle-store.js'; import { openInteractivePlanStoreForWrite } from './plan-authority.js'; import { openInteractiveProjectCatalogForWrite } from './project-catalog-authority.js'; -import { assertStorageRootLease, type StorageRootLease } from './root-authority.js'; +import { + assertStorageRootLease, + runWithStorageRootLease, + type StorageRootLease, +} from './root-authority.js'; import { openInteractiveRuntimePolicyStoresForWrite } from './runtime-policy-stores.js'; import { openInteractiveScheduledTaskStoreForWrite } from './scheduled-task-store.js'; import { openInteractiveSessionTodoStoreForWrite } from './session-todo-authority.js'; import { openInteractiveShellRunStoreForWrite } from './shell-run-authority.js'; +import { + openStorageFootprintReader, + type SessionStorageFootprint, + type StorageFootprint, +} from './storage-footprint.js'; import { openInteractiveUsageStoresForWrite } from './usage-stores.js'; +export type { + SessionStorageFootprint, + StorageFootprint, + StorageFootprintKind, + StorageFootprintTotal, +} from './storage-footprint.js'; + export interface OpenStorageWriterCompositionOptions { /** One trusted backend for the complete execution transaction domain. */ executionProvider?: ExecutionPersistenceProvider; @@ -63,9 +79,16 @@ export interface StorageWriterComposition { readonly contextOffloadUnavailable?: { readonly cause: unknown }; readonly usage: Awaited>; readonly shellRuns: Awaited>; + readonly footprint: InteractiveStorageFootprintReader; close(): Promise; } +/** Read-only State Root size measurement, bound to the composition's write lease. */ +export interface InteractiveStorageFootprintReader { + measure(): Promise; + measureSessions(sessionIds: readonly string[]): Promise; +} + const activeCompositions = new WeakSet(); export async function openStorageWriterComposition( @@ -178,6 +201,21 @@ async function createComposition( () => openInteractiveShellRunStoreForWrite(lease), closeWriter, ); + const footprintReader = await openWriter( + async () => + openStorageFootprintReader(lease.canonicalPath, { + ...(contextOffload ? { contextOffload } : {}), + }), + (reader) => reader.close(), + ); + const footprint: InteractiveStorageFootprintReader = Object.freeze({ + measure: () => + runWithStorageRootLease(lease, 'interactive', 'write', () => footprintReader.measure()), + measureSessions: (sessionIds: readonly string[]) => + runWithStorageRootLease(lease, 'interactive', 'write', () => + footprintReader.measureSessions(sessionIds), + ), + }); return Object.freeze({ execution, projectCatalog, @@ -194,6 +232,7 @@ async function createComposition( ...(contextOffloadUnavailable ? { contextOffloadUnavailable } : {}), usage, shellRuns, + footprint, close, }); } From bc635bc492d9dc471f33bff9607324e4c1951661 Mon Sep 17 00:00:00 2001 From: liugddx Date: Tue, 29 Sep 2026 18:19:26 +0800 Subject: [PATCH 2/4] fix(storage): keep storage usage measurement off the Host's hot path Review of the first M1 cut showed the full-table payload sums behind the transcript/runtime/usage_history totals read every leaf page in one synchronous call and blocked the Host event loop. - Totals report only facts that are cheap to learn: the runtime.sqlite file set (exact), artifact metadata sizes (not exact), context-offload blob bytes plus its SQLite file set, and the memory file set. The -wal/-shm/-journal sidecar list is shared with the long-term memory store. Reclaimable space and the worktree count are unchanged. - Split the protocol into `storage.usage.query` (totals) and `storage.usage.sessions.query` (per-Session), so measuring rows never computes totals. The 15s totals cache is gone; concurrent requests still share one scan, so Refresh re-measures. - Per-Session measurement yields after every statement, is capped at 25 Sessions per request, and omits Sessions the Host does not hold instead of reporting 0 B. The result is an ordered subsequence of the request. - Desktop measures rows one bounded request at a time, caches results for 60s and failures for a 30s cooldown, and a failing Host no longer hides other Hosts' sizes. The loader lives in the feature provider, so the Tasks page only gains the size label. - Reuse and extend @maka/ui formatBytes (GB/TB, optional locale) instead of a second formatter; kind order and copy are exhaustive over STORAGE_USAGE_KINDS; the Storage group drops the previous Host's figures when the Host or its generation changes. Co-Authored-By: Claude Opus 5.5 (1M context) --- .../__tests__/session-storage-loader.test.ts | 78 +++++-- .../__tests__/storage-usage-section.test.ts | 18 +- .../main/runtime-host-renderer-ipc-main.ts | 2 + apps/desktop/src/preload/bridge-contract.d.ts | 4 +- apps/desktop/src/preload/preload.ts | 55 ++--- .../runtime-host-renderer-operations.ts | 1 + .../src/preload/session-storage-usage.ts | 82 +++++++ .../runtime-host-settings-target.tsx | 4 + .../renderer/features/storage-usage/index.ts | 2 +- .../model/session-storage-loader.ts | 102 +++++---- .../storage-usage/services-context.tsx | 28 ++- .../features/storage-usage/testing.ts | 6 +- .../ui/storage-usage-section.tsx | 55 ++--- .../storage-usage/ui/task-storage-size.tsx | 44 +--- .../renderer/locales/storage-usage-copy.ts | 75 +++---- .../renderer/settings/tasks-settings-page.tsx | 106 +++++---- .../storage-usage-coordinator.test.ts | 112 +++++----- .../__tests__/storage-usage-protocol.test.ts | 119 +++++++---- packages/runtime-host/src/protocol/index.ts | 5 +- .../runtime-host/src/protocol/operations.ts | 1 + .../src/protocol/storage-usage.ts | 154 +++++++------ .../src/server/storage-usage-coordinator.ts | 81 +++---- .../src/__tests__/storage-footprint.test.ts | 40 ++-- .../src/git-worktree-child-executor.ts | 5 +- .../storage/src/sqlite-file-set.ts | 21 +- .../src/sqlite-long-term-memory-store.ts | 5 +- packages/storage/src/storage-footprint.ts | 202 +++++++++--------- .../ui/src/__tests__/format-bytes.test.ts | 33 +++ .../ui/src/tool-activity/preview-utils.ts | 22 +- 29 files changed, 821 insertions(+), 641 deletions(-) create mode 100644 apps/desktop/src/preload/session-storage-usage.ts rename apps/desktop/src/renderer/features/storage-usage/model/format-storage-size.ts => packages/storage/src/sqlite-file-set.ts (56%) create mode 100644 packages/ui/src/__tests__/format-bytes.test.ts diff --git a/apps/desktop/src/main/__tests__/session-storage-loader.test.ts b/apps/desktop/src/main/__tests__/session-storage-loader.test.ts index d1d7cd8ebf4..a49ff0dc476 100644 --- a/apps/desktop/src/main/__tests__/session-storage-loader.test.ts +++ b/apps/desktop/src/main/__tests__/session-storage-loader.test.ts @@ -19,44 +19,90 @@ import { strict as assert } from 'node:assert'; import { test } from 'node:test'; -import type { SessionStorageUsage } from '@maka/runtime-host/protocol'; -import { createSessionStorageLoader } from '../../renderer/features/storage-usage/testing.js'; +import { + STORAGE_USAGE_SESSION_MAX_ITEMS, + type SessionStorageUsage, +} from '@maka/runtime-host/protocol'; +import { + createSessionStorageLoader, + SESSION_STORAGE_FAILURE_COOLDOWN_MS, + SESSION_STORAGE_RESULT_TTL_MS, +} from '../../renderer/features/storage-usage/testing.js'; +import { loadSessionStorageUsage } from '../../preload/session-storage-usage.js'; function usage(sessionId: string): SessionStorageUsage { return { sessionId, bytes: { transcript: 1, runtime: 2, artifacts: 3 }, worktreeCount: 0 }; } -test('rows that mount together share bounded queries and are measured once', async () => { +test('rows that mount together are measured in bounded requests, one at a time', async () => { const queries: string[][] = []; + let inFlight = 0; + let maxInFlight = 0; const loader = createSessionStorageLoader(async (sessionIds) => { + inFlight += 1; + maxInFlight = Math.max(maxInFlight, inFlight); queries.push([...sessionIds]); + await new Promise((resolve) => setImmediate(resolve)); + inFlight -= 1; return Object.fromEntries(sessionIds.map((id) => [id, usage(id)])); }); - const ids = Array.from({ length: 101 }, (_, index) => `session-${index}`); + const count = STORAGE_USAGE_SESSION_MAX_ITEMS * 2 + 1; + const ids = Array.from({ length: count }, (_, index) => `session-${index}`); const measured = await Promise.all([...ids, 'session-0'].map((id) => loader.load(id))); assert.deepEqual( queries.map((query) => query.length), - [100, 1], + [STORAGE_USAGE_SESSION_MAX_ITEMS, STORAGE_USAGE_SESSION_MAX_ITEMS, 1], ); - assert.equal(measured[0]?.sessionId, 'session-0'); - assert.equal(measured[101], measured[0]); - + assert.equal(maxInFlight, 1); + assert.equal(measured[count], measured[0]); await loader.load('session-5'); - assert.equal(queries.length, 2, 'a measured row is served from the list cache'); + assert.equal(queries.length, 3, 'a fresh measurement is served from the cache'); }); -test('a failed or missing measurement renders nothing and is retried later', async () => { +test('failures and unknown tasks wait out a cooldown; measured sizes expire', async () => { + let now = 0; let fail = true; const queries: string[][] = []; - const loader = createSessionStorageLoader(async (sessionIds) => { - queries.push([...sessionIds]); - if (fail) throw new Error('Runtime Host unavailable'); - return { 'session-a': usage('session-a') }; - }); + const loader = createSessionStorageLoader( + async (sessionIds) => { + queries.push([...sessionIds]); + if (fail) throw new Error('Runtime Host unavailable'); + return { 'session-a': usage('session-a') }; + }, + { now: () => now }, + ); assert.equal(await loader.load('session-a'), undefined); fail = false; + assert.equal(await loader.load('session-a'), undefined, 'a remount inside the cooldown waits'); + now += SESSION_STORAGE_FAILURE_COOLDOWN_MS; assert.equal((await loader.load('session-a'))?.sessionId, 'session-a'); assert.equal(await loader.load('session-gone'), undefined); assert.equal(await loader.load('session-gone'), undefined); - assert.deepEqual(queries, [['session-a'], ['session-a'], ['session-gone'], ['session-gone']]); + now += SESSION_STORAGE_RESULT_TTL_MS; + await loader.load('session-a'); + assert.deepEqual(queries, [['session-a'], ['session-a'], ['session-gone'], ['session-a']]); +}); + +test('preload keeps one Host’s task sizes when another Host fails', async () => { + const routes: Record = { + 'desktop-a1': { scope: 'host-a', sessionId: 'a1' }, + 'desktop-a2': { scope: 'host-a', sessionId: 'a2' }, + 'desktop-b1': { scope: 'host-b', sessionId: 'b1' }, + }; + const result = await loadSessionStorageUsage( + ['desktop-a1', 'desktop-b1', 'desktop-a2', 'desktop-missing'], + { + resolve: async (sessionId) => { + const route = routes[sessionId]; + if (!route) throw new Error('The Runtime Host for this task is unavailable'); + return { ...route, scopeKey: route.scope }; + }, + query: async (scope, sessionIds) => { + if (scope === 'host-b') throw new Error('Runtime Host disconnected'); + // `a2` is not on its Host, so the Host omits it. + return sessionIds.filter((id) => id !== 'a2').map(usage); + }, + }, + ); + assert.deepEqual(result, { 'desktop-a1': usage('a1') }); }); diff --git a/apps/desktop/src/main/__tests__/storage-usage-section.test.ts b/apps/desktop/src/main/__tests__/storage-usage-section.test.ts index c8d7928b9b6..6dbb3a197ef 100644 --- a/apps/desktop/src/main/__tests__/storage-usage-section.test.ts +++ b/apps/desktop/src/main/__tests__/storage-usage-section.test.ts @@ -59,9 +59,9 @@ test('the Storage section reads the selected Host once and states its caveats', const usage: StorageUsageQueryResult = { measuredAt: 1, totals: [ - { kind: 'database', bytes: 3 * 1024 * 1024, exact: false }, - { kind: 'artifacts', bytes: 1024 * 1024, exact: true }, - { kind: 'usage_history', bytes: 2048, exact: false }, + { kind: 'memory', bytes: 2048, exact: true }, + { kind: 'database', bytes: 3 * 1024 * 1024, exact: true }, + { kind: 'artifacts', bytes: 1024 * 1024, exact: false }, ], reclaimableBytes: 512 * 1024, worktreeCount: 2, @@ -96,11 +96,15 @@ test('the Storage section reads the selected Host once and states its caveats', const text = container.textContent ?? ''; assert.deepEqual(requests, [host]); assert.match(text, /Total/); - assert.match(text, /≈ 4 MB/); - assert.match(text, /Artifacts/); - assert.match(text, /Kept after a task is deleted/); + assert.match(text, /≈ 4\.0 MB/); + // Rows follow the protocol's kind order, not the order the Host sent them in. + assert.ok(text.indexOf('Task database') < text.indexOf('Artifacts')); + assert.ok(text.indexOf('Artifacts') < text.indexOf('Long-term memory')); + assert.match(text, /3\.0 MB/); + assert.match(text, /≈ 1\.0 MB/); + assert.match(text, /Usage history is kept after a task is deleted/); assert.match(text, /2 worktrees/); - assert.match(text, /512 kB/); + assert.match(text, /512\.0 KB/); // Only measured kinds are listed; nothing offers to delete or compact. assert.doesNotMatch(text, /Offloaded context/); assert.doesNotMatch(text, /Delete|Compact|Vacuum/); diff --git a/apps/desktop/src/main/runtime-host-renderer-ipc-main.ts b/apps/desktop/src/main/runtime-host-renderer-ipc-main.ts index 9399b672ce2..54c7f104fea 100644 --- a/apps/desktop/src/main/runtime-host-renderer-ipc-main.ts +++ b/apps/desktop/src/main/runtime-host-renderer-ipc-main.ts @@ -102,6 +102,8 @@ function request( return client.request(operation, HOST_OPERATION_SPECS[operation].decodeInput(value)); case 'storage.usage.query': return client.request(operation, HOST_OPERATION_SPECS[operation].decodeInput(value)); + case 'storage.usage.sessions.query': + return client.request(operation, HOST_OPERATION_SPECS[operation].decodeInput(value)); case 'web-search.execute': return client.request(operation, HOST_OPERATION_SPECS[operation].decodeInput(value)); } diff --git a/apps/desktop/src/preload/bridge-contract.d.ts b/apps/desktop/src/preload/bridge-contract.d.ts index 8c6122825b5..79d014f8124 100644 --- a/apps/desktop/src/preload/bridge-contract.d.ts +++ b/apps/desktop/src/preload/bridge-contract.d.ts @@ -1842,8 +1842,8 @@ export interface MakaBridge { /** One Runtime Host's State Root footprint. Read-only; nothing is reclaimed. */ usage(host?: DesktopRuntimeHostRef): Promise; /** - * Per-task storage keyed by Desktop session id. A task whose Runtime Host is - * unavailable is absent from the result rather than failing the others. + * Per-task storage keyed by Desktop session id. A task is absent when its + * Runtime Host is unavailable or fails, or when that Host no longer holds it. */ sessionUsage(sessionIds: readonly string[]): Promise>; }; diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts index 0232f5c6edd..c646e4330fb 100644 --- a/apps/desktop/src/preload/preload.ts +++ b/apps/desktop/src/preload/preload.ts @@ -251,7 +251,6 @@ import type { OnboardingMilestoneId } from '@maka/core/onboarding'; import { decodeSharedSessionCatalogProjection, SCHEDULED_TASK_CATALOG_MAX_ITEMS, - STORAGE_USAGE_SESSION_MAX_ITEMS, type OperationInput, type OperationOutcome, type OperationOutput, @@ -262,6 +261,7 @@ import { type StorageUsageQueryResult, } from '@maka/runtime-host/protocol'; import type { PlanControlIpcResult } from '../shared/plan-mode-ipc.js'; +import { loadSessionStorageUsage } from './session-storage-usage.js'; import type { AgentGraphEpochDirectory } from '@maka/runtime-host/client'; import { desktopSessionKey, @@ -1249,46 +1249,21 @@ const runtimeHost: MakaBridge['runtimeHost'] = { }, }; -/** - * Per-task storage keyed by Desktop session id. Tasks are grouped by the Host - * that owns them; a task whose Host is unavailable is left out rather than - * failing the rest. - */ -async function loadSessionStorageUsage( +function loadDesktopSessionStorageUsage( sessionIds: readonly string[], ): Promise> { - const byScope = new Map< - RuntimeHostScopeKey, - { scope: DesktopTargetScope; desktopIds: Map } - >(); - for (const sessionId of new Set(sessionIds)) { - let ref: Awaited>; - try { - ref = await runtimeHostSessionRef(sessionId); - } catch { - continue; - } - const key = runtimeHostScopeKey(ref.scope); - const group = byScope.get(key) ?? { scope: ref.scope, desktopIds: new Map() }; - group.desktopIds.set(ref.sessionId, sessionId); - byScope.set(key, group); - } - const usage: Record = {}; - await Promise.all( - [...byScope.values()].map(async ({ scope, desktopIds }) => { - const hostIds = [...desktopIds.keys()]; - for (let offset = 0; offset < hostIds.length; offset += STORAGE_USAGE_SESSION_MAX_ITEMS) { - const result = await scopedRuntimeHost(scope).query('storage.usage.query', { - sessionIds: hostIds.slice(offset, offset + STORAGE_USAGE_SESSION_MAX_ITEMS), - }); - for (const session of result.sessions ?? []) { - const desktopId = desktopIds.get(session.sessionId); - if (desktopId) usage[desktopId] = session; - } - } - }), - ); - return usage; + return loadSessionStorageUsage(sessionIds, { + resolve: async (sessionId) => { + const ref = await runtimeHostSessionRef(sessionId); + return { ...ref, scopeKey: runtimeHostScopeKey(ref.scope) }; + }, + query: async (scope: DesktopTargetScope, hostIds) => + ( + await scopedRuntimeHost(scope).query('storage.usage.sessions.query', { + sessionIds: hostIds, + }) + ).sessions, + }); } async function listScheduledTasks(target?: DesktopRuntimeHostRef): Promise { @@ -3745,7 +3720,7 @@ const makaBridge = { return scopedRuntimeHost(await selectedRuntimeHostScope(host)).query('storage.usage.query', {}); }, sessionUsage(sessionIds: readonly string[]): Promise> { - return loadSessionStorageUsage(sessionIds); + return loadDesktopSessionStorageUsage(sessionIds); }, }, dailyReview: { diff --git a/apps/desktop/src/preload/runtime-host-renderer-operations.ts b/apps/desktop/src/preload/runtime-host-renderer-operations.ts index a0645d0433a..d327cb205dd 100644 --- a/apps/desktop/src/preload/runtime-host-renderer-operations.ts +++ b/apps/desktop/src/preload/runtime-host-renderer-operations.ts @@ -29,6 +29,7 @@ export const RENDERER_RUNTIME_HOST_QUERY_OPERATIONS = [ 'scheduled-task.query', // Read-only State Root and per-task size measurement; it reclaims nothing. 'storage.usage.query', + 'storage.usage.sessions.query', ] as const satisfies readonly (keyof OperationSpecMap)[]; export const RENDERER_RUNTIME_HOST_COMMAND_OPERATIONS = [ diff --git a/apps/desktop/src/preload/session-storage-usage.ts b/apps/desktop/src/preload/session-storage-usage.ts new file mode 100644 index 00000000000..8c1791d3249 --- /dev/null +++ b/apps/desktop/src/preload/session-storage-usage.ts @@ -0,0 +1,82 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { + STORAGE_USAGE_SESSION_MAX_ITEMS, + type SessionStorageUsage, +} from '@maka/runtime-host/protocol'; + +export interface SessionStorageUsageRouting { + /** Resolves a Desktop session id to its Host scope; rejects when the Host is gone. */ + resolve(sessionId: string): Promise<{ + readonly scope: Scope; + readonly scopeKey: string; + readonly sessionId: string; + }>; + /** One `storage.usage.sessions.query` against one Host. */ + query(scope: Scope, sessionIds: readonly string[]): Promise; +} + +/** + * Per-task storage keyed by Desktop session id. Tasks are grouped by the Host + * that holds them and each Host is paged one bounded request at a time. A task + * whose Host cannot be resolved, or a Host whose query fails, is left out + * rather than failing the other Hosts' tasks. + */ +export async function loadSessionStorageUsage( + sessionIds: readonly string[], + routing: SessionStorageUsageRouting, +): Promise> { + const byScope = new Map }>(); + for (const sessionId of new Set(sessionIds)) { + let ref: Awaited['resolve']>>; + try { + ref = await routing.resolve(sessionId); + } catch { + continue; + } + const group = byScope.get(ref.scopeKey) ?? { + scope: ref.scope, + desktopIds: new Map(), + }; + group.desktopIds.set(ref.sessionId, sessionId); + byScope.set(ref.scopeKey, group); + } + const usage: Record = {}; + await Promise.all( + [...byScope.values()].map(async ({ scope, desktopIds }) => { + const hostIds = [...desktopIds.keys()]; + try { + for (let offset = 0; offset < hostIds.length; offset += STORAGE_USAGE_SESSION_MAX_ITEMS) { + const sessions = await routing.query( + scope, + hostIds.slice(offset, offset + STORAGE_USAGE_SESSION_MAX_ITEMS), + ); + for (const session of sessions) { + const desktopId = desktopIds.get(session.sessionId); + if (desktopId) usage[desktopId] = session; + } + } + } catch { + // This Host's remaining tasks stay unknown; the other Hosts still answer. + } + }), + ); + return usage; +} diff --git a/apps/desktop/src/renderer/application/contracts/settings-presentation/runtime-host-settings-target.tsx b/apps/desktop/src/renderer/application/contracts/settings-presentation/runtime-host-settings-target.tsx index 28ca53082b6..78ad53e0185 100644 --- a/apps/desktop/src/renderer/application/contracts/settings-presentation/runtime-host-settings-target.tsx +++ b/apps/desktop/src/renderer/application/contracts/settings-presentation/runtime-host-settings-target.tsx @@ -71,6 +71,10 @@ export function useOptionalRuntimeHostSettingsTarget(): SettingsHostTarget | und return useContext(RuntimeHostSettingsTargetContext)?.host; } +export function useOptionalRuntimeHostSettingsGenerationKey(): string | undefined { + return useContext(RuntimeHostSettingsTargetContext)?.generationKey; +} + export function useRuntimeHostSettingsGenerationKey(): string { const target = useContext(RuntimeHostSettingsTargetContext); if (!target) throw new Error("Runtime Host Settings target is unavailable"); diff --git a/apps/desktop/src/renderer/features/storage-usage/index.ts b/apps/desktop/src/renderer/features/storage-usage/index.ts index 7e3b987206d..f64555059a9 100644 --- a/apps/desktop/src/renderer/features/storage-usage/index.ts +++ b/apps/desktop/src/renderer/features/storage-usage/index.ts @@ -21,6 +21,6 @@ // from this barrel and render these surfaces; they hold no storage state. export { StorageUsageSection } from './ui/storage-usage-section.js'; -export { TaskStorageSize, TaskStorageSizeScope } from './ui/task-storage-size.js'; +export { TaskStorageSize } from './ui/task-storage-size.js'; export { StorageUsageServicesProvider } from './services-context.js'; export type { StorageUsageHostTarget, StorageUsageServices } from './ports.js'; diff --git a/apps/desktop/src/renderer/features/storage-usage/model/session-storage-loader.ts b/apps/desktop/src/renderer/features/storage-usage/model/session-storage-loader.ts index a202ed3cc54..80b6f382496 100644 --- a/apps/desktop/src/renderer/features/storage-usage/model/session-storage-loader.ts +++ b/apps/desktop/src/renderer/features/storage-usage/model/session-storage-loader.ts @@ -17,66 +17,90 @@ * under the License. */ -import type { SessionStorageUsage } from '@maka/runtime-host/protocol'; +import { + STORAGE_USAGE_SESSION_MAX_ITEMS, + type SessionStorageUsage, +} from '@maka/runtime-host/protocol'; -/** One Host query measures at most this many Sessions. */ -const BATCH_SIZE = 100; +/** A measured size is reused this long before a remounted row asks again. */ +export const SESSION_STORAGE_RESULT_TTL_MS = 60_000; +/** A task that could not be measured is not asked about again this soon. */ +export const SESSION_STORAGE_FAILURE_COOLDOWN_MS = 30_000; export interface SessionStorageLoader { - /** Resolves undefined when the size could not be measured. */ + /** Resolves undefined when the size is unknown: unmeasurable or not on its Host. */ load(sessionId: string): Promise; } +interface Entry { + readonly result: Promise; + settledAt?: number; + measured?: boolean; +} + /** - * Coalesces the size requests of rows that mount together into one query, so - * a list asks for exactly the rows it renders. Results live as long as the - * loader; a failed measurement is forgotten so a later row can retry it. + * Turns row requests into Host queries. Rows that mount together are queued + * and measured one request at a time, `STORAGE_USAGE_SESSION_MAX_ITEMS` per + * request, so a long list never puts more than one measurement on a Host at + * once. Results and failures are both remembered for a while, so remounting a + * list neither re-measures every row nor hammers a Host that just failed. */ export function createSessionStorageLoader( loadSessionUsage: ( sessionIds: readonly string[], ) => Promise>>, + options: { readonly now?: () => number } = {}, ): SessionStorageLoader { - const results = new Map>(); - let pending = new Map void>(); - let scheduled = false; + const now = options.now ?? Date.now; + const entries = new Map(); + const queue = new Map void>(); + let draining = false; - const flush = () => { - scheduled = false; - const batch = pending; - pending = new Map(); - const ids = [...batch.keys()]; - for (let offset = 0; offset < ids.length; offset += BATCH_SIZE) { - const chunk = ids.slice(offset, offset + BATCH_SIZE); - loadSessionUsage(chunk).then( - (usage) => { - for (const id of chunk) { - const measured = usage[id]; - if (!measured) results.delete(id); - batch.get(id)?.(measured); - } - }, - () => { - for (const id of chunk) { - results.delete(id); - batch.get(id)?.(undefined); - } - }, - ); + const settle = (sessionId: string, usage: SessionStorageUsage | undefined) => { + const entry = entries.get(sessionId); + if (entry) { + entry.settledAt = now(); + entry.measured = usage !== undefined; } }; + const drain = async () => { + while (queue.size > 0) { + const chunk = [...queue.entries()].slice(0, STORAGE_USAGE_SESSION_MAX_ITEMS); + for (const [sessionId] of chunk) queue.delete(sessionId); + let usage: Readonly> = {}; + try { + usage = await loadSessionUsage(chunk.map(([sessionId]) => sessionId)); + } catch { + // Every id in the chunk settles as unknown and enters its cooldown. + } + for (const [sessionId, resolve] of chunk) { + const measured = usage[sessionId]; + settle(sessionId, measured); + resolve(measured); + } + } + draining = false; + }; + + const isFresh = (entry: Entry): boolean => { + if (entry.settledAt === undefined) return true; + const ttl = entry.measured ? SESSION_STORAGE_RESULT_TTL_MS : SESSION_STORAGE_FAILURE_COOLDOWN_MS; + return now() - entry.settledAt < ttl; + }; + return { load(sessionId) { - const existing = results.get(sessionId); - if (existing) return existing; + const existing = entries.get(sessionId); + if (existing && isFresh(existing)) return existing.result; const result = new Promise((resolve) => { - pending.set(sessionId, resolve); + queue.set(sessionId, resolve); }); - results.set(sessionId, result); - if (!scheduled) { - scheduled = true; - void Promise.resolve().then(flush); + entries.set(sessionId, { result }); + if (!draining) { + draining = true; + // Wait a microtask so every row mounted in this commit joins the batch. + void Promise.resolve().then(drain); } return result; }, diff --git a/apps/desktop/src/renderer/features/storage-usage/services-context.tsx b/apps/desktop/src/renderer/features/storage-usage/services-context.tsx index 6dcecf05c1b..a4707fec51c 100644 --- a/apps/desktop/src/renderer/features/storage-usage/services-context.tsx +++ b/apps/desktop/src/renderer/features/storage-usage/services-context.tsx @@ -17,17 +17,33 @@ * under the License. */ -import { createContext, type ReactNode, useContext } from 'react'; +import { createContext, type ReactNode, useContext, useMemo } from 'react'; +import { createSessionStorageLoader, type SessionStorageLoader } from './model/session-storage-loader.js'; import type { StorageUsageServices } from './ports.js'; -const StorageUsageServicesContext = createContext(undefined); +interface StorageUsageContextValue { + readonly services: StorageUsageServices; + /** One per-task size cache for every list that shows task sizes. */ + readonly sessionLoader: SessionStorageLoader; +} + +const StorageUsageServicesContext = createContext(undefined); export function StorageUsageServicesProvider(props: { readonly services: StorageUsageServices; readonly children?: ReactNode; }) { + const value = useMemo( + () => ({ + services: props.services, + sessionLoader: createSessionStorageLoader((sessionIds) => + props.services.loadSessionUsage(sessionIds), + ), + }), + [props.services], + ); return ( - + {props.children} ); @@ -35,5 +51,9 @@ export function StorageUsageServicesProvider(props: { /** Undefined outside a Desktop composition; the surfaces then render nothing. */ export function useOptionalStorageUsageServices(): StorageUsageServices | undefined { - return useContext(StorageUsageServicesContext); + return useContext(StorageUsageServicesContext)?.services; +} + +export function useOptionalSessionStorageLoader(): SessionStorageLoader | undefined { + return useContext(StorageUsageServicesContext)?.sessionLoader; } diff --git a/apps/desktop/src/renderer/features/storage-usage/testing.ts b/apps/desktop/src/renderer/features/storage-usage/testing.ts index fdc6b7b5126..a21c3b0d5f7 100644 --- a/apps/desktop/src/renderer/features/storage-usage/testing.ts +++ b/apps/desktop/src/renderer/features/storage-usage/testing.ts @@ -21,4 +21,8 @@ * Test-only surface. The loader is where row requests become Host queries, so * its batching and retry rules are worth checking without mounting a list. */ -export { createSessionStorageLoader } from './model/session-storage-loader.js'; +export { + createSessionStorageLoader, + SESSION_STORAGE_FAILURE_COOLDOWN_MS, + SESSION_STORAGE_RESULT_TTL_MS, +} from './model/session-storage-loader.js'; diff --git a/apps/desktop/src/renderer/features/storage-usage/ui/storage-usage-section.tsx b/apps/desktop/src/renderer/features/storage-usage/ui/storage-usage-section.tsx index 9512b500ad8..1aa654ff47b 100644 --- a/apps/desktop/src/renderer/features/storage-usage/ui/storage-usage-section.tsx +++ b/apps/desktop/src/renderer/features/storage-usage/ui/storage-usage-section.tsx @@ -19,66 +19,73 @@ import { useEffect, useState } from 'react'; import { Banner } from '@astryxdesign/core/Banner'; -import { Button, useUiLocale } from '@maka/ui'; -import type { StorageUsageKind, StorageUsageQueryResult } from '@maka/runtime-host/protocol'; +import { Button, formatBytes, useUiLocale } from '@maka/ui'; +import { STORAGE_USAGE_KINDS, type StorageUsageQueryResult } from '@maka/runtime-host/protocol'; import { SettingsRow, SettingsSection, + useOptionalRuntimeHostSettingsGenerationKey, useOptionalRuntimeHostSettingsTarget, } from '../../../application/contracts/settings-presentation/index.js'; import { getStorageUsageCopy } from '../../../locales/storage-usage-copy.js'; -import { formatStorageSize } from '../model/format-storage-size.js'; import { useOptionalStorageUsageServices } from '../services-context.js'; -/** Largest-first would reorder between measurements; a fixed order reads the same each visit. */ -const KIND_ORDER: readonly StorageUsageKind[] = [ - 'transcript', - 'runtime', - 'artifacts', - 'context_offload', - 'memory', - 'usage_history', - 'database', -]; - type Measurement = | { readonly status: 'loading'; readonly previous?: StorageUsageQueryResult } | { readonly status: 'ready'; readonly usage: StorageUsageQueryResult } | { readonly status: 'failed' }; +/** Measurements belong to one Host generation; another Host's numbers are never shown. */ +interface ScopedMeasurement { + readonly hostKey: string | undefined; + readonly measurement: Measurement; +} + /** * Settings · Data · Storage: what the selected Runtime Host's data occupies. * Read-only by design; it offers no action that deletes or compacts data. */ export function StorageUsageSection(props: { readonly hostVerified: boolean }) { const host = useOptionalRuntimeHostSettingsTarget(); + const hostKey = useOptionalRuntimeHostSettingsGenerationKey(); const services = useOptionalStorageUsageServices(); const locale = useUiLocale(); const copy = getStorageUsageCopy(locale); - const [measurement, setMeasurement] = useState({ status: 'loading' }); + const [scoped, setScoped] = useState({ + hostKey, + measurement: { status: 'loading' }, + }); const [attempt, setAttempt] = useState(0); useEffect(() => { if (!host || !services || !props.hostVerified) return; let current = true; - setMeasurement((previous) => ({ - status: 'loading', - ...(previous.status === 'ready' ? { previous: previous.usage } : {}), + setScoped((previous) => ({ + hostKey, + measurement: { + status: 'loading', + // A refresh keeps the last figures on screen; a new Host starts empty. + ...(previous.hostKey === hostKey && previous.measurement.status === 'ready' + ? { previous: previous.measurement.usage } + : {}), + }, })); services.loadUsage(host).then( (usage) => { - if (current) setMeasurement({ status: 'ready', usage }); + if (current) setScoped({ hostKey, measurement: { status: 'ready', usage } }); }, () => { - if (current) setMeasurement({ status: 'failed' }); + if (current) setScoped({ hostKey, measurement: { status: 'failed' } }); }, ); return () => { current = false; }; - }, [attempt, host, props.hostVerified, services]); + }, [attempt, host, hostKey, props.hostVerified, services]); if (!host || !services) return null; + const measurement: Measurement = + scoped.hostKey === hostKey ? scoped.measurement : { status: 'loading' }; const usage = measurement.status === 'ready' ? measurement.usage @@ -86,11 +93,11 @@ export function StorageUsageSection(props: { readonly hostVerified: boolean }) { ? measurement.previous : undefined; const size = (bytes: number, exact: boolean) => { - const formatted = formatStorageSize(bytes, locale); + const formatted = formatBytes(bytes, locale); return exact ? formatted : copy.approximately(formatted); }; const totals = usage - ? KIND_ORDER.flatMap((kind) => usage.totals.filter((total) => total.kind === kind)) + ? STORAGE_USAGE_KINDS.flatMap((kind) => usage.totals.filter((total) => total.kind === kind)) : []; const totalBytes = totals.reduce((sum, total) => sum + total.bytes, 0); const placeholder = measurement.status === 'failed' ? copy.loadFailed : copy.loading; @@ -140,7 +147,7 @@ export function StorageUsageSection(props: { readonly hostVerified: boolean }) { align="start" end={( - {formatStorageSize(usage.reclaimableBytes, locale)} + {formatBytes(usage.reclaimableBytes, locale)} )} /> diff --git a/apps/desktop/src/renderer/features/storage-usage/ui/task-storage-size.tsx b/apps/desktop/src/renderer/features/storage-usage/ui/task-storage-size.tsx index 25f0d13c531..967aa632842 100644 --- a/apps/desktop/src/renderer/features/storage-usage/ui/task-storage-size.tsx +++ b/apps/desktop/src/renderer/features/storage-usage/ui/task-storage-size.tsx @@ -17,43 +17,23 @@ * under the License. */ -import { createContext, type ReactNode, useContext, useEffect, useState } from 'react'; +import { useEffect, useState } from 'react'; import { Text } from '@astryxdesign/core/Text'; -import { useUiLocale } from '@maka/ui'; +import { formatBytes, useUiLocale } from '@maka/ui'; import type { SessionStorageUsage } from '@maka/runtime-host/protocol'; import { getStorageUsageCopy } from '../../../locales/storage-usage-copy.js'; -import { formatStorageSize } from '../model/format-storage-size.js'; -import { - createSessionStorageLoader, - sessionStorageBytes, - type SessionStorageLoader, -} from '../model/session-storage-loader.js'; -import { useOptionalStorageUsageServices } from '../services-context.js'; - -const SessionStorageLoaderContext = createContext(undefined); +import { sessionStorageBytes } from '../model/session-storage-loader.js'; +import { useOptionalSessionStorageLoader } from '../services-context.js'; /** - * Owns the per-task size cache for one list. Rows measure themselves as they - * mount, and rows mounted together share one Host query, so only the rows on - * screen are ever measured. + * A task's measured size, or nothing while unknown. Never a guess. + * + * Each mounted row asks for its own size. The archived-task list is not + * virtualized, so every row that passes the search mounts; the shared loader + * measures them sequentially, one bounded Host request at a time. */ -export function TaskStorageSizeScope(props: { readonly children?: ReactNode }) { - const services = useOptionalStorageUsageServices(); - const [loader] = useState(() => - services - ? createSessionStorageLoader((sessionIds) => services.loadSessionUsage(sessionIds)) - : undefined, - ); - return ( - - {props.children} - - ); -} - -/** A task's measured size, or nothing while unknown. Never a guess. */ export function TaskStorageSize(props: { readonly sessionId: string }) { - const loader = useContext(SessionStorageLoaderContext); + const loader = useOptionalSessionStorageLoader(); const locale = useUiLocale(); const [usage, setUsage] = useState(undefined); @@ -72,9 +52,7 @@ export function TaskStorageSize(props: { readonly sessionId: string }) { if (!usage) return null; return ( - {getStorageUsageCopy(locale).taskSize( - formatStorageSize(sessionStorageBytes(usage), locale), - )} + {getStorageUsageCopy(locale).taskSize(formatBytes(sessionStorageBytes(usage), locale))} ); } diff --git a/apps/desktop/src/renderer/locales/storage-usage-copy.ts b/apps/desktop/src/renderer/locales/storage-usage-copy.ts index 349b90b5fae..387cb413612 100644 --- a/apps/desktop/src/renderer/locales/storage-usage-copy.ts +++ b/apps/desktop/src/renderer/locales/storage-usage-copy.ts @@ -18,8 +18,7 @@ */ import type { UiCatalog, UiLocale } from '@maka/core/ui-locale'; - -type StorageUsageKindCopy = { label: string; detail: string }; +import type { StorageUsageKind } from '@maka/runtime-host/protocol'; export type StorageUsageCopy = { title: string; @@ -29,22 +28,14 @@ export type StorageUsageCopy = { refresh: string; total: string; totalDetail: string; - kinds: Record< - | 'transcript' - | 'runtime' - | 'artifacts' - | 'context_offload' - | 'memory' - | 'usage_history' - | 'database', - StorageUsageKindCopy - >; + /** Every kind the Host can report, so a new kind cannot render unlabeled. */ + kinds: Record; reclaimable: string; reclaimableDetail: string; worktrees: string; worktreesDetail: string; worktreeCount(count: number): string; - /** Prefix for a logical estimate rather than bytes on disk. */ + /** Prefix for an estimate rather than bytes on disk. */ approximately(size: string): string; /** Label for a task's size in the archived-task list. */ taskSize(size: string): string; @@ -60,24 +51,21 @@ const STORAGE_USAGE_COPY = { loadFailed: '无法统计存储占用', refresh: '重新统计', total: '合计', - totalDetail: '下列各项之和。标注 ≈ 的是按记录内容估算的大小,不含索引等开销。', + totalDetail: '下列各项之和。标注 ≈ 的是按记录估算的大小,可能与其他项略有重叠。', kinds: { - transcript: { label: '任务对话', detail: '任务的消息记录。' }, - runtime: { label: '运行日志', detail: '任务运行过程中记录的事件。' }, - artifacts: { label: '产物文件', detail: '任务生成或导入的文件。' }, + database: { + label: '任务数据库', + detail: '任务的对话、运行日志、用量历史和索引。用量历史在删除任务后仍会保留,以保证用量统计完整。', + }, + artifacts: { label: '产物文件', detail: '任务生成或导入的文件,按记录的文件大小统计。' }, context_offload: { label: '卸载的上下文', detail: '为节省上下文而移出的长内容,相同内容只保存一份。', }, memory: { label: '长期记忆', detail: '跨任务保留的记忆条目。' }, - usage_history: { - label: '用量历史', - detail: '模型调用与工具使用记录。删除任务后仍会保留,以保证用量统计完整。', - }, - database: { label: '其他数据与索引', detail: '其余任务记录、索引以及数据库中的空闲空间。' }, }, reclaimable: '可回收空间', - reclaimableDetail: '数据库中已释放但尚未归还磁盘的空间,已计入「其他数据与索引」。', + reclaimableDetail: '任务数据库中已释放但尚未归还磁盘的空间,已计入「任务数据库」。', worktrees: '子代理工作树', worktreesDetail: '只统计数量;每个工作树的大小取决于对应项目的检出内容。', worktreeCount: (count: number) => `${count} 个`, @@ -93,24 +81,21 @@ const STORAGE_USAGE_COPY = { loadFailed: '無法統計儲存空間占用', refresh: '重新統計', total: '合計', - totalDetail: '下列各項之和。標註 ≈ 的是依記錄內容估算的大小,不含索引等開銷。', + totalDetail: '下列各項之和。標註 ≈ 的是依記錄估算的大小,可能與其他項略有重疊。', kinds: { - transcript: { label: '任務對話', detail: '任務的訊息記錄。' }, - runtime: { label: '執行日誌', detail: '任務執行過程中記錄的事件。' }, - artifacts: { label: '產物檔案', detail: '任務生成或匯入的檔案。' }, + database: { + label: '任務資料庫', + detail: '任務的對話、執行日誌、用量歷史和索引。用量歷史在刪除任務後仍會保留,以確保用量統計完整。', + }, + artifacts: { label: '產物檔案', detail: '任務生成或匯入的檔案,依記錄的檔案大小統計。' }, context_offload: { label: '卸載的上下文', detail: '為節省上下文而移出的長內容,相同內容只儲存一份。', }, memory: { label: '長期記憶', detail: '跨任務保留的記憶條目。' }, - usage_history: { - label: '用量歷史', - detail: '模型呼叫與工具使用記錄。刪除任務後仍會保留,以確保用量統計完整。', - }, - database: { label: '其他資料與索引', detail: '其餘任務記錄、索引以及資料庫中的閒置空間。' }, }, reclaimable: '可回收空間', - reclaimableDetail: '資料庫中已釋放但尚未歸還磁碟的空間,已計入「其他資料與索引」。', + reclaimableDetail: '任務資料庫中已釋放但尚未歸還磁碟的空間,已計入「任務資料庫」。', worktrees: '子代理工作樹', worktreesDetail: '只統計數量;每個工作樹的大小取決於對應專案的檢出內容。', worktreeCount: (count: number) => `${count} 個`, @@ -127,28 +112,26 @@ const STORAGE_USAGE_COPY = { refresh: 'Measure again', total: 'Total', totalDetail: - 'The sum of the rows below. Values marked ≈ are estimated from record contents and exclude index overhead.', + 'The sum of the rows below. Values marked ≈ are estimated from records and may overlap slightly with another row.', kinds: { - transcript: { label: 'Task conversations', detail: 'Message history of your tasks.' }, - runtime: { label: 'Run logs', detail: 'Events recorded while tasks run.' }, - artifacts: { label: 'Artifacts', detail: 'Files that tasks produced or imported.' }, + database: { + label: 'Task database', + detail: + 'Task conversations, run logs, usage history, and indexes. Usage history is kept after a task is deleted so usage totals stay complete.', + }, + artifacts: { + label: 'Artifacts', + detail: 'Files that tasks produced or imported, by their recorded size.', + }, context_offload: { label: 'Offloaded context', detail: 'Long content moved out of the model context. Identical content is stored once.', }, memory: { label: 'Long-term memory', detail: 'Memories kept across tasks.' }, - usage_history: { - label: 'Usage history', - detail: 'Model call and tool usage records. Kept after a task is deleted so usage totals stay complete.', - }, - database: { - label: 'Other data and indexes', - detail: 'Remaining task records, indexes, and free space inside the database.', - }, }, reclaimable: 'Reclaimable space', reclaimableDetail: - 'Space the database has freed but not returned to the disk. Included in Other data and indexes.', + 'Space the task database has freed but not returned to the disk. Included in Task database.', worktrees: 'Subagent worktrees', worktreesDetail: 'Counted only. Each worktree’s size depends on its project checkout.', worktreeCount: (count: number) => (count === 1 ? '1 worktree' : `${count} worktrees`), diff --git a/apps/desktop/src/renderer/settings/tasks-settings-page.tsx b/apps/desktop/src/renderer/settings/tasks-settings-page.tsx index aad096dd81b..a5c71f2bcc0 100644 --- a/apps/desktop/src/renderer/settings/tasks-settings-page.tsx +++ b/apps/desktop/src/renderer/settings/tasks-settings-page.tsx @@ -32,7 +32,7 @@ import type { SessionCatalogController } from '../application/contracts/session- import { getSettingsSharedCopy } from '../locales/settings-shared-copy.js'; import { getSettingsTasksCopy } from '../locales/settings-tasks-copy.js'; import { getStorageUsageCopy } from '../locales/storage-usage-copy.js'; -import { TaskStorageSize, TaskStorageSizeScope } from '../features/storage-usage/index.js'; +import { TaskStorageSize } from '../features/storage-usage/index.js'; import { settingsActionErrorMessage } from './settings-error-copy'; import { SettingsPage, SettingsSection } from './settings-section'; import { @@ -219,59 +219,57 @@ export function TasksSettingsPage( {visible.length === 0 ? ( ) : ( - - - {visible.map((session) => { - const updated = session.lastMessageAt - ? formatCompactTimestamp(session.lastMessageAt, Date.now(), locale) - : undefined; - const description = [ - isOrphanedSubagentTask(session, knownSessionIds) - ? copy.deletedParent - : undefined, - projectLabelOf(session), - updated, - ] - .filter(Boolean) - .join(' · '); - return ( - 0 ? description : undefined} - startContent={ - + + {visible.map((session) => { + const updated = session.lastMessageAt + ? formatCompactTimestamp(session.lastMessageAt, Date.now(), locale) + : undefined; + const description = [ + isOrphanedSubagentTask(session, knownSessionIds) + ? copy.deletedParent + : undefined, + projectLabelOf(session), + updated, + ] + .filter(Boolean) + .join(' · '); + return ( + 0 ? description : undefined} + startContent={ )} diff --git a/packages/runtime-host/src/__tests__/storage-usage-coordinator.test.ts b/packages/runtime-host/src/__tests__/storage-usage-coordinator.test.ts index aec85cb13ab..b264f5463fc 100644 --- a/packages/runtime-host/src/__tests__/storage-usage-coordinator.test.ts +++ b/packages/runtime-host/src/__tests__/storage-usage-coordinator.test.ts @@ -23,33 +23,25 @@ import type { InteractiveStorageFootprintReader, StorageFootprint, } from '@maka/storage/storage-writer-composition'; -import { HOST_OPERATION_SPECS } from '../protocol/index.js'; import type { ConnectionContext } from '../server/operation-dispatcher.js'; -import { - HostStorageUsageCoordinator, - STORAGE_USAGE_TOTALS_TTL_MS, -} from '../server/storage-usage-coordinator.js'; +import { HostStorageUsageCoordinator } from '../server/storage-usage-coordinator.js'; const context = {} as ConnectionContext; -const footprint: StorageFootprint = { - totals: [{ kind: 'database', bytes: 4096, exact: false }], - reclaimableBytes: 1024, - worktreeCount: 1, -}; -test('storage usage shares one totals scan and reads Sessions fresh', async () => { - let now = 1_000; - let measures = 0; - let release: (() => void) | undefined; +function footprint(bytes: number): StorageFootprint { + return { + totals: [{ kind: 'database', bytes, exact: true }], + reclaimableBytes: 1024, + worktreeCount: 1, + }; +} + +/** A reader whose every `measure()` waits until the test settles it. */ +function deferredReader() { + const pending: Array<(value: StorageFootprint) => void> = []; const sessionQueries: Array = []; const reader: InteractiveStorageFootprintReader = { - measure: async () => { - measures += 1; - await new Promise((resolve) => { - release = resolve; - }); - return footprint; - }, + measure: () => new Promise((resolve) => pending.push(resolve)), measureSessions: async (sessionIds) => { sessionQueries.push(sessionIds); return sessionIds.map((sessionId) => ({ @@ -59,47 +51,56 @@ test('storage usage shares one totals scan and reads Sessions fresh', async () = })); }, }; + return { reader, pending, sessionQueries }; +} + +test('concurrent totals requests share one measurement and a later request re-measures', async () => { + let now = 1_000; + const { reader, pending } = deferredReader(); const coordinator = new HostStorageUsageCoordinator({ footprint: reader, now: () => now }); const query = coordinator.handlers['storage.usage.query']; const first = query({}, context); - const second = query({ sessionIds: ['session-1'] }, context); - await new Promise((resolve) => setImmediate(resolve)); - release?.(); - const [totalsOnly, withSessions] = await Promise.all([first, second]); - assert.equal(measures, 1); - assert.deepEqual(totalsOnly, { + const second = query({}, context); + assert.equal(pending.length, 1, 'concurrent requests share one scan'); + pending[0]!(footprint(4096)); + assert.deepEqual(await first, { ok: true, - result: { measuredAt: 1_000, ...footprint }, + result: { measuredAt: 1_000, ...footprint(4096) }, }); - assert.ok(withSessions.ok); - assert.deepEqual(withSessions.result.sessions, [ - { - sessionId: 'session-1', - bytes: { transcript: 1, runtime: 2, artifacts: 3 }, - worktreeCount: 0, - }, - ]); - const spec = HOST_OPERATION_SPECS['storage.usage.query']; - assert.doesNotThrow(() => - spec.assertOutputForInput?.({ sessionIds: ['session-1'] }, withSessions.result), - ); - - now += STORAGE_USAGE_TOTALS_TTL_MS - 1; - const cached = await query({ sessionIds: ['session-2'] }, context); - assert.equal(measures, 1); - assert.ok(cached.ok); - assert.equal(cached.result.measuredAt, 1_000); - assert.deepEqual(sessionQueries, [['session-1'], ['session-2']]); + assert.deepEqual(await second, await first); - now += 1; + now = 1_001; const refreshed = query({}, context); - await new Promise((resolve) => setImmediate(resolve)); - release?.(); - const next = await refreshed; - assert.equal(measures, 2); - assert.ok(next.ok); - assert.equal(next.result.measuredAt, now); + assert.equal(pending.length, 2, 'a request after the scan settles measures again'); + pending[1]!(footprint(8192)); + assert.deepEqual(await refreshed, { + ok: true, + result: { measuredAt: 1_001, ...footprint(8192) }, + }); +}); + +test('Session usage never computes totals', async () => { + const { reader, pending, sessionQueries } = deferredReader(); + const coordinator = new HostStorageUsageCoordinator({ footprint: reader }); + const outcome = await coordinator.handlers['storage.usage.sessions.query']( + { sessionIds: ['session-1'] }, + context, + ); + assert.deepEqual(outcome, { + ok: true, + result: { + sessions: [ + { + sessionId: 'session-1', + bytes: { transcript: 1, runtime: 2, artifacts: 3 }, + worktreeCount: 0, + }, + ], + }, + }); + assert.deepEqual(sessionQueries, [['session-1']]); + assert.equal(pending.length, 0); }); test('storage usage reports measurement failures and refuses work while draining', async () => { @@ -108,7 +109,7 @@ test('storage usage reports measurement failures and refuses work while draining footprint: { measure: async () => { if (fail) throw new Error('disk I/O error'); - return footprint; + return footprint(1); }, measureSessions: async () => [], }, @@ -124,7 +125,6 @@ test('storage usage reports measurement failures and refuses work while draining } finally { console.error = originalError; } - // A failed scan is not cached. fail = false; assert.equal((await query({}, context)).ok, true); diff --git a/packages/runtime-host/src/__tests__/storage-usage-protocol.test.ts b/packages/runtime-host/src/__tests__/storage-usage-protocol.test.ts index 84c6a30a5a3..b247e4f826f 100644 --- a/packages/runtime-host/src/__tests__/storage-usage-protocol.test.ts +++ b/packages/runtime-host/src/__tests__/storage-usage-protocol.test.ts @@ -25,19 +25,24 @@ import { decodeHostFrame, HOST_OPERATION_SPECS, STORAGE_USAGE_SESSION_MAX_ITEMS, + type StorageSessionUsageQueryResult, type StorageUsageQueryResult, } from '../protocol/index.js'; -const spec = HOST_OPERATION_SPECS['storage.usage.query']; +const totalsSpec = HOST_OPERATION_SPECS['storage.usage.query']; +const sessionsSpec = HOST_OPERATION_SPECS['storage.usage.sessions.query']; -const result: StorageUsageQueryResult = { +const totals: StorageUsageQueryResult = { measuredAt: 1_700_000_000_000, totals: [ - { kind: 'database', bytes: 4096, exact: false }, - { kind: 'artifacts', bytes: 12, exact: true }, + { kind: 'database', bytes: 4096, exact: true }, + { kind: 'artifacts', bytes: 12, exact: false }, ], reclaimableBytes: 8192, worktreeCount: 2, +}; + +const sessions: StorageSessionUsageQueryResult = { sessions: [ { sessionId: 'session-1', @@ -45,7 +50,7 @@ const result: StorageUsageQueryResult = { worktreeCount: 1, }, { - sessionId: 'session-2', + sessionId: 'session-3', bytes: { transcript: 0, runtime: 0, artifacts: 0 }, worktreeCount: 0, }, @@ -54,75 +59,101 @@ const result: StorageUsageQueryResult = { describe('storage usage protocol', () => { test('round-trips totals and per-Session usage through request and response frames', () => { - const request = decodeClientFrame({ - requestId: 'request-storage', - operation: 'storage.usage.query', - input: { sessionIds: ['session-1', 'session-2'] }, - }); - assert.deepEqual(request, { - requestId: 'request-storage', - operation: 'storage.usage.query', - input: { sessionIds: ['session-1', 'session-2'] }, - }); + assert.deepEqual( + decodeClientFrame({ + requestId: 'request-totals', + operation: 'storage.usage.query', + input: {}, + }), + { requestId: 'request-totals', operation: 'storage.usage.query', input: {} }, + ); assert.deepEqual( decodeHostFrame( JSON.parse( JSON.stringify({ - requestId: 'request-storage', + requestId: 'request-totals', operation: 'storage.usage.query', ok: true, - result, + result: totals, + }), + ), + ), + { requestId: 'request-totals', operation: 'storage.usage.query', ok: true, result: totals }, + ); + const input = { sessionIds: ['session-1', 'session-2', 'session-3'] }; + assert.deepEqual( + decodeClientFrame({ + requestId: 'request-sessions', + operation: 'storage.usage.sessions.query', + input, + }), + { requestId: 'request-sessions', operation: 'storage.usage.sessions.query', input }, + ); + assert.deepEqual( + decodeHostFrame( + JSON.parse( + JSON.stringify({ + requestId: 'request-sessions', + operation: 'storage.usage.sessions.query', + ok: true, + result: sessions, }), ), ), - { requestId: 'request-storage', operation: 'storage.usage.query', ok: true, result }, + { + requestId: 'request-sessions', + operation: 'storage.usage.sessions.query', + ok: true, + result: sessions, + }, ); - assert.deepEqual(spec.decodeInput({}), {}); + // Unknown Sessions are omitted, so the answer is an ordered subsequence. + assert.doesNotThrow(() => sessionsSpec.assertOutputForInput?.(input, sessions)); }); - test('rejects unbounded, duplicate, or malformed input', () => { + test('rejects unbounded, empty, duplicate, or malformed input', () => { const tooMany = Array.from( { length: STORAGE_USAGE_SESSION_MAX_ITEMS + 1 }, (_, index) => `session-${index}`, ); for (const input of [ { sessionIds: tooMany }, + { sessionIds: [] }, { sessionIds: ['session-1', 'session-1'] }, { sessionIds: ['../escape'] }, { sessionIds: 'session-1' }, - { sessionId: 'session-1' }, + {}, ]) { - assert.throws(() => spec.decodeInput(input), isInvalidFrame, JSON.stringify(input)); + assert.throws(() => sessionsSpec.decodeInput(input), isInvalidFrame, JSON.stringify(input)); } + assert.throws(() => totalsSpec.decodeInput({ sessionIds: ['session-1'] }), isInvalidFrame); }); test('rejects results with unknown kinds, open shapes, or Sessions that were not asked for', () => { - const malformed: unknown[] = [ - { ...result, totals: [{ kind: 'worktrees', bytes: 1, exact: true }] }, - { ...result, totals: [result.totals[0], result.totals[0]] }, - { ...result, reclaimableBytes: -1 }, - { ...result, extra: true }, - { - ...result, - sessions: [ - { ...result.sessions![0], bytes: { transcript: 1, runtime: 1, artifacts: 1, other: 1 } }, - ], - }, - ]; - for (const value of malformed) { - assert.throws(() => spec.decodeOutput(value), isInvalidFrame, JSON.stringify(value)); + for (const value of [ + { ...totals, totals: [{ kind: 'transcript', bytes: 1, exact: false }] }, + { ...totals, totals: [totals.totals[0], totals.totals[0]] }, + { ...totals, reclaimableBytes: -1 }, + { ...totals, sessions: [] }, + ]) { + assert.throws(() => totalsSpec.decodeOutput(value), isInvalidFrame, JSON.stringify(value)); } - const { sessions: _sessions, ...totalsOnly } = result; - assert.throws( - () => spec.assertOutputForInput?.({ sessionIds: ['session-2', 'session-1'] }, result), - isInvalidFrame, - ); assert.throws( - () => spec.assertOutputForInput?.({ sessionIds: ['session-1', 'session-2'] }, totalsOnly), + () => + sessionsSpec.decodeOutput({ + sessions: [ + { ...sessions.sessions[0], bytes: { transcript: 1, runtime: 1, artifacts: 1, x: 1 } }, + ], + }), isInvalidFrame, ); - assert.throws(() => spec.assertOutputForInput?.({}, result), isInvalidFrame); - assert.doesNotThrow(() => spec.assertOutputForInput?.({}, totalsOnly)); + for (const sessionIds of [['session-3', 'session-1'], ['session-1'], ['session-2']]) { + assert.throws( + () => sessionsSpec.assertOutputForInput?.({ sessionIds }, sessions), + isInvalidFrame, + sessionIds.join(','), + ); + } }); }); diff --git a/packages/runtime-host/src/protocol/index.ts b/packages/runtime-host/src/protocol/index.ts index 5eb7467b0b8..4945991f93d 100644 --- a/packages/runtime-host/src/protocol/index.ts +++ b/packages/runtime-host/src/protocol/index.ts @@ -105,8 +105,9 @@ export const RUNTIME_HOST_PROTOCOL_VERSION = 0 as const; // Increment when the same protocol version no longer guarantees safe Client-Host // interoperability. Mismatches are rejected before domain commands are admitted. export const RUNTIME_HOST_COMPATIBILITY_EPOCH = 199 as const; -// 199: `storage.usage.query` reports the State Root footprint and per-Session -// storage. An epoch-198 Host rejects the unknown operation. +// 199: `storage.usage.query` reports the State Root footprint and +// `storage.usage.sessions.query` per-Session storage. An epoch-198 Host rejects +// both unknown operations. // 198: Executor readiness exposes explicit restore, restore-failed and history-gap states. // 197: Queue reorder requests carry the expected queue revision. Epoch-196 // peers reject the required field or send an unfenced reorder request. diff --git a/packages/runtime-host/src/protocol/operations.ts b/packages/runtime-host/src/protocol/operations.ts index 4faf4ad8f2a..308ed53848d 100644 --- a/packages/runtime-host/src/protocol/operations.ts +++ b/packages/runtime-host/src/protocol/operations.ts @@ -360,6 +360,7 @@ export const REMOTE_OWNER_OPERATION_GRANTS = Object.freeze([ 'skill.catalog.preview-update', 'skill.catalog.query', 'storage.usage.query', + 'storage.usage.sessions.query', 'subscription.close', 'subscription.open', 'subscription.pty_interest.set', diff --git a/packages/runtime-host/src/protocol/storage-usage.ts b/packages/runtime-host/src/protocol/storage-usage.ts index 3c0e1193225..648697ce0bc 100644 --- a/packages/runtime-host/src/protocol/storage-usage.ts +++ b/packages/runtime-host/src/protocol/storage-usage.ts @@ -21,41 +21,50 @@ import { requireCount, requireEntityId, requireExactRecord, requireShapedRecord import { invalidProtocolFrame } from './errors.js'; import { defineOperation } from './operation-spec.js'; -/** Upper bound on Sessions measured by one query; a page of visible rows fits well inside it. */ -export const STORAGE_USAGE_SESSION_MAX_ITEMS = 100; +/** + * Sessions measured by one `storage.usage.sessions.query`. Each Session costs + * several indexed range scans on the Host, so a request stays small and a + * Client pages through a longer list one request at a time. + */ +export const STORAGE_USAGE_SESSION_MAX_ITEMS = 25; /** - * Non-overlapping parts of the Host's State Root footprint. + * State Root parts the Host can size without scanning database rows. * - * `transcript`, `runtime` and `usage_history` are logical payload bytes inside - * the operational database; `database` is the rest of that database's files - * (other records, indexes, free pages). `context_offload` is deduplicated blob - * bytes. Worktrees are counted separately and never sized. + * `database` is the operational SQLite file set. `artifacts` sums recorded + * artifact sizes. `context_offload` is stored blob bytes plus its own SQLite + * file set. `memory` is the long-term memory SQLite file set. Worktrees are + * counted separately and never sized. */ -export const STORAGE_USAGE_KINDS = [ - 'database', - 'transcript', - 'runtime', - 'usage_history', - 'artifacts', - 'context_offload', - 'memory', -] as const; +export const STORAGE_USAGE_KINDS = ['database', 'artifacts', 'context_offload', 'memory'] as const; export type StorageUsageKind = (typeof STORAGE_USAGE_KINDS)[number]; export interface StorageUsageTotal { readonly kind: StorageUsageKind; readonly bytes: number; - /** False when the figure is a logical payload size rather than bytes on disk. */ + /** False when the figure comes from recorded metadata or may overlap another figure. */ readonly exact: boolean; } +export type StorageUsageQueryInput = Record; + +export interface StorageUsageQueryResult { + /** Host clock, epoch milliseconds. */ + readonly measuredAt: number; + readonly totals: readonly StorageUsageTotal[]; + /** Free pages in the operational database that compaction could release. */ + readonly reclaimableBytes: number; + readonly worktreeCount: number; +} + export interface SessionStorageUsage { readonly sessionId: string; + /** Logical bytes stored for the Session, excluding page and index overhead. */ readonly bytes: { readonly transcript: number; readonly runtime: number; + /** Recorded artifact sizes. */ readonly artifacts: number; /** * Logical context-offload bytes referenced by the Session. Blobs are shared @@ -68,20 +77,16 @@ export interface SessionStorageUsage { readonly worktreeCount: number; } -export interface StorageUsageQueryInput { - /** Also measure these Sessions. Omit to read the State Root totals only. */ - readonly sessionIds?: readonly string[]; +export interface StorageSessionUsageQueryInput { + readonly sessionIds: readonly string[]; } -export interface StorageUsageQueryResult { - /** Host clock, epoch milliseconds. */ - readonly measuredAt: number; - readonly totals: readonly StorageUsageTotal[]; - /** Free pages in the operational database that compaction could release. */ - readonly reclaimableBytes: number; - readonly worktreeCount: number; - /** Present exactly when the input named Sessions, in input order. */ - readonly sessions?: readonly SessionStorageUsage[]; +export interface StorageSessionUsageQueryResult { + /** + * The requested Sessions that exist, in request order. A Session the Host + * does not hold is omitted rather than reported as empty. + */ + readonly sessions: readonly SessionStorageUsage[]; } const STORAGE_USAGE_ERRORS = [ @@ -103,39 +108,45 @@ export const STORAGE_USAGE_OPERATION_SPECS = { errors: STORAGE_USAGE_ERRORS, decodeInput: decodeStorageUsageQueryInput, decodeOutput: decodeStorageUsageQueryResult, + }), + 'storage.usage.sessions.query': defineOperation< + StorageSessionUsageQueryInput, + StorageSessionUsageQueryResult, + (typeof STORAGE_USAGE_ERRORS)[number] + >({ + mode: 'query', + availability: 'ready', + errors: STORAGE_USAGE_ERRORS, + decodeInput: decodeStorageSessionUsageQueryInput, + decodeOutput: decodeStorageSessionUsageQueryResult, assertOutputForInput: (input, output) => { - const requested = input.sessionIds; - const measured = output.sessions; - if (requested === undefined) { - if (measured !== undefined) { - throw invalidProtocolFrame('Storage usage returned Sessions that were not requested'); + // A subsequence of the request: each id at most once, in request order. + let next = 0; + for (const session of output.sessions) { + while (next < input.sessionIds.length && input.sessionIds[next] !== session.sessionId) { + next += 1; } - return; - } - if ( - measured === undefined || - measured.length !== requested.length || - measured.some((session, index) => session.sessionId !== requested[index]) - ) { - throw invalidProtocolFrame('Storage usage Sessions do not match the request'); + if (next === input.sessionIds.length) { + throw invalidProtocolFrame('Storage usage Sessions do not match the request'); + } + next += 1; } }, }), } as const; export function decodeStorageUsageQueryInput(value: unknown): StorageUsageQueryInput { - const input = requireShapedRecord(value, 'storage usage input', [], ['sessionIds']); - if (input.sessionIds === undefined) return {}; - return { sessionIds: decodeSessionIds(input.sessionIds) }; + requireExactRecord(value, 'storage usage input', []); + return {}; } export function decodeStorageUsageQueryResult(value: unknown): StorageUsageQueryResult { - const result = requireShapedRecord( - value, - 'storage usage result', - ['measuredAt', 'totals', 'reclaimableBytes', 'worktreeCount'], - ['sessions'], - ); + const result = requireExactRecord(value, 'storage usage result', [ + 'measuredAt', + 'totals', + 'reclaimableBytes', + 'worktreeCount', + ]); if (!Array.isArray(result.totals) || result.totals.length > STORAGE_USAGE_KINDS.length) { throw invalidProtocolFrame('Invalid storage usage totals'); } @@ -143,37 +154,42 @@ export function decodeStorageUsageQueryResult(value: unknown): StorageUsageQuery if (new Set(totals.map((total) => total.kind)).size !== totals.length) { throw invalidProtocolFrame('Duplicate storage usage kind'); } - let sessions: SessionStorageUsage[] | undefined; - if (result.sessions !== undefined) { - if ( - !Array.isArray(result.sessions) || - result.sessions.length > STORAGE_USAGE_SESSION_MAX_ITEMS - ) { - throw invalidProtocolFrame('Invalid storage usage Sessions'); - } - sessions = result.sessions.map(decodeSessionUsage); - if (new Set(sessions.map((session) => session.sessionId)).size !== sessions.length) { - throw invalidProtocolFrame('Duplicate storage usage Session'); - } - } return { measuredAt: requireCount(result.measuredAt, 'storage usage measuredAt'), totals, reclaimableBytes: requireCount(result.reclaimableBytes, 'storage usage reclaimableBytes'), worktreeCount: requireCount(result.worktreeCount, 'storage usage worktreeCount'), - ...(sessions === undefined ? {} : { sessions }), }; } -function decodeSessionIds(value: unknown): readonly string[] { - if (!Array.isArray(value) || value.length > STORAGE_USAGE_SESSION_MAX_ITEMS) { +export function decodeStorageSessionUsageQueryInput(value: unknown): StorageSessionUsageQueryInput { + const input = requireExactRecord(value, 'storage Session usage input', ['sessionIds']); + if ( + !Array.isArray(input.sessionIds) || + input.sessionIds.length === 0 || + input.sessionIds.length > STORAGE_USAGE_SESSION_MAX_ITEMS + ) { throw invalidProtocolFrame('Invalid storage usage sessionIds'); } - const sessionIds = value.map((sessionId) => requireEntityId(sessionId, 'sessionId')); + const sessionIds = input.sessionIds.map((sessionId) => requireEntityId(sessionId, 'sessionId')); if (new Set(sessionIds).size !== sessionIds.length) { throw invalidProtocolFrame('Duplicate storage usage sessionId'); } - return sessionIds; + return { sessionIds }; +} + +export function decodeStorageSessionUsageQueryResult( + value: unknown, +): StorageSessionUsageQueryResult { + const result = requireExactRecord(value, 'storage Session usage result', ['sessions']); + if (!Array.isArray(result.sessions) || result.sessions.length > STORAGE_USAGE_SESSION_MAX_ITEMS) { + throw invalidProtocolFrame('Invalid storage usage Sessions'); + } + const sessions = result.sessions.map(decodeSessionUsage); + if (new Set(sessions.map((session) => session.sessionId)).size !== sessions.length) { + throw invalidProtocolFrame('Duplicate storage usage Session'); + } + return { sessions }; } function decodeTotal(value: unknown): StorageUsageTotal { diff --git a/packages/runtime-host/src/server/storage-usage-coordinator.ts b/packages/runtime-host/src/server/storage-usage-coordinator.ts index a263cfce6b0..9a61956ff68 100644 --- a/packages/runtime-host/src/server/storage-usage-coordinator.ts +++ b/packages/runtime-host/src/server/storage-usage-coordinator.ts @@ -18,43 +18,30 @@ */ import { generalizedErrorMessage } from '@maka/core/redaction'; -import type { - InteractiveStorageFootprintReader, - StorageFootprint, -} from '@maka/storage/storage-writer-composition'; -import type { - OperationOutcome, - StorageUsageQueryInput, - StorageUsageQueryResult, -} from '../protocol/index.js'; +import type { InteractiveStorageFootprintReader } from '@maka/storage/storage-writer-composition'; +import type { OperationOutcome, StorageUsageQueryResult } from '../protocol/index.js'; import type { StorageUsageOperationHandlerMap } from './operation-dispatcher.js'; -/** - * State Root totals scan whole tables, so they are shared for a short while. - * Per-Session figures are index lookups and are always read fresh. - */ -export const STORAGE_USAGE_TOTALS_TTL_MS = 15_000; - -interface MeasuredTotals { - readonly measuredAt: number; - readonly footprint: StorageFootprint; -} - export interface HostStorageUsageCoordinatorOptions { readonly footprint: InteractiveStorageFootprintReader; readonly now?: () => number; } +type Failure = Extract, { ok: false }>; + /** Read-only storage visibility: measures, never reclaims or deletes. */ export class HostStorageUsageCoordinator { readonly handlers: StorageUsageOperationHandlerMap = { - 'storage.usage.query': (input) => this.#query(input), + 'storage.usage.query': () => this.#queryTotals(), + 'storage.usage.sessions.query': (input) => + this.#run(async () => ({ + sessions: await this.#footprint.measureSessions(input.sessionIds), + })), }; readonly #footprint: InteractiveStorageFootprintReader; readonly #now: () => number; - #totals: MeasuredTotals | undefined; - #measuring: Promise | undefined; + #measuring: Promise | undefined; #draining = false; constructor(options: HostStorageUsageCoordinatorOptions) { @@ -66,23 +53,26 @@ export class HostStorageUsageCoordinator { this.#draining = true; } - async #query(input: StorageUsageQueryInput): Promise> { + #queryTotals(): Promise> { + // Requests that arrive while a measurement runs share it; the next one + // after it settles measures again, so a refresh always reads fresh sizes. + return this.#run(() => { + this.#measuring ??= this.#footprint + .measure() + .then((footprint) => ({ measuredAt: this.#now(), ...footprint })) + .finally(() => { + this.#measuring = undefined; + }); + return this.#measuring; + }); + } + + async #run(measure: () => Promise): Promise<{ ok: true; result: T } | Failure> { if (this.#draining) { return { ok: false, error: { code: 'host_draining', message: 'Runtime Host is draining' } }; } try { - const [totals, sessions] = await Promise.all([ - this.#readTotals(), - input.sessionIds ? this.#footprint.measureSessions(input.sessionIds) : undefined, - ]); - const result: StorageUsageQueryResult = { - measuredAt: totals.measuredAt, - totals: totals.footprint.totals, - reclaimableBytes: totals.footprint.reclaimableBytes, - worktreeCount: totals.footprint.worktreeCount, - ...(sessions ? { sessions } : {}), - }; - return { ok: true, result }; + return { ok: true, result: await measure() }; } catch (error) { console.error( `[runtime-host] storage usage could not be measured: ${generalizedErrorMessage(error)}`, @@ -93,23 +83,4 @@ export class HostStorageUsageCoordinator { }; } } - - #readTotals(): Promise { - const cached = this.#totals; - if (cached && this.#now() - cached.measuredAt < STORAGE_USAGE_TOTALS_TTL_MS) { - return Promise.resolve(cached); - } - // Concurrent readers share one scan instead of each walking the tables. - this.#measuring ??= this.#footprint - .measure() - .then((footprint) => { - const measured = { measuredAt: this.#now(), footprint }; - this.#totals = measured; - return measured; - }) - .finally(() => { - this.#measuring = undefined; - }); - return this.#measuring; - } } diff --git a/packages/storage/src/__tests__/storage-footprint.test.ts b/packages/storage/src/__tests__/storage-footprint.test.ts index 4b6f6fd52f1..7f2b6360096 100644 --- a/packages/storage/src/__tests__/storage-footprint.test.ts +++ b/packages/storage/src/__tests__/storage-footprint.test.ts @@ -29,7 +29,7 @@ import { } from '../operational-state-store.js'; import { openStorageFootprintReader } from '../storage-footprint.js'; -test('storage footprint measures Sessions from their rows and totals without double counting', async () => { +test('storage footprint measures known Sessions from their rows and totals from files', async () => { const root = await mkdtemp(join(tmpdir(), 'maka-storage-footprint-')); const owner = acquireOperationalStateDatabase(root); const contextCalls: Array = []; @@ -80,6 +80,8 @@ test('storage footprint measures Sessions from their rows and totals without dou 'INSERT INTO usage_llm_calls(storage_key, id, ts, record_json, session_id) VALUES (?, ?, ?, ?, ?)', ).run('usage-1', 'usage-1', 1, 'u'.repeat(30), 'gone'); await writeFile(join(root, 'memory.sqlite'), Buffer.alloc(2048)); + await writeFile(join(root, 'memory.sqlite-journal'), Buffer.alloc(16)); + await writeFile(join(root, 'context-offload.sqlite'), Buffer.alloc(4096)); await mkdir(join(root, 'subagent-worktrees', 'lease-a'), { recursive: true }); await mkdir(join(root, 'subagent-worktrees', 'lease-b'), { recursive: true }); @@ -96,34 +98,29 @@ test('storage footprint measures Sessions from their rows and totals without dou bytes: { transcript: 0, runtime: 0, artifacts: 0, context: 700 }, worktreeCount: 1, }, - { - sessionId: 'missing', - bytes: { transcript: 0, runtime: 0, artifacts: 0, context: 700 }, - worktreeCount: 0, - }, ]); - assert.deepEqual(contextCalls, ['parent', 'child', 'missing']); + // Unknown ids are omitted rather than reported as empty. + assert.deepEqual(contextCalls, ['parent', 'child']); const footprint = await reader.measure(); const totals = new Map(footprint.totals.map((total) => [total.kind, total])); - assert.equal(totals.get('transcript')?.bytes, 102 + 22 + 300 + 52); - assert.equal(totals.get('runtime')?.bytes, 40); - assert.equal(totals.get('usage_history')?.bytes, 30); - assert.deepEqual(totals.get('artifacts'), { kind: 'artifacts', bytes: 1234, exact: true }); + assert.deepEqual( + footprint.totals.map((total) => total.kind), + ['database', 'artifacts', 'context_offload', 'memory'], + ); + assert.deepEqual(totals.get('database'), { + kind: 'database', + bytes: await databaseFileBytes(root), + exact: true, + }); + assert.deepEqual(totals.get('artifacts'), { kind: 'artifacts', bytes: 1234, exact: false }); assert.deepEqual(totals.get('context_offload'), { kind: 'context_offload', - bytes: 400, + bytes: 400 + 4096, exact: false, }); - assert.deepEqual(totals.get('memory'), { kind: 'memory', bytes: 2048, exact: true }); + assert.deepEqual(totals.get('memory'), { kind: 'memory', bytes: 2048 + 16, exact: true }); assert.equal(footprint.worktreeCount, 2); - - const databaseFiles = await databaseFileBytes(root); - const insideDatabase = ['database', 'transcript', 'runtime', 'usage_history'] as const; - assert.equal( - insideDatabase.reduce((sum, kind) => sum + (totals.get(kind)?.bytes ?? 0), 0), - databaseFiles, - ); const pageSize = Number( (db.prepare('PRAGMA page_size').get() as { page_size: number }).page_size, ); @@ -143,6 +140,7 @@ test('storage footprint omits context usage when the Store is unavailable', asyn const owner = acquireOperationalStateDatabase(root); const reader = openStorageFootprintReader(root); try { + insertSession(owner.database, 'alone', {}); const [session] = await reader.measureSessions(['alone']); assert.deepEqual(session?.bytes, { transcript: 0, runtime: 0, artifacts: 0 }); const footprint = await reader.measure(); @@ -188,7 +186,7 @@ function insertMessage(db: DatabaseSync, sessionId: string, sequence: number, te async function databaseFileBytes(root: string): Promise { let total = 0; - for (const suffix of ['', '-wal', '-shm']) { + for (const suffix of ['', '-wal', '-shm', '-journal']) { try { total += (await stat(join(root, `${OPERATIONAL_STATE_DATABASE_NAME}${suffix}`))).size; } catch {} diff --git a/packages/storage/src/git-worktree-child-executor.ts b/packages/storage/src/git-worktree-child-executor.ts index e5ef906414a..ead812813d4 100644 --- a/packages/storage/src/git-worktree-child-executor.ts +++ b/packages/storage/src/git-worktree-child-executor.ts @@ -46,10 +46,13 @@ export interface CreateGitWorktreeChildExecutorInput { * host-owned lease identity. Worktrees intentionally survive terminal child * runs so Session resume/follow-up keeps the exact workspace. */ +/** State Root directory that holds every leased Subagent worktree. */ +export const SUBAGENT_WORKTREE_DIRECTORY = 'subagent-worktrees'; + export function createGitWorktreeChildExecutor( input: CreateGitWorktreeChildExecutorInput, ): SubagentWorktreeExecutor { - return new GitWorktreeChildExecutor(join(input.storageRoot, 'subagent-worktrees')); + return new GitWorktreeChildExecutor(join(input.storageRoot, SUBAGENT_WORKTREE_DIRECTORY)); } class GitWorktreeChildExecutor implements SubagentWorktreeExecutor { diff --git a/apps/desktop/src/renderer/features/storage-usage/model/format-storage-size.ts b/packages/storage/src/sqlite-file-set.ts similarity index 56% rename from apps/desktop/src/renderer/features/storage-usage/model/format-storage-size.ts rename to packages/storage/src/sqlite-file-set.ts index b3549219981..f6a771df740 100644 --- a/apps/desktop/src/renderer/features/storage-usage/model/format-storage-size.ts +++ b/packages/storage/src/sqlite-file-set.ts @@ -17,22 +17,7 @@ * under the License. */ -import type { UiLocale } from '@maka/core/ui-locale'; - -const UNITS = ['byte', 'kilobyte', 'megabyte', 'gigabyte', 'terabyte'] as const; - -/** Binary-scaled byte size in the reader's locale, e.g. "1.5 GB". */ -export function formatStorageSize(bytes: number, locale: UiLocale): string { - let value = Math.max(0, bytes); - let unit = 0; - while (value >= 1024 && unit < UNITS.length - 1) { - value /= 1024; - unit += 1; - } - return new Intl.NumberFormat(locale, { - style: 'unit', - unit: UNITS[unit], - unitDisplay: 'short', - maximumFractionDigits: unit === 0 || value >= 100 ? 0 : 1, - }).format(value); +/** The files SQLite may keep beside a database, in any journal mode. */ +export function sqliteDatabaseSidecars(path: string): readonly string[] { + return [`${path}-wal`, `${path}-shm`, `${path}-journal`]; } diff --git a/packages/storage/src/sqlite-long-term-memory-store.ts b/packages/storage/src/sqlite-long-term-memory-store.ts index 237ba6cf3b4..8300f8b28aa 100644 --- a/packages/storage/src/sqlite-long-term-memory-store.ts +++ b/packages/storage/src/sqlite-long-term-memory-store.ts @@ -62,6 +62,7 @@ import { type SettleMemoryExtractionFailureRequest, type SettleMemoryExtractionFailureResult, } from '@maka/core/long-term-memory'; +import { sqliteDatabaseSidecars as databaseSidecars } from './sqlite-file-set.js'; import { assertSupportedSqliteLongTermMemorySchemaVersion, configureSqliteLongTermMemoryDatabase, @@ -2113,10 +2114,6 @@ function secureFile(path: string, create: boolean, allowUnlinked: boolean): void } } -function databaseSidecars(path: string): readonly string[] { - return [`${path}-wal`, `${path}-shm`, `${path}-journal`]; -} - function isNodeError(error: unknown): error is NodeJS.ErrnoException { return typeof error === 'object' && error !== null && 'code' in error; } diff --git a/packages/storage/src/storage-footprint.ts b/packages/storage/src/storage-footprint.ts index 7d33345cdd9..1e58f7ee96f 100644 --- a/packages/storage/src/storage-footprint.ts +++ b/packages/storage/src/storage-footprint.ts @@ -20,35 +20,27 @@ import { readdir, stat } from 'node:fs/promises'; import { join } from 'node:path'; import type { ContextOffloadStore } from '@maka/core/context-offload'; +import { SUBAGENT_WORKTREE_DIRECTORY } from './git-worktree-child-executor.js'; import { LONG_TERM_MEMORY_DATABASE_NAME } from './long-term-memory-store.js'; import { acquireOperationalStateDatabase, OPERATIONAL_STATE_DATABASE_NAME, type OperationalStateDatabaseLease, } from './operational-state-store.js'; +import { CONTEXT_OFFLOAD_DATABASE_NAME } from './sqlite-context-offload-store.js'; +import { sqliteDatabaseSidecars } from './sqlite-file-set.js'; /** - * Non-overlapping parts of the State Root footprint. - * - * `transcript`, `runtime` and `usage_history` are logical payload bytes stored - * inside runtime.sqlite; `database` is what remains of that file set once they - * are subtracted: other operational records, indexes, page overhead and free - * pages. The parts therefore add up to the measured files without counting a - * byte twice. + * State Root parts whose size is cheap to learn. Nothing here scans the rows of + * the operational database: a full-table payload sum reads every leaf page and + * blocks the Host for as long as that takes. */ -export type StorageFootprintKind = - | 'database' - | 'transcript' - | 'runtime' - | 'usage_history' - | 'artifacts' - | 'context_offload' - | 'memory'; +export type StorageFootprintKind = 'database' | 'artifacts' | 'context_offload' | 'memory'; export interface StorageFootprintTotal { readonly kind: StorageFootprintKind; readonly bytes: number; - /** False when the figure is logical payload size rather than bytes on disk. */ + /** False when the figure comes from recorded metadata rather than the files on disk. */ readonly exact: boolean; } @@ -63,8 +55,11 @@ export interface StorageFootprint { export interface SessionStorageFootprint { readonly sessionId: string; readonly bytes: { + /** Logical message bytes as stored in rows; excludes page and index overhead. */ readonly transcript: number; + /** Logical runtime event bytes as stored in rows. */ readonly runtime: number; + /** Artifact sizes recorded in their metadata. */ readonly artifacts: number; /** * Logical context-offload bytes referenced by this Session. Blobs are @@ -79,6 +74,11 @@ export interface SessionStorageFootprint { export interface StorageFootprintReader { measure(): Promise; + /** + * Measures the Sessions that exist, in input order; unknown ids are omitted. + * Callers bound the list (the Host protocol admits 25 per request), which + * keeps every `IN (...)` far below SQLite's bound-parameter limit. + */ measureSessions(sessionIds: readonly string[]): Promise; close(): void; } @@ -87,15 +87,11 @@ export interface OpenStorageFootprintReaderOptions { readonly contextOffload?: Pick; } -const SUBAGENT_WORKTREE_DIRECTORY = 'subagent-worktrees'; -const SQLITE_SIDECAR_SUFFIXES = ['', '-wal', '-shm'] as const; -const SESSION_BATCH_SIZE = 100; - /** - * Sums of logical payload bytes. `octet_length` on a TEXT column and `length` - * on a BLOB column read the record header only, so none of these loads the - * overflow pages that hold large payloads. Every table is scanned through an - * existing `session_id`-leading index when a Session filter is present. + * Per-Session payload sums. Each statement is a range scan over an index that + * leads with `session_id`, so its cost grows with the requested Sessions' rows + * rather than with the table. `octet_length` on TEXT and `length` on BLOB skip + * the overflow pages of large values, but every matching row is still read. */ const TRANSCRIPT_SOURCES = [ { table: 'session_messages', bytes: 'octet_length(record_json)' }, @@ -111,27 +107,18 @@ const RUNTIME_SOURCES = [ { table: 'core_agent_run_events', bytes: 'octet_length(record_json)' }, ] as const; -const USAGE_HISTORY_SOURCES = [ - { table: 'usage_llm_calls', bytes: 'octet_length(record_json)' }, - { table: 'usage_tool_invocations', bytes: 'octet_length(record_json)' }, - { - table: 'usage_model_call_attempts', - bytes: `octet_length(attempt_id) + COALESCE(octet_length(session_id), 0) - + COALESCE(octet_length(logical_call_id), 0) + COALESCE(octet_length(turn_id), 0) - + COALESCE(octet_length(connection_slug), 0) + COALESCE(octet_length(provider_id), 0) - + COALESCE(octet_length(model_id), 0)`, - }, -] as const; - -const ARTIFACT_BYTES = "COALESCE(json_extract(record_json, '$.sizeBytes'), 0)"; +const ARTIFACT_SOURCE = { + table: 'artifact_records', + bytes: "COALESCE(json_extract(record_json, '$.sizeBytes'), 0)", +} as const; const HAS_WORKTREE = "json_extract(payload_json, '$.subagentWorkspace') IS NOT NULL"; /** * Opens a read-only footprint reader over one State Root. It shares the * process-local runtime.sqlite connection and adds no triggers or counters, so - * the write path pays nothing for it (#5038). Measurements run one statement - * at a time and yield between them rather than holding a read transaction, so - * the totals are a close estimate, not a snapshot. + * the write path pays nothing for it (#5038). Every statement runs on its own + * and the reader yields to the event loop after it, so no read transaction is + * held and the Host keeps serving between statements. */ export function openStorageFootprintReader( root: string, @@ -153,26 +140,29 @@ class SqliteStorageFootprintReader implements StorageFootprintReader { async measure(): Promise { this.#assertOpen(); const databaseBytes = await fileSetBytes(join(this.root, OPERATIONAL_STATE_DATABASE_NAME)); - const transcript = await this.#sumAll(TRANSCRIPT_SOURCES); - const runtime = await this.#sumAll(RUNTIME_SOURCES); - const usageHistory = await this.#sumAll(USAGE_HISTORY_SOURCES); - const artifacts = await this.#sumAll([{ table: 'artifact_records', bytes: ARTIFACT_BYTES }]); const reclaimableBytes = this.#readReclaimableBytes(); - const memoryBytes = await fileSetBytes(join(this.root, LONG_TERM_MEMORY_DATABASE_NAME)); + await yieldToEventLoop(); + // One small metadata row per artifact file, so the whole table stays cheap. + const artifacts = this.#readAllArtifactBytes(); + await yieldToEventLoop(); const contextUsage = await this.contextOffload?.usage(); + const contextFileBytes = contextUsage + ? await fileSetBytes(join(this.root, CONTEXT_OFFLOAD_DATABASE_NAME)) + : 0; + const memoryBytes = await fileSetBytes(join(this.root, LONG_TERM_MEMORY_DATABASE_NAME)); const worktreeCount = await countDirectories(join(this.root, SUBAGENT_WORKTREE_DIRECTORY)); const totals: StorageFootprintTotal[] = [ - { - kind: 'database', - bytes: Math.max(0, databaseBytes - transcript - runtime - usageHistory), - exact: false, - }, - { kind: 'transcript', bytes: transcript, exact: false }, - { kind: 'runtime', bytes: runtime, exact: false }, - { kind: 'usage_history', bytes: usageHistory, exact: false }, - { kind: 'artifacts', bytes: artifacts, exact: true }, + { kind: 'database', bytes: databaseBytes, exact: true }, + { kind: 'artifacts', bytes: artifacts, exact: false }, ...(contextUsage - ? [{ kind: 'context_offload' as const, bytes: contextUsage.physicalBytes, exact: false }] + ? [ + { + kind: 'context_offload' as const, + // Inline blobs are counted in both terms, so this can overstate. + bytes: contextUsage.physicalBytes + contextFileBytes, + exact: false, + }, + ] : []), { kind: 'memory', bytes: memoryBytes, exact: true }, ]; @@ -183,33 +173,30 @@ class SqliteStorageFootprintReader implements StorageFootprintReader { sessionIds: readonly string[], ): Promise { this.#assertOpen(); - const unique = [...new Set(sessionIds)]; + const requested = [...new Set(sessionIds)]; + if (requested.length === 0) return []; + const known = await this.#readKnownSessions(requested); + const sessions = requested.filter((sessionId) => known.has(sessionId)); + if (sessions.length === 0) return []; + const transcript = await this.#sumBySession(TRANSCRIPT_SOURCES, sessions); + const runtime = await this.#sumBySession(RUNTIME_SOURCES, sessions); + const artifacts = await this.#sumBySession([ARTIFACT_SOURCE], sessions); + const worktrees = await this.#countWorktreesBySession(sessions); const results: SessionStorageFootprint[] = []; - for (let offset = 0; offset < unique.length; offset += SESSION_BATCH_SIZE) { - const batch = unique.slice(offset, offset + SESSION_BATCH_SIZE); - const transcript = this.#sumBySession(TRANSCRIPT_SOURCES, batch); - const runtime = this.#sumBySession(RUNTIME_SOURCES, batch); - const artifacts = this.#sumBySession( - [{ table: 'artifact_records', bytes: ARTIFACT_BYTES }], - batch, - ); - const worktrees = this.#countWorktreesBySession(batch); - for (const sessionId of batch) { - const context = this.contextOffload - ? (await this.contextOffload.usage(sessionId)).logicalBytes - : undefined; - results.push({ - sessionId, - bytes: { - transcript: transcript.get(sessionId) ?? 0, - runtime: runtime.get(sessionId) ?? 0, - artifacts: artifacts.get(sessionId) ?? 0, - ...(context === undefined ? {} : { context }), - }, - worktreeCount: worktrees.get(sessionId) ?? 0, - }); - } - await yieldToEventLoop(); + for (const sessionId of sessions) { + const context = this.contextOffload + ? (await this.contextOffload.usage(sessionId)).logicalBytes + : undefined; + results.push({ + sessionId, + bytes: { + transcript: transcript.get(sessionId) ?? 0, + runtime: runtime.get(sessionId) ?? 0, + artifacts: artifacts.get(sessionId) ?? 0, + ...(context === undefined ? {} : { context }), + }, + worktreeCount: worktrees.get(sessionId) ?? 0, + }); } return results; } @@ -220,57 +207,66 @@ class SqliteStorageFootprintReader implements StorageFootprintReader { this.lease.close(); } - async #sumAll(sources: readonly SqlByteSource[]): Promise { - let total = 0; - for (const source of sources) { - const row = this.lease.database - .prepare(`SELECT COALESCE(SUM(${source.bytes}), 0) AS bytes FROM ${source.table}`) - .get() as { bytes: number | bigint }; - total += toSafeCount(row.bytes); - await yieldToEventLoop(); - } - return total; + async #readKnownSessions(sessionIds: readonly string[]): Promise> { + const rows = this.lease.database + .prepare( + `SELECT session_id AS sessionId FROM session_metadata + WHERE session_id IN (${placeholders(sessionIds)})`, + ) + .all(...sessionIds) as Array<{ sessionId: string }>; + await yieldToEventLoop(); + return new Set(rows.map((row) => row.sessionId)); } - #sumBySession( + async #sumBySession( sources: readonly SqlByteSource[], sessionIds: readonly string[], - ): Map { + ): Promise> { const totals = new Map(); - const placeholders = sessionIds.map(() => '?').join(', '); for (const source of sources) { const rows = this.lease.database .prepare( `SELECT session_id AS sessionId, COALESCE(SUM(${source.bytes}), 0) AS bytes FROM ${source.table} - WHERE session_id IN (${placeholders}) + WHERE session_id IN (${placeholders(sessionIds)}) GROUP BY session_id`, ) .all(...sessionIds) as Array<{ sessionId: string; bytes: number | bigint }>; for (const row of rows) { totals.set(row.sessionId, (totals.get(row.sessionId) ?? 0) + toSafeCount(row.bytes)); } + await yieldToEventLoop(); } return totals; } - #countWorktreesBySession(sessionIds: readonly string[]): Map { - const placeholders = sessionIds.map(() => '?').join(', '); + async #countWorktreesBySession(sessionIds: readonly string[]): Promise> { + const list = placeholders(sessionIds); const rows = this.lease.database .prepare( `SELECT owner AS sessionId, COUNT(*) AS count FROM ( SELECT session_id AS owner FROM session_metadata - WHERE session_id IN (${placeholders}) AND ${HAS_WORKTREE} + WHERE session_id IN (${list}) AND ${HAS_WORKTREE} UNION ALL SELECT subagent_parent_session_id AS owner FROM session_metadata - WHERE subagent_parent_session_id IN (${placeholders}) AND ${HAS_WORKTREE} + WHERE subagent_parent_session_id IN (${list}) AND ${HAS_WORKTREE} ) GROUP BY owner`, ) .all(...sessionIds, ...sessionIds) as Array<{ sessionId: string; count: number | bigint }>; + await yieldToEventLoop(); return new Map(rows.map((row) => [row.sessionId, toSafeCount(row.count)])); } + #readAllArtifactBytes(): number { + const row = this.lease.database + .prepare( + `SELECT COALESCE(SUM(${ARTIFACT_SOURCE.bytes}), 0) AS bytes FROM ${ARTIFACT_SOURCE.table}`, + ) + .get() as { bytes: number | bigint }; + return toSafeCount(row.bytes); + } + #readReclaimableBytes(): number { const pageSize = this.lease.database.prepare('PRAGMA page_size').get() as { page_size: number | bigint; @@ -291,11 +287,15 @@ interface SqlByteSource { readonly bytes: string; } +function placeholders(values: readonly unknown[]): string { + return values.map(() => '?').join(', '); +} + async function fileSetBytes(databasePath: string): Promise { let total = 0; - for (const suffix of SQLITE_SIDECAR_SUFFIXES) { + for (const path of [databasePath, ...sqliteDatabaseSidecars(databasePath)]) { try { - total += (await stat(`${databasePath}${suffix}`)).size; + total += (await stat(path)).size; } catch (error) { if (!isMissingFile(error)) throw error; } diff --git a/packages/ui/src/__tests__/format-bytes.test.ts b/packages/ui/src/__tests__/format-bytes.test.ts new file mode 100644 index 00000000000..dff1593ffaf --- /dev/null +++ b/packages/ui/src/__tests__/format-bytes.test.ts @@ -0,0 +1,33 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import assert from 'node:assert/strict'; +import { test } from 'node:test'; +import { formatBytes } from '../tool-activity/preview-utils.js'; + +test('formatBytes keeps its sub-gigabyte output and scales on to GB and TB', () => { + assert.equal(formatBytes(0), '0 B'); + assert.equal(formatBytes(512), '512 B'); + assert.equal(formatBytes(1536), '1.5 KB'); + assert.equal(formatBytes(5 * 1024 * 1024), '5.0 MB'); + assert.equal(formatBytes(1.5 * 1024 ** 3), '1.5 GB'); + assert.equal(formatBytes(2 * 1024 ** 4), '2.0 TB'); + assert.equal(formatBytes(3 * 1024 ** 5), '3072.0 TB'); + assert.equal(formatBytes(1.5 * 1024 ** 3, 'en'), '1.5 GB'); +}); diff --git a/packages/ui/src/tool-activity/preview-utils.ts b/packages/ui/src/tool-activity/preview-utils.ts index 61a1db266f1..0b88d9fb5b3 100644 --- a/packages/ui/src/tool-activity/preview-utils.ts +++ b/packages/ui/src/tool-activity/preview-utils.ts @@ -31,11 +31,27 @@ export function capLines(text: string): { body: string; capped: number } { }; } -export function formatBytes(bytes: number): string { +const BYTE_UNITS = ['KB', 'MB', 'GB', 'TB'] as const; + +/** + * Binary-scaled size (1 KB = 1024 B), one decimal above bytes. A locale only + * changes the decimal separator; the unit labels stay the same. + */ +export function formatBytes(bytes: number, locale?: UiLocale): string { if (!Number.isFinite(bytes) || bytes <= 0) return '0 B'; if (bytes < 1024) return `${Math.round(bytes)} B`; - if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`; - return `${(bytes / (1024 * 1024)).toFixed(1)} MB`; + let value = bytes / 1024; + let unit = 0; + while (value >= 1024 && unit < BYTE_UNITS.length - 1) { + value /= 1024; + unit += 1; + } + const number = locale + ? new Intl.NumberFormat(locale, { minimumFractionDigits: 1, maximumFractionDigits: 1 }).format( + value, + ) + : value.toFixed(1); + return `${number} ${BYTE_UNITS[unit]}`; } export function formatDuration(ms: number | undefined): string | null { From 5af33e59d9004d1de9054fa4a197a1877e453a62 Mon Sep 17 00:00:00 2001 From: liugddx Date: Tue, 29 Sep 2026 22:11:57 +0800 Subject: [PATCH 3/4] fix(storage): address storage usage review findings - context_offload now reports the context-offload SQLite file set plus the managed value files beside it. Inline blobs already live in the SQLite files, so adding the Store's physical-byte counter double counted them. - Per-Session measurement runs one Session per statement and yields to the event loop after each, so a large task no longer holds the Host for a whole batch. - The archived-task list measures a row only once it scrolls into view (IntersectionObserver); visible rows still share bounded requests. - The renderer size cache evicts expired entries on each flush and is capped at 1,000 entries. - A Host whose storage query fails is skipped for a cooldown. An older Host rejects the unknown operation by closing the connection, the same way it treats recall.query, so retrying on every visible row would keep dropping it; the UI shows its unavailable state instead. - Drop the compatibility epoch bump. The two operations are an additive extension, declared in protocol-compatible-changes at epoch 198. - Footprint tests now cover runtime_partial_snapshots and core_agent_run_events rows, inline versus managed context blobs, and that multi-Session measurement yields between statements. Co-Authored-By: Claude Opus 5.5 (1M context) --- .../__tests__/session-storage-loader.test.ts | 42 ++++- .../__tests__/storage-usage-section.test.ts | 76 +++++++++ apps/desktop/src/preload/preload.ts | 30 ++-- .../src/preload/session-storage-usage.ts | 39 ++++- .../model/session-storage-loader.ts | 41 +++-- .../features/storage-usage/testing.ts | 1 + .../storage-usage/ui/task-storage-size.tsx | 50 ++++-- .../storage-usage-operations.json | 8 + packages/runtime-host/src/protocol/index.ts | 5 +- .../src/protocol/storage-usage.ts | 6 +- .../src/__tests__/storage-footprint.test.ts | 138 ++++++++++++++-- packages/storage/src/storage-footprint.ts | 147 +++++++++--------- 12 files changed, 444 insertions(+), 139 deletions(-) create mode 100644 packages/runtime-host/protocol-compatible-changes/storage-usage-operations.json diff --git a/apps/desktop/src/main/__tests__/session-storage-loader.test.ts b/apps/desktop/src/main/__tests__/session-storage-loader.test.ts index a49ff0dc476..5e3f3c0166b 100644 --- a/apps/desktop/src/main/__tests__/session-storage-loader.test.ts +++ b/apps/desktop/src/main/__tests__/session-storage-loader.test.ts @@ -25,10 +25,14 @@ import { } from '@maka/runtime-host/protocol'; import { createSessionStorageLoader, + SESSION_STORAGE_CACHE_MAX_ENTRIES, SESSION_STORAGE_FAILURE_COOLDOWN_MS, SESSION_STORAGE_RESULT_TTL_MS, } from '../../renderer/features/storage-usage/testing.js'; -import { loadSessionStorageUsage } from '../../preload/session-storage-usage.js'; +import { + createSessionStorageUsageReader, + SESSION_STORAGE_HOST_FAILURE_COOLDOWN_MS, +} from '../../preload/session-storage-usage.js'; function usage(sessionId: string): SessionStorageUsage { return { sessionId, bytes: { transcript: 1, runtime: 2, artifacts: 3 }, worktreeCount: 0 }; @@ -83,14 +87,35 @@ test('failures and unknown tasks wait out a cooldown; measured sizes expire', as assert.deepEqual(queries, [['session-a'], ['session-a'], ['session-gone'], ['session-a']]); }); +test('the size cache drops expired entries and stays within its cap', async () => { + let now = 0; + const loader = createSessionStorageLoader( + async (sessionIds) => Object.fromEntries(sessionIds.map((id) => [id, usage(id)])), + { now: () => now }, + ); + await Promise.all(['session-a', 'session-b'].map((id) => loader.load(id))); + assert.equal(loader.size(), 2); + now += SESSION_STORAGE_RESULT_TTL_MS; + await loader.load('session-c'); + assert.equal(loader.size(), 1, 'expired entries are evicted on the next flush'); + + const many = Array.from( + { length: SESSION_STORAGE_CACHE_MAX_ENTRIES + 10 }, + (_, index) => `bulk-${index}`, + ); + await Promise.all(many.map((id) => loader.load(id))); + assert.ok(loader.size() <= SESSION_STORAGE_CACHE_MAX_ENTRIES); +}); + test('preload keeps one Host’s task sizes when another Host fails', async () => { const routes: Record = { 'desktop-a1': { scope: 'host-a', sessionId: 'a1' }, 'desktop-a2': { scope: 'host-a', sessionId: 'a2' }, 'desktop-b1': { scope: 'host-b', sessionId: 'b1' }, }; - const result = await loadSessionStorageUsage( - ['desktop-a1', 'desktop-b1', 'desktop-a2', 'desktop-missing'], + let now = 0; + const queried: string[] = []; + const read = createSessionStorageUsageReader( { resolve: async (sessionId) => { const route = routes[sessionId]; @@ -98,11 +123,20 @@ test('preload keeps one Host’s task sizes when another Host fails', async () = return { ...route, scopeKey: route.scope }; }, query: async (scope, sessionIds) => { + queried.push(scope); + // An older Host rejects the unknown operation by dropping the connection. if (scope === 'host-b') throw new Error('Runtime Host disconnected'); // `a2` is not on its Host, so the Host omits it. return sessionIds.filter((id) => id !== 'a2').map(usage); }, }, + { now: () => now }, ); - assert.deepEqual(result, { 'desktop-a1': usage('a1') }); + const ids = ['desktop-a1', 'desktop-b1', 'desktop-a2', 'desktop-missing']; + assert.deepEqual(await read(ids), { 'desktop-a1': usage('a1') }); + // The failed Host is left alone for a cooldown instead of being dropped again. + assert.deepEqual(await read(ids), { 'desktop-a1': usage('a1') }); + now += SESSION_STORAGE_HOST_FAILURE_COOLDOWN_MS; + await read(ids); + assert.deepEqual(queried, ['host-a', 'host-b', 'host-a', 'host-a', 'host-b']); }); diff --git a/apps/desktop/src/main/__tests__/storage-usage-section.test.ts b/apps/desktop/src/main/__tests__/storage-usage-section.test.ts index 6dbb3a197ef..a62532fd98c 100644 --- a/apps/desktop/src/main/__tests__/storage-usage-section.test.ts +++ b/apps/desktop/src/main/__tests__/storage-usage-section.test.ts @@ -27,6 +27,7 @@ import type { StorageUsageQueryResult } from '@maka/runtime-host/protocol'; import { StorageUsageSection, StorageUsageServicesProvider, + TaskStorageSize, type StorageUsageHostTarget, } from '../../renderer/features/storage-usage/index.js'; import { RuntimeHostSettingsTarget } from '../../renderer/settings/runtime-host-settings-target.js'; @@ -36,6 +37,7 @@ const originalGlobals = { window: globalThis.window, HTMLElement: globalThis.HTMLElement, getComputedStyle: globalThis.getComputedStyle, + IntersectionObserver: globalThis.IntersectionObserver, IS_REACT_ACT_ENVIRONMENT: (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }) .IS_REACT_ACT_ENVIRONMENT, }; @@ -111,3 +113,77 @@ test('the Storage section reads the selected Host once and states its caveats', await act(async () => root.unmount()); }); + +test('a task row is measured only after it scrolls into view', async () => { + const { document, window } = parseHTML('
'); + const observers: Array<{ + readonly callback: (entries: Array<{ isIntersecting: boolean }>) => void; + disconnected: boolean; + }> = []; + class FakeIntersectionObserver { + readonly #record: (typeof observers)[number]; + constructor(callback: (entries: Array<{ isIntersecting: boolean }>) => void) { + this.#record = { callback, disconnected: false }; + observers.push(this.#record); + } + observe() {} + disconnect() { + this.#record.disconnected = true; + } + } + Object.assign(globalThis, { + document, + window, + HTMLElement: window.HTMLElement, + getComputedStyle: (element: Element) => + ({ color: (element as HTMLElement).style?.color || 'currentColor' }) as CSSStyleDeclaration, + IntersectionObserver: FakeIntersectionObserver, + IS_REACT_ACT_ENVIRONMENT: true, + }); + const requested: string[][] = []; + const services = { + loadUsage: async (): Promise => { + throw new Error('not used'); + }, + loadSessionUsage: async (sessionIds: readonly string[]) => { + requested.push([...sessionIds]); + return Object.fromEntries( + sessionIds.map((sessionId) => [ + sessionId, + { + sessionId, + bytes: { transcript: 1024, runtime: 1024, artifacts: 0 }, + worktreeCount: 0, + }, + ]), + ); + }, + }; + const container = document.getElementById('root') as unknown as HTMLElement; + const root = createRoot(container); + await act(async () => { + root.render( + createElement(LocaleProvider, { + locale: 'en', + children: createElement(StorageUsageServicesProvider, { + services, + children: [ + createElement(TaskStorageSize, { key: 'seen', sessionId: 'seen' }), + createElement(TaskStorageSize, { key: 'unseen', sessionId: 'unseen' }), + ], + }), + }), + ); + }); + assert.equal(observers.length, 2); + assert.deepEqual(requested, [], 'nothing is measured before a row is visible'); + + await act(async () => { + observers[0]!.callback([{ isIntersecting: true }]); + }); + assert.deepEqual(requested, [['seen']]); + assert.equal(observers[0]!.disconnected, true); + assert.match(container.textContent ?? '', /Uses 2\.0 KB/); + + await act(async () => root.unmount()); +}); diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts index c646e4330fb..441afb06c32 100644 --- a/apps/desktop/src/preload/preload.ts +++ b/apps/desktop/src/preload/preload.ts @@ -261,7 +261,7 @@ import { type StorageUsageQueryResult, } from '@maka/runtime-host/protocol'; import type { PlanControlIpcResult } from '../shared/plan-mode-ipc.js'; -import { loadSessionStorageUsage } from './session-storage-usage.js'; +import { createSessionStorageUsageReader } from './session-storage-usage.js'; import type { AgentGraphEpochDirectory } from '@maka/runtime-host/client'; import { desktopSessionKey, @@ -1249,22 +1249,18 @@ const runtimeHost: MakaBridge['runtimeHost'] = { }, }; -function loadDesktopSessionStorageUsage( - sessionIds: readonly string[], -): Promise> { - return loadSessionStorageUsage(sessionIds, { - resolve: async (sessionId) => { - const ref = await runtimeHostSessionRef(sessionId); - return { ...ref, scopeKey: runtimeHostScopeKey(ref.scope) }; - }, - query: async (scope: DesktopTargetScope, hostIds) => - ( - await scopedRuntimeHost(scope).query('storage.usage.sessions.query', { - sessionIds: hostIds, - }) - ).sessions, - }); -} +const loadDesktopSessionStorageUsage = createSessionStorageUsageReader({ + resolve: async (sessionId) => { + const ref = await runtimeHostSessionRef(sessionId); + return { ...ref, scopeKey: runtimeHostScopeKey(ref.scope) }; + }, + query: async (scope: DesktopTargetScope, hostIds) => + ( + await scopedRuntimeHost(scope).query('storage.usage.sessions.query', { + sessionIds: hostIds, + }) + ).sessions, +}); async function listScheduledTasks(target?: DesktopRuntimeHostRef): Promise { const host = scopedRuntimeHost(await selectedRuntimeHostScope(target)); diff --git a/apps/desktop/src/preload/session-storage-usage.ts b/apps/desktop/src/preload/session-storage-usage.ts index 8c1791d3249..f9317d0cd8e 100644 --- a/apps/desktop/src/preload/session-storage-usage.ts +++ b/apps/desktop/src/preload/session-storage-usage.ts @@ -33,15 +33,48 @@ export interface SessionStorageUsageRouting { query(scope: Scope, sessionIds: readonly string[]): Promise; } +/** A Host whose storage query failed is not asked again this soon. */ +export const SESSION_STORAGE_HOST_FAILURE_COOLDOWN_MS = 60_000; + +export type SessionStorageUsageReader = ( + sessionIds: readonly string[], +) => Promise>; + /** * Per-task storage keyed by Desktop session id. Tasks are grouped by the Host * that holds them and each Host is paged one bounded request at a time. A task * whose Host cannot be resolved, or a Host whose query fails, is left out * rather than failing the other Hosts' tasks. + * + * A failing Host is skipped for a cooldown. An older Host that predates the + * operation rejects it by closing the connection, as it does for any unknown + * operation, so asking again for every newly visible row would keep dropping + * that connection. */ -export async function loadSessionStorageUsage( +export function createSessionStorageUsageReader( + routing: SessionStorageUsageRouting, + options: { readonly now?: () => number } = {}, +): SessionStorageUsageReader { + const now = options.now ?? Date.now; + const failedScopes = new Map(); + const isCoolingDown = (scopeKey: string) => { + const failedAt = failedScopes.get(scopeKey); + if (failedAt === undefined) return false; + if (now() - failedAt < SESSION_STORAGE_HOST_FAILURE_COOLDOWN_MS) return true; + failedScopes.delete(scopeKey); + return false; + }; + return (sessionIds) => + loadSessionStorageUsage(sessionIds, routing, { + skip: isCoolingDown, + failed: (scopeKey) => failedScopes.set(scopeKey, now()), + }); +} + +async function loadSessionStorageUsage( sessionIds: readonly string[], routing: SessionStorageUsageRouting, + hosts: { skip(scopeKey: string): boolean; failed(scopeKey: string): void }, ): Promise> { const byScope = new Map }>(); for (const sessionId of new Set(sessionIds)) { @@ -51,6 +84,7 @@ export async function loadSessionStorageUsage( } catch { continue; } + if (hosts.skip(ref.scopeKey)) continue; const group = byScope.get(ref.scopeKey) ?? { scope: ref.scope, desktopIds: new Map(), @@ -60,7 +94,7 @@ export async function loadSessionStorageUsage( } const usage: Record = {}; await Promise.all( - [...byScope.values()].map(async ({ scope, desktopIds }) => { + [...byScope.entries()].map(async ([scopeKey, { scope, desktopIds }]) => { const hostIds = [...desktopIds.keys()]; try { for (let offset = 0; offset < hostIds.length; offset += STORAGE_USAGE_SESSION_MAX_ITEMS) { @@ -75,6 +109,7 @@ export async function loadSessionStorageUsage( } } catch { // This Host's remaining tasks stay unknown; the other Hosts still answer. + hosts.failed(scopeKey); } }), ); diff --git a/apps/desktop/src/renderer/features/storage-usage/model/session-storage-loader.ts b/apps/desktop/src/renderer/features/storage-usage/model/session-storage-loader.ts index 80b6f382496..61197b534de 100644 --- a/apps/desktop/src/renderer/features/storage-usage/model/session-storage-loader.ts +++ b/apps/desktop/src/renderer/features/storage-usage/model/session-storage-loader.ts @@ -26,10 +26,14 @@ import { export const SESSION_STORAGE_RESULT_TTL_MS = 60_000; /** A task that could not be measured is not asked about again this soon. */ export const SESSION_STORAGE_FAILURE_COOLDOWN_MS = 30_000; +/** Settled entries kept at most; the oldest are dropped first. */ +export const SESSION_STORAGE_CACHE_MAX_ENTRIES = 1_000; export interface SessionStorageLoader { /** Resolves undefined when the size is unknown: unmeasurable or not on its Host. */ load(sessionId: string): Promise; + /** Entries currently cached, settled or in flight. */ + size(): number; } interface Entry { @@ -39,10 +43,10 @@ interface Entry { } /** - * Turns row requests into Host queries. Rows that mount together are queued - * and measured one request at a time, `STORAGE_USAGE_SESSION_MAX_ITEMS` per - * request, so a long list never puts more than one measurement on a Host at - * once. Results and failures are both remembered for a while, so remounting a + * Turns row requests into Host queries. Rows that scroll into view together + * are queued and measured one request at a time, at most + * `STORAGE_USAGE_SESSION_MAX_ITEMS` per request, so a long list never puts + * more than one measurement on a Host at once. Results and failures are both remembered for a while, so remounting a * list neither re-measures every row nor hammers a Host that just failed. */ export function createSessionStorageLoader( @@ -64,7 +68,28 @@ export function createSessionStorageLoader( } }; + const isFresh = (entry: Entry): boolean => { + if (entry.settledAt === undefined) return true; + const ttl = entry.measured ? SESSION_STORAGE_RESULT_TTL_MS : SESSION_STORAGE_FAILURE_COOLDOWN_MS; + return now() - entry.settledAt < ttl; + }; + + /** Drops expired entries, then the oldest settled ones beyond the cap. */ + const prune = () => { + for (const [sessionId, entry] of entries) { + if (!isFresh(entry)) entries.delete(sessionId); + } + let excess = entries.size - SESSION_STORAGE_CACHE_MAX_ENTRIES; + for (const [sessionId, entry] of entries) { + if (excess <= 0) break; + if (entry.settledAt === undefined) continue; + entries.delete(sessionId); + excess -= 1; + } + }; + const drain = async () => { + prune(); while (queue.size > 0) { const chunk = [...queue.entries()].slice(0, STORAGE_USAGE_SESSION_MAX_ITEMS); for (const [sessionId] of chunk) queue.delete(sessionId); @@ -81,12 +106,7 @@ export function createSessionStorageLoader( } } draining = false; - }; - - const isFresh = (entry: Entry): boolean => { - if (entry.settledAt === undefined) return true; - const ttl = entry.measured ? SESSION_STORAGE_RESULT_TTL_MS : SESSION_STORAGE_FAILURE_COOLDOWN_MS; - return now() - entry.settledAt < ttl; + prune(); }; return { @@ -104,6 +124,7 @@ export function createSessionStorageLoader( } return result; }, + size: () => entries.size, }; } diff --git a/apps/desktop/src/renderer/features/storage-usage/testing.ts b/apps/desktop/src/renderer/features/storage-usage/testing.ts index a21c3b0d5f7..36f85638e05 100644 --- a/apps/desktop/src/renderer/features/storage-usage/testing.ts +++ b/apps/desktop/src/renderer/features/storage-usage/testing.ts @@ -23,6 +23,7 @@ */ export { createSessionStorageLoader, + SESSION_STORAGE_CACHE_MAX_ENTRIES, SESSION_STORAGE_FAILURE_COOLDOWN_MS, SESSION_STORAGE_RESULT_TTL_MS, } from './model/session-storage-loader.js'; diff --git a/apps/desktop/src/renderer/features/storage-usage/ui/task-storage-size.tsx b/apps/desktop/src/renderer/features/storage-usage/ui/task-storage-size.tsx index 967aa632842..14bb6ab6ebb 100644 --- a/apps/desktop/src/renderer/features/storage-usage/ui/task-storage-size.tsx +++ b/apps/desktop/src/renderer/features/storage-usage/ui/task-storage-size.tsx @@ -17,7 +17,7 @@ * under the License. */ -import { useEffect, useState } from 'react'; +import { useEffect, useRef, useState } from 'react'; import { Text } from '@astryxdesign/core/Text'; import { formatBytes, useUiLocale } from '@maka/ui'; import type { SessionStorageUsage } from '@maka/runtime-host/protocol'; @@ -25,20 +25,47 @@ import { getStorageUsageCopy } from '../../../locales/storage-usage-copy.js'; import { sessionStorageBytes } from '../model/session-storage-loader.js'; import { useOptionalSessionStorageLoader } from '../services-context.js'; +/** Starts measuring slightly before a row scrolls in, so its size is ready on arrival. */ +const VISIBILITY_MARGIN = '200px 0px'; + /** * A task's measured size, or nothing while unknown. Never a guess. * - * Each mounted row asks for its own size. The archived-task list is not - * virtualized, so every row that passes the search mounts; the shared loader - * measures them sequentially, one bounded Host request at a time. + * The archived-task list is not virtualized, so every matching row mounts. A + * row asks for its size only once it scrolls into view; rows never seen are + * never measured. The shared loader batches the rows that become visible + * together into bounded Host requests, one at a time. */ export function TaskStorageSize(props: { readonly sessionId: string }) { const loader = useOptionalSessionStorageLoader(); const locale = useUiLocale(); + const anchor = useRef(null); + const [visible, setVisible] = useState(false); const [usage, setUsage] = useState(undefined); useEffect(() => { - if (!loader) return; + const element = anchor.current; + if (!loader || !element || visible) return; + // Without an observer (a non-browser host) there is no scroll to wait for. + if (typeof IntersectionObserver === 'undefined') { + setVisible(true); + return; + } + const observer = new IntersectionObserver( + (entries) => { + if (entries.some((entry) => entry.isIntersecting)) { + observer.disconnect(); + setVisible(true); + } + }, + { rootMargin: VISIBILITY_MARGIN }, + ); + observer.observe(element); + return () => observer.disconnect(); + }, [loader, visible]); + + useEffect(() => { + if (!loader || !visible) return; let current = true; setUsage(undefined); void loader.load(props.sessionId).then((measured) => { @@ -47,12 +74,15 @@ export function TaskStorageSize(props: { readonly sessionId: string }) { return () => { current = false; }; - }, [loader, props.sessionId]); + }, [loader, props.sessionId, visible]); - if (!usage) return null; return ( - - {getStorageUsageCopy(locale).taskSize(formatBytes(sessionStorageBytes(usage), locale))} - + + {usage ? ( + + {getStorageUsageCopy(locale).taskSize(formatBytes(sessionStorageBytes(usage), locale))} + + ) : null} + ); } diff --git a/packages/runtime-host/protocol-compatible-changes/storage-usage-operations.json b/packages/runtime-host/protocol-compatible-changes/storage-usage-operations.json new file mode 100644 index 00000000000..cd3989874fc --- /dev/null +++ b/packages/runtime-host/protocol-compatible-changes/storage-usage-operations.json @@ -0,0 +1,8 @@ +{ + "epoch": 198, + "files": [ + "packages/runtime-host/src/protocol/storage-usage.ts", + "packages/runtime-host/src/protocol/operations.ts" + ], + "reason": "Adds the storage.usage.query and storage.usage.sessions.query operation specs and registers their keys, including the remote-owner grant list. Two new operation keys are an additive extension: a peer that predates them never sends either operation and never receives a response for one, so every existing request and response decodes byte-for-byte as before. Nothing already on the wire changes shape or meaning." +} diff --git a/packages/runtime-host/src/protocol/index.ts b/packages/runtime-host/src/protocol/index.ts index 4945991f93d..2f41d5595c1 100644 --- a/packages/runtime-host/src/protocol/index.ts +++ b/packages/runtime-host/src/protocol/index.ts @@ -104,10 +104,7 @@ export const RUNTIME_HOST_REGISTRATION_SCHEMA_VERSION = 1 as const; export const RUNTIME_HOST_PROTOCOL_VERSION = 0 as const; // Increment when the same protocol version no longer guarantees safe Client-Host // interoperability. Mismatches are rejected before domain commands are admitted. -export const RUNTIME_HOST_COMPATIBILITY_EPOCH = 199 as const; -// 199: `storage.usage.query` reports the State Root footprint and -// `storage.usage.sessions.query` per-Session storage. An epoch-198 Host rejects -// both unknown operations. +export const RUNTIME_HOST_COMPATIBILITY_EPOCH = 198 as const; // 198: Executor readiness exposes explicit restore, restore-failed and history-gap states. // 197: Queue reorder requests carry the expected queue revision. Epoch-196 // peers reject the required field or send an unfenced reorder request. diff --git a/packages/runtime-host/src/protocol/storage-usage.ts b/packages/runtime-host/src/protocol/storage-usage.ts index 648697ce0bc..04c854a44c0 100644 --- a/packages/runtime-host/src/protocol/storage-usage.ts +++ b/packages/runtime-host/src/protocol/storage-usage.ts @@ -32,9 +32,9 @@ export const STORAGE_USAGE_SESSION_MAX_ITEMS = 25; * State Root parts the Host can size without scanning database rows. * * `database` is the operational SQLite file set. `artifacts` sums recorded - * artifact sizes. `context_offload` is stored blob bytes plus its own SQLite - * file set. `memory` is the long-term memory SQLite file set. Worktrees are - * counted separately and never sized. + * artifact sizes. `context_offload` is its SQLite file set, which holds inline + * blobs, plus the managed value files beside it. `memory` is the long-term + * memory SQLite file set. Worktrees are counted separately and never sized. */ export const STORAGE_USAGE_KINDS = ['database', 'artifacts', 'context_offload', 'memory'] as const; diff --git a/packages/storage/src/__tests__/storage-footprint.test.ts b/packages/storage/src/__tests__/storage-footprint.test.ts index 7f2b6360096..444feb49e52 100644 --- a/packages/storage/src/__tests__/storage-footprint.test.ts +++ b/packages/storage/src/__tests__/storage-footprint.test.ts @@ -18,7 +18,7 @@ */ import assert from 'node:assert/strict'; -import { mkdir, mkdtemp, rm, stat, writeFile } from 'node:fs/promises'; +import { mkdir, mkdtemp, readdir, rm, stat, writeFile } from 'node:fs/promises'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { test } from 'node:test'; @@ -27,6 +27,11 @@ import { acquireOperationalStateDatabase, OPERATIONAL_STATE_DATABASE_NAME, } from '../operational-state-store.js'; +import { + CONTEXT_OFFLOAD_DATABASE_NAME, + CONTEXT_OFFLOAD_VALUES_DIRECTORY_NAME, + SqliteContextOffloadStore, +} from '../sqlite-context-offload-store.js'; import { openStorageFootprintReader } from '../storage-footprint.js'; test('storage footprint measures known Sessions from their rows and totals from files', async () => { @@ -69,6 +74,21 @@ test('storage footprint measures known Sessions from their rows and totals from payload_json, committed_at ) VALUES ('event-1', 'parent', 'invocation-1', 'run-1', 'turn-1', 1, 'kind', ?, 1)`, ).run('z'.repeat(40)); + // Every runtime source contributes, so a wrong table or column fails here. + db.prepare( + `INSERT INTO runtime_partial_snapshots( + stream_key, session_id, invocation_id, run_id, turn_id, after_event_id, + payload_json, text_content, updated_at + ) VALUES ('stream-1', 'parent', 'invocation-1', 'run-1', 'turn-1', NULL, ?, ?, 1)`, + ).run('p'.repeat(7), 'é'.repeat(3)); + db.prepare( + `INSERT INTO core_agent_runs(session_id, run_id, created_at) VALUES ('parent', 'run-1', 1)`, + ).run(); + db.prepare( + `INSERT INTO core_agent_run_events( + session_id, run_id, sequence, event_id, event_type, event_ts, record_json + ) VALUES ('parent', 'run-1', 0, 'agent-event-1', 'kind', 1, ?)`, + ).run('r'.repeat(11)); db.prepare('INSERT INTO artifact_records VALUES (?, ?, ?, ?, ?)').run( 'artifact-1', 'parent', @@ -76,12 +96,8 @@ test('storage footprint measures known Sessions from their rows and totals from 'parent/artifact-1-file', JSON.stringify({ sizeBytes: 1234 }), ); - db.prepare( - 'INSERT INTO usage_llm_calls(storage_key, id, ts, record_json, session_id) VALUES (?, ?, ?, ?, ?)', - ).run('usage-1', 'usage-1', 1, 'u'.repeat(30), 'gone'); await writeFile(join(root, 'memory.sqlite'), Buffer.alloc(2048)); await writeFile(join(root, 'memory.sqlite-journal'), Buffer.alloc(16)); - await writeFile(join(root, 'context-offload.sqlite'), Buffer.alloc(4096)); await mkdir(join(root, 'subagent-worktrees', 'lease-a'), { recursive: true }); await mkdir(join(root, 'subagent-worktrees', 'lease-b'), { recursive: true }); @@ -89,8 +105,14 @@ test('storage footprint measures known Sessions from their rows and totals from assert.deepEqual(sessions, [ { sessionId: 'parent', - // 'x' * 100 + JSON quotes, 'é' * 10 as 20 bytes + quotes, one 300-byte chunk. - bytes: { transcript: 102 + 22 + 300, runtime: 40, artifacts: 1234, context: 700 }, + bytes: { + // 'x' * 100 + JSON quotes, 'é' * 10 as 20 bytes + quotes, one 300-byte chunk. + transcript: 102 + 22 + 300, + // runtime event 40, partial snapshot 7 + 6, agent-run event 11. + runtime: 40 + 7 + 6 + 11, + artifacts: 1234, + context: 700, + }, worktreeCount: 1, }, { @@ -110,14 +132,14 @@ test('storage footprint measures known Sessions from their rows and totals from ); assert.deepEqual(totals.get('database'), { kind: 'database', - bytes: await databaseFileBytes(root), + bytes: await fileSetBytes(join(root, OPERATIONAL_STATE_DATABASE_NAME)), exact: true, }); assert.deepEqual(totals.get('artifacts'), { kind: 'artifacts', bytes: 1234, exact: false }); assert.deepEqual(totals.get('context_offload'), { kind: 'context_offload', - bytes: 400 + 4096, - exact: false, + bytes: 0, + exact: true, }); assert.deepEqual(totals.get('memory'), { kind: 'memory', bytes: 2048 + 16, exact: true }); assert.equal(footprint.worktreeCount, 2); @@ -135,7 +157,85 @@ test('storage footprint measures known Sessions from their rows and totals from } }); -test('storage footprint omits context usage when the Store is unavailable', async () => { +test('context offload counts inline blobs once and managed value files once', async () => { + const root = await mkdtemp(join(tmpdir(), 'maka-storage-footprint-context-')); + const owner = acquireOperationalStateDatabase(root); + const store = new SqliteContextOffloadStore(join(root, CONTEXT_OFFLOAD_DATABASE_NAME), { + limits: { + ownerMaxBytes: { read_image_snapshot: 4 * 1024 * 1024, tool_result_archive: 4 * 1024 * 1024 }, + sessionLogicalBytes: 16 * 1024 * 1024, + workspacePhysicalBytes: 32 * 1024 * 1024, + }, + }); + const reader = openStorageFootprintReader(root, { contextOffload: store }); + try { + const inlineBytes = 1_000_000; + const managedBytes = 300_000; + const inline = await store.put({ + sessionId: 'session-1', + owner: { kind: 'tool_result_archive', ownerId: 'tool-1' }, + bytes: new Uint8Array(inlineBytes).fill(1), + mediaType: 'application/octet-stream', + }); + const managed = await store.put({ + sessionId: 'session-1', + owner: { kind: 'read_image_snapshot', ownerId: 'read-1' }, + bytes: new Uint8Array(managedBytes).fill(2), + mediaType: 'image/png', + }); + assert.equal(inline.ok && managed.ok, true); + assert.equal((await store.usage()).physicalBytes, inlineBytes + managedBytes); + + const sqliteFiles = await fileSetBytes(join(root, CONTEXT_OFFLOAD_DATABASE_NAME)); + const valueFiles = await treeBytes(join(root, CONTEXT_OFFLOAD_VALUES_DIRECTORY_NAME)); + assert.equal(valueFiles, managedBytes); + // The inline blob already sits inside the SQLite file set. + assert.ok(sqliteFiles >= inlineBytes); + + const context = (await reader.measure()).totals.find( + (total) => total.kind === 'context_offload', + ); + assert.deepEqual(context, { + kind: 'context_offload', + bytes: sqliteFiles + managedBytes, + exact: true, + }); + } finally { + reader.close(); + store.close(); + owner.close(); + await rm(root, { recursive: true, force: true }); + } +}); + +test('multi-Session measurement yields to the event loop between statements', async () => { + const root = await mkdtemp(join(tmpdir(), 'maka-storage-footprint-yield-')); + const owner = acquireOperationalStateDatabase(root); + const reader = openStorageFootprintReader(root); + try { + const sessionIds = ['session-a', 'session-b', 'session-c']; + for (const sessionId of sessionIds) insertSession(owner.database, sessionId, {}); + let turns = 0; + let measuring = true; + const tick = () => { + if (!measuring) return; + turns += 1; + setImmediate(tick); + }; + setImmediate(tick); + const measured = await reader.measureSessions(sessionIds); + measuring = false; + assert.equal(measured.length, 3); + // Per Session: existence, 2 transcript, 3 runtime, 1 artifact and 1 worktree statement. + assert.ok(turns >= sessionIds.length * 8, `only ${turns} event-loop turns ran`); + } finally { + reader.close(); + owner.close(); + await rm(root, { recursive: true, force: true }); + } +}); + +test('storage footprint omits per-Session context when the Store is unavailable', async () => { const root = await mkdtemp(join(tmpdir(), 'maka-storage-footprint-no-context-')); const owner = acquireOperationalStateDatabase(root); const reader = openStorageFootprintReader(root); @@ -144,10 +244,6 @@ test('storage footprint omits context usage when the Store is unavailable', asyn const [session] = await reader.measureSessions(['alone']); assert.deepEqual(session?.bytes, { transcript: 0, runtime: 0, artifacts: 0 }); const footprint = await reader.measure(); - assert.equal( - footprint.totals.some((total) => total.kind === 'context_offload'), - false, - ); assert.equal(footprint.worktreeCount, 0); } finally { reader.close(); @@ -184,12 +280,20 @@ function insertMessage(db: DatabaseSync, sessionId: string, sequence: number, te ).run(sessionId, sequence, `${sessionId}-${sequence}`, JSON.stringify(text)); } -async function databaseFileBytes(root: string): Promise { +async function fileSetBytes(path: string): Promise { let total = 0; for (const suffix of ['', '-wal', '-shm', '-journal']) { try { - total += (await stat(join(root, `${OPERATIONAL_STATE_DATABASE_NAME}${suffix}`))).size; + total += (await stat(`${path}${suffix}`)).size; } catch {} } return total; } + +async function treeBytes(path: string): Promise { + let total = 0; + for (const entry of await readdir(path, { withFileTypes: true, recursive: true })) { + if (entry.isFile()) total += (await stat(join(entry.parentPath, entry.name))).size; + } + return total; +} diff --git a/packages/storage/src/storage-footprint.ts b/packages/storage/src/storage-footprint.ts index 1e58f7ee96f..86f94f9b929 100644 --- a/packages/storage/src/storage-footprint.ts +++ b/packages/storage/src/storage-footprint.ts @@ -17,6 +17,7 @@ * under the License. */ +import type { Dirent } from 'node:fs'; import { readdir, stat } from 'node:fs/promises'; import { join } from 'node:path'; import type { ContextOffloadStore } from '@maka/core/context-offload'; @@ -27,7 +28,10 @@ import { OPERATIONAL_STATE_DATABASE_NAME, type OperationalStateDatabaseLease, } from './operational-state-store.js'; -import { CONTEXT_OFFLOAD_DATABASE_NAME } from './sqlite-context-offload-store.js'; +import { + CONTEXT_OFFLOAD_DATABASE_NAME, + CONTEXT_OFFLOAD_VALUES_DIRECTORY_NAME, +} from './sqlite-context-offload-store.js'; import { sqliteDatabaseSidecars } from './sqlite-file-set.js'; /** @@ -76,8 +80,8 @@ export interface StorageFootprintReader { measure(): Promise; /** * Measures the Sessions that exist, in input order; unknown ids are omitted. - * Callers bound the list (the Host protocol admits 25 per request), which - * keeps every `IN (...)` far below SQLite's bound-parameter limit. + * Each Session is measured by its own statements, so the cost of one request + * is bounded by the caller's list (the Host protocol admits 25). */ measureSessions(sessionIds: readonly string[]): Promise; close(): void; @@ -88,8 +92,8 @@ export interface OpenStorageFootprintReaderOptions { } /** - * Per-Session payload sums. Each statement is a range scan over an index that - * leads with `session_id`, so its cost grows with the requested Sessions' rows + * Per-Session payload sums. Each statement covers one Session through an index + * that leads with `session_id`, so its cost grows with that Session's rows * rather than with the table. `octet_length` on TEXT and `length` on BLOB skip * the overflow pages of large values, but every matching row is still read. */ @@ -145,25 +149,17 @@ class SqliteStorageFootprintReader implements StorageFootprintReader { // One small metadata row per artifact file, so the whole table stays cheap. const artifacts = this.#readAllArtifactBytes(); await yieldToEventLoop(); - const contextUsage = await this.contextOffload?.usage(); - const contextFileBytes = contextUsage - ? await fileSetBytes(join(this.root, CONTEXT_OFFLOAD_DATABASE_NAME)) - : 0; + // Inline blobs live inside the SQLite file set, so only the managed value + // files outside it are added; the Store's physical-byte counter covers both. + const contextBytes = + (await fileSetBytes(join(this.root, CONTEXT_OFFLOAD_DATABASE_NAME))) + + (await directoryBytes(join(this.root, CONTEXT_OFFLOAD_VALUES_DIRECTORY_NAME))); const memoryBytes = await fileSetBytes(join(this.root, LONG_TERM_MEMORY_DATABASE_NAME)); const worktreeCount = await countDirectories(join(this.root, SUBAGENT_WORKTREE_DIRECTORY)); const totals: StorageFootprintTotal[] = [ { kind: 'database', bytes: databaseBytes, exact: true }, { kind: 'artifacts', bytes: artifacts, exact: false }, - ...(contextUsage - ? [ - { - kind: 'context_offload' as const, - // Inline blobs are counted in both terms, so this can overstate. - bytes: contextUsage.physicalBytes + contextFileBytes, - exact: false, - }, - ] - : []), + { kind: 'context_offload', bytes: contextBytes, exact: true }, { kind: 'memory', bytes: memoryBytes, exact: true }, ]; return { totals, reclaimableBytes, worktreeCount }; @@ -173,29 +169,27 @@ class SqliteStorageFootprintReader implements StorageFootprintReader { sessionIds: readonly string[], ): Promise { this.#assertOpen(); - const requested = [...new Set(sessionIds)]; - if (requested.length === 0) return []; - const known = await this.#readKnownSessions(requested); - const sessions = requested.filter((sessionId) => known.has(sessionId)); - if (sessions.length === 0) return []; - const transcript = await this.#sumBySession(TRANSCRIPT_SOURCES, sessions); - const runtime = await this.#sumBySession(RUNTIME_SOURCES, sessions); - const artifacts = await this.#sumBySession([ARTIFACT_SOURCE], sessions); - const worktrees = await this.#countWorktreesBySession(sessions); const results: SessionStorageFootprint[] = []; - for (const sessionId of sessions) { + // One Session per statement, with a yield after each: a large task's sum + // is still a long range scan, and the Host serves other work between them. + for (const sessionId of new Set(sessionIds)) { + if (!(await this.#sessionExists(sessionId))) continue; + const transcript = await this.#sumForSession(TRANSCRIPT_SOURCES, sessionId); + const runtime = await this.#sumForSession(RUNTIME_SOURCES, sessionId); + const artifacts = await this.#sumForSession([ARTIFACT_SOURCE], sessionId); + const worktreeCount = await this.#countWorktrees(sessionId); const context = this.contextOffload ? (await this.contextOffload.usage(sessionId)).logicalBytes : undefined; results.push({ sessionId, bytes: { - transcript: transcript.get(sessionId) ?? 0, - runtime: runtime.get(sessionId) ?? 0, - artifacts: artifacts.get(sessionId) ?? 0, + transcript, + runtime, + artifacts, ...(context === undefined ? {} : { context }), }, - worktreeCount: worktrees.get(sessionId) ?? 0, + worktreeCount, }); } return results; @@ -207,55 +201,42 @@ class SqliteStorageFootprintReader implements StorageFootprintReader { this.lease.close(); } - async #readKnownSessions(sessionIds: readonly string[]): Promise> { - const rows = this.lease.database - .prepare( - `SELECT session_id AS sessionId FROM session_metadata - WHERE session_id IN (${placeholders(sessionIds)})`, - ) - .all(...sessionIds) as Array<{ sessionId: string }>; + async #sessionExists(sessionId: string): Promise { + const row = this.lease.database + .prepare('SELECT 1 AS present FROM session_metadata WHERE session_id = ?') + .get(sessionId); await yieldToEventLoop(); - return new Set(rows.map((row) => row.sessionId)); + return row !== undefined; } - async #sumBySession( - sources: readonly SqlByteSource[], - sessionIds: readonly string[], - ): Promise> { - const totals = new Map(); + async #sumForSession(sources: readonly SqlByteSource[], sessionId: string): Promise { + let total = 0; for (const source of sources) { - const rows = this.lease.database + const row = this.lease.database .prepare( - `SELECT session_id AS sessionId, COALESCE(SUM(${source.bytes}), 0) AS bytes + `SELECT COALESCE(SUM(${source.bytes}), 0) AS bytes FROM ${source.table} - WHERE session_id IN (${placeholders(sessionIds)}) - GROUP BY session_id`, + WHERE session_id = ?`, ) - .all(...sessionIds) as Array<{ sessionId: string; bytes: number | bigint }>; - for (const row of rows) { - totals.set(row.sessionId, (totals.get(row.sessionId) ?? 0) + toSafeCount(row.bytes)); - } + .get(sessionId) as { bytes: number | bigint }; + total += toSafeCount(row.bytes); await yieldToEventLoop(); } - return totals; + return total; } - async #countWorktreesBySession(sessionIds: readonly string[]): Promise> { - const list = placeholders(sessionIds); - const rows = this.lease.database + async #countWorktrees(sessionId: string): Promise { + const row = this.lease.database .prepare( - `SELECT owner AS sessionId, COUNT(*) AS count FROM ( - SELECT session_id AS owner FROM session_metadata - WHERE session_id IN (${list}) AND ${HAS_WORKTREE} - UNION ALL - SELECT subagent_parent_session_id AS owner FROM session_metadata - WHERE subagent_parent_session_id IN (${list}) AND ${HAS_WORKTREE} - ) - GROUP BY owner`, + `SELECT + (SELECT COUNT(*) FROM session_metadata + WHERE session_id = ? AND ${HAS_WORKTREE}) + + (SELECT COUNT(*) FROM session_metadata + WHERE subagent_parent_session_id = ? AND ${HAS_WORKTREE}) AS count`, ) - .all(...sessionIds, ...sessionIds) as Array<{ sessionId: string; count: number | bigint }>; + .get(sessionId, sessionId) as { count: number | bigint }; await yieldToEventLoop(); - return new Map(rows.map((row) => [row.sessionId, toSafeCount(row.count)])); + return toSafeCount(row.count); } #readAllArtifactBytes(): number { @@ -287,10 +268,6 @@ interface SqlByteSource { readonly bytes: string; } -function placeholders(values: readonly unknown[]): string { - return values.map(() => '?').join(', '); -} - async function fileSetBytes(databasePath: string): Promise { let total = 0; for (const path of [databasePath, ...sqliteDatabaseSidecars(databasePath)]) { @@ -303,6 +280,32 @@ async function fileSetBytes(databasePath: string): Promise { return total; } +/** Files under the managed context value tree (`sha256//`), stat'ed asynchronously. */ +async function directoryBytes(path: string, depth = 0): Promise { + let entries: Dirent[]; + try { + entries = await readdir(path, { withFileTypes: true }); + } catch (error) { + if (isMissingFile(error)) return 0; + throw error; + } + let total = 0; + for (const entry of entries) { + const child = join(path, entry.name); + if (entry.isDirectory() && depth < 3) { + total += await directoryBytes(child, depth + 1); + } else if (entry.isFile()) { + try { + total += (await stat(child)).size; + } catch (error) { + // A value file deleted mid-walk simply no longer counts. + if (!isMissingFile(error)) throw error; + } + } + } + return total; +} + async function countDirectories(path: string): Promise { try { const entries = await readdir(path, { withFileTypes: true }); From 226470348e60186e323739469a106f79a7dbe1fe Mon Sep 17 00:00:00 2001 From: liugddx Date: Wed, 30 Sep 2026 08:39:40 +0800 Subject: [PATCH 4/4] fix(runtime-host): fail admission instead of dropping older Hosts Treating the two storage operations as a compatible extension was wrong for a new Desktop talking to an epoch-198 Host: the Host rejects the unknown key in `requireOperationKey` and closes the live connection, and Data Settings sends `storage.usage.query` on every open and retry. Restore the epoch bump (198 -> 199), so the mismatched pair is refused at the handshake, and drop the compatible-change declaration. Observe task rows against their nearest scrolling ancestor, so the 200px prefetch margin applies inside the Settings scroll container. Co-Authored-By: Claude Opus 5.5 (1M context) --- apps/desktop/src/preload/session-storage-usage.ts | 6 ++---- .../storage-usage/ui/task-storage-size.tsx | 15 ++++++++++++++- .../storage-usage-operations.json | 8 -------- packages/runtime-host/src/protocol/index.ts | 5 ++++- 4 files changed, 20 insertions(+), 14 deletions(-) delete mode 100644 packages/runtime-host/protocol-compatible-changes/storage-usage-operations.json diff --git a/apps/desktop/src/preload/session-storage-usage.ts b/apps/desktop/src/preload/session-storage-usage.ts index f9317d0cd8e..ee7c7de0494 100644 --- a/apps/desktop/src/preload/session-storage-usage.ts +++ b/apps/desktop/src/preload/session-storage-usage.ts @@ -46,10 +46,8 @@ export type SessionStorageUsageReader = ( * whose Host cannot be resolved, or a Host whose query fails, is left out * rather than failing the other Hosts' tasks. * - * A failing Host is skipped for a cooldown. An older Host that predates the - * operation rejects it by closing the connection, as it does for any unknown - * operation, so asking again for every newly visible row would keep dropping - * that connection. + * A failing Host is skipped for a cooldown, so a Host that is draining or + * failing is not asked again for every newly visible row. */ export function createSessionStorageUsageReader( routing: SessionStorageUsageRouting, diff --git a/apps/desktop/src/renderer/features/storage-usage/ui/task-storage-size.tsx b/apps/desktop/src/renderer/features/storage-usage/ui/task-storage-size.tsx index 14bb6ab6ebb..55e0f74fcbd 100644 --- a/apps/desktop/src/renderer/features/storage-usage/ui/task-storage-size.tsx +++ b/apps/desktop/src/renderer/features/storage-usage/ui/task-storage-size.tsx @@ -58,7 +58,7 @@ export function TaskStorageSize(props: { readonly sessionId: string }) { setVisible(true); } }, - { rootMargin: VISIBILITY_MARGIN }, + { root: scrollParent(element), rootMargin: VISIBILITY_MARGIN }, ); observer.observe(element); return () => observer.disconnect(); @@ -86,3 +86,16 @@ export function TaskStorageSize(props: { readonly sessionId: string }) { ); } + +/** + * The nearest scrolling ancestor. `rootMargin` only prefetches relative to the + * observer root, and the Settings list scrolls inside its own container rather + * than the viewport. + */ +function scrollParent(element: Element): Element | null { + for (let node = element.parentElement; node; node = node.parentElement) { + const overflowY = node.ownerDocument.defaultView?.getComputedStyle?.(node).overflowY; + if (overflowY === 'auto' || overflowY === 'scroll') return node; + } + return null; +} diff --git a/packages/runtime-host/protocol-compatible-changes/storage-usage-operations.json b/packages/runtime-host/protocol-compatible-changes/storage-usage-operations.json deleted file mode 100644 index cd3989874fc..00000000000 --- a/packages/runtime-host/protocol-compatible-changes/storage-usage-operations.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "epoch": 198, - "files": [ - "packages/runtime-host/src/protocol/storage-usage.ts", - "packages/runtime-host/src/protocol/operations.ts" - ], - "reason": "Adds the storage.usage.query and storage.usage.sessions.query operation specs and registers their keys, including the remote-owner grant list. Two new operation keys are an additive extension: a peer that predates them never sends either operation and never receives a response for one, so every existing request and response decodes byte-for-byte as before. Nothing already on the wire changes shape or meaning." -} diff --git a/packages/runtime-host/src/protocol/index.ts b/packages/runtime-host/src/protocol/index.ts index 2f41d5595c1..1d259650c0d 100644 --- a/packages/runtime-host/src/protocol/index.ts +++ b/packages/runtime-host/src/protocol/index.ts @@ -104,7 +104,10 @@ export const RUNTIME_HOST_REGISTRATION_SCHEMA_VERSION = 1 as const; export const RUNTIME_HOST_PROTOCOL_VERSION = 0 as const; // Increment when the same protocol version no longer guarantees safe Client-Host // interoperability. Mismatches are rejected before domain commands are admitted. -export const RUNTIME_HOST_COMPATIBILITY_EPOCH = 198 as const; +export const RUNTIME_HOST_COMPATIBILITY_EPOCH = 199 as const; +// 199: `storage.usage.query` and `storage.usage.sessions.query` report storage +// usage. An epoch-198 Host rejects the unknown operation and drops the +// connection, so the pair must fail admission instead. // 198: Executor readiness exposes explicit restore, restore-failed and history-gap states. // 197: Queue reorder requests carry the expected queue revision. Epoch-196 // peers reject the required field or send an unfenced reorder request.