import test from 'node:test'; import assert from 'node:assert/strict'; import { createProjectClient } from '../src/client.js'; const project = id => ({id,folderId:id,name:id,path:`/projects/${id}.isap`,projectIdentity:id,formatVersion:1}); function fixture(options = {}) { const writes = []; const files = new Map(['one','two','three'].map(id => [`${project(id).path}/project.json`,{ formatVersion:1,id,name:id,createdAt:'2026-11-03T12:00:00Z',updatedAt:'2026-11-03T12:00:00Z',unknown:{kept:true} }])); const saved = new Map(); const directories = new Set(['/projects']); const bridge = { async invoke(command,args) { if (command.startsWith('localstorage_')) { assert.equal(Object.hasOwn(args, 'workspaceId'), false, 'Private storage scope is set by the host'); assert.equal(Object.hasOwn(args, 'groupId'), false, 'Private storage scope is set by the host'); } if (options.invoke) { const result = options.invoke(command,args); if (result !== undefined) return result; } if (command === 'filesystem_get_files') { const path = args.files[0].path; return {items:[files.has(path) ? {status:'ok',path,source:'dashboard',authoritative:true,text:JSON.stringify(files.get(path)),fileId:path,syncRevision:4,contentHash:'a'.repeat(64)} : {status:'absent',path,source:'dashboard',authoritative:true}]}; } if (command === 'localstorage_get') return saved.get(args.key) ?? null; if (command === 'localstorage_put') { saved.set(args.key,args.value); return {ok:true}; } if (command === 'open_workspace_folder') return {file:{path:'/projects',id:'parent',kind:'folder',access:'read_write'}}; if (command === 'filesystem_list_dir') return {authoritative:true,files:[...directories] .filter(path => path === args.path || path.startsWith(args.path + '/')) .map(path => ({kind:'folder',path,id:path === '/projects' ? 'parent' : path,canWrite:true}))}; if (command === 'filesystem_create_folder') { directories.add(args.path); return {status:'ok',path:args.path,fileId:args.path}; } if (command === 'filesystem_upload_files') { writes.push(args); const {path,text}=args.files[0]; files.set(path,JSON.parse(text)); return {items:[{status:'ok',isComplete:true,path,fileId:path}]}; } throw new Error(`Unexpected command ${command}`); }, subscribeKv: options.subscribeKv }; const client = createProjectClient({bridge,extensionId:'contracts',scope:{workspaceId:'workspace',groupId:'group'},beforeSwitch:options.beforeSwitch}); return {client,writes,bridge,files}; } test('captured sessions fence old writes and close late subscriptions during switching', async () => { let finishSubscription; let stopped = 0; const {client,writes} = fixture({subscribeKv:() => new Promise(resolve=>{finishSubscription=resolve;})}); const first = await client.activate(project('one')); const subscription = first.subscribeKv('extensions/contracts/state.kv',{},()=>assert.fail('Old subscription event')); await client.activate(project('two')); finishSubscription({unsubscribe:async()=>{stopped++;}}); await assert.rejects(subscription,{name:'AbortError'}); await assert.rejects(first.writeJson('extensions/contracts/state.json',{}, {status:'absent',path:first.path('extensions/contracts/state.json')}),{name:'AbortError'}); assert.equal(stopped,1); assert.equal(writes.length,0); await client.close(); }); test('JSON writes require captured authoritative CAS base and preserve caller data', async () => { const {client,writes,files} = fixture(); const session = await client.activate(project('one')); files.set(session.path('extensions/contracts/state.json'),{unknown:{retained:1},value:2}); const base = await session.readJson('extensions/contracts/state.json'); await session.writeJson('extensions/contracts/state.json',{...base.value,value:3},base); const uploaded = writes[0].files[0]; assert.equal(uploaded.expectedSyncRevision,4); assert.equal(uploaded.expectedContentHash,'a'.repeat(64)); assert.equal(uploaded.replaceExisting,true); assert.deepEqual(JSON.parse(uploaded.text),{unknown:{retained:1},value:3}); assert.equal(writes[0].workspaceId,'workspace'); assert.equal(writes[0].groupId,'group'); await assert.rejects(session.writeJson('elsewhere.json',{},base),/authoritative read/); assert.throws(()=>session.path('../escape.json'),/Unsafe/); await client.close(); }); test('dirty state blocks switching and unavailable reads never become absence', async () => { let missing = false; const {client} = fixture({invoke:(command)=>missing && command==='filesystem_get_files' ? {items:[{status:'unavailable',authoritative:false}]} : undefined}); const first = await client.activate(project('one')); first.markDirty(); await assert.rejects(client.activate(project('two')),/Unsaved/); assert.equal(client.active,first); first.markDirty(false); missing=true; await assert.rejects(first.readJson('state.json'),{name:'ProjectUnavailableError'}); assert.equal(client.active,first); await client.close(); }); test('uncertain create retains the same folder and manifest identity on retry', async () => { const paths=[]; const {client}=fixture({invoke:(command,args)=>{ if(command!=='filesystem_upload_files'||!args.files[0].path.endsWith('/project.json'))return; paths.push(args.files[0].path); if(paths.length===1)throw new Error('Commit outcome unavailable'); }}); await assert.rejects(client.create('Example'),/unavailable/); const created=await client.create('Example'); assert.equal(paths[0],paths[1]); assert.equal(created.manifest.name,'Example'); assert.equal(created.project.projectIdentity,created.manifest.id); await client.close(); }); test('authoritative reads reject another path, cached drafts and ambiguous identities', async () => { let reply; const {client}=fixture({invoke:command=>command==='filesystem_get_files'?reply:undefined}); const session=await client.activate(project('one')); const path=session.path('state.json'); const valid={status:'ok',path,source:'dashboard',authoritative:true,fileId:'file',syncRevision:1,text:'{}'}; for(const change of [{path:path+'wrong'},{source:'cache'},{pendingUpload:true},{syncRevision:null},{workspaceFileOutcome:'conflict'},{status:'absent',path:path+'wrong'}]) { reply={items:[{...valid,...change}]}; await assert.rejects(session.readJson('state.json'),{name:'ProjectUnavailableError'}); } reply={items:[valid,valid]}; await assert.rejects(session.readJson('state.json'),{name:'ProjectUnavailableError'}); await client.close(); }); test('successful transport cannot confirm pending or conflicted project writes', async () => { let reply; const {client}=fixture({invoke:command=>command==='filesystem_upload_files'?reply:undefined}); const session=await client.activate(project('one')); const base=await session.readJson('state.json'); const valid={status:'ok',isComplete:true,path:base.path,fileId:'file'}; for(const change of [{isComplete:false},{path:base.path+'wrong'},{fileId:''},{pendingUpload:true},{pendingState:'queued'},{conflict:true},{workspaceFileOutcome:'conflict'},{workspaceFileOutcome:'pending'},{source:'cache'}]) { reply={items:[{...valid,...change}]}; await assert.rejects(session.writeJson('state.json',{},base),/not confirmed|conflict/); } reply={items:[valid]}; assert.equal((await session.writeJson('state.json',{},base)).fileId,'file'); await client.close(); }); test('a selected container lists valid project manifests and opens them through its existing grant', async () => { let picks = 0; const {client,files} = fixture({invoke(command, args) { if (command === 'open_workspace_folder') { picks++; return; } if (command === 'filesystem_list_dir' && args.path === '/projects') { return {authoritative:true,files:[ {path:'/projects',kind:'folder',fileId:'parent'}, {path:project('two').path,kind:'folder',fileId:'two',canWrite:false}, {path:project('missing').path,kind:'folder',fileId:'incomplete'}, {path:'/projects/not-a-folder.isap',kind:'file',fileId:'file'} ]}; } }}); assert.deepEqual(await client.list(),[]); await client.pickFolder(); const [listed] = await client.list(); assert.equal(listed.canWrite,false); assert.equal(listed.updatedAt,'2026-11-03T12:00:00Z'); const selected = await client.openListed(listed); assert.equal(selected.project.id,'two'); const manifest = files.get(listed.manifestPath); files.set(listed.manifestPath,{...manifest,id:'one'}); await assert.rejects(client.openListed(listed),/identity/); assert.equal(client.active,selected); assert.equal(picks,1); }); test('opening from an existing grant reports a denied row without reopening the picker', async () => { const {client,files} = fixture({invoke(command, args) { if (command === 'filesystem_get_files' && args.files[0].path === project('three').path + '/project.json') { return {items:[{path:args.files[0].path, status:'error', authoritative:false, error:'extension filesystem permission is required'}]}; } if (command === 'open_workspace_folder') assert.fail('Unexpected second project picker'); }}); const selected = await client.openListed(project('one')); files.delete(project('two').path+'/project.json'); await assert.rejects(client.openListed(project('two')), /manifest missing/); await assert.rejects(client.openListed(project('three')), /extension filesystem permission is required/); assert.equal(client.active,selected); }); test('a direct grant initializes the extension directory on first writable access', async () => { const selected = {...project('two'), canWrite:true}; const directories = []; const {client} = fixture({invoke(command, args) { if (command === 'filesystem_list_dir') return {authoritative:true, files:[]}; if (command === 'filesystem_create_folder') { directories.push(args.path); return {status:'ok', path:args.path, fileId:args.path}; } }}); assert.equal((await client.openListed(selected)).project.id, selected.id); assert.deepEqual(directories, [selected.path + '/extensions', selected.path + '/extensions/contracts']); }); test('first-open initialization reads the winning record after a folder race and an uncertain create', async () => { let uploads = 0; const {client, files} = fixture({invoke(command, args) { if (command === 'filesystem_create_folder') throw new Error('Already exists'); if (command === 'filesystem_list_dir') { return {authoritative:true, files:['extensions','contracts','data'].map(name => ({path:args.path + '/' + name, kind:'folder', id:name}))}; } if (command === 'filesystem_upload_files') { const file = args.files[0]; assert.equal(file.replaceExisting, false); assert.equal(file.path, project('one').path + '/extensions/contracts/data/current.json'); files.set(file.path, {from:'other session'}); uploads++; throw new Error('Create outcome unknown'); } }}); const session = await client.activate({...project('one'), canWrite:true}); const created = await session.ensureExtensionJson('data/current.json', () => ({from:'this session'})); assert.deepEqual(created.value, {from:'other session'}); const reopened = await session.ensureExtensionJson('data/current.json', () => assert.fail('Record already exists')); assert.deepEqual(reopened.value, created.value); assert.equal(uploads, 1); }); test('read-only, archived and uncertain reads cannot seed extension records', async () => { let answer; const {client, writes} = fixture({invoke(command, args) { if (command === 'filesystem_get_files' && answer && !args.files[0].path.endsWith('/project.json')) { return {items:[{path:args.files[0].path, ...answer}]}; } }}); const fail = () => assert.fail('Unexpected default'); for (const access of [{canWrite:false}, {archived:true, canWrite:true}]) { const session = await client.activate({...project('one'), ...access}); assert.equal((await session.ensureExtensionJson('state.json', fail)).status, 'absent'); } const session = await client.activate(project('two')); for (answer of [{status:'unavailable'}, {status:'absent',source:'dashboard',authoritative:true,found:true}]) { await assert.rejects(session.ensureExtensionJson('state.json', fail), {name:'ProjectUnavailableError'}); } assert.equal(writes.length, 0); }); test('an archived legacy folder stays in the archive until the manifest explicitly restores it', async () => { const {client} = fixture({invoke(command,args) { if (command === 'open_workspace_folder') { return {file:{path:project('two').path,id:'two',kind:'folder',access:'read_write'}}; } if (command === 'filesystem_list_dir' && args.path === project('two').path) { return {authoritative:true,files:[{path:args.path,fileId:'two',kind:'folder',archivedAt:100}]}; } }}); await client.pickFolder(); assert.deepEqual(await client.list(), []); const [archived] = await client.list(true); assert.equal(archived.archived,true); await client.setArchived(archived,false); assert.equal((await client.list())[0].archived,false); }); test('replaced and revoked roots do not hide accessible projects or conceal dashboard outages', async () => { let offline = false; const {client} = fixture({invoke(command,args) { if (command === 'localstorage_get' && args.key.endsWith('folders.v1')) return [ {path:'/revoked',id:'revoked'}, {path:'/replaced',id:'old'}, {path:'/projects',id:'parent'} ]; if (command !== 'filesystem_list_dir') return; if (args.path === '/revoked') throw new Error('Filesystem path requires a current extension root or picker grant'); if (args.path === '/replaced') return {authoritative:true,files:[ {kind:'folder',path:'/replaced',fileId:'new'}, {kind:'folder',path:'/replaced/other.isap',fileId:'other'} ]}; if (offline) throw new Error('Dashboard unavailable'); return {authoritative:true,files:[ {kind:'folder',path:'/projects',fileId:'workspace_file:parent'}, {kind:'folder',path:project('two').path,fileId:'two'} ]}; }}); assert.deepEqual((await client.list()).map(item => item.id), ['two']); offline = true; await assert.rejects(client.list(),/Dashboard unavailable/); });