diff --git a/apps/desktop/renderer-architecture.json b/apps/desktop/renderer-architecture.json index b1f7c46be53..971fcc238e7 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..5e3f3c0166b --- /dev/null +++ b/apps/desktop/src/main/__tests__/session-storage-loader.test.ts @@ -0,0 +1,142 @@ +/* + * 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 { + STORAGE_USAGE_SESSION_MAX_ITEMS, + type SessionStorageUsage, +} 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 { + 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 }; +} + +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 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), + [STORAGE_USAGE_SESSION_MAX_ITEMS, STORAGE_USAGE_SESSION_MAX_ITEMS, 1], + ); + assert.equal(maxInFlight, 1); + assert.equal(measured[count], measured[0]); + await loader.load('session-5'); + assert.equal(queries.length, 3, 'a fresh measurement is served from the cache'); +}); + +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') }; + }, + { 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); + now += SESSION_STORAGE_RESULT_TTL_MS; + await loader.load('session-a'); + 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' }, + }; + let now = 0; + const queried: string[] = []; + const read = createSessionStorageUsageReader( + { + 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) => { + 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 }, + ); + 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 new file mode 100644 index 00000000000..a62532fd98c --- /dev/null +++ b/apps/desktop/src/main/__tests__/storage-usage-section.test.ts @@ -0,0 +1,189 @@ +/* + * 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, + TaskStorageSize, + 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, + IntersectionObserver: globalThis.IntersectionObserver, + 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: '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, + }; + 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\.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\.0 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()); +}); + +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/main/runtime-host-renderer-ipc-main.ts b/apps/desktop/src/main/runtime-host-renderer-ipc-main.ts index 611b2023a1a..54c7f104fea 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,10 @@ 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 '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 d3db91690bd..79d014f8124 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 is absent when its + * Runtime Host is unavailable or fails, or when that Host no longer holds it. + */ + 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..441afb06c32 100644 --- a/apps/desktop/src/preload/preload.ts +++ b/apps/desktop/src/preload/preload.ts @@ -257,8 +257,11 @@ import { 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 { createSessionStorageUsageReader } from './session-storage-usage.js'; import type { AgentGraphEpochDirectory } from '@maka/runtime-host/client'; import { desktopSessionKey, @@ -1246,6 +1249,19 @@ const runtimeHost: MakaBridge['runtimeHost'] = { }, }; +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)); for (let attempt = 0; attempt < 3; attempt += 1) { @@ -3695,6 +3711,14 @@ const makaBridge = { ); }, }, + storage: { + async usage(host?: DesktopRuntimeHostRef): Promise { + return scopedRuntimeHost(await selectedRuntimeHostScope(host)).query('storage.usage.query', {}); + }, + sessionUsage(sessionIds: readonly string[]): Promise> { + return loadDesktopSessionStorageUsage(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..d327cb205dd 100644 --- a/apps/desktop/src/preload/runtime-host-renderer-operations.ts +++ b/apps/desktop/src/preload/runtime-host-renderer-operations.ts @@ -27,6 +27,9 @@ 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', + '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..ee7c7de0494 --- /dev/null +++ b/apps/desktop/src/preload/session-storage-usage.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 { + 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; +} + +/** 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, so a Host that is draining or + * failing is not asked again for every newly visible row. + */ +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)) { + let ref: Awaited['resolve']>>; + try { + ref = await routing.resolve(sessionId); + } catch { + continue; + } + if (hosts.skip(ref.scopeKey)) 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.entries()].map(async ([scopeKey, { 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. + hosts.failed(scopeKey); + } + }), + ); + 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/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..f64555059a9 --- /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 } 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 new file mode 100644 index 00000000000..61197b534de --- /dev/null +++ b/apps/desktop/src/renderer/features/storage-usage/model/session-storage-loader.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 { + STORAGE_USAGE_SESSION_MAX_ITEMS, + type SessionStorageUsage, +} from '@maka/runtime-host/protocol'; + +/** 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; +/** 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 { + readonly result: Promise; + settledAt?: number; + measured?: boolean; +} + +/** + * 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( + loadSessionUsage: ( + sessionIds: readonly string[], + ) => Promise>>, + options: { readonly now?: () => number } = {}, +): SessionStorageLoader { + const now = options.now ?? Date.now; + const entries = new Map(); + const queue = new Map void>(); + let draining = false; + + const settle = (sessionId: string, usage: SessionStorageUsage | undefined) => { + const entry = entries.get(sessionId); + if (entry) { + entry.settledAt = now(); + entry.measured = usage !== undefined; + } + }; + + 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); + 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; + prune(); + }; + + return { + load(sessionId) { + const existing = entries.get(sessionId); + if (existing && isFresh(existing)) return existing.result; + const result = new Promise((resolve) => { + queue.set(sessionId, resolve); + }); + 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; + }, + size: () => entries.size, + }; +} + +/** 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..a4707fec51c --- /dev/null +++ b/apps/desktop/src/renderer/features/storage-usage/services-context.tsx @@ -0,0 +1,59 @@ +/* + * 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, useMemo } from 'react'; +import { createSessionStorageLoader, type SessionStorageLoader } from './model/session-storage-loader.js'; +import type { StorageUsageServices } from './ports.js'; + +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} + + ); +} + +/** Undefined outside a Desktop composition; the surfaces then render nothing. */ +export function useOptionalStorageUsageServices(): StorageUsageServices | undefined { + 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 new file mode 100644 index 00000000000..36f85638e05 --- /dev/null +++ b/apps/desktop/src/renderer/features/storage-usage/testing.ts @@ -0,0 +1,29 @@ +/* + * 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, + 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/storage-usage-section.tsx b/apps/desktop/src/renderer/features/storage-usage/ui/storage-usage-section.tsx new file mode 100644 index 00000000000..1aa654ff47b --- /dev/null +++ b/apps/desktop/src/renderer/features/storage-usage/ui/storage-usage-section.tsx @@ -0,0 +1,168 @@ +/* + * 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, 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 { useOptionalStorageUsageServices } from '../services-context.js'; + +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 [scoped, setScoped] = useState({ + hostKey, + measurement: { status: 'loading' }, + }); + const [attempt, setAttempt] = useState(0); + + useEffect(() => { + if (!host || !services || !props.hostVerified) return; + let current = true; + 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) setScoped({ hostKey, measurement: { status: 'ready', usage } }); + }, + () => { + if (current) setScoped({ hostKey, measurement: { status: 'failed' } }); + }, + ); + return () => { + current = false; + }; + }, [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 + : measurement.status === 'loading' + ? measurement.previous + : undefined; + const size = (bytes: number, exact: boolean) => { + const formatted = formatBytes(bytes, locale); + return exact ? formatted : copy.approximately(formatted); + }; + const totals = usage + ? 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; + + 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 ? ( + <> + + {formatBytes(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..55e0f74fcbd --- /dev/null +++ b/apps/desktop/src/renderer/features/storage-usage/ui/task-storage-size.tsx @@ -0,0 +1,101 @@ +/* + * 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, useRef, useState } from 'react'; +import { Text } from '@astryxdesign/core/Text'; +import { formatBytes, useUiLocale } from '@maka/ui'; +import type { SessionStorageUsage } from '@maka/runtime-host/protocol'; +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. + * + * 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(() => { + 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); + } + }, + { root: scrollParent(element), 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) => { + if (current) setUsage(measured); + }); + return () => { + current = false; + }; + }, [loader, props.sessionId, visible]); + + return ( + + {usage ? ( + + {getStorageUsageCopy(locale).taskSize(formatBytes(sessionStorageBytes(usage), locale))} + + ) : null} + + ); +} + +/** + * 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/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..387cb413612 --- /dev/null +++ b/apps/desktop/src/renderer/locales/storage-usage-copy.ts @@ -0,0 +1,147 @@ +/* + * 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'; +import type { StorageUsageKind } from '@maka/runtime-host/protocol'; + +export type StorageUsageCopy = { + title: string; + help: string; + loading: string; + loadFailed: string; + refresh: string; + total: string; + totalDetail: string; + /** 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 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; + /** 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: { + database: { + label: '任务数据库', + detail: '任务的对话、运行日志、用量历史和索引。用量历史在删除任务后仍会保留,以保证用量统计完整。', + }, + artifacts: { label: '产物文件', detail: '任务生成或导入的文件,按记录的文件大小统计。' }, + context_offload: { + label: '卸载的上下文', + detail: '为节省上下文而移出的长内容,相同内容只保存一份。', + }, + memory: { 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: { + database: { + label: '任務資料庫', + detail: '任務的對話、執行日誌、用量歷史和索引。用量歷史在刪除任務後仍會保留,以確保用量統計完整。', + }, + artifacts: { label: '產物檔案', detail: '任務生成或匯入的檔案,依記錄的檔案大小統計。' }, + context_offload: { + label: '卸載的上下文', + detail: '為節省上下文而移出的長內容,相同內容只儲存一份。', + }, + memory: { 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 records and may overlap slightly with another row.', + kinds: { + 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.' }, + }, + reclaimable: 'Reclaimable space', + reclaimableDetail: + '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`), + 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 ? ( ) : ( @@ -239,6 +241,7 @@ export function TasksSettingsPage( startContent={