Skip to content

Commit 7ed6e16

Browse files
feat(workspace): expose /workspace Refresh and Sync over serve HTTP (#1366)
Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
1 parent 10fa461 commit 7ed6e16

5 files changed

Lines changed: 550 additions & 2 deletions

File tree

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

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ import {
3333
peekRowUnscoped,
3434
readLocalBinding,
3535
resolveBinding,
36+
resolvePinnedBindingForRouting,
3637
type CachedBinding,
3738
} from "./state"
3839

@@ -81,7 +82,7 @@ export interface SyncReport {
8182
* and only one of them is the workspace's memory toggle; a toast that said
8283
* "memory is off" for a failed local read sent the user to a setting that was
8384
* fine. */
84-
gatedBecause?: "flag-off" | "no-binding" | "memory-off" | "read-failed"
85+
gatedBecause?: "flag-off" | "no-binding" | "pin-unresolved" | "memory-off" | "read-failed"
8586
sent: number
8687
failed: number
8788
/** Already present in the workspace at their current payload. */
@@ -226,7 +227,15 @@ export async function sync(directory: string): Promise<SyncReport> {
226227
deferred: 0,
227228
})
228229
if (!MemorySync.isEnabled()) return gated("flag-off")
229-
const binding = await readLocalBinding(directory).catch(() => null)
230+
// altimate_change — the IDE extension's pin outranks the project's own link, as it does for
231+
// the per-write mirror (`memory-sync.resolveBinding`). Without it an extension-launched `serve`
232+
// answered "not linked" for the workspace it was pinned to. Only the pin arm is layered, so an
233+
// unpinned session keeps the cache-only read, and a pin that cannot be honoured stays gated —
234+
// under its own reason, since "nothing is linked" would misdescribe a workspace that exists —
235+
// rather than falling through to the project's link.
236+
const pinned = await resolvePinnedBindingForRouting(directory).catch(() => ({ status: "unknown" as const }))
237+
if (pinned && pinned.status !== "bound") return gated("pin-unresolved")
238+
const binding = pinned ? pinned.binding : await readLocalBinding(directory).catch(() => null)
230239
if (!binding) return gated("no-binding")
231240

232241
const blocks = await MemoryStore.listAll({ directory }).catch((err) => {

‎packages/opencode/src/plugin/tui/altimate/workspace.tsx‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1789,6 +1789,8 @@ function syncMessage(result: Manage.SyncReport): string {
17891789
return "Could not read this project's local memory, so nothing was synced."
17901790
case "no-binding":
17911791
return "Nothing to sync — this project is not linked to a workspace."
1792+
case "pin-unresolved":
1793+
return "Nothing to sync — the pinned workspace could not be confirmed for this project."
17921794
case "flag-off":
17931795
return "Nothing to sync — workspace memory is not enabled in this build."
17941796
default:

‎packages/opencode/src/server/server.ts‎

Lines changed: 131 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,10 @@ import { FreeTierConsent } from "../altimate/free/consent"
4545
import { InstanceStore } from "@/project/instance-store"
4646
import { AppRuntime } from "@/effect/app-runtime"
4747
// altimate_change end
48+
// altimate_change - `/workspace` Refresh and Sync: pilot flag gate, and the session-directory check
49+
import { Flag as CoreFlag } from "@opencode-ai/core/flag/flag"
50+
import nodePath from "node:path"
51+
import { Session } from "../session"
4852
// altimate_change end
4953
import { FileRoutes } from "./routes/file"
5054
import { ConfigRoutes } from "./routes/config"
@@ -71,6 +75,51 @@ globalThis.AI_SDK_LOG_WARNINGS = false
7175

7276
export namespace Server {
7377
const log = Log.create({ service: "server" })
78+
// altimate_change start — shared gate for the `/altimate/workspace/*` routes
79+
/** Why a `/workspace` action must not run, or undefined when it may.
80+
*
81+
* 409 is reserved for the pilot gate, so a caller can tell "this server is not in workspace mode"
82+
* apart from a bad request (400) without parsing the message.
83+
*
84+
* Outside the workspace pilot a skill sync purges the snapshot, so the flag is checked first.
85+
* A browser origin on an unsecured server is refused for the same reason as Altimate Base
86+
* registration: a CORS-allowed page is not a local process. Native clients (the extension host,
87+
* curl) send no Origin. With a server password set, a same-origin page may call; others may not. */
88+
export function workspaceRouteRefusal(
89+
origin: string | undefined,
90+
host: string | undefined,
91+
password: string | undefined = Flag.OPENCODE_SERVER_PASSWORD,
92+
): { status: 403 | 409; body: { ok: false; error: string } } | undefined {
93+
if (!CoreFlag.ALTIMATE_WORKSPACE) {
94+
return { status: 409, body: { ok: false, error: "Workspace mode is not enabled for this server." } }
95+
}
96+
if (!origin) return undefined
97+
if (!password) {
98+
log.warn("refused browser-originated workspace action on an unsecured server", { origin })
99+
return {
100+
status: 403,
101+
body: {
102+
ok: false,
103+
error: "Workspace actions cannot be run from a browser origin on an unsecured server. Set OPENCODE_SERVER_PASSWORD.",
104+
},
105+
}
106+
}
107+
// With a password set, basicAuth has vetted the credentials — but a browser replays cached
108+
// Basic credentials on a cross-site form POST too, so only this server's own pages may call.
109+
if (!sameOrigin(origin, host)) {
110+
log.warn("refused cross-origin workspace action", { origin })
111+
return { status: 403, body: { ok: false, error: "Workspace actions cannot be run from another origin." } }
112+
}
113+
return undefined
114+
}
115+
export function sameOrigin(origin: string, host: string | undefined): boolean {
116+
try {
117+
return !!host && new URL(origin).host === host
118+
} catch {
119+
return false
120+
}
121+
}
122+
// altimate_change end
74123
// altimate_change start — the Base credential every provider cache in this process is known to
75124
// reflect: set after the register route has disposed both registries for it. Unset until then,
76125
// because a cache built before a background registration finished cannot be told apart from one
@@ -949,6 +998,88 @@ export namespace Server {
949998
}
950999
})
9511000
// altimate_change end
1001+
// altimate_change start — POST /altimate/workspace/{refresh,sync}
1002+
// The `/workspace` menu's Refresh and Sync for the IDE extension, which runs this CLI
1003+
// headless and cannot reach the TUI slash command. Both act on the request's instance
1004+
// directory and return the `Manage` report as is; wording is the caller's job.
1005+
.post("/altimate/workspace/refresh", async (c) => {
1006+
const refused = workspaceRouteRefusal(c.req.header("origin"), c.req.header("host"))
1007+
if (refused) return c.json(refused.body, refused.status)
1008+
// An absent or empty body is a session-less refresh; anything else must be well formed.
1009+
// Falling back to "no session" on bad input would silently widen the operation to
1010+
// resetting every session's memory overlay.
1011+
let text: string
1012+
try {
1013+
text = await c.req.text()
1014+
} catch (err) {
1015+
const error = err instanceof Error ? err.message : String(err)
1016+
log.error("workspace refresh: could not read the request body", { error })
1017+
return c.json({ ok: false, error }, 500)
1018+
}
1019+
let body: unknown = {}
1020+
if (text.trim()) {
1021+
try {
1022+
body = JSON.parse(text)
1023+
} catch {
1024+
return c.json({ ok: false, error: "Request body is not valid JSON." }, 400)
1025+
}
1026+
}
1027+
if (body === null || typeof body !== "object" || Array.isArray(body)) {
1028+
return c.json({ ok: false, error: "Request body must be a JSON object." }, 400)
1029+
}
1030+
const raw = (body as Record<string, unknown>).sessionID
1031+
if (raw !== undefined && (typeof raw !== "string" || !raw)) {
1032+
return c.json({ ok: false, error: "sessionID must be a non-empty string." }, 400)
1033+
}
1034+
const sessionID = raw as string | undefined
1035+
// The memory reload loads THIS directory's workspace memory into the named session, so the
1036+
// session must be one of this directory's; another project's would receive it.
1037+
if (sessionID) {
1038+
// `Session.get` validates the id synchronously, so the call is deferred into the promise
1039+
// chain for a malformed id to land in the handler below rather than escape the route.
1040+
const session = await Promise.resolve()
1041+
.then(() => Session.get(sessionID as never))
1042+
.catch((err) => err as Error)
1043+
if (session instanceof NotFoundError) {
1044+
return c.json({ ok: false, error: `Session not found: ${sessionID}` }, 404)
1045+
}
1046+
if (session instanceof z.ZodError) {
1047+
return c.json({ ok: false, error: `Invalid sessionID: ${sessionID}` }, 400)
1048+
}
1049+
if (session instanceof Error) {
1050+
log.error("workspace refresh: session lookup failed", { error: session.message })
1051+
return c.json({ ok: false, error: session.message }, 500)
1052+
}
1053+
if (nodePath.resolve(session.directory) !== nodePath.resolve(Instance.directory)) {
1054+
return c.json({ ok: false, error: "That session belongs to a different project directory." }, 400)
1055+
}
1056+
}
1057+
try {
1058+
const Manage = await import("../altimate/workspace/manage")
1059+
// A changed skill snapshot reaches the registry at the start of the next turn
1060+
// (`refreshSkillRegistry` in session/prompt.ts), so nothing is invalidated here.
1061+
const report = await Manage.refresh(Instance.directory, sessionID)
1062+
return c.json({ ok: true as const, ...report })
1063+
} catch (err) {
1064+
const error = err instanceof Error ? err.message : String(err)
1065+
log.error("workspace refresh: failed", { error })
1066+
return c.json({ ok: false, error }, 500)
1067+
}
1068+
})
1069+
.post("/altimate/workspace/sync", async (c) => {
1070+
const refused = workspaceRouteRefusal(c.req.header("origin"), c.req.header("host"))
1071+
if (refused) return c.json(refused.body, refused.status)
1072+
try {
1073+
const Manage = await import("../altimate/workspace/manage")
1074+
const report = await Manage.sync(Instance.directory)
1075+
return c.json({ ok: true as const, ...report })
1076+
} catch (err) {
1077+
const error = err instanceof Error ? err.message : String(err)
1078+
log.error("workspace sync: failed", { error })
1079+
return c.json({ ok: false, error }, 500)
1080+
}
1081+
})
1082+
// altimate_change end
9521083
.all("/*", async (c) => {
9531084
const path = c.req.path
9541085

Lines changed: 157 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,157 @@
1+
// altimate_change - new file
2+
//
3+
// `/workspace` Sync follows the IDE extension's pin. `Manage.sync` read only the on-disk link, so a
4+
// `serve` pinned by the extension answered "not linked" for the workspace it was pinned to, while
5+
// the per-write mirror (which resolves through the pin) sent to it. These cover which binding the
6+
// sweep runs against; the sweep itself is covered by manage.test.ts and memory-sync.test.ts.
7+
import { afterAll, afterEach, beforeEach, describe, expect, test } from "bun:test"
8+
import { mkdirSync, rmSync } from "node:fs"
9+
import path from "node:path"
10+
import os from "node:os"
11+
12+
const ORIGINAL_XDG_STATE_HOME = process.env.XDG_STATE_HOME
13+
const ORIGINAL_PILOT = process.env.ALTIMATE_WORKSPACE
14+
const SANDBOX = path.join(os.tmpdir(), `altimate-manage-pin-test-${process.pid}-${Date.now()}`)
15+
mkdirSync(path.join(SANDBOX, "state"), { recursive: true })
16+
process.env.XDG_STATE_HOME = path.join(SANDBOX, "state")
17+
18+
const { recordApprovedBinding, __resetPinValidation } = await import("../../../src/altimate/workspace/state")
19+
const { sync } = await import("../../../src/altimate/workspace/manage")
20+
const { resetEnablementMemoForTests } = await import("../../../src/altimate/workspace/memory-sync")
21+
const { AltimateApi } = await import("../../../src/altimate/api/client")
22+
const { WorkspaceApi } = await import("../../../src/altimate/workspace/api-client")
23+
24+
const ROOT = path.join(SANDBOX, "project")
25+
const OUTSIDE = path.join(SANDBOX, "elsewhere")
26+
mkdirSync(ROOT, { recursive: true })
27+
mkdirSync(OUTSIDE, { recursive: true })
28+
29+
const originalIsConfigured = AltimateApi.isConfigured
30+
const originalGetCreds = AltimateApi.getCredentials
31+
const originalList = WorkspaceApi.listDatamates
32+
type Creds = Awaited<ReturnType<typeof AltimateApi.getCredentials>>
33+
34+
const PIN_VARS = [
35+
"ALTIMATE_CODE_SERVE",
36+
"ALTIMATE_PINNED_WORKSPACE_ID",
37+
"ALTIMATE_PINNED_WORKSPACE_NAME",
38+
"ALTIMATE_PINNED_WORKSPACE_ROOT",
39+
]
40+
// Restored in `afterAll`: `bun test` shares one process, and later files must see the pin they had.
41+
const ORIGINAL_PIN = Object.fromEntries(PIN_VARS.map((k) => [k, process.env[k]]))
42+
const originalFetch = globalThis.fetch
43+
44+
/** The pinned workspace has memory ON and the project's own link has it OFF, so the gate reason
45+
* says which of the two the sweep ran against. */
46+
const WORKSPACES = [
47+
{ id: 42, name: "pinned-workspace", memoryEnabled: true },
48+
{ id: 7, name: "project-link", memoryEnabled: false },
49+
]
50+
51+
function setPin(id = "42") {
52+
process.env.ALTIMATE_CODE_SERVE = "1"
53+
process.env.ALTIMATE_PINNED_WORKSPACE_ID = id
54+
process.env.ALTIMATE_PINNED_WORKSPACE_NAME = "pinned-workspace"
55+
process.env.ALTIMATE_PINNED_WORKSPACE_ROOT = ROOT
56+
}
57+
58+
function clearPin() {
59+
for (const k of PIN_VARS) delete process.env[k]
60+
}
61+
62+
async function seedLocalLink(directory = ROOT) {
63+
// Awaited, so the bind's skill sync and memory backfill finish inside this test's stubbed
64+
// `fetch` instead of straddling `afterEach` into another file's request log.
65+
await recordApprovedBinding(
66+
directory,
67+
{
68+
datamateId: 7,
69+
datamateName: "project-link",
70+
linkedAt: Date.now(),
71+
repoRemote: "[email protected]:acme/project.git",
72+
projectPath: null,
73+
} as never,
74+
{ awaitBackfill: true },
75+
)
76+
}
77+
78+
beforeEach(() => {
79+
process.env.ALTIMATE_WORKSPACE = "1"
80+
__resetPinValidation()
81+
resetEnablementMemoForTests()
82+
;(AltimateApi as unknown as { isConfigured: () => Promise<boolean> }).isConfigured = async () => true
83+
;(AltimateApi as unknown as { getCredentials: () => Promise<Creds> }).getCredentials = async () =>
84+
({ altimateInstanceName: "acme", altimateUrl: "https://api.test", altimateApiKey: "k" }) as Creds
85+
;(WorkspaceApi as unknown as { listDatamates: () => Promise<unknown> }).listDatamates = async () => WORKSPACES
86+
clearPin()
87+
globalThis.fetch = (async (_input: unknown, _init?: unknown) =>
88+
new Response(JSON.stringify({}), { status: 200, headers: { "content-type": "application/json" } })) as typeof fetch
89+
})
90+
91+
afterEach(() => {
92+
clearPin()
93+
globalThis.fetch = originalFetch
94+
})
95+
96+
afterAll(() => {
97+
;(AltimateApi as unknown as { isConfigured: typeof originalIsConfigured }).isConfigured = originalIsConfigured
98+
;(AltimateApi as unknown as { getCredentials: typeof originalGetCreds }).getCredentials = originalGetCreds
99+
;(WorkspaceApi as unknown as { listDatamates: typeof originalList }).listDatamates = originalList
100+
if (ORIGINAL_XDG_STATE_HOME === undefined) delete process.env.XDG_STATE_HOME
101+
else process.env.XDG_STATE_HOME = ORIGINAL_XDG_STATE_HOME
102+
if (ORIGINAL_PILOT === undefined) delete process.env.ALTIMATE_WORKSPACE
103+
else process.env.ALTIMATE_WORKSPACE = ORIGINAL_PILOT
104+
for (const [k, v] of Object.entries(ORIGINAL_PIN)) {
105+
if (v === undefined) delete process.env[k]
106+
else process.env[k] = v
107+
}
108+
rmSync(SANDBOX, { recursive: true, force: true })
109+
})
110+
111+
describe("sync under an IDE pin", () => {
112+
test("runs against the pinned workspace in a project that was never linked", async () => {
113+
setPin()
114+
const report = await sync(ROOT)
115+
expect(report.gated).toBe(false)
116+
expect(report.gatedBecause).toBeUndefined()
117+
})
118+
119+
test("the pin outranks the project's own link", async () => {
120+
await seedLocalLink()
121+
setPin()
122+
// The local link (7) has memory off and would gate; the pin (42) has it on.
123+
expect((await sync(ROOT)).gated).toBe(false)
124+
})
125+
126+
test("a pin naming a workspace this account cannot see fails closed, not onto the local link", async () => {
127+
await seedLocalLink()
128+
setPin("99")
129+
const report = await sync(ROOT)
130+
expect(report.gated).toBe(true)
131+
// Its own reason: the project IS linked (to 7), so "no-binding" would misdescribe it.
132+
expect(report.gatedBecause).toBe("pin-unresolved")
133+
})
134+
135+
test("a directory outside the pinned root is not treated as pinned", async () => {
136+
setPin()
137+
const report = await sync(OUTSIDE)
138+
expect(report.gated).toBe(true)
139+
expect(report.gatedBecause).toBe("pin-unresolved")
140+
})
141+
})
142+
143+
describe("sync without a pin", () => {
144+
test("still reads the project's own link", async () => {
145+
await seedLocalLink()
146+
const report = await sync(ROOT)
147+
// Reached the sweep with link 7, whose memory is off.
148+
expect(report.gated).toBe(true)
149+
expect(report.gatedBecause).toBe("memory-off")
150+
})
151+
152+
test("an unlinked project is still gated on the missing binding", async () => {
153+
// A directory no test links: the binding cache is process-memoized, so `ROOT` may still hold one.
154+
const report = await sync(OUTSIDE)
155+
expect(report.gatedBecause).toBe("no-binding")
156+
})
157+
})

0 commit comments

Comments
 (0)