diff --git a/docs/docs/usage/cli.md b/docs/docs/usage/cli.md index 5439457d0e..d7488aee90 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. 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 new file mode 100644 index 0000000000..ac1c13ea7a --- /dev/null +++ b/packages/opencode/src/altimate/workspace/workspace-activity.ts @@ -0,0 +1,368 @@ +// 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 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" +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: 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. */ +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"]), + 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") + } +} + +/** 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, 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 + +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. 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, from: "" } : value + +/** 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 + return precise(mark.at, -OVERLAP_MS) ?? mark.at +} + +/** 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) => 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 (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 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: kept, + overlap: (mark?.overlap ?? false) || items.some((i) => i.id !== undefined), + from: from && key(from) > floor ? 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 !(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 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) + 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"}` + +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 + * 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 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, subjects: new Set(), names: [] } + const name = nameOf(item) + // 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) + } + 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(subjects.size, kind)} ${action}${names.length ? ` (${shown}${more})` : ""}` + }) + 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?: 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" } + | { status: "failed"; error: string } + +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 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 since = mark && sinceOf(mark) + // 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 && oldestVsMark(page.items) <= 0) + page = await fetchActivity(workspace.id, since, actAs, MAX_LIMIT) + const { items } = page + 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 }) + 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, scope: scopeId(scope) } } + await save() + return { status: "ok", workspace, items: fresh, ...(line ? { line } : {}) } + }) + } catch (error) { + return failure(error) + } +} + +/** 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; 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 || !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. + 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 || look.overlap } : look, [ + ...look.ids, + ...(look.at ? [{ at: look.at }] : []), + ]) + // 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 } + }) + } catch (error) { + return failure(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 3733fe7fae..24252dff82 100644 --- a/packages/opencode/src/plugin/tui/altimate/rules.tsx +++ b/packages/opencode/src/plugin/tui/altimate/rules.tsx @@ -461,8 +461,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 @@ -477,8 +477,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 @@ -499,15 +499,56 @@ 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 (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)]) + // 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, + "/altimate/workspace/activity?host=tui&defer=1", + ) + if (disposed || typeof answer?.line !== "string") return + const line = printable(answer.line) + 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?.() + // 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() @@ -569,6 +610,34 @@ 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 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 c2c42eacc7..283c322e07 100644 --- a/packages/opencode/src/server/server.ts +++ b/packages/opencode/src/server/server.ts @@ -1505,6 +1505,49 @@ 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. 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) + 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, { 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 }) + } catch (err) { + const error = err instanceof Error ? err.message : String(err) + log.error("workspace activity failed", { error }) + 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.SeenMark.safeParse(read.body.seen) + if (!seen.success) return c.json({ ok: false, error: "seen must be the mark a deferred look returned." }, 400) + 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 }) + 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..46c1c2fcd3 --- /dev/null +++ b/packages/opencode/test/altimate/workspace/workspace-activity.test.ts @@ -0,0 +1,465 @@ +// 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, readdirSync, readFileSync, 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, +}) +/** 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` (undefined: none) and `limit` each activity request sent, and the answer it gets. */ +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` 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 || 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 = "" + +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-")) + 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 + const limit = Number(url.searchParams.get("limit")) + asked.push(since) + limits.push(limit) + return activity(since, limit) + } + 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("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.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") + 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, 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, + from: "", + }) + // 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.000000Z", + ) + }) +}) + +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("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") + 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") + }) +}) + +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("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) => ({ + 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 }) + 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() + }) + + 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" }) + // 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 () => { + 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.000000Z") + }) + + 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([""]) + // 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).") + }) +}) + +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("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( + "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"), + 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: 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 20e4bbe207..a1ce729937 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, requestActionsTitle, requestsProblem, shownKey } from "../../../src/plugin/tui/altimate/rules" +import { announceWhenClear, combinedToast, decisionToast, decisionToaster, requestActionsTitle, requestsProblem, shownKey } from "../../../src/plugin/tui/altimate/rules" import type { WorkspaceRequest } from "../../../src/plugin/tui/altimate/rules" describe("rules TUI", () => { @@ -98,6 +98,33 @@ describe("rules TUI", () => { }) }) +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 }) + }) +}) + describe("requestActionsTitle", () => { const request = (over: Partial & { kind?: "skill" | "knowledge" }): WorkspaceRequest & { kind: "skill" | "knowledge" } => ({ kind: "skill", diff --git a/packages/opencode/test/server/altimate-rules-routes.test.ts b/packages/opencode/test/server/altimate-rules-routes.test.ts index 72a3731002..bd7f2faf3f 100644 --- a/packages/opencode/test/server/altimate-rules-routes.test.ts +++ b/packages/opencode/test/server/altimate-rules-routes.test.ts @@ -207,3 +207,80 @@ 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: "", + scope: "s-1", + } + 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" }, + // 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: "", 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() + } + }) +})