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.", + ) + }) +})