Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
fix: use daemon local days for token usage (#635)
Gustavo Ye887cdfe74464
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex f89ed3bf0..8f0e2e45d 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -138,7 +138,7 @@ jobs:needs: scopeif: needs.scope.outputs.run_code_checks == 'true'runs-on: ubuntu-latest- timeout-minutes: 15+ timeout-minutes: 25env:RUN_COVERAGE: ${{ github.event_name != 'push' || startsWith(github.event.head_commit.message, 'release:') }}steps:@@ -163,14 +163,34 @@ jobs:- name: Build agent-driver for coverageif: env.RUN_COVERAGE == 'true'run: pnpm --filter @alook/agent-driver build- - name: Run full tests with coverage+ - name: Run non-daemon tests with coverage+ if: env.RUN_COVERAGE == 'true'+ run: |+ pnpm vitest run --project='!daemon-node' --coverage \+ --reporter=blob --outputFile=.vitest-reports/non-daemon.blob \+ --exclude src/pack.test.ts+ - name: Run daemon tests with coverage+ if: env.RUN_COVERAGE == 'true'+ run: |+ pnpm vitest run --project=daemon-node --coverage \+ --reporter=blob --outputFile=.vitest-reports/daemon.blob \+ --exclude src/cli/daemonLifecycle.real.test.ts \+ --exclude src/cli/diagnosticsLifecycle.real.test.ts \+ --exclude src/cli/daemonStop.test.ts \+ --exclude src/version.packed.test.ts \+ --exclude src/agent-driver-bundle.packed.test.ts \+ --exclude src/cli/daemonSelfUpdate.real.test.ts+ - name: Merge coverage reportsif: env.RUN_COVERAGE == 'true'run: |pnpm vitest run --coverage --coverage.reporter=json --coverage.reporter=text \- --exclude src/daemon/agent-driver/src/pack.test.ts \- --exclude src/daemon/src/version.packed.test.ts \- --exclude src/daemon/src/agent-driver-bundle.packed.test.ts \- --exclude src/daemon/src/cli/daemonSelfUpdate.real.test.ts+ --merge-reports=.vitest-reports+ - name: Run daemon real-process tests after coverage+ if: env.RUN_COVERAGE == 'true'+ run: |+ pnpm --filter @alook/daemon exec vitest run --no-file-parallelism \+ src/cli/daemonLifecycle.real.test.ts src/cli/diagnosticsLifecycle.real.test.ts \+ src/cli/daemonStop.test.ts- name: Run package artifact tests after coverageif: env.RUN_COVERAGE == 'true'run: |diff --git a/.gitignore b/.gitignoreindex 131ca266c..777fb3e87 100644--- a/.gitignore+++ b/.gitignore@@ -11,6 +11,7 @@ bundled/.next/src/web/readme-capture/next-env.d.tscoverage/+.vitest-reports/.open-next/temp/docs/diff --git a/scripts/ci/workflow-contract.test.ts b/scripts/ci/workflow-contract.test.tsindex 48f0b89e9..9b85932f0 100644--- a/scripts/ci/workflow-contract.test.ts+++ b/scripts/ci/workflow-contract.test.ts@@ -41,6 +41,10 @@ const rootVitestConfig = readFileSync(resolve(import.meta.dirname, "../../vitest.config.ts"),"utf8",)+const daemonVitestConfig = readFileSync(+ resolve(import.meta.dirname, "../../src/daemon/vitest.config.ts"),+ "utf8",+)const rootPackageJson = JSON.parse(readFileSync(resolve(import.meta.dirname, "../../package.json"), "utf8"),) as {@@ -458,9 +462,14 @@ describe("Turbo CI execution", () => {expect(windows).toContain("run: pnpm turbo run test --filter=@alook/cli --filter=@alook/app --filter=@alook/shared",)- for (const definition of [linux, windows]) {- expect(definition.match(/VITEST_MAX_WORKERS: 1/g)).toHaveLength(1)- }+ expect(linux.match(/VITEST_MAX_WORKERS: 1/g)).toHaveLength(1)+ expect(windows.match(/VITEST_MAX_WORKERS: 1/g)).toHaveLength(1)+ })++ it("isolates daemon process-authority tests in root workspace runs", () => {+ expect(daemonVitestConfig).toContain('name: "daemon-node"')+ expect(daemonVitestConfig).toContain("maxWorkers: 1")+ expect(daemonVitestConfig).toContain("sequence: { groupOrder: 2 }")})it("runs each direct Worker Node and runtime project once through its standard test task", () => {@@ -522,35 +531,59 @@ describe("Turbo CI execution", () => {)})- it("keeps package builds away from dist consumers and uploads one Istanbul report", () => {+ it("keeps package builds away from dist consumers and uploads one merged Istanbul report", () => {const linux = ciJob("test-linux")+ expect(linux).toContain("timeout-minutes: 25")expect(linux).toContain("RUN_COVERAGE: ${{ github.event_name != 'push' || startsWith(github.event.head_commit.message, 'release:') }}",)- expect(linux.match(/pnpm vitest run --coverage/g)).toHaveLength(1)+ expect(linux).toContain("pnpm vitest run --project='!daemon-node' --coverage")+ expect(linux).toContain("pnpm vitest run --project=daemon-node --coverage")+ expect(linux).toContain("--reporter=blob --outputFile=.vitest-reports/non-daemon.blob")+ expect(linux).toContain("--reporter=blob --outputFile=.vitest-reports/daemon.blob")+ expect(linux).toContain("--merge-reports=.vitest-reports")expect(linux.match(/codecov\/codecov-action/g)).toHaveLength(1)expect(linux).toContain("if: env.RUN_COVERAGE == 'true'")expect(linux).toContain("if: env.RUN_COVERAGE != 'true'")expect(linux).toContain("files: ./coverage/coverage-final.json")for (const testPath of [- "src/daemon/agent-driver/src/pack.test.ts",- "src/daemon/src/version.packed.test.ts",- "src/daemon/src/agent-driver-bundle.packed.test.ts",- "src/daemon/src/cli/daemonSelfUpdate.real.test.ts",+ "src/pack.test.ts",+ "src/cli/daemonLifecycle.real.test.ts",+ "src/cli/diagnosticsLifecycle.real.test.ts",+ "src/cli/daemonStop.test.ts",+ "src/version.packed.test.ts",+ "src/agent-driver-bundle.packed.test.ts",+ "src/cli/daemonSelfUpdate.real.test.ts",]) {expect(linux).toContain(`--exclude ${testPath}`)}+ expect(linux).not.toContain("--exclude src/daemon/")+ expect(linux).toContain("pnpm --filter @alook/daemon exec vitest run --no-file-parallelism")+ for (const testPath of [+ "src/cli/daemonLifecycle.real.test.ts",+ "src/cli/diagnosticsLifecycle.real.test.ts",+ "src/cli/daemonStop.test.ts",+ ]) {+ expect(linux.slice(linux.indexOf("- name: Run daemon real-process tests after coverage")))+ .toContain(testPath)+ }expect(linux).toContain("pnpm --filter @alook/agent-driver exec vitest run --no-file-parallelism src/pack.test.ts",)expect(linux).toContain("pnpm --filter @alook/daemon exec vitest run --no-file-parallelism src/version.packed.test.ts src/agent-driver-bundle.packed.test.ts src/cli/daemonSelfUpdate.real.test.ts",)- const coverageRun = linux.indexOf("- name: Run full tests with coverage")+ const nonDaemonCoverageRun = linux.indexOf("- name: Run non-daemon tests with coverage")+ const daemonCoverageRun = linux.indexOf("- name: Run daemon tests with coverage")+ const coverageMerge = linux.indexOf("- name: Merge coverage reports")+ const realProcessRuns = linux.indexOf("- name: Run daemon real-process tests after coverage")const packageRuns = linux.indexOf("- name: Run package artifact tests after coverage")const coverageUpload = linux.indexOf("- name: Upload coverage")- expect(coverageRun).toBeGreaterThan(-1)- expect(packageRuns).toBeGreaterThan(coverageRun)+ expect(nonDaemonCoverageRun).toBeGreaterThan(-1)+ expect(daemonCoverageRun).toBeGreaterThan(nonDaemonCoverageRun)+ expect(coverageMerge).toBeGreaterThan(daemonCoverageRun)+ expect(realProcessRuns).toBeGreaterThan(coverageMerge)+ expect(packageRuns).toBeGreaterThan(realProcessRuns)expect(coverageUpload).toBeGreaterThan(packageRuns)expect(linux).not.toContain("coverage:workers")expect(linux).not.toContain("workers-runtime")diff --git a/src/daemon/src/daemon/createDaemon.test.ts b/src/daemon/src/daemon/createDaemon.test.tsindex 7e632cf17..5977270d6 100644--- a/src/daemon/src/daemon/createDaemon.test.ts+++ b/src/daemon/src/daemon/createDaemon.test.ts@@ -147,6 +147,10 @@ class FakeSocket {headers: Record<string, string>;sent: string[] = [];private handlers: Record<string, ((...a: any[]) => void)[]> = {};+ private frameWaiters: Array<{+ matches: (frame: Record<string, unknown>) => boolean;+ resolve: (frame: Record<string, unknown>) => void;+ }> = [];constructor(url: string, headers: Record<string, string>) {this.url = url;this.headers = headers;@@ -156,6 +160,21 @@ class FakeSocket {}send(data: string): void {this.sent.push(data);+ let frame: Record<string, unknown>;+ try {+ frame = JSON.parse(data) as Record<string, unknown>;+ } catch {+ return;+ }+ for (let index = this.frameWaiters.length - 1; index >= 0; index -= 1) {+ const waiter = this.frameWaiters[index]!;+ if (!waiter.matches(frame)) continue;+ this.frameWaiters.splice(index, 1);+ waiter.resolve(frame);+ }+ }+ waitForFrame(matches: (frame: Record<string, unknown>) => boolean): Promise<Record<string, unknown>> {+ return new Promise((resolve) => this.frameWaiters.push({ matches, resolve }));}close(): void {this.emit("close");@@ -204,6 +223,7 @@ function daemonFakeSession(options: {onSend?: (input: { id: string; text: string; sequence?: number }) => void;onStop?: () => void;establish?: boolean;+ emitTurnStarted?: boolean;enforceCommandIdempotency?: boolean;} = {}): DaemonFakeSession {type Event = AgentEvent<BuiltinBackendSpecs, "codex">;@@ -242,7 +262,9 @@ function daemonFakeSession(options: {await session.fire("runtime_event", { kind: "session_init", sessionId: "test-session" });}emit({ type: "command_accepted", commandId: input.id, turnId: "daemon-test-turn", delivery: "prompt" } as never);- emit({ type: "turn_started", turnId: "daemon-test-turn", commandIds: [input.id] } as never);+ if (options.emitTurnStarted !== false) {+ emit({ type: "turn_started", turnId: "daemon-test-turn", commandIds: [input.id] } as never);+ }return { status: "accepted", delivery: "prompt", commandId: input.id, turnId: "daemon-test-turn" };},async send(input) {@@ -388,10 +410,14 @@ describe("createDaemon", () => {await sessions[0]!.fire("runtime_event", { kind: "turn_end", sessionId: "test-session" });const frames = () => sockets[0]!.sent.map((frame) => JSON.parse(frame) as any);+ expect(frames().find((frame) => frame.type === "ready")?.timeZone)+ .toBe(Intl.DateTimeFormat().resolvedOptions().timeZone);await vi.waitFor(() => expect(frames().some((frame) =>frame.type === "agent_activity"&& frame.agentId === "bot_1"&& frame.state === "idle"+ && typeof frame.usageTimeZone === "string"+ && /^\d{4}-\d{2}-\d{2}$/.test(frame.usageDay ?? "")&& frame.dailyUsage?.[0]?.metrics.input === 20&& frame.quota?.observation?.limits?.[0]?.usedPercent === 30)).toBe(true));@@ -423,6 +449,83 @@ describe("createDaemon", () => {}});+ it("uploads persisted Pi token usage when the bot becomes idle", async () => {+ const sockets: FakeSocket[] = [];+ const sessions: DaemonFakeSession[] = [];+ const workingDirectoryBase = mkdtempSync(join(tmpdir(), "daemon-pi-telemetry-"));+ startupSweepDirs.push(workingDirectoryBase);+ mkdirSync(join(workingDirectoryBase, "bot_1"), { recursive: true });+ vi.stubGlobal("fetch", vi.fn(async (input: string | URL | Request) => {+ const url = String(input);+ if (url.includes("/enroll-agent")) return Response.json({ runnerKey: "runner_test" });+ if (url.includes("/daemon/bots")) {+ return Response.json({ bots: [{ id: "bot_1", name: "Pi Bot", discriminator: "0001" }] });+ }+ return Response.json({ attempted: 0 });+ }));+ const daemon = await createDaemon({+ machineKey: "cmk_pi_telemetry",+ serverUrl: "http://server.invalid",+ serverWsUrl: "ws://x",+ webSocketFactory: factory(sockets) as never,+ runtimeReport: [{ id: "pi" }],+ driverFor: () => fullFakeDriver("pi"),+ sessionFactory: () => {+ const session = daemonFakeSession();+ sessions.push(session);+ return session;+ },+ capabilities: [],+ workingDirectoryBase,+ });++ try {+ sockets[0]!.emit("open");+ sockets[0]!.emit("message", JSON.stringify({+ type: "agent:wake",+ agentId: "bot_1",+ config: { version: 1, runtime: "pi", model: { kind: "default" }, mode: { kind: "default" } },+ launchId: "launch_pi",+ unreadNotice: { kind: "unread_notice", channel: "/demo#1234/general", latestSeq: 1 },+ }));+ await vi.waitFor(() => expect(sessions).toHaveLength(1));+ await sessions[0]!.fire("agent_event", {+ type: "token_usage",+ turnId: "daemon-test-turn",+ source: "pi_message_end",+ usage: {+ input: 13,+ output: 5,+ cache: 7,+ },+ });+ await sessions[0]!.fire("runtime_event", { kind: "turn_end", sessionId: "test-session" });++ const frames = () => sockets[0]!.sent.map((frame) => JSON.parse(frame) as any);+ await vi.waitFor(() => expect(frames().some((frame) =>+ frame.type === "agent_activity"+ && frame.agentId === "bot_1"+ && frame.state === "idle"+ && typeof frame.usageTimeZone === "string"+ && /^\d{4}-\d{2}-\d{2}$/.test(frame.usageDay ?? "")+ && frame.dailyUsage?.[0]?.metrics.input === 13+ && frame.dailyUsage?.[0]?.metrics.output === 5+ && frame.dailyUsage?.[0]?.metrics.cache === 7+ )).toBe(true));+ expect(JSON.parse(readFileSync(+ join(workingDirectoryBase, ".telemetry", "daily-token-usage.json"),+ "utf8",+ ))).toMatchObject({+ version: 1,+ bots: {+ bot_1: [{ metrics: { input: 13, output: 5, cache: 7 } }],+ },+ });+ } finally {+ await daemon.stop();+ }+ });+it("opens the builtin session factory and reports host preparation failures", async () => {const dir = mkdtempSync(join(tmpdir(), "daemon-builtin-session-"));try {@@ -706,7 +809,7 @@ for await (const line of createInterface({ input: process.stdin })) {startupSweepDirs.push(workingDirectoryBase);// The real driver SDK prepares the agent directory before session_started.// This test uses a fake session, so reproduce that precondition explicitly.- mkdirSync(join(workingDirectoryBase, "bot_1"));+ mkdirSync(join(workingDirectoryBase, "bot_1"), { recursive: true });const timers: Array<{callback: () => void;delayMs: number;@@ -1914,6 +2017,7 @@ describe("createDaemon — logging", () => {webSocketFactory: factory(sockets) as any,runtimeReport: [{ id: "codex" }],driverFor: () => fullFakeDriver("codex"),+ sessionFactory: () => daemonFakeSession(),capabilities: [],logger,});@@ -2264,6 +2368,7 @@ describe("createDaemon — level-triggered activity heartbeat (2b: live-connectiit("re-asserts a running agent's current activity every heartbeat with NO intervening transition — recovery path for a dropped frame on a live socket", async () => {vi.useFakeTimers();+ const setIntervalSpy = vi.spyOn(globalThis, "setInterval");global.fetch = vi.fn(async (url: string | URL) => {const href = String(url);if (href.includes("/enroll-agent")) return new Response(JSON.stringify({ runnerKey: "rk_1" }), { status: 200 });@@ -2273,7 +2378,8 @@ describe("createDaemon — level-triggered activity heartbeat (2b: live-connecti// A persistent, stdin-capable driver stays `running` after session_init// without emitting turn_end — so the agent sits in a STEADY working state,// which is exactly the window 2b exercises.- const emitters: DaemonFakeSession[] = [];+ const sessions: DaemonFakeSession[] = [];+ let commandId: string | undefined;const persistentDriver = {id: "codex",lifecycle: { kind: "persistent", start: "immediate", exit: "natural", inFlightWake: "queue" } as never,@@ -2285,7 +2391,6 @@ describe("createDaemon — level-triggered activity heartbeat (2b: live-connectispawn: async () => {const proc = new EventEmitter() as unknown as { kill: () => void; stdin: unknown };(proc as unknown as { kill: () => void }).kill = () => {};- emitters.push(proc as unknown as EventEmitter);return { process: proc as never };},parseLine: () => [],@@ -2294,16 +2399,26 @@ describe("createDaemon — level-triggered activity heartbeat (2b: live-connecti} as unknown as Driver;const sockets: FakeSocket[] = [];+ const workingDirectoryBase = mkdtempSync(join(tmpdir(), "daemon-heartbeat-"));+ startupSweepDirs.push(workingDirectoryBase);+ // Real driver sessions create the per-agent directory before the timeline+ // records session_started; this fake session must establish it explicitly.+ mkdirSync(join(workingDirectoryBase, "bot_1"));const daemon = await createDaemon({machineKey: "cmk_hb",serverUrl: "http://localhost:9999",serverWsUrl: "ws://x",+ workingDirectoryBase,webSocketFactory: factory(sockets) as any,runtimeReport: [{ id: "codex" }],driverFor: () => persistentDriver,sessionFactory: () => {- const session = daemonFakeSession({ establish: false });- emitters.push(session);+ const session = daemonFakeSession({+ establish: false,+ emitTurnStarted: false,+ onStart: (input) => { commandId = input.id; },+ });+ sessions.push(session);return session;},capabilities: [],@@ -2321,23 +2436,62 @@ describe("createDaemon — level-triggered activity heartbeat (2b: live-connectiunreadNotice: { kind: "unread_notice", channel: "/demo#1234/general", latestSeq: 1 },}),);+ const activityFrames = () =>+ sockets[0].sent.map((s) => JSON.parse(s)).filter((f: any) => f.type === "agent_activity");+// Let enroll + spawn resolve, then land the runtime handshake so the FSM- // reaches `running` (turnActive) — a steady working state.+ // settles its command admission before we explicitly enter a turn.await vi.advanceTimersByTimeAsync(50);- expect(emitters.length).toBeGreaterThan(0);- await emitters[0].fire("runtime_event", { kind: "session_init", sessionId: "s1" });- await vi.advanceTimersByTimeAsync(1);+ expect(sessions).toHaveLength(1);+ expect(commandId).toBeTypeOf("string");+ const idleFrame = sockets[0].waitForFrame((frame) =>+ frame.type === "agent_activity" && frame.agentId === "bot_1" && frame.state === "idle",+ );+ await sessions[0]!.fire("runtime_event", { kind: "session_init", sessionId: "s1" });+ await expect(idleFrame).resolves.toMatchObject({+ type: "agent_activity",+ agentId: "bot_1",+ state: "idle",+ });- const activityFrames = () =>- sockets[0].sent.map((s) => JSON.parse(s)).filter((f: any) => f.type === "agent_activity");+ // Observe the actual serialized socket send rather than polling fake time:+ // waitForFrame is registered before the event and resolves only after the+ // activity payload has traversed the per-agent report tail.+ const runningFrame = sockets[0].waitForFrame((frame) =>+ frame.type === "agent_activity" && frame.agentId === "bot_1" && frame.state === "running",+ );+ await sessions[0]!.fire("agent_event", {+ type: "turn_started",+ turnId: "daemon-test-turn",+ commandIds: [commandId!],+ });+ await expect(runningFrame).resolves.toMatchObject({+ type: "agent_activity",+ agentId: "bot_1",+ state: "running",+ });const beforeCount = activityFrames().length;- expect(beforeCount).toBeGreaterThan(0); // the edge transition to running fired- // Advance ONE heartbeat with no further runtime events → the level-triggered- // re-assert must emit another running frame despite zero transitions.- await vi.advanceTimersByTimeAsync(5_000);+ // Invoke the latest installed heartbeat with no further runtime events.+ // Setup may legitimately reinstall it across starting -> idle -> running;+ // the last registration is the active steady-state callback.+ // Calling+ // the registered callback directly keeps this test independent of the+ // platform-specific fake-timer handling for unref'ed intervals.+ const heartbeatCalls = setIntervalSpy.mock.calls.filter(([, delay]) => delay === 5_000);+ expect(heartbeatCalls.length).toBeGreaterThan(0);+ const heartbeatInstallCount = heartbeatCalls.length;+ const heartbeat = heartbeatCalls.at(-1)![0];+ expect(heartbeat).toBeTypeOf("function");+ if (typeof heartbeat !== "function") throw new Error("heartbeat callback was not installed");+ const heartbeatFrame = sockets[0].waitForFrame((frame) =>+ frame.type === "agent_activity" && frame.agentId === "bot_1" && frame.state === "running",+ );+ heartbeat();+ await heartbeatFrame;const after = activityFrames();- expect(after.length).toBeGreaterThan(beforeCount);+ expect(setIntervalSpy.mock.calls.filter(([, delay]) => delay === 5_000)).toHaveLength(heartbeatInstallCount);+ expect(after).toHaveLength(beforeCount + 1);expect(after.at(-1)).toMatchObject({ type: "agent_activity", agentId: "bot_1", state: "running" });await daemon.stop();diff --git a/src/daemon/src/daemon/createDaemon.ts b/src/daemon/src/daemon/createDaemon.tsindex 8252ec412..ebd2bfa39 100644--- a/src/daemon/src/daemon/createDaemon.ts+++ b/src/daemon/src/daemon/createDaemon.ts@@ -69,6 +69,7 @@ const RUNTIME_RAW_TRACE_MAX_BYTES = 8 * 1024 * 1024;export const RUNTIME_RAW_TRACE_AGENT_IDS_ENV = "ALOOK_RUNTIME_RAW_TRACE_AGENT_IDS";/** How often the daemon rewrites the `daemon status` snapshot file (batch E2). */const STATUS_WRITE_INTERVAL_MS = 5_000;+const TOKEN_USAGE_BACKENDS = new Set<BuiltinBackendId>(["claude", "codex", "opencode", "pi"]);export function parseRuntimeRawTraceAgentIds(value: string | undefined): ReadonlySet<string> {return new Set(@@ -456,10 +457,16 @@ export async function createDaemon(opts: CreateDaemonOptions): Promise<RunningDaconst quota = backendId === "claude" || backendId === "codex"? providerQuotaByBackend.get(backendId): undefined;- const dailyUsage = await dailyTokenUsage.snapshots(info.agentId);+ const usageWindow = backendId && TOKEN_USAGE_BACKENDS.has(backendId)+ ? await dailyTokenUsage.usageWindow(info.agentId)+ : null;return {...info,- ...(dailyUsage.length > 0 ? { dailyUsage } : {}),+ ...(usageWindow ? {+ usageTimeZone: usageWindow.usageTimeZone,+ usageDay: usageWindow.usageDay,+ ...(usageWindow.snapshots.length > 0 ? { dailyUsage: usageWindow.snapshots } : {}),+ } : {}),...(quota ? { quota: structuredClone(quota) } : {}),};};@@ -1062,6 +1069,7 @@ export async function createDaemon(opts: CreateDaemonOptions): Promise<RunningDaarch: opts.arch,osRelease: opts.osRelease,daemonVersion: opts.daemonVersion,+ timeZone: () => dailyTokenUsage.timeZone,providerQuotas: providerQuotaSnapshots,resyncActivities: async () => {const activities = await Promise.all(diff --git a/src/daemon/src/manager/agentRouter.test.ts b/src/daemon/src/manager/agentRouter.test.tsindex ae5dbc66f..1c93b4882 100644--- a/src/daemon/src/manager/agentRouter.test.ts+++ b/src/daemon/src/manager/agentRouter.test.ts@@ -638,6 +638,22 @@ describe("AgentRouter — buildReady runtimeReport", () => {expect(readys[0]).toMatchObject({ runtimeReport: [{ id: "claude" }] });});+ it("resolves the computer timezone again for each ready snapshot", () => {+ const { mgr } = fakeManager();+ const { ch } = fakeChannel();+ let timeZone = "Asia/Shanghai";+ const router = new AgentRouter({+ manager: mgr,+ channel: ch,+ runtimeReport: [{ id: "claude" }],+ timeZone: () => timeZone,+ });++ expect(router.buildReady().timeZone).toBe("Asia/Shanghai");+ timeZone = "America/Los_Angeles";+ expect(router.buildReady().timeZone).toBe("America/Los_Angeles");+ });+it("keeps the one-shot startup catalog unchanged in unhealthy → healthy ready resends", () => {const { mgr } = fakeManager();const { ch, readyResends } = fakeChannelWithSendReady();diff --git a/src/daemon/src/manager/agentRouter.ts b/src/daemon/src/manager/agentRouter.tsindex 1df63cd93..ebbc70488 100644--- a/src/daemon/src/manager/agentRouter.ts+++ b/src/daemon/src/manager/agentRouter.ts@@ -84,6 +84,7 @@ export interface AgentRouterOpts {arch?: string;osRelease?: string;daemonVersion?: string;+ timeZone?: string | (() => string);providerQuotas?: () => ProviderQuotaSnapshot[];resyncActivities?: () => HostAgentActivity[] | Promise<HostAgentActivity[]>;/**@@ -226,6 +227,9 @@ export class AgentRouter {* this into `wsControlChannel.sendReady()` for on-demand resends.*/buildReady(): HostReady {+ const timeZone = typeof this.opts.timeZone === "function"+ ? this.opts.timeZone()+ : this.opts.timeZone;return {runtimeReport: [...this.runtimes.values()],capabilities: [CONTROL_HEARTBEAT_CAPABILITY],@@ -235,6 +239,7 @@ export class AgentRouter {arch: this.opts.arch,osRelease: this.opts.osRelease,daemonVersion: this.opts.daemonVersion,+ timeZone,...(this.opts.providerQuotas ? { providerQuotas: this.opts.providerQuotas() } : {}),};}diff --git a/src/daemon/src/telemetry/dailyTokenUsage.test.ts b/src/daemon/src/telemetry/dailyTokenUsage.test.tsindex 8f2e1db30..727978eb3 100644--- a/src/daemon/src/telemetry/dailyTokenUsage.test.ts+++ b/src/daemon/src/telemetry/dailyTokenUsage.test.ts@@ -28,7 +28,7 @@ describe("DailyTokenUsageStore", () => {const root = mkdtempSync(join(tmpdir(), "alook-token-usage-"));roots.push(root);const now = new Date("2026-08-29T01:00:00Z");- const store = new DailyTokenUsageStore(root, () => now);+ const store = new DailyTokenUsageStore(root, () => now, "UTC");await Promise.all([store.record("bot-a", delta(10, 3, 2)),store.record("bot-b", delta(20, 4, 5)),@@ -49,7 +49,7 @@ describe("DailyTokenUsageStore", () => {it.skipIf(process.platform === "win32")("writes the atomic file with 0600 permissions", async () => {const root = mkdtempSync(join(tmpdir(), "alook-token-usage-mode-"));roots.push(root);- const store = new DailyTokenUsageStore(root, () => new Date("2026-08-29T01:00:00Z"));+ const store = new DailyTokenUsageStore(root, () => new Date("2026-08-29T01:00:00Z"), "UTC");await store.record("bot", delta(1, 2, 3));expect(statSync(join(root, ".telemetry", "daily-token-usage.json")).mode & 0o777).toBe(0o600);});@@ -58,10 +58,10 @@ describe("DailyTokenUsageStore", () => {const root = mkdtempSync(join(tmpdir(), "alook-token-rollover-"));roots.push(root);let now = new Date("2026-08-29T23:59:59Z");- const first = new DailyTokenUsageStore(root, () => now);+ const first = new DailyTokenUsageStore(root, () => now, "UTC");await first.record("bot", delta(10, 0, 0));- const restarted = new DailyTokenUsageStore(root, () => now);+ const restarted = new DailyTokenUsageStore(root, () => now, "UTC");await restarted.record("bot", {input: 2,output: null,@@ -96,7 +96,7 @@ describe("DailyTokenUsageStore", () => {const root = mkdtempSync(join(tmpdir(), "alook-token-retention-"));roots.push(root);let now = new Date("2026-08-20T12:00:00Z");- const store = new DailyTokenUsageStore(root, () => now);+ const store = new DailyTokenUsageStore(root, () => now, "UTC");for (let day = 0; day < 9; day += 1) {await store.record("bot", delta(day, day, day));now = new Date(now.getTime() + 86_400_000);@@ -119,7 +119,7 @@ describe("DailyTokenUsageStore", () => {const root = mkdtempSync(join(tmpdir(), "alook-token-quiet-prune-"));roots.push(root);let now = new Date("2026-08-20T12:00:00Z");- const store = new DailyTokenUsageStore(root, () => now);+ const store = new DailyTokenUsageStore(root, () => now, "UTC");await store.record("bot", delta(1, 1, 1));now = new Date("2026-08-29T12:00:00Z");@@ -140,10 +140,128 @@ describe("DailyTokenUsageStore", () => {mkdirSync(directory, { recursive: true });writeFileSync(filePath, "{not-json", "utf8");- const store = new DailyTokenUsageStore(root);+ const store = new DailyTokenUsageStore(root, () => new Date(), "UTC");await expect(store.record("bot", delta(1, 2, 3))).rejects.toThrow();expect(readFileSync(filePath, "utf8")).toBe("{not-json");expect(readdirSync(directory)).toEqual(["daily-token-usage.json"]);});++ it("rolls over at the daemon computer's local midnight", async () => {+ const root = mkdtempSync(join(tmpdir(), "alook-token-local-rollover-"));+ roots.push(root);+ let now = new Date("2026-08-29T15:59:59Z");+ const store = new DailyTokenUsageStore(root, () => now, "Asia/Shanghai");+ await store.record("bot", delta(10, 2, 3));+ now = new Date("2026-08-29T16:00:01Z");+ await store.record("bot", delta(5, 1, 4));++ expect(await store.snapshots("bot")).toEqual([+ { botId: "bot", day: "2026-08-29", metrics: { input: 10, output: 2, cache: 3 } },+ { botId: "bot", day: "2026-08-30", metrics: { input: 5, output: 1, cache: 4 } },+ ]);+ expect(await store.usageWindow("bot")).toEqual({+ usageDay: "2026-08-30",+ usageTimeZone: "Asia/Shanghai",+ snapshots: [+ { botId: "bot", day: "2026-08-29", metrics: { input: 10, output: 2, cache: 3 } },+ { botId: "bot", day: "2026-08-30", metrics: { input: 5, output: 1, cache: 4 } },+ ],+ });+ });++ it("reports the local day even when that day has no completed usage", async () => {+ const root = mkdtempSync(join(tmpdir(), "alook-token-empty-local-day-"));+ roots.push(root);+ let now = new Date("2026-08-29T12:00:00Z");+ const store = new DailyTokenUsageStore(root, () => now, "Asia/Shanghai");+ await store.record("bot", delta(7, 3, 2));+ now = new Date("2026-08-29T16:00:01Z");++ expect(await store.usageWindow("bot")).toEqual({+ usageDay: "2026-08-30",+ usageTimeZone: "Asia/Shanghai",+ snapshots: [+ { botId: "bot", day: "2026-08-29", metrics: { input: 7, output: 3, cache: 2 } },+ ],+ });+ });++ it("follows a live computer-timezone change without deleting the prior day's totals", async () => {+ const root = mkdtempSync(join(tmpdir(), "alook-token-timezone-change-"));+ roots.push(root);+ let now = new Date("2026-08-22T16:00:01Z");+ let timeZone = "Asia/Shanghai";+ const store = new DailyTokenUsageStore(root, () => now, () => timeZone);+ for (let day = 23; day <= 30; day += 1) {+ now = new Date(`2026-08-${String(day - 1).padStart(2, "0")}T16:00:01Z`);+ await store.record("bot", delta(day, 2, 3));+ }++ now = new Date("2026-08-29T16:00:01Z");+ timeZone = "America/Los_Angeles";+ await store.record("bot", delta(5, 1, 4));++ const window = await store.usageWindow("bot");+ expect(window.usageDay).toBe("2026-08-29");+ expect(window.usageTimeZone).toBe("America/Los_Angeles");+ expect(window.snapshots.map((snapshot) => snapshot.day)).toEqual([+ "2026-08-23",+ "2026-08-24",+ "2026-08-25",+ "2026-08-26",+ "2026-08-27",+ "2026-08-28",+ "2026-08-29",+ ]);+ expect(window.snapshots.at(-1)?.metrics).toEqual({ input: 34, output: 3, cache: 7 });+ const persisted = JSON.parse(readFileSync(+ join(root, ".telemetry", "daily-token-usage.json"),+ "utf8",+ )) as { bots: Record<string, Array<{ day: string }>> };+ expect(persisted.bots.bot?.map((snapshot) => snapshot.day)).toContain("2026-08-30");+ });++ it("retains two recovery days across an exact UTC+14 to UTC-12 switch", async () => {+ const root = mkdtempSync(join(tmpdir(), "alook-token-extreme-timezone-change-"));+ roots.push(root);+ let now = new Date("2026-08-21T10:30:00Z");+ let timeZone = "Pacific/Kiritimati";+ const store = new DailyTokenUsageStore(root, () => now, () => timeZone);+ for (let localDay = 22; localDay <= 30; localDay += 1) {+ now = new Date(`2026-08-${String(localDay - 1).padStart(2, "0")}T10:30:00Z`);+ await store.record("bot", delta(localDay, 2, 3));+ }++ now = new Date("2026-08-29T10:30:00Z");+ timeZone = "Etc/GMT+12";++ const window = await store.usageWindow("bot");+ expect(window.usageDay).toBe("2026-08-28");+ expect(window.usageTimeZone).toBe("Etc/GMT+12");+ expect(window.snapshots.map((snapshot) => snapshot.day)).toEqual([+ "2026-08-22",+ "2026-08-23",+ "2026-08-24",+ "2026-08-25",+ "2026-08-26",+ "2026-08-27",+ "2026-08-28",+ ]);+ const persisted = JSON.parse(readFileSync(+ join(root, ".telemetry", "daily-token-usage.json"),+ "utf8",+ )) as { bots: Record<string, Array<{ day: string }>> };+ expect(persisted.bots.bot?.map((snapshot) => snapshot.day)).toEqual([+ "2026-08-22",+ "2026-08-23",+ "2026-08-24",+ "2026-08-25",+ "2026-08-26",+ "2026-08-27",+ "2026-08-28",+ "2026-08-29",+ "2026-08-30",+ ]);+ });});diff --git a/src/daemon/src/telemetry/dailyTokenUsage.ts b/src/daemon/src/telemetry/dailyTokenUsage.tsindex 40f02ca8f..a71bb6743 100644--- a/src/daemon/src/telemetry/dailyTokenUsage.ts+++ b/src/daemon/src/telemetry/dailyTokenUsage.ts@@ -2,6 +2,7 @@ import { chmod, mkdir, open, readFile, rename, rm } from "node:fs/promises";import { dirname, join } from "node:path";import { randomUUID } from "node:crypto";import type { TokenUsageDelta } from "@alook/agent-driver";+import { calendarDayKeyDaysAgo, dayKeyInTimeZone } from "@alook/shared";export type DailyUsageMetric = number | null;@@ -20,16 +21,13 @@ type UsageFile = {bots: Record<string, DailyUsageSnapshot[]>;};-function dayKey(at: Date): string {- return at.toISOString().slice(0, 10);+function oldestRetainedDay(at: Date, timeZone: string): string {+ const today = dayKeyInTimeZone(at, timeZone);+ return calendarDayKeyDaysAgo(today, 8);}-function retainedDays(at: Date): Set<string> {- const days = new Set<string>();- for (let offset = 0; offset < 7; offset += 1) {- days.add(dayKey(new Date(at.getTime() - offset * 86_400_000)));- }- return days;+function oldestVisibleDay(today: string): string {+ return calendarDayKeyDaysAgo(today, 6);}function isMetric(value: unknown): value is DailyUsageMetric {@@ -84,17 +82,31 @@ export class DailyTokenUsageStore {private loaded = false;private data: UsageFile = { version: 1, bots: {} };private readonly filePath: string;-- constructor(workingDirectoryBase: string, private readonly now: () => Date = () => new Date()) {+ private readonly resolveTimeZone: () => string;++ constructor(+ workingDirectoryBase: string,+ private readonly now: () => Date = () => new Date(),+ timeZone: string | (() => string) = () => Intl.DateTimeFormat().resolvedOptions().timeZone,+ ) {+ this.resolveTimeZone = typeof timeZone === "string" ? () => timeZone : timeZone;+ void this.timeZone;this.filePath = join(workingDirectoryBase, ".telemetry", "daily-token-usage.json");}+ get timeZone(): string {+ const timeZone = this.resolveTimeZone();+ dayKeyInTimeZone(0, timeZone);+ return timeZone;+ }+record(botId: string, delta: TokenUsageDelta): Promise<void> {return this.enqueue(async () => {await this.load();const at = this.now();- this.prune(at);- const day = dayKey(at);+ const timeZone = this.timeZone;+ this.prune(at, timeZone);+ const day = dayKeyInTimeZone(at, timeZone);const snapshots = this.data.bots[botId] ?? [];const existing = snapshots.find((snapshot) => snapshot.day === day);const next = existing ?? emptySnapshot(botId, day);@@ -111,12 +123,33 @@ export class DailyTokenUsageStore {}snapshots(botId: string): Promise<DailyUsageSnapshot[]> {+ return this.usageWindow(botId).then((window) => window.snapshots);+ }++ usageWindow(botId: string): Promise<{+ usageDay: string;+ usageTimeZone: string;+ snapshots: DailyUsageSnapshot[];+ }> {let result: DailyUsageSnapshot[] = [];+ let usageDay = "";+ let usageTimeZone = "";return this.enqueue(async () => {await this.load();- if (this.prune(this.now())) await this.persist();- result = (this.data.bots[botId] ?? []).map((snapshot) => structuredClone(snapshot));- }).then(() => result);+ const at = this.now();+ const timeZone = this.timeZone;+ usageTimeZone = timeZone;+ usageDay = dayKeyInTimeZone(at, timeZone);+ if (this.prune(at, timeZone)) await this.persist();+ const oldestDay = oldestVisibleDay(usageDay);+ result = (this.data.bots[botId] ?? [])+ .filter((snapshot) => snapshot.day >= oldestDay && snapshot.day <= usageDay)+ .map((snapshot) => structuredClone(snapshot));+ }).then(() => ({+ usageDay,+ usageTimeZone,+ snapshots: result,+ }));}private enqueue<T>(operation: () => Promise<T>): Promise<T> {@@ -169,14 +202,13 @@ export class DailyTokenUsageStore {this.loaded = true;}- private prune(at: Date): boolean {- const keep = retainedDays(at);+ private prune(at: Date, timeZone: string): boolean {+ const oldestDay = oldestRetainedDay(at, timeZone);let changed = false;for (const [botId, snapshots] of Object.entries(this.data.bots)) {const retained = snapshots- .filter((snapshot) => keep.has(snapshot.day))- .sort((a, b) => a.day.localeCompare(b.day))- .slice(-7);+ .filter((snapshot) => snapshot.day >= oldestDay)+ .sort((a, b) => a.day.localeCompare(b.day));if (retained.length !== snapshots.length|| retained.some((snapshot, index) => snapshot !== snapshots[index])diff --git a/src/daemon/vitest.config.ts b/src/daemon/vitest.config.tsindex 62ffdff3c..54c809a08 100644--- a/src/daemon/vitest.config.ts+++ b/src/daemon/vitest.config.ts@@ -2,11 +2,16 @@ import { defineConfig } from "vitest/config";export default defineConfig({test: {+ name: "daemon-node",// Unit tests live next to sources as *.test.ts. Real-infra integration// tests live in ../../tests/integration/daemon/ and run separately via// `pnpm test:integration` (not part of this config's include).include: ["src/**/*.test.ts"],environment: "node",testTimeout: 10_000,+ // Process-authority fixtures send real signals. Keep daemon files serial+ // and out of the root workspace's concurrent project group.+ maxWorkers: 1,+ sequence: { groupOrder: 2 },},});diff --git a/src/shared/src/community-cli-contract.ts b/src/shared/src/community-cli-contract.tsindex 09f8152b1..2e3b03804 100644--- a/src/shared/src/community-cli-contract.ts+++ b/src/shared/src/community-cli-contract.ts@@ -865,6 +865,7 @@ export interface HostReady {arch?: string;osRelease?: string;daemonVersion?: string;+ timeZone?: string;providerQuotas?: ProviderQuotaSnapshot[];}@@ -878,6 +879,8 @@ export type AgentActivityState = "idle" | "starting" | "running" | "stopping";export interface HostAgentActivity {agentId: AgentId;state: AgentActivityState;+ usageTimeZone?: string;+ usageDay?: string;dailyUsage?: DailyUsageSnapshot[];quota?: ProviderQuotaSnapshot;}diff --git a/src/shared/src/db/community-machine-schema.ts b/src/shared/src/db/community-machine-schema.tsindex d3f54adb7..42dd8bb85 100644--- a/src/shared/src/db/community-machine-schema.ts+++ b/src/shared/src/db/community-machine-schema.ts@@ -187,6 +187,7 @@ export const communityMachine = sqliteTable(arch: text("arch").notNull().default(""),osRelease: text("os_release").notNull().default(""),daemonVersion: text("daemon_version").notNull().default(""),+ timeZone: text("time_zone"),metadata: text("metadata"),availableRuntimes: text("available_runtimes", { mode: "json" }).$type<CommunityMachineRuntime[]>()diff --git a/src/shared/src/db/queries/community/bot.ts b/src/shared/src/db/queries/community/bot.tsindex f3b8a8a71..ab6f4e9c2 100644--- a/src/shared/src/db/queries/community/bot.ts+++ b/src/shared/src/db/queries/community/bot.ts@@ -96,6 +96,7 @@ export async function listBotsForOwner(modelName: string | null;reasoningEffort: ReasoningEffort | null;runtimeConfigRevision: number;+ tokenUsageTimeZone: string | null;}>> {const rows = await db.select({@@ -114,9 +115,11 @@ export async function listBotsForOwner(modelName: communityBotBinding.modelName,reasoningEffort: communityBotBinding.reasoningEffort,runtimeConfigRevision: communityBotBinding.runtimeConfigRevision,+ tokenUsageTimeZone: communityMachine.timeZone,}).from(user).innerJoin(communityBotBinding, eq(communityBotBinding.userId, user.id))+ .innerJoin(communityMachine, eq(communityMachine.id, communityBotBinding.machineId)).where(and(eq(user.isBot, true),@@ -140,6 +143,7 @@ export async function listBotsForOwner(modelName: r.modelName ?? null,reasoningEffort: r.reasoningEffort ?? null,runtimeConfigRevision: r.runtimeConfigRevision ?? 0,+ tokenUsageTimeZone: r.tokenUsageTimeZone ?? null,}));}diff --git a/src/shared/src/db/queries/community/machine-session-epoch.ts b/src/shared/src/db/queries/community/machine-session-epoch.tsindex cc4fb6242..c90001b4c 100644--- a/src/shared/src/db/queries/community/machine-session-epoch.ts+++ b/src/shared/src/db/queries/community/machine-session-epoch.ts@@ -103,6 +103,7 @@ async function transitionLiveLease(arch: command.metadata.arch ?? prior.arch,osRelease: command.metadata.osRelease ?? prior.osRelease,daemonVersion: command.metadata.daemonVersion ?? prior.daemonVersion,+ timeZone: command.metadata.timeZone ?? prior.timeZone,metadata: command.metadata.metadata !== undefined? command.metadata.metadata: prior.metadata,@@ -294,6 +295,7 @@ async function rotateMachineSessionEpoch(arch: command.metadata.arch ?? prior.arch,osRelease: command.metadata.osRelease ?? prior.osRelease,daemonVersion: command.metadata.daemonVersion ?? prior.daemonVersion,+ timeZone: command.metadata.timeZone ?? prior.timeZone,metadata: command.metadata.metadata !== undefined ? command.metadata.metadata : prior.metadata,availableRuntimes: command.metadata.availableRuntimes !== undefined? command.metadata.availableRuntimes@@ -387,6 +389,7 @@ async function insertOfflineMachine(arch: metadata.arch ?? "",osRelease: metadata.osRelease ?? "",daemonVersion: metadata.daemonVersion ?? "",+ timeZone: metadata.timeZone ?? null,metadata: metadata.metadata ?? null,availableRuntimes: metadata.availableRuntimes ?? [],status: "offline",diff --git a/src/shared/src/db/queries/community/machine.ts b/src/shared/src/db/queries/community/machine.tsindex ba357b546..03f5915fa 100644--- a/src/shared/src/db/queries/community/machine.ts+++ b/src/shared/src/db/queries/community/machine.ts@@ -218,6 +218,7 @@ export interface MachineMetadataInput {arch?: string;osRelease?: string;daemonVersion?: string;+ timeZone?: string;metadata?: string | null;/** Agent CLIs detected on the host. Pass `undefined` to leave unchanged. */availableRuntimes?: CommunityMachineRuntime[];@@ -232,6 +233,7 @@ export interface MachineRow {arch: string;osRelease: string;daemonVersion: string;+ timeZone: string | null;metadata: string | null;availableRuntimes: CommunityMachineRuntime[];/** Source of truth for machine presence — written by WsDurableObject. */diff --git a/src/shared/src/index.ts b/src/shared/src/index.tsindex 90726c172..8368aa787 100644--- a/src/shared/src/index.ts+++ b/src/shared/src/index.ts@@ -720,7 +720,12 @@ export type { PromptAgent, PromptMention, ParseResult } from "./utils/prompt-parexport { MENTION_TOKEN_RE, stripMentionTokens } from "./utils/mention-token";export { isValidToken, isValidEmail } from "./utils/validation";export { escapeLikePattern } from "./utils/sql-like";-export { utcDayKey, utcDayKeyDaysAgo } from "./utils/day-key";+export {+ calendarDayKeyDaysAgo,+ dayKeyInTimeZone,+ utcDayKey,+ utcDayKeyDaysAgo,+} from "./utils/day-key";export { isOnline, formatStatus, isPresenceOnline, isPresenceOffline } from "./utils/status";export { isUniqueConstraintError } from "./utils/db-errors";export { generateWorkspaceSlug, sanitizeSlug, slugSuffix } from "./utils/slug";diff --git a/src/shared/src/schemas.ts b/src/shared/src/schemas.tsindex dfecc5057..b81c0b252 100644--- a/src/shared/src/schemas.ts+++ b/src/shared/src/schemas.ts@@ -987,6 +987,7 @@ export const HostReadyMessageSchema = z.object({arch: z.string().optional(),osRelease: z.string().optional(),daemonVersion: z.string().optional(),+ timeZone: z.string().min(1).max(128).optional(),providerQuotas: z.array(ProviderQuotaSnapshotSchema).max(2).optional().default([]),});export type HostReadyMessage = z.infer<typeof HostReadyMessageSchema>;@@ -1028,6 +1029,8 @@ export const AgentActivityMessageSchema = z.object({type: z.literal("agent_activity"),agentId: z.string(),state: z.enum(["idle", "starting", "running", "stopping"]),+ usageTimeZone: z.string().min(1).max(128).optional(),+ usageDay: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional(),dailyUsage: z.array(DailyUsageSnapshotSchema).max(7).optional(),quota: ProviderQuotaSnapshotSchema.optional(),});diff --git a/src/shared/src/utils/day-key.test.ts b/src/shared/src/utils/day-key.test.tsnew file mode 100644index 000000000..fe2d3e33d--- /dev/null+++ b/src/shared/src/utils/day-key.test.ts@@ -0,0 +1,46 @@+import { describe, expect, it } from "vitest"+import {+ calendarDayKeyDaysAgo,+ dayKeyInTimeZone,+ utcDayKey,+ utcDayKeyDaysAgo,+} from "./day-key"++describe("day keys", () => {+ it("keeps existing UTC helpers stable", () => {+ expect(utcDayKey("2026-08-29T23:00:00-07:00")).toBe("2026-08-30")+ expect(utcDayKeyDaysAgo("2026-03-01T00:00:00Z", 1)).toBe("2026-02-28")+ })++ it("subtracts literal calendar days across month and leap-year boundaries", () => {+ expect(calendarDayKeyDaysAgo("2026-03-01", 1)).toBe("2026-02-28")+ expect(calendarDayKeyDaysAgo("2024-03-01", 1)).toBe("2024-02-29")+ expect(calendarDayKeyDaysAgo("2026-12-31", -1)).toBe("2027-01-01")+ expect(() => calendarDayKeyDaysAgo("2026-02-30", 1)).toThrow("invalid calendar day key")+ })++ it("formats the same instant in the computer timezone instead of UTC", () => {+ const instant = "2026-08-29T16:00:01Z"+ expect(dayKeyInTimeZone(instant, "Asia/Shanghai")).toBe("2026-08-30")+ expect(dayKeyInTimeZone(instant, "America/Los_Angeles")).toBe("2026-08-29")+ })++ it("keeps seven literal calendar days stable across DST transitions", () => {+ expect(Array.from(+ { length: 7 },+ (_, offset) => calendarDayKeyDaysAgo("2026-03-10", 6 - offset),+ )).toEqual([+ "2026-03-04",+ "2026-03-05",+ "2026-03-06",+ "2026-03-07",+ "2026-03-08",+ "2026-03-09",+ "2026-03-10",+ ])+ expect(dayKeyInTimeZone("2026-03-08T09:59:59Z", "America/Los_Angeles")).toBe("2026-03-08")+ expect(dayKeyInTimeZone("2026-03-08T10:00:01Z", "America/Los_Angeles")).toBe("2026-03-08")+ expect(dayKeyInTimeZone("2026-11-01T08:59:59Z", "America/Los_Angeles")).toBe("2026-11-01")+ expect(dayKeyInTimeZone("2026-11-01T09:00:01Z", "America/Los_Angeles")).toBe("2026-11-01")+ })+})diff --git a/src/shared/src/utils/day-key.ts b/src/shared/src/utils/day-key.tsindex 066d680d3..3ad3ec5e4 100644--- a/src/shared/src/utils/day-key.ts+++ b/src/shared/src/utils/day-key.ts@@ -24,3 +24,37 @@ export function utcDayKeyDaysAgo(now: Date | string | number, days: number): strd.setUTCDate(d.getUTCDate() - days)return utcDayKey(d)}++export function calendarDayKeyDaysAgo(day: string, days: number): string {+ const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(day)+ if (!match) throw new RangeError("invalid calendar day key")+ const year = Number(match[1])+ const month = Number(match[2])+ const date = Number(match[3])+ const parsed = new Date(Date.UTC(year, month - 1, date))+ if (+ parsed.getUTCFullYear() !== year+ || parsed.getUTCMonth() !== month - 1+ || parsed.getUTCDate() !== date+ ) {+ throw new RangeError("invalid calendar day key")+ }+ parsed.setUTCDate(parsed.getUTCDate() - days)+ return utcDayKey(parsed)+}++export function dayKeyInTimeZone(now: Date | string | number, timeZone: string): string {+ const date = now instanceof Date ? now : new Date(now)+ const parts = new Intl.DateTimeFormat("en-US", {+ timeZone,+ year: "numeric",+ month: "2-digit",+ day: "2-digit",+ }).formatToParts(date)+ const values = new Map(parts.map((part) => [part.type, part.value]))+ const year = values.get("year")+ const month = values.get("month")+ const day = values.get("day")+ if (!year || !month || !day) throw new RangeError("unable to format calendar day key")+ return `${year}-${month}-${day}`+}diff --git a/src/shared/test/queries/community-bot.test.ts b/src/shared/test/queries/community-bot.test.tsindex d03d6fbaf..8c976fdb0 100644--- a/src/shared/test/queries/community-bot.test.ts+++ b/src/shared/test/queries/community-bot.test.ts@@ -172,6 +172,7 @@ describe("bot runtime-config read projections", () => {name: "helper",discriminator: "1234",image: null,+ avatarVersion: null,ownerUserId: "owner_1",description: "does things",createdAt: "2026-08-29T00:00:00.000Z",@@ -205,7 +206,7 @@ describe("bot runtime-config read projections", () => {it("returns reasoning effort and revision when listing an owner's bots", async () => {await expect(q.listBotsForOwner(makeOwnerListChain([storedBot]), "owner_1")).resolves.toEqual([- storedBot,+ { ...storedBot, tokenUsageTimeZone: null },])})diff --git a/src/shared/test/queries/machine-session-epoch.integration.test.ts b/src/shared/test/queries/machine-session-epoch.integration.test.tsindex 7b56ff49e..40888c3f4 100644--- a/src/shared/test/queries/machine-session-epoch.integration.test.ts+++ b/src/shared/test/queries/machine-session-epoch.integration.test.ts@@ -32,6 +32,7 @@ describe("machine session epoch SQL transaction", () => {arch TEXT NOT NULL DEFAULT '',os_release TEXT NOT NULL DEFAULT '',daemon_version TEXT NOT NULL DEFAULT '',+ time_zone TEXT,metadata TEXT,available_runtimes TEXT NOT NULL DEFAULT '[]',status TEXT NOT NULL DEFAULT 'offline',diff --git a/src/shared/test/schemas/community-runtime.test.ts b/src/shared/test/schemas/community-runtime.test.tsindex cb9e74174..2ba6c6263 100644--- a/src/shared/test/schemas/community-runtime.test.ts+++ b/src/shared/test/schemas/community-runtime.test.ts@@ -2,6 +2,7 @@ import { describe, it, expect } from "vitest";import {CommunityMachineRuntimeSchema,CommunityMachineRuntimeListSchema,+ CommunityDaemonReadySchema,HostReadyMessageSchema,MachineHeartbeatAckMessageSchema,DiagnosticCommandAckMessageSchema,@@ -317,6 +318,18 @@ describe("HostReadyMessageSchema", () => {});});+describe("CommunityDaemonReadySchema", () => {+ it("does not expose the WS-only machine timezone on the activation helper contract", () => {+ expect(CommunityDaemonReadySchema.parse({+ runtimeReport: [{ id: "codex" }],+ timeZone: "Asia/Shanghai",+ })).toEqual({+ runtimeReport: [{ id: "codex", status: "healthy" }],+ runningAgents: [],+ });+ });+});+describe("control-plane receipt schemas", () => {it("strictly parses heartbeat and diagnostic ingress receipts", () => {expect(MachineHeartbeatAckMessageSchema.parse({diff --git a/src/web/migrations/0094_community_machine_timezone.sql b/src/web/migrations/0094_community_machine_timezone.sqlnew file mode 100644index 000000000..a3bcdd46d--- /dev/null+++ b/src/web/migrations/0094_community_machine_timezone.sql@@ -0,0 +1,6 @@+ALTER TABLE community_machine+ADD COLUMN time_zone TEXT+CHECK (+ time_zone IS NULL+ OR length(time_zone) BETWEEN 1 AND 128+);diff --git a/src/web/src/app/api/community/bots/route.test.ts b/src/web/src/app/api/community/bots/route.test.tsindex ee0fba7ba..e0620fda9 100644--- a/src/web/src/app/api/community/bots/route.test.ts+++ b/src/web/src/app/api/community/bots/route.test.ts@@ -61,7 +61,7 @@ vi.mock("@/lib/middleware/helpers", async () => {}})-import { GET, POST } from "./route"+import { GET, POST, tokenUsageDayWindow } from "./route"function getReq() {return new NextRequest("http://localhost/api/community/bots", { method: "GET" })@@ -260,11 +260,12 @@ describe("GET /api/community/bots — heatmap activity", () => {{ id: "bot_cursor", runtime: "cursor" },{ id: "bot_opencode", runtime: "opencode" },{ id: "bot_pi", runtime: "pi" },+ { id: "bot_unknown", runtime: "custom" },])mockGetBotDailyActivityForOwner.mockResolvedValue(new Map())mockGetBotDailyTokenUsageForOwner.mockResolvedValue(new Map([- ["bot_codex", [{- botId: "bot_codex",+ ["bot_pi", [{+ botId: "bot_pi",day: today,metrics: {input: 8,@@ -281,7 +282,7 @@ describe("GET /api/community/bots — heatmap activity", () => {usage: { capability: string; days: Array<{ day: string; period: string; metrics: unknown }> }}>}- const supported = body.bots.find((bot) => bot.id === "bot_codex")!+ const supported = body.bots.find((bot) => bot.id === "bot_pi")!expect(supported.usage.capability).toBe("supported")expect(supported.usage.days).toHaveLength(7)expect(supported.usage.days.at(-1)).toEqual({@@ -299,7 +300,8 @@ describe("GET /api/community/bots — heatmap activity", () => {bot_codex: "supported",bot_cursor: "unsupported",bot_opencode: "supported",- bot_pi: "unsupported",+ bot_pi: "supported",+ bot_unknown: "unknown",})expect(mockGetBotDailyTokenUsageForOwner).toHaveBeenCalledWith(expect.anything(),@@ -307,4 +309,42 @@ describe("GET /api/community/bots — heatmap activity", () => {expect.stringMatching(/^\d{4}-\d{2}-\d{2}$/),)})++ it("uses the daemon computer timezone for the seven-day token window", () => {+ const now = new Date("2026-08-29T16:00:01Z")+ expect(tokenUsageDayWindow(now, "Asia/Shanghai")).toEqual([+ "2026-08-24",+ "2026-08-25",+ "2026-08-26",+ "2026-08-27",+ "2026-08-28",+ "2026-08-29",+ "2026-08-30",+ ])+ expect(tokenUsageDayWindow(now, "America/Los_Angeles").at(-1)).toBe("2026-08-29")+ expect(tokenUsageDayWindow(now, "not/a-time-zone").at(-1)).toBe("2026-08-29")+ })++ it("projects the GET response from the joined machine timezone without exposing it", async () => {+ vi.useFakeTimers()+ vi.setSystemTime(new Date("2026-08-29T16:00:01Z"))+ try {+ mockListBotsForOwner.mockResolvedValue([{+ id: "bot_1",+ runtime: "codex",+ tokenUsageTimeZone: "Asia/Shanghai",+ }])+ mockGetBotDailyActivityForOwner.mockResolvedValue(new Map())+ mockGetBotDailyTokenUsageForOwner.mockResolvedValue(new Map())++ const res = await GET(getReq(), ctx)+ const body = await res.json() as {+ bots: Array<Record<string, unknown> & { usage: { days: Array<{ day: string }> } }>+ }+ expect(body.bots[0]?.usage.days.at(-1)?.day).toBe("2026-08-30")+ expect(body.bots[0]).not.toHaveProperty("tokenUsageTimeZone")+ } finally {+ vi.useRealTimers()+ }+ })})diff --git a/src/web/src/app/api/community/bots/route.ts b/src/web/src/app/api/community/bots/route.tsindex 4c926dc44..725f7955b 100644--- a/src/web/src/app/api/community/bots/route.ts+++ b/src/web/src/app/api/community/bots/route.ts@@ -3,6 +3,9 @@ import {queries,CommunityBotCreateRequestSchema,COMMUNITY_BOT_LIMIT_PER_OWNER,+ calendarDayKeyDaysAgo,+ dayKeyInTimeZone,+ utcDayKey,utcDayKeyDaysAgo,resolveReasoningEffort,} from "@alook/shared"@@ -12,6 +15,19 @@ import { writeJSON, writeError, parseBody } from "@/lib/middleware/helpers"import { pushBotEventToMachine } from "@/lib/community/bot-push"import { canonicalUserImage } from "@/lib/community/storage"+export function tokenUsageDayWindow(now: Date, timeZone: string | null | undefined): string[] {+ let today = utcDayKey(now)+ if (timeZone) {+ try {+ today = dayKeyInTimeZone(now, timeZone)+ } catch { }+ }+ return Array.from(+ { length: 7 },+ (_, index) => calendarDayKeyDaysAgo(today, 6 - index),+ )+}+export const GET = withAuth(async (_req, ctx) => {const db = getDb(ctx.env.DB)const bots = await queries.communityBot.listBotsForOwner(db, ctx.userId)@@ -25,40 +41,41 @@ export const GET = withAuth(async (_req, ctx) => {ctx.userId,sinceDay,)- const usageSinceDay = utcDayKeyDaysAgo(new Date(), 6)+ const now = new Date()+ const usageSinceDay = utcDayKeyDaysAgo(now, 7)const usageByBot = await queries.communityBot.getBotDailyTokenUsageForOwner(db,ctx.userId,usageSinceDay,)- const now = new Date()- const usageDays = Array.from({ length: 7 }, (_, index) =>- utcDayKeyDaysAgo(now, 6 - index)- )- const withActivity = bots.map((bot) => ({- ...bot,- image: canonicalUserImage(bot.id, bot.image, bot.avatarVersion),- dailyActivity: activityByBot.get(bot.id) ?? [],- usage: {- capability: (["claude", "codex", "opencode"] as string[]).includes(bot.runtime)- ? "supported" as const- : bot.runtime === "cursor" || bot.runtime === "pi"- ? "unsupported" as const- : "unknown" as const,- days: usageDays.map((day, index) => {- const stored = usageByBot.get(bot.id)?.find((snapshot) => snapshot.day === day)- return {- day,- period: index === usageDays.length - 1 ? "in_progress" as const : "closed" as const,- metrics: stored?.metrics ?? {- input: null,- output: null,- cache: null,- },- }- }),- },- }))+ const withActivity = bots.map((bot) => {+ const { tokenUsageTimeZone, ...publicBot } = bot+ const usageDays = tokenUsageDayWindow(now, tokenUsageTimeZone)+ return {+ ...publicBot,+ image: canonicalUserImage(bot.id, bot.image, bot.avatarVersion),+ dailyActivity: activityByBot.get(bot.id) ?? [],+ usage: {+ capability: (["claude", "codex", "opencode", "pi"] as string[]).includes(bot.runtime)+ ? "supported" as const+ : bot.runtime === "cursor"+ ? "unsupported" as const+ : "unknown" as const,+ days: usageDays.map((day, index) => {+ const stored = usageByBot.get(bot.id)?.find((snapshot) => snapshot.day === day)+ return {+ day,+ period: index === usageDays.length - 1 ? "in_progress" as const : "closed" as const,+ metrics: stored?.metrics ?? {+ input: null,+ output: null,+ cache: null,+ },+ }+ }),+ },+ }+ })return writeJSON({ bots: withActivity })})diff --git a/src/web/src/test/e2e-ui/35-bot-token-usage-quota.spec.ts b/src/web/src/test/e2e-ui/35-bot-token-usage-quota.spec.tsindex 3879279d5..31c56c348 100644--- a/src/web/src/test/e2e-ui/35-bot-token-usage-quota.spec.ts+++ b/src/web/src/test/e2e-ui/35-bot-token-usage-quota.spec.ts@@ -1,7 +1,49 @@+import { randomUUID } from "node:crypto"+import { spawnSync } from "node:child_process"+import { writeFileSync } from "node:fs"import type { Page, TestInfo } from "@playwright/test"-import { test, expect } from "./_fixtures/community-fixture"+import { calendarDayKeyDaysAgo, dayKeyInTimeZone } from "@alook/shared"+import { test, expect, sessionCookie, userId } from "./_fixtures/community-fixture"import { gotoAfterUserWsAuth } from "./_fixtures/actions"import { tid } from "./_fixtures/testids"+import { REPO_ROOT, WEB_URL } from "./_setup/paths"++type D1Result<Row = Record<string, unknown>> = {+ results: Row[]+ success: boolean+}++function sqlLiteral(value: string): string {+ return `'${value.replaceAll("'", "''")}'`+}++function executeLocalD1<Row = Record<string, unknown>>(sql: string): D1Result<Row>[] {+ const result = spawnSync(+ "pnpm",+ ["exec", "wrangler", "d1", "execute", "alook-app", "--local", "--json", "--command", sql],+ {+ cwd: `${REPO_ROOT}/src/web`,+ encoding: "utf8",+ maxBuffer: 4 * 1024 * 1024,+ },+ )+ if (result.status !== 0) {+ throw new Error(`local D1 command failed (${result.status}): ${result.stderr}`)+ }+ return JSON.parse(result.stdout) as D1Result<Row>[]+}++async function postAsAlice(path: string, body?: unknown): Promise<Response> {+ return fetch(`${WEB_URL}${path}`, {+ method: "POST",+ headers: {+ Cookie: sessionCookie("alice"),+ "Content-Type": "application/json",+ Origin: WEB_URL,+ },+ body: body === undefined ? undefined : JSON.stringify(body),+ })+}const days = [{ day: "2026-08-23", period: "closed", metrics: { input: 1200, output: 400, cache: 2000 } },@@ -133,7 +175,7 @@ const bots = [modelName: null,lastRefreshContextAt: null,dailyActivity: [],- usage: { capability: "unsupported", days: [] },+ usage: { capability: "supported", days: smallerDays },},{id: "bot_claude",@@ -202,7 +244,7 @@ test("My Bots renders seven-day usage and replace-all quota across responsive thexpect(Math.abs(usageBox!.y + usageBox!.height - (botMetaBox!.y + botMetaBox!.height),)).toBeLessThanOrEqual(3)- await expect(page.getByTestId(tid.botUsage("bot_pi"))).toHaveCount(0)+ await expect(page.getByTestId(tid.botUsage("bot_pi")).getByRole("listitem")).toHaveCount(7)await expect(page.getByText("Token usage not supported")).toHaveCount(0)const claudeUsage = page.getByTestId(tid.botUsage("bot_claude"))await expect(claudeUsage.getByRole("listitem")).toHaveCount(7)@@ -326,3 +368,156 @@ test("My Bots renders seven-day usage and replace-all quota across responsive thawait desktopBoundaryDay.hover()await expect(page.locator('[data-slot="tooltip-content"]:visible')).toContainText("Input700")})++test("My Bots renders Pi usage through real D1 and the unmocked bots API", async ({ asUser }, testInfo) => {+ const ownerId = userId("alice")+ let machineId: string | undefined+ let botId: string | undefined+ try {+ const pairResponse = await postAsAlice("/api/community/machines/pair")+ expect(pairResponse.ok).toBe(true)+ const { tokenId } = await pairResponse.json() as { tokenId: string }++ const activateResponse = await fetch(`${WEB_URL}/api/community/daemon/activate`, {+ method: "POST",+ headers: {+ Authorization: `Bearer ${tokenId}`,+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ hostname: "real-d1-timezone-e2e",+ platform: "linux",+ arch: "x64",+ osRelease: "e2e",+ daemonVersion: "0.1.26",+ runtimeReport: [{ id: "pi", status: "healthy" }],+ }),+ })+ expect(activateResponse.ok).toBe(true)+ machineId = ((await activateResponse.json()) as { machineId: string }).machineId++ const createResponse = await postAsAlice("/api/community/bots", {+ name: `Local Day ${randomUUID().slice(0, 8)}`,+ description: "real Pi D1 usage projection evidence",+ machineId,+ runtime: "pi",+ })+ expect(createResponse.status).toBe(201)+ botId = ((await createResponse.json()) as { bot: { id: string } }).bot.id++ const timeZone = "Asia/Shanghai"+ const today = dayKeyInTimeZone(new Date(), timeZone)+ const expectedDays = Array.from(+ { length: 7 },+ (_, index) => calendarDayKeyDaysAgo(today, 6 - index),+ )+ const updatedAt = new Date().toISOString()+ executeLocalD1([+ `UPDATE community_machine SET time_zone = ${sqlLiteral(timeZone)} WHERE id = ${sqlLiteral(machineId)}`,+ ...expectedDays.map((day, index) => `+ INSERT INTO community_bot_daily_token_usage (+ bot_id, day, input_tokens, output_tokens, cache_tokens, updated_at+ ) VALUES (+ ${sqlLiteral(botId!)}, ${sqlLiteral(day)}, ${100 + index}, ${10 + index}, ${1000 + index}, ${sqlLiteral(updatedAt)}+ )+ `),+ ].join(";"))++ const d1Evidence = executeLocalD1<{+ time_zone: string+ day: string+ input_tokens: number+ output_tokens: number+ cache_tokens: number+ }>(`+ SELECT m.time_zone, u.day, u.input_tokens, u.output_tokens, u.cache_tokens+ FROM community_machine m+ JOIN community_bot_binding b ON b.machine_id = m.id+ JOIN community_bot_daily_token_usage u ON u.bot_id = b.user_id+ WHERE m.id = ${sqlLiteral(machineId)} AND b.user_id = ${sqlLiteral(botId)}+ ORDER BY u.day+ `)[0]!.results+ expect(d1Evidence.map((row) => row.day)).toEqual(expectedDays)+ expect(d1Evidence.every((row) => row.time_zone === timeZone)).toBe(true)+ const d1EvidencePath = testInfo.outputPath("real-pi-d1-token-usage.json")+ writeFileSync(d1EvidencePath, `${JSON.stringify(d1Evidence, null, 2)}\n`)+ await testInfo.attach("real-pi-d1-token-usage.json", { path: d1EvidencePath })++ const apiResponse = await fetch(`${WEB_URL}/api/community/bots`, {+ headers: { Cookie: sessionCookie("alice"), Origin: WEB_URL },+ })+ expect(apiResponse.ok).toBe(true)+ const apiBody = await apiResponse.json() as {+ bots: Array<{+ id: string+ usage: {+ capability: string+ days: Array<{+ day: string+ period: string+ metrics: { input: number | null; output: number | null; cache: number | null }+ }>+ }+ }>+ }+ const apiBot = apiBody.bots.find((bot) => bot.id === botId)+ expect(apiBot).toMatchObject({ id: botId })+ expect(apiBot?.usage.capability).toBe("supported")+ expect(apiBot?.usage.days.map((day) => day.day)).toEqual(expectedDays)+ expect(apiBot?.usage.days.at(-1)).toEqual({+ day: today,+ period: "in_progress",+ metrics: { input: 106, output: 16, cache: 1006 },+ })+ const apiEvidencePath = testInfo.outputPath("real-pi-bots-api-response.json")+ writeFileSync(apiEvidencePath, `${JSON.stringify(apiBot, null, 2)}\n`)+ await testInfo.attach("real-pi-bots-api-response.json", { path: apiEvidencePath })++ const { page } = await asUser("alice", { hasTouch: true })+ await page.setViewportSize({ width: 639, height: 844 })+ const browserApiResponse = page.waitForResponse((response) =>+ response.request().method() === "GET" && new URL(response.url()).pathname === "/api/community/bots",+ )+ await gotoAfterUserWsAuth(page, "/c/me/bots")+ expect((await browserApiResponse).ok()).toBe(true)++ const usage = page.getByTestId(tid.botUsage(botId))+ await expect(usage).toBeVisible()+ await expect(usage.getByRole("listitem")).toHaveCount(7)+ await usage.getByRole("button", { name: "Open token usage details" }).tap()+ const visibleDayTargets = page.locator(+ `[data-testid^="${tid.botUsageDay(botId, "")}"]:visible`,+ )+ await expect(visibleDayTargets).toHaveCount(7)+ const visibleDayTestIds = await visibleDayTargets.evaluateAll((elements) =>+ elements.map((element) => element.getAttribute("data-testid")),+ )+ expect(visibleDayTestIds).toEqual(expectedDays.map((day) => tid.botUsageDay(botId!, day)))+ const todayTarget = page.locator(+ `[data-testid="${tid.botUsageDay(botId, today)}"]:visible`,+ )+ await expect(todayTarget).toHaveText("Today")+ await expect(page.locator('[data-slot="popover-content"]:visible')).toContainText("Input106")+ const browserEvidencePath = testInfo.outputPath("real-pi-browser-observation.json")+ writeFileSync(browserEvidencePath, `${JSON.stringify({+ route: "/c/me/bots",+ botId,+ visibleDayTestIds,+ today,+ todayText: await todayTarget.textContent(),+ }, null, 2)}\n`)+ await testInfo.attach("real-pi-browser-observation.json", { path: browserEvidencePath })+ await attachScreenshot(page, testInfo, "real-pi-d1-local-today")+ } finally {+ if (botId || machineId) {+ executeLocalD1([+ botId ? `DELETE FROM community_bot_daily_token_usage WHERE bot_id = ${sqlLiteral(botId)}` : "",+ botId ? `DELETE FROM community_bot_binding WHERE user_id = ${sqlLiteral(botId)}` : "",+ botId ? `DELETE FROM \"user\" WHERE id = ${sqlLiteral(botId)}` : "",+ machineId ? `DELETE FROM community_machine_credential WHERE machine_id = ${sqlLiteral(machineId)}` : "",+ `DELETE FROM community_machine_token WHERE user_id = ${sqlLiteral(ownerId)}`,+ machineId ? `DELETE FROM community_machine WHERE id = ${sqlLiteral(machineId)}` : "",+ ].filter(Boolean).join(";"))+ }+ }+})diff --git a/src/ws-do/src/ws-durable/machine-frames.test.ts b/src/ws-do/src/ws-durable/machine-frames.test.tsindex 7277037b8..8533f9083 100644--- a/src/ws-do/src/ws-durable/machine-frames.test.ts+++ b/src/ws-do/src/ws-durable/machine-frames.test.ts@@ -175,6 +175,7 @@ describe("WebSocketDurableObject", () => {arch: "arm64",osRelease: "23.0.0",daemonVersion: "0.1.0",+ timeZone: "Asia/Shanghai",})await durable.webSocketMessage(ws as any, frame)@@ -188,6 +189,7 @@ describe("WebSocketDurableObject", () => {arch: "arm64",osRelease: "23.0.0",daemonVersion: "0.1.0",+ timeZone: "Asia/Shanghai",availableRuntimes: [{id: "claude",version: "1.0.0",diff --git a/src/ws-do/src/ws-durable/machine-ready.ts b/src/ws-do/src/ws-durable/machine-ready.tsindex 1d3baaa67..1697bfc76 100644--- a/src/ws-do/src/ws-durable/machine-ready.ts+++ b/src/ws-do/src/ws-durable/machine-ready.ts@@ -3,6 +3,7 @@ import {createDb,HostReadyMessageSchema,ProviderQuotaSnapshotSchema,+ dayKeyInTimeZone,queries,WS_EVENTS,} from "@alook/shared"@@ -114,13 +115,20 @@ export async function handleReadyFrame(const arch = ready.arch ?? ""const daemonVersion = ready.daemonVersion ?? ""const osRelease = ready.osRelease ?? ""+ let timeZone: string | undefined+ if (ready.timeZone) {+ try {+ dayKeyInTimeZone(new Date(), ready.timeZone)+ timeZone = ready.timeZone+ } catch { }+ }const availableRuntimes: CommunityMachineRuntime[] = ready.runtimeReportconst db = createDb(context.env.DB)const result = await queries.communityMachineSession.transitionMachineSessionEpoch(db, {type: "ready",epoch: identity,- metadata: { hostname, platform, arch, daemonVersion, osRelease, availableRuntimes },+ metadata: { hostname, platform, arch, daemonVersion, osRelease, timeZone, availableRuntimes },})if (result.type === "stale_epoch") {context.log.warn("community machine epoch rejected on ready", { machineId: identity.machineId })diff --git a/src/ws-do/src/ws-durable/machine-telemetry.test.ts b/src/ws-do/src/ws-durable/machine-telemetry.test.tsindex 0480d351c..ac9535bf1 100644--- a/src/ws-do/src/ws-durable/machine-telemetry.test.ts+++ b/src/ws-do/src/ws-durable/machine-telemetry.test.ts@@ -1,4 +1,5 @@import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"+import { calendarDayKeyDaysAgo, dayKeyInTimeZone } from "@alook/shared"import { createMockWebSocket } from "../__mocks__/cf"import {CFResponse,@@ -292,13 +293,17 @@ describe("WebSocketDurableObject", () => {const ws = createMockWebSocket()ws.serializeAttachment({ type: "community-machine", machineId: "cm_1", userId: "u_1", authenticated: true })+ const usageTimeZone = "Asia/Shanghai"+ const usageDay = dayKeyInTimeZone(new Date(), usageTimeZone)await durable.webSocketMessage(ws as any, JSON.stringify({type: "agent_activity",agentId: "bot_1",state: "idle",+ usageTimeZone,+ usageDay,dailyUsage: [{botId: "bot_1",- day: new Date().toISOString().slice(0, 10),+ day: usageDay,metrics: {input: 12,output: 7,@@ -328,11 +333,260 @@ describe("WebSocketDurableObject", () => {const statements = mockD1Batch.mock.calls[0]![0] as Array<{ sql: string; values: unknown[] }>expect(statements.map((statement) => statement.sql)).toEqual([expect.stringContaining("community_user_profile"),+ expect.stringContaining("time_zone"),expect.stringContaining("community_bot_daily_token_usage"),expect.stringContaining("DELETE FROM community_bot_daily_token_usage"),expect.stringContaining("community_machine_backend_quota"),])- expect(statements[1]!.values).toMatchObject({ 0: "bot_1", 2: 12, 3: 7, 4: null })+ expect(statements[1]!.values).toMatchObject({ 0: usageTimeZone, 1: "cm_1", 2: "u_1" })+ expect(statements[2]!.values).toMatchObject({ 0: "bot_1", 2: 12, 3: 7, 4: null })+ })++ it("advances the computer-local usage day without creating an empty usage row", async () => {+ const { durable, store } = createDO()+ store.set("community-machine-identity", {+ userId: "u_1",+ machineId: "cm_1",+ credentialHash: "0".repeat(64),+ })+ mockGetBotBinding.mockResolvedValue({ machineId: "cm_1", runtime: "codex" })+ mockGetProfile.mockResolvedValue({ statusEmoji: "💤", statusText: "Idle" })+ const ws = createMockWebSocket()+ ws.serializeAttachment({ type: "community-machine", machineId: "cm_1", userId: "u_1", authenticated: true })+ const usageTimeZone = "Asia/Shanghai"+ const usageDay = dayKeyInTimeZone(new Date(), usageTimeZone)++ await durable.webSocketMessage(ws as any, JSON.stringify({+ type: "agent_activity",+ agentId: "bot_1",+ state: "idle",+ usageTimeZone,+ usageDay,+ }))++ expect(mockD1Batch).toHaveBeenCalledOnce()+ const statements = mockD1Batch.mock.calls[0]![0] as Array<{ sql: string; values: unknown[] }>+ expect(statements.map((statement) => statement.sql)).toEqual([+ expect.stringContaining("time_zone"),+ expect.stringContaining("DELETE FROM community_bot_daily_token_usage"),+ ])+ expect(statements.some((statement) => statement.sql.includes("INSERT INTO community_bot_daily_token_usage"))).toBe(false)+ })++ it.each(["Pacific/Kiritimati", "Etc/GMT+12"])(+ "accepts the legal calendar envelope for edge timezone %s",+ async (usageTimeZone) => {+ const { durable, store } = createDO()+ store.set("community-machine-identity", {+ userId: "u_1",+ machineId: "cm_1",+ credentialHash: "0".repeat(64),+ })+ mockGetBotBinding.mockResolvedValue({ machineId: "cm_1", runtime: "codex" })+ mockGetProfile.mockResolvedValue({ statusEmoji: "💤", statusText: "Idle" })+ const ws = createMockWebSocket()+ ws.serializeAttachment({ type: "community-machine", machineId: "cm_1", userId: "u_1", authenticated: true })+ const usageDay = dayKeyInTimeZone(new Date(), usageTimeZone)++ await durable.webSocketMessage(ws as any, JSON.stringify({+ type: "agent_activity",+ agentId: "bot_1",+ state: "idle",+ usageTimeZone,+ usageDay,+ dailyUsage: [{+ botId: "bot_1",+ day: usageDay,+ metrics: { input: 3, output: 1, cache: 2 },+ }],+ }))++ expect(mockD1Batch).toHaveBeenCalledOnce()+ const statements = mockD1Batch.mock.calls[0]![0] as Array<{ sql: string; values: unknown[] }>+ expect(statements[0]!.values).toMatchObject({ 0: usageTimeZone, 1: "cm_1", 2: "u_1" })+ expect(statements.some((statement) => statement.sql.includes("INSERT INTO community_bot_daily_token_usage"))).toBe(true)+ },+ )++ it("retains the exact UTC+14 to UTC-12 recovery boundary in D1", async () => {+ vi.useFakeTimers()+ vi.setSystemTime(new Date("2026-08-29T10:30:00Z"))+ try {+ const { durable, store } = createDO()+ store.set("community-machine-identity", {+ userId: "u_1",+ machineId: "cm_1",+ credentialHash: "0".repeat(64),+ })+ mockGetBotBinding.mockResolvedValue({ machineId: "cm_1", runtime: "codex" })+ mockGetProfile.mockResolvedValue({ statusEmoji: "💤", statusText: "Idle" })+ const ws = createMockWebSocket()+ ws.serializeAttachment({ type: "community-machine", machineId: "cm_1", userId: "u_1", authenticated: true })++ await durable.webSocketMessage(ws as any, JSON.stringify({+ type: "agent_activity",+ agentId: "bot_1",+ state: "idle",+ usageTimeZone: "Pacific/Kiritimati",+ usageDay: "2026-08-30",+ dailyUsage: [],+ }))++ expect(mockD1Batch).toHaveBeenCalledOnce()+ const statements = mockD1Batch.mock.calls[0]![0] as Array<{ sql: string; values: unknown[] }>+ const prune = statements.find((statement) => statement.sql.includes("DELETE FROM community_bot_daily_token_usage"))+ expect(prune?.values).toMatchObject({+ 0: "bot_1",+ 1: "2026-08-22",+ 2: "bot_1",+ 3: "cm_1",+ })+ } finally {+ vi.useRealTimers()+ }+ })++ it.each([+ ["Pacific/Kiritimati", "2026-08-31"],+ ["Etc/GMT+12", "2026-08-28"],+ ])("rejects impossible server-envelope day %s / %s", async (usageTimeZone, usageDay) => {+ vi.useFakeTimers()+ vi.setSystemTime(new Date("2026-08-29T12:00:00Z"))+ try {+ const { durable, store } = createDO()+ store.set("community-machine-identity", {+ userId: "u_1",+ machineId: "cm_1",+ credentialHash: "0".repeat(64),+ })+ mockGetBotBinding.mockResolvedValue({ machineId: "cm_1", runtime: "codex" })+ mockGetProfile.mockResolvedValue({ statusEmoji: "💤", statusText: "Idle" })+ const ws = createMockWebSocket()+ ws.serializeAttachment({ type: "community-machine", machineId: "cm_1", userId: "u_1", authenticated: true })++ await durable.webSocketMessage(ws as any, JSON.stringify({+ type: "agent_activity",+ agentId: "bot_1",+ state: "idle",+ usageTimeZone,+ usageDay,+ dailyUsage: [{+ botId: "bot_1",+ day: usageDay,+ metrics: { input: 3, output: 1, cache: 2 },+ }],+ }))++ expect(mockD1Batch).not.toHaveBeenCalled()+ } finally {+ vi.useRealTimers()+ }+ })++ it.each([+ ["duplicate days", (day: string) => [+ { botId: "bot_1", day, metrics: { input: 3, output: 1, cache: 2 } },+ { botId: "bot_1", day, metrics: { input: 4, output: 1, cache: 2 } },+ ]],+ ["an out-of-window day", (day: string) => [{+ botId: "bot_1",+ day: calendarDayKeyDaysAgo(day, 7),+ metrics: { input: 3, output: 1, cache: 2 },+ }]],+ ["a different bot id", (day: string) => [{+ botId: "another_bot",+ day,+ metrics: { input: 3, output: 1, cache: 2 },+ }]],+ ["an invalid metric", (day: string) => [{+ botId: "bot_1",+ day,+ metrics: { input: -1, output: 1, cache: 2 },+ }]],+ ])("rejects %s without discarding valid calendar metadata", async (_label, snapshots) => {+ const { durable, store } = createDO()+ store.set("community-machine-identity", {+ userId: "u_1",+ machineId: "cm_1",+ credentialHash: "0".repeat(64),+ })+ mockGetBotBinding.mockResolvedValue({ machineId: "cm_1", runtime: "codex" })+ mockGetProfile.mockResolvedValue({ statusEmoji: "💤", statusText: "Idle" })+ const ws = createMockWebSocket()+ ws.serializeAttachment({ type: "community-machine", machineId: "cm_1", userId: "u_1", authenticated: true })+ const usageTimeZone = "Asia/Shanghai"+ const usageDay = dayKeyInTimeZone(new Date(), usageTimeZone)++ await durable.webSocketMessage(ws as any, JSON.stringify({+ type: "agent_activity",+ agentId: "bot_1",+ state: "idle",+ usageTimeZone,+ usageDay,+ dailyUsage: snapshots(usageDay),+ }))++ expect(mockD1Batch).toHaveBeenCalledOnce()+ const statements = mockD1Batch.mock.calls[0]![0] as Array<{ sql: string }>+ expect(statements.some((statement) => statement.sql.includes("time_zone"))).toBe(true)+ expect(statements.some((statement) => statement.sql.includes("INSERT INTO community_bot_daily_token_usage"))).toBe(false)+ })++ it("does not accept usage calendar metadata on a non-idle frame", async () => {+ const { durable, store } = createDO()+ store.set("community-machine-identity", {+ userId: "u_1",+ machineId: "cm_1",+ credentialHash: "0".repeat(64),+ })+ mockGetBotBinding.mockResolvedValue({ machineId: "cm_1", runtime: "codex" })+ const ws = createMockWebSocket()+ ws.serializeAttachment({ type: "community-machine", machineId: "cm_1", userId: "u_1", authenticated: true })+ const usageTimeZone = "Asia/Shanghai"+ const usageDay = dayKeyInTimeZone(new Date(), usageTimeZone)++ await durable.webSocketMessage(ws as any, JSON.stringify({+ type: "agent_activity",+ agentId: "bot_1",+ state: "running",+ usageTimeZone,+ usageDay,+ dailyUsage: [{+ botId: "bot_1",+ day: usageDay,+ metrics: { input: 3, output: 1, cache: 2 },+ }],+ }))++ expect(mockD1Batch).not.toHaveBeenCalled()+ })++ it("rejects mismatched computer-timezone metadata without treating its snapshots as legacy UTC", async () => {+ const { durable, store } = createDO()+ store.set("community-machine-identity", {+ userId: "u_1",+ machineId: "cm_1",+ credentialHash: "0".repeat(64),+ })+ mockGetBotBinding.mockResolvedValue({ machineId: "cm_1", runtime: "codex" })+ mockGetProfile.mockResolvedValue({ statusEmoji: "💤", statusText: "Idle" })+ const ws = createMockWebSocket()+ ws.serializeAttachment({ type: "community-machine", machineId: "cm_1", userId: "u_1", authenticated: true })++ await durable.webSocketMessage(ws as any, JSON.stringify({+ type: "agent_activity",+ agentId: "bot_1",+ state: "idle",+ usageTimeZone: "not/a-time-zone",+ usageDay: new Date().toISOString().slice(0, 10),+ dailyUsage: [{+ botId: "bot_1",+ day: new Date().toISOString().slice(0, 10),+ metrics: { input: 3, output: 1, cache: 2 },+ }],+ }))++ expect(mockD1Batch).not.toHaveBeenCalled()})it("persists each valid telemetry section when the sibling section is malformed", async () => {diff --git a/src/ws-do/src/ws-durable/machine-telemetry.ts b/src/ws-do/src/ws-durable/machine-telemetry.tsindex a4fd3ab96..868dc5225 100644--- a/src/ws-do/src/ws-durable/machine-telemetry.ts+++ b/src/ws-do/src/ws-durable/machine-telemetry.ts@@ -12,6 +12,8 @@ import {RUNNING_PRESETS,withD1Retry,WS_EVENTS,+ calendarDayKeyDaysAgo,+ dayKeyInTimeZone,utcDayKeyDaysAgo,} from "@alook/shared"import { handleFrameForBoundBot } from "./bound-bot-frame"@@ -26,6 +28,7 @@ import {prepareActivityProfileUpsert,prepareQuotaReplace,prepareUsagePrune,+ prepareMachineTimeZoneUpdate,prepareUsageUpsert,} from "./provider-telemetry-persistence"@@ -54,7 +57,7 @@ export async function handleActivityFrame(identity: CommunityMachineIdentity,): Promise<boolean> {const activityParse = AgentActivityMessageSchema- .omit({ dailyUsage: true, quota: true })+ .omit({ usageTimeZone: true, usageDay: true, dailyUsage: true, quota: true }).passthrough().safeParse(parsed)if (!activityParse.success) return false@@ -62,7 +65,44 @@ export async function handleActivityFrame(const { agentId, state } = activityParse.dataconst raw = parsed as Record<string, unknown>const now = new Date()- const allowedDays = new Set(Array.from({ length: 7 }, (_, offset) => utcDayKeyDaysAgo(now, offset)))+ const legacyAllowedDays = new Set(Array.from({ length: 7 }, (_, offset) => utcDayKeyDaysAgo(now, offset)))+ const rawUsageTimeZone = raw.usageTimeZone+ const rawUsageDay = raw.usageDay+ const hasUsageCalendarMetadata = rawUsageTimeZone !== undefined || rawUsageDay !== undefined+ const legalServerCalendarDays = new Set([+ dayKeyInTimeZone(now, "Etc/GMT+12"),+ utcDayKeyDaysAgo(now, 0),+ dayKeyInTimeZone(now, "Pacific/Kiritimati"),+ ])+ let validUsageCalendar: { timeZone: string; day: string } | undefined+ if (+ state === "idle"+ && typeof rawUsageTimeZone === "string"+ && rawUsageTimeZone.length >= 1+ && rawUsageTimeZone.length <= 128+ && typeof rawUsageDay === "string"+ && /^\d{4}-\d{2}-\d{2}$/.test(rawUsageDay)+ ) {+ try {+ const expectedDay = dayKeyInTimeZone(now, rawUsageTimeZone)+ const acceptableDays = new Set([+ calendarDayKeyDaysAgo(expectedDay, 1),+ expectedDay,+ calendarDayKeyDaysAgo(expectedDay, -1),+ ])+ if (acceptableDays.has(rawUsageDay) && legalServerCalendarDays.has(rawUsageDay)) {+ validUsageCalendar = { timeZone: rawUsageTimeZone, day: rawUsageDay }+ }+ } catch { }+ }+ const allowedUsageDays = validUsageCalendar+ ? new Set(Array.from(+ { length: 7 },+ (_, offset) => calendarDayKeyDaysAgo(validUsageCalendar.day, offset),+ ))+ : hasUsageCalendarMetadata+ ? null+ : legacyAllowedDaysconst usageParse = raw.dailyUsage === undefined? null: DailyUsageSnapshotSchema.array().max(7).safeParse(raw.dailyUsage)@@ -71,7 +111,8 @@ export async function handleActivityFrame(const validUsage = state === "idle"&& parsedUsage !== undefined&& usageDays?.size === parsedUsage.length- && parsedUsage.every((snapshot) => snapshot.botId === agentId && allowedDays.has(snapshot.day))+ && allowedUsageDays !== null+ && parsedUsage.every((snapshot) => snapshot.botId === agentId && allowedUsageDays.has(snapshot.day))? parsedUsage: undefinedconst quotaParse = raw.quota === undefined@@ -115,7 +156,9 @@ export async function handleActivityFrame(const profileChanged = preset !== null&& (preset.emoji !== priorEmoji || preset.text !== priorText)const quota = validQuota?.agentBackendId === binding.runtime ? validQuota : undefined- const hasTelemetry = (validUsage?.length ?? 0) > 0 || quota !== undefined+ const hasTelemetry = validUsageCalendar !== undefined+ || (validUsage?.length ?? 0) > 0+ || quota !== undefinedif (!hasTelemetry) {if (!profileChanged || !preset) returnawait withD1Retry(@@ -145,15 +188,29 @@ export async function handleActivityFrame(preset.text,))}+ if (validUsageCalendar) {+ statements.push(prepareMachineTimeZoneUpdate(+ context.env.DB,+ identity,+ validUsageCalendar.timeZone,+ ))+ }for (const snapshot of validUsage ?? []) {statements.push(prepareUsageUpsert(context.env.DB, identity.machineId, snapshot, nowIso))}- if (validUsage && validUsage.length > 0) {+ if (validUsageCalendar) {+ statements.push(prepareUsagePrune(+ context.env.DB,+ identity.machineId,+ agentId,+ calendarDayKeyDaysAgo(validUsageCalendar.day, 8),+ ))+ } else if (validUsage && validUsage.length > 0) {statements.push(prepareUsagePrune(context.env.DB,identity.machineId,agentId,- utcDayKeyDaysAgo(now, 6),+ utcDayKeyDaysAgo(now, 8),))}if (quota) statements.push(prepareQuotaReplace(context.env.DB, identity, quota, nowIso))diff --git a/src/ws-do/src/ws-durable/provider-telemetry-persistence.test.ts b/src/ws-do/src/ws-durable/provider-telemetry-persistence.test.tsindex 57a1ea5dc..b43d476f5 100644--- a/src/ws-do/src/ws-durable/provider-telemetry-persistence.test.ts+++ b/src/ws-do/src/ws-durable/provider-telemetry-persistence.test.ts@@ -3,6 +3,8 @@ import { DatabaseSync } from "node:sqlite";import type { DailyUsageSnapshot, ProviderQuotaSnapshot } from "@alook/shared";import {prepareQuotaReplace,+ prepareUsagePrune,+ prepareMachineTimeZoneUpdate,prepareUsageUpsert,} from "./provider-telemetry-persistence.js";@@ -67,7 +69,8 @@ describe("provider telemetry persistence SQL", () => {);CREATE TABLE community_machine (id TEXT PRIMARY KEY NOT NULL,- user_id TEXT NOT NULL+ user_id TEXT NOT NULL,+ time_zone TEXT);CREATE TABLE community_machine_backend_quota (machine_id TEXT NOT NULL,@@ -131,6 +134,53 @@ describe("provider telemetry persistence SQL", () => {expect(sqlite.prepare("SELECT COUNT(*) AS count FROM community_bot_daily_token_usage").get()).toEqual({ count: 0 });});+ it("updates the authenticated computer timezone and keeps the two-day recovery margin", () => {+ for (const day of ["2026-08-21", "2026-08-22", "2026-08-23", "2026-08-29", "2026-08-30"]) {+ const snapshot = { ...usage("bot_1", 1, 2, 3), day };+ run(prepareUsageUpsert(db, "machine_1", snapshot, "2026-08-29T16:00:01.000Z"));+ }++ run(prepareMachineTimeZoneUpdate(db, {+ machineId: "machine_1",+ userId: "owner_1",+ }, "Asia/Shanghai"));+ run(prepareUsagePrune(db, "machine_1", "bot_1", "2026-08-22"));++ expect(sqlite.prepare(`+ SELECT time_zone+ FROM community_machine+ WHERE id = 'machine_1'+ `).get()).toEqual({ time_zone: "Asia/Shanghai" });+ expect(sqlite.prepare(`+ SELECT day+ FROM community_bot_daily_token_usage+ ORDER BY day+ `).all()).toEqual([+ { day: "2026-08-22" },+ { day: "2026-08-23" },+ { day: "2026-08-29" },+ { day: "2026-08-30" },+ ]);+ });++ it("cannot update timezone or prune through a stale machine binding", () => {+ run(prepareUsageUpsert(db, "machine_1", usage("bot_1", 1, 2, 3), "2026-08-28T10:00:00.000Z"));+ sqlite.prepare("UPDATE community_bot_binding SET machine_id = ? WHERE user_id = ?").run("machine_2", "bot_1");++ run(prepareMachineTimeZoneUpdate(db, {+ machineId: "machine_1",+ userId: "wrong_owner",+ }, "Asia/Shanghai"));+ run(prepareUsagePrune(db, "machine_1", "bot_1", "2026-08-29"));++ expect(sqlite.prepare(`+ SELECT time_zone+ FROM community_machine+ WHERE id = 'machine_1'+ `).get()).toEqual({ time_zone: null });+ expect(sqlite.prepare("SELECT COUNT(*) AS count FROM community_bot_daily_token_usage").get()).toEqual({ count: 1 });+ });+it("retains a same-source success on transient error and replaces it for a new source", () => {const available = quota("A".repeat(22), {status: "available",diff --git a/src/ws-do/src/ws-durable/provider-telemetry-persistence.ts b/src/ws-do/src/ws-durable/provider-telemetry-persistence.tsindex 8d5d05d27..fa5af99ff 100644--- a/src/ws-do/src/ws-durable/provider-telemetry-persistence.ts+++ b/src/ws-do/src/ws-durable/provider-telemetry-persistence.ts@@ -73,6 +73,18 @@ export function prepareUsagePrune(`).bind(botId, oldestDay, botId, machineId);}+export function prepareMachineTimeZoneUpdate(+ db: D1Database,+ identity: { machineId: string; userId: string },+ timeZone: string,+): D1PreparedStatement {+ return db.prepare(`+ UPDATE community_machine+ SET time_zone = ?+ WHERE id = ? AND user_id = ?+ `).bind(timeZone, identity.machineId, identity.userId);+}+export function prepareQuotaReplace(db: D1Database,identity: { machineId: string; userId: string },