Personal Telegram developer console for GitHub

fix: persist Phase 2 workspace navigation refs (#58)

davoodmehraban89 committed Oct 7, 2026 at 19:07 UTC 6f591a460e1079d948e7e8650558a119099f9405
4 files changed +23 -2
src/durable/workspace-store.js
+1 -1
@@ -21,7 +21,7 @@ export class WorkspaceStore{
21 case'/workspace/message':return json({result:await this.#setCommitMessage(payload,now)});case'/workspace/cancel':return json({result:await this.#cancelWorkspace(payload)});case'/pending/set':return json({result:await this.#setPending(payload,now)});case'/pending/get':return json({result:await this.#getPending(now)});case'/pending/consume':return json({result:await this.#consumePending(payload,now)});case'/intent/seal':return json({result:await this.#sealIntent(payload,now)});case'/intent/get':return json({result:await this.#getExpiring(`intent:${String(payload.intentId||'')}`,now)});case'/intent/begin':return json({result:await this.#beginCommit(payload,now)});case'/intent/candidate':return json({result:await this.#setCandidate(payload,now)});case'/intent/complete':return json({result:await this.#completeCommit(payload,now)});case'/intent/stale':return json({result:await this.#markStale(payload,now)});default:return new Response('Not Found',{status:404})}}catch(error){return json({error:String(error?.message||'Workspace store operation failed')},400)}}
22 async #schedule(expiresAt){const expiry=Number(expiresAt);if(!Number.isFinite(expiry))return;const current=Number(await this.state.storage.get('__next_alarm'));if(!Number.isFinite(current)||expiry<current){await this.state.storage.put('__next_alarm',expiry);await this.state.storage.setAlarm(expiry)}}
23 async #getExpiring(key,now){if(!key||key.endsWith(':'))return null;const record=await this.state.storage.get(key);if(!record)return null;if(expired(record,now)){await this.state.storage.delete(key);return null}return record}
24 - async #createRefs(payload,now){if(!Array.isArray(payload.refs))throw new Error('Navigation refs are required');const expiresAt=now+positiveTtl(payload.ttlMs,REF_TTL_MS),output=[];for(const source of payload.refs){const refId=randomHandle(10),record={repoId:source?.repoId,path:String(source?.path||''),type:source?.type==='dir'?'dir':'file',sha:String(source?.sha||''),expiresAt};await this.state.storage.put(`ref:${refId}`,record);output.push({refId})}await this.#schedule(expiresAt);return output}
24 + async #createRefs(payload,now){if(!Array.isArray(payload.refs))throw new Error('Navigation refs are required');const expiresAt=now+positiveTtl(payload.ttlMs,REF_TTL_MS),output=[];for(const source of payload.refs){const refId=randomHandle(10),type=['dir','file','workspace-add','workspace-file'].includes(source?.type)?source.type:'file',workspaceId=String(source?.workspaceId||'');if(type.startsWith('workspace-')&&!/^[A-Za-z0-9_-]{10}$/.test(workspaceId))throw new Error('Workspace navigation ref is invalid');const record={repoId:source?.repoId,path:String(source?.path||''),type,sha:String(source?.sha||''),...(type.startsWith('workspace-')?{workspaceId}:{}),expiresAt};await this.state.storage.put(`ref:${refId}`,record);output.push({refId})}await this.#schedule(expiresAt);return output}
25 async #createWorkspace(payload,now){const id=randomHandle(10),expiresAt=Number.isFinite(Number(payload.expiresAt))?Number(payload.expiresAt):now+WORKSPACE_TTL_MS;if(expiresAt<=now)throw new Error('Workspace expiry must be in the future');const first=legacyFile(payload);validateFiles([first]);const workspace={id,schemaVersion:2,repoId:payload.repoId,repoFullName:String(payload.repoFullName||''),baseBranch:String(payload.baseBranch||''),baseHeadSha:String(payload.baseHeadSha||''),baseTreeSha:String(payload.baseTreeSha||''),path:first.path,blobSha:first.blobSha,originalText:first.originalText,originalDigest:first.originalDigest,draftText:first.draftText,draftDigest:first.draftDigest,files:[first],commitMessage:'',commitMessageDigest:'',currentIntentId:null,state:'DRAFT',createdAt:now,updatedAt:now,expiresAt};await this.state.storage.put(`ws:${id}`,workspace);await this.#schedule(expiresAt);return workspace}
26 async #requireWorkspace(id,now){const ws=migrate(await this.#getExpiring(`ws:${String(id||'')}`,now));if(!ws)throw new Error('Workspace not found or expired');return ws}
27 async #saveMaterial(ws,files,now){validateFiles(files);const primary=files[0];const updated={...ws,schemaVersion:2,files,path:primary.path,blobSha:primary.blobSha,originalText:primary.originalText,originalDigest:primary.originalDigest,draftText:primary.draftText,draftDigest:primary.draftDigest,currentIntentId:null,state:'DRAFT',updatedAt:now};await this.state.storage.put(`ws:${ws.id}`,updated);return updated}
src/plugins/github/workspace.js
+1 -1
@@ -219,7 +219,7 @@ export function createWorkspaceController({ github, workspaces, editorUrl = DEFA
219 const workspace = await requireWorkspace(workspaceId, ownerId);
220 if (Number(workspace.repoId) !== Number(repoId)) throw new Error('Workspace repository mismatch');
221 const existingPaths = new Set((Array.isArray(workspace.files) && workspace.files.length ? workspace.files : [{ path: workspace.path }]).map(file => file.path));
222 - const items = (await github.listFiles(repoId, '')).filter(item => item.type === 'file' && !existingPaths.has(item.path)).slice(0, 20);
222 + const items = (await github.listFiles(repoId, '', { ref: workspace.baseHeadSha })).filter(item => item.type === 'file' && !existingPaths.has(item.path)).slice(0, 20);
223 const refs = await workspaces.createNavigationRefs({ ownerId, refs: items.map(item => ({ repoId, workspaceId, path:item.path, type:'workspace-add', sha:item.sha })) });
224 return { text:`➕ <b>افزودن فایل به Change Set</b>\n${items.length ? 'یک فایل را انتخاب کنید.' : 'فایل قابل افزودن دیگری در این نما نیست.'}`, reply_markup:{inline_keyboard:items.map((item,i)=>[{text:`📄 ${short(item.path,42)}`,callback_data:`wadd:${refs[i].refId}`}]).concat([[{text:'↩️ Workspace',callback_data:`ws:${workspaceId}`} ]])} };
225 };
test/phase2-controller.test.js
+9
@@ -43,3 +43,12 @@ test('file picker rejects a repo id that is not bound to the workspace', async()
43 const c=createWorkspaceController({github:{async listFiles(){throw new Error('must not read mismatched repo')}},workspaces});
44 await assert.rejects(()=>c.resolveCallback('wfiles:W000000001:2',{ownerId:'42'}).execute(),/repository mismatch/i);
45 });
46 +
47 +test('file picker lists candidates from the exact workspace base snapshot', async()=>{
48 + let seen;
49 + const workspaces={async getWorkspace(){return structuredClone(ws)},async createNavigationRefs({refs}){return refs.map((_,i)=>({refId:'R'+String(i).padStart(9,'0')}))}};
50 + const github={async listFiles(repoId,path,options){seen={repoId,path,options};return [{type:'file',path:'src/new.js',sha:'e'.repeat(40)}]}};
51 + const c=createWorkspaceController({github,workspaces});
52 + await c.resolveCallback('wfiles:W000000001:1',{ownerId:'42'}).execute();
53 + assert.deepEqual(seen,{repoId:1,path:'',options:{ref:ws.baseHeadSha}});
54 +});
test/workspace-store.test.js
+12
@@ -105,6 +105,18 @@ test('workspace store isolates refs and workspaces by owner', async () => {
105 assert.equal(await client.getWorkspace({ ownerId: 'B', workspaceId: workspace.id }), null);
106 });
107
108 +test('workspace navigation refs preserve bounded workspace metadata', async () => {
109 + const Client = requireExport(clientModule, 'DurableWorkspaceStoreClient');
110 + const Store = requireExport(durableModule, 'WorkspaceStore');
111 + const namespace = makeNamespace(Store);
112 + const client = new Client({ namespace, now: () => 1_000 });
113 +
114 + const [ref] = await client.createNavigationRefs({ ownerId: 'A', refs: [{ repoId: 1, workspaceId: 'W000000001', path: 'src/a.js', type: 'workspace-add', sha: 'a'.repeat(40) }] });
115 + assert.deepEqual(await client.resolveNavigationRef({ ownerId: 'A', refId: ref.refId }), {
116 + repoId: 1, workspaceId: 'W000000001', path: 'src/a.js', type: 'workspace-add', sha: 'a'.repeat(40), expiresAt: 901000
117 + });
118 +});
119 +
120 test('expired refs and workspaces read as missing and schedule cleanup', async () => {
121 const Client = requireExport(clientModule, 'DurableWorkspaceStoreClient');
122 const Store = requireExport(durableModule, 'WorkspaceStore');