Personal Telegram developer console for GitHub

feat: complete GitHub Advanced read views (#19)

* docs: add GitHub Advanced read design * docs: add GitHub Advanced read plan * test: define GitHub Advanced read provider contract * feat: add bounded GitHub Advanced read APIs * fix: preserve GitHub read compatibility and log bounds * test: define GitHub Advanced plugin contract * feat: declare GitHub Advanced read actions * feat: add GitHub Advanced read navigation * docs: record accepted Safe Approval write smoke and GitHub Advanced progress * test: close Advanced read pagination gaps * test: require visible feedback for Advanced READ provider errors * fix: close Advanced read pagination gaps * fix: show Advanced read provider failures in Telegram * test: preserve issue pagination when GitHub mixes pull requests * fix: preserve issue pagination across mixed GitHub pages * fix: use provider page state for issue navigation * test: align issue fixture with paged provider contract * docs: record final GitHub Advanced read verification

davoodmehraban89 committed Oct 3, 2026 at 09:42 UTC ff270005fca1eda601df0a615ca81033c7340b3a
11 files changed +1093 -287
PROJECT_MEMORY.md
+67 -38
@@ -13,7 +13,7 @@
13 2. Prefer live evidence over chat memory.
14 3. Keep durable checkpoints here and never store secrets/tokens/private keys.
15 4. Do not call a phase production-accepted from CI alone; deployment and owner-device/runtime evidence are separate gates.
16 -5. Production WRITE actions must remain behind Safe Approval and durable one-time replay protection.
16 +5. Production WRITE / DESTRUCTIVE provider actions must remain behind Safe Approval and durable one-time replay protection.
17
18 ## Current Architecture
19 - Cloudflare Worker webhook boundary in `src/index.js`.
@@ -31,6 +31,7 @@
31 - Provider mutation never executes before policy approval.
32 - Provider errors are explicit; no fabricated success or fallback data.
33 - Secrets and signed approval callback tokens must not appear in logs/docs.
34 +- Telegram callback data and rendered provider text must remain bounded.
35
36 ## Production-Accepted Foundation
37 ### Plugin Foundation v1
@@ -43,53 +44,81 @@
44 - Deploy run `37095129406` succeeded; production Durable Object binding verified.
45 - CI/Actions pagination subsequently landed on `main` at `074033f5a067283727a38e034a6d19436fcce475`.
46
46 -### Approval rejection UX hardening
47 -- PR #17 merged at `2c131ea5fc564faae20cd7aff1ac00831f7fe185`.
48 -- Main CI #149 / run `37098697859` succeeded.
49 -- Deploy #84 / run `37098710348` succeeded on the exact merge SHA.
50 -- Active Cloudflare version after deploy: `e7182388-ca16-4aeb-b144-6d5f0fc63043` at 100% traffic.
51 -- Expired/replayed approvals now visibly update the Telegram message instead of appearing silent.
47 +### Approval and provider-error UX hardening
48 +- PR #17 merged at `2c131ea5fc564faae20cd7aff1ac00831f7fe185`; expired/replayed approvals now visibly update Telegram.
49 +- PR #18 merged at `a2e8a65763516765d47b535e514990f8698ad2a2`; approved provider failures now visibly update Telegram.
50 +- Main CI #155 / run `37099455730` succeeded with 82/82 tests.
51 +- Deploy #90 / run `37099465363` succeeded on the exact merge SHA.
52 +- Active Cloudflare production version after deploy: `1865c8ac-5d05-40cd-8478-8d9f5473e34b` at 100% traffic.
53
53 -## Live GitHub WRITE Smoke — 2026-10-03
54 +## Production Safe Approval WRITE Acceptance — 2026-10-03
55 Target:
56 - CI run #134, Actions run ID `37094321256`.
57
57 -Observed on production version `e7182388-ca16-4aeb-b144-6d5f0fc63043`:
58 -1. Owner requested `github.workflow.run.rerun_failed`.
59 -2. Audit: `approval_required` -> `approval_issued`.
60 -3. Owner pressed Confirm.
61 -4. Audit: `approval_verified` -> approved `action_attempt`.
62 -5. Provider result: `error` with `403 Resource not accessible by personal access token`.
63 -6. Owner pressed the same approval again; Durable replay guard rejected it as `Approval token already used`.
64 -7. GitHub run #134 remains `run_attempt=1`; therefore no rerun was accepted by GitHub.
58 +Verified sequence:
59 +1. An early owner approval reached the provider but GitHub returned `403 Resource not accessible by personal access token`; the same approval token was then replayed and correctly rejected as already used.
60 +2. The owner updated the existing fine-grained GitHub token permission so Actions has write access; no token value was stored or logged.
61 +3. A fresh owner request produced `approval_required` -> `approval_issued`.
62 +4. Owner pressed Confirm; production audit recorded `approval_verified` -> approved `action_attempt` with `owner_write_approved`.
63 +5. Production audit on Worker version `1865c8ac-5d05-40cd-8478-8d9f5473e34b` recorded `action_result=success` for `github.workflow.run.rerun_failed`.
64 +6. GitHub run #134 moved from `run_attempt=1` to `run_attempt=2`, proving the provider WRITE was accepted.
65 +7. Attempt 2 itself failed only because it reran the historical PR #15 merge ref from before the later Durable Object binding/config fix; this is historical-code behavior, not a current-main regression.
66
67 Conclusion:
67 -- Owner-bound approval path in production: VERIFIED.
68 -- Durable one-time replay protection in production: VERIFIED.
69 -- GitHub WRITE provider authorization: BLOCKED by current Worker `GITHUB_TOKEN` permissions.
70 -- For a fine-grained PAT, GitHub Actions repository permission must be `write` for rerun/cancel endpoints. A classic PAT requires appropriate private-repository `repo` scope.
71 -- Do not rotate or expose `GITHUB_TOKEN` automatically. Permission/credential change requires owner action.
72 -
73 -## Current Work
74 -### PR #18 — provider WRITE error feedback
75 -- Branch: `fix/provider-write-error-feedback`.
76 -- Purpose: after a valid approval, provider failures must visibly replace the approval message rather than silently return an error.
77 -- RED CI #150 / run `37099120240`: 18 test files, 82 tests, 81 pass / 1 expected failure in the new provider-error UI regression.
78 -- Implementation commit `75c9e540192ae3b42931329035002a95819f7163` adds Telegram feedback for approved provider failures while preserving one-time approval consumption.
79 -- CI #152 proved the implementation behavior but exposed a false-positive Persian test regex (`ناموفق` contains `موفق`).
80 -- Test correction commit `354f79c6f6f0b4372d85f30cf4ad8ece3e26944d` narrowed the success assertion.
81 -- CI #153 / run `37099346636`: 18 test files, 82 tests, 82 pass, 0 fail/skip/cancelled.
82 -- This file records the live permission blocker and current recovery path.
68 +- Owner-bound production approval: VERIFIED.
69 +- No provider WRITE before approval: VERIFIED.
70 +- Durable one-time replay protection: VERIFIED.
71 +- GitHub Actions WRITE authorization and provider POST: VERIFIED.
72 +- Telegram success feedback after accepted provider WRITE: VERIFIED.
73 +
74 +## Current Work — PR #19 GitHub Advanced READ
75 +- Branch: `feat/github-advanced-read`.
76 +- Design: `docs/superpowers/specs/2026-10-03-github-advanced-read-design.md`.
77 +- Plan: `docs/superpowers/plans/2026-10-03-github-advanced-read.md`.
78 +- Scope is READ-only: workflow job detail/log tail, artifacts metadata, branches/compare, PR detail/files/checks, issues, releases and bounded pagination. No new provider mutation is added in this slice.
79 +
80 +### TDD evidence
81 +- Provider RED CI #156 / run `37100585034`: 87 tests total, 82 pass / 5 expected failures for missing Advanced provider readers.
82 +- Provider compatibility fix followed after CI #157 exposed two regressions (log clamp and page-1 PR URL compatibility).
83 +- Provider GREEN CI #158 / run `37100892060`: 19 test files, 87/87 pass, 0 fail/skip/cancelled.
84 +- Plugin RED CI #159 / run `37100960176`: 92 tests total, 87 pass / 5 expected failures for undeclared/unimplemented Advanced routes and views.
85 +- Plugin GREEN CI #161 / run `37101099153`: 20 test files, 92/92 pass, 0 fail/skip/cancelled.
86 +- Review hardening RED CI #164 / run `37101390354`: 95 tests total, 92 pass / 3 expected failures for artifact pagination, PR diff pagination and visible READ-provider errors.
87 +- Review hardening GREEN CI #166 / run `37101635682`: 21 test files, 95/95 pass, 0 fail/skip/cancelled.
88 +- Mixed Issue/PR pagination RED CI #167 / run `37101783124`: 97 tests total, 95 pass / 2 expected failures.
89 +- Final GREEN CI #170 / run `37102060845` at head `9fbd33f3ad436c9519d521d704b6f7b882a2bbdd`: 22 test files, 97/97 pass, 0 fail/skip/cancelled.
90 +
91 +### Implemented in PR #19
92 +- Bounded raw workflow-job log tail with HTML escaping and visible truncation state.
93 +- Workflow job detail and per-job drill-down from run jobs.
94 +- Workflow artifact metadata view with bounded pagination.
95 +- Branch list and compare-to-default using a validated 40-hex head SHA.
96 +- Advanced PR list/detail/files-diff/checks views; PR diff page size matches rendered page size so files are not silently skipped.
97 +- Issues and releases views; Issue pagination preserves GitHub raw-page continuation even when PR entries are filtered out.
98 +- Pagination is clamped to page 1..100 and page size <=20 where list pagination is exposed.
99 +- New READ callbacks resolve without provider calls before central policy evaluation; callback lengths are regression-tested against Telegram limits.
100 +- READ provider failures now visibly update Telegram, including least-privilege guidance for provider 403, instead of appearing silent.
101 +
102 +### Review evidence
103 +- PR patch reviewed after hardening: no new provider mutation endpoint was added; only the pre-existing approval-gated workflow rerun/cancel POSTs remain.
104 +- Secret-pattern scan over the PR patch found no `ghp_` or `github_pat_` material.
105 +- Callback/data bounds, raw-log bounds, patch bounds and pagination gaps are regression-tested.
106 +
107 +### Not yet production-accepted
108 +- PR #19 is not merged at this checkpoint.
109 +- Exact post-merge `main` CI and Cloudflare deploy are NOT VERIFIED.
110 +- Owner-device production smoke for the new Advanced READ paths is NOT VERIFIED until after deploy.
111
112 ## Next Executable Actions
85 -1. Review PR #18, squash-merge, verify exact `main` CI/deploy and active Cloudflare version.
86 -2. Owner must update the Worker GitHub credential so `nexa-dev-bot` has GitHub Actions WRITE on the target repository; never paste the token into repository/docs/logs.
87 -3. Re-run the owner-device WRITE smoke through Telegram on run #134 (or another safe failed run).
88 -4. Acceptance requires: approval verified, provider POST accepted, `run_attempt` increases/new attempt appears, result visible in Telegram, replay still rejected.
89 -5. Only after provider WRITE smoke is green, continue the broader roadmap in verified vertical slices.
113 +1. Run one fresh final PR CI after this memory checkpoint, mark ready and squash-merge the exact reviewed head only if green.
114 +2. Verify exact post-merge `main` CI, deploy, active Cloudflare version and current-version telemetry.
115 +3. Perform owner-device READ smoke through Telegram for Branches/Compare, PR detail/files/checks, CI Run/Jobs/failed log/artifacts, Issues and Releases.
116 +4. If live Checks or Issues return 403, add only the specific missing fine-grained PAT READ permission; do not rotate the token unnecessarily.
117 +5. Then implement remaining GitHub Advanced WRITE items only where useful (workflow dispatch and/or specific-job rerun) as a separate Safe Approval slice.
118 +6. Continue to the Cloudflare Ops plugin and the broader roadmap.
119
120 ## Remaining Roadmap
92 -1. GitHub Advanced: logs, failed-step log view, artifacts metadata, branches/compare, PR detail/diff/checks, issues, releases, workflow dispatch where useful, bounded pagination.
121 +1. Finish GitHub Advanced production acceptance; add workflow dispatch/specific-job rerun only if operationally useful and always via Safe Approval.
122 2. Cloudflare Ops plugin: deployments, versions, bindings, health, telemetry/runtime errors and approval-gated rollback/deploy operations.
123 3. CI/CD Control Plane and release acceptance orchestration.
124 4. Monitoring + Incident Manager.
docs/superpowers/plans/2026-10-03-github-advanced-read.md new
+62
@@ -0,0 +1,62 @@
1 +# GitHub Advanced READ Implementation Plan
2 +
3 +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
4 +
5 +**Goal:** Add bounded, owner-only GitHub Advanced READ navigation for logs, artifacts, branches/compare, PR detail/checks, issues, and releases.
6 +
7 +**Architecture:** Extend the existing GitHub provider adapter with bounded readers, including a text reader for job logs, then expose them through the existing GitHub plugin and central READ policy. Keep callbacks compact and stateless; do not add provider writes in this slice.
8 +
9 +**Tech Stack:** Cloudflare Workers, Node.js 22 tests, GitHub REST API, Telegram inline callbacks.
10 +
11 +**Spec:** `docs/superpowers/specs/2026-10-03-github-advanced-read-design.md`
12 +
13 +## Global Constraints
14 +- Preserve `resolve -> policy -> execute` and owner-only READ policy.
15 +- No new WRITE/DESTRUCTIVE provider call in this slice.
16 +- Clamp growing list pagination to page 1..100 and page size <=20.
17 +- Bound logs/diff text before rendering to Telegram.
18 +- Keep callback_data compact and under Telegram limits.
19 +
20 +## Review Focus
21 +- Raw log responses that are not JSON must remain explicit and bounded.
22 +- Malformed numeric IDs / compare SHAs must fail closed at route resolution or provider validation.
23 +- Empty artifacts/issues/releases/checks render useful empty-state views.
24 +- Long branch/issue/release/patch text must not produce unbounded Telegram output.
25 +- New callbacks must not trigger GitHub calls before policy evaluation.
26 +
27 +---
28 +
29 +### Task 1: Provider READ APIs
30 +**Files:**
31 +- Modify: `src/github.js`
32 +- Test: `test/github-advanced-read.test.js`
33 +
34 +**Produces:** bounded methods for job detail/logs, artifacts, branches, compare, PR detail/files/checks, issues, and releases.
35 +
36 +- [ ] Write failing endpoint/mapping/bounds tests.
37 +- [ ] Run CI and confirm the new test fails before implementation.
38 +- [ ] Implement minimal provider readers plus `requestText`.
39 +- [ ] Run tests and require green.
40 +
41 +### Task 2: Plugin routes and views
42 +**Files:**
43 +- Modify: `src/plugins/github/manifest.js`
44 +- Modify: `src/plugins/github/plugin.js`
45 +- Test: `test/github-advanced-plugin.test.js`
46 +
47 +**Consumes:** Task 1 provider methods.
48 +**Produces:** compact READ callbacks and bounded Telegram views.
49 +
50 +- [ ] Write failing route/manifest/navigation/rendering tests.
51 +- [ ] Run tests and confirm RED.
52 +- [ ] Implement repository advanced navigation, job/log/artifact, branch/compare, PR detail/checks, issue and release views.
53 +- [ ] Run full suite and require green.
54 +
55 +### Task 3: Durable checkpoint and review
56 +**Files:**
57 +- Modify: `PROJECT_MEMORY.md`
58 +
59 +- [ ] Record the successful production WRITE smoke: run #134 attempt 1 -> 2 and Cloudflare `action_result=success`.
60 +- [ ] Record current branch scope and anything NOT VERIFIED.
61 +- [ ] Review diff for secret leakage, accidental provider writes, callback bounds, and out-of-scope changes.
62 +- [ ] Run fresh full CI, merge reviewed head, verify exact main CI/deploy and active Cloudflare version.
\ No newline at end of file
docs/superpowers/specs/2026-10-03-github-advanced-read-design.md new
+35
@@ -0,0 +1,35 @@
1 +# GitHub Advanced READ Design
2 +
3 +## Goal
4 +Complete the READ side of the GitHub Advanced roadmap without weakening the existing owner-only policy or Safe Approval boundary.
5 +
6 +## Scope
7 +Owner-only Telegram views for:
8 +- workflow job detail and bounded failed-job logs
9 +- workflow run artifact metadata
10 +- branches and compare-to-default
11 +- pull request detail, changed-file summary, and checks
12 +- issues
13 +- releases
14 +- bounded pagination where list size can grow
15 +
16 +## Non-goals
17 +- No new provider mutation in this slice.
18 +- Workflow dispatch and specific-job rerun remain separate WRITE slices behind Safe Approval.
19 +- No secret, token, binary artifact download, or full unbounded log/diff rendering.
20 +
21 +## Architecture
22 +Extend `GitHubService` with bounded REST readers and a text-response helper for job logs. Extend the GitHub plugin with compact numeric/SHA callbacks and Telegram views. All callbacks resolve to declared `READ` actions before provider calls, preserving `resolve -> policy -> execute`.
23 +
24 +## Bounds and safety
25 +- List pages: 10-20 items, page clamped to 1..100.
26 +- Logs: keep a bounded tail and escape HTML; never emit raw binary.
27 +- PR file patches: summarize/truncate per file; do not dump full diffs.
28 +- Compare callbacks carry a 40-hex commit SHA rather than arbitrary branch text to stay under Telegram callback limits.
29 +- Provider failures remain explicit.
30 +
31 +## Acceptance
32 +- New service/API tests cover endpoint shapes, pagination bounds, text log handling, and invalid identifiers.
33 +- Plugin tests prove side-effect-free route resolution, manifest risk declarations, compact callbacks, bounded rendering, and repository navigation.
34 +- Full CI green, reviewed PR merged, exact main CI/deploy green, production Cloudflare version verified.
35 +- Owner-device smoke for READ navigation is required before calling the slice production-accepted.
\ No newline at end of file
src/bot.js
+47
@@ -99,6 +99,30 @@ ${detail}
99 };
100 }
101
102 +function callbackReadFailedView(data, error) {
103 + const reason = String(error?.message || 'Provider read failed');
104 + const permissionDenied = /403|resource not accessible by personal access token/i.test(reason);
105 + const repoMatch = String(data || '').match(/^[^:]+:(\d+)/);
106 + const fallback = repoMatch ? `repo:${repoMatch[1]}` : 'menu:main';
107 + const detail = permissionDenied
108 + ? 'GitHub این درخواست خواندنی را با خطای 403 رد کرد. مجوز Read مربوط به این بخش در توکن فعلی کافی نیست.'
109 + : 'دریافت اطلاعات از سرویس با خطا مواجه شد. هیچ تغییری انجام نشد.';
110 +
111 + return {
112 + text:
113 +`⚠️ <b>دریافت اطلاعات با خطا مواجه شد</b>
114 +➖➖➖➖➖➖➖➖➖➖
115 +${detail}
116 +
117 +این خطا هیچ عملیات تغییردهنده‌ای اجرا نکرد.`,
118 + reply_markup: {
119 + inline_keyboard: [
120 + [{ text: repoMatch ? '↩️ بازگشت به پروژه' : '↩️ منوی اصلی', callback_data: fallback }]
121 + ]
122 + }
123 + };
124 +}
125 +
126 export class NexaDevBot {
127 constructor(env = {}) {
128 this.env = env;
@@ -323,6 +347,29 @@ export class NexaDevBot {
347 if (err.message && err.message.includes('message is not modified')) {
348 return { ok: true, unmodified: true, callbackAnswered };
349 }
350 +
351 + if (!data.startsWith('approve:')) {
352 + try {
353 + const view = callbackReadFailedView(data, err);
354 + const res = await this.telegram.editMessageText(
355 + chatId,
356 + messageId,
357 + view.text,
358 + view.reply_markup
359 + );
360 + return {
361 + ok: false,
362 + error: err.message,
363 + providerError: true,
364 + callbackAnswered,
365 + edited: true,
366 + res
367 + };
368 + } catch {
369 + // Preserve the original provider/navigation error when feedback delivery also fails.
370 + }
371 + }
372 +
373 return { ok: false, error: err.message, callbackAnswered };
374 }
375 }
src/github.js
+183 -186
@@ -1,5 +1,19 @@
1 import { DEFAULT_CONFIG } from './config.js';
2
3 +const clampPage = value => Math.max(1, Math.min(100, Number(value) || 1));
4 +const clampPerPage = (value, fallback = 10) => Math.max(1, Math.min(20, Number(value) || fallback));
5 +const boundedPatch = value => String(value || '').slice(0, 1200);
6 +const numericId = (value, label) => {
7 + const text = String(value ?? '');
8 + if (!/^\d+$/.test(text)) throw new Error(`Invalid ${label} ID`);
9 + return text;
10 +};
11 +const fullSha = (value, label = 'Git commit') => {
12 + const text = String(value || '');
13 + if (!/^[a-f0-9]{40}$/i.test(text)) throw new Error(`Invalid ${label} SHA`);
14 + return text;
15 +};
16 +
17 export class GitHubService {
18 constructor(token = '', owner = DEFAULT_CONFIG.defaultOwner) {
19 this.token = token;
@@ -8,9 +22,7 @@ export class GitHubService {
22 }
23
24 requireToken() {
11 - if (!this.token) {
12 - throw new Error('GITHUB_TOKEN is not configured');
13 - }
25 + if (!this.token) throw new Error('GITHUB_TOKEN is not configured');
26 }
27
28 getHeaders() {
@@ -30,125 +42,101 @@ export class GitHubService {
42 options.body = JSON.stringify(body);
43 options.headers = { ...headers, 'Content-Type': 'application/json' };
44 }
33 -
45 const res = await fetch(url, options);
46 const raw = await res.text();
47 let parsed = null;
48 if (raw) {
38 - try {
39 - parsed = JSON.parse(raw);
40 - } catch {
41 - parsed = null;
42 - }
49 + try { parsed = JSON.parse(raw); } catch { parsed = null; }
50 }
44 -
51 if (!res.ok) {
52 const providerMessage = parsed?.message || raw.slice(0, 240);
53 const detail = providerMessage ? ` ${providerMessage}` : '';
54 throw new Error(`${label} failed: ${res.status}${detail}`);
55 }
50 -
51 - if (allowEmpty) {
52 - return { accepted: true, status: res.status };
53 - }
54 -
56 + if (allowEmpty) return { accepted: true, status: res.status };
57 if (!raw) return null;
56 - if (parsed === null) {
57 - throw new Error(`${label} failed: invalid JSON response`);
58 - }
58 + if (parsed === null) throw new Error(`${label} failed: invalid JSON response`);
59 return parsed;
60 }
61
62 + async requestText(url, label, { maxChars = 12000 } = {}) {
63 + const res = await fetch(url, { method: 'GET', headers: this.getHeaders() });
64 + const raw = await res.text();
65 + if (!res.ok) {
66 + const detail = raw ? ` ${raw.slice(0, 240)}` : '';
67 + throw new Error(`${label} failed: ${res.status}${detail}`);
68 + }
69 + const limit = Math.max(1, Math.min(20000, Number(maxChars) || 12000));
70 + return { text: raw.length > limit ? raw.slice(-limit) : raw, truncated: raw.length > limit };
71 + }
72 +
73 repoUrl(repo, suffix = '') {
74 return `${this.baseUrl}/repos/${encodeURIComponent(this.owner)}/${encodeURIComponent(repo)}${suffix}`;
75 }
76
77 repositoryLookupUrl(repoRef) {
78 const value = String(repoRef || '');
68 - if (/^\d+$/.test(value)) {
69 - return `${this.baseUrl}/repositories/${value}`;
70 - }
71 - return this.repoUrl(value);
79 + return /^\d+$/.test(value) ? `${this.baseUrl}/repositories/${value}` : this.repoUrl(value);
80 }
81
82 repositoryApiBase(fullName) {
83 const parts = String(fullName || '').split('/').filter(Boolean);
76 - if (parts.length !== 2) {
77 - throw new Error('GitHub repository full_name is invalid');
78 - }
84 + if (parts.length !== 2) throw new Error('GitHub repository full_name is invalid');
85 return `${this.baseUrl}/repos/${parts.map(encodeURIComponent).join('/')}`;
86 }
87
88 async getRepositoryContext(repoRef) {
89 const raw = await this.requestJson(this.repositoryLookupUrl(repoRef), 'GitHub repository');
84 - return {
85 - raw,
86 - apiBase: this.repositoryApiBase(raw.full_name)
87 - };
90 + return { raw, apiBase: this.repositoryApiBase(raw.full_name) };
91 }
92
93 mapRepository(r) {
94 return {
92 - id: String(r.id ?? r.name),
93 - name: r.name,
94 - fullName: r.full_name,
95 - private: !!r.private,
96 - description: r.description || '',
97 - defaultBranch: r.default_branch || 'main',
98 - archived: !!r.archived,
99 - htmlUrl: r.html_url || '',
100 - stars: r.stargazers_count ?? 0,
101 - forks: r.forks_count ?? 0
95 + id: String(r.id ?? r.name), name: r.name, fullName: r.full_name, private: !!r.private,
96 + description: r.description || '', defaultBranch: r.default_branch || 'main', archived: !!r.archived,
97 + htmlUrl: r.html_url || '', stars: r.stargazers_count ?? 0, forks: r.forks_count ?? 0
98 };
99 }
100
101 mapWorkflowRun(run = {}) {
102 return {
107 - id: run.id,
108 - name: run.name || 'Workflow',
109 - status: run.status || '',
110 - conclusion: run.conclusion || null,
111 - event: run.event || '',
112 - branch: run.head_branch || '',
113 - sha: String(run.head_sha || '').slice(0, 7),
114 - runNumber: run.run_number ?? null,
115 - url: run.html_url || '',
116 - createdAt: run.created_at || '',
117 - updatedAt: run.updated_at || ''
103 + id: run.id, name: run.name || 'Workflow', status: run.status || '', conclusion: run.conclusion || null,
104 + event: run.event || '', branch: run.head_branch || '', sha: String(run.head_sha || '').slice(0, 7),
105 + runNumber: run.run_number ?? null, url: run.html_url || '', createdAt: run.created_at || '', updatedAt: run.updated_at || ''
106 };
107 }
108
109 mapWorkflowJob(job = {}) {
110 return {
123 - id: job.id,
124 - name: job.name || 'Job',
125 - status: job.status || '',
126 - conclusion: job.conclusion || null,
127 - startedAt: job.started_at || '',
128 - completedAt: job.completed_at || '',
129 - url: job.html_url || '',
111 + id: job.id, name: job.name || 'Job', status: job.status || '', conclusion: job.conclusion || null,
112 + startedAt: job.started_at || '', completedAt: job.completed_at || '', url: job.html_url || '',
113 steps: (job.steps || []).slice(0, 30).map(step => ({
131 - number: step.number,
132 - name: step.name || 'Step',
133 - status: step.status || '',
134 - conclusion: step.conclusion || null
114 + number: step.number, name: step.name || 'Step', status: step.status || '', conclusion: step.conclusion || null
115 }))
116 };
117 }
118
139 - async listRepositories() {
140 - const data = await this.requestJson(
141 - `${this.baseUrl}/user/repos?sort=updated&per_page=20&affiliation=owner,collaborator,organization_member`,
142 - 'GitHub repositories'
143 - );
119 + mapPullRequestFile(file = {}) {
120 + return {
121 + filename: file.filename || '', status: file.status || '', additions: file.additions ?? 0,
122 + deletions: file.deletions ?? 0, changes: file.changes ?? 0, patch: boundedPatch(file.patch)
123 + };
124 + }
125 +
126 + mapIssue(issue = {}) {
127 + return {
128 + number: issue.number,
129 + title: issue.title || '',
130 + state: issue.state || '',
131 + author: issue.user?.login || 'unknown',
132 + comments: issue.comments ?? 0,
133 + url: issue.html_url || ''
134 + };
135 + }
136
145 - return data.map(r => {
146 - const repo = this.mapRepository(r);
147 - return {
148 - ...repo,
149 - title: `${repo.name} ${repo.private ? '🔒' : '🌐'}`
150 - };
151 - });
137 + async listRepositories() {
138 + const data = await this.requestJson(`${this.baseUrl}/user/repos?sort=updated&per_page=20&affiliation=owner,collaborator,organization_member`, 'GitHub repositories');
139 + return data.map(r => { const repo = this.mapRepository(r); return { ...repo, title: `${repo.name} ${repo.private ? '🔒' : '🌐'}` }; });
140 }
141
142 async getRepository(repoRef) {
@@ -156,166 +144,175 @@ export class GitHubService {
144 return this.mapRepository(raw);
145 }
146
159 - async listPullRequests(repoRef) {
147 + async listPullRequests(repoRef, { perPage = 10, page = 1 } = {}) {
148 + const count = clampPerPage(perPage, 10);
149 + const pageNumber = clampPage(page);
150 + const pageQuery = pageNumber > 1 ? `&page=${pageNumber}` : '';
151 const { apiBase } = await this.getRepositoryContext(repoRef);
161 - const data = await this.requestJson(
162 - `${apiBase}/pulls?state=all&per_page=10`,
163 - 'GitHub pull requests'
164 - );
165 -
152 + const data = await this.requestJson(`${apiBase}/pulls?state=all&per_page=${count}${pageQuery}`, 'GitHub pull requests');
153 return data.map(pr => ({
167 - number: pr.number,
168 - title: pr.title,
169 - author: pr.user?.login || 'unknown',
170 - state: pr.state,
171 - merged: !!pr.merged_at,
172 - createdAt: pr.created_at,
173 - url: pr.html_url
154 + number: pr.number, title: pr.title, author: pr.user?.login || 'unknown', state: pr.state,
155 + merged: !!pr.merged_at, createdAt: pr.created_at, url: pr.html_url
156 }));
157 }
158
177 - async listCommits(repoRef) {
159 + async getPullRequest(repoRef, prNumber) {
160 + const number = numericId(prNumber, 'pull request');
161 const { apiBase } = await this.getRepositoryContext(repoRef);
179 - const data = await this.requestJson(
180 - `${apiBase}/commits?per_page=5`,
181 - 'GitHub commits'
182 - );
162 + const pr = await this.requestJson(`${apiBase}/pulls/${number}`, 'GitHub pull request');
163 + return {
164 + number: pr.number, title: pr.title || '', author: pr.user?.login || 'unknown', state: pr.state || '',
165 + merged: !!(pr.merged ?? pr.merged_at), body: pr.body || '', url: pr.html_url || '', head: pr.head?.ref || '',
166 + headSha: pr.head?.sha || '', base: pr.base?.ref || '', additions: pr.additions ?? 0,
167 + deletions: pr.deletions ?? 0, changedFiles: pr.changed_files ?? 0
168 + };
169 + }
170
171 + async listPullRequestFiles(repoRef, prNumber, { perPage = 20, page = 1 } = {}) {
172 + const number = numericId(prNumber, 'pull request');
173 + const count = clampPerPage(perPage, 20); const pageNumber = clampPage(page);
174 + const { apiBase } = await this.getRepositoryContext(repoRef);
175 + const data = await this.requestJson(`${apiBase}/pulls/${number}/files?per_page=${count}&page=${pageNumber}`, 'GitHub pull request files');
176 + return data.map(file => this.mapPullRequestFile(file));
177 + }
178 +
179 + async listCommits(repoRef) {
180 + const { apiBase } = await this.getRepositoryContext(repoRef);
181 + const data = await this.requestJson(`${apiBase}/commits?per_page=5`, 'GitHub commits');
182 return data.map(c => ({
185 - sha: c.sha.slice(0, 7),
186 - message: String(c.commit?.message || '').split('\n')[0],
187 - author: c.author?.login || c.commit?.author?.name || 'Unknown',
188 - date: c.commit?.author?.date ? c.commit.author.date.slice(0, 10) : ''
183 + sha: c.sha.slice(0, 7), message: String(c.commit?.message || '').split('\n')[0],
184 + author: c.author?.login || c.commit?.author?.name || 'Unknown', date: c.commit?.author?.date ? c.commit.author.date.slice(0, 10) : ''
185 }));
186 }
187
188 + async listCommitChecks(repoRef, sha, { perPage = 20, page = 1 } = {}) {
189 + const commitSha = fullSha(sha); const count = clampPerPage(perPage, 20); const pageNumber = clampPage(page);
190 + const { apiBase } = await this.getRepositoryContext(repoRef);
191 + const data = await this.requestJson(`${apiBase}/commits/${commitSha}/check-runs?per_page=${count}&page=${pageNumber}`, 'GitHub check runs');
192 + return (data.check_runs || []).map(check => ({ id: check.id, name: check.name || 'Check', status: check.status || '', conclusion: check.conclusion || null, url: check.html_url || '' }));
193 + }
194 +
195 async listFiles(repoRef, path = '') {
196 const { apiBase } = await this.getRepositoryContext(repoRef);
194 - const suffix = path
195 - ? `/contents/${path.split('/').map(encodeURIComponent).join('/')}`
196 - : '/contents';
197 + const suffix = path ? `/contents/${path.split('/').map(encodeURIComponent).join('/')}` : '/contents';
198 const data = await this.requestJson(`${apiBase}${suffix}`, 'GitHub contents');
198 -
199 - if (!Array.isArray(data)) {
200 - throw new Error('GitHub contents response is not a directory listing');
201 - }
202 -
203 - return data.map(item => ({
204 - name: item.name,
205 - path: item.path,
206 - type: item.type === 'dir' ? 'dir' : 'file',
207 - size: item.size ?? 0,
208 - sha: item.sha || ''
209 - }));
199 + if (!Array.isArray(data)) throw new Error('GitHub contents response is not a directory listing');
200 + return data.map(item => ({ name: item.name, path: item.path, type: item.type === 'dir' ? 'dir' : 'file', size: item.size ?? 0, sha: item.sha || '' }));
201 }
202
203 async listTree(repoRef, sha) {
213 - if (!/^[a-f0-9]{40}$/i.test(String(sha || ''))) {
214 - throw new Error('Invalid Git tree SHA');
215 - }
216 -
204 + if (!/^[a-f0-9]{40}$/i.test(String(sha || ''))) throw new Error('Invalid Git tree SHA');
205 const { apiBase } = await this.getRepositoryContext(repoRef);
218 - const data = await this.requestJson(
219 - `${apiBase}/git/trees/${encodeURIComponent(sha)}`,
220 - 'GitHub tree'
221 - );
222 -
223 - return (data.tree || [])
224 - .filter(item => item.type === 'tree' || item.type === 'blob')
225 - .map(item => ({
226 - name: item.path,
227 - path: item.path,
228 - type: item.type === 'tree' ? 'dir' : 'file',
229 - size: item.size ?? 0,
230 - sha: item.sha || ''
231 - }));
206 + const data = await this.requestJson(`${apiBase}/git/trees/${encodeURIComponent(sha)}`, 'GitHub tree');
207 + return (data.tree || []).filter(item => item.type === 'tree' || item.type === 'blob').map(item => ({
208 + name: item.path, path: item.path, type: item.type === 'tree' ? 'dir' : 'file', size: item.size ?? 0, sha: item.sha || ''
209 + }));
210 }
211
212 async getBlob(repoRef, sha) {
235 - if (!/^[a-f0-9]{40}$/i.test(String(sha || ''))) {
236 - throw new Error('Invalid Git blob SHA');
237 - }
238 -
213 + if (!/^[a-f0-9]{40}$/i.test(String(sha || ''))) throw new Error('Invalid Git blob SHA');
214 const { apiBase } = await this.getRepositoryContext(repoRef);
240 - const data = await this.requestJson(
241 - `${apiBase}/git/blobs/${encodeURIComponent(sha)}`,
242 - 'GitHub blob'
243 - );
244 -
245 - return {
246 - encoding: data.encoding || '',
247 - size: data.size ?? 0,
248 - content: data.content || ''
249 - };
215 + const data = await this.requestJson(`${apiBase}/git/blobs/${encodeURIComponent(sha)}`, 'GitHub blob');
216 + return { encoding: data.encoding || '', size: data.size ?? 0, content: data.content || '' };
217 }
218
219 async getRepoStatus(repoRef) {
220 const { raw, apiBase } = await this.getRepositoryContext(repoRef);
254 - const runsData = await this.requestJson(
255 - `${apiBase}/actions/runs?per_page=3`,
256 - 'GitHub Actions runs'
257 - );
258 -
221 + const runsData = await this.requestJson(`${apiBase}/actions/runs?per_page=3`, 'GitHub Actions runs');
222 const runs = runsData.workflow_runs || [];
223 return {
261 - repo: String(repoRef),
262 - repoName: raw.name,
263 - defaultBranch: raw.default_branch || 'main',
264 - lastRuns: runs.map(r => ({
265 - name: r.name,
266 - status: r.status,
267 - conclusion: r.conclusion,
268 - commit: r.head_commit?.message?.slice(0, 80) || '',
269 - url: r.html_url || ''
270 - }))
224 + repo: String(repoRef), repoName: raw.name, defaultBranch: raw.default_branch || 'main',
225 + lastRuns: runs.map(r => ({ name: r.name, status: r.status, conclusion: r.conclusion, commit: r.head_commit?.message?.slice(0, 80) || '', url: r.html_url || '' }))
226 };
227 }
228
229 async listWorkflowRuns(repoRef, { perPage = 10, page = 1 } = {}) {
275 - const count = Math.max(1, Math.min(20, Number(perPage) || 10));
276 - const pageNumber = Math.max(1, Math.min(100, Number(page) || 1));
230 + const count = clampPerPage(perPage, 10); const pageNumber = clampPage(page);
231 const { apiBase } = await this.getRepositoryContext(repoRef);
232 const pageQuery = pageNumber > 1 ? `&page=${pageNumber}` : '';
279 - const data = await this.requestJson(
280 - `${apiBase}/actions/runs?per_page=${count}${pageQuery}`,
281 - 'GitHub workflow runs'
282 - );
233 + const data = await this.requestJson(`${apiBase}/actions/runs?per_page=${count}${pageQuery}`, 'GitHub workflow runs');
234 return (data.workflow_runs || []).map(run => this.mapWorkflowRun(run));
235 }
236
237 async getWorkflowRun(repoRef, runId) {
287 - const { apiBase } = await this.getRepositoryContext(repoRef);
288 - const data = await this.requestJson(
289 - `${apiBase}/actions/runs/${encodeURIComponent(String(runId))}`,
290 - 'GitHub workflow run'
291 - );
292 - return this.mapWorkflowRun(data);
238 + const id = numericId(runId, 'workflow run'); const { apiBase } = await this.getRepositoryContext(repoRef);
239 + return this.mapWorkflowRun(await this.requestJson(`${apiBase}/actions/runs/${id}`, 'GitHub workflow run'));
240 }
241
242 async listWorkflowJobs(repoRef, runId) {
296 - const { apiBase } = await this.getRepositoryContext(repoRef);
297 - const data = await this.requestJson(
298 - `${apiBase}/actions/runs/${encodeURIComponent(String(runId))}/jobs?per_page=20`,
299 - 'GitHub workflow jobs'
300 - );
243 + const id = numericId(runId, 'workflow run'); const { apiBase } = await this.getRepositoryContext(repoRef);
244 + const data = await this.requestJson(`${apiBase}/actions/runs/${id}/jobs?per_page=20`, 'GitHub workflow jobs');
245 return (data.jobs || []).map(job => this.mapWorkflowJob(job));
246 }
247
304 - async rerunFailedWorkflowRun(repoRef, runId) {
248 + async getWorkflowJob(repoRef, jobId) {
249 + const id = numericId(jobId, 'workflow job'); const { apiBase } = await this.getRepositoryContext(repoRef);
250 + return this.mapWorkflowJob(await this.requestJson(`${apiBase}/actions/jobs/${id}`, 'GitHub workflow job'));
251 + }
252 +
253 + async getWorkflowJobLog(repoRef, jobId, { maxChars = 12000 } = {}) {
254 + const id = numericId(jobId, 'workflow job'); const { apiBase } = await this.getRepositoryContext(repoRef);
255 + return this.requestText(`${apiBase}/actions/jobs/${id}/logs`, 'GitHub workflow job log', { maxChars });
256 + }
257 +
258 + async listWorkflowArtifacts(repoRef, runId, { perPage = 20, page = 1 } = {}) {
259 + const id = numericId(runId, 'workflow run'); const count = clampPerPage(perPage, 20); const pageNumber = clampPage(page);
260 const { apiBase } = await this.getRepositoryContext(repoRef);
306 - return this.requestJson(
307 - `${apiBase}/actions/runs/${encodeURIComponent(String(runId))}/rerun-failed-jobs`,
308 - 'GitHub rerun failed jobs',
309 - { method: 'POST', allowEmpty: true }
310 - );
261 + const data = await this.requestJson(`${apiBase}/actions/runs/${id}/artifacts?per_page=${count}&page=${pageNumber}`, 'GitHub workflow artifacts');
262 + return (data.artifacts || []).map(artifact => ({
263 + id: artifact.id, name: artifact.name || 'Artifact', size: artifact.size_in_bytes ?? 0, expired: !!artifact.expired,
264 + createdAt: artifact.created_at || '', expiresAt: artifact.expires_at || '', downloadUrl: artifact.archive_download_url || ''
265 + }));
266 }
267
313 - async cancelWorkflowRun(repoRef, runId) {
268 + async listBranches(repoRef, { perPage = 20, page = 1 } = {}) {
269 + const count = clampPerPage(perPage, 20); const pageNumber = clampPage(page); const { apiBase } = await this.getRepositoryContext(repoRef);
270 + const data = await this.requestJson(`${apiBase}/branches?per_page=${count}&page=${pageNumber}`, 'GitHub branches');
271 + return data.map(branch => ({ name: branch.name || '', sha: branch.commit?.sha || '', protected: !!branch.protected }));
272 + }
273 +
274 + async compareWithDefault(repoRef, headSha) {
275 + const head = fullSha(headSha); const { raw, apiBase } = await this.getRepositoryContext(repoRef); const base = raw.default_branch || 'main';
276 + const data = await this.requestJson(`${apiBase}/compare/${encodeURIComponent(base)}...${head}`, 'GitHub compare');
277 + return {
278 + base, head, status: data.status || '', aheadBy: data.ahead_by ?? 0, behindBy: data.behind_by ?? 0,
279 + totalCommits: data.total_commits ?? 0, baseSha: data.base_commit?.sha || '', mergeBaseSha: data.merge_base_commit?.sha || '',
280 + files: (data.files || []).slice(0, 20).map(file => this.mapPullRequestFile(file))
281 + };
282 + }
283 +
284 + async listIssues(repoRef, { perPage = 10, page = 1 } = {}) {
285 + const count = clampPerPage(perPage, 10); const pageNumber = clampPage(page); const { apiBase } = await this.getRepositoryContext(repoRef);
286 + const data = await this.requestJson(`${apiBase}/issues?state=all&per_page=${count}&page=${pageNumber}`, 'GitHub issues');
287 + return data.filter(issue => !issue.pull_request).map(issue => this.mapIssue(issue));
288 + }
289 +
290 + async listIssuesPage(repoRef, { page = 1 } = {}) {
291 + const pageNumber = clampPage(page);
292 const { apiBase } = await this.getRepositoryContext(repoRef);
315 - return this.requestJson(
316 - `${apiBase}/actions/runs/${encodeURIComponent(String(runId))}/cancel`,
317 - 'GitHub cancel workflow run',
318 - { method: 'POST', allowEmpty: true }
319 - );
293 + const data = await this.requestJson(`${apiBase}/issues?state=all&per_page=20&page=${pageNumber}`, 'GitHub issues');
294 + return {
295 + items: data.filter(issue => !issue.pull_request).map(issue => this.mapIssue(issue)),
296 + hasMore: data.length === 20
297 + };
298 + }
299 +
300 + async listReleases(repoRef, { perPage = 10, page = 1 } = {}) {
301 + const count = clampPerPage(perPage, 10); const pageNumber = clampPage(page); const { apiBase } = await this.getRepositoryContext(repoRef);
302 + const data = await this.requestJson(`${apiBase}/releases?per_page=${count}&page=${pageNumber}`, 'GitHub releases');
303 + return data.map(release => ({
304 + id: release.id, tag: release.tag_name || '', name: release.name || release.tag_name || 'Release', draft: !!release.draft,
305 + prerelease: !!release.prerelease, publishedAt: release.published_at || release.created_at || '', url: release.html_url || ''
306 + }));
307 + }
308 +
309 + async rerunFailedWorkflowRun(repoRef, runId) {
310 + const id = numericId(runId, 'workflow run'); const { apiBase } = await this.getRepositoryContext(repoRef);
311 + return this.requestJson(`${apiBase}/actions/runs/${id}/rerun-failed-jobs`, 'GitHub rerun failed jobs', { method: 'POST', allowEmpty: true });
312 + }
313 +
314 + async cancelWorkflowRun(repoRef, runId) {
315 + const id = numericId(runId, 'workflow run'); const { apiBase } = await this.getRepositoryContext(repoRef);
316 + return this.requestJson(`${apiBase}/actions/runs/${id}/cancel`, 'GitHub cancel workflow run', { method: 'POST', allowEmpty: true });
317 }
318 }
src/plugins/github/manifest.js
+12 -1
@@ -1,7 +1,7 @@
1 export const githubPluginManifest = Object.freeze({
2 id: 'github',
3 name: 'GitHub',
4 - version: 2,
4 + version: 3,
5 commands: Object.freeze(['/repos']),
6 actions: Object.freeze({
7 'github.repos.list': Object.freeze({ risk: 'READ' }),
@@ -15,6 +15,17 @@ export const githubPluginManifest = Object.freeze({
15 'github.workflow.runs.list': Object.freeze({ risk: 'READ' }),
16 'github.workflow.run.detail': Object.freeze({ risk: 'READ' }),
17 'github.workflow.jobs.list': Object.freeze({ risk: 'READ' }),
18 + 'github.workflow.job.detail': Object.freeze({ risk: 'READ' }),
19 + 'github.workflow.job.log': Object.freeze({ risk: 'READ' }),
20 + 'github.workflow.artifacts.list': Object.freeze({ risk: 'READ' }),
21 + 'github.branches.list': Object.freeze({ risk: 'READ' }),
22 + 'github.compare.read': Object.freeze({ risk: 'READ' }),
23 + 'github.pr.advanced.list': Object.freeze({ risk: 'READ' }),
24 + 'github.pr.detail': Object.freeze({ risk: 'READ' }),
25 + 'github.pr.files.list': Object.freeze({ risk: 'READ' }),
26 + 'github.pr.checks.list': Object.freeze({ risk: 'READ' }),
27 + 'github.issues.list': Object.freeze({ risk: 'READ' }),
28 + 'github.releases.list': Object.freeze({ risk: 'READ' }),
29 'github.workflow.run.rerun_failed': Object.freeze({ risk: 'WRITE' }),
30 'github.workflow.run.cancel': Object.freeze({ risk: 'WRITE' })
31 })
src/plugins/github/plugin.js
+321 -62
@@ -15,24 +15,59 @@ const escapeHtml = value => String(value ?? '')
15 .replaceAll('>', '&gt;')
16 .replaceAll('"', '&quot;');
17
18 +const short = (value, max = 80) => {
19 + const text = String(value ?? '');
20 + return text.length > max ? `${text.slice(0, max - 1)}…` : text;
21 +};
22 +
23 const numericPair = (value, prefix) => {
24 const match = String(value || '').match(new RegExp(`^${prefix}:(\\d+):(\\d+)$`));
25 if (!match) return null;
26 return { repoId: Number(match[1]), runId: Number(match[2]) };
27 };
28
29 +const numericTriple = (value, prefix) => {
30 + const match = String(value || '').match(new RegExp(`^${prefix}:(\\d+):(\\d+):(\\d+)$`));
31 + if (!match) return null;
32 + return {
33 + repoId: Number(match[1]),
34 + itemId: Number(match[2]),
35 + page: Math.max(1, Math.min(100, Number(match[3]) || 1))
36 + };
37 +};
38 +
39 +const pagedPair = (value, prefix) => {
40 + const match = String(value || '').match(new RegExp(`^${prefix}:(\\d+):(\\d+)(?::(\\d+))?$`));
41 + if (!match) return null;
42 + return {
43 + repoId: Number(match[1]),
44 + itemId: Number(match[2]),
45 + page: Math.max(1, Math.min(100, Number(match[3]) || 1))
46 + };
47 +};
48 +
49 const numericSingle = (value, prefix) => {
50 const match = String(value || '').match(new RegExp(`^${prefix}:(\\d+)$`));
51 return match ? Number(match[1]) : null;
52 };
53
29 -const workflowRunsPage = value => {
30 - const match = String(value || '').match(/^runs:(\d+)(?::(\d+))?$/);
54 +const pagedSingle = (value, prefix) => {
55 + const match = String(value || '').match(new RegExp(`^${prefix}:(\\d+)(?::(\\d+))?$`));
56 + if (!match) return null;
57 + return {
58 + repoId: Number(match[1]),
59 + page: Math.max(1, Math.min(100, Number(match[2]) || 1))
60 + };
61 +};
62 +
63 +const compareRef = value => {
64 + const match = String(value || '').match(/^compare:(\d+):([a-f0-9]{40})$/i);
65 if (!match) return null;
32 - const page = Math.max(1, Math.min(100, Number(match[2]) || 1));
33 - return { repoId: Number(match[1]), page };
66 + return { repoId: Number(match[1]), sha: match[2] };
67 };
68
69 +const workflowRunsPage = value => pagedSingle(value, 'runs');
70 +
71 const runIcon = run => {
72 if (run.conclusion === 'success') return '✅';
73 if (run.conclusion === 'failure') return '❌';
@@ -40,20 +75,56 @@ const runIcon = run => {
75 return run.status === 'in_progress' ? '🟡' : '⏳';
76 };
77
43 -const addCiButton = (view, repoId) => {
78 +const stateIcon = value => {
79 + if (value === 'success' || value === 'completed') return '✅';
80 + if (value === 'failure') return '❌';
81 + if (value === 'cancelled') return '⏹';
82 + if (value === 'open') return '🟢';
83 + if (value === 'closed') return '⚫';
84 + return '•';
85 +};
86 +
87 +const addRepoAdvancedButtons = (view, repoId) => {
88 const rows = [...(view?.reply_markup?.inline_keyboard || [])];
45 - const ciRow = [{ text: '🧪 CI / Actions', callback_data: `runs:${repoId}` }];
89 const insertAt = Math.max(0, rows.length - 1);
47 - rows.splice(insertAt, 0, ciRow);
90 + rows.splice(insertAt, 0,
91 + [{ text: '🧪 CI / Actions', callback_data: `runs:${repoId}` }],
92 + [
93 + { text: '🌿 Branches', callback_data: `branches:${repoId}` },
94 + { text: '🔎 PRها', callback_data: `prs:${repoId}` }
95 + ],
96 + [
97 + { text: '🐛 Issues', callback_data: `issues:${repoId}` },
98 + { text: '🏷 Releases', callback_data: `releases:${repoId}` }
99 + ]
100 + );
101 return {
102 ...view,
50 - reply_markup: {
51 - ...(view?.reply_markup || {}),
52 - inline_keyboard: rows
53 - }
103 + reply_markup: { ...(view?.reply_markup || {}), inline_keyboard: rows }
104 };
105 };
106
107 +function listPagination(prefix, repoId, page, count, pageSize) {
108 + const row = [];
109 + if (page > 1) row.push({ text: '⬅️ جدیدتر', callback_data: `${prefix}:${repoId}:${page - 1}` });
110 + if (count === pageSize && page < 100) row.push({ text: 'قدیمی‌تر ➡️', callback_data: `${prefix}:${repoId}:${page + 1}` });
111 + return row.length ? [row] : [];
112 +}
113 +
114 +function explicitPagination(prefix, repoId, page, hasMore) {
115 + const row = [];
116 + if (page > 1) row.push({ text: '⬅️ جدیدتر', callback_data: `${prefix}:${repoId}:${page - 1}` });
117 + if (hasMore && page < 100) row.push({ text: 'قدیمی‌تر ➡️', callback_data: `${prefix}:${repoId}:${page + 1}` });
118 + return row.length ? [row] : [];
119 +}
120 +
121 +function pairPagination(prefix, repoId, itemId, page, count, pageSize) {
122 + const row = [];
123 + if (page > 1) row.push({ text: '⬅️ جدیدتر', callback_data: `${prefix}:${repoId}:${itemId}:${page - 1}` });
124 + if (count === pageSize && page < 100) row.push({ text: 'قدیمی‌تر ➡️', callback_data: `${prefix}:${repoId}:${itemId}:${page + 1}` });
125 + return row.length ? [row] : [];
126 +}
127 +
128 async function workflowRunsView(github, repoId, page = 1) {
129 const [repo, runs] = await Promise.all([
130 github.getRepository(repoId),
@@ -62,25 +133,16 @@ async function workflowRunsView(github, repoId, page = 1) {
133 const body = runs.length
134 ? 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')
135 : '<i>Workflow runی یافت نشد.</i>';
65 -
66 - const pagination = [];
67 - if (page > 1) {
68 - pagination.push({ text: '⬅️ جدیدتر', callback_data: `runs:${repoId}:${page - 1}` });
69 - }
70 - if (runs.length === 10 && page < 100) {
71 - pagination.push({ text: 'قدیمی‌تر ➡️', callback_data: `runs:${repoId}:${page + 1}` });
72 - }
136 const refreshCallback = page === 1 ? `runs:${repoId}` : `runs:${repoId}:${page}`;
74 -
137 return {
138 text: `🧪 <b>CI / Actions — ${escapeHtml(repo.name)}</b>\nصفحه: <b>${page}</b>\n➖➖➖➖➖➖➖➖➖➖\n${body}`,
139 reply_markup: {
140 inline_keyboard: [
141 ...runs.slice(0, 10).map(run => [{
80 - text: `${runIcon(run)} ${run.name} #${run.runNumber ?? run.id}`,
142 + text: `${runIcon(run)} ${short(run.name, 32)} #${run.runNumber ?? run.id}`,
143 callback_data: `run:${repoId}:${run.id}`
144 }]),
83 - ...(pagination.length ? [pagination] : []),
145 + ...listPagination('runs', repoId, page, runs.length, 10),
146 [
147 { text: '🔄 بروزرسانی', callback_data: refreshCallback },
148 { text: '🔙 پروژه', callback_data: `repo:${repoId}` }
@@ -96,7 +158,10 @@ async function workflowRunView(github, repoId, runId) {
158 github.getWorkflowRun(repoId, runId)
159 ]);
160 const rows = [
99 - [{ text: '👷 Jobها', callback_data: `jobs:${repoId}:${runId}` }]
161 + [
162 + { text: '👷 Jobها', callback_data: `jobs:${repoId}:${runId}` },
163 + { text: '📦 Artifacts', callback_data: `artifacts:${repoId}:${runId}` }
164 + ]
165 ];
166 if (run.conclusion === 'failure') {
167 rows.push([{ text: '🔁 اجرای مجدد jobهای ناموفق', callback_data: `rerun:${repoId}:${runId}` }]);
@@ -108,7 +173,6 @@ async function workflowRunView(github, repoId, runId) {
173 { text: '🔄 بروزرسانی', callback_data: `run:${repoId}:${runId}` },
174 { text: '🔙 CI / Actions', callback_data: `runs:${repoId}` }
175 ]);
111 -
176 return {
177 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>`,
178 reply_markup: { inline_keyboard: rows }
@@ -125,38 +189,207 @@ async function workflowJobsView(github, repoId, runId) {
189 ? jobs.slice(0, 20).map(job => {
190 const jobState = job.conclusion || job.status || 'unknown';
191 const steps = (job.steps || []).slice(0, 30)
128 - .map(step => ` ${step.conclusion === 'success' ? '✅' : step.conclusion === 'failure' ? '❌' : '•'} ${escapeHtml(step.name)} — ${escapeHtml(step.conclusion || step.status || 'unknown')}`)
192 + .map(step => ` ${stateIcon(step.conclusion || step.status)} ${escapeHtml(step.name)} — ${escapeHtml(step.conclusion || step.status || 'unknown')}`)
193 .join('\n');
194 return `<b>${escapeHtml(job.name)}</b> — ${escapeHtml(jobState)}${steps ? `\n${steps}` : ''}`;
195 }).join('\n\n')
196 : '<i>Jobی در این Run یافت نشد.</i>';
133 -
197 return {
198 text: `👷 <b>Jobهای ${escapeHtml(run.name)} — ${escapeHtml(repo.name)}</b>\n➖➖➖➖➖➖➖➖➖➖\n${body}`,
199 reply_markup: {
137 - inline_keyboard: [[
138 - { text: '🔄 بروزرسانی', callback_data: `jobs:${repoId}:${runId}` },
139 - { text: '🔙 Run', callback_data: `run:${repoId}:${runId}` }
140 - ]]
200 + inline_keyboard: [
201 + ...jobs.slice(0, 20).map(job => [{
202 + text: `${stateIcon(job.conclusion || job.status)} ${short(job.name, 40)}`,
203 + callback_data: `job:${repoId}:${job.id}`
204 + }]),
205 + [{ text: '🔄 بروزرسانی', callback_data: `jobs:${repoId}:${runId}` }, { text: '🔙 Run', callback_data: `run:${repoId}:${runId}` }]
206 + ]
207 }
208 };
209 }
210
145 -function workflowActionResultView(repoId, runId, action) {
146 - const rerun = action === 'rerun_failed';
211 +async function workflowJobView(github, repoId, jobId) {
212 + const [repo, job] = await Promise.all([github.getRepository(repoId), github.getWorkflowJob(repoId, jobId)]);
213 + const status = job.conclusion || job.status || 'unknown';
214 + 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');
215 + const rows = [];
216 + if (job.conclusion === 'failure') rows.push([{ text: '📜 مشاهده log ناموفق', callback_data: `joblog:${repoId}:${jobId}` }]);
217 + rows.push([{ text: '🔄 بروزرسانی', callback_data: `job:${repoId}:${jobId}` }, { text: '🔙 CI / Actions', callback_data: `runs:${repoId}` }]);
218 + return {
219 + text: `👷 <b>${escapeHtml(job.name)} — ${escapeHtml(repo.name)}</b>\nوضعیت: ${stateIcon(status)} <b>${escapeHtml(status)}</b>\n➖➖➖➖➖➖➖➖➖➖\n${steps || '<i>Stepی ثبت نشده.</i>'}`,
220 + reply_markup: { inline_keyboard: rows }
221 + };
222 +}
223 +
224 +async function workflowJobLogView(github, repoId, jobId) {
225 + const [job, log] = await Promise.all([
226 + github.getWorkflowJob(repoId, jobId),
227 + github.getWorkflowJobLog(repoId, jobId, { maxChars: 1800 })
228 + ]);
229 + const escaped = escapeHtml(log.text).slice(-3200);
230 + const note = log.truncated ? '⚠️ فقط بخش پایانی log نمایش داده شده است.\n\n' : '';
231 + return {
232 + text: `📜 <b>Log — ${escapeHtml(job.name)}</b>\n${note}<pre>${escaped || '(empty log)'}</pre>`,
233 + reply_markup: { inline_keyboard: [[{ text: '🔙 Job', callback_data: `job:${repoId}:${jobId}` }]] }
234 + };
235 +}
236 +
237 +async function workflowArtifactsView(github, repoId, runId, page = 1) {
238 + const [repo, artifacts] = await Promise.all([
239 + github.getRepository(repoId),
240 + github.listWorkflowArtifacts(repoId, runId, { perPage: 10, page })
241 + ]);
242 + const body = artifacts.length
243 + ? 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')
244 + : '<i>Artifactی برای این Run یافت نشد.</i>';
245 + const refreshCallback = page === 1 ? `artifacts:${repoId}:${runId}` : `artifacts:${repoId}:${runId}:${page}`;
246 return {
148 - text: rerun
149 - ? '✅ درخواست اجرای مجدد jobهای ناموفق برای GitHub ارسال شد.'
150 - : '✅ درخواست لغو Workflow برای GitHub ارسال شد.',
247 + text: `📦 <b>Artifacts — ${escapeHtml(repo.name)}</b>\nصفحه: <b>${page}</b>\n➖➖➖➖➖➖➖➖➖➖\n${body}`,
248 reply_markup: {
152 - inline_keyboard: [[
153 - { text: '🧪 مشاهده Run', callback_data: `run:${repoId}:${runId}` },
154 - { text: '🔙 CI / Actions', callback_data: `runs:${repoId}` }
155 - ]]
249 + inline_keyboard: [
250 + ...pairPagination('artifacts', repoId, runId, page, artifacts.length, 10),
251 + [{ text: '🔄 بروزرسانی', callback_data: refreshCallback }, { text: '🔙 Run', callback_data: `run:${repoId}:${runId}` }]
252 + ]
253 }
254 };
255 }
256
257 +async function branchesView(github, repoId, page = 1) {
258 + const [repo, branches] = await Promise.all([
259 + github.getRepository(repoId),
260 + github.listBranches(repoId, { perPage: 20, page })
261 + ]);
262 + const body = branches.length
263 + ? 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')
264 + : '<i>Branchی یافت نشد.</i>';
265 + return {
266 + text: `🌿 <b>Branches — ${escapeHtml(repo.name)}</b>\nصفحه: <b>${page}</b>\n➖➖➖➖➖➖➖➖➖➖\n${body}`,
267 + reply_markup: {
268 + inline_keyboard: [
269 + ...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}` }]),
270 + ...listPagination('branches', repoId, page, branches.length, 20),
271 + [{ text: '🔙 پروژه', callback_data: `repo:${repoId}` }]
272 + ]
273 + }
274 + };
275 +}
276 +
277 +async function compareView(github, repoId, sha) {
278 + const [repo, compare] = await Promise.all([github.getRepository(repoId), github.compareWithDefault(repoId, sha)]);
279 + 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');
280 + return {
281 + 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>'}`,
282 + reply_markup: { inline_keyboard: [[{ text: '🔙 Branches', callback_data: `branches:${repoId}` }]] }
283 + };
284 +}
285 +
286 +async function pullRequestsView(github, repoId, page = 1) {
287 + const [repo, prs] = await Promise.all([github.getRepository(repoId), github.listPullRequests(repoId, { perPage: 10, page })]);
288 + const body = prs.length
289 + ? 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')
290 + : '<i>Pull Requestی یافت نشد.</i>';
291 + return {
292 + text: `🔎 <b>Pull Requests — ${escapeHtml(repo.name)}</b>\nصفحه: <b>${page}</b>\n➖➖➖➖➖➖➖➖➖➖\n${body}`,
293 + reply_markup: {
294 + inline_keyboard: [
295 + ...prs.slice(0, 10).map(pr => [{ text: `#${pr.number} ${short(pr.title, 42)}`, callback_data: `prdetail:${repoId}:${pr.number}` }]),
296 + ...listPagination('prs', repoId, page, prs.length, 10),
297 + [{ text: '🔙 پروژه', callback_data: `repo:${repoId}` }]
298 + ]
299 + }
300 + };
301 +}
302 +
303 +async function pullRequestDetailView(github, repoId, prNumber) {
304 + const [repo, pr] = await Promise.all([github.getRepository(repoId), github.getPullRequest(repoId, prNumber)]);
305 + const body = escapeHtml(short(pr.body || '', 600));
306 + return {
307 + 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>'}`,
308 + reply_markup: {
309 + inline_keyboard: [
310 + [
311 + { text: '🧩 فایل‌ها / Diff', callback_data: `prfiles:${repoId}:${prNumber}:1` },
312 + { text: '✅ Checks', callback_data: `prchecks:${repoId}:${prNumber}:1` }
313 + ],
314 + [{ text: '🔙 PRها', callback_data: `prs:${repoId}` }]
315 + ]
316 + }
317 + };
318 +}
319 +
320 +async function pullRequestFilesView(github, repoId, prNumber, page = 1) {
321 + const files = await github.listPullRequestFiles(repoId, prNumber, { perPage: 8, page });
322 + const body = files.length ? files.slice(0, 8).map(file => {
323 + const patch = escapeHtml(short(file.patch || '', 220));
324 + return `🧩 <code>${escapeHtml(short(file.filename, 100))}</code> · ${escapeHtml(file.status)} · +${file.additions}/-${file.deletions}${patch ? `\n<pre>${patch}</pre>` : ''}`;
325 + }).join('\n\n') : '<i>فایل تغییریافته‌ای یافت نشد.</i>';
326 + return {
327 + text: `🧩 <b>PR #${prNumber} Files / Diff</b>\nصفحه: <b>${page}</b>\n➖➖➖➖➖➖➖➖➖➖\n${body}`,
328 + reply_markup: {
329 + inline_keyboard: [
330 + ...pairPagination('prfiles', repoId, prNumber, page, files.length, 8),
331 + [{ text: '🔙 PR', callback_data: `prdetail:${repoId}:${prNumber}` }]
332 + ]
333 + }
334 + };
335 +}
336 +
337 +async function pullRequestChecksView(github, repoId, prNumber, page = 1) {
338 + const pr = await github.getPullRequest(repoId, prNumber);
339 + const checks = await github.listCommitChecks(repoId, pr.headSha, { perPage: 20, page });
340 + const body = checks.length
341 + ? checks.slice(0, 20).map(check => `${stateIcon(check.conclusion || check.status)} <b>${escapeHtml(check.name)}</b> — ${escapeHtml(check.conclusion || check.status || 'unknown')}`).join('\n')
342 + : '<i>Checkی یافت نشد.</i>';
343 + return {
344 + text: `✅ <b>PR #${prNumber} Checks</b>\nصفحه: <b>${page}</b>\n➖➖➖➖➖➖➖➖➖➖\n${body}`,
345 + reply_markup: {
346 + inline_keyboard: [
347 + ...pairPagination('prchecks', repoId, prNumber, page, checks.length, 20),
348 + [{ text: '🔙 PR', callback_data: `prdetail:${repoId}:${prNumber}` }]
349 + ]
350 + }
351 + };
352 +}
353 +
354 +async function issuesView(github, repoId, page = 1) {
355 + const [repo, issuePage] = await Promise.all([
356 + github.getRepository(repoId),
357 + github.listIssuesPage(repoId, { page })
358 + ]);
359 + const issues = issuePage.items || [];
360 + const body = issues.length
361 + ? 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')
362 + : '<i>Issueی یافت نشد.</i>';
363 + return {
364 + text: `🐛 <b>Issues — ${escapeHtml(repo.name)}</b>\nصفحه: <b>${page}</b>\n➖➖➖➖➖➖➖➖➖➖\n${body}`,
365 + reply_markup: {
366 + inline_keyboard: [
367 + ...explicitPagination('issues', repoId, page, !!issuePage.hasMore),
368 + [{ text: '🔙 پروژه', callback_data: `repo:${repoId}` }]
369 + ]
370 + }
371 + };
372 +}
373 +
374 +async function releasesView(github, repoId, page = 1) {
375 + const [repo, releases] = await Promise.all([github.getRepository(repoId), github.listReleases(repoId, { perPage: 10, page })]);
376 + const body = releases.length
377 + ? 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')
378 + : '<i>Releaseی یافت نشد.</i>';
379 + return {
380 + text: `🏷 <b>Releases — ${escapeHtml(repo.name)}</b>\nصفحه: <b>${page}</b>\n➖➖➖➖➖➖➖➖➖➖\n${body}`,
381 + reply_markup: { inline_keyboard: [...listPagination('releases', repoId, page, releases.length, 10), [{ text: '🔙 پروژه', callback_data: `repo:${repoId}` }]] }
382 + };
383 +}
384 +
385 +function workflowActionResultView(repoId, runId, action) {
386 + const rerun = action === 'rerun_failed';
387 + return {
388 + text: rerun ? '✅ درخواست اجرای مجدد jobهای ناموفق برای GitHub ارسال شد.' : '✅ درخواست لغو Workflow برای GitHub ارسال شد.',
389 + reply_markup: { inline_keyboard: [[{ text: '🧪 مشاهده Run', callback_data: `run:${repoId}:${runId}` }, { text: '🔙 CI / Actions', callback_data: `runs:${repoId}` }]] }
390 + };
391 +}
392 +
393 function resolveReadCallback(data) {
394 const value = String(data || '');
395 if (value === 'menu:repos') return { actionId: 'github.repos.list', kind: 'legacy' };
@@ -173,6 +406,39 @@ function resolveReadCallback(data) {
406 const jobs = numericPair(value, 'jobs');
407 if (jobs) return { actionId: 'github.workflow.jobs.list', kind: 'jobs', ...jobs };
408
409 + const job = numericPair(value, 'job');
410 + if (job) return { actionId: 'github.workflow.job.detail', kind: 'job', repoId: job.repoId, jobId: job.runId };
411 +
412 + const joblog = numericPair(value, 'joblog');
413 + if (joblog) return { actionId: 'github.workflow.job.log', kind: 'joblog', repoId: joblog.repoId, jobId: joblog.runId };
414 +
415 + const artifacts = pagedPair(value, 'artifacts');
416 + if (artifacts) return { actionId: 'github.workflow.artifacts.list', kind: 'artifacts', repoId: artifacts.repoId, runId: artifacts.itemId, page: artifacts.page };
417 +
418 + const branches = pagedSingle(value, 'branches');
419 + if (branches) return { actionId: 'github.branches.list', kind: 'branches', ...branches };
420 +
421 + const compare = compareRef(value);
422 + if (compare) return { actionId: 'github.compare.read', kind: 'compare', ...compare };
423 +
424 + const prs = pagedSingle(value, 'prs');
425 + if (prs) return { actionId: 'github.pr.advanced.list', kind: 'prs', ...prs };
426 +
427 + const prdetail = numericPair(value, 'prdetail');
428 + if (prdetail) return { actionId: 'github.pr.detail', kind: 'prdetail', repoId: prdetail.repoId, prNumber: prdetail.runId };
429 +
430 + const prfiles = numericTriple(value, 'prfiles');
431 + if (prfiles) return { actionId: 'github.pr.files.list', kind: 'prfiles', repoId: prfiles.repoId, prNumber: prfiles.itemId, page: prfiles.page };
432 +
433 + const prchecks = numericTriple(value, 'prchecks');
434 + if (prchecks) return { actionId: 'github.pr.checks.list', kind: 'prchecks', repoId: prchecks.repoId, prNumber: prchecks.itemId, page: prchecks.page };
435 +
436 + const issues = pagedSingle(value, 'issues');
437 + if (issues) return { actionId: 'github.issues.list', kind: 'issues', ...issues };
438 +
439 + const releases = pagedSingle(value, 'releases');
440 + if (releases) return { actionId: 'github.releases.list', kind: 'releases', ...releases };
441 +
442 for (const [prefix, actionId] of CALLBACK_ACTIONS) {
443 if (value.startsWith(prefix)) return { actionId, kind: 'legacy' };
444 }
@@ -184,25 +450,18 @@ function resolveWriteCallback(data) {
450 if (rerun) {
451 return {
452 actionId: 'github.workflow.run.rerun_failed',
187 - approval: {
188 - input: rerun,
189 - label: 'اجرای مجدد jobهای ناموفق'
190 - },
453 + approval: { input: rerun, label: 'اجرای مجدد jobهای ناموفق' },
454 execute: async github => {
455 await github.rerunFailedWorkflowRun(rerun.repoId, rerun.runId);
456 return workflowActionResultView(rerun.repoId, rerun.runId, 'rerun_failed');
457 }
458 };
459 }
197 -
460 const cancel = numericPair(data, 'cancelrun');
461 if (cancel) {
462 return {
463 actionId: 'github.workflow.run.cancel',
202 - approval: {
203 - input: cancel,
204 - label: 'لغو Workflow در حال اجرا'
205 - },
464 + approval: { input: cancel, label: 'لغو Workflow در حال اجرا' },
465 execute: async github => {
466 await github.cancelWorkflowRun(cancel.repoId, cancel.runId);
467 return workflowActionResultView(cancel.repoId, cancel.runId, 'cancel');
@@ -221,21 +480,12 @@ export function createGitHubPlugin({ github, menu } = {}) {
480
481 resolveCommand(command) {
482 if (command !== '/repos') return null;
224 - return {
225 - actionId: 'github.repos.list',
226 - execute: () => menu.getReposListView()
227 - };
483 + return { actionId: 'github.repos.list', execute: () => menu.getReposListView() };
484 },
485
486 resolveCallback(data) {
487 const write = resolveWriteCallback(data);
232 - if (write) {
233 - return {
234 - actionId: write.actionId,
235 - approval: write.approval,
236 - execute: () => write.execute(github)
237 - };
238 - }
488 + if (write) return { actionId: write.actionId, approval: write.approval, execute: () => write.execute(github) };
489
490 const read = resolveReadCallback(data);
491 if (!read) return null;
@@ -243,12 +493,21 @@ export function createGitHubPlugin({ github, menu } = {}) {
493 return {
494 actionId: read.actionId,
495 execute: async () => {
246 - if (read.kind === 'repo') {
247 - return addCiButton(await menu.renderByCallback(data), read.repoId);
248 - }
496 + if (read.kind === 'repo') return addRepoAdvancedButtons(await menu.renderByCallback(data), read.repoId);
497 if (read.kind === 'runs') return workflowRunsView(github, read.repoId, read.page);
498 if (read.kind === 'run') return workflowRunView(github, read.repoId, read.runId);
499 if (read.kind === 'jobs') return workflowJobsView(github, read.repoId, read.runId);
500 + if (read.kind === 'job') return workflowJobView(github, read.repoId, read.jobId);
501 + if (read.kind === 'joblog') return workflowJobLogView(github, read.repoId, read.jobId);
502 + if (read.kind === 'artifacts') return workflowArtifactsView(github, read.repoId, read.runId, read.page);
503 + if (read.kind === 'branches') return branchesView(github, read.repoId, read.page);
504 + if (read.kind === 'compare') return compareView(github, read.repoId, read.sha);
505 + if (read.kind === 'prs') return pullRequestsView(github, read.repoId, read.page);
506 + if (read.kind === 'prdetail') return pullRequestDetailView(github, read.repoId, read.prNumber);
507 + if (read.kind === 'prfiles') return pullRequestFilesView(github, read.repoId, read.prNumber, read.page);
508 + if (read.kind === 'prchecks') return pullRequestChecksView(github, read.repoId, read.prNumber, read.page);
509 + if (read.kind === 'issues') return issuesView(github, read.repoId, read.page);
510 + if (read.kind === 'releases') return releasesView(github, read.repoId, read.page);
511 return menu.renderByCallback(data);
512 }
513 };
test/github-advanced-plugin.test.js new
+158
@@ -0,0 +1,158 @@
1 +import test from 'node:test';
2 +import assert from 'node:assert/strict';
3 +import { createGitHubPlugin } from '../src/plugins/github/plugin.js';
4 +import { githubPluginManifest } from '../src/plugins/github/manifest.js';
5 +
6 +const sha = 'a'.repeat(40);
7 +
8 +function callbacks(view) {
9 + return (view?.reply_markup?.inline_keyboard || []).flat().map(button => button.callback_data).filter(Boolean);
10 +}
11 +
12 +function makeGitHub() {
13 + const calls = [];
14 + const hit = (name, value) => { calls.push([name, value]); return value; };
15 + return {
16 + calls,
17 + async getRepository(id) { return hit('getRepository', { id: String(id), name: 'nexa-dev-bot', defaultBranch: 'main' }); },
18 + async listWorkflowRuns() { return []; },
19 + async getWorkflowRun(repo, run) { return hit('getWorkflowRun', { id: run, name: 'CI', status: 'completed', conclusion: 'failure', runNumber: 134, branch: 'main', sha: 'abc1234', event: 'push' }); },
20 + async listWorkflowJobs() { return hit('listWorkflowJobs', [{ id: 88, name: 'test', status: 'completed', conclusion: 'failure', steps: [{ number: 1, name: 'Run tests', conclusion: 'failure' }] }]); },
21 + async getWorkflowJob() { return hit('getWorkflowJob', { id: 88, name: 'test', status: 'completed', conclusion: 'failure', steps: [{ number: 1, name: 'Run tests', conclusion: 'failure' }] }); },
22 + async getWorkflowJobLog() { return hit('getWorkflowJobLog', { text: '<token>\nFAIL expected', truncated: true }); },
23 + async listWorkflowArtifacts() { return hit('listWorkflowArtifacts', [{ id: 9, name: 'coverage', size: 1234, expired: false, createdAt: '2026-10-03T00:00:00Z', expiresAt: '2026-10-10T00:00:00Z' }]); },
24 + async listBranches() { return hit('listBranches', [{ name: 'feature/x', sha, protected: false }]); },
25 + async compareWithDefault() { return hit('compareWithDefault', { base: 'main', head: sha, status: 'ahead', aheadBy: 2, behindBy: 0, totalCommits: 2, files: [{ filename: 'src/x.js', status: 'modified', additions: 3, deletions: 1, changes: 4, patch: '+x' }] }); },
26 + async listPullRequests() { return hit('listPullRequests', [{ number: 19, title: 'Feature', author: 'dev', state: 'open', merged: false }]); },
27 + async getPullRequest() { return hit('getPullRequest', { number: 19, title: 'Feature', author: 'dev', state: 'open', merged: false, body: 'Body', head: 'feature/x', headSha: sha, base: 'main', additions: 3, deletions: 1, changedFiles: 1 }); },
28 + async listPullRequestFiles() { return hit('listPullRequestFiles', [{ filename: 'src/x.js', status: 'modified', additions: 3, deletions: 1, changes: 4, patch: '+x' }]); },
29 + async listCommitChecks() { return hit('listCommitChecks', [{ id: 7, name: 'CI', status: 'completed', conclusion: 'success' }]); },
30 + async listIssues() { return hit('listIssues', [{ number: 4, title: 'Bug', state: 'open', author: 'u', comments: 2 }]); },
31 + async listIssuesPage() { return hit('listIssuesPage', { items: [{ number: 4, title: 'Bug', state: 'open', author: 'u', comments: 2 }], hasMore: false }); },
32 + async listReleases() { return hit('listReleases', [{ id: 6, tag: 'v1.2.0', name: 'Release 1.2', draft: false, prerelease: false, publishedAt: '2026-10-03T00:00:00Z' }]); },
33 + async rerunFailedWorkflowRun() {},
34 + async cancelWorkflowRun() {}
35 + };
36 +}
37 +
38 +function makeMenu() {
39 + return {
40 + async getReposListView() { return { text: 'repos', reply_markup: { inline_keyboard: [] } }; },
41 + async renderByCallback(data) {
42 + if (String(data).startsWith('repo:')) {
43 + return { text: 'repo', reply_markup: { inline_keyboard: [[{ text: 'back', callback_data: 'menu:repos' }]] } };
44 + }
45 + return { text: `legacy:${data}`, reply_markup: { inline_keyboard: [] } };
46 + }
47 + };
48 +}
49 +
50 +const advancedReadActions = [
51 + 'github.workflow.job.detail', 'github.workflow.job.log', 'github.workflow.artifacts.list',
52 + 'github.branches.list', 'github.compare.read', 'github.pr.advanced.list', 'github.pr.detail',
53 + 'github.pr.files.list', 'github.pr.checks.list', 'github.issues.list', 'github.releases.list'
54 +];
55 +
56 +test('GitHub Advanced manifest declares every new action as READ', () => {
57 + for (const actionId of advancedReadActions) assert.equal(githubPluginManifest.actions[actionId]?.risk, 'READ', actionId);
58 +});
59 +
60 +test('advanced callbacks resolve without provider side effects and callbacks stay Telegram-safe', async () => {
61 + const github = makeGitHub();
62 + const plugin = createGitHubPlugin({ github, menu: makeMenu() });
63 + const samples = [
64 + ['job:123:88', 'github.workflow.job.detail'],
65 + ['joblog:123:88', 'github.workflow.job.log'],
66 + ['artifacts:123:77', 'github.workflow.artifacts.list'],
67 + ['branches:123', 'github.branches.list'],
68 + [`compare:123:${sha}`, 'github.compare.read'],
69 + ['prs:123', 'github.pr.advanced.list'],
70 + ['prdetail:123:19', 'github.pr.detail'],
71 + ['prfiles:123:19:1', 'github.pr.files.list'],
72 + ['prchecks:123:19:1', 'github.pr.checks.list'],
73 + ['issues:123', 'github.issues.list'],
74 + ['releases:123', 'github.releases.list']
75 + ];
76 + for (const [data, actionId] of samples) {
77 + const route = plugin.resolveCallback(data);
78 + assert.equal(route?.actionId, actionId, data);
79 + assert.equal(github.calls.length, 0, `provider called during resolve: ${data}`);
80 + const view = await route.execute();
81 + for (const callback of callbacks(view)) assert.ok(callback.length <= 64, `${callback} exceeds Telegram callback_data limit`);
82 + github.calls.length = 0;
83 + }
84 +});
85 +
86 +test('repository and workflow views expose Advanced READ navigation', async () => {
87 + const github = makeGitHub();
88 + const plugin = createGitHubPlugin({ github, menu: makeMenu() });
89 + const repoView = await plugin.resolveCallback('repo:123').execute();
90 + const repoCallbacks = callbacks(repoView);
91 + for (const expected of ['runs:123', 'branches:123', 'prs:123', 'issues:123', 'releases:123']) assert.ok(repoCallbacks.includes(expected), expected);
92 +
93 + const runView = await plugin.resolveCallback('run:123:77').execute();
94 + assert.ok(callbacks(runView).includes('artifacts:123:77'));
95 +
96 + const jobsView = await plugin.resolveCallback('jobs:123:77').execute();
97 + assert.ok(callbacks(jobsView).includes('job:123:88'));
98 +
99 + const jobView = await plugin.resolveCallback('job:123:88').execute();
100 + assert.ok(callbacks(jobView).includes('joblog:123:88'));
101 +});
102 +
103 +test('failed job log is escaped and bounded-tail state is visible', async () => {
104 + const plugin = createGitHubPlugin({ github: makeGitHub(), menu: makeMenu() });
105 + const view = await plugin.resolveCallback('joblog:123:88').execute();
106 + assert.match(view.text, /&lt;token&gt;/);
107 + assert.doesNotMatch(view.text, /<token>/);
108 + assert.match(view.text, /انتهای log|بخش پایانی|truncated/i);
109 +});
110 +
111 +test('branches, PRs, issues and releases provide useful drill-down and pagination', async () => {
112 + const plugin = createGitHubPlugin({ github: makeGitHub(), menu: makeMenu() });
113 + const branchView = await plugin.resolveCallback('branches:123').execute();
114 + assert.ok(callbacks(branchView).includes(`compare:123:${sha}`));
115 +
116 + const prList = await plugin.resolveCallback('prs:123').execute();
117 + assert.ok(callbacks(prList).includes('prdetail:123:19'));
118 + const prDetail = await plugin.resolveCallback('prdetail:123:19').execute();
119 + assert.ok(callbacks(prDetail).includes('prfiles:123:19:1'));
120 + assert.ok(callbacks(prDetail).includes('prchecks:123:19:1'));
121 +
122 + const issues = await plugin.resolveCallback('issues:123').execute();
123 + assert.match(issues.text, /#4/);
124 + const releases = await plugin.resolveCallback('releases:123').execute();
125 + assert.match(releases.text, /v1\.2\.0/);
126 +});
127 +
128 +test('artifacts support bounded page navigation instead of silently stopping at the first page', async () => {
129 + const calls = [];
130 + const github = makeGitHub();
131 + github.listWorkflowArtifacts = async (repoId, runId, options) => {
132 + calls.push({ repoId, runId, options });
133 + return Array.from({ length: 10 }, (_, i) => ({ id: i + 1, name: `artifact-${i + 1}`, size: 1, expired: false }));
134 + };
135 + const plugin = createGitHubPlugin({ github, menu: makeMenu() });
136 + const route = plugin.resolveCallback('artifacts:123:77:2');
137 + assert.equal(route?.actionId, 'github.workflow.artifacts.list');
138 + const view = await route.execute();
139 + assert.deepEqual(calls[0], { repoId: 123, runId: 77, options: { perPage: 10, page: 2 } });
140 + assert.ok(callbacks(view).includes('artifacts:123:77:1'));
141 + assert.ok(callbacks(view).includes('artifacts:123:77:3'));
142 +});
143 +
144 +test('PR diff pages request only the number of files they can render and expose the next page', async () => {
145 + const calls = [];
146 + const github = makeGitHub();
147 + github.listPullRequestFiles = async (repoId, prNumber, options) => {
148 + calls.push({ repoId, prNumber, options });
149 + return Array.from({ length: 8 }, (_, i) => ({
150 + filename: `src/file-${i + 1}.js`, status: 'modified', additions: 1, deletions: 0, changes: 1, patch: '+x'
151 + }));
152 + };
153 + const plugin = createGitHubPlugin({ github, menu: makeMenu() });
154 + const view = await plugin.resolveCallback('prfiles:123:19:1').execute();
155 + assert.deepEqual(calls[0], { repoId: 123, prNumber: 19, options: { perPage: 8, page: 1 } });
156 + assert.match(view.text, /file-8\.js/);
157 + assert.ok(callbacks(view).includes('prfiles:123:19:2'));
158 +});
test/github-advanced-read-error-ui.test.js new
+34
@@ -0,0 +1,34 @@
1 +import test from 'node:test';
2 +import assert from 'node:assert/strict';
3 +import { NexaDevBot } from '../src/bot.js';
4 +
5 +test('Advanced READ provider failures visibly update Telegram instead of appearing silent', async () => {
6 + const bot = new NexaDevBot({
7 + TELEGRAM_BOT_TOKEN: 'telegram-test-token',
8 + TELEGRAM_WEBHOOK_SECRET: 'webhook-test-secret',
9 + GITHUB_TOKEN: 'github-test-token'
10 + });
11 + const edits = [];
12 + bot.telegram.answerCallbackQuery = async () => ({ ok: true });
13 + bot.telegram.editMessageText = async (chatId, messageId, text, replyMarkup) => {
14 + edits.push({ chatId, messageId, text, replyMarkup });
15 + return { ok: true };
16 + };
17 + bot.router.dispatchCallback = async () => {
18 + throw new Error('GitHub check runs failed: 403 Resource not accessible by personal access token');
19 + };
20 +
21 + const result = await bot.handleCallbackQuery({
22 + id: 'cb-read-error',
23 + data: 'prchecks:123:19:1',
24 + from: { id: 42 },
25 + message: { chat: { id: 42 }, message_id: 99 }
26 + });
27 +
28 + assert.equal(result.ok, false);
29 + assert.equal(result.edited, true);
30 + assert.equal(edits.length, 1);
31 + assert.match(edits[0].text, /دریافت اطلاعات|خطا/);
32 + assert.match(edits[0].text, /مجوز|دسترسی/);
33 + assert.doesNotMatch(edits[0].text, /github-test-token|telegram-test-token|webhook-test-secret/);
34 +});
test/github-advanced-read.test.js new
+113
@@ -0,0 +1,113 @@
1 +import test from 'node:test';
2 +import assert from 'node:assert/strict';
3 +import { GitHubService } from '../src/github.js';
4 +
5 +async function withFetch(mock, fn) {
6 + const originalFetch = globalThis.fetch;
7 + globalThis.fetch = mock;
8 + try { return await fn(); } finally { globalThis.fetch = originalFetch; }
9 +}
10 +
11 +function json(data, status = 200) {
12 + return new Response(JSON.stringify(data), { status, headers: { 'content-type': 'application/json' } });
13 +}
14 +
15 +const repo = {
16 + id: 123,
17 + name: 'nexa-dev-bot',
18 + full_name: 'davoodmehraban89/nexa-dev-bot',
19 + default_branch: 'main',
20 + private: true
21 +};
22 +
23 +const repoUrl = 'https://api.github.com/repos/davoodmehraban89/nexa-dev-bot';
24 +
25 +test('GitHub Advanced reads expose job detail and bounded raw job logs', async () => {
26 + const calls = [];
27 + await withFetch(async (url) => {
28 + const value = String(url); calls.push(value);
29 + if (value === 'https://api.github.com/repositories/123') return json(repo);
30 + if (value === `${repoUrl}/actions/jobs/88`) return json({ id: 88, name: 'test', status: 'completed', conclusion: 'failure', steps: [] });
31 + if (value === `${repoUrl}/actions/jobs/88/logs`) return new Response('0123456789ABCDEFGHIJ', { status: 200 });
32 + return json({ message: 'Not Found' }, 404);
33 + }, async () => {
34 + const service = new GitHubService('token');
35 + const job = await service.getWorkflowJob(123, 88);
36 + assert.equal(job.id, 88);
37 + const log = await service.getWorkflowJobLog(123, 88, { maxChars: 10 });
38 + assert.deepEqual(log, { text: 'ABCDEFGHIJ', truncated: true });
39 + assert.ok(calls.includes(`${repoUrl}/actions/jobs/88/logs`));
40 + });
41 +});
42 +
43 +test('GitHub Advanced reads list bounded workflow artifacts and branches', async () => {
44 + const calls = [];
45 + await withFetch(async (url) => {
46 + const value = String(url); calls.push(value);
47 + if (value === 'https://api.github.com/repositories/123') return json(repo);
48 + if (value === `${repoUrl}/actions/runs/77/artifacts?per_page=20&page=100`) return json({ artifacts: [{ id: 9, name: 'coverage', size_in_bytes: 1234, expired: false, created_at: '2026-10-03T00:00:00Z', expires_at: '2026-10-10T00:00:00Z', archive_download_url: 'https://api.github.com/a' }] });
49 + if (value === `${repoUrl}/branches?per_page=20&page=100`) return json([{ name: 'feature/x', commit: { sha: 'a'.repeat(40) }, protected: false }]);
50 + return json({ message: 'Not Found' }, 404);
51 + }, async () => {
52 + const service = new GitHubService('token');
53 + const artifacts = await service.listWorkflowArtifacts(123, 77, { perPage: 999, page: 999 });
54 + assert.deepEqual(artifacts[0], { id: 9, name: 'coverage', size: 1234, expired: false, createdAt: '2026-10-03T00:00:00Z', expiresAt: '2026-10-10T00:00:00Z', downloadUrl: 'https://api.github.com/a' });
55 + const branches = await service.listBranches(123, { perPage: 999, page: 999 });
56 + assert.deepEqual(branches[0], { name: 'feature/x', sha: 'a'.repeat(40), protected: false });
57 + });
58 +});
59 +
60 +test('GitHub compare validates a 40-hex head and returns bounded file summaries', async () => {
61 + const head = 'b'.repeat(40);
62 + await withFetch(async (url) => {
63 + const value = String(url);
64 + if (value === 'https://api.github.com/repositories/123') return json(repo);
65 + if (value === `${repoUrl}/compare/main...${head}`) return json({ status: 'ahead', ahead_by: 2, behind_by: 0, total_commits: 2, base_commit: { sha: 'a'.repeat(40) }, merge_base_commit: { sha: 'c'.repeat(40) }, files: [{ filename: 'src/x.js', status: 'modified', additions: 3, deletions: 1, changes: 4, patch: '+'.repeat(2000) }] });
66 + return json({ message: 'Not Found' }, 404);
67 + }, async () => {
68 + const service = new GitHubService('token');
69 + await assert.rejects(() => service.compareWithDefault(123, 'not-a-sha'), /SHA/i);
70 + const result = await service.compareWithDefault(123, head);
71 + assert.equal(result.base, 'main');
72 + assert.equal(result.head, head);
73 + assert.equal(result.aheadBy, 2);
74 + assert.ok(result.files[0].patch.length <= 1200);
75 + });
76 +});
77 +
78 +test('GitHub PR detail exposes files and checks with bounded pagination', async () => {
79 + const sha = 'd'.repeat(40);
80 + await withFetch(async (url) => {
81 + const value = String(url);
82 + if (value === 'https://api.github.com/repositories/123') return json(repo);
83 + if (value === `${repoUrl}/pulls/18`) return json({ number: 18, title: 'feat', state: 'open', merged: false, user: { login: 'dev' }, body: 'body', html_url: 'https://github.com/x/pull/18', head: { ref: 'feat/x', sha }, base: { ref: 'main' }, additions: 10, deletions: 2, changed_files: 1 });
84 + if (value === `${repoUrl}/pulls/18/files?per_page=20&page=100`) return json([{ filename: 'src/x.js', status: 'modified', additions: 10, deletions: 2, changes: 12, patch: '+'.repeat(2000) }]);
85 + if (value === `${repoUrl}/commits/${sha}/check-runs?per_page=20&page=100`) return json({ check_runs: [{ id: 7, name: 'CI', status: 'completed', conclusion: 'success', html_url: 'https://github.com/check/7' }] });
86 + return json({ message: 'Not Found' }, 404);
87 + }, async () => {
88 + const service = new GitHubService('token');
89 + const pr = await service.getPullRequest(123, 18);
90 + assert.equal(pr.headSha, sha);
91 + const files = await service.listPullRequestFiles(123, 18, { perPage: 999, page: 999 });
92 + assert.ok(files[0].patch.length <= 1200);
93 + const checks = await service.listCommitChecks(123, sha, { perPage: 999, page: 999 });
94 + assert.deepEqual(checks[0], { id: 7, name: 'CI', status: 'completed', conclusion: 'success', url: 'https://github.com/check/7' });
95 + });
96 +});
97 +
98 +test('GitHub issues exclude pull requests and releases are source-backed', async () => {
99 + await withFetch(async (url) => {
100 + const value = String(url);
101 + if (value === 'https://api.github.com/repositories/123') return json(repo);
102 + if (value === `${repoUrl}/issues?state=all&per_page=10&page=2`) return json([{ number: 4, title: 'bug', state: 'open', user: { login: 'u' }, comments: 2, html_url: 'https://github.com/i/4' }, { number: 5, title: 'pr', pull_request: {}, state: 'open' }]);
103 + if (value === `${repoUrl}/releases?per_page=10&page=2`) return json([{ id: 6, tag_name: 'v1.2.0', name: 'Release 1.2', draft: false, prerelease: false, published_at: '2026-10-03T00:00:00Z', html_url: 'https://github.com/r/6' }]);
104 + return json({ message: 'Not Found' }, 404);
105 + }, async () => {
106 + const service = new GitHubService('token');
107 + const issues = await service.listIssues(123, { page: 2 });
108 + assert.equal(issues.length, 1);
109 + assert.equal(issues[0].number, 4);
110 + const releases = await service.listReleases(123, { page: 2 });
111 + assert.equal(releases[0].tag, 'v1.2.0');
112 + });
113 +});
test/github-issues-pagination.test.js new
+61
@@ -0,0 +1,61 @@
1 +import test from 'node:test';
2 +import assert from 'node:assert/strict';
3 +import { GitHubService } from '../src/github.js';
4 +import { createGitHubPlugin } from '../src/plugins/github/plugin.js';
5 +
6 +const repo = {
7 + id: 123,
8 + name: 'nexa-dev-bot',
9 + full_name: 'davoodmehraban89/nexa-dev-bot',
10 + default_branch: 'main',
11 + private: true
12 +};
13 +
14 +function json(data, status = 200) {
15 + return new Response(JSON.stringify(data), { status, headers: { 'content-type': 'application/json' } });
16 +}
17 +
18 +test('GitHub issue page keeps raw-page hasMore even when pull requests are filtered out', async () => {
19 + const originalFetch = globalThis.fetch;
20 + globalThis.fetch = async url => {
21 + const value = String(url);
22 + if (value === 'https://api.github.com/repositories/123') return json(repo);
23 + if (value === 'https://api.github.com/repos/davoodmehraban89/nexa-dev-bot/issues?state=all&per_page=20&page=2') {
24 + const mixed = Array.from({ length: 20 }, (_, index) => index < 7
25 + ? { number: index + 1, title: `issue-${index + 1}`, state: 'open', user: { login: 'u' }, comments: 0 }
26 + : { number: index + 1, title: `pr-${index + 1}`, state: 'open', pull_request: {} });
27 + return json(mixed);
28 + }
29 + return json({ message: 'Not Found' }, 404);
30 + };
31 +
32 + try {
33 + const service = new GitHubService('token');
34 + const page = await service.listIssuesPage(123, { page: 2 });
35 + assert.equal(page.items.length, 7);
36 + assert.equal(page.hasMore, true);
37 + } finally {
38 + globalThis.fetch = originalFetch;
39 + }
40 +});
41 +
42 +test('Issues view shows older-page navigation from provider hasMore, not filtered item count', async () => {
43 + const github = {
44 + async getRepository() { return { id: '123', name: 'nexa-dev-bot', defaultBranch: 'main' }; },
45 + async listIssuesPage() {
46 + return {
47 + items: [{ number: 4, title: 'Bug', state: 'open', author: 'u', comments: 0 }],
48 + hasMore: true
49 + };
50 + }
51 + };
52 + const menu = {
53 + async getReposListView() { return { text: 'repos', reply_markup: { inline_keyboard: [] } }; },
54 + async renderByCallback() { return { text: 'legacy', reply_markup: { inline_keyboard: [] } }; }
55 + };
56 + const plugin = createGitHubPlugin({ github, menu });
57 + const view = await plugin.resolveCallback('issues:123:2').execute();
58 + const callbacks = view.reply_markup.inline_keyboard.flat().map(button => button.callback_data).filter(Boolean);
59 + assert.ok(callbacks.includes('issues:123:1'));
60 + assert.ok(callbacks.includes('issues:123:3'));
61 +});