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