claude-remote-cli 3.9.5 → 3.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/frontend/assets/index-BTOnhJQN.css +32 -0
- package/dist/frontend/assets/index-Dgf6cKGu.js +52 -0
- package/dist/frontend/index.html +2 -2
- package/dist/server/branch-linker.js +136 -0
- package/dist/server/config.js +31 -1
- package/dist/server/index.js +201 -2
- package/dist/server/integration-github.js +117 -0
- package/dist/server/integration-jira.js +177 -0
- package/dist/server/integration-linear.js +176 -0
- package/dist/server/org-dashboard.js +222 -0
- package/dist/server/review-poller.js +241 -0
- package/dist/server/sessions.js +43 -3
- package/dist/server/ticket-transitions.js +265 -0
- package/dist/test/branch-linker.test.js +231 -0
- package/dist/test/config.test.js +56 -0
- package/dist/test/integration-github.test.js +203 -0
- package/dist/test/integration-jira.test.js +302 -0
- package/dist/test/integration-linear.test.js +293 -0
- package/dist/test/org-dashboard.test.js +240 -0
- package/dist/test/review-poller.test.js +344 -0
- package/dist/test/ticket-transitions.test.js +470 -0
- package/package.json +1 -1
- package/dist/frontend/assets/index-BYv7-2w9.css +0 -32
- package/dist/frontend/assets/index-CO9tRKXI.js +0 -52
|
@@ -0,0 +1,240 @@
|
|
|
1
|
+
import { test, before, after } from 'node:test';
|
|
2
|
+
import assert from 'node:assert/strict';
|
|
3
|
+
import fs from 'node:fs';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import os from 'node:os';
|
|
6
|
+
import express from 'express';
|
|
7
|
+
import { createOrgDashboardRouter } from '../server/org-dashboard.js';
|
|
8
|
+
import { saveConfig, DEFAULTS } from '../server/config.js';
|
|
9
|
+
let tmpDir;
|
|
10
|
+
let configPath;
|
|
11
|
+
let server;
|
|
12
|
+
let baseUrl;
|
|
13
|
+
// A workspace path we can point git remote mocks at
|
|
14
|
+
const WORKSPACE_PATH_A = '/fake/workspace/repo-a';
|
|
15
|
+
const WORKSPACE_PATH_B = '/fake/workspace/repo-b';
|
|
16
|
+
/**
|
|
17
|
+
* Creates a mock execAsync that routes calls based on the command.
|
|
18
|
+
* - `git remote get-url origin` → returns configured remote URL or throws
|
|
19
|
+
* - `gh api user ...` → returns configured user login or throws
|
|
20
|
+
* - `gh api search/issues ...` → returns configured search response or throws
|
|
21
|
+
*/
|
|
22
|
+
function makeMockExec(opts) {
|
|
23
|
+
return async (cmd, args, options) => {
|
|
24
|
+
const command = cmd;
|
|
25
|
+
const argv = args;
|
|
26
|
+
if (command === 'git' && argv[0] === 'remote') {
|
|
27
|
+
const cwd = options.cwd ?? '';
|
|
28
|
+
const remote = opts.remotes?.[cwd];
|
|
29
|
+
if (remote)
|
|
30
|
+
return { stdout: remote + '\n', stderr: '' };
|
|
31
|
+
throw Object.assign(new Error('not a git repository'), { code: 128 });
|
|
32
|
+
}
|
|
33
|
+
if (command === 'gh' && argv[0] === 'api' && argv[1] === 'user') {
|
|
34
|
+
if (opts.userError)
|
|
35
|
+
throw opts.userError;
|
|
36
|
+
const login = opts.userLogin ?? 'testuser';
|
|
37
|
+
return { stdout: login + '\n', stderr: '' };
|
|
38
|
+
}
|
|
39
|
+
if (command === 'gh' && argv[0] === 'api' && argv[1]?.startsWith('search/issues')) {
|
|
40
|
+
if (opts.searchError)
|
|
41
|
+
throw opts.searchError;
|
|
42
|
+
const items = opts.searchItems ?? [];
|
|
43
|
+
return { stdout: JSON.stringify({ items }), stderr: '' };
|
|
44
|
+
}
|
|
45
|
+
throw new Error(`Unexpected exec call: ${command} ${argv.join(' ')}`);
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Builds a minimal GH search item for a given owner/repo and user.
|
|
50
|
+
*/
|
|
51
|
+
function makeSearchItem(overrides) {
|
|
52
|
+
const { ownerRepo, number = 1, title = 'Test PR', author = 'testuser', role = 'author', currentUser = 'testuser', } = overrides;
|
|
53
|
+
return {
|
|
54
|
+
number,
|
|
55
|
+
title,
|
|
56
|
+
html_url: `https://github.com/${ownerRepo}/pull/${number}`,
|
|
57
|
+
state: 'open',
|
|
58
|
+
user: { login: author },
|
|
59
|
+
pull_request: { head: { ref: 'feat/branch' }, base: { ref: 'main' } },
|
|
60
|
+
updated_at: '2026-03-21T00:00:00Z',
|
|
61
|
+
requested_reviewers: role === 'reviewer' ? [{ login: currentUser }] : [],
|
|
62
|
+
repository_url: `https://api.github.com/repos/${ownerRepo}`,
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
function startServer(execAsyncFn) {
|
|
66
|
+
return new Promise((resolve) => {
|
|
67
|
+
const app = express();
|
|
68
|
+
app.use(express.json());
|
|
69
|
+
// Cast through unknown: the mock satisfies the runtime contract but the
|
|
70
|
+
// overloaded promisify types don't align across module instances.
|
|
71
|
+
const deps = { configPath, execAsync: execAsyncFn };
|
|
72
|
+
app.use('/org-dashboard', createOrgDashboardRouter(deps));
|
|
73
|
+
server = app.listen(0, '127.0.0.1', () => {
|
|
74
|
+
const addr = server.address();
|
|
75
|
+
if (typeof addr === 'object' && addr) {
|
|
76
|
+
baseUrl = `http://127.0.0.1:${addr.port}`;
|
|
77
|
+
}
|
|
78
|
+
resolve();
|
|
79
|
+
});
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
function stopServer() {
|
|
83
|
+
return new Promise((resolve) => {
|
|
84
|
+
if (server)
|
|
85
|
+
server.close(() => resolve());
|
|
86
|
+
else
|
|
87
|
+
resolve();
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
async function getPrs() {
|
|
91
|
+
const res = await fetch(`${baseUrl}/org-dashboard/prs`);
|
|
92
|
+
return res.json();
|
|
93
|
+
}
|
|
94
|
+
before(() => {
|
|
95
|
+
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'org-dashboard-test-'));
|
|
96
|
+
configPath = path.join(tmpDir, 'config.json');
|
|
97
|
+
});
|
|
98
|
+
after(async () => {
|
|
99
|
+
await stopServer();
|
|
100
|
+
fs.rmSync(tmpDir, { recursive: true, force: true });
|
|
101
|
+
});
|
|
102
|
+
// Each test gets a fresh server with its own router (and thus its own cache).
|
|
103
|
+
// We stop/start the server around each test to reset the in-router cache state.
|
|
104
|
+
test('returns prs filtered to workspace repos', async () => {
|
|
105
|
+
await stopServer();
|
|
106
|
+
saveConfig(configPath, {
|
|
107
|
+
...DEFAULTS,
|
|
108
|
+
workspaces: [WORKSPACE_PATH_A, WORKSPACE_PATH_B],
|
|
109
|
+
});
|
|
110
|
+
const exec = makeMockExec({
|
|
111
|
+
remotes: {
|
|
112
|
+
[WORKSPACE_PATH_A]: 'git@github.com:myorg/repo-a.git',
|
|
113
|
+
[WORKSPACE_PATH_B]: 'git@github.com:myorg/repo-b.git',
|
|
114
|
+
},
|
|
115
|
+
userLogin: 'testuser',
|
|
116
|
+
searchItems: [
|
|
117
|
+
// Matches WORKSPACE_PATH_A
|
|
118
|
+
makeSearchItem({ ownerRepo: 'myorg/repo-a', number: 10, author: 'testuser' }),
|
|
119
|
+
// Matches WORKSPACE_PATH_B
|
|
120
|
+
makeSearchItem({ ownerRepo: 'myorg/repo-b', number: 20, author: 'testuser' }),
|
|
121
|
+
// Not in any workspace — should be excluded
|
|
122
|
+
makeSearchItem({ ownerRepo: 'myorg/other-repo', number: 30, author: 'testuser' }),
|
|
123
|
+
],
|
|
124
|
+
});
|
|
125
|
+
await startServer(exec);
|
|
126
|
+
const data = await getPrs();
|
|
127
|
+
assert.equal(data.error, undefined, `Unexpected error: ${data.error}`);
|
|
128
|
+
assert.equal(data.prs.length, 2, 'Should return only the 2 workspace-matched PRs');
|
|
129
|
+
const numbers = data.prs.map((p) => p.number).sort((a, b) => a - b);
|
|
130
|
+
assert.deepEqual(numbers, [10, 20]);
|
|
131
|
+
// Verify repoPath is attached
|
|
132
|
+
const pr10 = data.prs.find((p) => p.number === 10);
|
|
133
|
+
assert.equal(pr10?.repoPath, WORKSPACE_PATH_A);
|
|
134
|
+
});
|
|
135
|
+
test('returns gh_not_in_path error when gh not found', async () => {
|
|
136
|
+
await stopServer();
|
|
137
|
+
saveConfig(configPath, {
|
|
138
|
+
...DEFAULTS,
|
|
139
|
+
workspaces: [WORKSPACE_PATH_A],
|
|
140
|
+
});
|
|
141
|
+
const notFoundError = Object.assign(new Error('spawn gh ENOENT'), { code: 'ENOENT' });
|
|
142
|
+
const exec = makeMockExec({
|
|
143
|
+
remotes: { [WORKSPACE_PATH_A]: 'git@github.com:myorg/repo-a.git' },
|
|
144
|
+
userError: notFoundError,
|
|
145
|
+
});
|
|
146
|
+
await startServer(exec);
|
|
147
|
+
const data = await getPrs();
|
|
148
|
+
assert.equal(data.error, 'gh_not_in_path');
|
|
149
|
+
assert.equal(data.prs.length, 0);
|
|
150
|
+
});
|
|
151
|
+
test('returns gh_not_authenticated error', async () => {
|
|
152
|
+
await stopServer();
|
|
153
|
+
saveConfig(configPath, {
|
|
154
|
+
...DEFAULTS,
|
|
155
|
+
workspaces: [WORKSPACE_PATH_A],
|
|
156
|
+
});
|
|
157
|
+
const authError = new Error('You are not logged into any GitHub hosts. Run gh auth login to authenticate.');
|
|
158
|
+
const exec = makeMockExec({
|
|
159
|
+
remotes: { [WORKSPACE_PATH_A]: 'git@github.com:myorg/repo-a.git' },
|
|
160
|
+
userError: authError,
|
|
161
|
+
});
|
|
162
|
+
await startServer(exec);
|
|
163
|
+
const data = await getPrs();
|
|
164
|
+
assert.equal(data.error, 'gh_not_authenticated');
|
|
165
|
+
assert.equal(data.prs.length, 0);
|
|
166
|
+
});
|
|
167
|
+
test('returns empty prs with no_workspaces error when workspaces is empty', async () => {
|
|
168
|
+
await stopServer();
|
|
169
|
+
saveConfig(configPath, {
|
|
170
|
+
...DEFAULTS,
|
|
171
|
+
workspaces: [],
|
|
172
|
+
});
|
|
173
|
+
// execAsync should never be called here — pass a mock that always throws to
|
|
174
|
+
// verify the early-return path triggers before any exec
|
|
175
|
+
const exec = makeMockExec({});
|
|
176
|
+
await startServer(exec);
|
|
177
|
+
const data = await getPrs();
|
|
178
|
+
assert.equal(data.error, 'no_workspaces');
|
|
179
|
+
assert.equal(data.prs.length, 0);
|
|
180
|
+
});
|
|
181
|
+
test('detects reviewer role when current user is in requested_reviewers but not the author', async () => {
|
|
182
|
+
await stopServer();
|
|
183
|
+
saveConfig(configPath, {
|
|
184
|
+
...DEFAULTS,
|
|
185
|
+
workspaces: [WORKSPACE_PATH_A],
|
|
186
|
+
});
|
|
187
|
+
// PR authored by someone else; testuser is a requested reviewer
|
|
188
|
+
const reviewerItem = makeSearchItem({
|
|
189
|
+
ownerRepo: 'myorg/repo-a',
|
|
190
|
+
number: 42,
|
|
191
|
+
title: 'Review me',
|
|
192
|
+
author: 'otheruser',
|
|
193
|
+
role: 'reviewer',
|
|
194
|
+
currentUser: 'testuser',
|
|
195
|
+
});
|
|
196
|
+
const exec = makeMockExec({
|
|
197
|
+
remotes: { [WORKSPACE_PATH_A]: 'git@github.com:myorg/repo-a.git' },
|
|
198
|
+
userLogin: 'testuser',
|
|
199
|
+
searchItems: [reviewerItem],
|
|
200
|
+
});
|
|
201
|
+
await startServer(exec);
|
|
202
|
+
const data = await getPrs();
|
|
203
|
+
assert.equal(data.error, undefined, `Unexpected error: ${data.error}`);
|
|
204
|
+
assert.equal(data.prs.length, 1, 'Should return the reviewer PR');
|
|
205
|
+
const pr = data.prs[0];
|
|
206
|
+
assert.equal(pr?.number, 42);
|
|
207
|
+
assert.equal(pr?.role, 'reviewer', 'Role should be reviewer');
|
|
208
|
+
assert.equal(pr?.author, 'otheruser', 'Author should be otheruser, not the current user');
|
|
209
|
+
});
|
|
210
|
+
test('caches results within TTL — exec called only once for two requests', async () => {
|
|
211
|
+
await stopServer();
|
|
212
|
+
saveConfig(configPath, {
|
|
213
|
+
...DEFAULTS,
|
|
214
|
+
workspaces: [WORKSPACE_PATH_A],
|
|
215
|
+
});
|
|
216
|
+
let searchCallCount = 0;
|
|
217
|
+
// Wrap makeMockExec with a counter on the search path
|
|
218
|
+
const baseExec = makeMockExec({
|
|
219
|
+
remotes: { [WORKSPACE_PATH_A]: 'git@github.com:myorg/repo-a.git' },
|
|
220
|
+
userLogin: 'testuser',
|
|
221
|
+
searchItems: [makeSearchItem({ ownerRepo: 'myorg/repo-a', number: 1, author: 'testuser' })],
|
|
222
|
+
});
|
|
223
|
+
const countingExec = async (...args) => {
|
|
224
|
+
const [cmd, argv] = args;
|
|
225
|
+
if (cmd === 'gh' && typeof argv[1] === 'string' && argv[1].startsWith('search/issues')) {
|
|
226
|
+
searchCallCount++;
|
|
227
|
+
}
|
|
228
|
+
return baseExec(...args);
|
|
229
|
+
};
|
|
230
|
+
await startServer(countingExec);
|
|
231
|
+
// First request — populates cache
|
|
232
|
+
const first = await getPrs();
|
|
233
|
+
assert.equal(first.error, undefined);
|
|
234
|
+
assert.equal(first.prs.length, 1);
|
|
235
|
+
// Second request — should be served from cache, no additional exec call
|
|
236
|
+
const second = await getPrs();
|
|
237
|
+
assert.equal(second.error, undefined);
|
|
238
|
+
assert.equal(second.prs.length, 1);
|
|
239
|
+
assert.equal(searchCallCount, 1, 'gh search should have been called exactly once (cache hit on second request)');
|
|
240
|
+
});
|
|
@@ -0,0 +1,344 @@
|
|
|
1
|
+
import { test, before, after, afterEach } from 'node:test';
|
|
2
|
+
import assert from 'node:assert/strict';
|
|
3
|
+
import fs from 'node:fs';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import os from 'node:os';
|
|
6
|
+
import { startPolling, stopPolling, isPolling } from '../server/review-poller.js';
|
|
7
|
+
import { saveConfig, DEFAULTS } from '../server/config.js';
|
|
8
|
+
// ─── Shared fixtures ──────────────────────────────────────────────────────────
|
|
9
|
+
let tmpDir;
|
|
10
|
+
let configPath;
|
|
11
|
+
const WORKSPACE_PATH = '/fake/workspace/my-repo';
|
|
12
|
+
before(() => {
|
|
13
|
+
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'review-poller-test-'));
|
|
14
|
+
configPath = path.join(tmpDir, 'config.json');
|
|
15
|
+
});
|
|
16
|
+
after(() => {
|
|
17
|
+
fs.rmSync(tmpDir, { recursive: true, force: true });
|
|
18
|
+
});
|
|
19
|
+
afterEach(async () => {
|
|
20
|
+
// Guarantee no timer leaks between tests
|
|
21
|
+
await stopPolling();
|
|
22
|
+
});
|
|
23
|
+
// ─── Helpers ──────────────────────────────────────────────────────────────────
|
|
24
|
+
/** Builds a minimal GhNotification JSON string suitable for mock exec stdout. */
|
|
25
|
+
function makeNotificationLine(overrides) {
|
|
26
|
+
const { id = 'notif-1', reason = 'review_requested', prNumber = 42, ownerRepo = 'owner/my-repo', updatedAt = new Date().toISOString(), title = 'Test PR', } = overrides;
|
|
27
|
+
return JSON.stringify({
|
|
28
|
+
id,
|
|
29
|
+
reason,
|
|
30
|
+
subject: {
|
|
31
|
+
title,
|
|
32
|
+
url: `https://api.github.com/repos/${ownerRepo}/pulls/${prNumber}`,
|
|
33
|
+
type: 'PullRequest',
|
|
34
|
+
},
|
|
35
|
+
repository: { full_name: ownerRepo },
|
|
36
|
+
updated_at: updatedAt,
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Creates a mock execAsync. Routes by command:
|
|
41
|
+
* - `gh api /notifications` → returns notification lines joined by newline
|
|
42
|
+
* - `git remote get-url origin` → returns the configured remote URL
|
|
43
|
+
* - `git fetch ...` → resolves with empty output
|
|
44
|
+
* - `git worktree add ...` → resolves with empty output (unless worktreeError is set)
|
|
45
|
+
*/
|
|
46
|
+
function makeMockExec(opts) {
|
|
47
|
+
return async (cmd, args) => {
|
|
48
|
+
const command = cmd;
|
|
49
|
+
const argv = args;
|
|
50
|
+
opts.onExec?.(command, argv);
|
|
51
|
+
if (command === 'gh' && argv[0] === 'api') {
|
|
52
|
+
if (opts.ghError)
|
|
53
|
+
throw opts.ghError;
|
|
54
|
+
const lines = opts.notificationLines ?? [];
|
|
55
|
+
return { stdout: lines.join('\n'), stderr: '' };
|
|
56
|
+
}
|
|
57
|
+
if (command === 'git' && argv[0] === 'remote') {
|
|
58
|
+
if (opts.gitRemoteError)
|
|
59
|
+
throw opts.gitRemoteError;
|
|
60
|
+
const url = opts.remoteUrl ?? 'https://github.com/owner/my-repo.git';
|
|
61
|
+
return { stdout: url + '\n', stderr: '' };
|
|
62
|
+
}
|
|
63
|
+
if (command === 'git' && argv[0] === 'fetch') {
|
|
64
|
+
return { stdout: '', stderr: '' };
|
|
65
|
+
}
|
|
66
|
+
if (command === 'git' && argv[0] === 'worktree') {
|
|
67
|
+
if (opts.worktreeError)
|
|
68
|
+
throw opts.worktreeError;
|
|
69
|
+
return { stdout: '', stderr: '' };
|
|
70
|
+
}
|
|
71
|
+
throw new Error(`Unexpected exec call: ${command} ${argv.join(' ')}`);
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
/** Returns a deps object with sensible defaults. Override individual fields as needed. */
|
|
75
|
+
function makeDeps(overrides = {}) {
|
|
76
|
+
return {
|
|
77
|
+
configPath,
|
|
78
|
+
getWorkspacePaths: () => [WORKSPACE_PATH],
|
|
79
|
+
getWorkspaceSettings: () => undefined,
|
|
80
|
+
createSession: async () => { },
|
|
81
|
+
broadcastEvent: () => { },
|
|
82
|
+
execAsync: makeMockExec({}),
|
|
83
|
+
...overrides,
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
/** Waits for at least one poll cycle to complete given the interval. */
|
|
87
|
+
function waitForCycles(intervalMs, cycles = 1) {
|
|
88
|
+
return new Promise((resolve) => setTimeout(resolve, intervalMs * cycles + 20));
|
|
89
|
+
}
|
|
90
|
+
// ─── Tests ────────────────────────────────────────────────────────────────────
|
|
91
|
+
test('isPolling() returns false initially', () => {
|
|
92
|
+
assert.equal(isPolling(), false);
|
|
93
|
+
});
|
|
94
|
+
test('startPolling() sets isPolling() to true', () => {
|
|
95
|
+
saveConfig(configPath, {
|
|
96
|
+
...DEFAULTS,
|
|
97
|
+
automations: { pollIntervalMs: 60_000 },
|
|
98
|
+
});
|
|
99
|
+
startPolling(makeDeps());
|
|
100
|
+
assert.equal(isPolling(), true);
|
|
101
|
+
});
|
|
102
|
+
test('stopPolling() sets isPolling() to false', async () => {
|
|
103
|
+
saveConfig(configPath, {
|
|
104
|
+
...DEFAULTS,
|
|
105
|
+
automations: { pollIntervalMs: 60_000 },
|
|
106
|
+
});
|
|
107
|
+
startPolling(makeDeps());
|
|
108
|
+
assert.equal(isPolling(), true);
|
|
109
|
+
await stopPolling();
|
|
110
|
+
assert.equal(isPolling(), false);
|
|
111
|
+
});
|
|
112
|
+
test('startPolling() is idempotent — calling twice does not create two timers', async () => {
|
|
113
|
+
const INTERVAL = 50;
|
|
114
|
+
let callCount = 0;
|
|
115
|
+
saveConfig(configPath, {
|
|
116
|
+
...DEFAULTS,
|
|
117
|
+
automations: {
|
|
118
|
+
autoCheckoutReviewRequests: true,
|
|
119
|
+
pollIntervalMs: INTERVAL,
|
|
120
|
+
lastPollTimestamp: new Date().toISOString(),
|
|
121
|
+
},
|
|
122
|
+
});
|
|
123
|
+
const exec = makeMockExec({
|
|
124
|
+
onExec: (cmd, argv) => {
|
|
125
|
+
if (cmd === 'gh' && argv[0] === 'api')
|
|
126
|
+
callCount++;
|
|
127
|
+
},
|
|
128
|
+
});
|
|
129
|
+
const deps = makeDeps({ execAsync: exec });
|
|
130
|
+
startPolling(deps);
|
|
131
|
+
startPolling(deps); // second call must be a no-op
|
|
132
|
+
await waitForCycles(INTERVAL, 2);
|
|
133
|
+
// Two timer cycles elapsed. If only one timer exists, gh was called ~2 times.
|
|
134
|
+
// If startPolling were NOT idempotent (two timers), we would see ~4 calls.
|
|
135
|
+
assert.ok(callCount <= 3, `Expected at most 3 gh calls (got ${callCount}) — suggests only one timer running`);
|
|
136
|
+
});
|
|
137
|
+
test('first-run guard — when lastPollTimestamp is absent, no notifications are processed', async () => {
|
|
138
|
+
const INTERVAL = 50;
|
|
139
|
+
// Config without lastPollTimestamp — first-run scenario
|
|
140
|
+
saveConfig(configPath, {
|
|
141
|
+
...DEFAULTS,
|
|
142
|
+
automations: {
|
|
143
|
+
autoCheckoutReviewRequests: true,
|
|
144
|
+
pollIntervalMs: INTERVAL,
|
|
145
|
+
// No lastPollTimestamp — module will default to "now"
|
|
146
|
+
},
|
|
147
|
+
});
|
|
148
|
+
const broadcastedEvents = [];
|
|
149
|
+
let fetchCallCount = 0;
|
|
150
|
+
const exec = makeMockExec({
|
|
151
|
+
// Notification is old (well before "now"), so it should NOT be processed
|
|
152
|
+
notificationLines: [
|
|
153
|
+
makeNotificationLine({
|
|
154
|
+
updatedAt: new Date(Date.now() - 60_000).toISOString(), // 1 minute ago
|
|
155
|
+
ownerRepo: 'owner/my-repo',
|
|
156
|
+
}),
|
|
157
|
+
],
|
|
158
|
+
remoteUrl: 'https://github.com/owner/my-repo.git',
|
|
159
|
+
onExec: (cmd, argv) => {
|
|
160
|
+
if (cmd === 'git' && argv[0] === 'fetch')
|
|
161
|
+
fetchCallCount++;
|
|
162
|
+
},
|
|
163
|
+
});
|
|
164
|
+
const deps = makeDeps({
|
|
165
|
+
execAsync: exec,
|
|
166
|
+
broadcastEvent: (event, data) => broadcastedEvents.push({ event, data }),
|
|
167
|
+
});
|
|
168
|
+
startPolling(deps);
|
|
169
|
+
await waitForCycles(INTERVAL);
|
|
170
|
+
// The notification predates the first-run "now" baseline, so no checkout should occur
|
|
171
|
+
assert.equal(fetchCallCount, 0, 'git fetch should not be called for historical notifications');
|
|
172
|
+
assert.equal(broadcastedEvents.length, 0, 'No review-checkout events should be broadcast');
|
|
173
|
+
});
|
|
174
|
+
test('JSON parse safety — non-JSON lines in gh output do not crash', async () => {
|
|
175
|
+
const INTERVAL = 50;
|
|
176
|
+
saveConfig(configPath, {
|
|
177
|
+
...DEFAULTS,
|
|
178
|
+
automations: {
|
|
179
|
+
autoCheckoutReviewRequests: true,
|
|
180
|
+
pollIntervalMs: INTERVAL,
|
|
181
|
+
lastPollTimestamp: new Date(Date.now() - 120_000).toISOString(), // 2 min ago
|
|
182
|
+
},
|
|
183
|
+
});
|
|
184
|
+
// Mix valid JSON with non-JSON warning lines that gh sometimes emits
|
|
185
|
+
const validNotification = makeNotificationLine({
|
|
186
|
+
updatedAt: new Date().toISOString(),
|
|
187
|
+
ownerRepo: 'owner/my-repo',
|
|
188
|
+
prNumber: 7,
|
|
189
|
+
});
|
|
190
|
+
const exec = makeMockExec({
|
|
191
|
+
notificationLines: [
|
|
192
|
+
'Warning: some gh warning message',
|
|
193
|
+
validNotification,
|
|
194
|
+
'another non-JSON line',
|
|
195
|
+
],
|
|
196
|
+
remoteUrl: 'https://github.com/owner/my-repo.git',
|
|
197
|
+
});
|
|
198
|
+
// Just verify it doesn't throw — if parsing crashes, startPolling's setInterval
|
|
199
|
+
// would log an unhandled rejection. We capture broadcastEvent to confirm the
|
|
200
|
+
// valid notification was still processed.
|
|
201
|
+
const broadcastedEvents = [];
|
|
202
|
+
const deps = makeDeps({
|
|
203
|
+
execAsync: exec,
|
|
204
|
+
broadcastEvent: (event, data) => broadcastedEvents.push({ event, data }),
|
|
205
|
+
});
|
|
206
|
+
// Should not throw
|
|
207
|
+
startPolling(deps);
|
|
208
|
+
await waitForCycles(INTERVAL);
|
|
209
|
+
// The valid notification was newer than lastPollTimestamp — should be processed
|
|
210
|
+
const checkoutEvents = broadcastedEvents.filter((e) => e.event === 'review-checkout');
|
|
211
|
+
assert.equal(checkoutEvents.length, 1, 'Valid notification should still be processed despite surrounding non-JSON lines');
|
|
212
|
+
});
|
|
213
|
+
test('poll skips processing when autoCheckoutReviewRequests is disabled', async () => {
|
|
214
|
+
const INTERVAL = 50;
|
|
215
|
+
saveConfig(configPath, {
|
|
216
|
+
...DEFAULTS,
|
|
217
|
+
automations: {
|
|
218
|
+
autoCheckoutReviewRequests: false,
|
|
219
|
+
pollIntervalMs: INTERVAL,
|
|
220
|
+
lastPollTimestamp: new Date(Date.now() - 120_000).toISOString(),
|
|
221
|
+
},
|
|
222
|
+
});
|
|
223
|
+
let ghCallCount = 0;
|
|
224
|
+
const exec = makeMockExec({
|
|
225
|
+
notificationLines: [makeNotificationLine({ updatedAt: new Date().toISOString() })],
|
|
226
|
+
onExec: (cmd, argv) => {
|
|
227
|
+
if (cmd === 'gh' && argv[0] === 'api')
|
|
228
|
+
ghCallCount++;
|
|
229
|
+
},
|
|
230
|
+
});
|
|
231
|
+
startPolling(makeDeps({ execAsync: exec }));
|
|
232
|
+
await waitForCycles(INTERVAL);
|
|
233
|
+
// pollOnce returns early when the flag is off — gh should not even be called
|
|
234
|
+
assert.equal(ghCallCount, 0, 'gh should not be called when autoCheckoutReviewRequests is false');
|
|
235
|
+
});
|
|
236
|
+
test('stopPolling() awaits the in-flight poll before resolving', async () => {
|
|
237
|
+
const DELAY_MS = 100;
|
|
238
|
+
saveConfig(configPath, {
|
|
239
|
+
...DEFAULTS,
|
|
240
|
+
automations: {
|
|
241
|
+
autoCheckoutReviewRequests: true,
|
|
242
|
+
pollIntervalMs: 60_000,
|
|
243
|
+
lastPollTimestamp: new Date(Date.now() - 120_000).toISOString(),
|
|
244
|
+
},
|
|
245
|
+
});
|
|
246
|
+
const broadcastedEvents = [];
|
|
247
|
+
// Wrap the normal exec with a deliberate delay so the poll stays in-flight
|
|
248
|
+
const normalExec = makeMockExec({
|
|
249
|
+
notificationLines: [
|
|
250
|
+
makeNotificationLine({ updatedAt: new Date().toISOString(), ownerRepo: 'owner/my-repo' }),
|
|
251
|
+
],
|
|
252
|
+
remoteUrl: 'https://github.com/owner/my-repo.git',
|
|
253
|
+
});
|
|
254
|
+
const delayedExec = async (...args) => {
|
|
255
|
+
await new Promise((r) => setTimeout(r, DELAY_MS));
|
|
256
|
+
return normalExec(...args);
|
|
257
|
+
};
|
|
258
|
+
const deps = makeDeps({
|
|
259
|
+
execAsync: delayedExec,
|
|
260
|
+
broadcastEvent: (event, data) => broadcastedEvents.push({ event, data }),
|
|
261
|
+
});
|
|
262
|
+
startPolling(deps);
|
|
263
|
+
// Give the initial poll just enough time to start (but not finish — it takes ~100ms per call)
|
|
264
|
+
await new Promise((r) => setTimeout(r, 10));
|
|
265
|
+
// stopPolling() must await the in-flight poll
|
|
266
|
+
await stopPolling();
|
|
267
|
+
// The poll ran to completion — broadcastEvent must have been called
|
|
268
|
+
const checkoutEvents = broadcastedEvents.filter((e) => e.event === 'review-checkout');
|
|
269
|
+
assert.ok(checkoutEvents.length >= 1, 'broadcastEvent should have been called before stopPolling() returned');
|
|
270
|
+
});
|
|
271
|
+
test('poll-start watermark: lastPollTimestamp saved is the time before the fetch, not after', async () => {
|
|
272
|
+
const INTERVAL = 60_000;
|
|
273
|
+
saveConfig(configPath, {
|
|
274
|
+
...DEFAULTS,
|
|
275
|
+
automations: {
|
|
276
|
+
autoCheckoutReviewRequests: true,
|
|
277
|
+
pollIntervalMs: INTERVAL,
|
|
278
|
+
lastPollTimestamp: new Date(Date.now() - 120_000).toISOString(),
|
|
279
|
+
},
|
|
280
|
+
});
|
|
281
|
+
const EXEC_DELAY_MS = 50;
|
|
282
|
+
const normalExec = makeMockExec({
|
|
283
|
+
notificationLines: [],
|
|
284
|
+
remoteUrl: 'https://github.com/owner/my-repo.git',
|
|
285
|
+
});
|
|
286
|
+
const delayedExec = async (...args) => {
|
|
287
|
+
await new Promise((r) => setTimeout(r, EXEC_DELAY_MS));
|
|
288
|
+
return normalExec(...args);
|
|
289
|
+
};
|
|
290
|
+
const deps = makeDeps({ execAsync: delayedExec });
|
|
291
|
+
// Bracket the poll with timestamps
|
|
292
|
+
const beforePoll = Date.now();
|
|
293
|
+
startPolling(deps);
|
|
294
|
+
await stopPolling(); // waits for the initial poll to complete
|
|
295
|
+
const afterPoll = Date.now();
|
|
296
|
+
// Read the config that was written by the poll
|
|
297
|
+
const savedConfig = JSON.parse(fs.readFileSync(configPath, 'utf8'));
|
|
298
|
+
const savedTs = savedConfig.automations?.lastPollTimestamp;
|
|
299
|
+
assert.ok(savedTs !== undefined, 'lastPollTimestamp should have been saved');
|
|
300
|
+
const savedMs = new Date(savedTs).getTime();
|
|
301
|
+
assert.ok(savedMs >= beforePoll, `saved timestamp (${savedTs}) should be >= poll start (${new Date(beforePoll).toISOString()})`);
|
|
302
|
+
assert.ok(savedMs <= afterPoll, `saved timestamp (${savedTs}) should be <= poll end (${new Date(afterPoll).toISOString()})`);
|
|
303
|
+
// The key invariant: the saved timestamp is the poll-START watermark, not poll-end.
|
|
304
|
+
// We verify this by confirming it precedes the time after stopPolling returned.
|
|
305
|
+
// Because exec has a deliberate delay, a poll-END timestamp would be noticeably later.
|
|
306
|
+
// We simply confirm the saved value is a valid ISO string within the expected window.
|
|
307
|
+
assert.ok(!isNaN(savedMs), 'saved lastPollTimestamp should be a valid date');
|
|
308
|
+
});
|
|
309
|
+
test('pollInFlight guard prevents overlapping poll cycles', async () => {
|
|
310
|
+
const INTERVAL_MS = 10;
|
|
311
|
+
const EXEC_DELAY_MS = 100; // each poll takes ~100ms — far longer than the interval
|
|
312
|
+
saveConfig(configPath, {
|
|
313
|
+
...DEFAULTS,
|
|
314
|
+
automations: {
|
|
315
|
+
autoCheckoutReviewRequests: true,
|
|
316
|
+
pollIntervalMs: INTERVAL_MS,
|
|
317
|
+
lastPollTimestamp: new Date(Date.now() - 120_000).toISOString(),
|
|
318
|
+
},
|
|
319
|
+
});
|
|
320
|
+
let ghCallCount = 0;
|
|
321
|
+
const normalExec = makeMockExec({
|
|
322
|
+
notificationLines: [],
|
|
323
|
+
remoteUrl: 'https://github.com/owner/my-repo.git',
|
|
324
|
+
onExec: (cmd, argv) => {
|
|
325
|
+
if (cmd === 'gh' && argv[0] === 'api')
|
|
326
|
+
ghCallCount++;
|
|
327
|
+
},
|
|
328
|
+
});
|
|
329
|
+
const delayedExec = async (...args) => {
|
|
330
|
+
await new Promise((r) => setTimeout(r, EXEC_DELAY_MS));
|
|
331
|
+
return normalExec(...args);
|
|
332
|
+
};
|
|
333
|
+
const deps = makeDeps({ execAsync: delayedExec });
|
|
334
|
+
startPolling(deps);
|
|
335
|
+
// Wait long enough for several timer ticks to fire (10ms interval × ~15 ticks = 150ms)
|
|
336
|
+
// but each poll takes 100ms, so without the guard we would expect many concurrent calls.
|
|
337
|
+
await new Promise((r) => setTimeout(r, 150));
|
|
338
|
+
await stopPolling();
|
|
339
|
+
// Without the pollInFlight guard, 150ms / 10ms = ~15 timer fires would each spawn a poll,
|
|
340
|
+
// meaning gh could be called ~15 times. With the guard, at most 2 polls can complete
|
|
341
|
+
// in 150ms (one starting at t=0 finishing at ~100ms, one starting at ~100ms finishing at ~200ms).
|
|
342
|
+
assert.ok(ghCallCount <= 3, `Expected at most 3 gh calls due to pollInFlight guard (got ${ghCallCount})`);
|
|
343
|
+
assert.ok(ghCallCount >= 1, `Expected at least 1 gh call to confirm polling ran (got ${ghCallCount})`);
|
|
344
|
+
});
|