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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions docs/docs/usage/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <name>` 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.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3: The wait is bounded: the TUI retries four times at 5-second intervals, then shows the line even if a decision notice is still up. Say so, or the docs overstate the guarantee.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At docs/docs/usage/cli.md, line 71:

<comment>The wait is bounded: the TUI retries four times at 5-second intervals, then shows the line even if a decision notice is still up. Say so, or the docs overstate the guarantee.</comment>

<file context>
@@ -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 <name>` 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.
</file context>

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3: The scope list is incomplete: the last-look marker is also kept per server and tenant (the state key includes the API URL and tenant). Name them here so readers know switching server or tenant starts a fresh baseline.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At docs/docs/usage/cli.md, line 71:

<comment>The scope list is incomplete: the last-look marker is also kept per server and tenant (the state key includes the API URL and tenant). Name them here so readers know switching server or tenant starts a fresh baseline.</comment>

<file context>
@@ -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 <name>` 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.
</file context>

- 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.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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" }
Expand Down
171 changes: 171 additions & 0 deletions packages/opencode/src/altimate/workspace/workspace-activity.ts
Original file line number Diff line number Diff line change
@@ -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 (`<state>/workspace-activity/<digest>.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<typeof Item>

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<unknown>("GET", `/${datamateId}/activity`, {
base: "/datamates",
actAs,
query: { limit: String(limit), ...(since ? { since } : {}) },

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

WARNING: A server without the activity route reports an API-error row on every start

review-api.ts:127-132 passes expectedStatuses: [404] for exactly this reason ("A server or tenant without review answers 404 here on every poll: an answer, not an API error to report"). fetchActivity does not, so until altimate-backend#7876 is live on every tenant, each TUI start and extension connect sends a 404 that reportApiErrorRow records as workspace_api_error (api-client.ts:497-504). classify still maps it to unsupported afterwards, so the caller is unaffected — the row is pure telemetry noise. Passing expectedStatuses: [404] in this options object fixes it.

})
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<typeof Seen>
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<Seen> {
const raw = await fs.readFile(fileOf(scope), "utf8").catch(() => undefined)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: readSeen treats every read failure as a missing marker. A transient I/O or permission error can reset the client baseline and silently lose or duplicate activity; only ignore ENOENT and propagate other errors.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At packages/opencode/src/altimate/workspace/workspace-activity.ts, line 77:

<comment>`readSeen` treats every read failure as a missing marker. A transient I/O or permission error can reset the client baseline and silently lose or duplicate activity; only ignore `ENOENT` and propagate other errors.</comment>

<file context>
@@ -0,0 +1,171 @@
+  )
+
+async function readSeen(scope: Scope): Promise<Seen> {
+  const raw = await fs.readFile(fileOf(scope), "utf8").catch(() => undefined)
+  if (raw !== undefined) {
+    try {
</file context>
Suggested change
const raw = await fs.readFile(fileOf(scope), "utf8").catch(() => undefined)
const raw = await fs.readFile(fileOf(scope), "utf8").catch((error: unknown) => {
if (error && typeof error === "object" && "code" in error && error.code === "ENOENT") return undefined
throw error
})

if (raw !== undefined) {
try {
const state = Seen.parse(JSON.parse(raw))
if (JSON.stringify(state.scope) === JSON.stringify(scope)) return state
Comment on lines +80 to +81

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[🟠 MEDIUM] Relying on JSON.stringify for equality checking is brittle as it strictly depends on the property insertion order of objects. If the Zod parsed object or runtime construction ever alters the key order, this condition could evaluate to false, leading to a silent reset of the user's notification tracking state. Consider explicitly comparing the individual properties instead.

Suggested change:

Suggested change
const state = Seen.parse(JSON.parse(raw))
if (JSON.stringify(state.scope) === JSON.stringify(scope)) return state
const state = Seen.parse(JSON.parse(raw))
if (
state.scope.apiUrl === scope.apiUrl &&
state.scope.tenant === scope.tenant &&
state.scope.account === scope.account &&
state.scope.datamateId === scope.datamateId
) {
return state
}

} catch {}
}
return { version: 1, scope, seen: {} }
}

async function writeSeen(state: Seen): Promise<void> {
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<string, { kind: Item["kind"]; action: Item["action"]; 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)
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<Changes> {
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 })

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SUGGESTION: Redundant directory creation

writeSeen (line 89) and Flock.acquire (packages/core/src/util/flock.ts:320) both mkdir this same path, so this call duplicates them, and dir() is recomputed several times per call (here, in fileOf, and through the lock key). Computing it once and passing it down would remove the repetition.

return await Flock.withLock(
`workspace-activity:${path.basename(fileOf(scope))}`,
async (): Promise<Changes> => {
Comment on lines +147 to +149

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[🔴 HIGH] The lock name string passed to Flock.withLock contains a colon (:). If Flock.withLock uses this identifier directly to construct a lock file or directory on the filesystem, it will crash on Windows OS, where colons are strictly prohibited in filenames (except for drive letters). Consider using a safe character like a hyphen (-) instead.

Suggested change:

Suggested change
return await Flock.withLock(
`workspace-activity:${path.basename(fileOf(scope))}`,
async (): Promise<Changes> => {
return await Flock.withLock(
`workspace-activity-${path.basename(fileOf(scope))}`,
async (): Promise<Changes> => {

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 ?? ""

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SUGGESTION: Changes past the 20-item cap are never shown

When hasMore is true the mark still jumps to the newest change, so the items between the previous mark and the 20th newest are excluded from every later since query: the line says "and more", but those changes can never be seen afterwards. Consider paging from the previous mark until it is reached (then the mark is honest), or wording the suffix as a capped sample.

if (mark !== since) await writeSeen({ ...state, seen: { ...state.seen, [host]: mark } })
Comment on lines +156 to +157

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[🟠 MEDIUM] If the host parameter provided to changesSince is a dynamically generated identifier (like a unique session ID or UUID) rather than a bounded set of client names (e.g., 'ide' or 'tui'), the state.seen record stored in the local JSON file will grow indefinitely over time. This could lead to a storage and performance leak. Please ensure host is properly restricted or validated to prevent unbounded growth.

if (first) return { status: "first", workspace }
const line = summaryLine(workspace.name, items, hasMore)
return { status: "ok", workspace, items, ...(line ? { line } : {}) }

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

WARNING: items reaches clients with raw, non-printable server text

Item.name and actor_name are returned exactly as the server sent them, while the sibling /altimate/workspace/requests route makes every server string printable before responding (fromContribution, ruleRequests in review-requests.ts). Skill names are member-controlled, so they can carry terminal escapes or bidi controls; the TUI re-sanitizes line, but the VS Code extension is a separate consumer of this same payload and nothing in this repo guarantees it sanitizes. Either drop items from the response (no client here reads it — only line) or return printable(item.name).

},
{ 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"
29 changes: 29 additions & 0 deletions packages/opencode/src/plugin/tui/altimate/rules.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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<typeof setTimeout> | undefined
const showActivity = async () => {
if (disposed) return
const answer = await get<{ ok: boolean; status?: string; line?: string }>(api, "/altimate/workspace/activity?host=tui")

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: This request advances the activity marker before the summary is presented. If the TUI closes while the request or retry is in progress, disposal skips the toast but the next session sees the change as already read; acknowledge it only after presentation or preserve the pending summary for the next session.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At packages/opencode/src/plugin/tui/altimate/rules.tsx, line 509:

<comment>This request advances the activity marker before the summary is presented. If the TUI closes while the request or retry is in progress, disposal skips the toast but the next session sees the change as already read; acknowledge it only after presentation or preserve the pending summary for the next session.</comment>

<file context>
@@ -501,10 +501,33 @@ function installCards(api: TuiPluginApi) {
+  let activityTimer: ReturnType<typeof setTimeout> | 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)
</file context>

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)) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SUGGESTION: The line is marked seen before it is shown

changesSince already advanced the stored mark for this client before this GET returns, so if the TUI is disposed — or the toast never fires — during this up-to-20s wait for a decision toast, the line is lost permanently: the next start asks only for changes after it. Waiting for a decision toast before issuing the GET (rather than after) would close the window. The same exposure exists for any repeated or retried GET, since the route mutates per-user state on a GET.

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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: The activity timer is not synchronized with the asynchronous startup replay, so a slow replay can show decision notices after—and replace—the activity summary. Start the activity request only after the replay promise completes, while retaining a timeout fallback if replay never responds.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At packages/opencode/src/plugin/tui/altimate/rules.tsx, line 523:

<comment>The activity timer is not synchronized with the asynchronous startup replay, so a slow replay can show decision notices after—and replace—the activity summary. Start the activity request only after the replay promise completes, while retaining a timeout fallback if replay never responds.</comment>

<file context>
@@ -501,10 +501,33 @@ function installCards(api: TuiPluginApi) {
+    }
+    announce(0)
+  }
+  activityTimer = setTimeout(() => void showActivity(), 6_000)
+  activityTimer.unref?.()
+  // altimate_change end
</file context>

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()
Expand Down Expand Up @@ -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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SUGGESTION: Duplicated toast duration

This restates the longest duration produced by decisionToast/combinedToast (15000). If one of those changes, this silently waits the wrong time and the "waits while a decision toast is up" behaviour drifts. Deriving it from a single shared constant would keep them in step.

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

Expand Down
20 changes: 20 additions & 0 deletions packages/opencode/src/server/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) => {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SUGGESTION: New route missing from the route-level tests

test/server/altimate-rules-routes.test.ts:103-114 lists every workspace route in its browser-origin refusal table, and this route plus its host validation (the 400 branch above) are not covered there. Worth adding, in particular because this GET mutates per-client state.

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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: This validation admits Object-prototype property names, but changesSince treats state.seen[host] as a timestamp; host=constructor therefore becomes an inherited function instead of an unset marker. Reject reserved property names here, or use an own-property lookup when reading the marker.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At packages/opencode/src/server/server.ts, line 1469:

<comment>This validation admits Object-prototype property names, but `changesSince` treats `state.seen[host]` as a timestamp; `host=constructor` therefore becomes an inherited function instead of an unset marker. Reject reserved property names here, or use an own-property lookup when reading the marker.</comment>

<file context>
@@ -1460,6 +1460,26 @@ export namespace Server {
+        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")
</file context>
Suggested change
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)
if (
!/^[a-z][a-z0-9-]{0,31}$/.test(host) ||
["constructor", "hasOwnProperty", "isPrototypeOf", "propertyIsEnumerable", "toLocaleString", "toString", "valueOf"].includes(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)
Expand Down
Loading
Loading