Personal Telegram developer console for GitHub

audit/pr-menu-consolidation
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 540 lines 30.7 KB
Raw
1 import { githubPluginManifest } from './manifest.js';
2 import { createWorkspaceController } from './workspace.js';
3
4 const CALLBACK_ACTIONS = Object.freeze([
5 ['files:', 'github.files.list'],
6 ['tree:', 'github.tree.read'],
7 ['blob:', 'github.blob.read'],
8 ['pr:', 'github.pr.list'],
9 ['commits:', 'github.commits.list'],
10 ['status:', 'github.status.read']
11 ]);
12
13 const escapeHtml = value => String(value ?? '')
14 .replaceAll('&', '&')
15 .replaceAll('<', '&lt;')
16 .replaceAll('>', '&gt;')
17 .replaceAll('"', '&quot;');
18
19 const short = (value, max = 80) => {
20 const text = String(value ?? '');
21 return text.length > max ? `${text.slice(0, max - 1)}…` : text;
22 };
23
24 const numericPair = (value, prefix) => {
25 const match = String(value || '').match(new RegExp(`^${prefix}:(\\d+):(\\d+)$`));
26 if (!match) return null;
27 return { repoId: Number(match[1]), runId: Number(match[2]) };
28 };
29
30 const numericTriple = (value, prefix) => {
31 const match = String(value || '').match(new RegExp(`^${prefix}:(\\d+):(\\d+):(\\d+)$`));
32 if (!match) return null;
33 return {
34 repoId: Number(match[1]),
35 itemId: Number(match[2]),
36 page: Math.max(1, Math.min(100, Number(match[3]) || 1))
37 };
38 };
39
40 const pagedPair = (value, prefix) => {
41 const match = String(value || '').match(new RegExp(`^${prefix}:(\\d+):(\\d+)(?::(\\d+))?$`));
42 if (!match) return null;
43 return {
44 repoId: Number(match[1]),
45 itemId: Number(match[2]),
46 page: Math.max(1, Math.min(100, Number(match[3]) || 1))
47 };
48 };
49
50 const numericSingle = (value, prefix) => {
51 const match = String(value || '').match(new RegExp(`^${prefix}:(\\d+)$`));
52 return match ? Number(match[1]) : null;
53 };
54
55 const pagedSingle = (value, prefix) => {
56 const match = String(value || '').match(new RegExp(`^${prefix}:(\\d+)(?::(\\d+))?$`));
57 if (!match) return null;
58 return {
59 repoId: Number(match[1]),
60 page: Math.max(1, Math.min(100, Number(match[2]) || 1))
61 };
62 };
63
64 const compareRef = value => {
65 const match = String(value || '').match(/^compare:(\d+):([a-f0-9]{40})$/i);
66 if (!match) return null;
67 return { repoId: Number(match[1]), sha: match[2] };
68 };
69
70 const commitDetailRef = value => {
71 const match = String(value || '').match(/^commitdetail:(\d+):([a-f0-9]{40})$/i);
72 if (!match) return null;
73 return { repoId: Number(match[1]), sha: match[2] };
74 };
75
76 const workflowRunsPage = value => pagedSingle(value, 'runs');
77
78 const runIcon = run => {
79 if (run.conclusion === 'success') return '✅';
80 if (run.conclusion === 'failure') return '❌';
81 if (run.conclusion === 'cancelled') return '⏹';
82 return run.status === 'in_progress' ? '🟡' : '⏳';
83 };
84
85 const stateIcon = value => {
86 if (value === 'success' || value === 'completed') return '✅';
87 if (value === 'failure') return '❌';
88 if (value === 'cancelled') return '⏹';
89 if (value === 'open') return '🟢';
90 if (value === 'closed') return '⚫';
91 return '•';
92 };
93
94 const addRepoAdvancedButtons = (view, repoId) => {
95 const rows = [...(view?.reply_markup?.inline_keyboard || [])];
96 const insertAt = Math.max(0, rows.length - 1);
97 rows.splice(insertAt, 0,
98 [{ text: '🧪 CI / Actions', callback_data: `runs:${repoId}` }],
99 [{ text: '🌿 Branches', callback_data: `branches:${repoId}` }],
100 [
101 { text: '🐛 Issues', callback_data: `issues:${repoId}` },
102 { text: '🏷 Releases', callback_data: `releases:${repoId}` }
103 ]
104 );
105 return {
106 ...view,
107 reply_markup: { ...(view?.reply_markup || {}), inline_keyboard: rows }
108 };
109 };
110
111 function listPagination(prefix, repoId, page, count, pageSize) {
112 const row = [];
113 if (page > 1) row.push({ text: '⬅️ جدیدتر', callback_data: `${prefix}:${repoId}:${page - 1}` });
114 if (count === pageSize && page < 100) row.push({ text: 'قدیمی‌تر ➡️', callback_data: `${prefix}:${repoId}:${page + 1}` });
115 return row.length ? [row] : [];
116 }
117
118 function explicitPagination(prefix, repoId, page, hasMore) {
119 const row = [];
120 if (page > 1) row.push({ text: '⬅️ جدیدتر', callback_data: `${prefix}:${repoId}:${page - 1}` });
121 if (hasMore && page < 100) row.push({ text: 'قدیمی‌تر ➡️', callback_data: `${prefix}:${repoId}:${page + 1}` });
122 return row.length ? [row] : [];
123 }
124
125 function pairPagination(prefix, repoId, itemId, page, count, pageSize) {
126 const row = [];
127 if (page > 1) row.push({ text: '⬅️ جدیدتر', callback_data: `${prefix}:${repoId}:${itemId}:${page - 1}` });
128 if (count === pageSize && page < 100) row.push({ text: 'قدیمی‌تر ➡️', callback_data: `${prefix}:${repoId}:${itemId}:${page + 1}` });
129 return row.length ? [row] : [];
130 }
131
132 async function commitsView(github, repoId) {
133 const [repo, commits] = await Promise.all([github.getRepository(repoId), github.listCommits(repoId)]);
134 const body = commits.length
135 ? commits.slice(0, 10).map(commit => `• <code>${escapeHtml(commit.shortSha || commit.sha)}</code> — ${escapeHtml(short(commit.message, 110))}\n ${escapeHtml(commit.author || 'Unknown')}${commit.date ? ` · ${escapeHtml(commit.date)}` : ''}`).join('\n\n')
136 : '<i>کامیتی در پاسخ GitHub یافت نشد.</i>';
137 const detailRows = commits.slice(0, 10).map(commit => {
138 const sha = String(commit.fullSha || commit.sha || '');
139 return /^[a-f0-9]{40}$/i.test(sha)
140 ? [{ text: `📝 ${short(commit.message || sha.slice(0, 7), 42)}`, callback_data: `commitdetail:${repoId}:${sha}` }]
141 : null;
142 }).filter(Boolean);
143 return {
144 text: `📝 <b>آخرین Commitهای ${escapeHtml(repo.name)}</b>\n➖➖➖➖➖➖➖➖➖➖\n${body}`,
145 reply_markup: { inline_keyboard: [
146 ...detailRows,
147 [{ text: '🔄 بروزرسانی', callback_data: `commits:${repoId}` }, { text: '🔙 پروژه', callback_data: `repo:${repoId}` }]
148 ] }
149 };
150 }
151
152 async function commitDetailView(github, repoId, sha) {
153 const [repo, commit] = await Promise.all([github.getRepository(repoId), github.getCommit(repoId, sha)]);
154 const files = (commit.files || []).slice(0, 12)
155 .map(file => `• <code>${escapeHtml(short(file.filename, 90))}</code> · ${escapeHtml(file.status || 'changed')} · +${file.additions ?? 0}/-${file.deletions ?? 0}`)
156 .join('\n');
157 return {
158 text: `📝 <b>Commit — ${escapeHtml(repo.name)}</b>\n<code>${escapeHtml(commit.shortSha || String(commit.sha).slice(0, 7))}</code> · ${escapeHtml(commit.author || 'Unknown')}\n${escapeHtml(commit.date || '-')}\n+${commit.additions ?? 0}/-${commit.deletions ?? 0} · ${commit.changedFiles ?? (commit.files || []).length} files\n➖➖➖➖➖➖➖➖➖➖\n${escapeHtml(short(commit.message || '', 1200)) || '<i>بدون پیام.</i>'}\n\n<b>فایل‌های تغییرکرده</b>\n${files || '<i>فایلی گزارش نشده است.</i>'}`,
159 reply_markup: { inline_keyboard: [[{ text: '🔄 بروزرسانی', callback_data: `commitdetail:${repoId}:${sha}` }, { text: '🔙 Commitها', callback_data: `commits:${repoId}` }], [{ text: '🔙 پروژه', callback_data: `repo:${repoId}` }]] }
160 };
161 }
162
163 async function workflowRunsView(github, repoId, page = 1) {
164 const [repo, runs] = await Promise.all([
165 github.getRepository(repoId),
166 github.listWorkflowRuns(repoId, { perPage: 10, page })
167 ]);
168 const body = runs.length
169 ? runs.slice(0, 10).map(run => `${runIcon(run)} <b>${escapeHtml(run.name)}</b> #${run.runNumber ?? '-'}\n └ ${escapeHtml(run.branch || '-')} · <code>${escapeHtml(run.sha || '-')}</code> · ${escapeHtml(run.conclusion || run.status || 'unknown')}`).join('\n\n')
170 : '<i>Workflow runی یافت نشد.</i>';
171 const refreshCallback = page === 1 ? `runs:${repoId}` : `runs:${repoId}:${page}`;
172 return {
173 text: `🧪 <b>CI / Actions — ${escapeHtml(repo.name)}</b>\nصفحه: <b>${page}</b>\n➖➖➖➖➖➖➖➖➖➖\n${body}`,
174 reply_markup: {
175 inline_keyboard: [
176 ...runs.slice(0, 10).map(run => [{
177 text: `${runIcon(run)} ${short(run.name, 32)} #${run.runNumber ?? run.id}`,
178 callback_data: `run:${repoId}:${run.id}`
179 }]),
180 ...listPagination('runs', repoId, page, runs.length, 10),
181 [
182 { text: '🔄 بروزرسانی', callback_data: refreshCallback },
183 { text: '🔙 پروژه', callback_data: `repo:${repoId}` }
184 ]
185 ]
186 }
187 };
188 }
189
190 async function workflowRunView(github, repoId, runId) {
191 const [repo, run] = await Promise.all([
192 github.getRepository(repoId),
193 github.getWorkflowRun(repoId, runId)
194 ]);
195 const rows = [
196 [
197 { text: '👷 Jobها', callback_data: `jobs:${repoId}:${runId}` },
198 { text: '📦 Artifacts', callback_data: `artifacts:${repoId}:${runId}` }
199 ]
200 ];
201 if (run.conclusion === 'failure') rows.push([{ text: '🔁 اجرای مجدد jobهای ناموفق', callback_data: `rerun:${repoId}:${runId}` }]);
202 if (run.status === 'in_progress' || run.status === 'queued') rows.push([{ text: '⏹ لغو Workflow', callback_data: `cancelrun:${repoId}:${runId}` }]);
203 rows.push([
204 { text: '🔄 بروزرسانی', callback_data: `run:${repoId}:${runId}` },
205 { text: '🔙 CI / Actions', callback_data: `runs:${repoId}` }
206 ]);
207 return {
208 text: `🧪 <b>${escapeHtml(run.name)} — ${escapeHtml(repo.name)}</b>\n➖➖➖➖➖➖➖➖➖➖\nوضعیت: ${runIcon(run)} <b>${escapeHtml(run.conclusion || run.status || 'unknown')}</b>\nRun: <code>#${escapeHtml(run.runNumber ?? run.id)}</code>\nBranch: <code>${escapeHtml(run.branch || '-')}</code>\nSHA: <code>${escapeHtml(run.sha || '-')}</code>\nTrigger: <code>${escapeHtml(run.event || '-')}</code>`,
209 reply_markup: { inline_keyboard: rows }
210 };
211 }
212
213 async function workflowJobsView(github, repoId, runId) {
214 const [repo, run, jobs] = await Promise.all([
215 github.getRepository(repoId),
216 github.getWorkflowRun(repoId, runId),
217 github.listWorkflowJobs(repoId, runId)
218 ]);
219 const body = jobs.length
220 ? jobs.slice(0, 20).map(job => {
221 const jobState = job.conclusion || job.status || 'unknown';
222 const steps = (job.steps || []).slice(0, 30)
223 .map(step => ` ${stateIcon(step.conclusion || step.status)} ${escapeHtml(step.name)} — ${escapeHtml(step.conclusion || step.status || 'unknown')}`)
224 .join('\n');
225 return `<b>${escapeHtml(job.name)}</b> — ${escapeHtml(jobState)}${steps ? `\n${steps}` : ''}`;
226 }).join('\n\n')
227 : '<i>Jobی در این Run یافت نشد.</i>';
228 return {
229 text: `👷 <b>Jobهای ${escapeHtml(run.name)} — ${escapeHtml(repo.name)}</b>\n➖➖➖➖➖➖➖➖➖➖\n${body}`,
230 reply_markup: {
231 inline_keyboard: [
232 ...jobs.slice(0, 20).map(job => [{ text: `${stateIcon(job.conclusion || job.status)} ${short(job.name, 40)}`, callback_data: `job:${repoId}:${job.id}` }]),
233 [{ text: '🔄 بروزرسانی', callback_data: `jobs:${repoId}:${runId}` }, { text: '🔙 Run', callback_data: `run:${repoId}:${runId}` }]
234 ]
235 }
236 };
237 }
238
239 async function workflowJobView(github, repoId, jobId) {
240 const [repo, job] = await Promise.all([github.getRepository(repoId), github.getWorkflowJob(repoId, jobId)]);
241 const status = job.conclusion || job.status || 'unknown';
242 const steps = (job.steps || []).slice(0, 30).map(step => `${stateIcon(step.conclusion || step.status)} ${escapeHtml(step.name)} — ${escapeHtml(step.conclusion || step.status || 'unknown')}`).join('\n');
243 const rows = [];
244 if (job.conclusion === 'failure') rows.push([{ text: '📜 مشاهده log ناموفق', callback_data: `joblog:${repoId}:${jobId}` }]);
245 rows.push([{ text: '🔄 بروزرسانی', callback_data: `job:${repoId}:${jobId}` }, { text: '🔙 CI / Actions', callback_data: `runs:${repoId}` }]);
246 return {
247 text: `👷 <b>${escapeHtml(job.name)} — ${escapeHtml(repo.name)}</b>\nوضعیت: ${stateIcon(status)} <b>${escapeHtml(status)}</b>\n➖➖➖➖➖➖➖➖➖➖\n${steps || '<i>Stepی ثبت نشده.</i>'}`,
248 reply_markup: { inline_keyboard: rows }
249 };
250 }
251
252 async function workflowJobLogView(github, repoId, jobId) {
253 const [job, log] = await Promise.all([
254 github.getWorkflowJob(repoId, jobId),
255 github.getWorkflowJobLog(repoId, jobId, { maxChars: 1800 })
256 ]);
257 const escaped = escapeHtml(log.text).slice(-3200);
258 const note = log.truncated ? '⚠️ فقط بخش پایانی log نمایش داده شده است.\n\n' : '';
259 return {
260 text: `📜 <b>Log — ${escapeHtml(job.name)}</b>\n${note}<pre>${escaped || '(empty log)'}</pre>`,
261 reply_markup: { inline_keyboard: [[{ text: '🔙 Job', callback_data: `job:${repoId}:${jobId}` }]] }
262 };
263 }
264
265 async function workflowArtifactsView(github, repoId, runId, page = 1) {
266 const [repo, artifacts] = await Promise.all([
267 github.getRepository(repoId),
268 github.listWorkflowArtifacts(repoId, runId, { perPage: 10, page })
269 ]);
270 const body = artifacts.length
271 ? artifacts.slice(0, 10).map(item => `📦 <b>${escapeHtml(item.name)}</b>\n ${item.expired ? 'منقضی شده' : 'فعال'} · ${Number(item.size || 0).toLocaleString()} bytes\n expires: ${escapeHtml(item.expiresAt || '-')}`).join('\n\n')
272 : '<i>Artifactی برای این Run یافت نشد.</i>';
273 const refreshCallback = page === 1 ? `artifacts:${repoId}:${runId}` : `artifacts:${repoId}:${runId}:${page}`;
274 return {
275 text: `📦 <b>Artifacts — ${escapeHtml(repo.name)}</b>\nصفحه: <b>${page}</b>\n➖➖➖➖➖➖➖➖➖➖\n${body}`,
276 reply_markup: { inline_keyboard: [...pairPagination('artifacts', repoId, runId, page, artifacts.length, 10), [{ text: '🔄 بروزرسانی', callback_data: refreshCallback }, { text: '🔙 Run', callback_data: `run:${repoId}:${runId}` }]] }
277 };
278 }
279
280 async function branchesView(github, repoId, page = 1) {
281 const [repo, branches] = await Promise.all([github.getRepository(repoId), github.listBranches(repoId, { perPage: 20, page })]);
282 const body = branches.length
283 ? branches.slice(0, 20).map(branch => `🌿 <b>${escapeHtml(short(branch.name, 70))}</b>\n <code>${escapeHtml(String(branch.sha).slice(0, 10))}</code>${branch.protected ? ' · 🛡 protected' : ''}`).join('\n\n')
284 : '<i>Branchی یافت نشد.</i>';
285 return {
286 text: `🌿 <b>Branches — ${escapeHtml(repo.name)}</b>\nصفحه: <b>${page}</b>\n➖➖➖➖➖➖➖➖➖➖\n${body}`,
287 reply_markup: { inline_keyboard: [
288 ...branches.slice(0, 20).filter(branch => /^[a-f0-9]{40}$/i.test(String(branch.sha))).map(branch => [{ text: `↔️ ${short(branch.name, 42)}`, callback_data: `compare:${repoId}:${branch.sha}` }]),
289 ...listPagination('branches', repoId, page, branches.length, 20),
290 [{ text: '🔙 پروژه', callback_data: `repo:${repoId}` }]
291 ] }
292 };
293 }
294
295 async function compareView(github, repoId, sha) {
296 const [repo, compare] = await Promise.all([github.getRepository(repoId), github.compareWithDefault(repoId, sha)]);
297 const files = (compare.files || []).slice(0, 12).map(file => `${stateIcon(file.status)} <code>${escapeHtml(short(file.filename, 90))}</code> · +${file.additions}/-${file.deletions}`).join('\n');
298 return {
299 text: `↔️ <b>Compare — ${escapeHtml(repo.name)}</b>\n<code>${escapeHtml(compare.base)}</code> ← <code>${escapeHtml(String(compare.head).slice(0, 10))}</code>\nوضعیت: <b>${escapeHtml(compare.status || '-')}</b>\nAhead: <b>${compare.aheadBy ?? 0}</b> · Behind: <b>${compare.behindBy ?? 0}</b> · Commits: <b>${compare.totalCommits ?? 0}</b>\n➖➖➖➖➖➖➖➖➖➖\n${files || '<i>فایل تغییریافته‌ای نیست.</i>'}`,
300 reply_markup: { inline_keyboard: [[{ text: '🔙 Branches', callback_data: `branches:${repoId}` }]] }
301 };
302 }
303
304 async function pullRequestsView(github, repoId, page = 1) {
305 const [repo, prs] = await Promise.all([github.getRepository(repoId), github.listPullRequests(repoId, { perPage: 10, page })]);
306 const body = prs.length
307 ? prs.slice(0, 10).map(pr => `${pr.merged ? '🟣' : stateIcon(pr.state)} <b>#${pr.number} ${escapeHtml(short(pr.title, 100))}</b>\n ${escapeHtml(pr.author)} · ${escapeHtml(pr.merged ? 'merged' : pr.state)}`).join('\n\n')
308 : '<i>Pull Requestی یافت نشد.</i>';
309 return {
310 text: `🔎 <b>Pull Requests — ${escapeHtml(repo.name)}</b>\nصفحه: <b>${page}</b>\n➖➖➖➖➖➖➖➖➖➖\n${body}`,
311 reply_markup: { inline_keyboard: [
312 ...prs.slice(0, 10).map(pr => [{ text: `#${pr.number} ${short(pr.title, 42)}`, callback_data: `prdetail:${repoId}:${pr.number}` }]),
313 ...listPagination('prs', repoId, page, prs.length, 10),
314 [{ text: '🔙 پروژه', callback_data: `repo:${repoId}` }]
315 ] }
316 };
317 }
318
319 async function pullRequestDetailView(github, repoId, prNumber) {
320 const [repo, pr] = await Promise.all([github.getRepository(repoId), github.getPullRequest(repoId, prNumber)]);
321 const body = escapeHtml(short(pr.body || '', 600));
322 return {
323 text: `🔎 <b>PR #${pr.number} — ${escapeHtml(repo.name)}</b>\n<b>${escapeHtml(pr.title)}</b>\n${pr.merged ? '🟣 merged' : `${stateIcon(pr.state)} ${escapeHtml(pr.state)}`} · ${escapeHtml(pr.author)}\n<code>${escapeHtml(pr.head || '-')}</code> → <code>${escapeHtml(pr.base || '-')}</code>\n+${pr.additions}/-${pr.deletions} · ${pr.changedFiles} files\n➖➖➖➖➖➖➖➖➖➖\n${body || '<i>بدون توضیح.</i>'}`,
324 reply_markup: { inline_keyboard: [[{ text: '🧩 فایل‌ها / Diff', callback_data: `prfiles:${repoId}:${prNumber}:1` }, { text: '✅ Checks', callback_data: `prchecks:${repoId}:${prNumber}:1` }], [{ text: '🔙 PRها', callback_data: `prs:${repoId}` }]] }
325 };
326 }
327
328 async function pullRequestFilesView(github, repoId, prNumber, page = 1) {
329 const files = await github.listPullRequestFiles(repoId, prNumber, { perPage: 8, page });
330 const body = files.length ? files.slice(0, 8).map(file => {
331 const patch = escapeHtml(short(file.patch || '', 220));
332 return `🧩 <code>${escapeHtml(short(file.filename, 100))}</code> · ${escapeHtml(file.status)} · +${file.additions}/-${file.deletions}${patch ? `\n<pre>${patch}</pre>` : ''}`;
333 }).join('\n\n') : '<i>فایل تغییریافته‌ای یافت نشد.</i>';
334 return {
335 text: `🧩 <b>PR #${prNumber} Files / Diff</b>\nصفحه: <b>${page}</b>\n➖➖➖➖➖➖➖➖➖➖\n${body}`,
336 reply_markup: { inline_keyboard: [...pairPagination('prfiles', repoId, prNumber, page, files.length, 8), [{ text: '🔙 PR', callback_data: `prdetail:${repoId}:${prNumber}` }]] }
337 };
338 }
339
340 async function pullRequestChecksView(github, repoId, prNumber, page = 1) {
341 const pr = await github.getPullRequest(repoId, prNumber);
342 const checks = await github.listCommitChecks(repoId, pr.headSha, { perPage: 20, page });
343 const body = checks.length
344 ? checks.slice(0, 20).map(check => `${stateIcon(check.conclusion || check.status)} <b>${escapeHtml(check.name)}</b> — ${escapeHtml(check.conclusion || check.status || 'unknown')}`).join('\n')
345 : '<i>Checkی یافت نشد.</i>';
346 return {
347 text: `✅ <b>PR #${prNumber} Checks</b>\nصفحه: <b>${page}</b>\n➖➖➖➖➖➖➖➖➖➖\n${body}`,
348 reply_markup: { inline_keyboard: [...pairPagination('prchecks', repoId, prNumber, page, checks.length, 20), [{ text: '🔙 PR', callback_data: `prdetail:${repoId}:${prNumber}` }]] }
349 };
350 }
351
352 async function issuesView(github, repoId, page = 1) {
353 const [repo, issuePage] = await Promise.all([github.getRepository(repoId), github.listIssuesPage(repoId, { page })]);
354 const issues = issuePage.items || [];
355 const body = issues.length
356 ? issues.slice(0, 20).map(issue => `${stateIcon(issue.state)} <b>#${issue.number} ${escapeHtml(short(issue.title, 110))}</b>\n ${escapeHtml(issue.author)} · ${issue.comments} comments`).join('\n\n')
357 : '<i>Issueی یافت نشد.</i>';
358 return {
359 text: `🐛 <b>Issues — ${escapeHtml(repo.name)}</b>\nصفحه: <b>${page}</b>\n➖➖➖➖➖➖➖➖➖➖\n${body}`,
360 reply_markup: { inline_keyboard: [
361 ...issues.slice(0, 20).map(issue => [{ text: `#${issue.number} ${short(issue.title, 42)}`, callback_data: `issuedetail:${repoId}:${issue.number}` }]),
362 ...explicitPagination('issues', repoId, page, !!issuePage.hasMore),
363 [{ text: '🔙 پروژه', callback_data: `repo:${repoId}` }]
364 ] }
365 };
366 }
367
368 async function issueDetailView(github, repoId, issueNumber) {
369 const [repo, issue] = await Promise.all([github.getRepository(repoId), github.getIssue(repoId, issueNumber)]);
370 const labels = (issue.labels || []).map(label => `#${escapeHtml(label)}`).join(' ');
371 const assignees = (issue.assignees || []).map(name => `@${escapeHtml(name)}`).join(' ');
372 const body = escapeHtml(short(issue.body || '', 1800));
373 return {
374 text: `🐛 <b>Issue #${issue.number} — ${escapeHtml(repo.name)}</b>\n<b>${escapeHtml(issue.title)}</b>\n${stateIcon(issue.state)} ${escapeHtml(issue.state || 'unknown')} · ${escapeHtml(issue.author)} · ${issue.comments ?? 0} comments\nLabels: ${labels || '-'}\nAssignees: ${assignees || '-'}\nUpdated: ${escapeHtml(issue.updatedAt || issue.createdAt || '-')}\n➖➖➖➖➖➖➖➖➖➖\n${body || '<i>بدون توضیح.</i>'}`,
375 reply_markup: { inline_keyboard: [[{ text: '🔄 بروزرسانی', callback_data: `issuedetail:${repoId}:${issueNumber}` }, { text: '🔙 Issues', callback_data: `issues:${repoId}` }]] }
376 };
377 }
378
379 async function releasesView(github, repoId, page = 1) {
380 const [repo, releases] = await Promise.all([github.getRepository(repoId), github.listReleases(repoId, { perPage: 10, page })]);
381 const body = releases.length
382 ? releases.slice(0, 10).map(release => `🏷 <b>${escapeHtml(release.tag || release.name)}</b>${release.prerelease ? ' · pre-release' : ''}${release.draft ? ' · draft' : ''}\n ${escapeHtml(short(release.name, 110))}\n ${escapeHtml(release.publishedAt || '-')}`).join('\n\n')
383 : '<i>هیچ Release منتشرشده‌ای برای این مخزن در GitHub وجود ندارد.</i>';
384 return {
385 text: `🏷 <b>Releases — ${escapeHtml(repo.name)}</b>\nصفحه: <b>${page}</b>\n➖➖➖➖➖➖➖➖➖➖\n${body}`,
386 reply_markup: { inline_keyboard: [
387 ...releases.slice(0, 10).map(release => [{ text: `🏷 ${short(release.tag || release.name, 42)}`, callback_data: `releasedetail:${repoId}:${release.id}` }]),
388 ...listPagination('releases', repoId, page, releases.length, 10),
389 [{ text: '🔙 پروژه', callback_data: `repo:${repoId}` }]
390 ] }
391 };
392 }
393
394 async function releaseDetailView(github, repoId, releaseId) {
395 const [repo, release] = await Promise.all([github.getRepository(repoId), github.getRelease(repoId, releaseId)]);
396 const body = escapeHtml(short(release.body || '', 1800));
397 const flags = [release.draft ? 'draft' : '', release.prerelease ? 'pre-release' : ''].filter(Boolean).join(' · ');
398 return {
399 text: `🏷 <b>${escapeHtml(release.name)} — ${escapeHtml(repo.name)}</b>\nTag: <code>${escapeHtml(release.tag || '-')}</code>\nTarget: <code>${escapeHtml(release.target || '-')}</code>\nAuthor: ${escapeHtml(release.author || 'unknown')}\nPublished: ${escapeHtml(release.publishedAt || '-')}${flags ? `\nState: ${escapeHtml(flags)}` : ''}\n➖➖➖➖➖➖➖➖➖➖\n${body || '<i>بدون Release notes.</i>'}`,
400 reply_markup: { inline_keyboard: [[{ text: '🔄 بروزرسانی', callback_data: `releasedetail:${repoId}:${releaseId}` }, { text: '🔙 Releases', callback_data: `releases:${repoId}` }]] }
401 };
402 }
403
404 function workflowActionResultView(repoId, runId, action) {
405 const rerun = action === 'rerun_failed';
406 return {
407 text: rerun ? '✅ درخواست اجرای مجدد jobهای ناموفق برای GitHub ارسال شد.' : '✅ درخواست لغو Workflow برای GitHub ارسال شد.',
408 reply_markup: { inline_keyboard: [[{ text: '🧪 مشاهده Run', callback_data: `run:${repoId}:${runId}` }, { text: '🔙 CI / Actions', callback_data: `runs:${repoId}` }]] }
409 };
410 }
411
412 function resolveReadCallback(data) {
413 const value = String(data || '');
414 if (value === 'menu:repos') return { actionId: 'github.repos.list', kind: 'legacy' };
415 const repoId = numericSingle(value, 'repo');
416 if (repoId !== null) return { actionId: 'github.repo.detail', kind: 'repo', repoId };
417 const commits = numericSingle(value, 'commits');
418 if (commits !== null) return { actionId: 'github.commits.list', kind: 'commits', repoId: commits };
419 const commitdetail = commitDetailRef(value);
420 if (commitdetail) return { actionId: 'github.commit.detail', kind: 'commitdetail', ...commitdetail };
421 const runs = workflowRunsPage(value);
422 if (runs) return { actionId: 'github.workflow.runs.list', kind: 'runs', ...runs };
423 const run = numericPair(value, 'run');
424 if (run) return { actionId: 'github.workflow.run.detail', kind: 'run', ...run };
425 const jobs = numericPair(value, 'jobs');
426 if (jobs) return { actionId: 'github.workflow.jobs.list', kind: 'jobs', ...jobs };
427 const job = numericPair(value, 'job');
428 if (job) return { actionId: 'github.workflow.job.detail', kind: 'job', repoId: job.repoId, jobId: job.runId };
429 const joblog = numericPair(value, 'joblog');
430 if (joblog) return { actionId: 'github.workflow.job.log', kind: 'joblog', repoId: joblog.repoId, jobId: joblog.runId };
431 const artifacts = pagedPair(value, 'artifacts');
432 if (artifacts) return { actionId: 'github.workflow.artifacts.list', kind: 'artifacts', repoId: artifacts.repoId, runId: artifacts.itemId, page: artifacts.page };
433 const branches = pagedSingle(value, 'branches');
434 if (branches) return { actionId: 'github.branches.list', kind: 'branches', ...branches };
435 const compare = compareRef(value);
436 if (compare) return { actionId: 'github.compare.read', kind: 'compare', ...compare };
437 const legacyPr = numericSingle(value, 'pr');
438 if (legacyPr !== null) return { actionId: 'github.pr.advanced.list', kind: 'prs', repoId: legacyPr, page: 1 };
439 const prs = pagedSingle(value, 'prs');
440 if (prs) return { actionId: 'github.pr.advanced.list', kind: 'prs', ...prs };
441 const prdetail = numericPair(value, 'prdetail');
442 if (prdetail) return { actionId: 'github.pr.detail', kind: 'prdetail', repoId: prdetail.repoId, prNumber: prdetail.runId };
443 const prfiles = numericTriple(value, 'prfiles');
444 if (prfiles) return { actionId: 'github.pr.files.list', kind: 'prfiles', repoId: prfiles.repoId, prNumber: prfiles.itemId, page: prfiles.page };
445 const prchecks = numericTriple(value, 'prchecks');
446 if (prchecks) return { actionId: 'github.pr.checks.list', kind: 'prchecks', repoId: prchecks.repoId, prNumber: prchecks.itemId, page: prchecks.page };
447 const issues = pagedSingle(value, 'issues');
448 if (issues) return { actionId: 'github.issues.list', kind: 'issues', ...issues };
449 const issuedetail = numericPair(value, 'issuedetail');
450 if (issuedetail) return { actionId: 'github.issue.detail', kind: 'issuedetail', repoId: issuedetail.repoId, issueNumber: issuedetail.runId };
451 const releases = pagedSingle(value, 'releases');
452 if (releases) return { actionId: 'github.releases.list', kind: 'releases', ...releases };
453 const releasedetail = numericPair(value, 'releasedetail');
454 if (releasedetail) return { actionId: 'github.release.detail', kind: 'releasedetail', repoId: releasedetail.repoId, releaseId: releasedetail.runId };
455 for (const [prefix, actionId] of CALLBACK_ACTIONS) {
456 if (value.startsWith(prefix)) return { actionId, kind: 'legacy' };
457 }
458 return null;
459 }
460
461 function resolveWriteCallback(data) {
462 const rerun = numericPair(data, 'rerun');
463 if (rerun) {
464 return {
465 actionId: 'github.workflow.run.rerun_failed',
466 approval: { input: rerun, label: 'اجرای مجدد jobهای ناموفق' },
467 execute: async github => {
468 await github.rerunFailedWorkflowRun(rerun.repoId, rerun.runId);
469 return workflowActionResultView(rerun.repoId, rerun.runId, 'rerun_failed');
470 }
471 };
472 }
473 const cancel = numericPair(data, 'cancelrun');
474 if (cancel) {
475 return {
476 actionId: 'github.workflow.run.cancel',
477 approval: { input: cancel, label: 'لغو Workflow در حال اجرا' },
478 execute: async github => {
479 await github.cancelWorkflowRun(cancel.repoId, cancel.runId);
480 return workflowActionResultView(cancel.repoId, cancel.runId, 'cancel');
481 }
482 };
483 }
484 return null;
485 }
486
487 export function createGitHubPlugin({ github, menu, workspaces } = {}) {
488 if (!github) throw new Error('GitHub plugin requires github service');
489 if (!menu) throw new Error('GitHub plugin requires menu manager');
490 const workspaceController = workspaces ? createWorkspaceController({ github, workspaces }) : null;
491
492 return {
493 manifest: githubPluginManifest,
494
495 resolveCommand(command) {
496 if (command !== '/repos') return null;
497 return { actionId: 'github.repos.list', execute: () => menu.getReposListView() };
498 },
499
500 resolveMessage(payload, context = {}) {
501 return workspaceController?.resolveMessage(payload, context) || null;
502 },
503
504 resolveCallback(data, context = {}) {
505 const write = resolveWriteCallback(data);
506 if (write) return { actionId: write.actionId, approval: write.approval, execute: () => write.execute(github) };
507
508 const workspaceRoute = workspaceController?.resolveCallback(data, context);
509 if (workspaceRoute) return workspaceRoute;
510
511 const read = resolveReadCallback(data);
512 if (!read) return null;
513 return {
514 actionId: read.actionId,
515 execute: async () => {
516 if (read.kind === 'repo') return addRepoAdvancedButtons(await menu.renderByCallback(data), read.repoId);
517 if (read.kind === 'commits') return typeof github.listCommits === 'function' ? commitsView(github, read.repoId) : menu.renderByCallback(data);
518 if (read.kind === 'commitdetail') return commitDetailView(github, read.repoId, read.sha);
519 if (read.kind === 'runs') return workflowRunsView(github, read.repoId, read.page);
520 if (read.kind === 'run') return workflowRunView(github, read.repoId, read.runId);
521 if (read.kind === 'jobs') return workflowJobsView(github, read.repoId, read.runId);
522 if (read.kind === 'job') return workflowJobView(github, read.repoId, read.jobId);
523 if (read.kind === 'joblog') return workflowJobLogView(github, read.repoId, read.jobId);
524 if (read.kind === 'artifacts') return workflowArtifactsView(github, read.repoId, read.runId, read.page);
525 if (read.kind === 'branches') return branchesView(github, read.repoId, read.page);
526 if (read.kind === 'compare') return compareView(github, read.repoId, read.sha);
527 if (read.kind === 'prs') return pullRequestsView(github, read.repoId, read.page);
528 if (read.kind === 'prdetail') return pullRequestDetailView(github, read.repoId, read.prNumber);
529 if (read.kind === 'prfiles') return pullRequestFilesView(github, read.repoId, read.prNumber, read.page);
530 if (read.kind === 'prchecks') return pullRequestChecksView(github, read.repoId, read.prNumber, read.page);
531 if (read.kind === 'issues') return issuesView(github, read.repoId, read.page);
532 if (read.kind === 'issuedetail') return issueDetailView(github, read.repoId, read.issueNumber);
533 if (read.kind === 'releases') return releasesView(github, read.repoId, read.page);
534 if (read.kind === 'releasedetail') return releaseDetailView(github, read.repoId, read.releaseId);
535 return menu.renderByCallback(data);
536 }
537 };
538 }
539 };
540 }