Personal Telegram developer console for GitHub

fix/editor-safe-file-options
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 468 lines 28.1 KB
Raw
1 import {
2 buildUnifiedDiff,
3 digestText,
4 makeTargetBranch,
5 normalizeCommitMessage,
6 validateEditableFile
7 } from '../../core/workspace-policy.js';
8 import { DEFAULT_CONFIG } from '../../config.js';
9 import { commitWorkspaceIntent } from './workspace-commit.js';
10
11 export { commitWorkspaceIntent } from './workspace-commit.js';
12
13 const HANDLE_10 = '[A-Za-z0-9_-]{10}';
14 const INTENT_8 = '[A-Za-z0-9_-]{8}';
15 const escapeHtml = value => String(value ?? '')
16 .replaceAll('&', '&')
17 .replaceAll('<', '&lt;')
18 .replaceAll('>', '&gt;')
19 .replaceAll('"', '&quot;');
20 const short = (value, max = 70) => {
21 const text = String(value ?? '');
22 return text.length > max ? `${text.slice(0, max - 1)}…` : text;
23 };
24
25 const ownerFrom = context => {
26 const ownerId = String(context?.ownerId ?? '');
27 if (!ownerId) throw new Error('Workspace owner is required');
28 return ownerId;
29 };
30
31 function parseCallback(data) {
32 const value = String(data || '');
33 let match = value.match(/^(?:files):(\d+)$/);
34 if (match) return { actionId: 'github.files.list', kind: 'root', repoId: Number(match[1]) };
35 match = value.match(new RegExp(`^wnav:(${HANDLE_10})$`));
36 if (match) return { actionId: 'github.workspace.navigate', kind: 'navigate', refId: match[1] };
37 match = value.match(new RegExp(`^wedit:(${HANDLE_10})$`));
38 if (match) return { actionId: 'github.workspace.create', kind: 'edit', refId: match[1] };
39 match = value.match(new RegExp(`^ws:(${HANDLE_10})$`));
40 if (match) return { actionId: 'github.workspace.view', kind: 'workspace', workspaceId: match[1] };
41 match = value.match(new RegExp(`^wadd:(${HANDLE_10})$`));
42 if (match) return { actionId: 'github.workspace.file.add', kind: 'add_file', refId: match[1] };
43 match = value.match(new RegExp(`^wremove:(${HANDLE_10})$`));
44 if (match) return { actionId: 'github.workspace.file.remove', kind: 'remove_file', refId: match[1] };
45 match = value.match(new RegExp(`^wfiles:(${HANDLE_10}):(\\d+)$`));
46 if (match) return { actionId: 'github.workspace.file.pick', kind: 'pick_file', workspaceId: match[1], repoId: Number(match[2]) };
47 match = value.match(new RegExp(`^wfile:(${HANDLE_10})$`));
48 if (match) return { actionId: 'github.workspace.input.prepare', kind: 'input', workspaceId: match[1], mode: 'draft_file' };
49 match = value.match(new RegExp(`^wtext:(${HANDLE_10})$`));
50 if (match) return { actionId: 'github.workspace.input.prepare', kind: 'input', workspaceId: match[1], mode: 'draft' };
51 match = value.match(new RegExp(`^wmsg:(${HANDLE_10})$`));
52 if (match) return { actionId: 'github.workspace.input.prepare', kind: 'input', workspaceId: match[1], mode: 'commit_message' };
53 match = value.match(new RegExp(`^wdiff:(${HANDLE_10})$`));
54 if (match) return { actionId: 'github.workspace.diff', kind: 'diff', workspaceId: match[1] };
55 match = value.match(new RegExp(`^wready:(${HANDLE_10})$`));
56 if (match) return { actionId: 'github.workspace.ready', kind: 'ready', workspaceId: match[1] };
57 match = value.match(new RegExp(`^wcancel:(${HANDLE_10})$`));
58 if (match) return { actionId: 'github.workspace.cancel', kind: 'cancel', workspaceId: match[1] };
59 match = value.match(new RegExp(`^wscommit:(\\d+):(${INTENT_8})$`));
60 if (match) return {
61 actionId: 'github.workspace.commit_branch',
62 kind: 'commit',
63 repoId: Number(match[1]),
64 intentId: match[2]
65 };
66 return null;
67 }
68
69 function editorUrlFor(workspace, editorUrl, path = '') {
70 const configured = String(editorUrl || '').trim();
71 if (!configured) return '';
72 try {
73 const url = new URL(configured);
74 if (url.protocol !== 'https:') return '';
75 url.searchParams.set('workspaceId', workspace.id);
76 if (path) url.searchParams.set('path', path);
77 return url.toString();
78 } catch {
79 return '';
80 }
81 }
82
83 function workspaceButtons(workspace, editorUrl) {
84 const editor = editorUrlFor(workspace, editorUrl);
85 const firstRow = [];
86 if (editor) firstRow.push({ text: '🧑‍💻 Editor', web_app: { url: editor } });
87 firstRow.push({ text: '📎 بارگذاری فایل', callback_data: `wfile:${workspace.id}` });
88 if (!editor) firstRow.push({ text: '📝 Paste متن', callback_data: `wtext:${workspace.id}` });
89 return [
90 firstRow,
91 [{ text: '✍️ پیام Commit', callback_data: `wmsg:${workspace.id}` }],
92 [
93 { text: '🔍 Diff', callback_data: `wdiff:${workspace.id}` },
94 { text: '✅ آماده Commit', callback_data: `wready:${workspace.id}` }
95 ],
96 [
97 { text: '🗑 لغو Draft', callback_data: `wcancel:${workspace.id}` },
98 { text: '🔙 فایل‌ها', callback_data: `files:${workspace.repoId}` }
99 ]
100 ];
101 }
102
103 function workspaceCommitResultView(repoId, intent, result) {
104 const rows = [
105 [{ text: '🧪 CI / Actions', callback_data: `runs:${repoId}` }]
106 ];
107 if (intent?.workspaceId) {
108 rows.push([{ text: '📝 Workspace', callback_data: `ws:${intent.workspaceId}` }]);
109 }
110 rows.push([{ text: '📦 پروژه', callback_data: `repo:${repoId}` }]);
111 return {
112 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شاخهٔ پیش‌فرض تغییر نکرده است.`,
113 reply_markup: { inline_keyboard: rows }
114 };
115 }
116
117 export function createWorkspaceController({ github, workspaces, editorUrl = DEFAULT_CONFIG.workspaceEditorUrl } = {}) {
118 if (!github) throw new Error('Workspace controller requires GitHub service');
119 if (!workspaces) throw new Error('Workspace controller requires durable workspace store');
120
121 const requireWorkspace = async (workspaceId, ownerId) => {
122 const workspace = await workspaces.getWorkspace({ ownerId, workspaceId });
123 if (!workspace) throw new Error('Workspace not found or expired');
124 return workspace;
125 };
126
127 const renderDirectory = async (repoId, path, ownerId) => {
128 const [repo, items] = await Promise.all([
129 github.getRepository(repoId),
130 github.listFiles(repoId, path)
131 ]);
132 const visible = items.slice(0, 30);
133 const handles = await workspaces.createNavigationRefs({
134 ownerId,
135 refs: visible.map(item => ({ repoId, path: item.path, type: item.type, sha: item.sha }))
136 });
137 const body = visible.length
138 ? visible.map(item => `${item.type === 'dir' ? '📁' : '📄'} <code>${escapeHtml(short(item.name, 100))}</code>${item.type === 'file' && item.size ? ` (${Number(item.size).toLocaleString()} B)` : ''}`).join('\n')
139 : '<i>این پوشه خالی است.</i>';
140 const rows = visible.map((item, index) => [{
141 text: `${item.type === 'dir' ? '📁' : '📄'} ${short(item.name, 46)}`,
142 callback_data: `wnav:${handles[index].refId}`
143 }]);
144 rows.push([
145 { text: '🔄 بروزرسانی', callback_data: `files:${repoId}` },
146 { text: '📦 پروژه', callback_data: `repo:${repoId}` }
147 ]);
148 return {
149 text: `📂 <b>فایل‌های ${escapeHtml(repo.name)}</b>\n${path ? `مسیر: <code>${escapeHtml(path)}</code>\n` : ''}➖➖➖➖➖➖➖➖➖➖\n${body}`,
150 reply_markup: { inline_keyboard: rows }
151 };
152 };
153
154 const getPinnedFile = async ref => {
155 const repo = await github.getRepository(ref.repoId);
156 const snapshot = await github.getBranchSnapshot(ref.repoId, repo.defaultBranch);
157 const file = await github.getFileAtRef(ref.repoId, ref.path, snapshot.headSha);
158 return { repo, snapshot, file };
159 };
160
161 const renderFile = async (refId, ownerId) => {
162 const ref = await workspaces.resolveNavigationRef({ ownerId, refId });
163 if (!ref || ref.type !== 'file') throw new Error('Workspace file reference is missing or expired');
164 const { repo, snapshot, file } = await getPinnedFile(ref);
165 const policy = validateEditableFile({ path: file.path, text: file.content, byteLength: file.size });
166 const preview = file.content.length > 2600 ? `${file.content.slice(0, 2600)}\n…` : file.content;
167 const reason = repo.archived
168 ? 'این مخزن آرشیوشده است و ویرایش فایل در آن غیرفعال است.'
169 : policy.reason;
170 const rows = [];
171 if (!repo.archived && policy.editable) rows.push([{ text: '✏️ Edit', callback_data: `wedit:${refId}` }]);
172 rows.push([{ text: '🔙 فایل‌ها', callback_data: `files:${ref.repoId}` }, { text: '📦 پروژه', callback_data: `repo:${ref.repoId}` }]);
173 return {
174 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` : ''}➖➖➖➖➖➖➖➖➖➖\n<pre>${escapeHtml(preview)}</pre>`,
175 reply_markup: { inline_keyboard: rows }
176 };
177 };
178
179 const createDraft = async (refId, ownerId) => {
180 const ref = await workspaces.resolveNavigationRef({ ownerId, refId });
181 if (!ref || ref.type !== 'file') throw new Error('Workspace file reference is missing or expired');
182 const { repo, snapshot, file } = await getPinnedFile(ref);
183 if (repo.archived) throw new Error('Archived repository is not editable');
184 const policy = validateEditableFile({ path: file.path, text: file.content, byteLength: file.size });
185 if (!policy.editable) throw new Error(policy.reason || 'File is not editable');
186 const originalDigest = await digestText(file.content);
187 const workspace = await workspaces.createWorkspace({
188 ownerId,
189 repoId: Number(ref.repoId),
190 repoFullName: repo.fullName,
191 baseBranch: repo.defaultBranch,
192 baseHeadSha: snapshot.headSha,
193 baseTreeSha: snapshot.treeSha,
194 path: file.path,
195 blobSha: file.sha,
196 originalText: file.content,
197 originalDigest
198 });
199 return {
200 text: `📝 <b>Draft ساخته شد</b>\nمخزن: <code>${escapeHtml(repo.fullName)}</code>\nفایل: <code>${escapeHtml(file.path)}</code>\nBase: <code>${escapeHtml(snapshot.headSha.slice(0, 10))}</code>\n\nهنوز هیچ تغییری در GitHub انجام نشده است.`,
201 reply_markup: { inline_keyboard: [[{ text: '📝 باز کردن Draft', callback_data: `ws:${workspace.id}` }], [{ text: '🔙 فایل‌ها', callback_data: `files:${ref.repoId}` }]] }
202 };
203 };
204
205 const renderWorkspaceObject = async (workspace, ownerId) => {
206 const files = Array.isArray(workspace.files) && workspace.files.length ? workspace.files : [{ path: workspace.path, originalText: workspace.originalText, draftText: workspace.draftText }];
207 const changedCount = files.filter(file => file.draftText !== file.originalText).length;
208 const refs = await workspaces.createNavigationRefs?.({ ownerId, refs: files.map(file => ({ workspaceId: workspace.id, path: file.path, type: 'workspace-file', repoId: workspace.repoId })) }) || [];
209 const commitMessage = workspace.commitMessage ? `<code>${escapeHtml(short(workspace.commitMessage, 120))}</code>` : '<i>ثبت نشده</i>';
210 const list = files.map((file, i) => `${file.draftText !== file.originalText ? '●' : '○'} <code>${escapeHtml(file.path)}</code>${refs[i]?.refId && files.length > 1 ? ` — <i>قابل حذف</i>` : ''}`).join('\n');
211 const buttons = workspaceButtons(workspace, editorUrl);
212 if (editorUrl && files.length > 1) {
213 const fileEditors = files.map(file => [{ text: 'Edit ' + short(file.path, 34), web_app: { url: editorUrlFor(workspace, editorUrl, file.path) } }]);
214 buttons.unshift(...fileEditors);
215 const genericEditorUrl = editorUrlFor(workspace, editorUrl);
216 const genericEditorIndex = buttons.findIndex(row => row.some(button => button.web_app?.url === genericEditorUrl));
217 if (genericEditorIndex >= 0) buttons[genericEditorIndex] = buttons[genericEditorIndex].filter(button => !button.web_app);
218 }
219 buttons.unshift([{ text: '➕ افزودن فایل', callback_data: `wfiles:${workspace.id}:${workspace.repoId}` }]);
220 if (files.length > 1 && refs[1]?.refId) buttons.unshift([{ text: `➖ حذف ${short(files[1].path, 28)}`, callback_data: `wremove:${refs[1].refId}` }]);
221 return { 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ذخیره فقط Draft محلی را تغییر می‌دهد؛ GitHub فقط بعد از Diff، Ready و Safe Approval تغییر می‌کند.`, reply_markup:{inline_keyboard:buttons} };
222 };
223
224 const renderWorkspace = async (workspaceId, ownerId) => renderWorkspaceObject(await requireWorkspace(workspaceId, ownerId), ownerId);
225
226 const pickWorkspaceFile = async (workspaceId, repoId, ownerId) => {
227 const workspace = await requireWorkspace(workspaceId, ownerId);
228 if (Number(workspace.repoId) !== Number(repoId)) throw new Error('Workspace repository mismatch');
229 const existingPaths = new Set((Array.isArray(workspace.files) && workspace.files.length ? workspace.files : [{ path: workspace.path }]).map(file => file.path));
230 const items = (await github.listFiles(repoId, '', { ref: workspace.baseHeadSha })).filter(item => item.type === 'file' && !existingPaths.has(item.path)).slice(0, 20);
231 const refs = await workspaces.createNavigationRefs({ ownerId, refs: items.map(item => ({ repoId, workspaceId, path:item.path, type:'workspace-add', sha:item.sha })) });
232 return { text:`➕ <b>افزودن فایل به Change Set</b>\n${items.length ? 'یک فایل را انتخاب کنید.' : 'فایل قابل افزودن دیگری در این نما نیست.'}`, reply_markup:{inline_keyboard:items.map((item,i)=>[{text:`📄 ${short(item.path,42)}`,callback_data:`wadd:${refs[i].refId}`}]).concat([[{text:'↩️ Workspace',callback_data:`ws:${workspaceId}`} ]])} };
233 };
234
235 const addWorkspaceFile = async (refId, ownerId) => {
236 const ref = await workspaces.resolveNavigationRef({ownerId,refId});
237 if (!ref || ref.type !== 'workspace-add') throw new Error('Workspace add-file reference is missing or expired');
238 const workspace = await requireWorkspace(ref.workspaceId, ownerId);
239 const file = await github.getFileAtRef(ref.repoId, ref.path, workspace.baseHeadSha);
240 const policy = validateEditableFile({path:file.path,text:file.content,byteLength:file.size});
241 if (!policy.editable) throw new Error(policy.reason || 'File is not editable');
242 const digest = await digestText(file.content);
243 const updated = await workspaces.upsertWorkspaceFile({ownerId,workspaceId:workspace.id,file:{path:file.path,blobSha:file.sha,originalText:file.content,originalDigest:digest,draftText:file.content,draftDigest:digest}});
244 const view = await renderWorkspaceObject(updated, ownerId); view.text = `✅ فایل <code>${escapeHtml(file.path)}</code> اضافه شد.\n\n${view.text}`; return view;
245 };
246
247 const removeWorkspaceFile = async (refId, ownerId) => {
248 const ref=await workspaces.resolveNavigationRef({ownerId,refId});
249 if(!ref || ref.type!=='workspace-file') throw new Error('Workspace file reference is missing or expired');
250 const updated=await workspaces.removeWorkspaceFile({ownerId,workspaceId:ref.workspaceId,path:ref.path});
251 return renderWorkspaceObject(updated,ownerId);
252 };
253
254 const prepareInput = async (workspaceId, mode, ownerId) => {
255 const workspace = await requireWorkspace(workspaceId, ownerId);
256 await workspaces.setPendingInput({ ownerId, workspaceId, mode });
257 const fileMode = mode === 'draft_file';
258 const draftMode = mode === 'draft';
259 return {
260 text: fileMode
261 ? `📎 <b>فایل متنی جایگزین را ارسال کنید</b>\nمقصد در مخزن: <code>${escapeHtml(workspace.path)}</code>\n\nفایل ارسال‌شده فقط به‌عنوان محتوای جایگزین Draft استفاده می‌شود؛ نام فایل مقصد را تغییر نمی‌دهد. سقف Policy: 20,000 کاراکتر Unicode و 65,536 بایت UTF-8 معتبر. فایل‌های باینری، LFS یا محتوای غیرمجاز رد می‌شوند.`
262 : draftMode
263 ? `📝 <b>ورودی متنی قدیمی Workspace</b>\nفایل: <code>${escapeHtml(workspace.path)}</code>\n\nاین مسیر فقط برای سازگاری پیام‌های قدیمی باقی مانده است. Editor جدید مسیر اصلی است. سقف: 20,000 کاراکتر Unicode و 65,536 بایت UTF-8.`
264 : `✍️ <b>پیام Commit را ارسال کنید</b>\nفایل: <code>${escapeHtml(workspace.path)}</code>\n\nپیام باید غیرخالی و حداکثر 120 کاراکتر باشد. پیام بعدی فقط یک‌بار مصرف می‌شود.`,
265 reply_markup: { inline_keyboard: [[{ text: '↩️ بازگشت به Draft', callback_data: `ws:${workspace.id}` }]] }
266 };
267 };
268
269 const applyPendingInput = async ({ pending, text, file }, ownerId) => {
270 const workspaceId = String(pending?.workspaceId || '');
271 const mode = String(pending?.mode || '');
272 if (!new RegExp(`^${HANDLE_10}$`).test(workspaceId) || !['draft', 'draft_file', 'commit_message'].includes(mode)) {
273 throw new Error('Pending workspace input is invalid');
274 }
275
276 if (mode === 'draft_file' && (!file || typeof file.text !== 'string')) {
277 throw new Error('A UTF-8 Telegram document is required for this workspace input');
278 }
279
280 const consumed = await workspaces.consumePendingInput({ ownerId, workspaceId, mode });
281 if (!consumed) throw new Error('Pending workspace input was already consumed or expired');
282 const workspace = await requireWorkspace(workspaceId, ownerId);
283
284 if (mode === 'draft' || mode === 'draft_file') {
285 const inputText = mode === 'draft_file' ? file.text : text;
286 const inputBytes = mode === 'draft_file' ? Number(file.byteLength) : undefined;
287 const policy = validateEditableFile({ path: workspace.path, text: inputText, byteLength: inputBytes });
288 if (!policy.editable) {
289 return {
290 text: `⚠️ <b>Draft تغییر نکرد</b>\n${escapeHtml(policy.reason || 'محتوای ارسال‌شده مجاز نیست.')}\n\nاین ورودی مصرف شد؛ برای تلاش دوباره ${mode === 'draft_file' ? '«بارگذاری فایل»' : 'Editor'} را باز کنید.`,
291 reply_markup: { inline_keyboard: [[{ text: '📝 بازگشت به Draft', callback_data: `ws:${workspace.id}` }]] }
292 };
293 }
294 const digest = await digestText(policy.text);
295 const updated = await workspaces.updateDraft({ ownerId, workspaceId, text: policy.text, digest });
296 const source = mode === 'draft_file'
297 ? `\nفایل ورودی: <code>${escapeHtml(short(file.name || 'uploaded file', 100))}</code>`
298 : '';
299 return {
300 text: `✅ <b>Draft محلی ذخیره شد</b>\nفایل مقصد: <code>${escapeHtml(updated.path)}</code>${source}\nکاراکتر: <b>${policy.charLength}</b> · بایت UTF-8: <b>${policy.byteLength}</b>\n\nهنوز هیچ تغییری در GitHub انجام نشده است.`,
301 reply_markup: { inline_keyboard: workspaceButtons(updated, editorUrl) }
302 };
303 }
304
305 let message;
306 try {
307 message = normalizeCommitMessage(text);
308 } catch (error) {
309 return {
310 text: `⚠️ <b>پیام Commit ذخیره نشد</b>\n${escapeHtml(error?.message || 'Commit message is invalid')}\n\nاین ورودی مصرف شد؛ برای تلاش دوباره «پیام Commit» را بزنید.`,
311 reply_markup: { inline_keyboard: [[{ text: '📝 بازگشت به Draft', callback_data: `ws:${workspace.id}` }]] }
312 };
313 }
314 const digest = await digestText(message);
315 const updated = await workspaces.setCommitMessage({ ownerId, workspaceId, message, digest });
316 return {
317 text: `✅ <b>پیام Commit ذخیره شد</b>\n<code>${escapeHtml(message)}</code>\n\nهنوز هیچ تغییری در GitHub انجام نشده است.`,
318 reply_markup: { inline_keyboard: workspaceButtons(updated, editorUrl) }
319 };
320 };
321
322 const renderDiff = async (workspaceId, ownerId) => {
323 const workspace = await requireWorkspace(workspaceId, ownerId);
324 const files = Array.isArray(workspace.files) && workspace.files.length ? workspace.files : [{path:workspace.path,originalText:workspace.originalText,draftText:workspace.draftText}];
325 const changed = files.filter(file => file.draftText !== file.originalText);
326 const diffs = changed.map(file => ({file,diff:buildUnifiedDiff({path:file.path,before:file.originalText,after:file.draftText,maxChars:Math.max(500,Math.floor(2200/Math.max(1,changed.length)))})}));
327 const additions=diffs.reduce((n,x)=>n+x.diff.additions,0), deletions=diffs.reduce((n,x)=>n+x.diff.deletions,0);
328 const body=diffs.length ? diffs.map(({file,diff})=>`<b>${escapeHtml(file.path)}</b> · +${diff.additions}/-${diff.deletions}${diff.truncated?' ⚠️':''}\n<pre>${escapeHtml(diff.text)}</pre>`).join('\n') : '<i>هیچ تغییر محلی وجود ندارد.</i>';
329 return { text:`🔍 <b>Diff تجمیعی Change Set</b>\n${changed.length} فایل تغییرکرده · +${additions} / -${deletions}\n➖➖➖➖➖➖➖➖➖➖\n${body}`, reply_markup:{inline_keyboard:[[{text:'📝 Draft',callback_data:`ws:${workspace.id}`},{text:'✅ آماده Commit',callback_data:`wready:${workspace.id}`}]]} };
330 };
331
332 const sealReadyIntent = async (workspaceId, ownerId) => {
333 const workspace = await requireWorkspace(workspaceId, ownerId);
334 const workspaceFiles = Array.isArray(workspace.files) && workspace.files.length ? workspace.files : null;
335 const changedFiles = workspaceFiles ? workspaceFiles.filter(file => file.draftText !== file.originalText) : null;
336 if (workspaceFiles ? changedFiles.length === 0 : workspace.draftText === workspace.originalText) throw new Error('No draft change to commit');
337 const commitMessage = normalizeCommitMessage(workspace.commitMessage);
338 const commitMessageDigest = await digestText(commitMessage);
339 const targetBranch = makeTargetBranch(workspace.id);
340 const createdAt = Number(workspace.createdAt);
341 const commitTimestamp = new Date(Number.isFinite(createdAt) ? createdAt : 0).toISOString();
342 const fileDescriptors = workspaceFiles ? await Promise.all(workspaceFiles.map(async file => ({ path:file.path, sourceBlobSha:file.blobSha, contentDigest:file.draftDigest || await digestText(file.draftText) }))) : null;
343 const material = workspaceFiles ? {
344 repoId:Number(workspace.repoId), workspaceId:workspace.id, baseBranch:workspace.baseBranch, baseHeadSha:workspace.baseHeadSha, baseTreeSha:workspace.baseTreeSha,
345 files:fileDescriptors, commitMessageDigest, targetBranch, commitTimestamp
346 } : {
347 repoId: Number(workspace.repoId),
348 workspaceId: workspace.id,
349 baseBranch: workspace.baseBranch,
350 baseHeadSha: workspace.baseHeadSha,
351 baseTreeSha: workspace.baseTreeSha,
352 path: workspace.path,
353 sourceBlobSha: workspace.blobSha,
354 contentDigest: await digestText(workspace.draftText),
355 commitMessageDigest,
356 targetBranch,
357 commitTimestamp
358 };
359 const intentDigest = await digestText(JSON.stringify(material));
360 const intent = await workspaces.sealIntent({
361 ownerId,
362 workspaceId,
363 intent: { ...material, intentDigest }
364 });
365 if (!intent?.id || !/^[A-Za-z0-9_-]{8}$/.test(intent.id)) throw new Error('Commit intent ID is invalid');
366 return {
367 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 اجرا نمی‌شود.`,
368 reply_markup: {
369 inline_keyboard: [
370 [{ text: '✅ تأیید و Commit', callback_data: `wscommit:${workspace.repoId}:${intent.id}` }],
371 [{ text: '🔍 Diff', callback_data: `wdiff:${workspace.id}` }, { text: '📝 Draft', callback_data: `ws:${workspace.id}` }]
372 ]
373 }
374 };
375 };
376
377 const cancelDraft = async (workspaceId, ownerId) => {
378 const workspace = await requireWorkspace(workspaceId, ownerId);
379 await workspaces.cancelWorkspace({ ownerId, workspaceId });
380 return {
381 text: `🗑 <b>Draft لغو شد</b>\nفایل: <code>${escapeHtml(workspace.path)}</code>\nهیچ تغییری در GitHub انجام نشد.`,
382 reply_markup: { inline_keyboard: [[{ text: '🔙 فایل‌ها', callback_data: `files:${workspace.repoId}` }]] }
383 };
384 };
385
386 return {
387 resolveCallback(data, context = {}) {
388 const parsed = parseCallback(data);
389 if (!parsed) return null;
390
391 if (parsed.kind === 'commit') {
392 return {
393 actionId: parsed.actionId,
394 approval: {
395 input: { repoId: parsed.repoId, intentId: parsed.intentId },
396 label: 'Commit روی branch جدید',
397 cancelCallback: `repo:${parsed.repoId}`
398 },
399 audit: { repoId: parsed.repoId, intentId: parsed.intentId },
400 execute: async () => {
401 const ownerId = ownerFrom(context);
402 const result = await commitWorkspaceIntent({
403 github,
404 workspaces,
405 ownerId,
406 repoId: parsed.repoId,
407 intentId: parsed.intentId
408 });
409 const intent = await workspaces.getIntent({ ownerId, intentId: parsed.intentId });
410 const view = workspaceCommitResultView(parsed.repoId, intent, result);
411 return {
412 ...view,
413 audit: {
414 repoId: parsed.repoId,
415 intentId: parsed.intentId,
416 workspaceId: intent?.workspaceId,
417 path: intent?.path,
418 contentDigest: intent?.contentDigest,
419 commitMessageDigest: intent?.commitMessageDigest,
420 baseHeadSha: intent?.baseHeadSha,
421 targetBranch: intent?.targetBranch,
422 commitSha: result.commitSha,
423 branch: result.branch,
424 idempotent: result.idempotent
425 }
426 };
427 }
428 };
429 }
430
431 return {
432 actionId: parsed.actionId,
433 execute: async () => {
434 const ownerId = ownerFrom(context);
435 if (parsed.kind === 'root') return renderDirectory(parsed.repoId, '', ownerId);
436 if (parsed.kind === 'workspace') return renderWorkspace(parsed.workspaceId, ownerId);
437 if (parsed.kind === 'pick_file') return pickWorkspaceFile(parsed.workspaceId, parsed.repoId, ownerId);
438 if (parsed.kind === 'add_file') return addWorkspaceFile(parsed.refId, ownerId);
439 if (parsed.kind === 'remove_file') return removeWorkspaceFile(parsed.refId, ownerId);
440 if (parsed.kind === 'edit') return createDraft(parsed.refId, ownerId);
441 if (parsed.kind === 'input') return prepareInput(parsed.workspaceId, parsed.mode, ownerId);
442 if (parsed.kind === 'diff') return renderDiff(parsed.workspaceId, ownerId);
443 if (parsed.kind === 'ready') return sealReadyIntent(parsed.workspaceId, ownerId);
444 if (parsed.kind === 'cancel') return cancelDraft(parsed.workspaceId, ownerId);
445 const ref = await workspaces.resolveNavigationRef({ ownerId, refId: parsed.refId });
446 if (!ref) throw new Error('Workspace navigation reference is missing or expired');
447 return ref.type === 'dir'
448 ? renderDirectory(ref.repoId, ref.path, ownerId)
449 : renderFile(parsed.refId, ownerId);
450 }
451 };
452 },
453
454 resolveMessage(payload, context = {}) {
455 const pending = payload?.pending;
456 if (!pending || !['draft', 'draft_file', 'commit_message'].includes(String(pending.mode || ''))) return null;
457 if (!new RegExp(`^${HANDLE_10}$`).test(String(pending.workspaceId || ''))) return null;
458 return {
459 actionId: 'github.workspace.input.apply',
460 execute: async () => applyPendingInput({
461 pending,
462 text: String(payload?.text ?? ''),
463 file: payload?.file && typeof payload.file === 'object' ? payload.file : null
464 }, ownerFrom(context))
465 };
466 }
467 };
468 }