Personal Telegram developer console for GitHub

phase2-acceptance-closeout
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 458 lines 27 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 const items = (await github.listFiles(repoId, '')).filter(item => item.type === 'file' && !(workspace.files || []).some(file => file.path === item.path)).slice(0, 20);
221 const refs = await workspaces.createNavigationRefs({ ownerId, refs: items.map(item => ({ repoId, workspaceId, path:item.path, type:'workspace-add', sha:item.sha })) });
222 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}`} ]])} };
223 };
224
225 const addWorkspaceFile = async (refId, ownerId) => {
226 const ref = await workspaces.resolveNavigationRef({ownerId,refId});
227 if (!ref || ref.type !== 'workspace-add') throw new Error('Workspace add-file reference is missing or expired');
228 const workspace = await requireWorkspace(ref.workspaceId, ownerId);
229 const file = await github.getFileAtRef(ref.repoId, ref.path, workspace.baseHeadSha);
230 const policy = validateEditableFile({path:file.path,text:file.content,byteLength:file.size});
231 if (!policy.editable) throw new Error(policy.reason || 'File is not editable');
232 const digest = await digestText(file.content);
233 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}});
234 const view = await renderWorkspaceObject(updated, ownerId); view.text = `✅ فایل <code>${escapeHtml(file.path)}</code> اضافه شد.\n\n${view.text}`; return view;
235 };
236
237 const removeWorkspaceFile = async (refId, ownerId) => {
238 const ref=await workspaces.resolveNavigationRef({ownerId,refId});
239 if(!ref || ref.type!=='workspace-file') throw new Error('Workspace file reference is missing or expired');
240 const updated=await workspaces.removeWorkspaceFile({ownerId,workspaceId:ref.workspaceId,path:ref.path});
241 return renderWorkspaceObject(updated,ownerId);
242 };
243
244 const prepareInput = async (workspaceId, mode, ownerId) => {
245 const workspace = await requireWorkspace(workspaceId, ownerId);
246 await workspaces.setPendingInput({ ownerId, workspaceId, mode });
247 const fileMode = mode === 'draft_file';
248 const draftMode = mode === 'draft';
249 return {
250 text: fileMode
251 ? `📎 <b>فایل متنی جایگزین را ارسال کنید</b>\nمقصد در مخزن: <code>${escapeHtml(workspace.path)}</code>\n\nفایل ارسال‌شده فقط به‌عنوان محتوای جایگزین Draft استفاده می‌شود؛ نام فایل مقصد را تغییر نمی‌دهد. سقف Policy: 20,000 کاراکتر Unicode و 65,536 بایت UTF-8 معتبر. فایل‌های باینری، LFS یا محتوای غیرمجاز رد می‌شوند.`
252 : draftMode
253 ? `📝 <b>ورودی متنی قدیمی Workspace</b>\nفایل: <code>${escapeHtml(workspace.path)}</code>\n\nاین مسیر فقط برای سازگاری پیام‌های قدیمی باقی مانده است. Editor جدید مسیر اصلی است. سقف: 20,000 کاراکتر Unicode و 65,536 بایت UTF-8.`
254 : `✍️ <b>پیام Commit را ارسال کنید</b>\nفایل: <code>${escapeHtml(workspace.path)}</code>\n\nپیام باید غیرخالی و حداکثر 120 کاراکتر باشد. پیام بعدی فقط یک‌بار مصرف می‌شود.`,
255 reply_markup: { inline_keyboard: [[{ text: '↩️ بازگشت به Draft', callback_data: `ws:${workspace.id}` }]] }
256 };
257 };
258
259 const applyPendingInput = async ({ pending, text, file }, ownerId) => {
260 const workspaceId = String(pending?.workspaceId || '');
261 const mode = String(pending?.mode || '');
262 if (!new RegExp(`^${HANDLE_10}$`).test(workspaceId) || !['draft', 'draft_file', 'commit_message'].includes(mode)) {
263 throw new Error('Pending workspace input is invalid');
264 }
265
266 if (mode === 'draft_file' && (!file || typeof file.text !== 'string')) {
267 throw new Error('A UTF-8 Telegram document is required for this workspace input');
268 }
269
270 const consumed = await workspaces.consumePendingInput({ ownerId, workspaceId, mode });
271 if (!consumed) throw new Error('Pending workspace input was already consumed or expired');
272 const workspace = await requireWorkspace(workspaceId, ownerId);
273
274 if (mode === 'draft' || mode === 'draft_file') {
275 const inputText = mode === 'draft_file' ? file.text : text;
276 const inputBytes = mode === 'draft_file' ? Number(file.byteLength) : undefined;
277 const policy = validateEditableFile({ path: workspace.path, text: inputText, byteLength: inputBytes });
278 if (!policy.editable) {
279 return {
280 text: `⚠️ <b>Draft تغییر نکرد</b>\n${escapeHtml(policy.reason || 'محتوای ارسال‌شده مجاز نیست.')}\n\nاین ورودی مصرف شد؛ برای تلاش دوباره ${mode === 'draft_file' ? '«بارگذاری فایل»' : 'Editor'} را باز کنید.`,
281 reply_markup: { inline_keyboard: [[{ text: '📝 بازگشت به Draft', callback_data: `ws:${workspace.id}` }]] }
282 };
283 }
284 const digest = await digestText(policy.text);
285 const updated = await workspaces.updateDraft({ ownerId, workspaceId, text: policy.text, digest });
286 const source = mode === 'draft_file'
287 ? `\nفایل ورودی: <code>${escapeHtml(short(file.name || 'uploaded file', 100))}</code>`
288 : '';
289 return {
290 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 انجام نشده است.`,
291 reply_markup: { inline_keyboard: workspaceButtons(updated, editorUrl) }
292 };
293 }
294
295 let message;
296 try {
297 message = normalizeCommitMessage(text);
298 } catch (error) {
299 return {
300 text: `⚠️ <b>پیام Commit ذخیره نشد</b>\n${escapeHtml(error?.message || 'Commit message is invalid')}\n\nاین ورودی مصرف شد؛ برای تلاش دوباره «پیام Commit» را بزنید.`,
301 reply_markup: { inline_keyboard: [[{ text: '📝 بازگشت به Draft', callback_data: `ws:${workspace.id}` }]] }
302 };
303 }
304 const digest = await digestText(message);
305 const updated = await workspaces.setCommitMessage({ ownerId, workspaceId, message, digest });
306 return {
307 text: `✅ <b>پیام Commit ذخیره شد</b>\n<code>${escapeHtml(message)}</code>\n\nهنوز هیچ تغییری در GitHub انجام نشده است.`,
308 reply_markup: { inline_keyboard: workspaceButtons(updated, editorUrl) }
309 };
310 };
311
312 const renderDiff = async (workspaceId, ownerId) => {
313 const workspace = await requireWorkspace(workspaceId, ownerId);
314 const files = Array.isArray(workspace.files) && workspace.files.length ? workspace.files : [{path:workspace.path,originalText:workspace.originalText,draftText:workspace.draftText}];
315 const changed = files.filter(file => file.draftText !== file.originalText);
316 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)))})}));
317 const additions=diffs.reduce((n,x)=>n+x.diff.additions,0), deletions=diffs.reduce((n,x)=>n+x.diff.deletions,0);
318 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>';
319 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}`}]]} };
320 };
321
322 const sealReadyIntent = async (workspaceId, ownerId) => {
323 const workspace = await requireWorkspace(workspaceId, ownerId);
324 const workspaceFiles = Array.isArray(workspace.files) && workspace.files.length ? workspace.files : null;
325 const changedFiles = workspaceFiles ? workspaceFiles.filter(file => file.draftText !== file.originalText) : null;
326 if (workspaceFiles ? changedFiles.length === 0 : workspace.draftText === workspace.originalText) throw new Error('No draft change to commit');
327 const commitMessage = normalizeCommitMessage(workspace.commitMessage);
328 const commitMessageDigest = await digestText(commitMessage);
329 const targetBranch = makeTargetBranch(workspace.id);
330 const createdAt = Number(workspace.createdAt);
331 const commitTimestamp = new Date(Number.isFinite(createdAt) ? createdAt : 0).toISOString();
332 const fileDescriptors = workspaceFiles ? await Promise.all(workspaceFiles.map(async file => ({ path:file.path, sourceBlobSha:file.blobSha, contentDigest:file.draftDigest || await digestText(file.draftText) }))) : null;
333 const material = workspaceFiles ? {
334 repoId:Number(workspace.repoId), workspaceId:workspace.id, baseBranch:workspace.baseBranch, baseHeadSha:workspace.baseHeadSha, baseTreeSha:workspace.baseTreeSha,
335 files:fileDescriptors, commitMessageDigest, targetBranch, commitTimestamp
336 } : {
337 repoId: Number(workspace.repoId),
338 workspaceId: workspace.id,
339 baseBranch: workspace.baseBranch,
340 baseHeadSha: workspace.baseHeadSha,
341 baseTreeSha: workspace.baseTreeSha,
342 path: workspace.path,
343 sourceBlobSha: workspace.blobSha,
344 contentDigest: await digestText(workspace.draftText),
345 commitMessageDigest,
346 targetBranch,
347 commitTimestamp
348 };
349 const intentDigest = await digestText(JSON.stringify(material));
350 const intent = await workspaces.sealIntent({
351 ownerId,
352 workspaceId,
353 intent: { ...material, intentDigest }
354 });
355 if (!intent?.id || !/^[A-Za-z0-9_-]{8}$/.test(intent.id)) throw new Error('Commit intent ID is invalid');
356 return {
357 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 اجرا نمی‌شود.`,
358 reply_markup: {
359 inline_keyboard: [
360 [{ text: '✅ تأیید و Commit', callback_data: `wscommit:${workspace.repoId}:${intent.id}` }],
361 [{ text: '🔍 Diff', callback_data: `wdiff:${workspace.id}` }, { text: '📝 Draft', callback_data: `ws:${workspace.id}` }]
362 ]
363 }
364 };
365 };
366
367 const cancelDraft = async (workspaceId, ownerId) => {
368 const workspace = await requireWorkspace(workspaceId, ownerId);
369 await workspaces.cancelWorkspace({ ownerId, workspaceId });
370 return {
371 text: `🗑 <b>Draft لغو شد</b>\nفایل: <code>${escapeHtml(workspace.path)}</code>\nهیچ تغییری در GitHub انجام نشد.`,
372 reply_markup: { inline_keyboard: [[{ text: '🔙 فایل‌ها', callback_data: `files:${workspace.repoId}` }]] }
373 };
374 };
375
376 return {
377 resolveCallback(data, context = {}) {
378 const parsed = parseCallback(data);
379 if (!parsed) return null;
380
381 if (parsed.kind === 'commit') {
382 return {
383 actionId: parsed.actionId,
384 approval: {
385 input: { repoId: parsed.repoId, intentId: parsed.intentId },
386 label: 'Commit روی branch جدید',
387 cancelCallback: `repo:${parsed.repoId}`
388 },
389 audit: { repoId: parsed.repoId, intentId: parsed.intentId },
390 execute: async () => {
391 const ownerId = ownerFrom(context);
392 const result = await commitWorkspaceIntent({
393 github,
394 workspaces,
395 ownerId,
396 repoId: parsed.repoId,
397 intentId: parsed.intentId
398 });
399 const intent = await workspaces.getIntent({ ownerId, intentId: parsed.intentId });
400 const view = workspaceCommitResultView(parsed.repoId, intent, result);
401 return {
402 ...view,
403 audit: {
404 repoId: parsed.repoId,
405 intentId: parsed.intentId,
406 workspaceId: intent?.workspaceId,
407 path: intent?.path,
408 contentDigest: intent?.contentDigest,
409 commitMessageDigest: intent?.commitMessageDigest,
410 baseHeadSha: intent?.baseHeadSha,
411 targetBranch: intent?.targetBranch,
412 commitSha: result.commitSha,
413 branch: result.branch,
414 idempotent: result.idempotent
415 }
416 };
417 }
418 };
419 }
420
421 return {
422 actionId: parsed.actionId,
423 execute: async () => {
424 const ownerId = ownerFrom(context);
425 if (parsed.kind === 'root') return renderDirectory(parsed.repoId, '', ownerId);
426 if (parsed.kind === 'workspace') return renderWorkspace(parsed.workspaceId, ownerId);
427 if (parsed.kind === 'pick_file') return pickWorkspaceFile(parsed.workspaceId, parsed.repoId, ownerId);
428 if (parsed.kind === 'add_file') return addWorkspaceFile(parsed.refId, ownerId);
429 if (parsed.kind === 'remove_file') return removeWorkspaceFile(parsed.refId, ownerId);
430 if (parsed.kind === 'edit') return createDraft(parsed.refId, ownerId);
431 if (parsed.kind === 'input') return prepareInput(parsed.workspaceId, parsed.mode, ownerId);
432 if (parsed.kind === 'diff') return renderDiff(parsed.workspaceId, ownerId);
433 if (parsed.kind === 'ready') return sealReadyIntent(parsed.workspaceId, ownerId);
434 if (parsed.kind === 'cancel') return cancelDraft(parsed.workspaceId, ownerId);
435 const ref = await workspaces.resolveNavigationRef({ ownerId, refId: parsed.refId });
436 if (!ref) throw new Error('Workspace navigation reference is missing or expired');
437 return ref.type === 'dir'
438 ? renderDirectory(ref.repoId, ref.path, ownerId)
439 : renderFile(parsed.refId, ownerId);
440 }
441 };
442 },
443
444 resolveMessage(payload, context = {}) {
445 const pending = payload?.pending;
446 if (!pending || !['draft', 'draft_file', 'commit_message'].includes(String(pending.mode || ''))) return null;
447 if (!new RegExp(`^${HANDLE_10}$`).test(String(pending.workspaceId || ''))) return null;
448 return {
449 actionId: 'github.workspace.input.apply',
450 execute: async () => applyPendingInput({
451 pending,
452 text: String(payload?.text ?? ''),
453 file: payload?.file && typeof payload.file === 'object' ? payload.file : null
454 }, ownerFrom(context))
455 };
456 }
457 };
458 }