Personal Telegram developer console for GitHub

test: define path-safe workspace entry flow

davoodmehraban89 committed Oct 3, 2026 at 12:39 UTC ca2537221d88819e511ce20f7e7e8696c54f29fb
1 file changed +265
test/github-workspace-ui.test.js new
+265
@@ -0,0 +1,265 @@
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 shows Edit while risky or 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: '.env.production', text: 'NOT_A_REAL_SECRET=value\n', editable: false, reason: /sensitive/i },
140 + { path: 'large.txt', text: 'x'.repeat(3001), editable: false, reason: /3,000|3000/ },
141 + { path: 'asset.txt', text: 'version https://git-lfs.github.com/spec/v1\noid sha256:abc\nsize 9\n', editable: false, reason: /LFS/i }
142 + ]) {
143 + const github = makeGitHub({ fileText: fixture.text, filePath: fixture.path });
144 + const workspaces = makeWorkspaces();
145 + const plugin = createGitHubPlugin({ github, menu: makeMenu(), workspaces });
146 + const root = await plugin.resolveCallback('files:123', { ownerId: '42' }).execute();
147 + const fileCallback = flatten(root).find(button => button.callback_data?.startsWith('wnav:') && !button.text?.includes('deep'))?.callback_data;
148 + const view = await plugin.resolveCallback(fileCallback, { ownerId: '42' }).execute();
149 + assert.match(view.text, /پیش.?نمایش|فایل/i);
150 + const edit = flatten(view).find(button => button.callback_data?.startsWith('wedit:'));
151 + if (fixture.editable) {
152 + assert.ok(edit, fixture.path);
153 + } else {
154 + assert.equal(edit, undefined, fixture.path);
155 + assert.match(view.text, fixture.reason);
156 + }
157 + }
158 +});
159 +
160 +test('wedit pins default-branch snapshot and exact file before creating a durable draft', async () => {
161 + const github = makeGitHub({ filePath: 'src/app.js', fileText: 'before\n' });
162 + const workspaces = makeWorkspaces();
163 + const plugin = createGitHubPlugin({ github, menu: makeMenu(), workspaces });
164 + const root = await plugin.resolveCallback('files:123', { ownerId: '42' }).execute();
165 + const fileCallback = flatten(root).find(button => button.callback_data?.startsWith('wnav:') && !button.text?.includes('deep'))?.callback_data;
166 + const fileView = await plugin.resolveCallback(fileCallback, { ownerId: '42' }).execute();
167 + const editCallback = flatten(fileView).find(button => button.callback_data?.startsWith('wedit:'))?.callback_data;
168 +
169 + github.calls.length = 0;
170 + workspaces.calls.length = 0;
171 + const route = plugin.resolveCallback(editCallback, { ownerId: '42' });
172 + assert.equal(route.actionId, 'github.workspace.create');
173 + assert.deepEqual(github.calls, []);
174 + assert.deepEqual(workspaces.calls, []);
175 + const draftView = await route.execute();
176 +
177 + const snapshotIndex = github.calls.findIndex(call => call[0] === 'getBranchSnapshot');
178 + const fileIndex = github.calls.findIndex(call => call[0] === 'getFileAtRef');
179 + const createCall = workspaces.calls.find(call => call[0] === 'createWorkspace');
180 + assert.ok(snapshotIndex >= 0 && fileIndex > snapshotIndex);
181 + assert.deepEqual(github.calls[fileIndex].slice(2), ['src/app.js', github.headSha]);
182 + assert.deepEqual(createCall, ['createWorkspace', '42', 'src/app.js', github.headSha]);
183 + assert.match(draftView.text, /Draft|پیش.?نویس/i);
184 + assert.ok(flatten(draftView).some(button => button.callback_data === 'ws:W000000001'));
185 +});
186 +
187 +test('archived repository cannot create an editable workspace', async () => {
188 + const github = makeGitHub({ archived: true, filePath: 'src/app.js' });
189 + const workspaces = makeWorkspaces();
190 + const plugin = createGitHubPlugin({ github, menu: makeMenu(), workspaces });
191 + const root = await plugin.resolveCallback('files:123', { ownerId: '42' }).execute();
192 + const fileCallback = flatten(root).find(button => button.callback_data?.startsWith('wnav:') && !button.text?.includes('deep'))?.callback_data;
193 + const fileView = await plugin.resolveCallback(fileCallback, { ownerId: '42' }).execute();
194 + const editCallback = flatten(fileView).find(button => button.callback_data?.startsWith('wedit:'))?.callback_data;
195 + assert.equal(editCallback, undefined);
196 + assert.match(fileView.text, /archiv|آرشیو/i);
197 + assert.equal(workspaces.calls.some(call => call[0] === 'createWorkspace'), false);
198 +});
199 +
200 +test('legacy tree blob and path-bearing files callbacks remain on MenuManager path', async () => {
201 + const github = makeGitHub();
202 + const workspaces = makeWorkspaces();
203 + const menu = makeMenu();
204 + const plugin = createGitHubPlugin({ github, menu, workspaces });
205 +
206 + for (const callback of [
207 + `tree:123:${'a'.repeat(40)}`,
208 + `blob:123:${'b'.repeat(40)}`,
209 + 'files:123:src/deep'
210 + ]) {
211 + const route = plugin.resolveCallback(callback, { ownerId: '42' });
212 + const view = await route.execute();
213 + assert.equal(view.text, `legacy:${callback}`);
214 + }
215 +});
216 +
217 +test('workspace READ actions are declared and all short callback families fit Telegram limit', () => {
218 + const plugin = createGitHubPlugin({ github: makeGitHub(), menu: makeMenu(), workspaces: makeWorkspaces() });
219 + for (const actionId of [
220 + 'github.workspace.navigate',
221 + 'github.workspace.create',
222 + 'github.workspace.view',
223 + 'github.workspace.input.prepare',
224 + 'github.workspace.diff',
225 + 'github.workspace.ready',
226 + 'github.workspace.cancel'
227 + ]) {
228 + assert.equal(plugin.manifest.actions[actionId]?.risk, 'READ', actionId);
229 + }
230 + for (const callback of [
231 + 'wnav:R123456789', 'wedit:R123456789', 'ws:W123456789', 'wtext:W123456789',
232 + 'wmsg:W123456789', 'wdiff:W123456789', 'wready:W123456789', 'wcancel:W123456789'
233 + ]) {
234 + assert.ok(new TextEncoder().encode(callback).byteLength <= 64, callback);
235 + }
236 +});
237 +
238 +test('GitHubService reads pinned branch snapshot and UTF-8 file at full SHA', async () => {
239 + const originalFetch = globalThis.fetch;
240 + const seen = [];
241 + const headSha = 'a'.repeat(40);
242 + const treeSha = 'b'.repeat(40);
243 + const blobSha = 'c'.repeat(40);
244 + globalThis.fetch = async (url, options = {}) => {
245 + seen.push([String(url), options.method || 'GET']);
246 + const value = String(url);
247 + if (value.endsWith('/repositories/123')) return Response.json({ id: 123, name: 'demo', full_name: 'davood/demo', default_branch: 'main' });
248 + if (value.endsWith('/repos/davood/demo/git/ref/heads/main')) return Response.json({ object: { sha: headSha } });
249 + if (value.endsWith(`/repos/davood/demo/git/commits/${headSha}`)) return Response.json({ sha: headSha, tree: { sha: treeSha } });
250 + if (value.endsWith(`/repos/davood/demo/contents/src/app.js?ref=${headSha}`)) {
251 + return Response.json({ type: 'file', path: 'src/app.js', sha: blobSha, size: 6, encoding: 'base64', content: btoa('hello\n') });
252 + }
253 + return new Response('unexpected', { status: 500 });
254 + };
255 + try {
256 + const github = new GitHubService('token', 'davood');
257 + assert.deepEqual(await github.getBranchSnapshot(123, 'main'), { branch: 'main', headSha, treeSha });
258 + assert.deepEqual(await github.getFileAtRef(123, 'src/app.js', headSha), {
259 + path: 'src/app.js', sha: blobSha, size: 6, encoding: 'utf-8', content: 'hello\n'
260 + });
261 + assert.ok(seen.some(([url]) => url.endsWith(`/contents/src/app.js?ref=${headSha}`)));
262 + } finally {
263 + globalThis.fetch = originalFetch;
264 + }
265 +});