Personal Telegram developer console for GitHub

feat/studio-g0-foundation
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 1,127 lines 33.6 KB
Raw
1 import assert from 'node:assert/strict';
2 import { after, before, test } from 'node:test';
3 import { build } from 'esbuild';
4 import { mkdir, rm } from 'node:fs/promises';
5 import { pathToFileURL } from 'node:url';
6 import { JSDOM } from 'jsdom';
7 import React, { act } from 'react';
8 import { EditorView } from '@codemirror/view';
9
10 let App;
11 const bundle = `.wrangler/studio-frontend-test-${process.pid}.mjs`;
12 const limits = {
13 maxChars: 20000,
14 maxBytes: 65536,
15 maxFiles: 8,
16 maxAggregateBytes: 131072
17 };
18 const repository = {
19 id: 17,
20 name: 'hello',
21 fullName: 'owner/hello',
22 defaultBranch: 'main',
23 private: false,
24 description: 'A real repository'
25 };
26 const source = '<img src=x onerror="window.pwned=true">\nconst answer = 1;';
27 function workspace(text = source, revision = 0) {
28 return {
29 id: 'Abcdef1234',
30 repoId: 17,
31 repoFullName: 'owner/hello',
32 baseBranch: 'main',
33 baseHeadSha: 'a'.repeat(40),
34 state: 'DRAFT',
35 path: 'index.js',
36 files: [{ path: 'index.js', draftText: text, revision }],
37 commitMessage: ''
38 };
39 }
40
41 before(async () => {
42 await mkdir('.wrangler', { recursive: true });
43 await build({
44 entryPoints: ['web/src/App.tsx'],
45 outfile: bundle,
46 bundle: true,
47 packages: 'external',
48 platform: 'node',
49 format: 'esm',
50 jsx: 'automatic',
51 logLevel: 'silent'
52 });
53 ({ App } = await import(pathToFileURL(`${process.cwd()}/${bundle}`)));
54 });
55 after(() => rm(bundle, { force: true }));
56
57 async function setup({
58 telegram = true,
59 respond,
60 stored = {},
61 storageUnavailable = false
62 } = {}) {
63 const dom = new JSDOM(
64 '<!doctype html><html><head><meta name="csp-nonce" content="test-nonce"></head><body><div id="root"></div></body></html>',
65 { url: 'https://studio.example/studio/', pretendToBeVisual: true }
66 );
67 for (const [key, value] of Object.entries(stored))
68 dom.window.localStorage.setItem(key, value);
69 if (storageUnavailable)
70 Object.defineProperty(dom.window, 'localStorage', {
71 get() {
72 throw new Error('Storage unavailable');
73 }
74 });
75 const previous = new Map();
76 for (const key of [
77 'window',
78 'document',
79 'navigator',
80 'HTMLElement',
81 'MutationObserver',
82 'Node',
83 'NodeFilter',
84 'DOMRect',
85 'getComputedStyle',
86 'requestAnimationFrame',
87 'cancelAnimationFrame'
88 ]) {
89 previous.set(key, Object.getOwnPropertyDescriptor(globalThis, key));
90 Object.defineProperty(globalThis, key, {
91 configurable: true,
92 writable: true,
93 value:
94 typeof dom.window[key] === 'function' &&
95 [
96 'getComputedStyle',
97 'requestAnimationFrame',
98 'cancelAnimationFrame'
99 ].includes(key)
100 ? dom.window[key].bind(dom.window)
101 : dom.window[key]
102 });
103 }
104 dom.window.Range.prototype.getClientRects = () => [];
105 dom.window.Range.prototype.getBoundingClientRect = () =>
106 new dom.window.DOMRect();
107 globalThis.IS_REACT_ACT_ENVIRONMENT = true;
108 const calls = [];
109 let closed = false;
110 if (telegram) {
111 dom.window.Telegram = {
112 WebApp: {
113 initData: 'opaque-signed-init-data',
114 ready() {},
115 expand() {},
116 enableClosingConfirmation() {},
117 disableClosingConfirmation() {},
118 close() {
119 closed = true;
120 }
121 }
122 };
123 }
124 const fetcher = async (url, init = {}) => {
125 const call = {
126 url: String(url),
127 method: init.method || 'GET',
128 headers: new Headers(init.headers),
129 body: init.body ? JSON.parse(init.body) : undefined
130 };
131 calls.push(call);
132 const custom = await respond?.(call, calls);
133 if (custom)
134 return Response.json(custom.body, { status: custom.status || 200 });
135 if (call.url === '/api/v1/studio') {
136 return Response.json({
137 ok: true,
138 user: { name: 'داوود' },
139 limits,
140 version: '1'
141 });
142 }
143 if (call.url === '/api/v1/studio/repos') {
144 return Response.json({ ok: true, repositories: [repository] });
145 }
146 if (call.url.startsWith('/api/v1/studio/tree?')) {
147 return Response.json({
148 ok: true,
149 repository,
150 path: '',
151 items: [
152 {
153 refId: 'FileRef123',
154 name: 'index.js',
155 path: 'index.js',
156 type: 'file',
157 size: source.length
158 }
159 ]
160 });
161 }
162 if (call.url === '/api/v1/studio/workspaces' && call.method === 'POST') {
163 return Response.json({ ok: true, workspace: workspace(), limits });
164 }
165 if (call.url.endsWith('/files') && call.method === 'PUT') {
166 return Response.json({
167 ok: true,
168 workspace: workspace(call.body.text, 1),
169 limits
170 });
171 }
172 if (call.url.endsWith('/diff')) {
173 return Response.json({
174 ok: true,
175 review: {
176 baseHeadSha: 'a'.repeat(40),
177 files: [{ path: 'index.js', revision: 1 }]
178 },
179 diff: {
180 text: '--- a/index.js\n+++ b/index.js\n-const answer = 1;\n+const answer = 2;',
181 additions: 1,
182 deletions: 1,
183 truncated: false
184 }
185 });
186 }
187 if (call.url.endsWith('/message')) {
188 return Response.json({
189 ok: true,
190 workspace: {
191 ...workspace('const answer = 2;', 1),
192 commitMessage: call.body.message
193 },
194 limits
195 });
196 }
197 if (call.url.endsWith('/approval')) {
198 return Response.json({
199 ok: true,
200 approvalRequested: true,
201 workspaceId: 'Abcdef1234',
202 targetBranch: 'nexa/edit-Abcdef1234',
203 baseHeadSha: 'a'.repeat(40),
204 expiresAt: Date.now() + 600000
205 });
206 }
207 if (call.url === '/api/v1/studio/workspaces/Abcdef1234') {
208 return Response.json({
209 ok: true,
210 workspace: workspace('const remote = true;', 4),
211 limits
212 });
213 }
214 throw new Error(`Unexpected API route: ${call.method} ${call.url}`);
215 };
216 const { createRoot } = await import('react-dom/client');
217 let root = createRoot(dom.window.document.getElementById('root'));
218 await act(async () => root.render(React.createElement(App, { fetcher })));
219 async function remount() {
220 await act(async () => root.unmount());
221 root = createRoot(dom.window.document.getElementById('root'));
222 await act(async () => root.render(React.createElement(App, { fetcher })));
223 }
224 const buttons = () => [...dom.window.document.querySelectorAll('button')];
225 async function click(label) {
226 const button = buttons().find((entry) => entry.textContent.includes(label));
227 assert.ok(button, `Button exists: ${label}`);
228 assert.equal(button.disabled, false, `Button enabled: ${label}`);
229 await act(async () => button.click());
230 }
231 async function edit(text) {
232 const view = EditorView.findFromDOM(
233 dom.window.document.querySelector('.cm-editor')
234 );
235 assert.ok(view, 'Real CodeMirror editor mounted');
236 await act(async () =>
237 view.dispatch({
238 changes: { from: 0, to: view.state.doc.length, insert: text }
239 })
240 );
241 }
242 async function input(label, value) {
243 const element = dom.window.document.querySelector(
244 `[aria-label="${label}"]`
245 );
246 assert.ok(element, `Input exists: ${label}`);
247 await act(async () => {
248 Object.getOwnPropertyDescriptor(
249 dom.window.HTMLInputElement.prototype,
250 'value'
251 ).set.call(element, value);
252 element.dispatchEvent(new dom.window.Event('input', { bubbles: true }));
253 element.dispatchEvent(new dom.window.Event('change', { bubbles: true }));
254 });
255 }
256 async function cleanup() {
257 await act(async () => root.unmount());
258 dom.window.close();
259 for (const [key, descriptor] of previous) {
260 if (descriptor) Object.defineProperty(globalThis, key, descriptor);
261 else delete globalThis[key];
262 }
263 delete globalThis.IS_REACT_ACT_ENVIRONMENT;
264 }
265 return {
266 dom,
267 calls,
268 click,
269 edit,
270 input,
271 remount,
272 cleanup,
273 get closed() {
274 return closed;
275 }
276 };
277 }
278
279 async function openEditor(ui) {
280 await ui.click('hello');
281 await ui.click('index.js');
282 }
283
284 test('refuses browser access outside Telegram without issuing authenticated requests', async () => {
285 const ui = await setup({ telegram: false });
286 try {
287 assert.match(ui.dom.window.document.body.textContent, /تلگرام/);
288 assert.equal(ui.calls.length, 0);
289 } finally {
290 await ui.cleanup();
291 }
292 });
293
294 test('real repository → literal CodeMirror edits → diff → Telegram approval, never invented success', async () => {
295 const ui = await setup();
296 try {
297 await openEditor(ui);
298 assert.equal(ui.dom.window.document.querySelector('img'), null);
299 assert.equal(ui.dom.window.pwned, undefined);
300 assert.match(
301 ui.dom.window.document.querySelector('.cm-editor').textContent,
302 /<img/
303 );
304 await ui.edit('const answer = 2;');
305 await ui.click('ذخیره تغییرات');
306 const save = ui.calls.find(
307 (entry) => entry.method === 'PUT' && entry.url.endsWith('/files')
308 );
309 assert.deepEqual(save.body, {
310 path: 'index.js',
311 text: 'const answer = 2;'
312 });
313 assert.equal(save.headers.get('if-match'), '0');
314 assert.ok(
315 ui.calls.every(
316 (entry) =>
317 entry.headers.get('x-telegram-init-data') ===
318 'opaque-signed-init-data'
319 )
320 );
321 assert.deepEqual(Object.entries(ui.dom.window.localStorage), [
322 ['nexa.studio.workspace', 'Abcdef1234']
323 ]);
324 assert.equal(ui.dom.window.location.search, '');
325 await ui.click('بازبینی تغییرات');
326 assert.match(
327 ui.dom.window.document.querySelector('.diff-view').textContent,
328 /const answer = 2/
329 );
330 assert.match(
331 ui.dom.window.document.body.textContent,
332 /nexa\/edit-Abcdef1234/
333 );
334 await ui.input('پیام Commit', 'Update answer');
335 await ui.click('درخواست تأیید امن');
336 assert.match(ui.dom.window.document.body.textContent, /تلگرام/);
337 assert.equal(
338 ui.calls.filter((entry) => entry.url.endsWith('/approval')).length,
339 1
340 );
341 assert.equal(
342 ui.calls.filter((entry) => entry.url.endsWith('/message'))[0].body
343 .message,
344 'Update answer'
345 );
346 assert.equal(ui.closed, false);
347 assert.doesNotMatch(
348 ui.dom.window.document.body.textContent,
349 /Commit با موفقیت ثبت شد/
350 );
351 assert.equal(ui.dom.window.document.querySelector('img'), null);
352 await ui.click('بستن و رفتن به تلگرام');
353 assert.equal(ui.closed, true);
354 } finally {
355 await ui.cleanup();
356 }
357 });
358
359 test('409 requires an explicit conflict choice and another Save before retrying with the latest revision', async () => {
360 let writes = 0;
361 const ui = await setup({
362 respond(call) {
363 if (
364 call.method === 'PUT' &&
365 call.url.endsWith('/files') &&
366 ++writes === 1
367 ) {
368 return {
369 status: 409,
370 body: { ok: false, error: 'نسخه تغییر کرده است.' }
371 };
372 }
373 }
374 });
375 try {
376 await openEditor(ui);
377 await ui.edit('my unsaved source');
378 await ui.click('ذخیره تغییرات');
379 assert.match(ui.dom.window.document.body.textContent, /بارگیری نسخه جدید/);
380 await ui.click('نگه‌داشتن نسخه من');
381 assert.equal(writes, 1);
382 assert.match(
383 ui.dom.window.document.querySelector('.cm-editor').textContent,
384 /my unsaved source/
385 );
386 await ui.click('ذخیره تغییرات');
387 assert.equal(writes, 2);
388 const last = ui.calls
389 .filter((entry) => entry.method === 'PUT' && entry.url.endsWith('/files'))
390 .at(-1);
391 assert.equal(last.headers.get('if-match'), '4');
392 assert.equal(last.body.text, 'my unsaved source');
393 } finally {
394 await ui.cleanup();
395 }
396 });
397
398 test('unsaved navigation needs an explicit discard and server UTF-8 limits disable saving', async () => {
399 const ui = await setup({
400 respond(call) {
401 if (call.url === '/api/v1/studio/workspaces' && call.method === 'POST') {
402 return {
403 body: {
404 ok: true,
405 workspace: workspace('a'),
406 limits: { ...limits, maxBytes: 5 }
407 }
408 };
409 }
410 }
411 });
412 try {
413 await openEditor(ui);
414 await ui.edit('سلام');
415 const save = [...ui.dom.window.document.querySelectorAll('button')].find(
416 (entry) => entry.textContent.includes('ذخیره تغییرات')
417 );
418 assert.equal(save.disabled, true);
419 assert.match(ui.dom.window.document.body.textContent, /سقف/);
420 await ui.click('بازگشت به فایل‌ها');
421 assert.ok(ui.dom.window.document.querySelector('[role="dialog"]'));
422 await ui.click('ادامه ویرایش');
423 assert.match(
424 ui.dom.window.document.querySelector('.cm-editor').textContent,
425 /سلام/
426 );
427 assert.equal(ui.calls.filter((entry) => entry.method === 'PUT').length, 0);
428 } finally {
429 await ui.cleanup();
430 }
431 });
432
433 test('adding a file keeps unsaved tabs and uses the pinned workspace tree', async () => {
434 const ui = await setup({
435 respond(call) {
436 if (call.url.includes('/tree?') && call.url.includes('workspaceId=')) {
437 return {
438 body: {
439 ok: true,
440 repository,
441 path: '',
442 items: [
443 {
444 refId: 'FileRef123',
445 name: 'index.js',
446 path: 'index.js',
447 type: 'file',
448 size: 3
449 },
450 {
451 refId: 'OtherRef12',
452 name: 'other.ts',
453 path: 'other.ts',
454 type: 'file',
455 size: 4
456 }
457 ]
458 }
459 };
460 }
461 if (call.url.endsWith('/files') && call.method === 'POST') {
462 return {
463 body: {
464 ok: true,
465 workspace: {
466 ...workspace(),
467 files: [
468 ...workspace().files,
469 {
470 path: 'other.ts',
471 draftText: 'export const next = 1;',
472 revision: 0
473 }
474 ]
475 },
476 limits
477 }
478 };
479 }
480 }
481 });
482 try {
483 await openEditor(ui);
484 await ui.edit('const localOnly = true;');
485 await ui.click('افزودن فایل');
486 const tree = ui.calls.find((entry) => entry.url.includes('workspaceId='));
487 assert.equal(
488 new URL(tree.url, 'https://studio.example').searchParams.get(
489 'workspaceId'
490 ),
491 'Abcdef1234'
492 );
493 await ui.click('other.ts');
494 assert.match(
495 ui.dom.window.document.querySelector('.cm-editor').textContent,
496 /export const next/
497 );
498 await ui.click('index.js');
499 assert.match(
500 ui.dom.window.document.querySelector('.cm-editor').textContent,
501 /const localOnly = true/
502 );
503 assert.equal(
504 ui.dom.window.document.querySelectorAll('[role="tab"]').length,
505 2
506 );
507 assert.equal(ui.calls.filter((entry) => entry.method === 'PUT').length, 0);
508 assert.deepEqual(
509 ui.calls.find(
510 (entry) => entry.method === 'POST' && entry.url.endsWith('/files')
511 ).body,
512 { refId: 'OtherRef12' }
513 );
514 } finally {
515 await ui.cleanup();
516 }
517 });
518
519 test('initial provider failure offers a real retry and empty repositories can reload', async () => {
520 let reads = 0;
521 const ui = await setup({
522 respond(call) {
523 if (call.url === '/api/v1/studio/repos') {
524 reads += 1;
525 if (reads === 1)
526 return {
527 status: 503,
528 body: {
529 ok: false,
530 error: 'دریافت مخازن انجام نشد. دوباره تلاش کن.'
531 }
532 };
533 if (reads === 2) return { body: { ok: true, repositories: [] } };
534 }
535 }
536 });
537 try {
538 assert.match(
539 ui.dom.window.document.querySelector('[role="alert"]').textContent,
540 /دریافت مخازن/
541 );
542 await ui.click('تلاش دوباره');
543 assert.match(
544 ui.dom.window.document.body.textContent,
545 /مخزنی برای نمایش نیست/
546 );
547 await ui.click('دریافت دوباره مخازن');
548 await ui.click('hello');
549 assert.equal(reads, 3);
550 assert.match(ui.dom.window.document.body.textContent, /index.js/);
551 } finally {
552 await ui.cleanup();
553 }
554 });
555
556 test('loading the latest conflict version discards only by explicit choice without a write', async () => {
557 const ui = await setup({
558 respond(call) {
559 if (call.method === 'PUT' && call.url.endsWith('/files'))
560 return {
561 status: 409,
562 body: { ok: false, error: 'نسخه تغییر کرده است.' }
563 };
564 }
565 });
566 try {
567 await openEditor(ui);
568 await ui.edit('local change');
569 await ui.click('ذخیره تغییرات');
570 await ui.click('بارگیری نسخه جدید');
571 assert.match(
572 ui.dom.window.document.querySelector('.cm-editor').textContent,
573 /const remote = true/
574 );
575 assert.equal(ui.calls.filter((entry) => entry.method === 'PUT').length, 1);
576 const save = [...ui.dom.window.document.querySelectorAll('button')].find(
577 (entry) => entry.textContent.includes('ذخیره تغییرات')
578 );
579 assert.equal(save.disabled, true);
580 } finally {
581 await ui.cleanup();
582 }
583 });
584
585 test('a committed result appears only after an actual workspace refresh confirms it', async () => {
586 const ui = await setup({
587 respond(call) {
588 if (
589 call.url === '/api/v1/studio/workspaces/Abcdef1234' &&
590 call.method === 'GET'
591 ) {
592 return {
593 body: {
594 ok: true,
595 workspace: {
596 ...workspace('const answer = 2;', 1),
597 state: 'COMMITTED',
598 result: {
599 commitSha: 'b'.repeat(40),
600 branch: 'nexa/edit-Abcdef1234'
601 }
602 },
603 limits
604 }
605 };
606 }
607 }
608 });
609 try {
610 await openEditor(ui);
611 await ui.edit('const answer = 2;');
612 await ui.click('ذخیره تغییرات');
613 await ui.click('بازبینی تغییرات');
614 await ui.input('پیام Commit', 'Update answer');
615 await ui.click('درخواست تأیید امن');
616 assert.equal(ui.dom.window.document.querySelector('.result-link'), null);
617 await ui.click('بررسی نتیجه');
618 const result = ui.dom.window.document.querySelector('.result-link');
619 assert.equal(
620 result.href,
621 `https://github.com/owner/hello/commit/${'b'.repeat(40)}`
622 );
623 assert.match(ui.dom.window.document.body.textContent, /Commit ثبت شد/);
624 } finally {
625 await ui.cleanup();
626 }
627 });
628
629 test('Escape dismisses the unsaved navigation dialog and keeps the local draft', async () => {
630 const ui = await setup();
631 try {
632 await openEditor(ui);
633 await ui.edit('keep this draft');
634 await ui.click('بازگشت به فایل‌ها');
635 await act(async () =>
636 ui.dom.window.document.dispatchEvent(
637 new ui.dom.window.KeyboardEvent('keydown', {
638 key: 'Escape',
639 bubbles: true
640 })
641 )
642 );
643 assert.equal(
644 !!ui.dom.window.document.querySelector('[role="dialog"]'),
645 false
646 );
647 assert.match(
648 ui.dom.window.document.querySelector('.cm-editor').textContent,
649 /keep this draft/
650 );
651 } finally {
652 await ui.cleanup();
653 }
654 });
655
656 test('approval binds the displayed diff even when message response contains a newer unseen file', async () => {
657 const ui = await setup({
658 respond(call) {
659 if (call.url.endsWith('/message')) {
660 return {
661 body: {
662 ok: true,
663 workspace: {
664 ...workspace('UNREVIEWED REMOTE CHANGE', 4),
665 commitMessage: call.body.message
666 },
667 limits
668 }
669 };
670 }
671 if (call.url.endsWith('/approval')) {
672 return {
673 status: 409,
674 body: {
675 ok: false,
676 error: 'نسخه فایل تغییر کرده است. آخرین نسخه را باز کنید.'
677 }
678 };
679 }
680 }
681 });
682 try {
683 await openEditor(ui);
684 await ui.edit('const answer = 2;');
685 await ui.click('ذخیره تغییرات');
686 await ui.click('بازبینی تغییرات');
687 await ui.input('پیام Commit', 'Update answer');
688 await ui.click('درخواست تأیید امن');
689 const requested = ui.calls.find((entry) => entry.url.endsWith('/approval'));
690 assert.deepEqual(requested.body, {
691 message: 'Update answer',
692 review: {
693 baseHeadSha: 'a'.repeat(40),
694 files: [{ path: 'index.js', revision: 1 }]
695 }
696 });
697 assert.doesNotMatch(
698 ui.dom.window.document.body.textContent,
699 /درخواست تأیید به تلگرام فرستاده شد/
700 );
701 const approvalButton = [
702 ...ui.dom.window.document.querySelectorAll('button')
703 ].find((entry) => entry.textContent.includes('درخواست تأیید امن'));
704 assert.equal(approvalButton.disabled, true);
705 assert.match(
706 ui.dom.window.document.body.textContent,
707 /بارگیری و بازبینی تازه/
708 );
709 await ui.click('بارگیری و بازبینی تازه');
710 assert.equal(
711 ui.calls.filter((entry) => entry.url.endsWith('/approval')).length,
712 1
713 );
714 assert.equal(
715 ui.calls.filter((entry) => entry.url.endsWith('/diff')).length,
716 2
717 );
718 assert.ok(
719 ui.calls.some(
720 (entry) =>
721 entry.url === '/api/v1/studio/workspaces/Abcdef1234' &&
722 entry.method === 'GET'
723 )
724 );
725 } finally {
726 await ui.cleanup();
727 }
728 });
729
730 function twoFiles(
731 a = 'original A',
732 aRevision = 0,
733 b = 'original B',
734 bRevision = 0
735 ) {
736 return {
737 ...workspace(a, aRevision),
738 files: [
739 { path: 'index.js', draftText: a, revision: aRevision },
740 { path: 'other.ts', draftText: b, revision: bRevision }
741 ]
742 };
743 }
744
745 for (const operation of ['save', 'add', 'resolve']) {
746 test(`${operation} keeps the unseen file baseline and requires its original revision on the next save`, async () => {
747 let writes = 0;
748 const ui = await setup({
749 respond(call) {
750 if (call.url === '/api/v1/studio/workspaces' && call.method === 'POST')
751 return { body: { ok: true, workspace: twoFiles(), limits } };
752 if (call.url.includes('/tree?') && call.url.includes('workspaceId='))
753 return {
754 body: {
755 ok: true,
756 path: '',
757 items: [
758 {
759 refId: 'ThirdRef12',
760 name: 'third.js',
761 path: 'third.js',
762 type: 'file',
763 size: 1
764 }
765 ]
766 }
767 };
768 if (call.url.endsWith('/files') && call.method === 'POST')
769 return {
770 body: {
771 ok: true,
772 workspace: {
773 ...twoFiles('original A', 0, 'unseen remote B', 7),
774 files: [
775 ...twoFiles('original A', 0, 'unseen remote B', 7).files,
776 { path: 'third.js', draftText: 'third', revision: 0 }
777 ]
778 },
779 limits
780 }
781 };
782 if (call.url.endsWith('/files') && call.method === 'PUT') {
783 writes += 1;
784 if (operation === 'resolve' && writes === 1)
785 return {
786 status: 409,
787 body: { ok: false, error: 'نسخه تغییر کرده است.' }
788 };
789 if (call.body.path === 'other.ts')
790 return {
791 status: 409,
792 body: { ok: false, error: 'نسخه تغییر کرده است.' }
793 };
794 return {
795 body: {
796 ok: true,
797 workspace: twoFiles(call.body.text, 1, 'unseen remote B', 7),
798 limits
799 }
800 };
801 }
802 if (call.url === '/api/v1/studio/workspaces/Abcdef1234')
803 return {
804 body: {
805 ok: true,
806 workspace: twoFiles('remote A', 3, 'unseen remote B', 7),
807 limits
808 }
809 };
810 }
811 });
812 try {
813 await openEditor(ui);
814 if (operation === 'add') {
815 await ui.click('افزودن فایل');
816 await ui.click('third.js');
817 } else {
818 await ui.edit('local A');
819 await ui.click('ذخیره تغییرات');
820 if (operation === 'resolve') await ui.click('نگه‌داشتن نسخه من');
821 }
822 await ui.click('other.ts');
823 assert.match(
824 ui.dom.window.document.querySelector('.cm-editor').textContent,
825 /original B/
826 );
827 await ui.edit('my B change');
828 await ui.click('ذخیره تغییرات');
829 const saveB = ui.calls.find(
830 (call) => call.method === 'PUT' && call.body.path === 'other.ts'
831 );
832 assert.equal(
833 saveB.headers.get('if-match'),
834 '0',
835 'Never silently adopt an unseen remote revision'
836 );
837 assert.match(
838 ui.dom.window.document.body.textContent,
839 /بارگیری نسخه جدید/
840 );
841 } finally {
842 await ui.cleanup();
843 }
844 });
845 }
846
847 test('approval compares the exact displayed message when another session changes only the message', async () => {
848 const ui = await setup({
849 respond(call) {
850 if (call.url.endsWith('/message'))
851 return {
852 body: {
853 ok: true,
854 workspace: {
855 ...workspace('const answer = 2;', 1),
856 commitMessage: 'unseen remote message'
857 },
858 limits
859 }
860 };
861 if (call.url.endsWith('/approval'))
862 return {
863 status: 409,
864 body: {
865 ok: false,
866 error: 'پیام تغییر کرده است. دوباره بازبینی کنید.'
867 }
868 };
869 }
870 });
871 try {
872 await openEditor(ui);
873 await ui.edit('const answer = 2;');
874 await ui.click('ذخیره تغییرات');
875 await ui.click('بازبینی تغییرات');
876 await ui.input('پیام Commit', ' My reviewed message ');
877 await ui.click('درخواست تأیید امن');
878 const request = ui.calls.find((call) => call.url.endsWith('/approval'));
879 assert.equal(request.body.message, 'My reviewed message');
880 assert.deepEqual(request.body.review.files, [
881 { path: 'index.js', revision: 1 }
882 ]);
883 assert.equal(
884 ui.dom.window.document.querySelector('[aria-label="پیام Commit"]').value,
885 ' My reviewed message '
886 );
887 assert.doesNotMatch(
888 ui.dom.window.document.body.textContent,
889 /درخواست تأیید به تلگرام فرستاده شد/
890 );
891 assert.match(
892 ui.dom.window.document.body.textContent,
893 /بارگیری و بازبینی تازه/
894 );
895 } finally {
896 await ui.cleanup();
897 }
898 });
899
900 test('remount restores only the opaque handle and continues with fresh server draft content', async () => {
901 const ui = await setup();
902 try {
903 await openEditor(ui);
904 await ui.edit('unsaved source must disappear');
905 assert.deepEqual(Object.entries(ui.dom.window.localStorage), [
906 ['nexa.studio.workspace', 'Abcdef1234']
907 ]);
908 await ui.remount();
909 assert.equal(ui.dom.window.document.querySelector('.cm-editor'), null);
910 assert.ok(
911 ui.calls.some(
912 (call) =>
913 call.url.endsWith('/workspaces/Abcdef1234') && call.method === 'GET'
914 )
915 );
916 await ui.click('ادامه فضای کاری');
917 assert.match(
918 ui.dom.window.document.querySelector('.cm-editor').textContent,
919 /const remote = true/
920 );
921 assert.doesNotMatch(
922 ui.dom.window.document.body.textContent,
923 /unsaved source must disappear/
924 );
925 } finally {
926 await ui.cleanup();
927 }
928 });
929
930 for (const state of ['READY', 'COMMITTED']) {
931 test(`remounted ${state} workspace uses fresh evidence before review or a committed result`, async () => {
932 let resumed = false;
933 const ui = await setup({
934 respond(call) {
935 if (resumed && call.url === '/api/v1/studio/workspaces/Abcdef1234')
936 return {
937 body: {
938 ok: true,
939 workspace: {
940 ...workspace('const answer = 2;', 1),
941 state,
942 commitMessage: 'Saved message',
943 ...(state === 'COMMITTED'
944 ? {
945 result: {
946 commitSha: 'b'.repeat(40),
947 branch: 'nexa/edit-Abcdef1234'
948 }
949 }
950 : {})
951 },
952 limits
953 }
954 };
955 }
956 });
957 try {
958 await openEditor(ui);
959 await ui.edit('const answer = 2;');
960 await ui.click('ذخیره تغییرات');
961 await ui.click('بازبینی تغییرات');
962 await ui.input('پیام Commit', 'Saved message');
963 await ui.click('درخواست تأیید امن');
964 await ui.click('بستن و رفتن به تلگرام');
965 resumed = true;
966 await ui.remount();
967 assert.equal(ui.dom.window.document.querySelector('.result-link'), null);
968 assert.doesNotMatch(
969 ui.dom.window.document.body.textContent,
970 /درخواست تأیید به تلگرام فرستاده شد/
971 );
972 const approvals = ui.calls.filter((call) =>
973 call.url.endsWith('/approval')
974 ).length;
975 const diffs = ui.calls.filter((call) =>
976 call.url.endsWith('/diff')
977 ).length;
978 await ui.click('ادامه فضای کاری');
979 assert.equal(
980 ui.calls.filter((call) => call.url.endsWith('/approval')).length,
981 approvals
982 );
983 if (state === 'COMMITTED') {
984 assert.equal(
985 ui.dom.window.document.querySelector('.result-link').href,
986 `https://github.com/owner/hello/commit/${'b'.repeat(40)}`
987 );
988 } else {
989 assert.equal(
990 ui.calls.filter((call) => call.url.endsWith('/diff')).length,
991 diffs + 1
992 );
993 assert.equal(
994 ui.dom.window.document.querySelector('[aria-label="پیام Commit"]')
995 .value,
996 'Saved message'
997 );
998 assert.doesNotMatch(
999 ui.dom.window.document.body.textContent,
1000 /درخواست تأیید به تلگرام فرستاده شد/
1001 );
1002 await ui.click('بازگشت به ویرایشگر');
1003 await ui.click('بازبینی تغییرات');
1004 await ui.click('درخواست تأیید امن');
1005 assert.equal(
1006 ui.calls.filter((call) => call.url.endsWith('/approval')).length,
1007 approvals + 1
1008 );
1009 }
1010 } finally {
1011 await ui.cleanup();
1012 }
1013 });
1014 }
1015
1016 for (const mode of ['invalid', 'expired', 'forbidden', 'nonowner', 'outside']) {
1017 test(`stored workspace recovery handles ${mode} without retaining an invalid session`, async () => {
1018 const ui = await setup({
1019 telegram: mode !== 'outside',
1020 stored: {
1021 'nexa.studio.workspace':
1022 mode === 'invalid' ? 'not/a/handle' : 'Abcdef1234'
1023 },
1024 respond(call) {
1025 if (mode === 'nonowner' && call.url === '/api/v1/studio')
1026 return {
1027 status: 403,
1028 body: { ok: false, error: 'دسترسی مجاز نیست.' }
1029 };
1030 if (
1031 ['expired', 'forbidden'].includes(mode) &&
1032 call.url.endsWith('/workspaces/Abcdef1234')
1033 )
1034 return {
1035 status: mode === 'expired' ? 404 : 403,
1036 body: { ok: false, error: 'فضای کار منقضی شده است.' }
1037 };
1038 }
1039 });
1040 try {
1041 if (mode === 'outside') assert.equal(ui.calls.length, 0);
1042 else
1043 assert.equal(
1044 ui.dom.window.localStorage.getItem('nexa.studio.workspace'),
1045 null
1046 );
1047 if (mode === 'nonowner' || mode === 'invalid')
1048 assert.equal(
1049 ui.calls.some((call) => call.url.includes('/workspaces/')),
1050 false
1051 );
1052 assert.doesNotMatch(
1053 ui.dom.window.document.body.textContent,
1054 /ادامه فضای کاری/
1055 );
1056 } finally {
1057 await ui.cleanup();
1058 }
1059 });
1060 }
1061
1062 test('cancel clears the saved handle and unavailable local storage never breaks editing', async () => {
1063 for (const storageUnavailable of [false, true]) {
1064 const ui = await setup({
1065 storageUnavailable,
1066 respond(call) {
1067 if (call.method === 'DELETE')
1068 return { body: { ok: true, cancelled: true } };
1069 }
1070 });
1071 try {
1072 await openEditor(ui);
1073 await ui.edit('a real edit');
1074 await ui.click('ذخیره تغییرات');
1075 await ui.click('لغو فضای کاری');
1076 await ui.click('کنار گذاشتن و ادامه');
1077 assert.equal(
1078 ui.calls.filter((call) => call.method === 'DELETE').length,
1079 1
1080 );
1081 assert.doesNotMatch(
1082 ui.dom.window.document.body.textContent,
1083 /ادامه فضای کاری/
1084 );
1085 if (!storageUnavailable)
1086 assert.equal(
1087 ui.dom.window.localStorage.getItem('nexa.studio.workspace'),
1088 null
1089 );
1090 } finally {
1091 await ui.cleanup();
1092 }
1093 }
1094 });
1095
1096 test('a temporary recovery failure keeps the handle and retries against the server', async () => {
1097 let reads = 0;
1098 const ui = await setup({
1099 stored: { 'nexa.studio.workspace': 'Abcdef1234' },
1100 respond(call) {
1101 if (call.url.endsWith('/workspaces/Abcdef1234') && ++reads === 1)
1102 return {
1103 status: 503,
1104 body: { ok: false, error: 'سرویس موقتاً در دسترس نیست.' }
1105 };
1106 }
1107 });
1108 try {
1109 assert.equal(
1110 ui.dom.window.localStorage.getItem('nexa.studio.workspace'),
1111 'Abcdef1234'
1112 );
1113 assert.match(
1114 ui.dom.window.document.querySelector('[role="alert"]').textContent,
1115 /موقتاً/
1116 );
1117 await ui.click('تلاش دوباره');
1118 await ui.click('ادامه فضای کاری');
1119 assert.equal(reads, 3);
1120 assert.match(
1121 ui.dom.window.document.querySelector('.cm-editor').textContent,
1122 /const remote = true/
1123 );
1124 } finally {
1125 await ui.cleanup();
1126 }
1127 });