Skip to content

Commit c6f2d15

Browse files
sahrizviclaude
andcommitted
feat(workspace): show memory and skill-sync state in the sidebar
Retargeted onto main after #1278 merged: the branch's history was rebuilt as one commit carrying only the sidebar change and its supporting fixes, which the stacked history had interleaved with #1278's own commits. The pane names the workspace but said nothing about whether local state has drifted from it, so there was no moment at which a user learned they have memory the workspace never received, or skills that have not synced. Two lines under the name and manage URL: 12 memories · 3 not synced skills synced 6m ago Status, not affordances. The tile refreshes every 30s and reacts at once to a link, unlink or rebind made in this process (`onBindingChanged`). Supporting changes, each with the review round that asked for it: - `Manage.status(dir, { poll })`: the poller resolves the memory setting on a rate-limited path (at most once per five minutes on a "no", never once it is "yes"); the `/workspace` menu stays cache-only and off the network. - `memory-sync`: the poller's scoped memo is its only cache, `pendingCount` trusts a settled enablement, `resetOverlay` clears every memo. - `skill-sync`: `lastSuccessfulSyncAt` reads a `.synced-at` marker written on clean runs only; a partial run and a clean up-to-date run both leave the manifest unusable for this. Missing or malformed marker is unknown. - `state`: binding-change listeners; `lastValidatedAt` stamped only when the server says bound. - Sidebar: scope-aware rebind (clears detail on an account switch even for a same-numbered workspace), floored age labels, coalesced refresh that stops after unmount. - Sync toast: `gatedBecause` names why a sweep never ran, and a gated sweep is never a green success. Tests: 630 pass across the workspace, plugin and telemetry suites on main; every guard above was mutation-checked in the original review rounds. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_012Q51zFUmPg1WwtS5CrGJE6
1 parent 024e800 commit c6f2d15

9 files changed

Lines changed: 793 additions & 45 deletions

File tree

‎packages/opencode/src/altimate/workspace/manage.ts‎

Lines changed: 61 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -44,11 +44,17 @@ export interface StatusReport {
4444
/** Blocks held locally for this project, and how many have not reached the
4545
* workspace. `null` when memory is off — "not synced" and "not applicable" are
4646
* different answers and a status line must not conflate them. */
47-
/** `unsynced: null` means the workspace's memory setting is not known from
48-
* cache and status did not go to the network to find out. Rendering that as
47+
/** `unsynced: null` means the workspace's memory setting is not known — from
48+
* cache for the menu, which never asks; from the bounded poller path for the
49+
* sidebar, when the service could not be reached. Rendering that as
4950
* 0 would tell the user their memory is current when nobody knows. */
5051
memory: { local: number; unsynced: number | null } | null
5152
skillsEnabled: boolean
53+
/** When workspace skills last synced successfully, or null if they have not in
54+
* this process. Null is genuinely "unknown", not "never" — the store is
55+
* per-process, so a fresh session has not synced yet even for a project whose
56+
* snapshot is current on disk. Callers must not render it as "never synced". */
57+
skillsSyncedAt: number | null
5258
}
5359

