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 905 lines 32 KB
Raw
1 import {
2 WORKSPACE_EDITOR_LIMITS,
3 buildUnifiedDiff,
4 digestText,
5 makeTargetBranch,
6 normalizeCommitMessage,
7 validateEditableFile
8 } from '../../core/workspace-policy.js';
9 import { DEFAULT_CONFIG } from '../../config.js';
10 import { commitWorkspaceIntent } from './workspace-commit.js';
11
12 export { commitWorkspaceIntent } from './workspace-commit.js';
13
14 const HANDLE_10 = '[A-Za-z0-9_-]{10}';
15 const INTENT_8 = '[A-Za-z0-9_-]{8}';
16 const escapeHtml = (value) =>
17 String(value ?? '')
18 .replaceAll('&', '&')
19 .replaceAll('<', '&lt;')
20 .replaceAll('>', '&gt;')
21 .replaceAll('"', '&quot;');
22 const short = (value, max = 70) => {
23 const text = String(value ?? '');
24 return text.length > max ? `${text.slice(0, max - 1)}…` : text;
25 };
26
27 const ownerFrom = (context) => {
28 const ownerId = String(context?.ownerId ?? '');
29 if (!ownerId) throw new Error('Workspace owner is required');
30 return ownerId;
31 };
32
33 function parseCallback(data) {
34 const value = String(data || '');
35 let match = value.match(/^(?:files):(\d+)$/);
36 if (match)
37 return {
38 actionId: 'github.files.list',
39 kind: 'root',
40 repoId: Number(match[1])
41 };
42 match = value.match(new RegExp(`^wnav:(${HANDLE_10})$`));
43 if (match)
44 return {
45 actionId: 'github.workspace.navigate',
46 kind: 'navigate',
47 refId: match[1]
48 };
49 match = value.match(new RegExp(`^wedit:(${HANDLE_10})$`));
50 if (match)
51 return {
52 actionId: 'github.workspace.create',
53 kind: 'edit',
54 refId: match[1]
55 };
56 match = value.match(new RegExp(`^ws:(${HANDLE_10})$`));
57 if (match)
58 return {
59 actionId: 'github.workspace.view',
60 kind: 'workspace',
61 workspaceId: match[1]
62 };
63 match = value.match(new RegExp(`^wadd:(${HANDLE_10})$`));
64 if (match)
65 return {
66 actionId: 'github.workspace.file.add',
67 kind: 'add_file',
68 refId: match[1]
69 };
70 match = value.match(new RegExp(`^wremove:(${HANDLE_10})$`));
71 if (match)
72 return {
73 actionId: 'github.workspace.file.remove',
74 kind: 'remove_file',
75 refId: match[1]
76 };
77 match = value.match(new RegExp(`^wfiles:(${HANDLE_10}):(\\d+)$`));
78 if (match)
79 return {
80 actionId: 'github.workspace.file.pick',
81 kind: 'pick_file',
82 workspaceId: match[1],
83 repoId: Number(match[2])
84 };
85 match = value.match(new RegExp(`^wfile:(${HANDLE_10})$`));
86 if (match)
87 return {
88 actionId: 'github.workspace.input.prepare',
89 kind: 'input',
90 workspaceId: match[1],
91 mode: 'draft_file'
92 };
93 match = value.match(new RegExp(`^wtext:(${HANDLE_10})$`));
94 if (match)
95 return {
96 actionId: 'github.workspace.input.prepare',
97 kind: 'input',
98 workspaceId: match[1],
99 mode: 'draft'
100 };
101 match = value.match(new RegExp(`^wmsg:(${HANDLE_10})$`));
102 if (match)
103 return {
104 actionId: 'github.workspace.input.prepare',
105 kind: 'input',
106 workspaceId: match[1],
107 mode: 'commit_message'
108 };
109 match = value.match(new RegExp(`^wdiff:(${HANDLE_10})$`));
110 if (match)
111 return {
112 actionId: 'github.workspace.diff',
113 kind: 'diff',
114 workspaceId: match[1]
115 };
116 match = value.match(new RegExp(`^wready:(${HANDLE_10})$`));
117 if (match)
118 return {
119 actionId: 'github.workspace.ready',
120 kind: 'ready',
121 workspaceId: match[1]
122 };
123 match = value.match(new RegExp(`^wcancel:(${HANDLE_10})$`));
124 if (match)
125 return {
126 actionId: 'github.workspace.cancel',
127 kind: 'cancel',
128 workspaceId: match[1]
129 };
130 match = value.match(new RegExp(`^wscommit:(\\d+):(${INTENT_8})$`));
131 if (match)
132 return {
133 actionId: 'github.workspace.commit_branch',
134 kind: 'commit',
135 repoId: Number(match[1]),
136 intentId: match[2]
137 };
138 return null;
139 }
140
141 function editorUrlFor(workspace, editorUrl, path = '') {
142 const configured = String(editorUrl || '').trim();
143 if (!configured) return '';
144 try {
145 const url = new URL(configured);
146 if (url.protocol !== 'https:') return '';
147 url.searchParams.set('workspaceId', workspace.id);
148 if (path) url.searchParams.set('path', path);
149 return url.toString();
150 } catch {
151 return '';
152 }
153 }
154
155 function workspaceButtons(workspace, editorUrl) {
156 const editor = editorUrlFor(workspace, editorUrl);
157 return [
158 ...(editor ? [[{ text: '🧑‍💻 Editor', web_app: { url: editor } }]] : []),
159 [{ text: '✍️ پیام Commit', callback_data: `wmsg:${workspace.id}` }],
160 [
161 { text: '🔍 Diff', callback_data: `wdiff:${workspace.id}` },
162 { text: '✅ آماده Commit', callback_data: `wready:${workspace.id}` }
163 ],
164 [
165 { text: '🗑 لغو Draft', callback_data: `wcancel:${workspace.id}` },
166 { text: '🔙 فایل‌ها', callback_data: `files:${workspace.repoId}` }
167 ]
168 ];
169 }
170
171 function draftInputNotice(workspace, editorUrl) {
172 return editorUrlFor(workspace, editorUrl)
173 ? 'متن منبع و فایل را در چت ارسال نکنید؛ ویرایش Draft فقط در Mini App احراز هویت‌شده انجام می‌شود.'
174 : 'Editor در دسترس نیست؛ پیکربندی Mini App باید اصلاح شود. متن منبع و فایل را در چت ارسال نکنید.';
175 }
176
177 function workspaceCommitResultView(repoId, intent, result) {
178 const rows = [[{ text: '🧪 CI / Actions', callback_data: `runs:${repoId}` }]];
179 if (intent?.workspaceId) {
180 rows.push([
181 { text: '📝 Workspace', callback_data: `ws:${intent.workspaceId}` }
182 ]);
183 }
184 rows.push([{ text: '📦 پروژه', callback_data: `repo:${repoId}` }]);
185 return {
186 text: `✅ <b>Commit روی branch جدید ایجاد شد</b>\nBranch: <code>${escapeHtml(result.branch)}</code>\nSHA: <code>${escapeHtml(result.commitSha)}</code>${result.idempotent ? '\nوضعیت: <b>reconciled / idempotent</b>' : ''}\n\nشاخهٔ پیش‌فرض تغییر نکرده است.`,
187 reply_markup: { inline_keyboard: rows }
188 };
189 }
190
191 export function createWorkspaceController({
192 github,
193 workspaces,
194 editorUrl = DEFAULT_CONFIG.workspaceEditorUrl
195 } = {}) {
196 if (!github) throw new Error('Workspace controller requires GitHub service');
197 if (!workspaces)
198 throw new Error('Workspace controller requires durable workspace store');
199
200 const requireWorkspace = async (workspaceId, ownerId) => {
201 const workspace = await workspaces.getWorkspace({ ownerId, workspaceId });
202 if (!workspace) throw new Error('Workspace not found or expired');
203 return workspace;
204 };
205
206 const renderDirectory = async (repoId, path, ownerId) => {
207 const [repo, items] = await Promise.all([
208 github.getRepository(repoId),
209 github.listFiles(repoId, path)
210 ]);
211 const visible = items.slice(0, 30);
212 const handles = await workspaces.createNavigationRefs({
213 ownerId,
214 refs: visible.map((item) => ({
215 repoId,
216 path: item.path,
217 type: item.type,
218 sha: item.sha
219 }))
220 });
221 const body = visible.length
222 ? visible
223 .map(
224 (item) =>
225 `${item.type === 'dir' ? '📁' : '📄'} <code>${escapeHtml(short(item.name, 100))}</code>${item.type === 'file' && item.size ? ` (${Number(item.size).toLocaleString()} B)` : ''}`
226 )
227 .join('\n')
228 : '<i>این پوشه خالی است.</i>';
229 const rows = visible.map((item, index) => [
230 {
231 text: `${item.type === 'dir' ? '📁' : '📄'} ${short(item.name, 46)}`,
232 callback_data: `wnav:${handles[index].refId}`
233 }
234 ]);
235 rows.push([
236 { text: '🔄 بروزرسانی', callback_data: `files:${repoId}` },
237 { text: '📦 پروژه', callback_data: `repo:${repoId}` }
238 ]);
239 return {
240 text: `📂 <b>فایل‌های ${escapeHtml(repo.name)}</b>\n${path ? `مسیر: <code>${escapeHtml(path)}</code>\n` : ''}➖➖➖➖➖➖➖➖➖➖\n${body}`,
241 reply_markup: { inline_keyboard: rows }
242 };
243 };
244
245 const getPinnedFile = async (ref) => {
246 const repo = await github.getRepository(ref.repoId);
247 const snapshot = await github.getBranchSnapshot(
248 ref.repoId,
249 repo.defaultBranch
250 );
251 const file = await github.getFileAtRef(
252 ref.repoId,
253 ref.path,
254 snapshot.headSha
255 );
256 return { repo, snapshot, file };
257 };
258
259 const renderFile = async (refId, ownerId) => {
260 const ref = await workspaces.resolveNavigationRef({ ownerId, refId });
261 if (!ref || ref.type !== 'file')
262 throw new Error('Workspace file reference is missing or expired');
263 const { repo, snapshot, file } = await getPinnedFile(ref);
264 const policy = validateEditableFile({
265 path: file.path,
266 text: file.content,
267 byteLength: file.size
268 });
269 const reason = repo.archived
270 ? 'این مخزن آرشیوشده است و ویرایش فایل در آن غیرفعال است.'
271 : policy.reason;
272 const rows = [];
273 const previewLink = editorUrlFor({ id: refId }, editorUrl);
274 if (previewLink && policy.editable) {
275 const url = new URL(previewLink);
276 url.searchParams.delete('workspaceId');
277 url.searchParams.set('refId', refId);
278 rows.push([
279 { text: '📄 مشاهده در Mini App', web_app: { url: url.toString() } }
280 ]);
281 }
282 if (!repo.archived && policy.editable)
283 rows.push([{ text: '✏️ Edit', callback_data: `wedit:${refId}` }]);
284 rows.push([
285 { text: '🔙 فایل‌ها', callback_data: `files:${ref.repoId}` },
286 { text: '📦 پروژه', callback_data: `repo:${ref.repoId}` }
287 ]);
288 return {
289 text: `📄 <b>فایل — ${escapeHtml(repo.name)}</b>\nمسیر: <code>${escapeHtml(file.path)}</code>\nRef: <code>${escapeHtml(snapshot.headSha.slice(0, 10))}</code>\n${reason ? `⚠️ ${escapeHtml(reason)}\n` : ''}محتوای فایل در پیام تلگرام ارسال نمی‌شود؛ برای مشاهده، Mini App را باز کنید.`,
290 reply_markup: { inline_keyboard: rows }
291 };
292 };
293
294 const createWorkspaceFromRef = async (refId, ownerId) => {
295 const ref = await workspaces.resolveNavigationRef({ ownerId, refId });
296 if (!ref || ref.type !== 'file')
297 throw new Error('Workspace file reference is missing or expired');
298 const { repo, snapshot, file } = await getPinnedFile(ref);
299 if (repo.archived) throw new Error('Archived repository is not editable');
300 const policy = validateEditableFile({
301 path: file.path,
302 text: file.content,
303 byteLength: file.size
304 });
305 if (!policy.editable)
306 throw new Error(policy.reason || 'File is not editable');
307 const originalDigest = await digestText(file.content);
308 return workspaces.createWorkspace({
309 ownerId,
310 repoId: Number(ref.repoId),
311 repoFullName: repo.fullName,
312 baseBranch: repo.defaultBranch,
313 baseHeadSha: snapshot.headSha,
314 baseTreeSha: snapshot.treeSha,
315 path: file.path,
316 blobSha: file.sha,
317 originalText: file.content,
318 originalDigest
319 });
320 };
321
322 const createDraft = async (refId, ownerId) => {
323 const workspace = await createWorkspaceFromRef(refId, ownerId);
324 return {
325 text: `📝 <b>Draft ساخته شد</b>\nمخزن: <code>${escapeHtml(workspace.repoFullName)}</code>\nفایل: <code>${escapeHtml(workspace.path)}</code>\nBase: <code>${escapeHtml(workspace.baseHeadSha.slice(0, 10))}</code>\n\nهنوز هیچ تغییری در GitHub انجام نشده است.`,
326 reply_markup: {
327 inline_keyboard: [
328 [{ text: '📝 باز کردن Draft', callback_data: `ws:${workspace.id}` }],
329 [{ text: '🔙 فایل‌ها', callback_data: `files:${workspace.repoId}` }]
330 ]
331 }
332 };
333 };
334
335 const renderWorkspaceObject = async (workspace, ownerId) => {
336 const files =
337 Array.isArray(workspace.files) && workspace.files.length
338 ? workspace.files
339 : [
340 {
341 path: workspace.path,
342 originalText: workspace.originalText,
343 draftText: workspace.draftText
344 }
345 ];
346 const changedCount = files.filter(
347 (file) => file.draftText !== file.originalText
348 ).length;
349 const refs =
350 (await workspaces.createNavigationRefs?.({
351 ownerId,
352 refs: files.map((file) => ({
353 workspaceId: workspace.id,
354 path: file.path,
355 type: 'workspace-file',
356 repoId: workspace.repoId
357 }))
358 })) || [];
359 const commitMessage = workspace.commitMessage
360 ? `<code>${escapeHtml(short(workspace.commitMessage, 120))}</code>`
361 : '<i>ثبت نشده</i>';
362 const list = files
363 .map(
364 (file, i) =>
365 `${file.draftText !== file.originalText ? '●' : '○'} <code>${escapeHtml(file.path)}</code>${refs[i]?.refId && files.length > 1 ? ` — <i>قابل حذف</i>` : ''}`
366 )
367 .join('\n');
368 const buttons = workspaceButtons(workspace, editorUrl);
369 if (editorUrlFor(workspace, editorUrl) && files.length > 1) {
370 const fileEditors = files.map((file) => [
371 {
372 text: 'Edit ' + short(file.path, 34),
373 web_app: { url: editorUrlFor(workspace, editorUrl, file.path) }
374 }
375 ]);
376 buttons.unshift(...fileEditors);
377 const genericEditorUrl = editorUrlFor(workspace, editorUrl);
378 const genericEditorIndex = buttons.findIndex((row) =>
379 row.some((button) => button.web_app?.url === genericEditorUrl)
380 );
381 if (genericEditorIndex >= 0) buttons.splice(genericEditorIndex, 1);
382 }
383 buttons.unshift([
384 {
385 text: '➕ افزودن فایل',
386 callback_data: `wfiles:${workspace.id}:${workspace.repoId}`
387 }
388 ]);
389 if (files.length > 1 && refs[1]?.refId)
390 buttons.unshift([
391 {
392 text: `➖ حذف ${short(files[1].path, 28)}`,
393 callback_data: `wremove:${refs[1].refId}`
394 }
395 ]);
396 return {
397 text: `📝 <b>Repository Workspace</b>\nChange Set: <b>${files.length} فایل</b> · تغییرکرده: <b>${changedCount}</b>\n${list}\nوضعیت: <b>${escapeHtml(workspace.state || 'DRAFT')}</b>\nBase: <code>${escapeHtml(String(workspace.baseHeadSha || '').slice(0, 10))}</code>\nپیام Commit: ${commitMessage}\n\n${draftInputNotice(workspace, editorUrl)}\nذخیره فقط Draft محلی را تغییر می‌دهد؛ GitHub فقط بعد از Diff، Ready و Safe Approval تغییر می‌کند.`,
398 reply_markup: { inline_keyboard: buttons }
399 };
400 };
401
402 const renderWorkspace = async (workspaceId, ownerId) =>
403 renderWorkspaceObject(
404 await requireWorkspace(workspaceId, ownerId),
405 ownerId
406 );
407
408 const pickWorkspaceFile = async (workspaceId, repoId, ownerId) => {
409 const workspace = await requireWorkspace(workspaceId, ownerId);
410 if (Number(workspace.repoId) !== Number(repoId))
411 throw new Error('Workspace repository mismatch');
412 const existingPaths = new Set(
413 (Array.isArray(workspace.files) && workspace.files.length
414 ? workspace.files
415 : [{ path: workspace.path }]
416 ).map((file) => file.path)
417 );
418 const items = (
419 await github.listFiles(repoId, '', { ref: workspace.baseHeadSha })
420 )
421 .filter((item) => item.type === 'file' && !existingPaths.has(item.path))
422 .slice(0, 20);
423 const refs = await workspaces.createNavigationRefs({
424 ownerId,
425 refs: items.map((item) => ({
426 repoId,
427 workspaceId,
428 path: item.path,
429 type: 'workspace-add',
430 sha: item.sha
431 }))
432 });
433 return {
434 text: `➕ <b>افزودن فایل به Change Set</b>\n${items.length ? 'یک فایل را انتخاب کنید.' : 'فایل قابل افزودن دیگری در این نما نیست.'}`,
435 reply_markup: {
436 inline_keyboard: items
437 .map((item, i) => [
438 {
439 text: `📄 ${short(item.path, 42)}`,
440 callback_data: `wadd:${refs[i].refId}`
441 }
442 ])
443 .concat([
444 [{ text: '↩️ Workspace', callback_data: `ws:${workspaceId}` }]
445 ])
446 }
447 };
448 };
449
450 const addWorkspaceFileFromRef = async (
451 refId,
452 ownerId,
453 expectedWorkspaceId = null
454 ) => {
455 const ref = await workspaces.resolveNavigationRef({ ownerId, refId });
456 if (!ref || ref.type !== 'workspace-add')
457 throw new Error('Workspace add-file reference is missing or expired');
458 if (expectedWorkspaceId && ref.workspaceId !== expectedWorkspaceId)
459 throw new Error('Workspace reference mismatch');
460 const workspace = await requireWorkspace(ref.workspaceId, ownerId);
461 if (Number(workspace.repoId) !== Number(ref.repoId))
462 throw new Error('Workspace repository mismatch');
463 if (workspace.files.length >= WORKSPACE_EDITOR_LIMITS.maxFiles)
464 throw new Error('Workspace file count is limited');
465 const file = await github.getFileAtRef(
466 ref.repoId,
467 ref.path,
468 workspace.baseHeadSha
469 );
470 const policy = validateEditableFile({
471 path: file.path,
472 text: file.content,
473 byteLength: file.size
474 });
475 if (!policy.editable)
476 throw new Error(policy.reason || 'File is not editable');
477 const aggregateBytes = workspace.files.reduce(
478 (total, entry) =>
479 total +
480 Math.max(
481 new TextEncoder().encode(entry.originalText ?? '').byteLength,
482 new TextEncoder().encode(entry.draftText ?? '').byteLength
483 ),
484 policy.byteLength
485 );
486 if (aggregateBytes > WORKSPACE_EDITOR_LIMITS.maxAggregateBytes)
487 throw new Error('Workspace aggregate size is limited');
488 const digest = await digestText(file.content);
489 return workspaces.upsertWorkspaceFile({
490 ownerId,
491 workspaceId: workspace.id,
492 file: {
493 path: file.path,
494 blobSha: file.sha,
495 originalText: file.content,
496 originalDigest: digest,
497 draftText: file.content,
498 draftDigest: digest
499 }
500 });
501 };
502
503 const addWorkspaceFile = async (refId, ownerId) => {
504 const updated = await addWorkspaceFileFromRef(refId, ownerId);
505 const view = await renderWorkspaceObject(updated, ownerId);
506 view.text = `✅ فایل به Change Set اضافه شد.\n\n${view.text}`;
507 return view;
508 };
509
510 const removeWorkspaceFile = async (refId, ownerId) => {
511 const ref = await workspaces.resolveNavigationRef({ ownerId, refId });
512 if (!ref || ref.type !== 'workspace-file')
513 throw new Error('Workspace file reference is missing or expired');
514 const updated = await workspaces.removeWorkspaceFile({
515 ownerId,
516 workspaceId: ref.workspaceId,
517 path: ref.path
518 });
519 return renderWorkspaceObject(updated, ownerId);
520 };
521
522 const prepareInput = async (workspaceId, mode, ownerId) => {
523 const workspace = await requireWorkspace(workspaceId, ownerId);
524 if (mode !== 'commit_message') {
525 await workspaces.consumePendingInput({ ownerId, workspaceId, mode });
526 return {
527 text: `📝 <b>ویرایش Draft در Mini App</b>\n${draftInputNotice(workspace, editorUrl)}`,
528 reply_markup: {
529 inline_keyboard: workspaceButtons(workspace, editorUrl)
530 }
531 };
532 }
533 await workspaces.setPendingInput({ ownerId, workspaceId, mode });
534 return {
535 text: `✍️ <b>پیام Commit را ارسال کنید</b>\nفایل: <code>${escapeHtml(workspace.path)}</code>\n\nپیام باید غیرخالی و حداکثر 120 کاراکتر باشد. پیام بعدی فقط یک‌بار مصرف می‌شود.`,
536 reply_markup: {
537 inline_keyboard: [
538 [{ text: '↩️ بازگشت به Draft', callback_data: `ws:${workspace.id}` }]
539 ]
540 }
541 };
542 };
543
544 const applyPendingInput = async ({ pending, text }, ownerId) => {
545 const workspaceId = String(pending?.workspaceId || '');
546 const mode = String(pending?.mode || '');
547 if (
548 !new RegExp(`^${HANDLE_10}$`).test(workspaceId) ||
549 !['draft', 'draft_file', 'commit_message'].includes(mode)
550 ) {
551 throw new Error('Pending workspace input is invalid');
552 }
553
554 const consumed = await workspaces.consumePendingInput({
555 ownerId,
556 workspaceId,
557 mode
558 });
559 if (!consumed)
560 throw new Error(
561 'Pending workspace input was already consumed or expired'
562 );
563 const workspace = await requireWorkspace(workspaceId, ownerId);
564
565 if (mode !== 'commit_message') {
566 return {
567 text: `⚠️ <b>Draft تغییر نکرد</b>\nورودی قدیمی چت لغو شد. ${draftInputNotice(workspace, editorUrl)}`,
568 reply_markup: {
569 inline_keyboard: workspaceButtons(workspace, editorUrl)
570 }
571 };
572 }
573
574 let message;
575 try {
576 message = normalizeCommitMessage(text);
577 } catch (error) {
578 return {
579 text: `⚠️ <b>پیام Commit ذخیره نشد</b>\n${escapeHtml(error?.message || 'Commit message is invalid')}\n\nاین ورودی مصرف شد؛ برای تلاش دوباره «پیام Commit» را بزنید.`,
580 reply_markup: {
581 inline_keyboard: [
582 [
583 {
584 text: '📝 بازگشت به Draft',
585 callback_data: `ws:${workspace.id}`
586 }
587 ]
588 ]
589 }
590 };
591 }
592 const digest = await digestText(message);
593 const updated = await workspaces.setCommitMessage({
594 ownerId,
595 workspaceId,
596 message,
597 digest
598 });
599 return {
600 text: `✅ <b>پیام Commit ذخیره شد</b>\n<code>${escapeHtml(message)}</code>\n\nهنوز هیچ تغییری در GitHub انجام نشده است.`,
601 reply_markup: { inline_keyboard: workspaceButtons(updated, editorUrl) }
602 };
603 };
604
605 const renderDiff = async (workspaceId, ownerId) => {
606 const workspace = await requireWorkspace(workspaceId, ownerId);
607 const files =
608 Array.isArray(workspace.files) && workspace.files.length
609 ? workspace.files
610 : [
611 {
612 path: workspace.path,
613 originalText: workspace.originalText,
614 draftText: workspace.draftText
615 }
616 ];
617 const changed = files.filter(
618 (file) => file.draftText !== file.originalText
619 );
620 const diffs = changed.map((file) => ({
621 file,
622 diff: buildUnifiedDiff({
623 path: file.path,
624 before: file.originalText,
625 after: file.draftText,
626 maxChars: Math.max(500, Math.floor(2200 / Math.max(1, changed.length)))
627 })
628 }));
629 const additions = diffs.reduce((n, x) => n + x.diff.additions, 0),
630 deletions = diffs.reduce((n, x) => n + x.diff.deletions, 0);
631 const body = diffs.length
632 ? diffs
633 .map(
634 ({ file, diff }) =>
635 `<b>${escapeHtml(file.path)}</b> · +${diff.additions}/-${diff.deletions}${diff.truncated ? ' ⚠️' : ''}`
636 )
637 .join('\n')
638 : '<i>هیچ تغییر محلی وجود ندارد.</i>';
639 return {
640 text: `🔍 <b>Diff تجمیعی Change Set</b>\n${changed.length} فایل تغییرکرده · +${additions} / -${deletions}\n➖➖➖➖➖➖➖➖➖➖\n${body}\n\nمتن Diff فقط در Mini App نمایش داده می‌شود.`,
641 reply_markup: {
642 inline_keyboard: [
643 ...(editorUrlFor(workspace, editorUrl)
644 ? [
645 [
646 {
647 text: '🔍 مشاهده Diff در Mini App',
648 web_app: {
649 url: editorUrlFor(workspace, editorUrl) + '&view=diff'
650 }
651 }
652 ]
653 ]
654 : []),
655 [
656 { text: '📝 Draft', callback_data: `ws:${workspace.id}` },
657 { text: '✅ آماده Commit', callback_data: `wready:${workspace.id}` }
658 ]
659 ]
660 }
661 };
662 };
663
664 const sealWorkspaceIntent = async (workspaceId, ownerId, review) => {
665 const workspace = await requireWorkspace(workspaceId, ownerId);
666 const workspaceFiles =
667 Array.isArray(workspace.files) && workspace.files.length
668 ? workspace.files
669 : null;
670 const changedFiles = workspaceFiles
671 ? workspaceFiles.filter((file) => file.draftText !== file.originalText)
672 : null;
673 if (
674 workspaceFiles
675 ? changedFiles.length === 0
676 : workspace.draftText === workspace.originalText
677 )
678 throw new Error('No draft change to commit');
679 const commitMessage = normalizeCommitMessage(workspace.commitMessage);
680 const commitMessageDigest = await digestText(commitMessage);
681 const targetBranch = makeTargetBranch(workspace.id);
682 const createdAt = Number(workspace.createdAt);
683 const commitTimestamp = new Date(
684 Number.isFinite(createdAt) ? createdAt : 0
685 ).toISOString();
686 const fileDescriptors = workspaceFiles
687 ? await Promise.all(
688 workspaceFiles.map(async (file) => ({
689 path: file.path,
690 sourceBlobSha: file.blobSha,
691 contentDigest:
692 file.draftDigest || (await digestText(file.draftText))
693 }))
694 )
695 : null;
696 const material = workspaceFiles
697 ? {
698 repoId: Number(workspace.repoId),
699 workspaceId: workspace.id,
700 baseBranch: workspace.baseBranch,
701 baseHeadSha: workspace.baseHeadSha,
702 baseTreeSha: workspace.baseTreeSha,
703 files: fileDescriptors,
704 commitMessageDigest,
705 targetBranch,
706 commitTimestamp
707 }
708 : {
709 repoId: Number(workspace.repoId),
710 workspaceId: workspace.id,
711 baseBranch: workspace.baseBranch,
712 baseHeadSha: workspace.baseHeadSha,
713 baseTreeSha: workspace.baseTreeSha,
714 path: workspace.path,
715 sourceBlobSha: workspace.blobSha,
716 contentDigest: await digestText(workspace.draftText),
717 commitMessageDigest,
718 targetBranch,
719 commitTimestamp
720 };
721 const intentDigest = await digestText(JSON.stringify(material));
722 const intent = await workspaces.sealIntent({
723 ownerId,
724 workspaceId,
725 intent: { ...material, intentDigest },
726 ...(review ? { expectedReview: review } : {})
727 });
728 if (!intent?.id || !/^[A-Za-z0-9_-]{8}$/.test(intent.id))
729 throw new Error('Commit intent ID is invalid');
730 return { workspace, workspaceFiles, changedFiles, targetBranch, intent };
731 };
732
733 const sealReadyIntent = async (workspaceId, ownerId) => {
734 const { workspace, workspaceFiles, changedFiles, targetBranch, intent } =
735 await sealWorkspaceIntent(workspaceId, ownerId);
736 return {
737 text: `✅ <b>آمادهٔ تأیید Commit</b>\n${workspaceFiles ? `Change Set: <b>${changedFiles.length} فایل تغییرکرده</b>\n${changedFiles.map((file) => `• <code>${escapeHtml(file.path)}</code>`).join('\n')}` : `فایل: <code>${escapeHtml(workspace.path)}</code>`}\nBranch: <code>${escapeHtml(targetBranch)}</code>\nBase: <code>${escapeHtml(String(workspace.baseHeadSha).slice(0, 10))}</code>\n\nمرحلهٔ بعد فقط درخواست تأیید امن را می‌سازد؛ تا تأیید معتبر مصرف نشود GitHub WRITE اجرا نمی‌شود.`,
738 reply_markup: {
739 inline_keyboard: [
740 [
741 {
742 text: '✅ تأیید و Commit',
743 callback_data: `wscommit:${workspace.repoId}:${intent.id}`
744 }
745 ],
746 [
747 { text: '🔍 Diff', callback_data: `wdiff:${workspace.id}` },
748 { text: '📝 Draft', callback_data: `ws:${workspace.id}` }
749 ]
750 ]
751 }
752 };
753 };
754
755 const cancelDraft = async (workspaceId, ownerId) => {
756 const workspace = await requireWorkspace(workspaceId, ownerId);
757 await workspaces.cancelWorkspace({ ownerId, workspaceId });
758 return {
759 text: `🗑 <b>Draft لغو شد</b>\nفایل: <code>${escapeHtml(workspace.path)}</code>\nهیچ تغییری در GitHub انجام نشد.`,
760 reply_markup: {
761 inline_keyboard: [
762 [{ text: '🔙 فایل‌ها', callback_data: `files:${workspace.repoId}` }]
763 ]
764 }
765 };
766 };
767
768 return {
769 createWorkspaceFromRef({ ownerId, refId }) {
770 return createWorkspaceFromRef(refId, ownerFrom({ ownerId }));
771 },
772
773 addWorkspaceFileFromRef({ ownerId, workspaceId, refId }) {
774 return addWorkspaceFileFromRef(
775 refId,
776 ownerFrom({ ownerId }),
777 workspaceId
778 );
779 },
780
781 sealWorkspaceIntent({ ownerId, workspaceId, review }) {
782 return sealWorkspaceIntent(workspaceId, ownerFrom({ ownerId }), review);
783 },
784
785 resolveCallback(data, context = {}) {
786 const parsed = parseCallback(data);
787 if (!parsed) return null;
788
789 if (parsed.kind === 'commit') {
790 return {
791 actionId: parsed.actionId,
792 approval: {
793 input: { repoId: parsed.repoId, intentId: parsed.intentId },
794 label: 'Commit روی branch جدید',
795 cancelCallback: `repo:${parsed.repoId}`
796 },
797 audit: { repoId: parsed.repoId, intentId: parsed.intentId },
798 execute: async () => {
799 const ownerId = ownerFrom(context);
800 const result = await commitWorkspaceIntent({
801 github,
802 workspaces,
803 ownerId,
804 repoId: parsed.repoId,
805 intentId: parsed.intentId
806 });
807 const intent = await workspaces.getIntent({
808 ownerId,
809 intentId: parsed.intentId
810 });
811 const view = workspaceCommitResultView(
812 parsed.repoId,
813 intent,
814 result
815 );
816 return {
817 ...view,
818 audit: {
819 repoId: parsed.repoId,
820 intentId: parsed.intentId,
821 workspaceId: intent?.workspaceId,
822 path: intent?.path,
823 contentDigest: intent?.contentDigest,
824 commitMessageDigest: intent?.commitMessageDigest,
825 baseHeadSha: intent?.baseHeadSha,
826 targetBranch: intent?.targetBranch,
827 commitSha: result.commitSha,
828 branch: result.branch,
829 idempotent: result.idempotent
830 }
831 };
832 }
833 };
834 }
835
836 return {
837 actionId: parsed.actionId,
838 execute: async () => {
839 const ownerId = ownerFrom(context);
840 if (parsed.kind === 'root')
841 return renderDirectory(parsed.repoId, '', ownerId);
842 if (parsed.kind === 'workspace')
843 return renderWorkspace(parsed.workspaceId, ownerId);
844 if (parsed.kind === 'pick_file')
845 return pickWorkspaceFile(
846 parsed.workspaceId,
847 parsed.repoId,
848 ownerId
849 );
850 if (parsed.kind === 'add_file')
851 return addWorkspaceFile(parsed.refId, ownerId);
852 if (parsed.kind === 'remove_file')
853 return removeWorkspaceFile(parsed.refId, ownerId);
854 if (parsed.kind === 'edit') return createDraft(parsed.refId, ownerId);
855 if (parsed.kind === 'input')
856 return prepareInput(parsed.workspaceId, parsed.mode, ownerId);
857 if (parsed.kind === 'diff')
858 return renderDiff(parsed.workspaceId, ownerId);
859 if (parsed.kind === 'ready')
860 return sealReadyIntent(parsed.workspaceId, ownerId);
861 if (parsed.kind === 'cancel')
862 return cancelDraft(parsed.workspaceId, ownerId);
863 const ref = await workspaces.resolveNavigationRef({
864 ownerId,
865 refId: parsed.refId
866 });
867 if (!ref)
868 throw new Error(
869 'Workspace navigation reference is missing or expired'
870 );
871 return ref.type === 'dir'
872 ? renderDirectory(ref.repoId, ref.path, ownerId)
873 : renderFile(parsed.refId, ownerId);
874 }
875 };
876 },
877
878 resolveMessage(payload, context = {}) {
879 const pending = payload?.pending;
880 if (
881 !pending ||
882 !['draft', 'draft_file', 'commit_message'].includes(
883 String(pending.mode || '')
884 )
885 )
886 return null;
887 if (!new RegExp(`^${HANDLE_10}$`).test(String(pending.workspaceId || '')))
888 return null;
889 return {
890 actionId: 'github.workspace.input.apply',
891 execute: async () =>
892 applyPendingInput(
893 {
894 pending,
895 text:
896 pending.mode === 'commit_message'
897 ? String(payload?.text ?? '')
898 : undefined
899 },
900 ownerFrom(context)
901 )
902 };
903 }
904 };
905 }