Personal Telegram developer console for GitHub

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