5460
export interface RefreshReport {
@@ -92,22 +98,40 @@ export interface SyncReport {
9298
/** What the project is linked to and how far its local state has drifted.
9399
*
94100
* Cheap enough for a status line: one binding read from the local cache and, when
95-
* memory is on, one index read. Network only when there is no cached row. */
96-
export async function status(directory: string): Promise<StatusReport> {
97-
// The cached row first, and the resolver only when there is none. A fresh
98-
// clone, or a new machine, whose project is still bound server-side has no
99-
// cached row, and reading only the cache answered "this project is not
100-
// linked" with a lone Done — so that case asks. But the resolver revalidates
101-
// a cached row too, and on the first call of a process nothing has been
102-
// validated yet: the menu then sat on the API's full timeout when the
103-
// service was unreachable. A cached row is taken as it is here; the poll and
104-
// the operations behind the menu are what revalidate it.
105-
const binding =
106-
(await readLocalBinding(directory).catch(() => null)) ?? (await resolveBinding(directory).catch(() => null))
101+
* memory is on, one index read. Network only when there is no cached row, or
102+
* on the poller path. */
103+
export async function status(
104+
directory: string,
105+
opts: {
106+
/** Set for the sidebar poller. Resolves the workspace's memory setting
107+
* through the poller path — the service is asked at most once every few
108+
* minutes when the answer is "no" and not at all once it is "yes" — because
109+
* on a cold cache nothing else would ever warm it, and the counts would
110+
* simply never appear. The binding goes through the resolver too: the
111+
* poll runs in the background, and it is what revalidates a cached row.
112+
*
113+
* Unset for the `/workspace` menu, which is awaited before the dialog can
114+
* open and must NOT wait on the network: there the setting is read from
115+
* cache alone and reported as unknown (`null`) if not held, and a cached
116+
* row is taken as it is. `sync` does the live check. */
117+
poll?: boolean
118+
} = {},
119+
): Promise<StatusReport> {
120+
// The cached row first, and the resolver only when there is none — for the
121+
// menu. A fresh clone, or a new machine, whose project is still bound
122+
// server-side has no cached row, and reading only the cache answered "this
123+
// project is not linked" with a lone Done — so that case asks. But the
124+
// resolver revalidates a cached row too, and on the first call of a process
125+
// nothing has been validated yet: the menu then sat on the API's full
126+
// timeout when the service was unreachable.
127+
const binding = opts.poll
128+
? await resolveBinding(directory).catch(() => null)
129+
: ((await readLocalBinding(directory).catch(() => null)) ?? (await resolveBinding(directory).catch(() => null)))
107130
return {
108131
binding,
109-
memory: await memoryCounts(directory, binding),
132+
memory: await memoryCounts(directory, binding, opts.poll === true),
110133
skillsEnabled: SkillSync.isEnabled(),
134+
skillsSyncedAt: await SkillSync.lastSuccessfulSyncAt(directory),
111135
}
112136
}
113137

@@ -221,18 +245,35 @@ export async function sync(directory: string): Promise<SyncReport> {
221245
* accurate claim — nothing is pending against a workspace that accepts nothing.
222246
* Best-effort: a status line must not fail because an index read did.
223247
*
224-
* Cache-only. `status` is awaited before the `/workspace` dialog can appear,
225-
* so it must not sit on the network: the enablement check behind `pendingCount`
226-
* is a GET with a 15s budget, and on a slow or dead link the menu looked like it
227-
* did nothing. When the setting is not known from cache the count is `null` —
228-
* unknown — and `sync` does the live check. */
248+
* The enablement policy differs by caller, and both are deliberate.
249+
*
250+
* The `/workspace` menu (`poll` false) is awaited before the dialog can appear,
251+
* so it reads the setting from cache alone: the check behind `pendingCount` is a
252+
* GET with a 15s budget, and on a slow or dead link the menu looked like it did
253+
* nothing. Not known from cache is `null`, and `sync` does the live check.
254+
*
255+
* The sidebar poller (`poll` true) may ask, on the rate-limited poller path.
256+
* It runs in the background, so a wait costs nothing visible — and on a cold
257+
* cache it is the only thing that will ever warm the answer the menu then
258+
* reads. Either way, "unknown" is reported as unknown, never as zero. */
229259
async function memoryCounts(
230260
directory: string,
231261
binding: CachedBinding | null,
262+
poll: boolean,
232263
): Promise<{ local: number; unsynced: number | null } | null> {
233264
if (!MemorySync.isEnabled()) return null
234265
try {
235266
const blocks = await MemoryStore.listAll({ directory })
267+
if (poll && binding) {
268+
const status = await MemorySync.memoryEnabledForPoller(binding)
269+
// "disabled" is a real answer: memory is off, so nothing is outstanding
270+
// and 0 is the truth. "unknown" is not — the service could not be
271+
// reached, and reporting 0 there claims the workspace is up to date on
272+
// the strength of a failed request.
273+
if (status !== "enabled") return { local: blocks.length, unsynced: status === "disabled" ? 0 : null }
274+
// Enablement is settled; `pendingCount`'s own gate must not re-ask.
275+
return { local: blocks.length, unsynced: await MemorySync.pendingCount(blocks, binding, { trustEnabled: true }) }
276+
}
236277
return { local: blocks.length, unsynced: await MemorySync.pendingCount(blocks, binding, { network: false }) }
237278
} catch (err) {
238279
log.warn("could not count local memory for the workspace status", { err: String(err) })

‎packages/opencode/src/altimate/workspace/memory-sync.ts‎

Lines changed: 88 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ import { TRAINING_META_COMMENT } from "@/altimate/training/types"
2727
import { resolveBinding as resolveProjectBinding, type CachedBinding } from "./state"
2828
import { indexKey, readIndex, readIndexEntry, recordIndexEntry } from "./memory-index"
2929
import { WorkspaceApi } from "./api-client"
30+
import { AltimateApi } from "@/altimate/api/client"
3031
import {
3132
LIST_LIMIT,
3233
MemoryApi,
@@ -207,8 +208,17 @@ async function memoryEnabled(binding: CachedBinding): Promise<boolean> {
207208
/** Three-way, because a read that cannot reach the service must not be reported
208209
* as "this workspace has no memory" — that reads as success while destroying
209210
* whatever the session already had. */
210-
async function memoryStatus(binding: CachedBinding): Promise<"enabled" | "disabled" | "error"> {
211-
const cached = memoryEnabledCache.get(binding.datamateId)
211+
async function memoryStatus(
212+
binding: CachedBinding,
213+
opts: {
214+
/** Skip the positive cache and ask. The cache is keyed by bare workspace
215+
* id, which is safe for the write path (its credentials are fixed) but not
216+
* for a caller whose own memo is tenant-scoped: on a memo miss it must not
217+
* inherit a positive written under a previous account. */
218+
fresh?: boolean
219+
} = {},
220+
): Promise<"enabled" | "disabled" | "error"> {
221+
const cached = opts.fresh ? undefined : memoryEnabledCache.get(binding.datamateId)
212222
if (cached && Date.now() - cached.checkedAt < MEMORY_ENABLED_TTL_MS) return "enabled"
213223
try {
214224
const workspaces = await WorkspaceApi.listDatamates()
@@ -660,6 +670,75 @@ async function runQueue<T>(
660670
return { ok, failed, declined, skipped, deferred }
661671
}
662672

673+
/** How long a poller trusts either answer. Deliberately separate from
674+
* `MEMORY_ENABLED_TTL_MS` and from the main cache: `memoryEnabled` stays
675+
* positive-only with a 60s TTL so the WRITE path picks up a newly enabled
676+
* workspace almost at once, which is the property that matters for not losing
677+
* memory. A poller can afford to be a few minutes behind; what it cannot afford
678+
* is a request every tick.
679+
*
680+
* Both answers are memoized, not just the "no". Reusing the write path's 60s
681+
* positive meant that a minute after the first check an ENABLED workspace went
682+
* back to the network on every other tick — a steady drip of `/datamates`
683+
* requests for the life of the session. (cubic P2 on #1279.) */
684+
const POLL_TTL_MS = 5 * 60 * 1000
685+
686+
/** Keyed by tenant and API URL as well as workspace id. Workspace ids are
687+
* tenant-local, so a bare id let a same-numbered workspace in a NEWLY switched
688+
* account inherit the previous tenant's answer and hide its unsynced count for
689+
* the whole TTL. (cubic P2 on #1279.) */
690+
const pollMemo = new Map<string, { at: number; status: "enabled" | "disabled" }>()
691+
692+
async function pollMemoKey(binding: CachedBinding): Promise<string> {
693+
try {
694+
const creds = await AltimateApi.getCredentials()
695+
return `${creds.altimateInstanceName}|${creds.altimateUrl}|${binding.datamateId}`
696+
} catch {
697+
// No credentials resolved: fall back to an id-only key. The caller is about
698+
// to fail its lookup anyway, and a wrong-tenant hit is impossible when
699+
// there is no tenant.
700+
return `?|?|${binding.datamateId}`
701+
}
702+
}
703+
704+
/** Whether this workspace has memory on, for a caller that polls.
705+
*
706+
* Three-way on purpose. `memoryEnabled` folds "the service could not be
707+
* reached" into `false`, which is right for the write path — it fails closed so
708+
* an outage cannot leak a mirror — but wrong for a status line: rendering an
709+
* unreachable service as "0 not synced" tells the user their memory is current
710+
* when nobody knows. `memoryStatus` already draws that distinction; this used
711+
* to throw it away and then memoize the result for five minutes. (cubic P2 on
712+
* #1279.)
713+
*
714+
* An "unknown" is never memoized: the next tick should ask again rather than
715+
* inherit a network blip. */
716+
export async function memoryEnabledForPoller(
717+
binding: CachedBinding,
718+
): Promise<"enabled" | "disabled" | "unknown"> {
719+
// The scoped memo is the poller's only cache. `memoryEnabledCache` is keyed by
720+
// bare workspace id — right for the write path, which is tenant-bound by its
721+
// credentials — but consulting it here reopened a 60s cross-tenant window the
722+
// scoped memo had closed: a positive written under the previous account was
723+
// served to a same-numbered workspace in the next. One extra request per five
724+
// minutes per tenant is the price, and `memoryStatus` still warms both.
725+
const key = await pollMemoKey(binding)
726+
const memo = pollMemo.get(key)
727+
if (memo && Date.now() - memo.at < POLL_TTL_MS) return memo.status
728+
const status = await memoryStatus(binding, { fresh: true })
729+
if (status === "error") return "unknown"
730+
pollMemo.set(key, { at: Date.now(), status })
731+
return status
732+
}
733+
734+
/** Test seam: the poller memo is process-global and would otherwise leak between
735+
* cases in the same file. */
736+
export function resetPollMemoForTests(): void {
737+
pollMemo.clear()
738+
memoryEnabledCache.clear()
739+
memoryDisabledMemo.clear()
740+
}
741+
663742
/** Split blocks into those the workspace still needs and those already there at
664743
* their current payload.
665744
*
@@ -718,10 +797,17 @@ export async function pendingCount(
718797
* known"), never wait on the network. The default asks, and is what a
719798
* sweep wants. */
720799
network?: boolean
800+
/** The caller has already resolved the workspace's setting as enabled —
801+
* the poller does, on its own rate-limited path — so the gate here must
802+
* not ask again. Without this the poll dripped a `/datamates` request every
803+
* 60s once the write path's positive expired, which is the exact drip the
804+
* poller memo exists to stop. */
805+
trustEnabled?: boolean
721806
} = {},
722807
): Promise<number | null> {
723808
if (blocks.length === 0) return 0
724809
if (!isEnabled()) return 0
810+
if (opts.trustEnabled && binding) return partitionPending(blocks, binding, await readIndex()).pending.length
725811
if (opts.network === false && binding) {
726812
const cached = memoryEnabledCached(binding)
727813
if (cached === "unknown") return null

‎packages/opencode/src/altimate/workspace/skill-sync.ts‎

Lines changed: 49 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,10 @@ const MANAGED_DIR = path.join(".altimate-code", "skill", "_workspace")
6868
* discovery scans. See the swap in `syncSkills`. */
6969
const STAGING_DIR = path.join(".altimate-code", "skill-staging")
7070
const MANIFEST_NAME = ".manifest.json"
71+
/** Written at the managed root after every CLEAN run, holding the epoch ms.
72+
* The manifest cannot serve: a partial run publishes one too, and a clean run
73+
* that finds the snapshot up to date publishes nothing. */
74+
const SYNCED_MARKER = ".synced-at"
7175

7276
export interface ManifestSkill {
7377
/** Server's ``updated_at``, verbatim. The only change signal the API offers. */
@@ -251,6 +255,40 @@ export async function flushPendingSyncs(timeoutMs = 30_000): Promise<void> {
251255
}
252256
}
253257

258+
/** When this project's workspace skills last synced successfully, or null if
259+
* they never have in this process.
260+
*
261+
* Exposed for the sidebar. `recentlySynced` answers a boolean against the poll
262+
* interval, which cannot say "6 minutes ago" — and a status line whose whole job
263+
* is to make staleness visible needs the age, not a threshold. Reads the
264+
* process-global store, so the TUI plugin realm sees the same map the sync
265+
* writes (see `STORE_KEY` above). */
266+
export async function lastSuccessfulSyncAt(directory: string): Promise<number | null> {
267+
// From disk, not from the map. The map is on `globalThis`, which is shared
268+
// across module realms but NOT across threads — and the per-message sync
269+
// that does most of the stamping runs in the server worker, while the TUI
270+
// and its sidebar render on the main thread. Read from the map alone, the
271+
// "skills synced Xm ago" line never saw the syncs that actually happened.
272+
// The marker is written on exactly the runs that stamp the map, so the two
273+
// agree; the manifest's mtime did not — a partial run publishes one, and a
274+
// clean up-to-date run publishes nothing.
275+
try {
276+
// Validated, not coerced: `Number("")` is 0, and a truncated marker would
277+
// otherwise render as a sync from 1970.
278+
const raw = (await fs.readFile(path.join(managedRoot(directory), SYNCED_MARKER), "utf8")).trim()
279+
if (!/^\d+$/.test(raw)) return null
280+
const at = Number(raw)
281+
return Number.isSafeInteger(at) && at > 0 ? at : null
282+
} catch (err) {
283+
// No snapshot is no sync: after an unlink, a rebind, or an empty
284+
// workspace, an in-memory stamp from before would report a sync that no
285+
// longer describes what is on disk.
286+
const code = (err as NodeJS.ErrnoException)?.code
287+
if (code === "ENOENT" || code === "ENOTDIR") return null
288+
return lastSyncedAt.get(path.resolve(directory)) ?? null
289+
}
290+
}
291+
254292
/** Has this project's snapshot been checked within the poll interval? Callers
255293
* on a per-message path use this to skip the network entirely. */
256294
export async function recentlySynced(directory: string): Promise<boolean> {
@@ -323,10 +361,10 @@ function safePathComponent(p: unknown): p is string {
323361
if (typeof p !== "string" || !p) return false
324362
if (p === "." || p === "..") return false
325363
if (path.isAbsolute(p)) return false
326-
// These two are written as FILES at the staged root. An id of either name
327-
// becomes a directory there, the write fails EISDIR, and that workspace can
328-
// never sync again.
329-
if (p === MANIFEST_NAME || p === ".gitignore") return false
364+
// These are written as FILES at the managed root. An id of any of these
365+
// names becomes a directory there, the write fails EISDIR, and that
366+
// workspace can never sync again.
367+
if (p === MANIFEST_NAME || p === ".gitignore" || p === SYNCED_MARKER) return false
330368
return !/[\\/\0]/.test(p)
331369
}
332370

@@ -977,7 +1015,13 @@ export async function syncSkills(directory: string): Promise<{ changed: boolean
9771015
}
9781016
// Only a clean run earns the poll interval. `failed` is set by the inner
9791017
// catch, which swallows so that skills can never block a turn.
980-
if (ok && !failed && sawRemote) lastSyncedAt.set(canon, Date.now())
1018+
if (ok && !failed && sawRemote) {
1019+
const now = Date.now()
1020+
lastSyncedAt.set(canon, now)
1021+
// Only where a snapshot exists: a clean run against an empty workspace
1022+
// removed the root, and there is nothing for an age to describe.
1023+
await fs.writeFile(path.join(managedRoot(canon), SYNCED_MARKER), String(now)).catch(() => {})
1024+
}
9811025
return { changed }
9821026
})()
9831027
inFlight.set(canon, settled)

0 commit comments

Comments
 (0)