Personal Telegram developer console for GitHub

phase2-20261005-h
audit/commit-drilldown audit/finalize-workspace-menu-security audit/ops-actionability audit/pr-menu-consolidation audit/status-menu-consolidation audit/telegram-menu-e2e audit/telegram-menu-e2e-wave2 chore/actions-node24-runtime cleanup/remove-diag design/cloudflare-ops-read docs/control-plane-2-7-design docs/guide-v2-1-sync docs/menu-audit-final-sync docs/phase2-acceptance-closeout docs/phase2-multifile-design feat/bootstrap-worker feat/cloudflare-ops-read feat/cp2-multifile-final feat/cp2-multifile-workspace feat/cp3-github-write-final feat/cp4-cloudflare-ops-final feat/cp5-cicd-control-plane feat/cp6-incident-manager feat/cp7-automation-engine feat/deep-file-browser feat/final-delivery-16-20 feat/github-advanced-read feat/in-app-guide-v2 feat/navigation-recovery-ux-v2 feat/ops-console-v2-1 feat/persistent-menu-code-input feat/phase2-multifile-workspace feat/phase2-multifile-workspace-v2 feat/plugin-foundation-v1 feat/safe-github-ops feat/self-register-webhook feat/studio-g0-foundation feat/telegram-main-inline-menu feat/telegram-pr-merge feat/ux-platform-8-12 feat/v3a-readonly-copilot feat/workspace-file-upload feature/mobile-repo-browser feature/multi-file-change-set fix/approval-expiry-feedback fix/callback-resilience-and-docs fix/ci-actions-pagination fix/cloudflare-fetch-binding fix/editor-request-body-cap fix/editor-safe-file-options fix/issues-permission-release-empty-ux fix/main-menu-callback-fallback fix/phase2-file-editor-selection fix/phase2-final-ux fix/phase2-workspace-ref-persistence fix/production-auto-deploy fix/provider-write-error-feedback fix/repository-id-navigation-fallback fix/repository-pr-navigation fix/telegram-callback-updates fix/telegram-runtime-diagnostics fix/workspace-editor-flow-v2 fix/workspace-recovery-validation hardening/ci-zero-test-telegram-token hardening/pr1-destructive-totp hardening/pr2-kill-switch main multifile-workspace nexa/edit-BwJEIIY3PW nexa/edit-IPHT8irO7b nexa/edit-b4Od3BIMYd p2-multifile phase2-20261005 phase2-20261005-a phase2-20261005-b phase2-20261005-c phase2-20261005-d phase2-20261005-e phase2-20261005-f phase2-20261005-g phase2-20261005-h phase2-20261005-i phase2-20261005-j phase2-20261005-k phase2-20261005-l phase2-20261005-m phase2-20261005-n phase2-20261005-o phase2-20261005-p phase2-20261005-q phase2-20261005-r phase2-20261005-s phase2-20261005-t phase2-20261005-u phase2-20261005-v phase2-20261005-w phase2-20261005-x phase2-20261005-y phase2-20261005-z phase2-acceptance-closeout phase2-add-file-hotfix phase2-change-set phase2-design-20261005 phase2-design-final phase2-implementation phase2-multifile-implementation phase2-multifile-spec phase2-spec-final phase2-workspace phase2/multifile-workspace plan/nexa-studio-v2-reviewed security/remove-telegram-setup spec/repository-workspace-editor v3a/multifile work/multifile
js 266 lines 12.2 KB
Raw
1 import test from 'node:test';
2 import assert from 'node:assert/strict';
3 import { GitHubService } from '../src/github.js';
4 import { createGitHubPlugin } from '../src/plugins/github/plugin.js';
5
6 function makeMenu() {
7 const calls = [];
8 return {
9 calls,
10 async getReposListView() { calls.push('/repos'); return { text: 'repos', reply_markup: { inline_keyboard: [] } }; },
11 async renderByCallback(data) { calls.push(data); return { text: `legacy:${data}`, reply_markup: { inline_keyboard: [] } }; }
12 };
13 }
14
15 function makeWorkspaces() {
16 const calls = [];
17 const refs = new Map();
18 const workspaces = new Map();
19 let refCounter = 0;
20 return {
21 calls,
22 refs,
23 workspaces,
24 async createNavigationRefs({ ownerId, refs: input }) {
25 calls.push(['createNavigationRefs', ownerId, structuredClone(input)]);
26 return input.map(ref => {
27 refCounter += 1;
28 const refId = `R${String(refCounter).padStart(9, '0')}`;
29 refs.set(`${ownerId}:${refId}`, structuredClone(ref));
30 return { refId };
31 });
32 },
33 async resolveNavigationRef({ ownerId, refId }) {
34 calls.push(['resolveNavigationRef', ownerId, refId]);
35 return refs.get(`${ownerId}:${refId}`) || null;
36 },
37 async createWorkspace(payload) {
38 calls.push(['createWorkspace', payload.ownerId, payload.path, payload.baseHeadSha]);
39 const workspace = { id: 'W000000001', state: 'DRAFT', draftText: payload.originalText, ...payload };
40 workspaces.set(`${payload.ownerId}:${workspace.id}`, workspace);
41 return workspace;
42 },
43 async getWorkspace({ ownerId, workspaceId }) {
44 calls.push(['getWorkspace', ownerId, workspaceId]);
45 return workspaces.get(`${ownerId}:${workspaceId}`) || null;
46 }
47 };
48 }
49
50 function makeGitHub({ archived = false, fileText = 'export const ok = true;\n', filePath = 'src/deep/really-long-file-name-for-mobile-editor.js' } = {}) {
51 const calls = [];
52 const headSha = 'a'.repeat(40);
53 const treeSha = 'b'.repeat(40);
54 const blobSha = 'c'.repeat(40);
55 return {
56 calls,
57 headSha,
58 treeSha,
59 blobSha,
60 async getRepository(repoId) {
61 calls.push(['getRepository', Number(repoId)]);
62 return { id: String(repoId), name: 'demo', fullName: 'davood/demo', defaultBranch: 'main', archived };
63 },
64 async listFiles(repoId, path = '', options = {}) {
65 calls.push(['listFiles', Number(repoId), path, options.ref || null]);
66 if (path === 'src/deep') {
67 return [{ name: 'nested.js', path: 'src/deep/nested.js', type: 'file', size: 20, sha: 'd'.repeat(40) }];
68 }
69 return [
70 { name: 'deep', path: 'src/deep', type: 'dir', size: 0, sha: 'e'.repeat(40) },
71 { name: 'really-long-file-name-for-mobile-editor.js', path: filePath, type: 'file', size: new TextEncoder().encode(fileText).byteLength, sha: blobSha }
72 ];
73 },
74 async getBranchSnapshot(repoId, branch) {
75 calls.push(['getBranchSnapshot', Number(repoId), branch]);
76 return { branch, headSha, treeSha };
77 },
78 async getFileAtRef(repoId, path, ref) {
79 calls.push(['getFileAtRef', Number(repoId), path, ref]);
80 return {
81 path,
82 sha: path === filePath ? blobSha : 'd'.repeat(40),
83 size: new TextEncoder().encode(fileText).byteLength,
84 encoding: 'utf-8',
85 content: fileText
86 };
87 }
88 };
89 }
90
91 function flatten(view) {
92 return view.reply_markup?.inline_keyboard?.flat() || [];
93 }
94
95 test('exact files callback resolves side-effect-free then renders path-safe short navigation refs', async () => {
96 const github = makeGitHub();
97 const workspaces = makeWorkspaces();
98 const menu = makeMenu();
99 const plugin = createGitHubPlugin({ github, menu, workspaces });
100
101 const route = plugin.resolveCallback('files:123', { ownerId: '42' });
102 assert.equal(route.actionId, 'github.files.list');
103 assert.deepEqual(github.calls, []);
104 assert.deepEqual(workspaces.calls, []);
105
106 const view = await route.execute();
107 const buttons = flatten(view).filter(button => button.callback_data?.startsWith('wnav:'));
108 assert.equal(buttons.length, 2);
109 for (const button of buttons) {
110 assert.match(button.callback_data, /^wnav:[A-Za-z0-9_-]{10}$/);
111 assert.ok(new TextEncoder().encode(button.callback_data).byteLength <= 64);
112 assert.doesNotMatch(button.callback_data, /src|really-long|\.js/);
113 }
114 assert.equal(menu.calls.length, 0);
115 });
116
117 test('nested directory resolves through short ref and preserves the full server-side path', async () => {
118 const github = makeGitHub();
119 const workspaces = makeWorkspaces();
120 const plugin = createGitHubPlugin({ github, menu: makeMenu(), workspaces });
121 const root = await plugin.resolveCallback('files:123', { ownerId: '42' }).execute();
122 const dirCallback = flatten(root).find(button => button.text?.includes('deep'))?.callback_data;
123 assert.match(dirCallback, /^wnav:/);
124
125 github.calls.length = 0;
126 workspaces.calls.length = 0;
127 const route = plugin.resolveCallback(dirCallback, { ownerId: '42' });
128 assert.equal(route.actionId, 'github.workspace.navigate');
129 assert.deepEqual(github.calls, []);
130 assert.deepEqual(workspaces.calls, []);
131 const nested = await route.execute();
132 assert.ok(flatten(nested).some(button => /^wnav:/.test(button.callback_data || '')));
133 assert.ok(github.calls.some(call => call[0] === 'listFiles' && call[2] === 'src/deep'));
134 });
135
136 test('eligible file preview including README shows Edit while risky or truly oversized content stays readable with explicit disabled reason', async () => {
137 for (const fixture of [
138 { path: 'src/app.js', text: 'console.log(1);\n', editable: true },
139 { path: 'README.md', text: `# Nexa Dev Bot\n\n${'x'.repeat(8200)}`, editable: true },
140 { path: '.env.production', text: 'NOT_A_REAL_SECRET=value\n', editable: false, reason: /sensitive/i },
141 { path: 'large.txt', text: 'x'.repeat(20001), editable: false, reason: /20,000|20000/ },
142 { path: 'asset.txt', text: 'version https://git-lfs.github.com/spec/v1\noid sha256:abc\nsize 9\n', editable: false, reason: /LFS/i }
143 ]) {
144 const github = makeGitHub({ fileText: fixture.text, filePath: fixture.path });
145 const workspaces = makeWorkspaces();
146 const plugin = createGitHubPlugin({ github, menu: makeMenu(), workspaces });
147 const root = await plugin.resolveCallback('files:123', { ownerId: '42' }).execute();
148 const fileCallback = flatten(root).find(button => button.callback_data?.startsWith('wnav:') && !button.text?.includes('deep'))?.callback_data;
149 const view = await plugin.resolveCallback(fileCallback, { ownerId: '42' }).execute();
150 assert.match(view.text, /پیش.?نمایش|فایل/i);
151 const edit = flatten(view).find(button => button.callback_data?.startsWith('wedit:'));
152 if (fixture.editable) {
153 assert.ok(edit, fixture.path);
154 } else {
155 assert.equal(edit, undefined, fixture.path);
156 assert.match(view.text, fixture.reason);
157 }
158 }
159 });
160
161 test('wedit pins default-branch snapshot and exact file before creating a durable draft', async () => {
162 const github = makeGitHub({ filePath: 'src/app.js', fileText: 'before\n' });
163 const workspaces = makeWorkspaces();
164 const plugin = createGitHubPlugin({ github, menu: makeMenu(), workspaces });
165 const root = await plugin.resolveCallback('files:123', { ownerId: '42' }).execute();
166 const fileCallback = flatten(root).find(button => button.callback_data?.startsWith('wnav:') && !button.text?.includes('deep'))?.callback_data;
167 const fileView = await plugin.resolveCallback(fileCallback, { ownerId: '42' }).execute();
168 const editCallback = flatten(fileView).find(button => button.callback_data?.startsWith('wedit:'))?.callback_data;
169
170 github.calls.length = 0;
171 workspaces.calls.length = 0;
172 const route = plugin.resolveCallback(editCallback, { ownerId: '42' });
173 assert.equal(route.actionId, 'github.workspace.create');
174 assert.deepEqual(github.calls, []);
175 assert.deepEqual(workspaces.calls, []);
176 const draftView = await route.execute();
177
178 const snapshotIndex = github.calls.findIndex(call => call[0] === 'getBranchSnapshot');
179 const fileIndex = github.calls.findIndex(call => call[0] === 'getFileAtRef');
180 const createCall = workspaces.calls.find(call => call[0] === 'createWorkspace');
181 assert.ok(snapshotIndex >= 0 && fileIndex > snapshotIndex);
182 assert.deepEqual(github.calls[fileIndex].slice(2), ['src/app.js', github.headSha]);
183 assert.deepEqual(createCall, ['createWorkspace', '42', 'src/app.js', github.headSha]);
184 assert.match(draftView.text, /Draft|پیش.?نویس/i);
185 assert.ok(flatten(draftView).some(button => button.callback_data === 'ws:W000000001'));
186 });
187
188 test('archived repository cannot create an editable workspace', async () => {
189 const github = makeGitHub({ archived: true, filePath: 'src/app.js' });
190 const workspaces = makeWorkspaces();
191 const plugin = createGitHubPlugin({ github, menu: makeMenu(), workspaces });
192 const root = await plugin.resolveCallback('files:123', { ownerId: '42' }).execute();
193 const fileCallback = flatten(root).find(button => button.callback_data?.startsWith('wnav:') && !button.text?.includes('deep'))?.callback_data;
194 const fileView = await plugin.resolveCallback(fileCallback, { ownerId: '42' }).execute();
195 const editCallback = flatten(fileView).find(button => button.callback_data?.startsWith('wedit:'))?.callback_data;
196 assert.equal(editCallback, undefined);
197 assert.match(fileView.text, /archiv|آرشیو/i);
198 assert.equal(workspaces.calls.some(call => call[0] === 'createWorkspace'), false);
199 });
200
201 test('legacy tree blob and path-bearing files callbacks remain on MenuManager path', async () => {
202 const github = makeGitHub();
203 const workspaces = makeWorkspaces();
204 const menu = makeMenu();
205 const plugin = createGitHubPlugin({ github, menu, workspaces });
206
207 for (const callback of [
208 `tree:123:${'a'.repeat(40)}`,
209 `blob:123:${'b'.repeat(40)}`,
210 'files:123:src/deep'
211 ]) {
212 const route = plugin.resolveCallback(callback, { ownerId: '42' });
213 const view = await route.execute();
214 assert.equal(view.text, `legacy:${callback}`);
215 }
216 });
217
218 test('workspace READ actions are declared and all short callback families fit Telegram limit', () => {
219 const plugin = createGitHubPlugin({ github: makeGitHub(), menu: makeMenu(), workspaces: makeWorkspaces() });
220 for (const actionId of [
221 'github.workspace.navigate',
222 'github.workspace.create',
223 'github.workspace.view',
224 'github.workspace.input.prepare',
225 'github.workspace.diff',
226 'github.workspace.ready',
227 'github.workspace.cancel'
228 ]) {
229 assert.equal(plugin.manifest.actions[actionId]?.risk, 'READ', actionId);
230 }
231 for (const callback of [
232 'wnav:R123456789', 'wedit:R123456789', 'ws:W123456789', 'wtext:W123456789',
233 'wmsg:W123456789', 'wdiff:W123456789', 'wready:W123456789', 'wcancel:W123456789'
234 ]) {
235 assert.ok(new TextEncoder().encode(callback).byteLength <= 64, callback);
236 }
237 });
238
239 test('GitHubService reads pinned branch snapshot and UTF-8 file at full SHA', async () => {
240 const originalFetch = globalThis.fetch;
241 const seen = [];
242 const headSha = 'a'.repeat(40);
243 const treeSha = 'b'.repeat(40);
244 const blobSha = 'c'.repeat(40);
245 globalThis.fetch = async (url, options = {}) => {
246 seen.push([String(url), options.method || 'GET']);
247 const value = String(url);
248 if (value.endsWith('/repositories/123')) return Response.json({ id: 123, name: 'demo', full_name: 'davood/demo', default_branch: 'main' });
249 if (value.endsWith('/repos/davood/demo/git/ref/heads/main')) return Response.json({ object: { sha: headSha } });
250 if (value.endsWith(`/repos/davood/demo/git/commits/${headSha}`)) return Response.json({ sha: headSha, tree: { sha: treeSha } });
251 if (value.endsWith(`/repos/davood/demo/contents/src/app.js?ref=${headSha}`)) {
252 return Response.json({ type: 'file', path: 'src/app.js', sha: blobSha, size: 6, encoding: 'base64', content: btoa('hello\n') });
253 }
254 return new Response('unexpected', { status: 500 });
255 };
256 try {
257 const github = new GitHubService('token', 'davood');
258 assert.deepEqual(await github.getBranchSnapshot(123, 'main'), { branch: 'main', headSha, treeSha });
259 assert.deepEqual(await github.getFileAtRef(123, 'src/app.js', headSha), {
260 path: 'src/app.js', sha: blobSha, size: 6, encoding: 'utf-8', content: 'hello\n'
261 });
262 assert.ok(seen.some(([url]) => url.endsWith(`/contents/src/app.js?ref=${headSha}`)));
263 } finally {
264 globalThis.fetch = originalFetch;
265 }
266 });