Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,7 @@ lib/
pending-requests.ts daemon side: `PendingRequests`, a channel's still-open blocking requests and current session id for the hello
daemon-broker.ts daemon side: the loopback forwarder that gives a sharing host's omp processes `OMP_AUTH_BROKER_URL`/`OMP_AUTH_BROKER_TOKEN` (`credentialsEnv`); forwards to the link's server with the link's host token
registry.ts `<agent dir>/omp-web/hosts.json`: create/update/revoke, token hashing and lookup; the `local` record (`rotateLocalHostToken`, `customLocalLabel`)
usage-sync.ts main side of usage from linked hosts: `pullAllHostUsage` pulls each linked host's transcript stamps and records (`listUsageTranscripts`, `readUsageRecords`) into `usage.db` on `/api/usage`, 30 s TTL per host (a forced refresh reads every transcript again); a host's sync state follows its link status, its last sync time is kept in `usage.db`
session-index.ts sessions and projects across hosts, cached per host; `hostForSessionId`, `sessionSpawnTarget`, `invalidateLocalSessionLists`
cluster.ts pure cluster rules: `clusterOf` (= `pools[0]`), `isClusterMember`, `sharesCredentials`, `joinCluster`/`leaveCluster`, `clusterJoinBlock`, `ompSharesCredentials` (also the daemon's spawn check); browser-importable (Settings uses it)
cluster-config.ts pure, daemon-safe: what a cluster member mirrors from the master (`MIRRORED`, `LOCAL_SETTINGS`, `CONFIG_LIMITS`), `buildManifest`, `stripLocalSettings`/`mergeLocalSettings`, `isManagedPath`, `ClusterConfigError`
Expand Down Expand Up @@ -1690,7 +1691,7 @@ during the wait.
`invalidateSessionFileListCache()` — never add a session-mutation path that
forgets this. Regression test: `session-reader.test.mjs`.
- A mutation that main triggers calls `invalidateLocalSessionLists()`: it clears main's per-host entry and sends the daemon `invalidateSessionLists` (the daemon runs the invalidation above). A route that changes this machine's session files and does not call it leaves the sidebar stale for up to 30 s.
- **Still read on main, from this machine's own files:** transcript search (`session-content-search.ts`, `/api/sessions/search`), the session watcher (`session-watcher.ts`), this machine's archive list/restore (linked hosts' go through their daemons), import, usage (`usage-db.ts`), subagent history and local file-reference readers. Their main-side session caches are invalidated separately. Workspace shell-output authorization and bytes now come from the owning daemon; new remote-capable readers must use the host seam.
- **Still read on main, from this machine's own files:** transcript search (`session-content-search.ts`, `/api/sessions/search`), the session watcher (`session-watcher.ts`), this machine's archive list/restore (linked hosts' go through their daemons), import, this machine's usage (`usage-db.ts`; linked hosts' usage comes through `lib/hosts/usage-sync.ts`), subagent history and local file-reference readers. Their main-side session caches are invalidated separately. Workspace shell-output authorization and bytes now come from the owning daemon; new remote-capable readers must use the host seam.

### Chat scroll-follow
- `useAgentSession` follows the conversation: the effect depends on both
Expand Down
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,13 @@ All notable changes to **omp-web** (`@kahme247/ompweb`) are documented in this f

## [Unreleased]

### Added

- **Usage includes linked hosts.** Settings → Usage now counts the tokens and cost of sessions on every linked host, not only this machine. Each host's daemon reads its own transcripts; the web server keeps a copy, so a host that goes offline keeps its last numbers. A new **Host** breakdown shows each machine's share and when an offline host last synced, and project rows name their host. A host that is still syncing fills in on its own. Refresh reads every host's sessions again, with the prices in that host's `models.yml`. A host on an older ompweb is listed as needing an update.

### Fixed

- **Refreshing Usage applies changed prices, and says when it fails.** Prices edited in `models.yml` now apply to existing sessions when you refresh Settings → Usage. They used to keep the old prices until the web server restarted. A refresh that fails now shows the error above the last report instead of leaving it up without a word.
- **Windows updates no longer fail when the update status is read while it is written.** Host update state, the server worker's status and upgrade plans retry their atomic replacement for a moment when a concurrent reader holds the file, as the server's own update state already did.
- **GitHub workflow watches no longer regress to stale run states.** Workflow updates retain GitHub's run timestamp and ignore older snapshots for the same or an earlier attempt, so a delayed `queued` response cannot follow a newer `in_progress` delivery.
- **Keep sidebar transcript results aligned with expandable hits on every linked host.** Each daemon now searches its own active conversations, ignoring abandoned branches and pre-compaction messages.
Expand Down
2 changes: 1 addition & 1 deletion app/api/usage/route.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { apiErrorResponse } from "@/lib/api-utils";
import { getUsageReport } from "@/lib/usage-service";
import { getUsageReport } from "@/lib/usage-report";
import type { UsageGranularity, UsageTimeRange } from "@/lib/usage-types";

export async function GET(req: Request) {
Expand Down
173 changes: 173 additions & 0 deletions components/UsageConfig.hosts.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,173 @@
import "../tests/setup-dom.mjs";
import assert from "node:assert/strict";
import test from "node:test";
import { act, createElement } from "react";
const { cleanup, fireEvent, render, within } = await import("@testing-library/react/pure.js");
const { UsageConfig } = await import("./UsageConfig");

const settle = () => act(() => new Promise((resolve) => setTimeout(resolve, 20)));

const host = (hostId, label, state, syncedAt, cost) => ({ hostId, label, state, syncedAt, cost, tokens: cost * 1000, share: 0, sessionsCount: 1 });
const project = (hostId, hostLabel, name) => ({
hostId, hostLabel, project: `/work/${name}`, projectName: name, cost: 1, tokens: 1000, share: 50, sessionsCount: 1,
});

/** Answer `/api/usage` with `reports` in turn, the last one from then on; `null` answers 503. Returns the URLs asked for. */
function fakeUsage(t, ...reports) {
const requests = [];
const originalFetch = globalThis.fetch;
globalThis.fetch = async (url) => {
if (!String(url).startsWith("/api/usage")) return Response.json({});
requests.push(String(url));
const next = reports[Math.min(requests.length, reports.length) - 1];
return next ? Response.json(next) : new Response("", { status: 503, statusText: "Service Unavailable" });
};
t.after(() => {
cleanup();
globalThis.fetch = originalFetch;
});
return requests;
}

/** Fake `setTimeout`. The returned function advances it by `ms`, then lets pending fetches answer and React render. */
function mockTimers(t) {
t.mock.timers.enable({ apis: ["setTimeout"] });
t.after(() => t.mock.timers.reset());
return (ms = 0) => act(async () => {
t.mock.timers.tick(ms);
for (let i = 0; i < 30; i++) await Promise.resolve();
});
}

function report(extra) {
return {
summary: {
totalCost: 3, totalTokens: 3000, inputTokens: 2000, outputTokens: 1000, reasoningTokens: 0,
cacheReadTokens: 0, cacheWriteTokens: 0, cachePercentage: 0, cacheSavings: 0, tokensPerActiveDay: 3000,
costQuality: { providerReported: 100, modelPriced: 0, unpriced: 0 },
},
scanInfo: { transcriptsScanned: 2, transcriptsOutsideWindow: 0, usageRecordsCount: 2, durationSeconds: 0.1 },
providers: [], modelBreakdown: [], dayBreakdown: [], timeSeries: [],
projectBreakdown: [project("local", "", "web"), project("h1", "laptop", "api")],
...extra,
};
}

test("the HOST breakdown lists every machine with its sync state", async (t) => {
const syncedAt = Date.UTC(2026, 10, 10, 12, 0);
fakeUsage(t, report({
hostBreakdown: [
host("local", "", "current", null, 2),
host("h1", "laptop", "offline", syncedAt, 1),
host("h2", "build", "unsupported", null, 0),
host("h3", "tablet", "stale", null, 0),
host("h4", "nas", "syncing", null, 0),
],
}));
const { container } = render(createElement(UsageConfig));
await settle();
fireEvent.click(within(container).getByRole("button", { name: "HOST" }));
const rows = [...container.querySelectorAll("tbody tr")].map((row) => row.cells[0].textContent);
assert.deepEqual(rows, [
"This machine",
`laptopOffline · last synced ${new Date(syncedAt).toLocaleString()}`,
"buildUpdate ompweb on this host to include its usage",
"tabletNot synced yet",
"nasSyncing…",
]);
});

test("project rows of a linked host name it", async (t) => {
fakeUsage(t, report({ hostBreakdown: [host("local", "", "current", null, 2), host("h1", "laptop", "current", 1, 1)] }));
const { container } = render(createElement(UsageConfig));
await settle();
fireEvent.click(within(container).getByRole("button", { name: "PROJECT" }));
const rows = [...container.querySelectorAll("tbody tr")].map((row) => row.cells[0].textContent);
assert.deepEqual(rows, ["web", "api · laptop"]);
});

test("a single machine shows no HOST toggle", async (t) => {
fakeUsage(t, report({ hostBreakdown: [host("local", "", "current", null, 3)] }));
const { container } = render(createElement(UsageConfig));
await settle();
assert.ok(within(container).getByRole("button", { name: "PROJECT" }));
assert.equal(within(container).queryByRole("button", { name: "HOST" }), null);
});

test("a report without hostBreakdown shows no HOST toggle", async (t) => {
fakeUsage(t, report({}));
const { container } = render(createElement(UsageConfig));
await settle();
assert.ok(within(container).getByRole("button", { name: "PROJECT" }));
assert.equal(within(container).queryByRole("button", { name: "HOST" }), null);
});

test("while a host is syncing the report is fetched again, until the host is done", async (t) => {
const laptop = (state) => report({ hostBreakdown: [host("local", "", "current", null, 2), host("h1", "laptop", state, null, 1)] });
const requests = fakeUsage(t, laptop("syncing"), laptop("syncing"), laptop("current"));
const advance = mockTimers(t);
const { container } = render(createElement(UsageConfig));
await advance();
fireEvent.click(within(container).getByRole("button", { name: "HOST" }));
const laptopRow = () => container.querySelectorAll("tbody tr")[1].cells[0].textContent;
assert.deepEqual([requests.length, laptopRow()], [1, "laptopSyncing…"]);

await advance(1999);
assert.equal(requests.length, 1);
await advance(1);
assert.deepEqual([requests.length, laptopRow()], [2, "laptopSyncing…"]);
await advance(2000);
assert.deepEqual([requests.length, laptopRow()], [3, "laptop"]);
assert.ok(requests.every((url) => !url.includes("refresh")), "polling never forces a refresh");

await advance(60_000);
assert.equal(requests.length, 3, "nothing is syncing any more");
});

test("leaving the page stops fetching for a host that is still syncing", async (t) => {
const requests = fakeUsage(t, report({ hostBreakdown: [host("local", "", "current", null, 2), host("h1", "laptop", "syncing", null, 1)] }));
const advance = mockTimers(t);
const { unmount } = render(createElement(UsageConfig));
await advance();
unmount();
await advance(60_000);
assert.equal(requests.length, 1);
});

test("a background update that fails is shown above the report it could not replace, until one arrives", async (t) => {
const laptop = (state) => report({ hostBreakdown: [host("local", "", "current", null, 2), host("h1", "laptop", state, null, 1)] });
const requests = fakeUsage(t, laptop("syncing"), null, laptop("current"));
const advance = mockTimers(t);
const { container } = render(createElement(UsageConfig));
await advance();
assert.equal(within(container).queryByRole("alert"), null);

await advance(2000);
assert.equal(within(container).getByRole("alert").textContent, "Could not load usage data: Failed to fetch usage: Service Unavailable");
assert.ok(within(container).getByRole("button", { name: "HOST" }), "the report stays on screen");

await advance(2000);
assert.deepEqual([requests.length, within(container).queryByRole("alert")], [3, null]);
});

test("a background update still on its way when Refresh is pressed does not replace the refreshed report", async (t) => {
const laptop = (state) => report({ hostBreakdown: [host("local", "", "current", null, 2), host("h1", "laptop", state, null, 1)] });
const requests = fakeUsage(t, laptop("syncing"), laptop("current"), laptop("syncing"));
const delivered = globalThis.fetch;
const late = Promise.withResolvers();
let calls = 0;
// The second call, the background update, answers only once the refresh has.
globalThis.fetch = (url, init) => (++calls === 2 ? late.promise.then(() => delivered(url, init)) : delivered(url, init));
const advance = mockTimers(t);
const { container } = render(createElement(UsageConfig));
await advance();
fireEvent.click(within(container).getByRole("button", { name: "HOST" }));
const laptopRow = () => container.querySelectorAll("tbody tr")[1].cells[0].textContent;

await advance(2000);
fireEvent.click(within(container).getByRole("button", { name: "Refresh usage data" }));
await advance();
late.resolve();
await advance();
assert.deepEqual([requests.length, laptopRow()], [3, "laptop"]);
});
Loading