Open History to see the last commit
1/**
2 * Unit tests for the OpenCode workspace projector.
3 *
4 * Drives `projectOpencodeWorkspace` with a fake `SandboxHandle` (recording
5 * every `fs.write` / `fs.read` / `process.exec`) and a `WorkspaceProjection`
6 * carrying one of each skill kind plus a plugin. Asserts:
7 *
8 * - `opencode.json` written at the workspace root with the MCP server whose
9 * secret header is RESOLVED (not the SecretRef).
10 * - A `bearer(ref)` header resolves to `"Bearer <value>"`.
11 * - A 2nd call REWRITES `opencode.json` (with a fresh resolved secret) but
12 * does NOT re-run the marker-gated operations.
13 * - The marker file is written.
14 * - gitSkill / agentSkill / plugin all warn-and-skip (not throw).
15 */
16import { describe, expect, it, vi } from 'vitest'
17import {
18 bearer,
19 createSecrets,
20 mcpSkill,
21 agentSkill,
22 gitSkill,
23 resolveGitSkillDir,
24} from '@tanstack/ai-sandbox'
25import { projectOpencodeWorkspace } from '../src/adapters/projection'
26import type {
27 ExecResult,
28 SandboxHandle,
29 WorkspaceProjection,
30 WorkspaceSkill,
31} from '@tanstack/ai-sandbox'
32
33interface RecordedExec {
34 command: string
35 cwd: string | undefined
36}
37
38interface FakeHandle {
39 handle: SandboxHandle
40 writes: Map<string, string>
41 reads: Array<string>
42 execs: Array<RecordedExec>
43 existing: Set<string>
44}
45
46/** Build a fake handle that records writes, reads, and execs. */
47function makeFakeHandle(
48 execResult: ExecResult = { stdout: '', stderr: '', exitCode: 0 },
49): FakeHandle {
50 const writes = new Map<string, string>()
51 const reads: Array<string> = []
52 const execs: Array<RecordedExec> = []
53 const existing = new Set<string>()
54
55 const handle = {
56 fs: {
57 write: (path: string, data: string | Uint8Array) => {
58 writes.set(path, typeof data === 'string' ? data : '')
59 existing.add(path)
60 return Promise.resolve()
61 },
62 read: (path: string) => {
63 reads.push(path)
64 const content = writes.get(path)
65 if (content === undefined)
66 return Promise.reject(new Error(`not found: ${path}`))
67 return Promise.resolve(content)
68 },
69 exists: (path: string) => Promise.resolve(existing.has(path)),
70 mkdir: (_path: string) => Promise.resolve(),
71 },
72 process: {
73 exec: (command: string, options?: { cwd?: string }) => {
74 execs.push({ command, cwd: options?.cwd })
75 return Promise.resolve(execResult)
76 },
77 },
78 } as unknown as SandboxHandle
79
80 return { handle, writes, reads, execs, existing }
81}
82
83const ROOT = '/workspace'
84const MARKER = `${ROOT}/.tanstack-projected-abc123`
85
86describe('projectOpencodeWorkspace', () => {
87 function buildScenario() {
88 const secrets = createSecrets({ MCP_TOKEN: 'super-secret' })
89 const skills: Array<WorkspaceSkill> = [
90 mcpSkill('issues', {
91 url: 'https://mcp.example.com/mcp',
92 headers: { Authorization: secrets.MCP_TOKEN },
93 }),
94 agentSkill('public-skill'),
95 gitSkill({ repo: 'me/my-skill' }),
96 ]
97 const projection: WorkspaceProjection = {
98 skills,
99 plugins: ['@acme/plugin'],
100 resolveSecret: (ref) => {
101 if (ref.__secretName === 'MCP_TOKEN') return 'super-secret'
102 throw new Error(`unknown secret "${ref.__secretName}"`)
103 },
104 markerPath: MARKER,
105 root: ROOT,
106 }
107 return {
108 projection,
109 gitDir: resolveGitSkillDir(ROOT, { kind: 'git', repo: 'me/my-skill' }),
110 }
111 }
112
113 it('writes opencode.json with the MCP secret resolved, warns for gitSkill/agentSkill/plugin, writes the marker', async () => {
114 const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
115 const fake = makeFakeHandle()
116 const { projection } = buildScenario()
117
118 await projectOpencodeWorkspace(fake.handle, projection)
119
120 // opencode.json written with MCP server — secret RESOLVED, no SecretRef leak.
121 const raw = fake.writes.get(`${ROOT}/opencode.json`)
122 expect(raw).toBeDefined()
123 const config = JSON.parse(raw ?? '{}') as { mcp?: Record<string, unknown> }
124 expect(config.mcp).toBeDefined()
125 const entry = config.mcp?.['issues'] as {
126 type?: string
127 url?: string
128 enabled?: boolean
129 headers?: Record<string, string>
130 }
131 expect(entry?.type).toBe('remote')
132 expect(entry?.url).toBe('https://mcp.example.com/mcp')
133 expect(entry?.enabled).toBe(true)
134 expect(entry?.headers?.['Authorization']).toBe('super-secret')
135 // No raw SecretRef bleed-through.
136 expect(raw).not.toContain('__secretName')
137
138 // agentSkill and gitSkill and plugin all produce warnings, not throws.
139 expect(warn).toHaveBeenCalled()
140 const messages = warn.mock.calls.map((call) => String(call[0]))
141 expect(
142 messages.some((m) => m.includes('[opencode]') && m.includes('gitSkill')),
143 ).toBe(true)
144 expect(
145 messages.some(
146 (m) => m.includes('[opencode]') && m.includes('agentSkill'),
147 ),
148 ).toBe(true)
149 expect(
150 messages.some((m) => m.includes('[opencode]') && m.includes('plugin')),
151 ).toBe(true)
152
153 // Marker written.
154 expect(fake.writes.has(MARKER)).toBe(true)
155
156 warn.mockRestore()
157 })
158
159 it('passes plain-string header values through unchanged', async () => {
160 const fake = makeFakeHandle()
161 const projection: WorkspaceProjection = {
162 skills: [
163 mcpSkill('issues', {
164 url: 'https://mcp.example.com/mcp',
165 headers: { 'X-Plain': 'literal-value' },
166 }),
167 ],
168 plugins: [],
169 resolveSecret: () => {
170 throw new Error('resolveSecret should not be called for plain headers')
171 },
172 markerPath: MARKER,
173 root: ROOT,
174 }
175
176 await projectOpencodeWorkspace(fake.handle, projection)
177
178 const config = JSON.parse(
179 fake.writes.get(`${ROOT}/opencode.json`) ?? '{}',
180 ) as {
181 mcp?: Record<string, { headers?: Record<string, string> }>
182 }
183 expect(config.mcp?.['issues']?.headers?.['X-Plain']).toBe('literal-value')
184 })
185
186 it('resolves a bearer(ref) header to "Bearer <resolved-value>"', async () => {
187 const fake = makeFakeHandle()
188 const secrets = createSecrets({ LIN: 'lin-token' })
189 const projection: WorkspaceProjection = {
190 skills: [
191 mcpSkill('issues', {
192 url: 'https://mcp.example.com/mcp',
193 headers: { Authorization: bearer(secrets.LIN) },
194 }),
195 ],
196 plugins: [],
197 resolveSecret: (ref) => {
198 if (ref.__secretName === 'LIN') return 'lin-token'
199 throw new Error(`unknown secret "${ref.__secretName}"`)
200 },
201 markerPath: MARKER,
202 root: ROOT,
203 }
204
205 await projectOpencodeWorkspace(fake.handle, projection)
206
207 const raw = fake.writes.get(`${ROOT}/opencode.json`)
208 const config = JSON.parse(raw ?? '{}') as {
209 mcp?: Record<string, { headers?: Record<string, string> }>
210 }
211 expect(config.mcp?.['issues']?.headers?.['Authorization']).toBe(
212 'Bearer lin-token',
213 )
214 expect(raw).not.toContain('__secretName')
215 expect(raw).not.toContain('__bearerRef')
216 })
217
218 it('rewrites opencode.json on a second call but does not re-run marker-gated ops', async () => {
219 const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
220 const fake = makeFakeHandle()
221 const { projection } = buildScenario()
222
223 await projectOpencodeWorkspace(fake.handle, projection)
224 const warnCountAfterFirst = warn.mock.calls.length
225
226 // Clear the recorded opencode.json write to prove a second call rewrites it.
227 fake.writes.delete(`${ROOT}/opencode.json`)
228 // Make the existing-file check for merging return "not found" since we deleted it.
229 fake.existing.delete(`${ROOT}/opencode.json`)
230
231 await projectOpencodeWorkspace(fake.handle, projection)
232
233 // The secret-bearing MCP config is rewritten every call.
234 const rewritten = fake.writes.get(`${ROOT}/opencode.json`)
235 expect(rewritten).toBeDefined()
236 expect(rewritten).toContain('super-secret')
237
238 // The marker-gated operations (gitSkill / agentSkill / plugins) do NOT
239 // emit further warnings on the second call (marker present, they are skipped).
240 expect(warn.mock.calls.length).toBe(warnCountAfterFirst)
241
242 warn.mockRestore()
243 })
244
245 it('skips opencode.json write when there are no MCP skills', async () => {
246 const fake = makeFakeHandle()
247 const projection: WorkspaceProjection = {
248 skills: [agentSkill('only-agent-skill')],
249 plugins: [],
250 resolveSecret: () => {
251 throw new Error('should not be called')
252 },
253 markerPath: MARKER,
254 root: ROOT,
255 }
256
257 const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
258 await projectOpencodeWorkspace(fake.handle, projection)
259 warn.mockRestore()
260
261 expect(fake.writes.has(`${ROOT}/opencode.json`)).toBe(false)
262 // Marker still written (non-MCP, marker-gated ops ran).
263 expect(fake.writes.has(MARKER)).toBe(true)
264 })
265
266 it('merges the mcp section into an existing opencode.json, preserving other keys', async () => {
267 const fake = makeFakeHandle()
268 // Pre-populate an existing opencode.json with a non-mcp setting.
269 const existing = JSON.stringify({
270 theme: 'dark',
271 keybinds: { 'ctrl+s': 'save' },
272 })
273 fake.writes.set(`${ROOT}/opencode.json`, existing)
274 fake.existing.add(`${ROOT}/opencode.json`)
275
276 const projection: WorkspaceProjection = {
277 skills: [
278 mcpSkill('issues', {
279 url: 'https://mcp.example.com/mcp',
280 headers: {},
281 }),
282 ],
283 plugins: [],
284 resolveSecret: () => {
285 throw new Error('no secret refs in this test')
286 },
287 markerPath: MARKER,
288 root: ROOT,
289 }
290
291 await projectOpencodeWorkspace(fake.handle, projection)
292
293 const raw = fake.writes.get(`${ROOT}/opencode.json`)
294 const config = JSON.parse(raw ?? '{}') as {
295 theme?: string
296 keybinds?: unknown
297 mcp?: Record<string, unknown>
298 }
299 // Existing keys preserved.
300 expect(config.theme).toBe('dark')
301 expect(config.keybinds).toBeDefined()
302 // MCP section written.
303 expect(config.mcp?.['issues']).toBeDefined()
304 })
305})