From 901b40f6ede19aa5ccfa6a1dab40e3cc6b73c88a Mon Sep 17 00:00:00 2001 From: Sarav Date: Mon, 16 Nov 2026 08:10:52 +0530 Subject: [PATCH 1/7] fix: workspace review decision toasts survive "Sync now"; publish refusals carry a code MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - TUI: the TUI shows one toast at a time, and "Sync now" ended with its "Synced: …" summary, which replaced a skill or knowledge decision the sync had just announced. The decision was recorded as shown, so the person never saw "approved" or "rejected — reason". Decisions now go through one toaster per TUI: those arriving together are shown as one toast (five named, the rest counted), and "Sync now" skips its summary when a decision was shown, or is about to be, since it started. Problems (sync skipped, proposals kept queued) are still said. - `skill publish --json`: a refusal this command explains now carries its stable `code` (`review_disabled`, `too_many_requests`, …) next to `error`. - Docs: the `code` field. Found in an end-to-end run of workspace review against a local backend. Co-Authored-By: Claude Opus 5.5 --- docs/docs/configure/skills.md | 2 +- packages/opencode/src/cli/cmd/skill.ts | 19 ++- .../src/plugin/tui/altimate/rules.tsx | 119 ++++++++++++++++-- .../test/cli/tui/rules-requests.test.ts | 57 ++++++++- 4 files changed, 176 insertions(+), 21 deletions(-) diff --git a/docs/docs/configure/skills.md b/docs/docs/configure/skills.md index c79b11322a..b0ea413c35 100644 --- a/docs/docs/configure/skills.md +++ b/docs/docs/configure/skills.md @@ -207,7 +207,7 @@ altimate-code workspace review status # changes nothing on the server; --j - `Sent "" for review to `: you are a member of a workspace whose owner turned review on. The team gets the skill once the owner or an admin approves it in the Altimate web app; until then only you get your pending version. Approving and rejecting happen only in the web app. - `Already waiting for review` or `Already approved`: the same content was already submitted or approved, so nothing new was sent. -Requests sent from the CLI are recorded as such in the request's history. What the team gets is the exact version that was approved: editing the skill afterwards changes nothing for them until you run `skill publish` again, which submits the new version as an update. A member publishing to a workspace whose owner has review off is refused before anything is uploaded. If the skill uploads but cannot be sent (offline, an expired sign-in, too many open requests), the command says so and exits non-zero; running it again updates the uploaded skill and submits it. Against a workspace service without review, `skill publish` attaches the skill directly as before, which only the workspace owner can do. With `--json`, the output carries `ok`, the upload (`action`, `public_id`, `files`, `bytes`, `workspace_id`, `workspace_name`) and `review` with the service's `status`, `attached_directly`, `duplicate`, `owner_name` and `contribution` (`null` without review); every failure exits non-zero with `{"ok": false, "error": ...}`. +Requests sent from the CLI are recorded as such in the request's history. What the team gets is the exact version that was approved: editing the skill afterwards changes nothing for them until you run `skill publish` again, which submits the new version as an update. A member publishing to a workspace whose owner has review off is refused before anything is uploaded. If the skill uploads but cannot be sent (offline, an expired sign-in, too many open requests), the command says so and exits non-zero; running it again updates the uploaded skill and submits it. Against a workspace service without review, `skill publish` attaches the skill directly as before, which only the workspace owner can do. With `--json`, the output carries `ok`, the upload (`action`, `public_id`, `files`, `bytes`, `workspace_id`, `workspace_name`) and `review` with the service's `status`, `attached_directly`, `duplicate`, `owner_name` and `contribution` (`null` without review); every failure exits non-zero with `{"ok": false, "error": ...}`, plus a stable `code` when the command refused for a known reason (for example `review_disabled`, `too_many_requests`, `not_workspace_owner`, `bundle_too_large`). When the owner or an admin approves or rejects one of your requests that this client has seen pending (submitted from it, or listed by an earlier check), or one it has not seen that is decided after it began checking (sent from the web app or another machine), the TUI shows a notice once in each project linked to that workspace (with the reason for a rejection). Each altimate-code process with a linked project open checks at start and every 5 minutes (a server without review is asked again only after 6 hours) and keeps the 50 most recent decisions in your own state directory, so a decision that arrives while the TUI is closed or disconnected is shown when it next starts (as rule review notices are). The first time a TUI opens a project, decisions already kept are recorded without a notice; `workspace review status` lists them. `altimate-code workspace review status` lists your requests on the linked workspace (skills and knowledge bases): kind, name, status, whether it is new or an update, the reviewer and their reason, and `expired` for a request waiting longer than 14 days (it can still be approved). In the web app, or from `/rules` in the TUI (which lists your skill and knowledge requests under your rule proposals), you can withdraw a request that is still waiting and remove an approved skill or knowledge base of yours from the workspace; in the web app the owner or an admin can remove it too, with a reason. The VS Code extension does the same through `altimate-code serve` (`GET /altimate/workspace/requests`, `POST /altimate/workspace/requests/{id}/withdraw|remove`), and Claude Code and Codex sessions are told of decisions, and of your requests still waiting, when they start, whether or not team rules apply in the project. Each client (the TUI, the extension, Claude Code's and Codex's session start, Claude Code's toast) shows a decision once per account and workspace; the first time a client asks, decisions already kept are recorded as shown without a notice. `altimate-code workspace review decisions --json` answers them for plugins: newest first: `--unseen --host ` only those not given to that client yet, `--mark-seen` remembers them as given, `--claim` holds them for 5 minutes until `--ack …` says they were shown. `--unseen`, `--mark-seen`, `--claim` and `--ack` need `--host` (else `{"ok": false, "status": "host_required"}`). The command always prints one JSON object and exits 0, so a plugin can tell an older CLI from an answer. When the owner or an admin removes one of yours that this client has seen approved (or waiting; up to the 200 approved ones it tracks per workspace), the TUI shows that once too, with the reason; your own removal and withdrawal show nothing. `workspace review status` lists them as `withdrawn` and `removed from the workspace`. diff --git a/packages/opencode/src/cli/cmd/skill.ts b/packages/opencode/src/cli/cmd/skill.ts index 78869d40f1..c1f25a6219 100644 --- a/packages/opencode/src/cli/cmd/skill.ts +++ b/packages/opencode/src/cli/cmd/skill.ts @@ -12,7 +12,13 @@ import { Global } from "@/global" import { detectToolReferences, skillSource, isToolOnPath } from "./skill-helpers" // altimate_change start — telemetry for skill operations import { Telemetry } from "@/altimate/telemetry" -import { describePublish, explainPublishError, publishSkill, type PublishReport } from "@/altimate/workspace/skill-publish" +import { + describePublish, + explainPublishError, + publishErrorCode, + publishSkill, + type PublishReport, +} from "@/altimate/workspace/skill-publish" import { Flag } from "@opencode-ai/core/flag/flag" import { printable } from "@/altimate/rules/printable" // altimate_change end @@ -490,8 +496,9 @@ const SkillPublishCommand = cmd({ // altimate_change start — workspace review: every outcome goes through one writer, JSON or text, and every failure // exits non-zero const json = args.json === true - const fail = (message: string) => { - if (json) process.stdout.write(JSON.stringify({ ok: false, error: message }, null, 2) + EOL) + // `code`: the stable reason for a refusal this command explains (`review_disabled`, `too_many_requests`, …). + const fail = (message: string, code?: string) => { + if (json) process.stdout.write(JSON.stringify({ ok: false, error: message, ...(code ? { code } : {}) }, null, 2) + EOL) else process.stderr.write(message + EOL) process.exitCode = 1 } @@ -499,13 +506,13 @@ const SkillPublishCommand = cmd({ // writer, once: a result already written is not followed by a second one, but the command still exits non-zero. // Server text is made inert before it reaches the terminal. let written = false - const once = (message: string) => { + const once = (message: string, code?: string) => { if (written) { process.exitCode = 1 return } written = true - fail(printable(message)) + fail(printable(message), code) } // altimate_change end try { @@ -563,7 +570,7 @@ const SkillPublishCommand = cmd({ } catch {} } catch (err) { const known = explainPublishError(err) - once(known ?? `Publish failed: ${err instanceof Error ? err.message : String(err)}`) + once(known ?? `Publish failed: ${err instanceof Error ? err.message : String(err)}`, publishErrorCode(err) ?? undefined) } }) } catch (err) { diff --git a/packages/opencode/src/plugin/tui/altimate/rules.tsx b/packages/opencode/src/plugin/tui/altimate/rules.tsx index 46da86d6c4..5a1e37077d 100644 --- a/packages/opencode/src/plugin/tui/altimate/rules.tsx +++ b/packages/opencode/src/plugin/tui/altimate/rules.tsx @@ -454,7 +454,7 @@ function installCards(api: TuiPluginApi) { const key = shownKey(p) if (seen.has(key)) return api.kv.set(seenKey(), [...seen, key].slice(-200)) - if (!quiet) reviewToast(api, p) + if (!quiet) toasterOf(api).push(p) } // `live`: a decision that arrived as an event before the first replay. It is news even when the replay is the scope's // first, which records what was kept before it silently. @@ -505,6 +505,7 @@ function installCards(api: TuiPluginApi) { disposed = true if (leaseTimer) clearTimeout(leaseTimer) clearTimeout(startup) + disposeToaster(api) for (const off of offs.splice(0)) off() disposeEffects() }) @@ -516,23 +517,112 @@ type Shown = { public_id: string; text: string; status: string; reason?: string; /** How a decision is remembered as shown: rule and skill ids live in different id spaces. */ export const shownKey = (p: Pick) => `${p.kind ?? "rule"}:${p.public_id}:${p.status}` -function reviewToast(api: TuiPluginApi, raw: Shown) { - const p = { ...raw, text: printable(raw.text), reason: raw.reason && printable(raw.reason), reviewer: raw.reviewer && printable(raw.reviewer) } +type DecisionToast = { variant: "success" | "warning" | "info"; message: string; duration: number } + +const cleanShown = (raw: Shown): Shown => ({ + ...raw, + text: printable(raw.text), + reason: raw.reason && printable(raw.reason), + reviewer: raw.reviewer && printable(raw.reviewer), +}) +const quote = (text: string) => `"${text.length > 80 ? text.slice(0, 79) + "…" : text}"` +const isBad = (p: Shown) => p.status === "rejected" || (p.status === "retired" && p.kind !== undefined && p.kind !== "rule") + +/** The toast for one decision on the person's own rule, skill or knowledge request; none for a rule status this + * version does not show. */ +export function decisionToast(raw: Shown): DecisionToast | undefined { + const p = cleanShown(raw) const who = p.reviewer ? ` by ${p.reviewer}` : "" - const quoted = `"${p.text.length > 80 ? p.text.slice(0, 79) + "…" : p.text}"` + const quoted = quote(p.text) // A skill or knowledge base the person submitted to the workspace: `text` is its name. if (p.kind && p.kind !== "rule") { const what = p.kind === "skill" ? `Your skill ${quoted}` : `Your knowledge base ${quoted}` - if (p.status === "active") api.ui.toast({ variant: "success", message: `${what} was approved${who}. It now reaches the workspace.`, duration: 10000 }) - else if (p.status === "rejected") api.ui.toast({ variant: "warning", message: `${what} was rejected${who}${p.reason ? ` — ${p.reason}` : ""}`, duration: 15000 }) - else if (p.status === "retired") api.ui.toast({ variant: "warning", message: `${what} was removed from the workspace${who}${p.reason ? ` — ${p.reason}` : ""}`, duration: 15000 }) + if (p.status === "active") return { variant: "success", message: `${what} was approved${who}. It now reaches the workspace.`, duration: 10000 } + if (p.status === "rejected") return { variant: "warning", message: `${what} was rejected${who}${p.reason ? ` — ${p.reason}` : ""}`, duration: 15000 } + if (p.status === "retired") return { variant: "warning", message: `${what} was removed from the workspace${who}${p.reason ? ` — ${p.reason}` : ""}`, duration: 15000 } // A status this version does not know (a newer server) is still shown, not dropped. - else api.ui.toast({ variant: "info", message: `${what} is now ${printable(p.status)}${who}.`, duration: 10000 }) - return + return { variant: "info", message: `${what} is now ${printable(p.status)}${who}.`, duration: 10000 } } - if (p.status === "active") api.ui.toast({ variant: "success", message: `Your rule was approved${who}: ${quoted}. It now applies to the team.`, duration: 10000 }) - else if (p.status === "rejected") api.ui.toast({ variant: "warning", message: `Your rule was rejected${who}: ${quoted}${p.reason ? ` — ${p.reason}` : ""}`, duration: 15000 }) - else if (p.status === "retired") api.ui.toast({ variant: "info", message: `Retired${who}: ${quoted}`, duration: 10000 }) + if (p.status === "active") return { variant: "success", message: `Your rule was approved${who}: ${quoted}. It now applies to the team.`, duration: 10000 } + if (p.status === "rejected") return { variant: "warning", message: `Your rule was rejected${who}: ${quoted}${p.reason ? ` — ${p.reason}` : ""}`, duration: 15000 } + if (p.status === "retired") return { variant: "info", message: `Retired${who}: ${quoted}`, duration: 10000 } + return undefined +} + +/** How many decisions a combined toast names. */ +const COMBINED_NAMED = 5 + +/** One line of a combined toast. */ +function decisionLine(raw: Shown): string { + const p = cleanShown(raw) + const what = p.kind === "skill" ? "skill" : p.kind === "knowledge" ? "knowledge base" : "rule" + const did: Record = { active: "approved", rejected: "rejected", retired: p.kind && p.kind !== "rule" ? "removed" : "retired" } + const who = p.reviewer ? ` by ${p.reviewer}` : "" + const why = isBad(p) && p.reason ? ` — ${p.reason}` : "" + return `${what} ${quote(p.text)} ${did[p.status] ?? printable(p.status)}${who}${why}` +} + +/** The toast for decisions that arrived together. The TUI shows one toast at a time, so several are listed in one + * rather than each replacing the last; a warning when any of them is a rejection or a removal. */ +export function combinedToast(decisions: Shown[]): DecisionToast | undefined { + const shown = decisions.filter((d) => decisionToast(d) !== undefined) + if (shown.length <= 1) return shown[0] && decisionToast(shown[0]) + // A TUI closed for a while can replay many at once: a few are named, the rest counted (`/rules` lists them all). + const named = shown.slice(0, COMBINED_NAMED).map(decisionLine) + const more = shown.length - named.length + return { + variant: shown.some(isBad) ? "warning" : "success", + message: `${shown.length} decisions on your requests: ${named.join(" · ")}${more > 0 ? ` · and ${more} more (see /rules)` : ""}`, + duration: 15000, + } +} + +/** Decisions to toast, held for `windowMs` so the ones that arrive together are shown together. `shownSince` tells + * "Sync now" a decision was (or is about to be) shown since it started, so its summary does not replace it. */ +export function decisionToaster(show: (toast: DecisionToast) => void, windowMs = 300, now = () => Date.now()) { + let queue: Shown[] = [] + let timer: ReturnType | undefined + let lastShown = Number.NEGATIVE_INFINITY + const flush = () => { + timer = undefined + const toast = combinedToast(queue.splice(0)) + if (!toast) return + lastShown = now() + show(toast) + } + return { + push(decision: Shown) { + queue.push(decision) + if (timer === undefined) { + timer = setTimeout(flush, windowMs) + timer.unref?.() + } + }, + flush, + shownSince: (since: number) => queue.some((d) => decisionToast(d) !== undefined) || lastShown >= since, + dispose() { + if (timer !== undefined) clearTimeout(timer) + timer = undefined + queue = [] + }, + } +} + +const toasters = new WeakMap>() +/** This TUI's one decision toaster: shared by the notices and "Sync now". */ +function toasterOf(api: TuiPluginApi) { + let toaster = toasters.get(api) + if (!toaster) { + toaster = decisionToaster((toast) => api.ui.toast(toast)) + toasters.set(api, toaster) + } + return toaster +} + +/** Drops this TUI's toaster: nothing held is shown after the plugin goes away, and a later one starts fresh. */ +function disposeToaster(api: TuiPluginApi) { + toasters.get(api)?.dispose() + toasters.delete(api) } async function showMenu(api: TuiPluginApi) { @@ -611,10 +701,13 @@ async function showMenu(api: TuiPluginApi) { if (option.value === "sync" || option.value === "toggle" || option.value === "follow") api.ui.dialog.clear() if (option.value === "sync") { api.ui.toast({ variant: "info", message: "Syncing rules…", duration: 3000 }) + const started = Date.now() const report = await post<{ ok: boolean; error?: string; pull?: { ok: boolean; rules: number; pending: number; error?: string; notices: unknown[] }; push?: { sent: unknown[]; queued?: number; error?: string }; context?: { status: string; reason?: string } }>(api, "/altimate/rules/sync").catch(() => undefined) // A review notice from this pull is its own toast: the success summary would cover it, but a problem (proposals // kept queued, a failed pull) is still said. - const reviewed = !!report?.pull?.notices.length + // A skill or knowledge decision this sync found arrives as an event, not in `pull.notices`: the TUI shows one + // toast at a time, so the summary must not replace it either. + const reviewed = !!report?.pull?.notices.length || toasterOf(api).shownSince(started) if (report?.context && report.context.status !== "ready") api.ui.toast({ variant: "warning", message: `Rules sync skipped: ${printable(report.context.reason ?? report.context.status)}.`, duration: 8000 }) else if (report?.pull?.ok && report.push?.error) diff --git a/packages/opencode/test/cli/tui/rules-requests.test.ts b/packages/opencode/test/cli/tui/rules-requests.test.ts index 75a2a8b0b9..07a1887546 100644 --- a/packages/opencode/test/cli/tui/rules-requests.test.ts +++ b/packages/opencode/test/cli/tui/rules-requests.test.ts @@ -3,7 +3,7 @@ // The `/rules` menu's pure helpers: how a shown decision is remembered, and why the skill and knowledge part is missing // or short. import { describe, expect, test } from "bun:test" -import { requestsProblem, shownKey } from "../../../src/plugin/tui/altimate/rules" +import { combinedToast, decisionToast, decisionToaster, requestsProblem, shownKey } from "../../../src/plugin/tui/altimate/rules" describe("rules TUI", () => { test("a decision is remembered by kind, id and status: a rule and a skill with one id do not hide each other", () => { @@ -25,4 +25,59 @@ describe("rules TUI", () => { expect(requestsProblem({ ok: true, review_status: "not_linked" })).toBeUndefined() expect(requestsProblem({ ok: true, review_status: "unsupported" })).toBeUndefined() }) + + const approved = { kind: "skill" as const, public_id: "a", text: "cost-guard", status: "active", reviewer: "Olive" } + const rejected = { kind: "knowledge" as const, public_id: "b", text: "Glossary", status: "rejected", reviewer: "Olive", reason: "Too broad" } + + test("one decision reads as before; a rule status this version does not show makes no toast", () => { + expect(decisionToast(approved)).toEqual({ + variant: "success", + message: 'Your skill "cost-guard" was approved by Olive. It now reaches the workspace.', + duration: 10000, + }) + expect(decisionToast(rejected)?.message).toBe('Your knowledge base "Glossary" was rejected by Olive — Too broad') + expect(decisionToast({ public_id: "r", text: "x", status: "superseded" })).toBeUndefined() + expect(combinedToast([approved])).toEqual(decisionToast(approved)) + expect(combinedToast([])).toBeUndefined() + }) + + test("decisions that arrive together are one toast, a warning when any is a rejection or a removal", () => { + expect(combinedToast([approved, rejected])).toEqual({ + variant: "warning", + message: '2 decisions on your requests: skill "cost-guard" approved by Olive · knowledge base "Glossary" rejected by Olive — Too broad', + duration: 15000, + }) + const removed = { ...approved, public_id: "c", status: "retired", reason: "Old" } + expect(combinedToast([approved, removed])?.message).toContain('skill "cost-guard" removed by Olive — Old') + expect(combinedToast([approved, { ...approved, public_id: "d", text: "naming" }])?.variant).toBe("success") + // Many at once (a TUI that was closed): five are named, the rest counted. + const many = Array.from({ length: 8 }, (_, i) => ({ ...approved, public_id: `m${i}`, text: `skill-${i}` })) + const message = combinedToast(many)!.message + expect(message.startsWith("8 decisions on your requests: ")).toBe(true) + expect(message).toContain('skill "skill-4" approved') + expect(message).not.toContain("skill-5") + expect(message.endsWith(" · and 3 more (see /rules)")).toBe(true) + }) + + test("the toaster shows decisions held together once, and tells Sync now one was shown since it started", () => { + const shown: string[] = [] + let clock = 1000 + const toaster = decisionToaster((t) => shown.push(t.message), 60_000, () => clock) + expect(toaster.shownSince(0)).toBe(false) + toaster.push(approved) + toaster.push(rejected) + // Held, not yet shown: Sync now must still not cover it with its summary. + expect(toaster.shownSince(1000)).toBe(true) + toaster.flush() + expect(shown).toEqual([combinedToast([approved, rejected])!.message]) + expect(toaster.shownSince(1000)).toBe(true) + clock = 2000 + expect(toaster.shownSince(1500)).toBe(false) + // Only a status with no toast: nothing shown, nothing claimed. + toaster.push({ public_id: "r", text: "x", status: "superseded" }) + expect(toaster.shownSince(1500)).toBe(false) + toaster.flush() + expect(shown).toHaveLength(1) + toaster.dispose() + }) }) From 639b466f979f856fe950f2edaf48e68c8cad172e Mon Sep 17 00:00:00 2001 From: Sarav Date: Mon, 16 Nov 2026 09:05:14 +0530 Subject: [PATCH 2/7] feat: "what changed" in the linked workspace, once when a session starts - `workspace-activity.ts`: reads altimate-backend's `GET /datamates/{id}/activity` (skills and knowledge added, updated or removed, last 30 days) and builds one line: "Since your last session in Growth: 2 skills added (naming, cost-guard), 1 knowledge base removed (Glossary)." Each client keeps its own last look per server, tenant, account and workspace in the person's state directory (`workspace-activity/`); the mark is the newest change's server time, so a skewed clock cannot hide or repeat a change. The first look records where to start and says nothing. - `GET /altimate/workspace/activity?host=` for the IDE extension. - TUI: shows the line a few seconds after startup, after the review-decision replay, and waits while a decision toast is up (one toast at a time). - `review-requests.context` is exported for it (the linked workspace with one captured credential). - Docs: `usage/cli.md`. Co-Authored-By: Claude Opus 5.5 --- docs/docs/usage/cli.md | 1 + .../src/altimate/workspace/review-requests.ts | 2 +- .../altimate/workspace/workspace-activity.ts | 171 ++++++++++++++++++ .../src/plugin/tui/altimate/rules.tsx | 29 +++ packages/opencode/src/server/server.ts | 20 ++ .../workspace/workspace-activity.test.ts | 152 ++++++++++++++++ 6 files changed, 374 insertions(+), 1 deletion(-) create mode 100644 packages/opencode/src/altimate/workspace/workspace-activity.ts create mode 100644 packages/opencode/test/altimate/workspace/workspace-activity.test.ts diff --git a/docs/docs/usage/cli.md b/docs/docs/usage/cli.md index 5439457d0e..54fcdd19e7 100644 --- a/docs/docs/usage/cli.md +++ b/docs/docs/usage/cli.md @@ -68,6 +68,7 @@ With workspaces on: - In a project linked to a workspace, integrations come only from the workspace's engine, so the `datamate_manager` tool is not offered there and refuses to run. `datamate-*` MCP servers already in the config still load, and a one-time notice names the file they are in; the config is not edited. - `altimate-code skill publish ` uploads a project skill to the linked workspace, attached directly for the workspace owner or an admin and sent for review for a member when review is on; see [Skills](../configure/skills.md#cli-commands). - When the owner or an admin approves or rejects one of your skill or knowledge base requests that altimate-code has seen pending (submitted from it, or listed by an earlier check), or that is decided after it began checking, the TUI shows a notice once in each project linked to that workspace, with the reason for a rejection. Every altimate-code process that opens a linked project checks at start and every 5 minutes while workspaces are on and you are signed in: it lists your own requests on the workspace (up to 10 pages of 50); a server without review is asked again only after 6 hours. The decision is kept per account and workspace in your own state directory (`$XDG_STATE_HOME/altimate-code/workspace-reviews/`, the 50 most recent), so a TUI that was closed or disconnected when it arrived shows it when it next starts. The first time a TUI opens a project, decisions already kept are recorded without a notice; `altimate-code workspace review status` lists them. Withdrawing a waiting request and removing an approved one happen in the web app or from `/rules` in the TUI, which lists your skill and knowledge requests with your rule proposals. Editor and agent plugins read decisions with `altimate-code workspace review decisions --json` (see [Skills](../configure/skills.md#cli-commands)), which always prints one JSON object and exits 0. When the owner or an admin removes one of yours that altimate-code has seen approved or waiting (up to the 200 approved ones it tracks per workspace), the TUI shows that once too, with the reason; your own removal and withdrawal show nothing. +- A few seconds after the TUI starts in a linked project, it says in one line what changed in the skills and knowledge the workspace gives its team since you last looked, for example "Since your last session in Growth: 2 skills added (naming, cost-guard), 1 knowledge base removed (Glossary)." It reads the workspace's recent changes (the last 30 days) and keeps when you last looked per account, workspace and client in your own state directory (`$XDG_STATE_HOME/altimate-code/workspace-activity/`); the first time it only records where to start from. It waits while a review decision notice is showing. The VS Code extension asks `altimate-code serve` for the same line (`GET /altimate/workspace/activity?host=vscode`), with its own last look. Changes the service does not record (the owner detaching their own skill, the owner's knowledge selection) are not listed. - Workspace skills are synced at the version the workspace serves you: the approved version, or your own pending version of a skill you submitted. The next sync follows what the workspace serves: a skill whose first submission is rejected, or that is detached from the workspace, is removed from the project; when an update to an approved skill is rejected or replaced, the skill stays at its approved version. Each skill is downloaded as one version: if it is approved or rejected while its files are being read, nothing of it is installed from that sync and it is fetched again on the next one. When a download fails, the copy already in the project is kept only if it is still the version the workspace serves, as far as the server has said (its list, or a read refused because the version just changed), or if neither the copy nor the list names a version (a copy synced before revisions, or an older server), in which case it is kept until the server says otherwise; a copy of a version it no longer serves (for example your rejected pending version), or of a skill it no longer lists, is removed until the download succeeds, even when no other skill could be downloaded. Two processes syncing the same project take turns: a sync never replaces or removes a snapshot another process installed after it started, and the next sync starts from the newer one. - When the linked workspace has knowledge, the agent is told to check it for best practices and team conventions before answering, without you having to mention the knowledge base. - In an ordinary session the agent is told every turn which workspace the project is linked to — or that none is, or that the link could not be verified just now. In an extension-pinned session it is told the pinned workspace instead, and that it differs from the project's own link. Either way "which workspace am I in?" has an answer, and the agent is told not to confuse it with a Databricks workspace or an IDE workspace folder. diff --git a/packages/opencode/src/altimate/workspace/review-requests.ts b/packages/opencode/src/altimate/workspace/review-requests.ts index 42a1ea4eea..3e855af05d 100644 --- a/packages/opencode/src/altimate/workspace/review-requests.ts +++ b/packages/opencode/src/altimate/workspace/review-requests.ts @@ -140,7 +140,7 @@ export async function act( } /** The workspace the project is linked to, with one captured credential that is still the one signed in. */ -async function context( +export async function context( directory: string, ): Promise< | { ready: false; status: "signed_out" | "not_linked" | "account_changed" | "unconfirmed" } diff --git a/packages/opencode/src/altimate/workspace/workspace-activity.ts b/packages/opencode/src/altimate/workspace/workspace-activity.ts new file mode 100644 index 0000000000..268f0a4668 --- /dev/null +++ b/packages/opencode/src/altimate/workspace/workspace-activity.ts @@ -0,0 +1,171 @@ +// altimate_change - new file +// +// "What changed" for everyone on a workspace: the skills and knowledge added to, updated in or removed from what the +// workspace gives its team since this person last looked, as one line a client shows when a session starts (the TUI; +// the IDE extension through `GET /altimate/workspace/activity`). Read from altimate-backend's +// `GET /datamates/{id}/activity`, which only lists what is already recorded and looks back at most 30 days. +// +// Each client (`host`) keeps its own last look, per server, tenant, account and workspace, in the person's own state +// directory (`/workspace-activity/.json`), never in a repository. The first look records where to start +// from and says nothing: what happened before is history, not news (as review decisions are treated). The mark is the +// newest change's own server time, so a clock that is off cannot hide a change or show one twice. +import { createHash, randomUUID } from "node:crypto" +import fs from "node:fs/promises" +import path from "node:path" +import z from "zod" +import { Global } from "@/global" +import { Flock } from "@opencode-ai/core/util/flock" +import { classify } from "../rules/api" +import { printable } from "../rules/printable" +import { altimateRequest, type ActAs } from "./api-client" + +/** How many changes one look reads. */ +export const LIMIT = 20 +/** How many names the line gives for one kind of change. */ +const NAMED = 3 + +export const Item = z.object({ + kind: z.enum(["skill", "knowledge"]), + name: z.string(), + action: z.enum(["added", "updated", "removed"]), + actor_name: z.string().nullable().optional(), + at: z.string(), +}) +export type Item = z.infer + +const Activity = z.object({ items: z.array(z.unknown()), has_more: z.boolean().default(false) }) + +/** Changes after `since` (all of the last 30 days without it), newest first. A row this version cannot read is + * skipped. Throws a classified `RulesApiError`. */ +export async function fetchActivity(datamateId: number, since: string | undefined, actAs: ActAs, limit = LIMIT) { + try { + const raw = await altimateRequest("GET", `/${datamateId}/activity`, { + base: "/datamates", + actAs, + query: { limit: String(limit), ...(since ? { since } : {}) }, + }) + const page = Activity.parse(raw) + const items = page.items.flatMap((row) => { + const parsed = Item.safeParse(row) + return parsed.success ? [parsed.data] : [] + }) + return { items, hasMore: page.has_more } + } catch (error) { + throw classify(error, "reviews_not_available") + } +} + +const Seen = z.object({ + version: z.literal(1), + scope: z.object({ apiUrl: z.string(), tenant: z.string(), account: z.string(), datamateId: z.number() }), + /** Per client: the server time of the newest change it was given; "" when it first looked at an empty window. */ + seen: z.record(z.string(), z.string()).default({}), +}) +type Seen = z.infer +type Scope = Seen["scope"] + +/** Where each client's last look is kept. */ +export const dir = () => path.join(Global.Path.state, "workspace-activity") +const fileOf = (scope: Scope) => + path.join( + dir(), + createHash("sha256").update(JSON.stringify([scope.apiUrl, scope.tenant, scope.account, scope.datamateId])).digest("hex") + + ".json", + ) + +async function readSeen(scope: Scope): Promise { + const raw = await fs.readFile(fileOf(scope), "utf8").catch(() => undefined) + if (raw !== undefined) { + try { + const state = Seen.parse(JSON.parse(raw)) + if (JSON.stringify(state.scope) === JSON.stringify(scope)) return state + } catch {} + } + return { version: 1, scope, seen: {} } +} + +async function writeSeen(state: Seen): Promise { + const file = fileOf(state.scope) + await fs.mkdir(path.dirname(file), { recursive: true, mode: 0o700 }) + const tmp = `${file}.${process.pid}.${randomUUID()}.tmp` + try { + await fs.writeFile(tmp, JSON.stringify(state, null, 2) + "\n", { mode: 0o600, flag: "wx" }) + await fs.rename(tmp, file) + } catch (error) { + await fs.rm(tmp, { force: true }).catch(() => {}) + throw error + } +} + +const plural = (n: number, kind: Item["kind"]) => + `${n} ${kind === "skill" ? (n === 1 ? "skill" : "skills") : n === 1 ? "knowledge base" : "knowledge bases"}` + +/** The one line: "Since your last session in X: 2 skills added (a, b), 1 knowledge base removed (c)." Several changes + * to one item count once per kind of change; the newest come first. Text is made printable. */ +export function summaryLine(workspaceName: string, items: Item[], hasMore = false): string | undefined { + if (items.length === 0) return undefined + const groups = new Map() + for (const item of items) { + const key = `${item.kind}:${item.action}` + const group = groups.get(key) ?? { kind: item.kind, action: item.action, names: [] } + const name = printable(item.name) + if (!group.names.includes(name)) group.names.push(name) + groups.set(key, group) + } + const parts = [...groups.values()].map(({ kind, action, names }) => { + const shown = names.slice(0, NAMED).join(", ") + const more = names.length > NAMED ? `, and ${names.length - NAMED} more` : "" + return `${plural(names.length, kind)} ${action} (${shown}${more})` + }) + return `Since your last session in ${printable(workspaceName)}: ${parts.join(", ")}${hasMore ? ", and more" : ""}.` +} + +export type Changes = + | { status: "ok"; workspace: { id: number; name: string }; items: Item[]; line?: string } + /** First look for this client: where to start from is recorded, nothing is said. */ + | { status: "first"; workspace: { id: number; name: string } } + | { status: "signed_out" | "not_linked" | "account_changed" | "unconfirmed" | "unsupported" } + | { status: "failed"; error: string } + +/** What changed on the project's workspace since `host` last looked, and mark it seen. Never throws. */ +export async function changesSince(directory: string, host: string): Promise { + try { + const { context } = await import("./review-requests") + const ctx = await context(directory) + if (!ctx.ready) return { status: ctx.status } + const { RulesSync } = await import("../rules/sync") + const account = await RulesSync.accountOf(ctx.actAs) + if (!account) return { status: "account_changed" } + const scope: Scope = { + apiUrl: ctx.actAs.url.replace(/\/+$/, ""), + tenant: ctx.actAs.instance, + account, + datamateId: ctx.datamateId, + } + const workspace = { id: ctx.datamateId, name: ctx.name } + await fs.mkdir(dir(), { recursive: true, mode: 0o700 }) + return await Flock.withLock( + `workspace-activity:${path.basename(fileOf(scope))}`, + async (): Promise => { + const state = await readSeen(scope) + // Undefined: never looked. "": looked when nothing had changed in the window, so everything listed since is + // new (no local clock is involved). Otherwise the newest change it was given. + const since = state.seen[host] + const first = since === undefined + const { items, hasMore } = await fetchActivity(ctx.datamateId, since || undefined, ctx.actAs, first ? 1 : LIMIT) + const mark = items[0]?.at ?? since ?? "" + if (mark !== since) await writeSeen({ ...state, seen: { ...state.seen, [host]: mark } }) + if (first) return { status: "first", workspace } + const line = summaryLine(workspace.name, items, hasMore) + return { status: "ok", workspace, items, ...(line ? { line } : {}) } + }, + { dir: dir(), staleMs: 60_000, timeoutMs: 5_000 }, + ) + } catch (error) { + const { ReviewApi } = await import("./review-api") + if (ReviewApi.unavailable(error)) return { status: "unsupported" } + return { status: "failed", error: printable(error instanceof Error ? error.message : String(error)) } + } +} + +export * as WorkspaceActivity from "./workspace-activity" diff --git a/packages/opencode/src/plugin/tui/altimate/rules.tsx b/packages/opencode/src/plugin/tui/altimate/rules.tsx index 5a1e37077d..e6b519a4eb 100644 --- a/packages/opencode/src/plugin/tui/altimate/rules.tsx +++ b/packages/opencode/src/plugin/tui/altimate/rules.tsx @@ -501,10 +501,33 @@ function installCards(api: TuiPluginApi) { replay() void load() }, 4_000) + // altimate_change start — workspace activity: what changed in the workspace since this TUI last looked, once, after + // the startup replay. The TUI shows one toast at a time, so it waits while a decision toast is still up. + let activityTimer: ReturnType | undefined + const showActivity = async () => { + if (disposed) return + const answer = await get<{ ok: boolean; status?: string; line?: string }>(api, "/altimate/workspace/activity?host=tui") + if (disposed || typeof answer?.line !== "string") return + const line = printable(answer.line) + const announce = (tries: number) => { + if (disposed) return + if (tries < ACTIVITY_WAITS && toasterOf(api).shownSince(Date.now() - DECISION_TOAST_MS)) { + activityTimer = setTimeout(() => announce(tries + 1), ACTIVITY_RETRY_MS) + activityTimer.unref?.() + return + } + api.ui.toast({ variant: "info", message: line, duration: 12_000 }) + } + announce(0) + } + activityTimer = setTimeout(() => void showActivity(), 6_000) + activityTimer.unref?.() + // altimate_change end api.lifecycle?.onDispose?.(() => { disposed = true if (leaseTimer) clearTimeout(leaseTimer) clearTimeout(startup) + if (activityTimer) clearTimeout(activityTimer) disposeToaster(api) for (const off of offs.splice(0)) off() disposeEffects() @@ -549,6 +572,12 @@ export function decisionToast(raw: Shown): DecisionToast | undefined { return undefined } +/** The longest a decision toast stays up: the activity line waits for it. */ +const DECISION_TOAST_MS = 15_000 +const ACTIVITY_RETRY_MS = 5_000 +/** How many times the activity line waits for a decision toast before showing anyway. */ +const ACTIVITY_WAITS = 4 + /** How many decisions a combined toast names. */ const COMBINED_NAMED = 5 diff --git a/packages/opencode/src/server/server.ts b/packages/opencode/src/server/server.ts index 7d4365d60c..6d2c37c923 100644 --- a/packages/opencode/src/server/server.ts +++ b/packages/opencode/src/server/server.ts @@ -1460,6 +1460,26 @@ export namespace Server { return c.json({ ok: false, error }, 500) } }) + // altimate_change start — workspace activity: what changed in the workspace's skills and knowledge since this + // client (`host`) last looked, as one line to show when a session starts. Marks it seen; the first look says nothing. + .get("/altimate/workspace/activity", async (c) => { + const refused = workspaceRouteRefusal(c.req.header("origin"), c.req.header("host"), undefined, c.req.header("sec-fetch-site")) + if (refused) return c.json(refused.body, refused.status) + const host = c.req.query("host") ?? "" + if (!/^[a-z][a-z0-9-]{0,31}$/.test(host)) return c.json({ ok: false, error: "host must name the client, e.g. vscode." }, 400) + try { + const { WorkspaceActivity } = await import("../altimate/workspace/workspace-activity") + const changes = await WorkspaceActivity.changesSince(Instance.directory, host) + // `status`: ok, first (nothing said the first time), signed_out, not_linked, account_changed, unconfirmed, + // unsupported, failed. + return c.json({ ok: true as const, ...changes }) + } catch (err) { + const error = err instanceof Error ? err.message : String(err) + log.error("workspace activity failed", { error }) + return c.json({ ok: false, error }, 500) + } + }) + // altimate_change end .post("/altimate/workspace/requests/:id/:action", async (c) => { const refused = workspaceRouteRefusal(c.req.header("origin"), c.req.header("host"), undefined, c.req.header("sec-fetch-site")) if (refused) return c.json(refused.body, refused.status) diff --git a/packages/opencode/test/altimate/workspace/workspace-activity.test.ts b/packages/opencode/test/altimate/workspace/workspace-activity.test.ts new file mode 100644 index 0000000000..83e75aca9c --- /dev/null +++ b/packages/opencode/test/altimate/workspace/workspace-activity.test.ts @@ -0,0 +1,152 @@ +// altimate_change - new file +// +// "What changed" for everyone on a workspace (`workspace-activity.ts`): the line a client shows when a session starts, +// and each client's own last look. Network is stubbed at `globalThis.fetch`; files are real, in a sandbox state +// directory. +import { afterAll, afterEach, beforeEach, describe, expect, test } from "bun:test" +import { mkdirSync, mkdtempSync, rmSync } from "node:fs" +import os from "node:os" +import path from "node:path" + +const ORIGINAL_XDG_STATE_HOME = process.env.XDG_STATE_HOME +const SANDBOX = mkdtempSync(path.join(os.tmpdir(), "altimate-activity-")) +mkdirSync(path.join(SANDBOX, "state"), { recursive: true }) +process.env.XDG_STATE_HOME = path.join(SANDBOX, "state") + +const { AltimateApi } = await import("../../../src/altimate/api/client") +const { WorkspaceActivity } = await import("../../../src/altimate/workspace/workspace-activity") +const { recordApprovedBinding } = await import("../../../src/altimate/workspace/state") + +type Creds = Awaited> +const originalIsConfigured = AltimateApi.isConfigured +const originalGetCreds = AltimateApi.getCredentials +const originalFetch = globalThis.fetch +const API = "https://api.example.com" +let configured = true +;(AltimateApi as unknown as { isConfigured: () => Promise }).isConfigured = async () => configured +;(AltimateApi as unknown as { getCredentials: () => Promise }).getCredentials = async () => + ({ altimateInstanceName: "acme", altimateUrl: API, altimateApiKey: "k" }) as Creds + +const reply = (body: unknown, status = 200) => + new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } }) +const change = (name: string, action: string, at: string, kind = "skill") => ({ + kind, + name, + action, + actor_name: "Ada", + at, +}) + +/** The `since` each activity request sent (undefined: none), and the answer it gets. */ +let asked: (string | undefined)[] = [] +let activity: (since: string | undefined) => Response = () => reply({ items: [], has_more: false }) +let project = "" + +beforeEach(async () => { + configured = true + asked = [] + activity = () => reply({ items: [], has_more: false }) + rmSync(WorkspaceActivity.dir(), { recursive: true, force: true }) + project = mkdtempSync(path.join(SANDBOX, "proj-")) + globalThis.fetch = (async (input: any) => { + const url = new URL(typeof input === "string" ? input : input.url) + if (url.pathname.endsWith("/users/me")) return reply({ id: 7 }) + if (url.pathname.endsWith("/datamates/42/activity")) { + const since = url.searchParams.get("since") ?? undefined + asked.push(since) + return activity(since) + } + return reply({ items: [], total: 0, page: 1, size: 50, pages: 1 }) + }) as typeof fetch + await recordApprovedBinding( + project, + { datamateId: 42, datamateName: "Growth", repoRemote: null, projectPath: project, linkedAt: Date.now() } as never, + { awaitBackfill: true }, + ) +}) + +afterEach(() => { + globalThis.fetch = originalFetch +}) + +afterAll(() => { + ;(AltimateApi as unknown as { isConfigured: typeof originalIsConfigured }).isConfigured = originalIsConfigured + ;(AltimateApi as unknown as { getCredentials: typeof originalGetCreds }).getCredentials = originalGetCreds + if (ORIGINAL_XDG_STATE_HOME === undefined) delete process.env.XDG_STATE_HOME + else process.env.XDG_STATE_HOME = ORIGINAL_XDG_STATE_HOME + rmSync(SANDBOX, { recursive: true, force: true }) +}) + +describe("what changed since this client last looked", () => { + test("the first look says nothing; the next one says what changed after the newest change it saw", async () => { + activity = () => reply({ items: [change("old", "added", "2026-11-10T00:00:00Z")], has_more: true }) + expect(await WorkspaceActivity.changesSince(project, "tui")).toEqual({ + status: "first", + workspace: { id: 42, name: "Growth" }, + }) + activity = (since) => + reply({ + items: since + ? [ + change("cost-guard", "removed", "2026-11-12T00:00:00Z"), + change("naming", "added", "2026-11-11T00:00:00Z"), + change("glossary", "added", "2026-11-11T00:00:00Z", "knowledge"), + ] + : [], + has_more: false, + }) + const next = await WorkspaceActivity.changesSince(project, "tui") + expect(asked).toEqual([undefined, "2026-11-10T00:00:00Z"]) + expect(next.status === "ok" && next.line).toBe( + "Since your last session in Growth: 1 skill removed (cost-guard), 1 skill added (naming), 1 knowledge base added (glossary).", + ) + // Nothing newer: nothing to say, and the mark stays on the newest change seen. + activity = () => reply({ items: [], has_more: false }) + const quiet = await WorkspaceActivity.changesSince(project, "tui") + expect(quiet).toEqual({ status: "ok", workspace: { id: 42, name: "Growth" }, items: [] }) + expect(asked[2]).toBe("2026-11-12T00:00:00Z") + }) + + test("a first look at an empty window records no clock time: what comes later is all new", async () => { + expect((await WorkspaceActivity.changesSince(project, "tui")).status).toBe("first") + activity = () => reply({ items: [change("naming", "added", "2026-11-11T00:00:00Z")], has_more: false }) + const next = await WorkspaceActivity.changesSince(project, "tui") + // No `since`: the whole window is after the empty first look. + expect(asked).toEqual([undefined, undefined]) + expect(next.status === "ok" && next.line).toBe("Since your last session in Growth: 1 skill added (naming).") + }) + + test("each client keeps its own last look", async () => { + activity = () => reply({ items: [change("a", "added", "2026-11-10T00:00:00Z")], has_more: false }) + expect((await WorkspaceActivity.changesSince(project, "tui")).status).toBe("first") + expect((await WorkspaceActivity.changesSince(project, "vscode")).status).toBe("first") + expect((await WorkspaceActivity.changesSince(project, "tui")).status).toBe("ok") + }) + + test("a server without the route, and a signed-out person, say why", async () => { + activity = () => reply({ detail: "Not Found" }, 404) + expect((await WorkspaceActivity.changesSince(project, "tui")).status).toBe("unsupported") + configured = false + expect((await WorkspaceActivity.changesSince(project, "tui")).status).toBe("signed_out") + }) +}) + +describe("the line", () => { + test("groups by kind of change, names a few, and counts an item changed twice once", () => { + const items = [ + change("a", "added", "6"), + change("b", "added", "5"), + change("c", "added", "4"), + change("d", "added", "3"), + change("a", "added", "2"), + change("x", "updated", "1"), + ] as never + expect(WorkspaceActivity.summaryLine("Growth", items)).toBe( + "Since your last session in Growth: 4 skills added (a, b, c, and 1 more), 1 skill updated (x).", + ) + expect(WorkspaceActivity.summaryLine("Growth", [], true)).toBeUndefined() + expect(WorkspaceActivity.summaryLine("Gro\u001b[1mwth", [change("e", "removed", "1")] as never, true)).toBe( + "Since your last session in Gro [1mwth: 1 skill removed (e), and more.", + ) + }) +}) From 93e27044b5948fd6fc6006223bbc001e6bd1c7a1 Mon Sep 17 00:00:00 2001 From: Sarav Date: Tue, 17 Nov 2026 13:24:37 +0530 Subject: [PATCH 3/7] fix: workspace activity: overlap, honest counts, shown before seen - each look asks again from 5 minutes before the mark and drops changes it already reported, by the id the server now gives each one, so a change that commits late behind the mark is still reported; a server without ids is asked from the mark itself, as before (old string marks are read) - with more changes than one look reads (now 50), the line says there were more and names the newest instead of giving partial counts - items are counted by the server's `subject` (by name without it); names are capped at 40 characters and the line at 300; an empty name is left out - `GET /altimate/workspace/activity?defer=1` leaves the mark until `POST /altimate/workspace/activity/seen` confirms the line was shown; the TUI uses it, so a TUI that closes first shows the line next time (the extension's plain look is unchanged) - the TUI waits for the startup replay, then for decision toasts to clear, for up to a minute; still busy, it shows nothing and the line comes next time, instead of replacing a decision toast (`announceWhenClear`) - docs: shared last look per account and workspace, the overlap, more than 50 changes, and the deferred confirmation Co-Authored-By: Claude Opus 5.5 --- docs/docs/usage/cli.md | 2 +- .../altimate/workspace/workspace-activity.ts | 212 +++++++++++++----- .../src/plugin/tui/altimate/rules.tsx | 76 +++++-- packages/opencode/src/server/server.ts | 23 +- .../workspace/workspace-activity.test.ts | 99 +++++++- .../test/cli/tui/rules-requests.test.ts | 29 ++- 6 files changed, 366 insertions(+), 75 deletions(-) diff --git a/docs/docs/usage/cli.md b/docs/docs/usage/cli.md index 54fcdd19e7..00a0e2e3a4 100644 --- a/docs/docs/usage/cli.md +++ b/docs/docs/usage/cli.md @@ -68,7 +68,7 @@ With workspaces on: - In a project linked to a workspace, integrations come only from the workspace's engine, so the `datamate_manager` tool is not offered there and refuses to run. `datamate-*` MCP servers already in the config still load, and a one-time notice names the file they are in; the config is not edited. - `altimate-code skill publish ` uploads a project skill to the linked workspace, attached directly for the workspace owner or an admin and sent for review for a member when review is on; see [Skills](../configure/skills.md#cli-commands). - When the owner or an admin approves or rejects one of your skill or knowledge base requests that altimate-code has seen pending (submitted from it, or listed by an earlier check), or that is decided after it began checking, the TUI shows a notice once in each project linked to that workspace, with the reason for a rejection. Every altimate-code process that opens a linked project checks at start and every 5 minutes while workspaces are on and you are signed in: it lists your own requests on the workspace (up to 10 pages of 50); a server without review is asked again only after 6 hours. The decision is kept per account and workspace in your own state directory (`$XDG_STATE_HOME/altimate-code/workspace-reviews/`, the 50 most recent), so a TUI that was closed or disconnected when it arrived shows it when it next starts. The first time a TUI opens a project, decisions already kept are recorded without a notice; `altimate-code workspace review status` lists them. Withdrawing a waiting request and removing an approved one happen in the web app or from `/rules` in the TUI, which lists your skill and knowledge requests with your rule proposals. Editor and agent plugins read decisions with `altimate-code workspace review decisions --json` (see [Skills](../configure/skills.md#cli-commands)), which always prints one JSON object and exits 0. When the owner or an admin removes one of yours that altimate-code has seen approved or waiting (up to the 200 approved ones it tracks per workspace), the TUI shows that once too, with the reason; your own removal and withdrawal show nothing. -- A few seconds after the TUI starts in a linked project, it says in one line what changed in the skills and knowledge the workspace gives its team since you last looked, for example "Since your last session in Growth: 2 skills added (naming, cost-guard), 1 knowledge base removed (Glossary)." It reads the workspace's recent changes (the last 30 days) and keeps when you last looked per account, workspace and client in your own state directory (`$XDG_STATE_HOME/altimate-code/workspace-activity/`); the first time it only records where to start from. It waits while a review decision notice is showing. The VS Code extension asks `altimate-code serve` for the same line (`GET /altimate/workspace/activity?host=vscode`), with its own last look. Changes the service does not record (the owner detaching their own skill, the owner's knowledge selection) are not listed. +- A few seconds after the TUI starts in a linked project, it says in one line what changed in the skills and knowledge the workspace gives its team since you last looked, for example "Since your last session in Growth: 2 skills added (naming, cost-guard), 1 knowledge base removed (Glossary)." It reads the workspace's recent changes (the last 30 days) and keeps when you last looked per account, workspace and client in your own state directory (`$XDG_STATE_HOME/altimate-code/workspace-activity/`); the first time it only records where to start from. Every TUI and project on the same account and workspace shares one last look, so whichever starts first shows the line. Each look also asks again from a few minutes before the last one, so a change that was saved late is not missed, and never repeats one it already reported. With more changes than it reads at once (50), it says there were more and names the newest instead of giving counts. It waits while a review decision notice is showing; if one is still up after a minute, or the TUI closes first, the line is shown the next time instead. The VS Code extension asks `altimate-code serve` for the same line (`GET /altimate/workspace/activity?host=vscode`), with its own last look; a client can add `defer=1` and confirm with `POST /altimate/workspace/activity/seen` once it showed the line. Changes the service does not record (the owner detaching their own skill, the owner's knowledge selection) are not listed. - Workspace skills are synced at the version the workspace serves you: the approved version, or your own pending version of a skill you submitted. The next sync follows what the workspace serves: a skill whose first submission is rejected, or that is detached from the workspace, is removed from the project; when an update to an approved skill is rejected or replaced, the skill stays at its approved version. Each skill is downloaded as one version: if it is approved or rejected while its files are being read, nothing of it is installed from that sync and it is fetched again on the next one. When a download fails, the copy already in the project is kept only if it is still the version the workspace serves, as far as the server has said (its list, or a read refused because the version just changed), or if neither the copy nor the list names a version (a copy synced before revisions, or an older server), in which case it is kept until the server says otherwise; a copy of a version it no longer serves (for example your rejected pending version), or of a skill it no longer lists, is removed until the download succeeds, even when no other skill could be downloaded. Two processes syncing the same project take turns: a sync never replaces or removes a snapshot another process installed after it started, and the next sync starts from the newer one. - When the linked workspace has knowledge, the agent is told to check it for best practices and team conventions before answering, without you having to mention the knowledge base. - In an ordinary session the agent is told every turn which workspace the project is linked to — or that none is, or that the link could not be verified just now. In an extension-pinned session it is told the pinned workspace instead, and that it differs from the project's own link. Either way "which workspace am I in?" has an answer, and the agent is told not to confuse it with a Databricks workspace or an IDE workspace folder. diff --git a/packages/opencode/src/altimate/workspace/workspace-activity.ts b/packages/opencode/src/altimate/workspace/workspace-activity.ts index 268f0a4668..f2c3bed608 100644 --- a/packages/opencode/src/altimate/workspace/workspace-activity.ts +++ b/packages/opencode/src/altimate/workspace/workspace-activity.ts @@ -8,7 +8,10 @@ // Each client (`host`) keeps its own last look, per server, tenant, account and workspace, in the person's own state // directory (`/workspace-activity/.json`), never in a repository. The first look records where to start // from and says nothing: what happened before is history, not news (as review decisions are treated). The mark is the -// newest change's own server time, so a clock that is off cannot hide a change or show one twice. +// newest change's own server time, so a local clock that is off plays no part. The server stamps a change with the time +// its transaction started, so one that commits late can land behind the mark: each look asks again from `OVERLAP_MS` +// before it and drops the changes it already reported, by the `id` the server gives each one (a server without ids is +// asked from the mark itself, as before). import { createHash, randomUUID } from "node:crypto" import fs from "node:fs/promises" import path from "node:path" @@ -19,12 +22,21 @@ import { classify } from "../rules/api" import { printable } from "../rules/printable" import { altimateRequest, type ActAs } from "./api-client" -/** How many changes one look reads. */ -export const LIMIT = 20 +/** How many changes one look reads (the server allows up to 100): room for the ones the overlap reads again. */ +export const LIMIT = 50 +/** How far behind the mark each look asks again, for changes that committed late. */ +export const OVERLAP_MS = 5 * 60_000 /** How many names the line gives for one kind of change. */ const NAMED = 3 +/** The longest name the line gives, and the longest line. */ +const NAME_MAX = 40 +const LINE_MAX = 300 export const Item = z.object({ + /** The change, stable across answers. Absent from older servers. */ + id: z.string().optional(), + /** The skill or knowledge base, stable within the workspace. Absent from older servers. */ + subject: z.string().optional(), kind: z.enum(["skill", "knowledge"]), name: z.string(), action: z.enum(["added", "updated", "removed"]), @@ -55,15 +67,54 @@ export async function fetchActivity(datamateId: number, since: string | undefine } } +/** One client's last look: the server time of the newest change it was given ("" when it first looked at an empty + * window), the ids it reported within `OVERLAP_MS` of that, and whether the server gives ids (then each look asks + * from `OVERLAP_MS` before the mark). */ +export const Mark = z.object({ + at: z.string(), + ids: z.array(z.object({ id: z.string(), at: z.string() })).default([]), + overlap: z.boolean().default(false), +}) +export type Mark = z.infer + const Seen = z.object({ version: z.literal(1), scope: z.object({ apiUrl: z.string(), tenant: z.string(), account: z.string(), datamateId: z.number() }), - /** Per client: the server time of the newest change it was given; "" when it first looked at an empty window. */ - seen: z.record(z.string(), z.string()).default({}), + /** Per client. A plain string is a mark from before ids. */ + seen: z.record(z.string(), z.union([z.string(), Mark])).default({}), }) type Seen = z.infer type Scope = Seen["scope"] +export const markOf = (value: Seen["seen"][string] | undefined): Mark | undefined => + value === undefined ? undefined : typeof value === "string" ? { at: value, ids: [], overlap: false } : value + +/** A server time in milliseconds; one without a zone is UTC, as the server keeps them. */ +const ms = (at: string) => Date.parse(/(?:[zZ]|[+-]\d\d:?\d\d)$/.test(at) ? at : `${at}Z`) + +/** The `since` a look asks from. */ +export function sinceOf(mark: Mark): string | undefined { + if (!mark.at) return undefined + if (!mark.overlap) return mark.at + const at = ms(mark.at) + return Number.isNaN(at) ? mark.at : new Date(at - OVERLAP_MS).toISOString() +} + +/** The mark after a look (or after merging two): the newest time, and the ids within `OVERLAP_MS` of it. */ +export function advance(mark: Mark | undefined, items: Pick[]): Mark { + const times = [...(mark?.at ? [mark.at] : []), ...items.map((i) => i.at)].filter((at) => !Number.isNaN(ms(at))) + const at = times.reduce((a, b) => (a && ms(a) >= ms(b) ? a : b), "") || mark?.at || "" + const floor = at ? ms(at) - OVERLAP_MS : Number.NEGATIVE_INFINITY + const ids = new Map() + for (const entry of [...(mark?.ids ?? []), ...items.flatMap((i) => (i.id ? [{ id: i.id, at: i.at }] : []))]) + if (ms(entry.at) > floor) ids.set(entry.id, entry.at) + return { + at, + ids: [...ids].map(([id, at]) => ({ id, at })).slice(-200), + overlap: (mark?.overlap ?? false) || items.some((i) => i.id !== undefined), + } +} + /** Where each client's last look is kept. */ export const dir = () => path.join(Global.Path.state, "workspace-activity") const fileOf = (scope: Scope) => @@ -100,71 +151,130 @@ async function writeSeen(state: Seen): Promise { const plural = (n: number, kind: Item["kind"]) => `${n} ${kind === "skill" ? (n === 1 ? "skill" : "skills") : n === 1 ? "knowledge base" : "knowledge bases"}` -/** The one line: "Since your last session in X: 2 skills added (a, b), 1 knowledge base removed (c)." Several changes - * to one item count once per kind of change; the newest come first. Text is made printable. */ +const cap = (text: string, max: number) => (text.length > max ? `${text.slice(0, max - 1)}…` : text) +const nameOf = (item: Item) => cap(printable(item.name).trim(), NAME_MAX) + +/** The one line: "Since your last session in X: 2 skills added (a, b), 1 knowledge base removed (c)." Items are counted + * by `subject` (by name from a server without it), so several changes to one item count once per kind of change and + * two items with one name count twice; the newest come first. With more changes than one look reads (`hasMore`) the + * counts would be partial, so the line says there were more and names the newest instead. Text is made printable, and + * names and the line are capped. */ export function summaryLine(workspaceName: string, items: Item[], hasMore = false): string | undefined { if (items.length === 0) return undefined - const groups = new Map() + const where = `Since your last session in ${cap(printable(workspaceName), NAME_MAX)}` + if (hasMore) { + const newest = items.slice(0, NAMED).map((item) => `${nameOf(item) || `a ${item.kind === "skill" ? "skill" : "knowledge base"}`} ${item.action}`) + return cap(`${where}: more than ${items.length} ${items.length === 1 ? "change" : "changes"} to its skills and knowledge; the newest: ${newest.join(", ")}.`, LINE_MAX) + } + const groups = new Map; names: string[] }>() for (const item of items) { const key = `${item.kind}:${item.action}` - const group = groups.get(key) ?? { kind: item.kind, action: item.action, names: [] } - const name = printable(item.name) - if (!group.names.includes(name)) group.names.push(name) + const group = groups.get(key) ?? { kind: item.kind, action: item.action, subjects: new Set(), names: [] } + const name = nameOf(item) + group.subjects.add(item.subject ?? `name:${name}`) + if (name && !group.names.includes(name)) group.names.push(name) groups.set(key, group) } - const parts = [...groups.values()].map(({ kind, action, names }) => { + const parts = [...groups.values()].map(({ kind, action, subjects, names }) => { const shown = names.slice(0, NAMED).join(", ") const more = names.length > NAMED ? `, and ${names.length - NAMED} more` : "" - return `${plural(names.length, kind)} ${action} (${shown}${more})` + return `${plural(subjects.size, kind)} ${action}${names.length ? ` (${shown}${more})` : ""}` }) - return `Since your last session in ${printable(workspaceName)}: ${parts.join(", ")}${hasMore ? ", and more" : ""}.` + return cap(`${where}: ${parts.join(", ")}.`, LINE_MAX) } export type Changes = - | { status: "ok"; workspace: { id: number; name: string }; items: Item[]; line?: string } + /** `seen`: with `defer`, the mark to hand back to `acknowledge` once the line was shown. */ + | { status: "ok"; workspace: { id: number; name: string }; items: Item[]; line?: string; seen?: Mark } /** First look for this client: where to start from is recorded, nothing is said. */ | { status: "first"; workspace: { id: number; name: string } } | { status: "signed_out" | "not_linked" | "account_changed" | "unconfirmed" | "unsupported" } | { status: "failed"; error: string } -/** What changed on the project's workspace since `host` last looked, and mark it seen. Never throws. */ -export async function changesSince(directory: string, host: string): Promise { +type Located = + | { ok: true; scope: Scope; workspace: { id: number; name: string }; actAs: ActAs } + | { ok: false; changes: Changes } + +/** The project's workspace and whose look this is. */ +async function locate(directory: string): Promise { + const { context } = await import("./review-requests") + const ctx = await context(directory) + if (!ctx.ready) return { ok: false, changes: { status: ctx.status } } + const { RulesSync } = await import("../rules/sync") + const account = await RulesSync.accountOf(ctx.actAs) + if (!account) return { ok: false, changes: { status: "account_changed" } } + const scope: Scope = { + apiUrl: ctx.actAs.url.replace(/\/+$/, ""), + tenant: ctx.actAs.instance, + account, + datamateId: ctx.datamateId, + } + return { ok: true, scope, workspace: { id: ctx.datamateId, name: ctx.name }, actAs: ctx.actAs } +} + +async function locked(scope: Scope, run: () => Promise): Promise { + await fs.mkdir(dir(), { recursive: true, mode: 0o700 }) + return Flock.withLock(`workspace-activity:${path.basename(fileOf(scope))}`, run, { + dir: dir(), + staleMs: 60_000, + timeoutMs: 5_000, + }) +} + +async function failure(error: unknown): Promise { + const { ReviewApi } = await import("./review-api") + if (ReviewApi.unavailable(error)) return { status: "unsupported" } + return { status: "failed", error: printable(error instanceof Error ? error.message : String(error)) } +} + +/** What changed on the project's workspace since `host` last looked, and mark it seen. With `defer`, a look that has + * a line to show leaves the mark where it was and returns the next one as `seen`, for `acknowledge` once the line was + * shown: a client that goes away first shows it next time. Never throws. */ +export async function changesSince(directory: string, host: string, options: { defer?: boolean } = {}): Promise { try { - const { context } = await import("./review-requests") - const ctx = await context(directory) - if (!ctx.ready) return { status: ctx.status } - const { RulesSync } = await import("../rules/sync") - const account = await RulesSync.accountOf(ctx.actAs) - if (!account) return { status: "account_changed" } - const scope: Scope = { - apiUrl: ctx.actAs.url.replace(/\/+$/, ""), - tenant: ctx.actAs.instance, - account, - datamateId: ctx.datamateId, - } - const workspace = { id: ctx.datamateId, name: ctx.name } - await fs.mkdir(dir(), { recursive: true, mode: 0o700 }) - return await Flock.withLock( - `workspace-activity:${path.basename(fileOf(scope))}`, - async (): Promise => { - const state = await readSeen(scope) - // Undefined: never looked. "": looked when nothing had changed in the window, so everything listed since is - // new (no local clock is involved). Otherwise the newest change it was given. - const since = state.seen[host] - const first = since === undefined - const { items, hasMore } = await fetchActivity(ctx.datamateId, since || undefined, ctx.actAs, first ? 1 : LIMIT) - const mark = items[0]?.at ?? since ?? "" - if (mark !== since) await writeSeen({ ...state, seen: { ...state.seen, [host]: mark } }) - if (first) return { status: "first", workspace } - const line = summaryLine(workspace.name, items, hasMore) - return { status: "ok", workspace, items, ...(line ? { line } : {}) } - }, - { dir: dir(), staleMs: 60_000, timeoutMs: 5_000 }, - ) + const where = await locate(directory) + if (!where.ok) return where.changes + const { scope, workspace, actAs } = where + return await locked(scope, async (): Promise => { + const state = await readSeen(scope) + // Undefined: never looked. "": looked when nothing had changed in the window, so everything listed since is new + // (no local clock is involved). Otherwise the newest change it was given. + const mark = markOf(state.seen[host]) + const { items, hasMore } = await fetchActivity(workspace.id, mark && sinceOf(mark), actAs, LIMIT) + const reported = new Set(mark?.ids.map((entry) => entry.id)) + const fresh = items.filter((item) => item.id === undefined || !reported.has(item.id)) + const next = advance(mark, items) + const save = () => + JSON.stringify(next) === JSON.stringify(mark) ? Promise.resolve() : writeSeen({ ...state, seen: { ...state.seen, [host]: next } }) + if (mark === undefined) { + await save() + return { status: "first", workspace } + } + const line = summaryLine(workspace.name, fresh, hasMore) + if (line && options.defer) return { status: "ok", workspace, items: fresh, line, seen: next } + await save() + return { status: "ok", workspace, items: fresh, ...(line ? { line } : {}) } + }) + } catch (error) { + return failure(error) + } +} + +/** The line from a deferred look was shown: record its mark, merged with any look since. Never throws. */ +export async function acknowledge(directory: string, host: string, seen: Mark): Promise<{ status: "ok" } | Changes> { + try { + const where = await locate(directory) + if (!where.ok) return where.changes + const { scope } = where + return await locked(scope, async () => { + const state = await readSeen(scope) + const current = markOf(state.seen[host]) + const merged = advance(current ? { ...current, overlap: current.overlap || seen.overlap } : seen, [...seen.ids, ...(seen.at ? [{ at: seen.at }] : [])]) + await writeSeen({ ...state, seen: { ...state.seen, [host]: merged } }) + return { status: "ok" as const } + }) } catch (error) { - const { ReviewApi } = await import("./review-api") - if (ReviewApi.unavailable(error)) return { status: "unsupported" } - return { status: "failed", error: printable(error instanceof Error ? error.message : String(error)) } + return failure(error) } } diff --git a/packages/opencode/src/plugin/tui/altimate/rules.tsx b/packages/opencode/src/plugin/tui/altimate/rules.tsx index cdc68c471d..96f263bf26 100644 --- a/packages/opencode/src/plugin/tui/altimate/rules.tsx +++ b/packages/opencode/src/plugin/tui/altimate/rules.tsx @@ -458,8 +458,8 @@ function installCards(api: TuiPluginApi) { } // `live`: a decision that arrived as an event before the first replay. It is news even when the replay is the scope's // first, which records what was kept before it silently. - const replay = (live?: Shown) => - void summaryOf(api).then((summary) => { + const replay = (live?: Shown): Promise => + summaryOf(api).then((summary) => { if (!summary) return scope = summary.notices_scope ?? "none" const first = api.kv.get(seenKey(), undefined) === undefined @@ -474,8 +474,8 @@ function installCards(api: TuiPluginApi) { if (live) notify(live) }) // Before the first replay this TUI does not know whose decisions they are: the replay learns it, then shows this one. - listen("rule.proposal.reviewed", (event) => (scope ? notify(event.properties) : replay(event.properties))) - listen("altimate.rules.changed", () => replay()) + listen("rule.proposal.reviewed", (event) => (scope ? notify(event.properties) : void replay(event.properties))) + listen("altimate.rules.changed", () => void replay()) // This TUI shows proposal cards: it holds the server's renderer lease for its project while it runs, renewed at the // interval the server asks for. Without a live lease, the save tools save as before cards and the after-turn check // waits. No answer (the server may still be starting): tried again in a few seconds. A refusal (workspaces off, an @@ -496,29 +496,45 @@ function installCards(api: TuiPluginApi) { void lease() // A plugin that goes away (reloaded, another server) stops renewing and stops listening, so its lease lapses. // Startup: after the session-start sync had a moment, catch up on reviews and cards from before this TUI listened. + // altimate_change start — workspace activity: the startup replay, which the activity line waits for + let replayed: () => void = () => {} + const startupReplay = new Promise((resolve) => (replayed = resolve)) + // altimate_change end const startup = setTimeout(() => { if (disposed) return - replay() + // altimate_change start — workspace activity: the activity line waits for the startup replay + void replay().finally(() => replayed()) + // altimate_change end void load() }, 4_000) // altimate_change start — workspace activity: what changed in the workspace since this TUI last looked, once, after - // the startup replay. The TUI shows one toast at a time, so it waits while a decision toast is still up. + // the startup replay (its decisions are queued for their toast first). The TUI shows one toast at a time, so the line + // waits while a decision toast is up; if one is still up after `ACTIVITY_WAIT_MS`, it is not shown. The look is + // deferred: the server moves this TUI's mark only when the line was shown, so a TUI that closes first, or gives up + // waiting, shows it next time. let activityTimer: ReturnType | undefined + const wait = (ms: number) => + new Promise((resolve) => { + activityTimer = setTimeout(resolve, ms) + activityTimer.unref?.() + }) const showActivity = async () => { + await Promise.race([startupReplay, wait(ACTIVITY_REPLAY_WAIT_MS)]) if (disposed) return - const answer = await get<{ ok: boolean; status?: string; line?: string }>(api, "/altimate/workspace/activity?host=tui") + const answer = await get<{ ok: boolean; status?: string; line?: string; seen?: unknown }>( + api, + "/altimate/workspace/activity?host=tui&defer=1", + ) if (disposed || typeof answer?.line !== "string") return const line = printable(answer.line) - const announce = (tries: number) => { - if (disposed) return - if (tries < ACTIVITY_WAITS && toasterOf(api).shownSince(Date.now() - DECISION_TOAST_MS)) { - activityTimer = setTimeout(() => announce(tries + 1), ACTIVITY_RETRY_MS) - activityTimer.unref?.() - return - } - api.ui.toast({ variant: "info", message: line, duration: 12_000 }) - } - announce(0) + const shown = await announceWhenClear({ + busy: () => toasterOf(api).shownSince(Date.now() - DECISION_TOAST_MS), + wait: () => wait(ACTIVITY_RETRY_MS), + waits: Math.ceil(ACTIVITY_WAIT_MS / ACTIVITY_RETRY_MS), + disposed: () => disposed, + show: () => api.ui.toast({ variant: "info", message: line, duration: 12_000 }), + }) + if (shown && answer.seen !== undefined) await post(api, "/altimate/workspace/activity/seen", { host: "tui", seen: answer.seen }).catch(() => undefined) } activityTimer = setTimeout(() => void showActivity(), 6_000) activityTimer.unref?.() @@ -575,8 +591,30 @@ export function decisionToast(raw: Shown): DecisionToast | undefined { /** The longest a decision toast stays up: the activity line waits for it. */ const DECISION_TOAST_MS = 15_000 const ACTIVITY_RETRY_MS = 5_000 -/** How many times the activity line waits for a decision toast before showing anyway. */ -const ACTIVITY_WAITS = 4 +/** How long the activity line waits for decision toasts to clear before it gives up (it shows next time). */ +const ACTIVITY_WAIT_MS = 60_000 +/** How long the activity line waits for the startup replay. */ +const ACTIVITY_REPLAY_WAIT_MS = 10_000 + +/** Shows a line once nothing else is showing: checks `busy`, and waits between checks up to `waits` times. Shows + * nothing if it is still busy after that, or once `disposed`. Returns whether it showed. */ +export async function announceWhenClear(options: { + busy: () => boolean + wait: () => Promise + waits: number + disposed: () => boolean + show: () => void +}): Promise { + for (let tries = 0; ; tries++) { + if (options.disposed()) return false + if (!options.busy()) { + options.show() + return true + } + if (tries >= options.waits) return false + await options.wait() + } +} /** How many decisions a combined toast names. */ const COMBINED_NAMED = 5 diff --git a/packages/opencode/src/server/server.ts b/packages/opencode/src/server/server.ts index 6d2c37c923..7b6b1842fc 100644 --- a/packages/opencode/src/server/server.ts +++ b/packages/opencode/src/server/server.ts @@ -1461,7 +1461,8 @@ export namespace Server { } }) // altimate_change start — workspace activity: what changed in the workspace's skills and knowledge since this - // client (`host`) last looked, as one line to show when a session starts. Marks it seen; the first look says nothing. + // client (`host`) last looked, as one line to show when a session starts. Marks it seen; the first look says + // nothing. With `defer=1` a line leaves the mark for `POST .../activity/seen` once the client showed it. .get("/altimate/workspace/activity", async (c) => { const refused = workspaceRouteRefusal(c.req.header("origin"), c.req.header("host"), undefined, c.req.header("sec-fetch-site")) if (refused) return c.json(refused.body, refused.status) @@ -1469,7 +1470,7 @@ export namespace Server { if (!/^[a-z][a-z0-9-]{0,31}$/.test(host)) return c.json({ ok: false, error: "host must name the client, e.g. vscode." }, 400) try { const { WorkspaceActivity } = await import("../altimate/workspace/workspace-activity") - const changes = await WorkspaceActivity.changesSince(Instance.directory, host) + const changes = await WorkspaceActivity.changesSince(Instance.directory, host, { defer: c.req.query("defer") === "1" }) // `status`: ok, first (nothing said the first time), signed_out, not_linked, account_changed, unconfirmed, // unsupported, failed. return c.json({ ok: true as const, ...changes }) @@ -1479,6 +1480,24 @@ export namespace Server { return c.json({ ok: false, error }, 500) } }) + .post("/altimate/workspace/activity/seen", async (c) => { + const refused = workspaceRouteRefusal(c.req.header("origin"), c.req.header("host"), undefined, c.req.header("sec-fetch-site")) + if (refused) return c.json(refused.body, refused.status) + const read = await readJsonObject(() => c.req.text(), "workspace activity seen") + if ("failure" in read) return c.json(read.failure.body, read.failure.status) + const host = typeof read.body.host === "string" ? read.body.host : "" + if (!/^[a-z][a-z0-9-]{0,31}$/.test(host)) return c.json({ ok: false, error: "host must name the client, e.g. vscode." }, 400) + try { + const { WorkspaceActivity } = await import("../altimate/workspace/workspace-activity") + const seen = WorkspaceActivity.Mark.safeParse(read.body.seen) + if (!seen.success) return c.json({ ok: false, error: "seen must be the mark a deferred look returned." }, 400) + return c.json({ ok: true as const, ...(await WorkspaceActivity.acknowledge(Instance.directory, host, seen.data)) }) + } catch (err) { + const error = err instanceof Error ? err.message : String(err) + log.error("workspace activity seen failed", { error }) + return c.json({ ok: false, error }, 500) + } + }) // altimate_change end .post("/altimate/workspace/requests/:id/:action", async (c) => { const refused = workspaceRouteRefusal(c.req.header("origin"), c.req.header("host"), undefined, c.req.header("sec-fetch-site")) diff --git a/packages/opencode/test/altimate/workspace/workspace-activity.test.ts b/packages/opencode/test/altimate/workspace/workspace-activity.test.ts index 83e75aca9c..817f3248b3 100644 --- a/packages/opencode/test/altimate/workspace/workspace-activity.test.ts +++ b/packages/opencode/test/altimate/workspace/workspace-activity.test.ts @@ -36,6 +36,12 @@ const change = (name: string, action: string, at: string, kind = "skill") => ({ actor_name: "Ada", at, }) +/** A change as a server with ids sends it. */ +const tracked = (id: string, name: string, action: string, at: string, kind = "skill", subject = `${kind}:${name}`) => ({ + ...change(name, action, at, kind), + id, + subject, +}) /** The `since` each activity request sent (undefined: none), and the answer it gets. */ let asked: (string | undefined)[] = [] @@ -131,7 +137,98 @@ describe("what changed since this client last looked", () => { }) }) +describe("changes that commit late, and what was already reported", () => { + test("each look asks again from a few minutes before the mark, and reports only what it had not", async () => { + activity = () => reply({ items: [tracked("e1", "naming", "added", "2026-11-12T10:00:00Z")], has_more: false }) + expect((await WorkspaceActivity.changesSince(project, "tui")).status).toBe("first") + // A change stamped before the mark (its transaction started earlier, it committed later), and the one already seen. + activity = () => + reply({ + items: [ + tracked("e1", "naming", "added", "2026-11-12T10:00:00Z"), + tracked("e0", "late", "added", "2026-11-12T09:59:00Z"), + ], + has_more: false, + }) + const next = await WorkspaceActivity.changesSince(project, "tui") + expect(asked[1]).toBe("2026-11-12T09:55:00.000Z") + expect(next.status === "ok" && next.line).toBe("Since your last session in Growth: 1 skill added (late).") + // Both are reported now: nothing more to say. + const quiet = await WorkspaceActivity.changesSince(project, "tui") + expect(quiet.status === "ok" && quiet.line).toBeUndefined() + }) + + test("an older server without ids is asked from the mark itself, as before", () => { + expect(WorkspaceActivity.sinceOf({ at: "2026-11-12T10:00:00Z", ids: [], overlap: false })).toBe("2026-11-12T10:00:00Z") + // A mark written before ids, read back. + expect(WorkspaceActivity.markOf("2026-11-12T10:00:00Z")).toEqual({ at: "2026-11-12T10:00:00Z", ids: [], overlap: false }) + // A server time without a zone is UTC. + expect(WorkspaceActivity.sinceOf({ at: "2026-11-12T10:00:00", ids: [], overlap: true })).toBe("2026-11-12T09:55:00.000Z") + }) +}) + +describe("a deferred look", () => { + test("keeps the mark until the line was shown, so a client that goes away first shows it next time", async () => { + activity = () => reply({ items: [], has_more: false }) + expect((await WorkspaceActivity.changesSince(project, "tui")).status).toBe("first") + activity = () => reply({ items: [tracked("e1", "naming", "added", "2026-11-12T10:00:00Z")], has_more: false }) + const unshown = await WorkspaceActivity.changesSince(project, "tui", { defer: true }) + expect(unshown.status === "ok" && unshown.line).toBe("Since your last session in Growth: 1 skill added (naming).") + // Not acknowledged: the next start says it again. + const again = await WorkspaceActivity.changesSince(project, "tui", { defer: true }) + expect(again.status === "ok" && again.line).toBe("Since your last session in Growth: 1 skill added (naming).") + if (again.status !== "ok" || !again.seen) throw new Error("expected a mark to acknowledge") + expect(await WorkspaceActivity.acknowledge(project, "tui", again.seen)).toEqual({ status: "ok" }) + const after = await WorkspaceActivity.changesSince(project, "tui", { defer: true }) + expect(after.status === "ok" && after.line).toBeUndefined() + }) +}) + describe("the line", () => { + test("with more changes than one look reads, says so instead of giving partial counts", () => { + const items = [ + tracked("e3", "a", "removed", "3"), + tracked("e2", "b", "added", "2"), + tracked("e1", "c", "added", "1"), + tracked("e0", "d", "updated", "0"), + ] as never + expect(WorkspaceActivity.summaryLine("Growth", items, true)).toBe( + "Since your last session in Growth: more than 4 changes to its skills and knowledge; the newest: a removed, b added, c added.", + ) + }) + + test("counts items, not names: two knowledge bases with one name are two, one item changed twice is one", () => { + const items = [ + tracked("e1", "Glossary", "added", "2", "knowledge", "kb-1"), + tracked("e2", "Glossary", "added", "1", "knowledge", "kb-2"), + tracked("e3", "naming", "added", "1", "skill", "s-1"), + tracked("e4", "naming", "added", "0", "skill", "s-1"), + ] as never + expect(WorkspaceActivity.summaryLine("Growth", items)).toBe( + "Since your last session in Growth: 2 knowledge bases added (Glossary), 1 skill added (naming).", + ) + }) + + test("caps long names and the whole line, and leaves out an empty name", () => { + const long = "x".repeat(300) + const line = WorkspaceActivity.summaryLine( + "Growth", + [ + tracked("e1", long, "added", "3", "skill", "s-1"), + tracked("e2", "", "removed", "2", "skill", "s-2"), + ] as never, + )! + expect(line).toBe(`Since your last session in Growth: 1 skill added (${"x".repeat(39)}…), 1 skill removed.`) + const many = Array.from({ length: 6 }, (_, g) => + Array.from({ length: 3 }, (_, i) => + tracked(`e${g}-${i}`, `${"n".repeat(38)}${g}${i}`, ["added", "updated", "removed"][g % 3], "1", g < 3 ? "skill" : "knowledge", `s${g}-${i}`), + ), + ).flat() + const capped = WorkspaceActivity.summaryLine("Growth", many as never)! + expect(capped.length).toBe(300) + expect(capped.endsWith("…")).toBe(true) + }) + test("groups by kind of change, names a few, and counts an item changed twice once", () => { const items = [ change("a", "added", "6"), @@ -146,7 +243,7 @@ describe("the line", () => { ) expect(WorkspaceActivity.summaryLine("Growth", [], true)).toBeUndefined() expect(WorkspaceActivity.summaryLine("Gro\u001b[1mwth", [change("e", "removed", "1")] as never, true)).toBe( - "Since your last session in Gro [1mwth: 1 skill removed (e), and more.", + "Since your last session in Gro [1mwth: more than 1 change to its skills and knowledge; the newest: e removed.", ) }) }) diff --git a/packages/opencode/test/cli/tui/rules-requests.test.ts b/packages/opencode/test/cli/tui/rules-requests.test.ts index 07a1887546..9232fe2d97 100644 --- a/packages/opencode/test/cli/tui/rules-requests.test.ts +++ b/packages/opencode/test/cli/tui/rules-requests.test.ts @@ -3,7 +3,7 @@ // The `/rules` menu's pure helpers: how a shown decision is remembered, and why the skill and knowledge part is missing // or short. import { describe, expect, test } from "bun:test" -import { combinedToast, decisionToast, decisionToaster, requestsProblem, shownKey } from "../../../src/plugin/tui/altimate/rules" +import { announceWhenClear, combinedToast, decisionToast, decisionToaster, requestsProblem, shownKey } from "../../../src/plugin/tui/altimate/rules" describe("rules TUI", () => { test("a decision is remembered by kind, id and status: a rule and a skill with one id do not hide each other", () => { @@ -81,3 +81,30 @@ describe("rules TUI", () => { toaster.dispose() }) }) + +describe("the activity line waits for decision toasts", () => { + const run = (busy: boolean[], disposedAfter = Infinity) => { + let checks = 0 + const shown: string[] = [] + const result = announceWhenClear({ + busy: () => busy[Math.min(checks++, busy.length - 1)], + wait: async () => {}, + waits: 3, + disposed: () => checks >= disposedAfter, + show: () => shown.push("line"), + }) + return result.then((ok) => ({ ok, shown, checks })) + } + + test("shows once the toast is gone", async () => { + expect(await run([true, true, false])).toEqual({ ok: true, shown: ["line"], checks: 3 }) + }) + + test("never shows over a toast that is still up: it gives up, so the line comes next time", async () => { + expect(await run([true])).toEqual({ ok: false, shown: [], checks: 4 }) + }) + + test("shows nothing once the TUI is closing", async () => { + expect(await run([true, false], 1)).toEqual({ ok: false, shown: [], checks: 1 }) + }) +}) From ead58180b74c5e68e24059ca3e3fd4cb11544030 Mon Sep 17 00:00:00 2001 From: Sarav Date: Tue, 17 Nov 2026 13:47:54 +0530 Subject: [PATCH 4/7] fix: workspace activity: has_more under the overlap, route tests, honest docs - the server's `has_more` counts the changes the overlap reads again, so the line trusts it only when the page did not reach back to the mark; then the page holds every change after the mark and the line gives counts - a page cut inside the overlap is read again with the most the server gives (100); the mark records `from`, the oldest time a cut page read, below which an unrecorded change is history, not news - tests: two new changes after a bulk of 60 already seen give counts, not "more than"; more changes after the mark than a page holds still say so; acknowledging an older look keeps a newer one recorded in between - route tests for `defer=1` and `POST /altimate/workspace/activity/seen`, including refused input and a browser origin - docs no longer claim only one TUI shows the line or that nothing is ever repeated or missed; a burst of more than 100 changes is the limit Co-Authored-By: Claude Opus 5.5 --- docs/docs/usage/cli.md | 2 +- .../altimate/workspace/workspace-activity.ts | 52 +++++++++--- .../workspace/workspace-activity.test.ts | 79 +++++++++++++++++-- .../test/server/altimate-rules-routes.test.ts | 64 +++++++++++++++ 4 files changed, 180 insertions(+), 17 deletions(-) diff --git a/docs/docs/usage/cli.md b/docs/docs/usage/cli.md index 00a0e2e3a4..c4e0d50e08 100644 --- a/docs/docs/usage/cli.md +++ b/docs/docs/usage/cli.md @@ -68,7 +68,7 @@ With workspaces on: - In a project linked to a workspace, integrations come only from the workspace's engine, so the `datamate_manager` tool is not offered there and refuses to run. `datamate-*` MCP servers already in the config still load, and a one-time notice names the file they are in; the config is not edited. - `altimate-code skill publish ` uploads a project skill to the linked workspace, attached directly for the workspace owner or an admin and sent for review for a member when review is on; see [Skills](../configure/skills.md#cli-commands). - When the owner or an admin approves or rejects one of your skill or knowledge base requests that altimate-code has seen pending (submitted from it, or listed by an earlier check), or that is decided after it began checking, the TUI shows a notice once in each project linked to that workspace, with the reason for a rejection. Every altimate-code process that opens a linked project checks at start and every 5 minutes while workspaces are on and you are signed in: it lists your own requests on the workspace (up to 10 pages of 50); a server without review is asked again only after 6 hours. The decision is kept per account and workspace in your own state directory (`$XDG_STATE_HOME/altimate-code/workspace-reviews/`, the 50 most recent), so a TUI that was closed or disconnected when it arrived shows it when it next starts. The first time a TUI opens a project, decisions already kept are recorded without a notice; `altimate-code workspace review status` lists them. Withdrawing a waiting request and removing an approved one happen in the web app or from `/rules` in the TUI, which lists your skill and knowledge requests with your rule proposals. Editor and agent plugins read decisions with `altimate-code workspace review decisions --json` (see [Skills](../configure/skills.md#cli-commands)), which always prints one JSON object and exits 0. When the owner or an admin removes one of yours that altimate-code has seen approved or waiting (up to the 200 approved ones it tracks per workspace), the TUI shows that once too, with the reason; your own removal and withdrawal show nothing. -- A few seconds after the TUI starts in a linked project, it says in one line what changed in the skills and knowledge the workspace gives its team since you last looked, for example "Since your last session in Growth: 2 skills added (naming, cost-guard), 1 knowledge base removed (Glossary)." It reads the workspace's recent changes (the last 30 days) and keeps when you last looked per account, workspace and client in your own state directory (`$XDG_STATE_HOME/altimate-code/workspace-activity/`); the first time it only records where to start from. Every TUI and project on the same account and workspace shares one last look, so whichever starts first shows the line. Each look also asks again from a few minutes before the last one, so a change that was saved late is not missed, and never repeats one it already reported. With more changes than it reads at once (50), it says there were more and names the newest instead of giving counts. It waits while a review decision notice is showing; if one is still up after a minute, or the TUI closes first, the line is shown the next time instead. The VS Code extension asks `altimate-code serve` for the same line (`GET /altimate/workspace/activity?host=vscode`), with its own last look; a client can add `defer=1` and confirm with `POST /altimate/workspace/activity/seen` once it showed the line. Changes the service does not record (the owner detaching their own skill, the owner's knowledge selection) are not listed. +- A few seconds after the TUI starts in a linked project, it says in one line what changed in the skills and knowledge the workspace gives its team since you last looked, for example "Since your last session in Growth: 2 skills added (naming, cost-guard), 1 knowledge base removed (Glossary)." It reads the workspace's recent changes (the last 30 days) and keeps when you last looked per account, workspace and client in your own state directory (`$XDG_STATE_HOME/altimate-code/workspace-activity/`); the first time it only records where to start from. All TUIs on the same account and workspace share one last look: usually the first to start shows the line and the others say nothing, though two that start at the same moment can both show it. Each look also asks again from a few minutes before the last one, so a change saved a little late is still reported, and a change it already reported is skipped. With more changes since the last look than it reads at once (50), it says there were more and names the newest instead of giving counts; a burst of more than 100 changes within a few minutes can leave a late one unreported. It waits while a review decision notice is showing; if one is still up after a minute, or the TUI closes first, the line is shown the next time instead. The VS Code extension asks `altimate-code serve` for the same line (`GET /altimate/workspace/activity?host=vscode`), with its own last look; a client can add `defer=1` and confirm with `POST /altimate/workspace/activity/seen` once it showed the line. Changes the service does not record (the owner detaching their own skill, the owner's knowledge selection) are not listed. - Workspace skills are synced at the version the workspace serves you: the approved version, or your own pending version of a skill you submitted. The next sync follows what the workspace serves: a skill whose first submission is rejected, or that is detached from the workspace, is removed from the project; when an update to an approved skill is rejected or replaced, the skill stays at its approved version. Each skill is downloaded as one version: if it is approved or rejected while its files are being read, nothing of it is installed from that sync and it is fetched again on the next one. When a download fails, the copy already in the project is kept only if it is still the version the workspace serves, as far as the server has said (its list, or a read refused because the version just changed), or if neither the copy nor the list names a version (a copy synced before revisions, or an older server), in which case it is kept until the server says otherwise; a copy of a version it no longer serves (for example your rejected pending version), or of a skill it no longer lists, is removed until the download succeeds, even when no other skill could be downloaded. Two processes syncing the same project take turns: a sync never replaces or removes a snapshot another process installed after it started, and the next sync starts from the newer one. - When the linked workspace has knowledge, the agent is told to check it for best practices and team conventions before answering, without you having to mention the knowledge base. - In an ordinary session the agent is told every turn which workspace the project is linked to — or that none is, or that the link could not be verified just now. In an extension-pinned session it is told the pinned workspace instead, and that it differs from the project's own link. Either way "which workspace am I in?" has an answer, and the agent is told not to confuse it with a Databricks workspace or an IDE workspace folder. diff --git a/packages/opencode/src/altimate/workspace/workspace-activity.ts b/packages/opencode/src/altimate/workspace/workspace-activity.ts index f2c3bed608..388e4be7e9 100644 --- a/packages/opencode/src/altimate/workspace/workspace-activity.ts +++ b/packages/opencode/src/altimate/workspace/workspace-activity.ts @@ -22,8 +22,10 @@ import { classify } from "../rules/api" import { printable } from "../rules/printable" import { altimateRequest, type ActAs } from "./api-client" -/** How many changes one look reads (the server allows up to 100): room for the ones the overlap reads again. */ +/** How many changes one look reads: room for the ones the overlap reads again. */ export const LIMIT = 50 +/** The most the server gives in one answer: a look whose page was cut inside the overlap reads again with this. */ +export const MAX_LIMIT = 100 /** How far behind the mark each look asks again, for changes that committed late. */ export const OVERLAP_MS = 5 * 60_000 /** How many names the line gives for one kind of change. */ @@ -68,12 +70,14 @@ export async function fetchActivity(datamateId: number, since: string | undefine } /** One client's last look: the server time of the newest change it was given ("" when it first looked at an empty - * window), the ids it reported within `OVERLAP_MS` of that, and whether the server gives ids (then each look asks - * from `OVERLAP_MS` before the mark). */ + * window), the ids it reported within `OVERLAP_MS` of that, whether the server gives ids (then each look asks from + * `OVERLAP_MS` before the mark), and `from`: when that look's page was cut, the oldest time it read. Below `from` the + * ids are incomplete, so an unrecorded change there is taken as already seen ("" when the ids are complete). */ export const Mark = z.object({ at: z.string(), ids: z.array(z.object({ id: z.string(), at: z.string() })).default([]), overlap: z.boolean().default(false), + from: z.string().default(""), }) export type Mark = z.infer @@ -87,7 +91,7 @@ type Seen = z.infer type Scope = Seen["scope"] export const markOf = (value: Seen["seen"][string] | undefined): Mark | undefined => - value === undefined ? undefined : typeof value === "string" ? { at: value, ids: [], overlap: false } : value + value === undefined ? undefined : typeof value === "string" ? { at: value, ids: [], overlap: false, from: "" } : value /** A server time in milliseconds; one without a zone is UTC, as the server keeps them. */ const ms = (at: string) => Date.parse(/(?:[zZ]|[+-]\d\d:?\d\d)$/.test(at) ? at : `${at}Z`) @@ -100,21 +104,34 @@ export function sinceOf(mark: Mark): string | undefined { return Number.isNaN(at) ? mark.at : new Date(at - OVERLAP_MS).toISOString() } -/** The mark after a look (or after merging two): the newest time, and the ids within `OVERLAP_MS` of it. */ -export function advance(mark: Mark | undefined, items: Pick[]): Mark { +/** The mark after a look (or after merging two): the newest time, and the ids within `OVERLAP_MS` of it. `cut`: the + * look's page did not hold every change it asked for, so its ids are complete only from its oldest item. */ +export function advance(mark: Mark | undefined, items: Pick[], options: { cut?: boolean } = {}): Mark { const times = [...(mark?.at ? [mark.at] : []), ...items.map((i) => i.at)].filter((at) => !Number.isNaN(ms(at))) const at = times.reduce((a, b) => (a && ms(a) >= ms(b) ? a : b), "") || mark?.at || "" const floor = at ? ms(at) - OVERLAP_MS : Number.NEGATIVE_INFINITY const ids = new Map() for (const entry of [...(mark?.ids ?? []), ...items.flatMap((i) => (i.id ? [{ id: i.id, at: i.at }] : []))]) if (ms(entry.at) > floor) ids.set(entry.id, entry.at) + const oldest = items.at(-1)?.at + const from = options.cut && oldest && ms(oldest) > floor ? oldest : "" return { at, ids: [...ids].map(([id, at]) => ({ id, at })).slice(-200), overlap: (mark?.overlap ?? false) || items.some((i) => i.id !== undefined), + from, } } +/** Whether a change on a look's page is news: not reported before, and not an unrecorded change from below where the + * last look's ids stop being complete (`from`), which is history. A server without ids: everything after the mark. */ +function isFresh(mark: Mark | undefined, reported: Set, item: Item): boolean { + if (item.id === undefined) return true + if (reported.has(item.id)) return false + if (!mark?.at || !mark.from) return true + return !(ms(item.at) <= ms(mark.at) && ms(item.at) <= ms(mark.from)) +} + /** Where each client's last look is kept. */ export const dir = () => path.join(Global.Path.state, "workspace-activity") const fileOf = (scope: Scope) => @@ -240,10 +257,19 @@ export async function changesSince(directory: string, host: string, options: { d // Undefined: never looked. "": looked when nothing had changed in the window, so everything listed since is new // (no local clock is involved). Otherwise the newest change it was given. const mark = markOf(state.seen[host]) - const { items, hasMore } = await fetchActivity(workspace.id, mark && sinceOf(mark), actAs, LIMIT) + const since = mark && sinceOf(mark) + // Whether a page reached back to the mark: then it holds every change after the mark, and `has_more` is about the + // overlap the look read again, not about news. + const reached = (items: Item[]) => + Boolean(mark?.at) && items.length > 0 && ms(items[items.length - 1].at) <= ms(mark!.at) + let page = await fetchActivity(workspace.id, since, actAs, LIMIT) + // Cut inside the overlap: read again with the most the server gives, so a change that committed late is in it. + if (page.hasMore && mark?.overlap && reached(page.items)) page = await fetchActivity(workspace.id, since, actAs, MAX_LIMIT) + const { items } = page + const hasMore = page.hasMore && !reached(items) const reported = new Set(mark?.ids.map((entry) => entry.id)) - const fresh = items.filter((item) => item.id === undefined || !reported.has(item.id)) - const next = advance(mark, items) + const fresh = items.filter((item) => isFresh(mark, reported, item)) + const next = advance(mark, items, { cut: page.hasMore }) const save = () => JSON.stringify(next) === JSON.stringify(mark) ? Promise.resolve() : writeSeen({ ...state, seen: { ...state.seen, [host]: next } }) if (mark === undefined) { @@ -269,7 +295,13 @@ export async function acknowledge(directory: string, host: string, seen: Mark): return await locked(scope, async () => { const state = await readSeen(scope) const current = markOf(state.seen[host]) - const merged = advance(current ? { ...current, overlap: current.overlap || seen.overlap } : seen, [...seen.ids, ...(seen.at ? [{ at: seen.at }] : [])]) + const merged = advance(current ? { ...current, overlap: current.overlap || seen.overlap } : seen, [ + ...seen.ids, + ...(seen.at ? [{ at: seen.at }] : []), + ]) + // Where either look's ids stop being complete, the later one holds. + const froms = [current?.from, seen.from].filter((at): at is string => Boolean(at)).sort((a, b) => ms(b) - ms(a)) + if (froms[0] && ms(froms[0]) > ms(merged.at) - OVERLAP_MS) merged.from = froms[0] await writeSeen({ ...state, seen: { ...state.seen, [host]: merged } }) return { status: "ok" as const } }) diff --git a/packages/opencode/test/altimate/workspace/workspace-activity.test.ts b/packages/opencode/test/altimate/workspace/workspace-activity.test.ts index 817f3248b3..c3bc2080bf 100644 --- a/packages/opencode/test/altimate/workspace/workspace-activity.test.ts +++ b/packages/opencode/test/altimate/workspace/workspace-activity.test.ts @@ -43,14 +43,23 @@ const tracked = (id: string, name: string, action: string, at: string, kind = "s subject, }) -/** The `since` each activity request sent (undefined: none), and the answer it gets. */ +/** The `since` (undefined: none) and `limit` each activity request sent, and the answer it gets. */ let asked: (string | undefined)[] = [] -let activity: (since: string | undefined) => Response = () => reply({ items: [], has_more: false }) +let limits: number[] = [] +let activity: (since: string | undefined, limit: number) => Response = () => reply({ items: [], has_more: false }) +/** A server holding `changes`: newest first (ties by id, newest first), after `since`, at most `limit`. */ +const server = (changes: ReturnType[]) => (since: string | undefined, limit: number) => { + const after = changes + .filter((c) => since === undefined || Date.parse(c.at) > Date.parse(since)) + .sort((a, b) => Date.parse(b.at) - Date.parse(a.at) || b.id.localeCompare(a.id, undefined, { numeric: true })) + return reply({ items: after.slice(0, limit), has_more: after.length > limit }) +} let project = "" beforeEach(async () => { configured = true asked = [] + limits = [] activity = () => reply({ items: [], has_more: false }) rmSync(WorkspaceActivity.dir(), { recursive: true, force: true }) project = mkdtempSync(path.join(SANDBOX, "proj-")) @@ -59,8 +68,10 @@ beforeEach(async () => { if (url.pathname.endsWith("/users/me")) return reply({ id: 7 }) if (url.pathname.endsWith("/datamates/42/activity")) { const since = url.searchParams.get("since") ?? undefined + const limit = Number(url.searchParams.get("limit")) asked.push(since) - return activity(since) + limits.push(limit) + return activity(since, limit) } return reply({ items: [], total: 0, page: 1, size: 50, pages: 1 }) }) as typeof fetch @@ -159,11 +170,50 @@ describe("changes that commit late, and what was already reported", () => { }) test("an older server without ids is asked from the mark itself, as before", () => { - expect(WorkspaceActivity.sinceOf({ at: "2026-11-12T10:00:00Z", ids: [], overlap: false })).toBe("2026-11-12T10:00:00Z") + expect(WorkspaceActivity.sinceOf({ at: "2026-11-12T10:00:00Z", ids: [], overlap: false, from: "" })).toBe( + "2026-11-12T10:00:00Z", + ) // A mark written before ids, read back. - expect(WorkspaceActivity.markOf("2026-11-12T10:00:00Z")).toEqual({ at: "2026-11-12T10:00:00Z", ids: [], overlap: false }) + expect(WorkspaceActivity.markOf("2026-11-12T10:00:00Z")).toEqual({ + at: "2026-11-12T10:00:00Z", + ids: [], + overlap: false, + from: "", + }) // A server time without a zone is UTC. - expect(WorkspaceActivity.sinceOf({ at: "2026-11-12T10:00:00", ids: [], overlap: true })).toBe("2026-11-12T09:55:00.000Z") + expect(WorkspaceActivity.sinceOf({ at: "2026-11-12T10:00:00", ids: [], overlap: true, from: "" })).toBe( + "2026-11-12T09:55:00.000Z", + ) + }) +}) + +describe("more changes than a page, under the overlap", () => { + const bulk = (n: number, at: string) => + Array.from({ length: n }, (_, i) => tracked(`a${i}`, `bulk-${i}`, "added", at)) + + test("changes it already saw in the overlap do not make the line say there were more", async () => { + // 60 skills attached in one save: the first look reads 50 of them and records where to start. + const changes = bulk(60, "2026-11-12T10:00:00Z") + activity = server(changes) + expect((await WorkspaceActivity.changesSince(project, "tui")).status).toBe("first") + // A day later, exactly two new changes. + changes.push(tracked("n1", "naming", "added", "2026-11-13T09:00:00Z"), tracked("n2", "cost-guard", "removed", "2026-11-13T10:00:00Z")) + const next = await WorkspaceActivity.changesSince(project, "tui") + expect(next.status === "ok" && next.line).toBe( + "Since your last session in Growth: 1 skill removed (cost-guard), 1 skill added (naming).", + ) + // The page was cut inside the overlap, so it was read again with the most the server gives. + expect(limits).toEqual([WorkspaceActivity.LIMIT, WorkspaceActivity.LIMIT, WorkspaceActivity.MAX_LIMIT]) + const quiet = await WorkspaceActivity.changesSince(project, "tui") + expect(quiet.status === "ok" && quiet.line).toBeUndefined() + }) + + test("more changes after the mark than a page holds still say there were more", async () => { + activity = server([tracked("o1", "old", "added", "2026-11-12T10:00:00Z")]) + expect((await WorkspaceActivity.changesSince(project, "tui")).status).toBe("first") + activity = server([tracked("o1", "old", "added", "2026-11-12T10:00:00Z"), ...bulk(70, "2026-11-13T10:00:00Z")]) + const next = await WorkspaceActivity.changesSince(project, "tui") + expect(next.status === "ok" && next.line).toStartWith("Since your last session in Growth: more than 50 changes") }) }) @@ -182,6 +232,23 @@ describe("a deferred look", () => { const after = await WorkspaceActivity.changesSince(project, "tui", { defer: true }) expect(after.status === "ok" && after.line).toBeUndefined() }) + + test("acknowledging an older look keeps what a look in between recorded", async () => { + activity = () => reply({ items: [], has_more: false }) + expect((await WorkspaceActivity.changesSince(project, "tui")).status).toBe("first") + const changes = [tracked("e1", "naming", "added", "2026-11-12T10:00:00Z")] + activity = server(changes) + const older = await WorkspaceActivity.changesSince(project, "tui", { defer: true }) + if (older.status !== "ok" || !older.seen) throw new Error("expected a mark to acknowledge") + // Another look, not deferred, records a newer change before the older one is acknowledged. + changes.push(tracked("e2", "cost-guard", "added", "2026-11-12T11:00:00Z")) + expect((await WorkspaceActivity.changesSince(project, "tui")).status).toBe("ok") + await WorkspaceActivity.acknowledge(project, "tui", older.seen) + // The newer mark holds: nothing is said again. + const after = await WorkspaceActivity.changesSince(project, "tui") + expect(after.status === "ok" && after.line).toBeUndefined() + expect(asked.at(-1)).toBe("2026-11-12T10:55:00.000Z") + }) }) describe("the line", () => { diff --git a/packages/opencode/test/server/altimate-rules-routes.test.ts b/packages/opencode/test/server/altimate-rules-routes.test.ts index 70b9ede3ba..7c946fb25e 100644 --- a/packages/opencode/test/server/altimate-rules-routes.test.ts +++ b/packages/opencode/test/server/altimate-rules-routes.test.ts @@ -187,3 +187,67 @@ describe("rules sync route", () => { } }, 15_000) }) + +describe("workspace activity routes", () => { + test("a browser origin is refused", async () => { + const origin = { origin: "https://evil.example", "sec-fetch-site": "cross-site" } + for (const [method, url, body] of [ + ["GET", "/altimate/workspace/activity?host=tui"], + ["POST", "/altimate/workspace/activity/seen", { host: "tui", seen: { at: "" } }], + ] as const) { + const response = await request(method, url, body, origin) + expect([403, 409]).toContain(response.status) + expect(await response.json()).toMatchObject({ ok: false }) + } + }) + + test("a deferred look is passed through, and its mark comes back for the client to confirm", async () => { + const { WorkspaceActivity } = await import("../../src/altimate/workspace/workspace-activity") + const { spyOn } = await import("bun:test") + const seen = { at: "2026-11-12T10:00:00Z", ids: [{ id: "e1", at: "2026-11-12T10:00:00Z" }], overlap: true, from: "" } + const look = spyOn(WorkspaceActivity, "changesSince").mockResolvedValue({ + status: "ok", + workspace: { id: 42, name: "Growth" }, + items: [], + line: "Since your last session in Growth: 1 skill added (naming).", + seen, + }) + try { + const deferred = await request("GET", "/altimate/workspace/activity?host=tui&defer=1") + expect(await deferred.json()).toMatchObject({ ok: true, status: "ok", seen }) + expect(look.mock.calls[0]?.[1]).toBe("tui") + expect(look.mock.calls[0]?.[2]).toEqual({ defer: true }) + await request("GET", "/altimate/workspace/activity?host=vscode") + expect(look.mock.calls[1]?.[2]).toEqual({ defer: false }) + } finally { + look.mockRestore() + } + }) + + test("confirming a shown line takes the mark back; anything else is refused before it is recorded", async () => { + const { WorkspaceActivity } = await import("../../src/altimate/workspace/workspace-activity") + const { spyOn } = await import("bun:test") + const acknowledge = spyOn(WorkspaceActivity, "acknowledge").mockResolvedValue({ status: "ok" }) + try { + for (const body of [ + {}, + { host: "Bad Host", seen: { at: "" } }, + { host: "tui" }, + { host: "tui", seen: { at: 5 } }, + { host: "tui", seen: "2026-11-12T10:00:00Z" }, + ]) { + const response = await request("POST", "/altimate/workspace/activity/seen", body) + expect(response.status).toBe(400) + expect(await response.json()).toMatchObject({ ok: false }) + } + expect(acknowledge).not.toHaveBeenCalled() + const seen = { at: "2026-11-12T10:00:00Z", ids: [], overlap: true, from: "" } + const ok = await request("POST", "/altimate/workspace/activity/seen", { host: "tui", seen }) + expect(await ok.json()).toEqual({ ok: true, status: "ok" }) + expect(acknowledge.mock.calls[0]?.[1]).toBe("tui") + expect(acknowledge.mock.calls[0]?.[2]).toEqual(seen) + } finally { + acknowledge.mockRestore() + } + }) +}) From a6bc4f6efdf8a3e95b7914a970e0401673c93dc4 Mon Sep 17 00:00:00 2001 From: Sarav Date: Tue, 17 Nov 2026 13:50:16 +0530 Subject: [PATCH 5/7] fix: acknowledging a cut look keeps the older cut point, and only when both looks were cut A look that read its whole window vouches for its ids, so merging it with a cut look keeps no cut point; two cut looks keep the older one. The docs give the real burst limit (50, one look's page). Co-Authored-By: Claude Opus 5.5 --- docs/docs/usage/cli.md | 2 +- .../altimate/workspace/workspace-activity.ts | 10 +++++++--- .../workspace/workspace-activity.test.ts | 20 ++++++++++++++++++- 3 files changed, 27 insertions(+), 5 deletions(-) diff --git a/docs/docs/usage/cli.md b/docs/docs/usage/cli.md index c4e0d50e08..88a106840a 100644 --- a/docs/docs/usage/cli.md +++ b/docs/docs/usage/cli.md @@ -68,7 +68,7 @@ With workspaces on: - In a project linked to a workspace, integrations come only from the workspace's engine, so the `datamate_manager` tool is not offered there and refuses to run. `datamate-*` MCP servers already in the config still load, and a one-time notice names the file they are in; the config is not edited. - `altimate-code skill publish ` uploads a project skill to the linked workspace, attached directly for the workspace owner or an admin and sent for review for a member when review is on; see [Skills](../configure/skills.md#cli-commands). - When the owner or an admin approves or rejects one of your skill or knowledge base requests that altimate-code has seen pending (submitted from it, or listed by an earlier check), or that is decided after it began checking, the TUI shows a notice once in each project linked to that workspace, with the reason for a rejection. Every altimate-code process that opens a linked project checks at start and every 5 minutes while workspaces are on and you are signed in: it lists your own requests on the workspace (up to 10 pages of 50); a server without review is asked again only after 6 hours. The decision is kept per account and workspace in your own state directory (`$XDG_STATE_HOME/altimate-code/workspace-reviews/`, the 50 most recent), so a TUI that was closed or disconnected when it arrived shows it when it next starts. The first time a TUI opens a project, decisions already kept are recorded without a notice; `altimate-code workspace review status` lists them. Withdrawing a waiting request and removing an approved one happen in the web app or from `/rules` in the TUI, which lists your skill and knowledge requests with your rule proposals. Editor and agent plugins read decisions with `altimate-code workspace review decisions --json` (see [Skills](../configure/skills.md#cli-commands)), which always prints one JSON object and exits 0. When the owner or an admin removes one of yours that altimate-code has seen approved or waiting (up to the 200 approved ones it tracks per workspace), the TUI shows that once too, with the reason; your own removal and withdrawal show nothing. -- A few seconds after the TUI starts in a linked project, it says in one line what changed in the skills and knowledge the workspace gives its team since you last looked, for example "Since your last session in Growth: 2 skills added (naming, cost-guard), 1 knowledge base removed (Glossary)." It reads the workspace's recent changes (the last 30 days) and keeps when you last looked per account, workspace and client in your own state directory (`$XDG_STATE_HOME/altimate-code/workspace-activity/`); the first time it only records where to start from. All TUIs on the same account and workspace share one last look: usually the first to start shows the line and the others say nothing, though two that start at the same moment can both show it. Each look also asks again from a few minutes before the last one, so a change saved a little late is still reported, and a change it already reported is skipped. With more changes since the last look than it reads at once (50), it says there were more and names the newest instead of giving counts; a burst of more than 100 changes within a few minutes can leave a late one unreported. It waits while a review decision notice is showing; if one is still up after a minute, or the TUI closes first, the line is shown the next time instead. The VS Code extension asks `altimate-code serve` for the same line (`GET /altimate/workspace/activity?host=vscode`), with its own last look; a client can add `defer=1` and confirm with `POST /altimate/workspace/activity/seen` once it showed the line. Changes the service does not record (the owner detaching their own skill, the owner's knowledge selection) are not listed. +- A few seconds after the TUI starts in a linked project, it says in one line what changed in the skills and knowledge the workspace gives its team since you last looked, for example "Since your last session in Growth: 2 skills added (naming, cost-guard), 1 knowledge base removed (Glossary)." It reads the workspace's recent changes (the last 30 days) and keeps when you last looked per account, workspace and client in your own state directory (`$XDG_STATE_HOME/altimate-code/workspace-activity/`); the first time it only records where to start from. All TUIs on the same account and workspace share one last look: usually the first to start shows the line and the others say nothing, though two that start at the same moment can both show it. Each look also asks again from a few minutes before the last one, so a change saved a little late is still reported, and a change it already reported is skipped. With more changes since the last look than it reads at once (50), it says there were more and names the newest instead of giving counts; a burst of more than 50 changes within a few minutes can leave a late one unreported. It waits while a review decision notice is showing; if one is still up after a minute, or the TUI closes first, the line is shown the next time instead. The VS Code extension asks `altimate-code serve` for the same line (`GET /altimate/workspace/activity?host=vscode`), with its own last look; a client can add `defer=1` and confirm with `POST /altimate/workspace/activity/seen` once it showed the line. Changes the service does not record (the owner detaching their own skill, the owner's knowledge selection) are not listed. - Workspace skills are synced at the version the workspace serves you: the approved version, or your own pending version of a skill you submitted. The next sync follows what the workspace serves: a skill whose first submission is rejected, or that is detached from the workspace, is removed from the project; when an update to an approved skill is rejected or replaced, the skill stays at its approved version. Each skill is downloaded as one version: if it is approved or rejected while its files are being read, nothing of it is installed from that sync and it is fetched again on the next one. When a download fails, the copy already in the project is kept only if it is still the version the workspace serves, as far as the server has said (its list, or a read refused because the version just changed), or if neither the copy nor the list names a version (a copy synced before revisions, or an older server), in which case it is kept until the server says otherwise; a copy of a version it no longer serves (for example your rejected pending version), or of a skill it no longer lists, is removed until the download succeeds, even when no other skill could be downloaded. Two processes syncing the same project take turns: a sync never replaces or removes a snapshot another process installed after it started, and the next sync starts from the newer one. - When the linked workspace has knowledge, the agent is told to check it for best practices and team conventions before answering, without you having to mention the knowledge base. - In an ordinary session the agent is told every turn which workspace the project is linked to — or that none is, or that the link could not be verified just now. In an extension-pinned session it is told the pinned workspace instead, and that it differs from the project's own link. Either way "which workspace am I in?" has an answer, and the agent is told not to confuse it with a Databricks workspace or an IDE workspace folder. diff --git a/packages/opencode/src/altimate/workspace/workspace-activity.ts b/packages/opencode/src/altimate/workspace/workspace-activity.ts index 388e4be7e9..dd6ca109b8 100644 --- a/packages/opencode/src/altimate/workspace/workspace-activity.ts +++ b/packages/opencode/src/altimate/workspace/workspace-activity.ts @@ -299,9 +299,13 @@ export async function acknowledge(directory: string, host: string, seen: Mark): ...seen.ids, ...(seen.at ? [{ at: seen.at }] : []), ]) - // Where either look's ids stop being complete, the later one holds. - const froms = [current?.from, seen.from].filter((at): at is string => Boolean(at)).sort((a, b) => ms(b) - ms(a)) - if (froms[0] && ms(froms[0]) > ms(merged.at) - OVERLAP_MS) merged.from = froms[0] + // Ids are incomplete only below where both looks stopped reading: a look that read its whole window + // vouches for it, so only when both were cut does the older cut point hold. + const froms = [current?.from, seen.from] + if (froms.every(Boolean)) { + const older = (froms as string[]).sort((a, b) => ms(a) - ms(b))[0] + if (ms(older) > ms(merged.at) - OVERLAP_MS) merged.from = older + } await writeSeen({ ...state, seen: { ...state.seen, [host]: merged } }) return { status: "ok" as const } }) diff --git a/packages/opencode/test/altimate/workspace/workspace-activity.test.ts b/packages/opencode/test/altimate/workspace/workspace-activity.test.ts index c3bc2080bf..ec6b2899fd 100644 --- a/packages/opencode/test/altimate/workspace/workspace-activity.test.ts +++ b/packages/opencode/test/altimate/workspace/workspace-activity.test.ts @@ -4,7 +4,7 @@ // and each client's own last look. Network is stubbed at `globalThis.fetch`; files are real, in a sandbox state // directory. import { afterAll, afterEach, beforeEach, describe, expect, test } from "bun:test" -import { mkdirSync, mkdtempSync, rmSync } from "node:fs" +import { mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync } from "node:fs" import os from "node:os" import path from "node:path" @@ -249,6 +249,24 @@ describe("a deferred look", () => { expect(after.status === "ok" && after.line).toBeUndefined() expect(asked.at(-1)).toBe("2026-11-12T10:55:00.000Z") }) + + test("a cut look acknowledged after a complete one does not hide later changes as history", async () => { + activity = () => reply({ items: [], has_more: false }) + expect((await WorkspaceActivity.changesSince(project, "tui")).status).toBe("first") + const changes = [tracked("e1", "naming", "added", "2026-11-12T10:00:00Z")] + activity = server(changes) + const older = await WorkspaceActivity.changesSince(project, "tui", { defer: true }) + if (older.status !== "ok" || !older.seen) throw new Error("expected a mark to acknowledge") + // A look in between read its whole window; the deferred one is acknowledged as if its page had been cut. + changes.push(tracked("e2", "cost-guard", "added", "2026-11-12T10:04:00Z")) + expect((await WorkspaceActivity.changesSince(project, "tui")).status).toBe("ok") + await WorkspaceActivity.acknowledge(project, "tui", { ...older.seen, from: "2026-11-12T10:00:00Z" }) + const stored = readdirSync(WorkspaceActivity.dir(), { recursive: true }) + .map(String) + .filter((f) => f.endsWith(".json")) + .map((f) => JSON.parse(readFileSync(path.join(WorkspaceActivity.dir(), f), "utf8"))) + expect(stored.map((state) => state.seen?.tui?.from)).toEqual([""]) + }) }) describe("the line", () => { From 96b8ee830ca99eb26851ea6e5d8cf4b56b0b49d7 Mon Sep 17 00:00:00 2001 From: Sarav Date: Tue, 17 Nov 2026 19:06:58 +0530 Subject: [PATCH 6/7] fix: workspace activity: exact times, cut points that hold, scoped seen - times compare to the microsecond the server keeps (`precise`, a fixed-width UTC string), so a change in the mark's millisecond moves the mark instead of being announced on every look; the item wins a tie - acknowledging a cut look keeps its cut point wherever the other look does not vouch for it (after the other's newest time, or both cut), so a burst summed up as "more than 50" does not come back on the next start - more than 200 ids in the window: the oldest go and the cut point moves up to the oldest kept; when ids first arrive, the cut point is the old mark, so the change reported without an id is not reported again - a deferred look's `seen` carries the workspace and account it came from; `POST /altimate/workspace/activity/seen` answers 409 `scope_changed` after a relink or another sign-in, and writes nothing - without a `subject`, items are told apart by the whole name; names and the line are cut on whole characters (grapheme clusters where available) - the TUI clears the wait that lost the race with the startup replay - docs: a server without ids is asked from the last look itself, where a late or tied change can be missed - tests for each, with the stub server filtering to the microsecond Co-Authored-By: Claude Opus 5.5 --- docs/docs/usage/cli.md | 2 +- .../altimate/workspace/workspace-activity.ts | 137 ++++++++++++------ .../src/plugin/tui/altimate/rules.tsx | 2 + packages/opencode/src/server/server.ts | 8 +- .../workspace/workspace-activity.test.ts | 123 +++++++++++++++- .../test/server/altimate-rules-routes.test.ts | 17 ++- 6 files changed, 233 insertions(+), 56 deletions(-) diff --git a/docs/docs/usage/cli.md b/docs/docs/usage/cli.md index 88a106840a..d7488aee90 100644 --- a/docs/docs/usage/cli.md +++ b/docs/docs/usage/cli.md @@ -68,7 +68,7 @@ With workspaces on: - In a project linked to a workspace, integrations come only from the workspace's engine, so the `datamate_manager` tool is not offered there and refuses to run. `datamate-*` MCP servers already in the config still load, and a one-time notice names the file they are in; the config is not edited. - `altimate-code skill publish ` uploads a project skill to the linked workspace, attached directly for the workspace owner or an admin and sent for review for a member when review is on; see [Skills](../configure/skills.md#cli-commands). - When the owner or an admin approves or rejects one of your skill or knowledge base requests that altimate-code has seen pending (submitted from it, or listed by an earlier check), or that is decided after it began checking, the TUI shows a notice once in each project linked to that workspace, with the reason for a rejection. Every altimate-code process that opens a linked project checks at start and every 5 minutes while workspaces are on and you are signed in: it lists your own requests on the workspace (up to 10 pages of 50); a server without review is asked again only after 6 hours. The decision is kept per account and workspace in your own state directory (`$XDG_STATE_HOME/altimate-code/workspace-reviews/`, the 50 most recent), so a TUI that was closed or disconnected when it arrived shows it when it next starts. The first time a TUI opens a project, decisions already kept are recorded without a notice; `altimate-code workspace review status` lists them. Withdrawing a waiting request and removing an approved one happen in the web app or from `/rules` in the TUI, which lists your skill and knowledge requests with your rule proposals. Editor and agent plugins read decisions with `altimate-code workspace review decisions --json` (see [Skills](../configure/skills.md#cli-commands)), which always prints one JSON object and exits 0. When the owner or an admin removes one of yours that altimate-code has seen approved or waiting (up to the 200 approved ones it tracks per workspace), the TUI shows that once too, with the reason; your own removal and withdrawal show nothing. -- A few seconds after the TUI starts in a linked project, it says in one line what changed in the skills and knowledge the workspace gives its team since you last looked, for example "Since your last session in Growth: 2 skills added (naming, cost-guard), 1 knowledge base removed (Glossary)." It reads the workspace's recent changes (the last 30 days) and keeps when you last looked per account, workspace and client in your own state directory (`$XDG_STATE_HOME/altimate-code/workspace-activity/`); the first time it only records where to start from. All TUIs on the same account and workspace share one last look: usually the first to start shows the line and the others say nothing, though two that start at the same moment can both show it. Each look also asks again from a few minutes before the last one, so a change saved a little late is still reported, and a change it already reported is skipped. With more changes since the last look than it reads at once (50), it says there were more and names the newest instead of giving counts; a burst of more than 50 changes within a few minutes can leave a late one unreported. It waits while a review decision notice is showing; if one is still up after a minute, or the TUI closes first, the line is shown the next time instead. The VS Code extension asks `altimate-code serve` for the same line (`GET /altimate/workspace/activity?host=vscode`), with its own last look; a client can add `defer=1` and confirm with `POST /altimate/workspace/activity/seen` once it showed the line. Changes the service does not record (the owner detaching their own skill, the owner's knowledge selection) are not listed. +- A few seconds after the TUI starts in a linked project, it says in one line what changed in the skills and knowledge the workspace gives its team since you last looked, for example "Since your last session in Growth: 2 skills added (naming, cost-guard), 1 knowledge base removed (Glossary)." It reads the workspace's recent changes (the last 30 days) and keeps when you last looked per account, workspace and client in your own state directory (`$XDG_STATE_HOME/altimate-code/workspace-activity/`); the first time it only records where to start from. All TUIs on the same account and workspace share one last look: usually the first to start shows the line and the others say nothing, though two that start at the same moment can both show it. When the service gives each change an id, each look also asks again from a few minutes before the last one, so a change saved a little late is still reported, and a change it already reported is skipped; a service without ids is asked from the last look itself, so there a change saved late, or at the same moment as the last one it reported, can be missed. With more changes since the last look than it reads at once (50), it says there were more and names the newest instead of giving counts; a burst of more than 50 changes within a few minutes can leave a late one unreported. It waits while a review decision notice is showing; if one is still up after a minute, or the TUI closes first, the line is shown the next time instead. The VS Code extension asks `altimate-code serve` for the same line (`GET /altimate/workspace/activity?host=vscode`), with its own last look; a client can add `defer=1` and confirm with `POST /altimate/workspace/activity/seen` once it showed the line. Changes the service does not record (the owner detaching their own skill, the owner's knowledge selection) are not listed. - Workspace skills are synced at the version the workspace serves you: the approved version, or your own pending version of a skill you submitted. The next sync follows what the workspace serves: a skill whose first submission is rejected, or that is detached from the workspace, is removed from the project; when an update to an approved skill is rejected or replaced, the skill stays at its approved version. Each skill is downloaded as one version: if it is approved or rejected while its files are being read, nothing of it is installed from that sync and it is fetched again on the next one. When a download fails, the copy already in the project is kept only if it is still the version the workspace serves, as far as the server has said (its list, or a read refused because the version just changed), or if neither the copy nor the list names a version (a copy synced before revisions, or an older server), in which case it is kept until the server says otherwise; a copy of a version it no longer serves (for example your rejected pending version), or of a skill it no longer lists, is removed until the download succeeds, even when no other skill could be downloaded. Two processes syncing the same project take turns: a sync never replaces or removes a snapshot another process installed after it started, and the next sync starts from the newer one. - When the linked workspace has knowledge, the agent is told to check it for best practices and team conventions before answering, without you having to mention the knowledge base. - In an ordinary session the agent is told every turn which workspace the project is linked to — or that none is, or that the link could not be verified just now. In an extension-pinned session it is told the pinned workspace instead, and that it differs from the project's own link. Either way "which workspace am I in?" has an answer, and the agent is told not to confuse it with a Databricks workspace or an IDE workspace folder. diff --git a/packages/opencode/src/altimate/workspace/workspace-activity.ts b/packages/opencode/src/altimate/workspace/workspace-activity.ts index dd6ca109b8..d60c5c056d 100644 --- a/packages/opencode/src/altimate/workspace/workspace-activity.ts +++ b/packages/opencode/src/altimate/workspace/workspace-activity.ts @@ -93,33 +93,55 @@ type Scope = Seen["scope"] export const markOf = (value: Seen["seen"][string] | undefined): Mark | undefined => value === undefined ? undefined : typeof value === "string" ? { at: value, ids: [], overlap: false, from: "" } : value -/** A server time in milliseconds; one without a zone is UTC, as the server keeps them. */ -const ms = (at: string) => Date.parse(/(?:[zZ]|[+-]\d\d:?\d\d)$/.test(at) ? at : `${at}Z`) +/** How many reported ids a mark keeps: past that, the oldest go and `from` moves up to cover them. */ +const MAX_IDS = 200 + +/** A server time as a fixed-width UTC string with microseconds, which the server keeps: two of them compare as + * strings, exactly. One without a zone is UTC, as the server keeps them. `undefined` when it is not a time. */ +export function precise(at: string, shiftMs = 0): string | undefined { + const match = /^(\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d)(?:\.(\d+))?([zZ]|[+-]\d\d:?\d\d)?$/.exec(at) + if (!match) return undefined + const whole = Date.parse(`${match[1]}${match[3] ?? "Z"}`) + if (Number.isNaN(whole)) return undefined + // Offsets are whole minutes, so only the whole seconds move with them; the fraction is kept to the microsecond. + return `${new Date(whole + shiftMs).toISOString().slice(0, 19)}.${(match[2] ?? "").padEnd(6, "0").slice(0, 6)}Z` +} +const key = (at: string) => precise(at) ?? "" +const newest = (a: string, b: string) => (key(b) >= key(a) ? b : a) /** The `since` a look asks from. */ export function sinceOf(mark: Mark): string | undefined { if (!mark.at) return undefined if (!mark.overlap) return mark.at - const at = ms(mark.at) - return Number.isNaN(at) ? mark.at : new Date(at - OVERLAP_MS).toISOString() + return precise(mark.at, -OVERLAP_MS) ?? mark.at } -/** The mark after a look (or after merging two): the newest time, and the ids within `OVERLAP_MS` of it. `cut`: the - * look's page did not hold every change it asked for, so its ids are complete only from its oldest item. */ +/** The mark after a look (or after merging two): the newest time (the item's on a tie), and the ids within + * `OVERLAP_MS` of it. `from` is where the ids stop being complete: the oldest item of a `cut` page; the old mark when + * ids first arrive (it reported what came before without them); and the oldest id kept when more than `MAX_IDS` are + * in the window. */ export function advance(mark: Mark | undefined, items: Pick[], options: { cut?: boolean } = {}): Mark { - const times = [...(mark?.at ? [mark.at] : []), ...items.map((i) => i.at)].filter((at) => !Number.isNaN(ms(at))) - const at = times.reduce((a, b) => (a && ms(a) >= ms(b) ? a : b), "") || mark?.at || "" - const floor = at ? ms(at) - OVERLAP_MS : Number.NEGATIVE_INFINITY - const ids = new Map() + const times = [...(mark?.at ? [mark.at] : []), ...items.map((i) => i.at)].filter((at) => precise(at) !== undefined) + const at = times.reduce((a, b) => (a ? newest(a, b) : b), "") || mark?.at || "" + const floor = (at && precise(at, -OVERLAP_MS)) || "" + const window = new Map() for (const entry of [...(mark?.ids ?? []), ...items.flatMap((i) => (i.id ? [{ id: i.id, at: i.at }] : []))]) - if (ms(entry.at) > floor) ids.set(entry.id, entry.at) + if (key(entry.at) > floor) window.set(entry.id, entry.at) + const ids = [...window].map(([id, at]) => ({ id, at })).sort((a, b) => (key(a.at) < key(b.at) ? -1 : key(a.at) > key(b.at) ? 1 : 0)) + const kept = ids.slice(-MAX_IDS) + const turningOn = !(mark?.overlap ?? false) && Boolean(mark?.at) && items.some((i) => i.id !== undefined) const oldest = items.at(-1)?.at - const from = options.cut && oldest && ms(oldest) > floor ? oldest : "" + const froms = [ + ...(options.cut && oldest ? [oldest] : []), + ...(turningOn && mark ? [mark.at] : []), + ...(ids.length > kept.length ? [kept[0].at] : []), + ] + const from = froms.reduce((a, b) => (a ? newest(a, b) : b), "") return { at, - ids: [...ids].map(([id, at]) => ({ id, at })).slice(-200), + ids: kept, overlap: (mark?.overlap ?? false) || items.some((i) => i.id !== undefined), - from, + from: from && key(from) > floor ? from : "", } } @@ -129,17 +151,14 @@ function isFresh(mark: Mark | undefined, reported: Set, item: Item): boo if (item.id === undefined) return true if (reported.has(item.id)) return false if (!mark?.at || !mark.from) return true - return !(ms(item.at) <= ms(mark.at) && ms(item.at) <= ms(mark.from)) + return !(key(item.at) <= key(mark.at) && key(item.at) <= key(mark.from)) } /** Where each client's last look is kept. */ export const dir = () => path.join(Global.Path.state, "workspace-activity") -const fileOf = (scope: Scope) => - path.join( - dir(), - createHash("sha256").update(JSON.stringify([scope.apiUrl, scope.tenant, scope.account, scope.datamateId])).digest("hex") + - ".json", - ) +const scopeId = (scope: Scope) => + createHash("sha256").update(JSON.stringify([scope.apiUrl, scope.tenant, scope.account, scope.datamateId])).digest("hex") +const fileOf = (scope: Scope) => path.join(dir(), `${scopeId(scope)}.json`) async function readSeen(scope: Scope): Promise { const raw = await fs.readFile(fileOf(scope), "utf8").catch(() => undefined) @@ -168,8 +187,14 @@ async function writeSeen(state: Seen): Promise { const plural = (n: number, kind: Item["kind"]) => `${n} ${kind === "skill" ? (n === 1 ? "skill" : "skills") : n === 1 ? "knowledge base" : "knowledge bases"}` -const cap = (text: string, max: number) => (text.length > max ? `${text.slice(0, max - 1)}…` : text) -const nameOf = (item: Item) => cap(printable(item.name).trim(), NAME_MAX) +const segmenter = typeof Intl.Segmenter === "function" ? new Intl.Segmenter(undefined, { granularity: "grapheme" }) : undefined +/** `text` cut to `max` characters, ending with "…", never inside one. */ +const cap = (text: string, max: number) => { + const chars = segmenter ? Array.from(segmenter.segment(text), (s) => s.segment) : Array.from(text) + return chars.length > max ? `${chars.slice(0, max - 1).join("")}…` : text +} +const fullName = (item: Item) => printable(item.name).trim() +const nameOf = (item: Item) => cap(fullName(item), NAME_MAX) /** The one line: "Since your last session in X: 2 skills added (a, b), 1 knowledge base removed (c)." Items are counted * by `subject` (by name from a server without it), so several changes to one item count once per kind of change and @@ -188,7 +213,8 @@ export function summaryLine(workspaceName: string, items: Item[], hasMore = fals const key = `${item.kind}:${item.action}` const group = groups.get(key) ?? { kind: item.kind, action: item.action, subjects: new Set(), names: [] } const name = nameOf(item) - group.subjects.add(item.subject ?? `name:${name}`) + // Without a `subject`, the whole name tells items apart; only what is shown is cut. + group.subjects.add(item.subject ?? `name:${fullName(item)}`) if (name && !group.names.includes(name)) group.names.push(name) groups.set(key, group) } @@ -200,9 +226,13 @@ export function summaryLine(workspaceName: string, items: Item[], hasMore = fals return cap(`${where}: ${parts.join(", ")}.`, LINE_MAX) } +/** A deferred look's mark, with the workspace and account it belongs to. */ +export const SeenMark = Mark.extend({ scope: z.string() }) +export type SeenMark = z.infer + export type Changes = /** `seen`: with `defer`, the mark to hand back to `acknowledge` once the line was shown. */ - | { status: "ok"; workspace: { id: number; name: string }; items: Item[]; line?: string; seen?: Mark } + | { status: "ok"; workspace: { id: number; name: string }; items: Item[]; line?: string; seen?: SeenMark } /** First look for this client: where to start from is recorded, nothing is said. */ | { status: "first"; workspace: { id: number; name: string } } | { status: "signed_out" | "not_linked" | "account_changed" | "unconfirmed" | "unsupported" } @@ -258,15 +288,17 @@ export async function changesSince(directory: string, host: string, options: { d // (no local clock is involved). Otherwise the newest change it was given. const mark = markOf(state.seen[host]) const since = mark && sinceOf(mark) - // Whether a page reached back to the mark: then it holds every change after the mark, and `has_more` is about the - // overlap the look read again, not about news. - const reached = (items: Item[]) => - Boolean(mark?.at) && items.length > 0 && ms(items[items.length - 1].at) <= ms(mark!.at) + // How the page's oldest change compares with the mark, to the microsecond. At or below it: the page holds every + // change after the mark (newest first), so `has_more` is about the overlap the look read again, not about news. + // Changes at the mark itself were reported, or are below where the last look's ids stop (`from`). + const oldestVsMark = (items: Item[]) => + mark?.at && items.length > 0 ? key(items[items.length - 1].at).localeCompare(key(mark.at)) : 1 let page = await fetchActivity(workspace.id, since, actAs, LIMIT) // Cut inside the overlap: read again with the most the server gives, so a change that committed late is in it. - if (page.hasMore && mark?.overlap && reached(page.items)) page = await fetchActivity(workspace.id, since, actAs, MAX_LIMIT) + if (page.hasMore && mark?.overlap && oldestVsMark(page.items) <= 0) + page = await fetchActivity(workspace.id, since, actAs, MAX_LIMIT) const { items } = page - const hasMore = page.hasMore && !reached(items) + const hasMore = page.hasMore && !(oldestVsMark(items) <= 0) const reported = new Set(mark?.ids.map((entry) => entry.id)) const fresh = items.filter((item) => isFresh(mark, reported, item)) const next = advance(mark, items, { cut: page.hasMore }) @@ -277,7 +309,7 @@ export async function changesSince(directory: string, host: string, options: { d return { status: "first", workspace } } const line = summaryLine(workspace.name, fresh, hasMore) - if (line && options.defer) return { status: "ok", workspace, items: fresh, line, seen: next } + if (line && options.defer) return { status: "ok", workspace, items: fresh, line, seen: { ...next, scope: scopeId(scope) } } await save() return { status: "ok", workspace, items: fresh, ...(line ? { line } : {}) } }) @@ -286,26 +318,43 @@ export async function changesSince(directory: string, host: string, options: { d } } -/** The line from a deferred look was shown: record its mark, merged with any look since. Never throws. */ -export async function acknowledge(directory: string, host: string, seen: Mark): Promise<{ status: "ok" } | Changes> { +/** Where the ids of two looks merged stop being complete. A cut point holds where the other look does not vouch + * for it: after the other's newest time (the other never read there), or when the other was cut too (then the older + * point, below which neither read). A look that read its whole window up to and past a cut point vouches for it. */ +export function mergedFrom(current: Mark | undefined, seen: Mark): string { + const holds = (x: Mark | undefined, y: Mark | undefined) => + Boolean(x?.from) && (!y?.at || key(x!.from) > key(y.at) || Boolean(y.from)) + const points = [...(holds(seen, current) ? [seen.from] : []), ...(holds(current, seen) ? [current!.from] : [])] + if (points.length < 2) return points[0] ?? "" + // Both hold. After the other's newest time, each is the only one that read there: the newer point covers both. + const past = points.filter((p, i) => key(p) > key((i === 0 ? current : seen)?.at ?? "")) + if (past.length > 0) return past.reduce((a, b) => newest(a, b)) + return points.reduce((a, b) => (key(a) <= key(b) ? a : b)) +} + +/** The line from a deferred look was shown: record its mark, merged with any look since. A mark from another + * workspace or account (relinked, or signed in as someone else, since the look) is refused: `scope_changed`. Never + * throws. */ +export async function acknowledge( + directory: string, + host: string, + seen: SeenMark, +): Promise<{ status: "ok" | "scope_changed" } | Changes> { try { const where = await locate(directory) if (!where.ok) return where.changes const { scope } = where + if (seen.scope !== scopeId(scope)) return { status: "scope_changed" as const } + const { scope: _scope, ...look } = seen return await locked(scope, async () => { const state = await readSeen(scope) const current = markOf(state.seen[host]) - const merged = advance(current ? { ...current, overlap: current.overlap || seen.overlap } : seen, [ - ...seen.ids, - ...(seen.at ? [{ at: seen.at }] : []), + const merged = advance(current ? { ...current, overlap: current.overlap || look.overlap } : look, [ + ...look.ids, + ...(look.at ? [{ at: look.at }] : []), ]) - // Ids are incomplete only below where both looks stopped reading: a look that read its whole window - // vouches for it, so only when both were cut does the older cut point hold. - const froms = [current?.from, seen.from] - if (froms.every(Boolean)) { - const older = (froms as string[]).sort((a, b) => ms(a) - ms(b))[0] - if (ms(older) > ms(merged.at) - OVERLAP_MS) merged.from = older - } + const from = mergedFrom(current, look) + merged.from = from && key(from) > ((merged.at && precise(merged.at, -OVERLAP_MS)) || "") ? from : "" await writeSeen({ ...state, seen: { ...state.seen, [host]: merged } }) return { status: "ok" as const } }) diff --git a/packages/opencode/src/plugin/tui/altimate/rules.tsx b/packages/opencode/src/plugin/tui/altimate/rules.tsx index 96f263bf26..af529d4261 100644 --- a/packages/opencode/src/plugin/tui/altimate/rules.tsx +++ b/packages/opencode/src/plugin/tui/altimate/rules.tsx @@ -520,6 +520,8 @@ function installCards(api: TuiPluginApi) { }) const showActivity = async () => { await Promise.race([startupReplay, wait(ACTIVITY_REPLAY_WAIT_MS)]) + // The replay may have won: its wait is not left running, so dispose clears every timer still pending. + if (activityTimer) clearTimeout(activityTimer) if (disposed) return const answer = await get<{ ok: boolean; status?: string; line?: string; seen?: unknown }>( api, diff --git a/packages/opencode/src/server/server.ts b/packages/opencode/src/server/server.ts index 7b6b1842fc..1ce4fe01f8 100644 --- a/packages/opencode/src/server/server.ts +++ b/packages/opencode/src/server/server.ts @@ -1489,9 +1489,13 @@ export namespace Server { if (!/^[a-z][a-z0-9-]{0,31}$/.test(host)) return c.json({ ok: false, error: "host must name the client, e.g. vscode." }, 400) try { const { WorkspaceActivity } = await import("../altimate/workspace/workspace-activity") - const seen = WorkspaceActivity.Mark.safeParse(read.body.seen) + const seen = WorkspaceActivity.SeenMark.safeParse(read.body.seen) if (!seen.success) return c.json({ ok: false, error: "seen must be the mark a deferred look returned." }, 400) - return c.json({ ok: true as const, ...(await WorkspaceActivity.acknowledge(Instance.directory, host, seen.data)) }) + const result = await WorkspaceActivity.acknowledge(Instance.directory, host, seen.data) + // The project was relinked, or another account signed in, since the look: its mark is not this workspace's. + if (result.status === "scope_changed") + return c.json({ ok: false, status: result.status, error: "The workspace or account changed since that look." }, 409) + return c.json({ ok: true as const, ...result }) } catch (err) { const error = err instanceof Error ? err.message : String(err) log.error("workspace activity seen failed", { error }) diff --git a/packages/opencode/test/altimate/workspace/workspace-activity.test.ts b/packages/opencode/test/altimate/workspace/workspace-activity.test.ts index ec6b2899fd..de92c16232 100644 --- a/packages/opencode/test/altimate/workspace/workspace-activity.test.ts +++ b/packages/opencode/test/altimate/workspace/workspace-activity.test.ts @@ -47,11 +47,13 @@ const tracked = (id: string, name: string, action: string, at: string, kind = "s let asked: (string | undefined)[] = [] let limits: number[] = [] let activity: (since: string | undefined, limit: number) => Response = () => reply({ items: [], has_more: false }) -/** A server holding `changes`: newest first (ties by id, newest first), after `since`, at most `limit`. */ -const server = (changes: ReturnType[]) => (since: string | undefined, limit: number) => { +/** A server holding `changes`: newest first (ties by id, newest first), after `since` to the microsecond as the + * service compares, at most `limit`. Changes without ids sort by time only. */ +const server = (changes: { at: string; id?: string }[]) => (since: string | undefined, limit: number) => { + const at = (value: string) => WorkspaceActivity.precise(value) ?? "" const after = changes - .filter((c) => since === undefined || Date.parse(c.at) > Date.parse(since)) - .sort((a, b) => Date.parse(b.at) - Date.parse(a.at) || b.id.localeCompare(a.id, undefined, { numeric: true })) + .filter((c) => since === undefined || at(c.at) > at(since)) + .sort((a, b) => at(b.at).localeCompare(at(a.at)) || (b.id ?? "").localeCompare(a.id ?? "", undefined, { numeric: true })) return reply({ items: after.slice(0, limit), has_more: after.length > limit }) } let project = "" @@ -162,7 +164,7 @@ describe("changes that commit late, and what was already reported", () => { has_more: false, }) const next = await WorkspaceActivity.changesSince(project, "tui") - expect(asked[1]).toBe("2026-11-12T09:55:00.000Z") + expect(asked[1]).toBe("2026-11-12T09:55:00.000000Z") expect(next.status === "ok" && next.line).toBe("Since your last session in Growth: 1 skill added (late).") // Both are reported now: nothing more to say. const quiet = await WorkspaceActivity.changesSince(project, "tui") @@ -182,7 +184,7 @@ describe("changes that commit late, and what was already reported", () => { }) // A server time without a zone is UTC. expect(WorkspaceActivity.sinceOf({ at: "2026-11-12T10:00:00", ids: [], overlap: true, from: "" })).toBe( - "2026-11-12T09:55:00.000Z", + "2026-11-12T09:55:00.000000Z", ) }) }) @@ -208,6 +210,16 @@ describe("more changes than a page, under the overlap", () => { expect(quiet.status === "ok" && quiet.line).toBeUndefined() }) + test("a page cut at the mark's own time still holds every change after it: the count is exact", async () => { + // 120 changes at one time, more than the most one answer holds: the first look reads 50 of them. + const changes = bulk(120, "2026-11-12T10:00:00Z") + activity = server(changes) + expect((await WorkspaceActivity.changesSince(project, "tui")).status).toBe("first") + changes.push(tracked("n1", "naming", "added", "2026-11-12T10:00:30Z")) + const next = await WorkspaceActivity.changesSince(project, "tui") + expect(next.status === "ok" && next.line).toBe("Since your last session in Growth: 1 skill added (naming).") + }) + test("more changes after the mark than a page holds still say there were more", async () => { activity = server([tracked("o1", "old", "added", "2026-11-12T10:00:00Z")]) expect((await WorkspaceActivity.changesSince(project, "tui")).status).toBe("first") @@ -217,6 +229,60 @@ describe("more changes than a page, under the overlap", () => { }) }) +describe("times to the microsecond, as the server keeps them", () => { + test("a change in the same millisecond as the mark is reported once, then the mark moves past it", async () => { + // A server without ids: each look asks from the mark itself. + const changes: { at: string; kind: string; name: string; action: string }[] = [ + change("first", "added", "2026-11-12T09:00:00.123456Z"), + ] + activity = server(changes) + expect((await WorkspaceActivity.changesSince(project, "tui")).status).toBe("first") + changes.push(change("same-millisecond", "added", "2026-11-12T09:00:00.123789Z")) + const next = await WorkspaceActivity.changesSince(project, "tui") + expect(next.status === "ok" && next.line).toBe("Since your last session in Growth: 1 skill added (same-millisecond).") + expect(asked[1]).toBe("2026-11-12T09:00:00.123456Z") + const quiet = await WorkspaceActivity.changesSince(project, "tui") + expect(quiet.status === "ok" && quiet.line).toBeUndefined() + expect(asked[2]).toBe("2026-11-12T09:00:00.123789Z") + }) + + test("times compare exactly, whatever their zone or digits", () => { + expect(WorkspaceActivity.precise("2026-11-12T10:00:00.5+05:30")).toBe("2026-11-12T04:30:00.500000Z") + expect(WorkspaceActivity.precise("2026-11-12T10:00:00")).toBe("2026-11-12T10:00:00.000000Z") + expect(WorkspaceActivity.precise("not a time")).toBeUndefined() + }) +}) + +describe("when the server starts giving ids", () => { + test("the change the last look reported without an id is not reported again", async () => { + const changes: { at: string; id?: string }[] = [change("before", "added", "2026-11-12T10:00:00Z")] + activity = server(changes) + expect((await WorkspaceActivity.changesSince(project, "tui")).status).toBe("first") + // The server is updated: ids from now on, for old changes too. + changes.splice(0, 1, tracked("e0", "before", "added", "2026-11-12T10:00:00Z")) + changes.push(tracked("e1", "after", "added", "2026-11-12T10:01:00Z")) + const next = await WorkspaceActivity.changesSince(project, "tui") + expect(next.status === "ok" && next.line).toBe("Since your last session in Growth: 1 skill added (after).") + // The next look reads from 5 minutes before the mark: "before" is in it, and is history. + const quiet = await WorkspaceActivity.changesSince(project, "tui") + expect(quiet.status === "ok" && quiet.line).toBeUndefined() + }) +}) + +describe("more ids in the window than a mark keeps", () => { + test("the oldest go, and the cut point moves up to cover them", () => { + const items = Array.from({ length: 250 }, (_, i) => ({ + id: `e${i}`, + at: `2026-11-12T10:00:${String(Math.floor(i / 5)).padStart(2, "0")}.${String(i % 5).padStart(6, "0")}Z`, + })).reverse() + const mark = WorkspaceActivity.advance(undefined, items) + expect(mark.ids).toHaveLength(200) + // The 50 oldest went; the oldest kept is e50, and below it unknown ids are history. + expect(mark.ids[0]).toEqual({ id: "e50", at: "2026-11-12T10:00:10.000000Z" }) + expect(mark.from).toBe("2026-11-12T10:00:10.000000Z") + }) +}) + describe("a deferred look", () => { test("keeps the mark until the line was shown, so a client that goes away first shows it next time", async () => { activity = () => reply({ items: [], has_more: false }) @@ -233,6 +299,38 @@ describe("a deferred look", () => { expect(after.status === "ok" && after.line).toBeUndefined() }) + test("acknowledging a cut look after a complete one keeps its overflow from coming back", async () => { + const changes: ReturnType[] = [tracked("o1", "old", "added", "2026-11-12T09:00:00Z")] + activity = server(changes) + expect((await WorkspaceActivity.changesSince(project, "tui")).status).toBe("first") + // A complete look: nothing new. + expect((await WorkspaceActivity.changesSince(project, "tui")).status).toBe("ok") + // 70 skills attached in one save, an hour later. + for (let i = 0; i < 70; i++) changes.push(tracked(`b${i}`, `bulk-${i}`, "added", "2026-11-12T10:00:00Z")) + const shown = await WorkspaceActivity.changesSince(project, "tui", { defer: true }) + expect(shown.status === "ok" && shown.line).toStartWith("Since your last session in Growth: more than 50 changes") + if (shown.status !== "ok" || !shown.seen) throw new Error("expected a mark to acknowledge") + expect(await WorkspaceActivity.acknowledge(project, "tui", shown.seen)).toEqual({ status: "ok" }) + // The next start says nothing: the 20 it did not name were summed up as "more than 50". + const next = await WorkspaceActivity.changesSince(project, "tui", { defer: true }) + expect(next.status === "ok" && next.line).toBeUndefined() + }) + + test("a mark from before a relink is refused, and the new workspace's look is untouched", async () => { + activity = () => reply({ items: [], has_more: false }) + expect((await WorkspaceActivity.changesSince(project, "tui")).status).toBe("first") + activity = server([tracked("e1", "naming", "added", "2026-11-12T10:00:00Z")]) + const shown = await WorkspaceActivity.changesSince(project, "tui", { defer: true }) + if (shown.status !== "ok" || !shown.seen) throw new Error("expected a mark to acknowledge") + // Relinked to another workspace while the line waited to be shown. + await recordApprovedBinding( + project, + { datamateId: 43, datamateName: "Other", repoRemote: null, projectPath: project, linkedAt: Date.now() } as never, + { awaitBackfill: true }, + ) + expect(await WorkspaceActivity.acknowledge(project, "tui", shown.seen)).toEqual({ status: "scope_changed" }) + }) + test("acknowledging an older look keeps what a look in between recorded", async () => { activity = () => reply({ items: [], has_more: false }) expect((await WorkspaceActivity.changesSince(project, "tui")).status).toBe("first") @@ -247,7 +345,7 @@ describe("a deferred look", () => { // The newer mark holds: nothing is said again. const after = await WorkspaceActivity.changesSince(project, "tui") expect(after.status === "ok" && after.line).toBeUndefined() - expect(asked.at(-1)).toBe("2026-11-12T10:55:00.000Z") + expect(asked.at(-1)).toBe("2026-11-12T10:55:00.000000Z") }) test("a cut look acknowledged after a complete one does not hide later changes as history", async () => { @@ -294,6 +392,17 @@ describe("the line", () => { ) }) + test("without a subject, long names that share their first characters are still two items", () => { + const items = [change(`${"x".repeat(40)}A`, "added", "2"), change(`${"x".repeat(40)}B`, "added", "1")] as never + expect(WorkspaceActivity.summaryLine("Growth", items)).toStartWith("Since your last session in Growth: 2 skills added (") + }) + + test("a cut never splits a character", () => { + const line = WorkspaceActivity.summaryLine("Growth", [change("😀".repeat(45), "added", "1")] as never)! + expect(line).toBe(`Since your last session in Growth: 1 skill added (${"😀".repeat(39)}…).`) + expect(line).not.toMatch(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])/) + }) + test("caps long names and the whole line, and leaves out an empty name", () => { const long = "x".repeat(300) const line = WorkspaceActivity.summaryLine( diff --git a/packages/opencode/test/server/altimate-rules-routes.test.ts b/packages/opencode/test/server/altimate-rules-routes.test.ts index 7c946fb25e..d468d41c2e 100644 --- a/packages/opencode/test/server/altimate-rules-routes.test.ts +++ b/packages/opencode/test/server/altimate-rules-routes.test.ts @@ -204,7 +204,13 @@ describe("workspace activity routes", () => { test("a deferred look is passed through, and its mark comes back for the client to confirm", async () => { const { WorkspaceActivity } = await import("../../src/altimate/workspace/workspace-activity") const { spyOn } = await import("bun:test") - const seen = { at: "2026-11-12T10:00:00Z", ids: [{ id: "e1", at: "2026-11-12T10:00:00Z" }], overlap: true, from: "" } + const seen = { + at: "2026-11-12T10:00:00Z", + ids: [{ id: "e1", at: "2026-11-12T10:00:00Z" }], + overlap: true, + from: "", + scope: "s-1", + } const look = spyOn(WorkspaceActivity, "changesSince").mockResolvedValue({ status: "ok", workspace: { id: 42, name: "Growth" }, @@ -235,17 +241,24 @@ describe("workspace activity routes", () => { { host: "tui" }, { host: "tui", seen: { at: 5 } }, { host: "tui", seen: "2026-11-12T10:00:00Z" }, + // A mark without the workspace and account it came from. + { host: "tui", seen: { at: "2026-11-12T10:00:00Z", ids: [], overlap: true, from: "" } }, ]) { const response = await request("POST", "/altimate/workspace/activity/seen", body) expect(response.status).toBe(400) expect(await response.json()).toMatchObject({ ok: false }) } expect(acknowledge).not.toHaveBeenCalled() - const seen = { at: "2026-11-12T10:00:00Z", ids: [], overlap: true, from: "" } + const seen = { at: "2026-11-12T10:00:00Z", ids: [], overlap: true, from: "", scope: "s-1" } const ok = await request("POST", "/altimate/workspace/activity/seen", { host: "tui", seen }) expect(await ok.json()).toEqual({ ok: true, status: "ok" }) expect(acknowledge.mock.calls[0]?.[1]).toBe("tui") expect(acknowledge.mock.calls[0]?.[2]).toEqual(seen) + // Relinked or signed in as someone else since the look. + acknowledge.mockResolvedValue({ status: "scope_changed" }) + const moved = await request("POST", "/altimate/workspace/activity/seen", { host: "tui", seen }) + expect(moved.status).toBe(409) + expect(await moved.json()).toMatchObject({ ok: false, status: "scope_changed" }) } finally { acknowledge.mockRestore() } From b70bd98d93d842ee250d1a6ef55a7d4f98ad3135 Mon Sep 17 00:00:00 2001 From: Sarav Date: Tue, 17 Nov 2026 19:11:02 +0530 Subject: [PATCH 7/7] fix: a deferred look acknowledged when ids first appear does not report a change again A mark recorded without ids vouches for nothing, so it no longer clears the cut point the first look with ids sets. Acknowledging also keeps the cut point eviction set. Two tests now check what their names say: a relinked mark writes nothing for the new workspace, and a late change below a cleared cut point is reported. Co-Authored-By: Claude Opus 5.5 --- .../altimate/workspace/workspace-activity.ts | 8 ++++--- .../workspace/workspace-activity.test.ts | 22 +++++++++++++++++++ 2 files changed, 27 insertions(+), 3 deletions(-) diff --git a/packages/opencode/src/altimate/workspace/workspace-activity.ts b/packages/opencode/src/altimate/workspace/workspace-activity.ts index d60c5c056d..ac1c13ea7a 100644 --- a/packages/opencode/src/altimate/workspace/workspace-activity.ts +++ b/packages/opencode/src/altimate/workspace/workspace-activity.ts @@ -320,10 +320,11 @@ export async function changesSince(directory: string, host: string, options: { d /** Where the ids of two looks merged stop being complete. A cut point holds where the other look does not vouch * for it: after the other's newest time (the other never read there), or when the other was cut too (then the older - * point, below which neither read). A look that read its whole window up to and past a cut point vouches for it. */ + * point, below which neither read). A look that read its whole window up to and past a cut point vouches for it; a + * look recorded without ids (an older server) vouches for nothing. */ export function mergedFrom(current: Mark | undefined, seen: Mark): string { const holds = (x: Mark | undefined, y: Mark | undefined) => - Boolean(x?.from) && (!y?.at || key(x!.from) > key(y.at) || Boolean(y.from)) + Boolean(x?.from) && (!y?.at || !y.overlap || key(x!.from) > key(y.at) || Boolean(y.from)) const points = [...(holds(seen, current) ? [seen.from] : []), ...(holds(current, seen) ? [current!.from] : [])] if (points.length < 2) return points[0] ?? "" // Both hold. After the other's newest time, each is the only one that read there: the newer point covers both. @@ -353,7 +354,8 @@ export async function acknowledge( ...look.ids, ...(look.at ? [{ at: look.at }] : []), ]) - const from = mergedFrom(current, look) + // The newer of the merged looks' cut point and one `advance` set when it evicted ids. + const from = [mergedFrom(current, look), merged.from].filter(Boolean).reduce((a, b) => newest(a, b), "") merged.from = from && key(from) > ((merged.at && precise(merged.at, -OVERLAP_MS)) || "") ? from : "" await writeSeen({ ...state, seen: { ...state.seen, [host]: merged } }) return { status: "ok" as const } diff --git a/packages/opencode/test/altimate/workspace/workspace-activity.test.ts b/packages/opencode/test/altimate/workspace/workspace-activity.test.ts index de92c16232..46c1c2fcd3 100644 --- a/packages/opencode/test/altimate/workspace/workspace-activity.test.ts +++ b/packages/opencode/test/altimate/workspace/workspace-activity.test.ts @@ -269,6 +269,22 @@ describe("when the server starts giving ids", () => { }) }) +describe("when the server starts giving ids, on a deferred look", () => { + test("the change reported without an id is not reported again after the acknowledgement", async () => { + const changes: { at: string; id?: string }[] = [change("before", "added", "2026-11-12T10:00:00Z")] + activity = server(changes) + expect((await WorkspaceActivity.changesSince(project, "tui")).status).toBe("first") + changes.splice(0, 1, tracked("e0", "before", "added", "2026-11-12T10:00:00Z")) + changes.push(tracked("e1", "after", "added", "2026-11-12T10:01:00Z")) + const shown = await WorkspaceActivity.changesSince(project, "tui", { defer: true }) + expect(shown.status === "ok" && shown.line).toBe("Since your last session in Growth: 1 skill added (after).") + if (shown.status !== "ok" || !shown.seen) throw new Error("expected a mark to acknowledge") + expect(await WorkspaceActivity.acknowledge(project, "tui", shown.seen)).toEqual({ status: "ok" }) + const next = await WorkspaceActivity.changesSince(project, "tui", { defer: true }) + expect(next.status === "ok" && next.line).toBeUndefined() + }) +}) + describe("more ids in the window than a mark keeps", () => { test("the oldest go, and the cut point moves up to cover them", () => { const items = Array.from({ length: 250 }, (_, i) => ({ @@ -329,6 +345,8 @@ describe("a deferred look", () => { { awaitBackfill: true }, ) expect(await WorkspaceActivity.acknowledge(project, "tui", shown.seen)).toEqual({ status: "scope_changed" }) + // Nothing was written for the new workspace: its first look only records where to start. + expect((await WorkspaceActivity.changesSince(project, "tui")).status).toBe("first") }) test("acknowledging an older look keeps what a look in between recorded", async () => { @@ -364,6 +382,10 @@ describe("a deferred look", () => { .filter((f) => f.endsWith(".json")) .map((f) => JSON.parse(readFileSync(path.join(WorkspaceActivity.dir(), f), "utf8"))) expect(stored.map((state) => state.seen?.tui?.from)).toEqual([""]) + // A change that commits late, stamped below that cut point, is still reported. + changes.push(tracked("e3", "late", "added", "2026-11-12T09:59:30Z")) + const next = await WorkspaceActivity.changesSince(project, "tui") + expect(next.status === "ok" && next.line).toBe("Since your last session in Growth: 1 skill added (late).") }) })