Personal Telegram developer console for GitHub

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