Skip to content

Commit 52cbd41

Browse files
fix(workspace): identify a workspace by credential scope and id, not id alone
Workspace ids are tenant-local. After an account switch the same id in the new tenant is another workspace: the engine (started under the old credentials), the inventory cache and the reload decision now key on `tenant|apiUrl|id`. On a relink whose overlay then fails, nothing is handed back to a raw IDE or hosted entry. `/mcps … datamate` asks who owns the key before checking config.
1 parent 7632549 commit 52cbd41

6 files changed

Lines changed: 122 additions & 45 deletions

File tree

‎packages/opencode/src/altimate/workspace/engine-overlay.ts‎

Lines changed: 54 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,15 @@
2626
import { DATAMATE_KEY } from "@/altimate/datamate-transport"
2727
import { MCP } from "@/mcp"
2828
import { Config } from "@/config/config"
29-
import { currentDirectory, isEnabled, isHeadless, isServe, log, syncInternals } from "./engine-seams"
29+
import {
30+
currentDirectory,
31+
isEnabled,
32+
isHeadless,
33+
isServe,
34+
log,
35+
syncInternals,
36+
type ScopedBinding,
37+
} from "./engine-seams"
3038
import { declaredBounded, notify, printLine, resolveBinding, versionOf, which } from "./engine-probes"
3139
import {
3240
ENGINE_BINARY,
@@ -95,7 +103,10 @@ export function invalidateProbe(): void {
95103

96104
type Overlay = {
97105
directory: string
98-
workspace: { id: string; name: string }
106+
/** `key` is the workspace's identity across accounts — ids are tenant-local,
107+
* so the same number in another tenant is another workspace, and a session
108+
* that switched accounts must not keep the old one's engine or inventory. */
109+
workspace: { id: string; name: string; key: string }
99110
/** The derived entry, or null when the engine is unusable. */
100111
entry: LocalMcpConfig | null
101112
refusal: Extract<Outcome, { kind: "engine-missing" | "engine-too-old" }> | null
@@ -138,6 +149,12 @@ function stateFor(directory: string): DirectoryState {
138149
return state
139150
}
140151

152+
/** Identity of the workspace a binding names: the credential scope it was
153+
* read under plus the tenant-local id. */
154+
function workspaceKey(binding: ScopedBinding): string {
155+
return `${binding.scope ?? ""}|${binding.datamateId}`
156+
}
157+
141158
function sameEntry(a: LocalMcpConfig | null, b: LocalMcpConfig | null): boolean {
142159
return !!a && !!b && a.command.join("\0") === b.command.join("\0")
143160
}
@@ -176,7 +193,11 @@ export async function overlay(
176193
state.current = null
177194
return
178195
}
179-
const workspace = { id: String(binding.datamateId), name: binding.datamateName }
196+
const workspace = {
197+
id: String(binding.datamateId),
198+
name: binding.datamateName,
199+
key: workspaceKey(binding),
200+
}
180201
const probe = await probeEngine()
181202
if (probe.kind === "ok") {
182203
const entry = engineEntry(workspace.id)
@@ -213,7 +234,8 @@ export async function overlay(
213234
* the key and say why, instead of replacing the engine underneath a turn. */
214235
export function managedWorkspace(directory: string | null = currentDirectory()): { id: string; name: string } | null {
215236
if (!directory) return null
216-
return directories.get(directory)?.current?.workspace ?? null
237+
const workspace = directories.get(directory)?.current?.workspace
238+
return workspace ? { id: workspace.id, name: workspace.name } : null
217239
}
218240

219241
/** `managedWorkspace` once the overlay has run for this instance. The overlay
@@ -287,11 +309,13 @@ async function releaseKey(loaded: { mcp?: Record<string, unknown> } | undefined,
287309
}
288310
}
289311

290-
async function declaredFor(workspaceId: string): Promise<Declared | null> {
291-
const cached = declaredCache.get(workspaceId)
312+
async function declaredFor(workspace: { id: string; key: string }): Promise<Declared | null> {
313+
// Cached per workspace identity, not per id: the same id in another tenant
314+
// is another allowlist.
315+
const cached = declaredCache.get(workspace.key)
292316
if (cached && (cached.value || now() - cached.at < DECLARED_RETRY_MS)) return cached.value
293-
const value = await declaredBounded(workspaceId)
294-
declaredCache.set(workspaceId, { value, at: now() })
317+
const value = await declaredBounded(workspace.id)
318+
declaredCache.set(workspace.key, { value, at: now() })
295319
return value
296320
}
297321

@@ -389,12 +413,13 @@ async function reconcile(sessionID: string, directory: string, state: DirectoryS
389413
record(sessionID, { kind: "unbound" })
390414
return
391415
}
392-
const workspaceId = String(binding.datamateId)
416+
const boundKey = workspaceKey(binding)
393417

394-
// Reload the overlay when the binding moved, or when a refused engine may
395-
// have appeared since (the probe memo bounds how often that is asked).
418+
// Reload the overlay when the binding moved — to another workspace, or the
419+
// same id under another account — or when a refused engine may have
420+
// appeared since (the probe memo bounds how often that is asked).
396421
let reload = state.current
397-
? state.current.workspace.id !== workspaceId
422+
? state.current.workspace.key !== boundKey
398423
: state.failedAt === undefined || now() - state.failedAt >= FAILED_PROBE_TTL_MS
399424
if (!reload && state.current && !state.current.entry) {
400425
const probe = await probeEngine()
@@ -410,17 +435,21 @@ async function reconcile(sessionID: string, directory: string, state: DirectoryS
410435
// last applied for this same workspace: a running engine is not released
411436
// over a fault in the probe. After a relink nothing is kept — workspace A's
412437
// engine must not serve a directory now bound to B.
413-
const retained = state.failedAt !== undefined && state.applied?.workspace.id === workspaceId ? state.applied : null
438+
const retained = state.failedAt !== undefined && state.applied?.workspace.key === boundKey ? state.applied : null
414439
const overlayNow = state.current ?? retained
415440
if (!overlayNow) {
416-
if (state.applied) await releaseKey(loaded, !!state.applied.entry)
417-
state.applied = null
418441
if (state.failedAt === undefined) {
442+
if (state.applied) await releaseKey(loaded, !!state.applied.entry)
443+
state.applied = null
419444
record(sessionID, { kind: "unbound" })
420445
return
421446
}
422-
// Bound, but the overlay could not be derived: say so, once, rather than
423-
// settling a bound directory as unbound in silence.
447+
// Bound, but the overlay could not be derived. Whatever runs under the key
448+
// is dropped and nothing is handed back: the reloaded config may carry a
449+
// raw IDE or hosted entry, and that must not answer for this workspace.
450+
if (state.applied?.entry || DATAMATE_KEY in (await mcp().status())) await mcp().remove(DATAMATE_KEY)
451+
state.applied = null
452+
// Say so, once, rather than settling a bound directory as unbound in silence.
424453
const outcome: Outcome = { kind: "connect-failed", error: "the workspace engine could not be checked" }
425454
record(sessionID, outcome)
426455
await announceRefusal(sessionID, outcome, {
@@ -435,7 +464,12 @@ async function reconcile(sessionID: string, directory: string, state: DirectoryS
435464
// Bring MCP in line with the overlay: start or replace the engine when the
436465
// derived entry changed, drop it when there is none any more.
437466
if (overlayNow.entry) {
438-
if (!sameEntry(state.applied?.entry ?? null, overlayNow.entry)) await mcp().add(DATAMATE_KEY, overlayNow.entry)
467+
// The argv is the same for the same id in another tenant; the engine
468+
// reads its credentials when it starts, so it is replaced on identity, not
469+
// only on argv.
470+
const replaced =
471+
!sameEntry(state.applied?.entry ?? null, overlayNow.entry) || state.applied?.workspace.key !== workspace.key
472+
if (replaced) await mcp().add(DATAMATE_KEY, overlayNow.entry)
439473
} else if (state.applied?.entry || DATAMATE_KEY in (await mcp().status())) {
440474
// Ours to drop — or a client that predates the link, which MCP bootstrapped
441475
// from an IDE or hosted entry while the directory was unbound. With the
@@ -447,7 +481,7 @@ async function reconcile(sessionID: string, directory: string, state: DirectoryS
447481
if (!overlayNow.entry) {
448482
const refusal = overlayNow.refusal ?? { kind: "engine-missing" as const }
449483
if (refusal.kind === "engine-missing") {
450-
const declared = await declaredFor(workspace.id)
484+
const declared = await declaredFor(workspace)
451485
const count = declared?.keys.length
452486
const outcome: Outcome =
453487
count === undefined ? { kind: "engine-missing" } : { kind: "engine-missing", declared: count }
@@ -474,7 +508,7 @@ async function reconcile(sessionID: string, directory: string, state: DirectoryS
474508

475509
// The engine is configured. The first status call boots MCP, which awaits
476510
// the engine's handshake; the allowlist lookup overlaps with it.
477-
const [statusMap, declared] = await Promise.all([mcp().status(), declaredFor(workspace.id)])
511+
const [statusMap, declared] = await Promise.all([mcp().status(), declaredFor(workspace)])
478512
let status = statusMap[DATAMATE_KEY]
479513
const session = sessions.get(sessionID)
480514
if (status?.status !== "connected" && !session?.retried) {

‎packages/opencode/src/altimate/workspace/engine-probes.ts‎

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,17 +8,22 @@ import { AltimateApi } from "@/altimate/api/client"
88
import { AppRuntime } from "@/effect/app-runtime"
99
import { EventV2Bridge } from "@/event-v2-bridge"
1010
import { TuiEvent } from "@/server/tui-event"
11-
import { readLocalBinding, type CachedBinding } from "./state"
12-
import { log, syncInternals } from "./engine-seams"
11+
import { credentialScope, readLocalBinding } from "./state"
12+
import { log, syncInternals, type ScopedBinding } from "./engine-seams"
1313
import type { Declared, Toast } from "./engine-types"
1414

1515
/** How long the allowlist lookup may hold a turn. Once per workspace per process. */
1616
export const DECLARED_TIMEOUT_MS = 4_000
1717

18-
export async function resolveBinding(directory: string): Promise<CachedBinding | null> {
18+
export async function resolveBinding(directory: string): Promise<ScopedBinding | null> {
1919
if (syncInternals.resolveBinding) return syncInternals.resolveBinding(directory)
2020
try {
21-
return await readLocalBinding(directory)
21+
const binding = await readLocalBinding(directory)
22+
if (!binding) return null
23+
// The cache only answers for the credentials' own tenant, so a hit is in
24+
// scope; carry that scope, since the workspace id alone is tenant-local.
25+
const scope = await credentialScope()
26+
return { ...binding, scope: scope ? `${scope.tenant}|${scope.apiUrl}` : undefined }
2227
} catch (err) {
2328
log.warn("could not resolve the workspace binding", { err: String(err) })
2429
return null

‎packages/opencode/src/altimate/workspace/engine-seams.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,12 @@ import type { Declared, LocalMcpConfig, McpEntry, McpStatus, Toast } from "./eng
1111
export const log = Log.create({ service: "workspace-engine" })
1212

1313
/** Test seams. Production leaves every field unset. */
14+
/** A binding plus the credential scope it was read under (`tenant|apiUrl`).
15+
* Absent when the scope could not be resolved. */
16+
export type ScopedBinding = CachedBinding & { scope?: string }
17+
1418
export const syncInternals: {
15-
resolveBinding?: (directory: string) => Promise<CachedBinding | null>
19+
resolveBinding?: (directory: string) => Promise<ScopedBinding | null>
1620
which?: (cmd: string) => string | null
1721
versionOf?: (bin: string) => Promise<string | null>
1822
declared?: (workspaceId: string) => Promise<Declared | null>

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

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -163,6 +163,13 @@ function canonicalizeKey(directory: string): string {
163163
}
164164
}
165165

166+
/** The (tenant, apiUrl) the current credentials name — the scope every
167+
* binding lives in. Workspace ids are tenant-local, so anything that keys on
168+
* a workspace across an account switch needs this alongside the id. */
169+
export async function credentialScope(): Promise<{ tenant: string; apiUrl: string } | null> {
170+
return tenantKey()
171+
}
172+
166173
async function tenantKey(): Promise<{ tenant: string; apiUrl: string } | null> {
167174
// Best-effort: ``AltimateApi.getCredentials`` can throw ``SyntaxError`` on
168175
// a corrupt credentials JSON, ``ZodError`` on schema drift, or a raw

‎packages/opencode/src/session/prompt.ts‎

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -2974,6 +2974,18 @@ NOTE: At any point in time through this workflow you should feel free to ask the
29742974
})
29752975

29762976
const model = await lastModel(input.sessionID)
2977+
// The workspace-managed `datamate` key is derived per process: this
2978+
// command must not close or restart that engine, nor persist `enabled`
2979+
// for it. Asked before the config check — a refused engine has no
2980+
// config entry at all, and "not found" would be the wrong answer.
2981+
const managed = name === DATAMATE_KEY ? await WorkspaceEngine.managedWorkspaceLoaded() : null
2982+
if (managed) {
2983+
return respond(
2984+
userMsg.info.id,
2985+
`MCP server **${name}** is managed by workspace **${managed.name}** in this project and cannot be ${subCmd}d here. Unlink the project, or run without ALTIMATE_WORKSPACE, to manage it by hand.`,
2986+
model,
2987+
)
2988+
}
29772989
// MCP.connect/disconnect on an unknown name logs and returns silently, so
29782990
// validate against config first and give the user a clear signal on a typo.
29792991
const cfg = await Config.get()
@@ -2987,18 +2999,6 @@ NOTE: At any point in time through this workflow you should feel free to ask the
29872999
)
29883000
}
29893001

2990-
// The workspace-managed `datamate` key is derived per process: this
2991-
// command must not close or restart that engine, nor persist `enabled`
2992-
// for it. Same refusal as the HTTP routes, in the command's own reply.
2993-
const managed = name === DATAMATE_KEY ? await WorkspaceEngine.managedWorkspaceLoaded() : null
2994-
if (managed) {
2995-
return respond(
2996-
userMsg.info.id,
2997-
`MCP server **${name}** is managed by workspace **${managed.name}** in this project and cannot be ${subCmd}d here. Unlink the project, or run without ALTIMATE_WORKSPACE, to manage it by hand.`,
2998-
model,
2999-
)
3000-
}
3001-
30023002
let responseText: string
30033003

30043004
if (isEnable) {

‎packages/opencode/test/altimate/workspace/engine-overlay.test.ts‎

Lines changed: 35 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -25,18 +25,18 @@ import {
2525
type McpEntry,
2626
type Toast,
2727
} from "../../../src/altimate/workspace/engine-overlay"
28-
import type { CachedBinding } from "../../../src/altimate/workspace/state"
28+
import type { ScopedBinding } from "../../../src/altimate/workspace/engine-seams"
2929
import { DATAMATE_KEY } from "../../../src/altimate/datamate-transport"
3030

3131
const DIR = "/tmp/analytics"
3232
const ORIGINAL_FLAG = process.env.ALTIMATE_WORKSPACE
3333

34-
const bound = (id: number, name = "analytics"): CachedBinding =>
35-
({ datamateId: id, datamateName: name, repoRemote: null, projectPath: DIR, linkedAt: 0 }) as CachedBinding
34+
const bound = (id: number, name = "analytics", scope = "acme|https://api.acme.example"): ScopedBinding =>
35+
({ datamateId: id, datamateName: name, repoRemote: null, projectPath: DIR, linkedAt: 0, scope }) as ScopedBinding
3636

3737
type Harness = {
3838
config: { mcp?: Record<string, unknown> }
39-
binding: CachedBinding | null
39+
binding: ScopedBinding | null
4040
which: string | null
4141
version: string | null
4242
status: string
@@ -60,7 +60,7 @@ function install(opts: {
6060
flag?: boolean
6161
serve?: boolean
6262
headless?: boolean
63-
binding?: CachedBinding | null
63+
binding?: ScopedBinding | null
6464
which?: string | null
6565
version?: string | null
6666
declared?: Declared | null
@@ -396,7 +396,7 @@ describe("beforeTurn — what a turn boundary does", () => {
396396
test("overlay state is kept per directory, so one process can host two bound projects", async () => {
397397
const DIR_B = "/tmp/growth"
398398
const h = install({})
399-
const bindings: Record<string, CachedBinding> = { [DIR]: bound(42), [DIR_B]: bound(7, "growth") }
399+
const bindings: Record<string, ScopedBinding> = { [DIR]: bound(42), [DIR_B]: bound(7, "growth") }
400400
syncInternals.resolveBinding = async (directory) => bindings[directory] ?? null
401401
const configA: { mcp?: Record<string, unknown> } = { mcp: {} }
402402
const configB: { mcp?: Record<string, unknown> } = { mcp: {} }
@@ -535,9 +535,36 @@ describe("beforeTurn — what a turn boundary does", () => {
535535
expect(settledOutcome("s1")?.kind).toBe("attached")
536536
})
537537

538-
test("a relink whose overlay then fails releases the old workspace's engine and says so", async () => {
539-
// Workspace A's engine may not go on serving a directory now bound to B.
538+
test("the same workspace id under another account is another workspace: engine and inventory replaced", async () => {
539+
// Ids are tenant-local. After an account switch the directory may be bound
540+
// to "workspace 42" of the new tenant; the engine started under the old
541+
// credentials and the old allowlist must not be kept.
540542
const h = install({})
543+
let lookups = 0
544+
const inner = syncInternals.declared!
545+
syncInternals.declared = async (id) => {
546+
lookups += 1
547+
return inner(id)
548+
}
549+
await beforeTurn("s1")
550+
expect(settledOutcome("s1")?.kind).toBe("attached")
551+
expect(h.added).toHaveLength(0)
552+
expect(lookups).toBe(1)
553+
h.binding = bound(42, "analytics", "globex|https://api.globex.example")
554+
await beforeTurn("s1")
555+
expect(settledOutcome("s1")?.kind).toBe("attached")
556+
expect(h.added).toHaveLength(1)
557+
expect(lookups).toBe(2)
558+
// Same account, same workspace: nothing is replaced.
559+
await beforeTurn("s1")
560+
expect(h.added).toHaveLength(1)
561+
expect(lookups).toBe(2)
562+
})
563+
564+
test("a relink whose overlay then fails releases the old workspace's engine and says so", async () => {
565+
// Workspace A's engine may not go on serving a directory now bound to B —
566+
// and neither may the IDE entry the reloaded config still carries.
567+
const h = install({ mcp: { datamate: IDE_ENTRY } })
541568
await beforeTurn("s1")
542569
expect(settledOutcome("s1")?.kind).toBe("attached")
543570
h.binding = bound(43, "ops")

0 commit comments

Comments
 (0)