Personal Telegram developer console for GitHub

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