@myrialabs/clopen 0.4.33 → 0.4.35
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/backend/auth/permissions.ts +10 -0
- package/backend/auth/rate-limiter.test.ts +115 -0
- package/backend/auth/rate-limiter.ts +25 -12
- package/backend/containers/actions.ts +316 -0
- package/backend/containers/disk-usage.test.ts +68 -0
- package/backend/containers/disk-usage.ts +170 -0
- package/backend/containers/logs.ts +335 -0
- package/backend/containers/monitor.ts +410 -0
- package/backend/containers/parse.test.ts +599 -0
- package/backend/containers/parse.ts +905 -0
- package/backend/containers/port-index.test.ts +91 -0
- package/backend/containers/port-index.ts +198 -0
- package/backend/containers/prune-job.test.ts +148 -0
- package/backend/containers/prune-job.ts +129 -0
- package/backend/containers/pty-backend.ts +337 -0
- package/backend/containers/pty.ts +114 -0
- package/backend/containers/runtime.ts +218 -0
- package/backend/containers/scan.ts +293 -0
- package/backend/db-client/connection-manager.ts +13 -0
- package/backend/files/file-watcher.test.ts +105 -0
- package/backend/files/file-watcher.ts +45 -1
- package/backend/git/git-service.test.ts +33 -0
- package/backend/git/git-service.ts +7 -3
- package/backend/git/nested-repos.test.ts +292 -1
- package/backend/git/nested-repos.ts +330 -17
- package/backend/host/runner.ts +204 -0
- package/backend/index.ts +20 -2
- package/backend/middleware/security.test.ts +95 -0
- package/backend/middleware/security.ts +114 -0
- package/backend/ports/attribute.test.ts +231 -0
- package/backend/ports/attribute.ts +444 -0
- package/backend/ports/kill.ts +203 -0
- package/backend/ports/monitor.ts +365 -0
- package/backend/ports/processes.test.ts +98 -0
- package/backend/ports/processes.ts +374 -0
- package/backend/ports/registry.ts +165 -0
- package/backend/ports/scan-host.ts +329 -0
- package/backend/ports/scan.test.ts +341 -0
- package/backend/ports/scan.ts +687 -0
- package/backend/ports/ssh-lineage.ts +318 -0
- package/backend/preview/browser/browser-video-capture.ts +84 -31
- package/backend/ssh/forwards.ts +31 -0
- package/backend/ws/auth/device.ts +1 -1
- package/backend/ws/auth/login.ts +8 -4
- package/backend/ws/containers/actions.ts +156 -0
- package/backend/ws/containers/index.ts +43 -0
- package/backend/ws/containers/list.ts +146 -0
- package/backend/ws/containers/logs.ts +43 -0
- package/backend/ws/containers/tunnel.ts +101 -0
- package/backend/ws/git/log.ts +3 -1
- package/backend/ws/git/status.ts +37 -27
- package/backend/ws/index.ts +4 -0
- package/backend/ws/message-rate-limiter.test.ts +45 -0
- package/backend/ws/message-rate-limiter.ts +34 -3
- package/backend/ws/ports/index.ts +19 -0
- package/backend/ws/ports/kill.ts +80 -0
- package/backend/ws/ports/list.ts +60 -0
- package/backend/ws/ssh/connections.ts +8 -0
- package/backend/ws/system/device-info.ts +99 -43
- package/dist/assets/{index-BF4buYmI.js → index-B0iIhSO9.js} +1 -1
- package/dist/assets/{index-BW0DA8NV.js → index-BRJqss6F.js} +1 -1
- package/dist/assets/main-Buko4D0t.css +1 -0
- package/dist/assets/{main-BbwWLJRN.js → main-C_iGUZyL.js} +468 -447
- package/dist/index.html +2 -2
- package/dist/manifest.json +9 -2
- package/package.json +1 -1
- package/shared/types/containers/container.ts +366 -0
- package/shared/types/containers/index.ts +5 -0
- package/shared/types/host/index.ts +18 -0
- package/shared/types/ports/index.ts +5 -0
- package/shared/types/ports/port.ts +230 -0
- package/shared/utils/logger.ts +3 -0
- package/shared/utils/ws-client.ts +67 -12
- package/shared/utils/ws-server.ts +64 -13
- package/dist/assets/main-CCvRMXlP.css +0 -1
|
@@ -0,0 +1,293 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Containers — one host, one scan, one table.
|
|
3
|
+
*
|
|
4
|
+
* Held per watched host so the runtime probe and the image/volume catalogue
|
|
5
|
+
* survive between ticks. That is what keeps a live panel down to a single
|
|
6
|
+
* command per tick: the container list is what changes second to second, while
|
|
7
|
+
* images and volumes change when someone builds or prunes, and re-reading them
|
|
8
|
+
* every tick would triple the cost of the view for an answer that is almost
|
|
9
|
+
* always identical.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import type {
|
|
13
|
+
ContainerEntry,
|
|
14
|
+
ContainerImageEntry,
|
|
15
|
+
ContainerLimitation,
|
|
16
|
+
ContainerNetworkEntry,
|
|
17
|
+
ContainerScanResult,
|
|
18
|
+
ContainerVolumeEntry
|
|
19
|
+
} from '$shared/types/containers';
|
|
20
|
+
import type { CommandRunner, ProbePlatform } from '../host/runner';
|
|
21
|
+
import {
|
|
22
|
+
containerArgv,
|
|
23
|
+
detectRuntime,
|
|
24
|
+
forgetRuntime,
|
|
25
|
+
limitationFor,
|
|
26
|
+
looksLikeRuntimeFailure,
|
|
27
|
+
tryRun
|
|
28
|
+
} from './runtime';
|
|
29
|
+
import {
|
|
30
|
+
linkUsage,
|
|
31
|
+
parseDockerImages,
|
|
32
|
+
parseDockerNetworks,
|
|
33
|
+
parseDockerPs,
|
|
34
|
+
parseDockerVolumes,
|
|
35
|
+
parseMounts,
|
|
36
|
+
parseNetworkMembership,
|
|
37
|
+
parsePodmanImages,
|
|
38
|
+
parsePodmanNetworks,
|
|
39
|
+
parsePodmanPs,
|
|
40
|
+
parsePodmanVolumes
|
|
41
|
+
} from './parse';
|
|
42
|
+
import { debug } from '$shared/utils/logger';
|
|
43
|
+
import { CONTAINER_TIMEOUTS } from '$shared/types/containers';
|
|
44
|
+
|
|
45
|
+
/** How long the image and volume lists are reused before being read again. */
|
|
46
|
+
const CATALOG_TTL_MS = 15_000;
|
|
47
|
+
|
|
48
|
+
/** Running first, then everything that could be started, then the wreckage. */
|
|
49
|
+
const STATE_ORDER: Record<ContainerEntry['state'], number> = {
|
|
50
|
+
running: 0,
|
|
51
|
+
paused: 1,
|
|
52
|
+
restarting: 2,
|
|
53
|
+
created: 3,
|
|
54
|
+
exited: 4,
|
|
55
|
+
removing: 5,
|
|
56
|
+
dead: 6,
|
|
57
|
+
unknown: 7
|
|
58
|
+
};
|
|
59
|
+
|
|
60
|
+
interface Catalog {
|
|
61
|
+
images: ContainerImageEntry[];
|
|
62
|
+
volumes: ContainerVolumeEntry[];
|
|
63
|
+
networks: ContainerNetworkEntry[];
|
|
64
|
+
limitations: ContainerLimitation[];
|
|
65
|
+
readAt: number;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export class HostContainerScanner {
|
|
69
|
+
private catalog: Catalog | null = null;
|
|
70
|
+
/**
|
|
71
|
+
* A scan already running. Callers join it rather than starting a second one:
|
|
72
|
+
* a remote scan can outlast the poll interval, and two in flight would double
|
|
73
|
+
* the SSH channels for the same answer.
|
|
74
|
+
*/
|
|
75
|
+
private inFlight: Promise<ContainerScanResult> | null = null;
|
|
76
|
+
|
|
77
|
+
constructor(
|
|
78
|
+
private readonly hostId: string,
|
|
79
|
+
private readonly hostName: string,
|
|
80
|
+
private readonly runner: CommandRunner,
|
|
81
|
+
private readonly platform: ProbePlatform
|
|
82
|
+
) {}
|
|
83
|
+
|
|
84
|
+
/** Read this host, joining a scan already in progress rather than racing it. */
|
|
85
|
+
async scan(now = Date.now()): Promise<ContainerScanResult> {
|
|
86
|
+
if (this.inFlight) return this.inFlight;
|
|
87
|
+
this.inFlight = this.runScan(now).finally(() => {
|
|
88
|
+
this.inFlight = null;
|
|
89
|
+
});
|
|
90
|
+
return this.inFlight;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
private empty(
|
|
94
|
+
scannedAt: string,
|
|
95
|
+
limitations: ContainerLimitation[],
|
|
96
|
+
error: string | null = null
|
|
97
|
+
): ContainerScanResult {
|
|
98
|
+
return {
|
|
99
|
+
hostId: this.hostId,
|
|
100
|
+
scannedAt,
|
|
101
|
+
runtime: null,
|
|
102
|
+
runtimeVersion: null,
|
|
103
|
+
runtimeProblem: 'none',
|
|
104
|
+
entries: [],
|
|
105
|
+
images: [],
|
|
106
|
+
volumes: [],
|
|
107
|
+
networks: [],
|
|
108
|
+
limitations,
|
|
109
|
+
error
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
private async runScan(now: number): Promise<ContainerScanResult> {
|
|
114
|
+
const scannedAt = new Date(now).toISOString();
|
|
115
|
+
|
|
116
|
+
const info = await detectRuntime(this.hostId, this.runner, this.platform, now);
|
|
117
|
+
if (info.problem !== 'none' || !info.runtime) {
|
|
118
|
+
const message = limitationFor(info, this.hostName);
|
|
119
|
+
return {
|
|
120
|
+
...this.empty(scannedAt, message ? [{ code: problemCode(info.problem), message }] : []),
|
|
121
|
+
runtimeProblem: info.problem
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
const runtime = info.runtime;
|
|
126
|
+
const listing = await tryRun(
|
|
127
|
+
this.runner,
|
|
128
|
+
containerArgv(runtime, this.platform, [
|
|
129
|
+
'ps',
|
|
130
|
+
'--all',
|
|
131
|
+
'--no-trunc',
|
|
132
|
+
'--format',
|
|
133
|
+
runtime === 'docker' ? '{{json .}}' : 'json'
|
|
134
|
+
]),
|
|
135
|
+
CONTAINER_TIMEOUTS.list
|
|
136
|
+
);
|
|
137
|
+
|
|
138
|
+
if (listing.code !== 0) {
|
|
139
|
+
// The runtime answered `version` and then refused to list: it went away
|
|
140
|
+
// between the two, so the cached "this host has docker" must go too.
|
|
141
|
+
if (looksLikeRuntimeFailure(listing)) forgetRuntime(this.hostId);
|
|
142
|
+
const reason = listing.stderr.trim() || listing.stdout.trim() || `exit status ${listing.code}`;
|
|
143
|
+
return {
|
|
144
|
+
...this.empty(scannedAt, [], reason),
|
|
145
|
+
runtime,
|
|
146
|
+
runtimeVersion: info.version
|
|
147
|
+
};
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
const entries =
|
|
151
|
+
runtime === 'docker'
|
|
152
|
+
? parseDockerPs(listing.stdout, this.hostId)
|
|
153
|
+
: parsePodmanPs(listing.stdout, this.hostId);
|
|
154
|
+
|
|
155
|
+
entries.sort(
|
|
156
|
+
(a, b) =>
|
|
157
|
+
STATE_ORDER[a.state] - STATE_ORDER[b.state] ||
|
|
158
|
+
(a.composeProject ?? '').localeCompare(b.composeProject ?? '') ||
|
|
159
|
+
a.name.localeCompare(b.name)
|
|
160
|
+
);
|
|
161
|
+
|
|
162
|
+
const catalog = await this.readCatalog(runtime, now);
|
|
163
|
+
linkUsage(
|
|
164
|
+
entries,
|
|
165
|
+
catalog.images,
|
|
166
|
+
catalog.volumes,
|
|
167
|
+
parseMounts(listing.stdout, runtime),
|
|
168
|
+
catalog.networks,
|
|
169
|
+
parseNetworkMembership(listing.stdout, runtime)
|
|
170
|
+
);
|
|
171
|
+
|
|
172
|
+
return {
|
|
173
|
+
hostId: this.hostId,
|
|
174
|
+
scannedAt,
|
|
175
|
+
runtime,
|
|
176
|
+
runtimeVersion: info.version,
|
|
177
|
+
runtimeProblem: 'none',
|
|
178
|
+
entries,
|
|
179
|
+
images: catalog.images,
|
|
180
|
+
volumes: catalog.volumes,
|
|
181
|
+
networks: catalog.networks,
|
|
182
|
+
limitations: catalog.limitations,
|
|
183
|
+
error: null
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* Images, volumes and networks, re-read only when the cached set has aged
|
|
189
|
+
* out. A failure here degrades those tabs and nothing else — the container
|
|
190
|
+
* list is the point of the view and must not disappear because `volume ls`
|
|
191
|
+
* did.
|
|
192
|
+
*/
|
|
193
|
+
private async readCatalog(runtime: 'docker' | 'podman', now: number): Promise<Catalog> {
|
|
194
|
+
if (this.catalog && now - this.catalog.readAt < CATALOG_TTL_MS) return this.catalog;
|
|
195
|
+
|
|
196
|
+
const limitations: ContainerLimitation[] = [];
|
|
197
|
+
const format = runtime === 'docker' ? '{{json .}}' : 'json';
|
|
198
|
+
|
|
199
|
+
const imagesResult = await tryRun(
|
|
200
|
+
this.runner,
|
|
201
|
+
containerArgv(runtime, this.platform, ['images', '--format', format]),
|
|
202
|
+
CONTAINER_TIMEOUTS.list
|
|
203
|
+
);
|
|
204
|
+
let images: ContainerImageEntry[] = this.catalog?.images ?? [];
|
|
205
|
+
if (imagesResult.code === 0) {
|
|
206
|
+
images =
|
|
207
|
+
runtime === 'docker'
|
|
208
|
+
? parseDockerImages(imagesResult.stdout)
|
|
209
|
+
: parsePodmanImages(imagesResult.stdout);
|
|
210
|
+
} else {
|
|
211
|
+
debug.log('containers', `images unavailable on ${this.hostName}:`, imagesResult.stderr);
|
|
212
|
+
limitations.push({
|
|
213
|
+
code: 'images-unavailable',
|
|
214
|
+
message: `${this.hostName} did not return an image list${
|
|
215
|
+
imagesResult.stderr.trim() ? `: ${imagesResult.stderr.trim().split('\n')[0]}` : '.'
|
|
216
|
+
}`
|
|
217
|
+
});
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
const volumesResult = await tryRun(
|
|
221
|
+
this.runner,
|
|
222
|
+
containerArgv(runtime, this.platform, ['volume', 'ls', '--format', format]),
|
|
223
|
+
CONTAINER_TIMEOUTS.list
|
|
224
|
+
);
|
|
225
|
+
let volumes: ContainerVolumeEntry[] = this.catalog?.volumes ?? [];
|
|
226
|
+
if (volumesResult.code === 0) {
|
|
227
|
+
volumes =
|
|
228
|
+
runtime === 'docker'
|
|
229
|
+
? parseDockerVolumes(volumesResult.stdout)
|
|
230
|
+
: parsePodmanVolumes(volumesResult.stdout);
|
|
231
|
+
} else {
|
|
232
|
+
debug.log('containers', `volumes unavailable on ${this.hostName}:`, volumesResult.stderr);
|
|
233
|
+
limitations.push({
|
|
234
|
+
code: 'volumes-unavailable',
|
|
235
|
+
message: `${this.hostName} did not return a volume list${
|
|
236
|
+
volumesResult.stderr.trim() ? `: ${volumesResult.stderr.trim().split('\n')[0]}` : '.'
|
|
237
|
+
}`
|
|
238
|
+
});
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
const networksResult = await tryRun(
|
|
242
|
+
this.runner,
|
|
243
|
+
containerArgv(runtime, this.platform, ['network', 'ls', '--format', format]),
|
|
244
|
+
CONTAINER_TIMEOUTS.list
|
|
245
|
+
);
|
|
246
|
+
let networks: ContainerNetworkEntry[] = this.catalog?.networks ?? [];
|
|
247
|
+
if (networksResult.code === 0) {
|
|
248
|
+
networks =
|
|
249
|
+
runtime === 'docker'
|
|
250
|
+
? parseDockerNetworks(networksResult.stdout)
|
|
251
|
+
: parsePodmanNetworks(networksResult.stdout);
|
|
252
|
+
} else {
|
|
253
|
+
debug.log('containers', `networks unavailable on ${this.hostName}:`, networksResult.stderr);
|
|
254
|
+
limitations.push({
|
|
255
|
+
code: 'networks-unavailable',
|
|
256
|
+
message: `${this.hostName} did not return a network list${
|
|
257
|
+
networksResult.stderr.trim() ? `: ${networksResult.stderr.trim().split('\n')[0]}` : '.'
|
|
258
|
+
}`
|
|
259
|
+
});
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
images.sort(
|
|
263
|
+
(a, b) => Number(a.dangling) - Number(b.dangling) || a.repository.localeCompare(b.repository)
|
|
264
|
+
);
|
|
265
|
+
volumes.sort((a, b) => a.name.localeCompare(b.name));
|
|
266
|
+
// The runtime's own networks last: they are furniture, not something the
|
|
267
|
+
// user made, and they can never be acted on.
|
|
268
|
+
networks.sort(
|
|
269
|
+
(a, b) => Number(a.predefined) - Number(b.predefined) || a.name.localeCompare(b.name)
|
|
270
|
+
);
|
|
271
|
+
|
|
272
|
+
this.catalog = { images, volumes, networks, limitations, readAt: now };
|
|
273
|
+
return this.catalog;
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
/** Force the next scan to re-read images and volumes, after an action. */
|
|
277
|
+
invalidateCatalog(): void {
|
|
278
|
+
this.catalog = null;
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
function problemCode(
|
|
283
|
+
problem: 'none' | 'not-installed' | 'daemon-unreachable' | 'permission-denied'
|
|
284
|
+
): ContainerLimitation['code'] {
|
|
285
|
+
switch (problem) {
|
|
286
|
+
case 'not-installed':
|
|
287
|
+
return 'no-runtime';
|
|
288
|
+
case 'permission-denied':
|
|
289
|
+
return 'permission-denied';
|
|
290
|
+
default:
|
|
291
|
+
return 'daemon-unreachable';
|
|
292
|
+
}
|
|
293
|
+
}
|
|
@@ -40,6 +40,19 @@ class ConnectionManager {
|
|
|
40
40
|
private entries = new Map<string, ConnectionEntry>();
|
|
41
41
|
private sweeperHandle: ReturnType<typeof setInterval> | null = null;
|
|
42
42
|
|
|
43
|
+
/**
|
|
44
|
+
* Local ports currently held open by SSH tunnels, for the port manager.
|
|
45
|
+
* These are ephemeral ports nobody asked for by number, so without this the
|
|
46
|
+
* panel would show them as an unexplained listener owned by Clopen itself.
|
|
47
|
+
*/
|
|
48
|
+
activeTunnelPorts(): Array<{ connectionId: string; localPort: number }> {
|
|
49
|
+
const ports: Array<{ connectionId: string; localPort: number }> = [];
|
|
50
|
+
for (const [connectionId, entry] of this.entries) {
|
|
51
|
+
if (entry.tunnel) ports.push({ connectionId, localPort: entry.tunnel.localPort });
|
|
52
|
+
}
|
|
53
|
+
return ports;
|
|
54
|
+
}
|
|
55
|
+
|
|
43
56
|
private startSweeper(): void {
|
|
44
57
|
if (this.sweeperHandle) return;
|
|
45
58
|
this.sweeperHandle = setInterval(() => {
|
|
@@ -10,6 +10,9 @@
|
|
|
10
10
|
|
|
11
11
|
import { describe, expect, mock, test, beforeAll, afterEach } from 'bun:test';
|
|
12
12
|
import { mkdtemp, mkdir, rm, writeFile } from 'node:fs/promises';
|
|
13
|
+
import { execGit } from '../git/git-executor';
|
|
14
|
+
import { clearNestedRepoCache, findNestedRepoPaths } from '../git/nested-repos';
|
|
15
|
+
import { relative } from 'node:path';
|
|
13
16
|
import { tmpdir } from 'node:os';
|
|
14
17
|
import { join } from 'node:path';
|
|
15
18
|
|
|
@@ -48,6 +51,16 @@ async function makeProject(): Promise<string> {
|
|
|
48
51
|
return dir;
|
|
49
52
|
}
|
|
50
53
|
|
|
54
|
+
/** Wait until an async `predicate` holds, or fail after `timeout` ms. */
|
|
55
|
+
async function waitForAsync(predicate: () => Promise<boolean>, timeout = 8000): Promise<void> {
|
|
56
|
+
const deadline = Date.now() + timeout;
|
|
57
|
+
while (Date.now() < deadline) {
|
|
58
|
+
if (await predicate()) return;
|
|
59
|
+
await new Promise((resolve) => setTimeout(resolve, 50));
|
|
60
|
+
}
|
|
61
|
+
throw new Error('Timed out waiting for watcher-driven invalidation');
|
|
62
|
+
}
|
|
63
|
+
|
|
51
64
|
/** Wait until `predicate` holds, or fail after `timeout` ms. */
|
|
52
65
|
async function waitFor(predicate: () => boolean, timeout = 4000): Promise<void> {
|
|
53
66
|
const deadline = Date.now() + timeout;
|
|
@@ -58,6 +71,19 @@ async function waitFor(predicate: () => boolean, timeout = 4000): Promise<void>
|
|
|
58
71
|
throw new Error('Timed out waiting for watcher event');
|
|
59
72
|
}
|
|
60
73
|
|
|
74
|
+
function gitRepoPathsFor(projectId: string): string[] {
|
|
75
|
+
return emitted
|
|
76
|
+
.filter((e) => e.projectId === projectId && e.event === 'git:changed')
|
|
77
|
+
.flatMap((e) => e.payload.repoPaths as string[]);
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
async function initRepo(dir: string): Promise<void> {
|
|
81
|
+
await mkdir(dir, { recursive: true });
|
|
82
|
+
await execGit(['init', '-b', 'main', '.'], dir);
|
|
83
|
+
await execGit(['config', 'user.email', 'test@example.com'], dir);
|
|
84
|
+
await execGit(['config', 'user.name', 'Test'], dir);
|
|
85
|
+
}
|
|
86
|
+
|
|
61
87
|
function changesFor(projectId: string): string[] {
|
|
62
88
|
return emitted
|
|
63
89
|
.filter((e) => e.projectId === projectId && e.event === 'files:changed')
|
|
@@ -69,6 +95,7 @@ afterEach(async () => {
|
|
|
69
95
|
fileWatcher.releaseProject(projectId);
|
|
70
96
|
}
|
|
71
97
|
emitted.length = 0;
|
|
98
|
+
clearNestedRepoCache();
|
|
72
99
|
await Promise.all(tempRoots.splice(0).map((dir) => rm(dir, { recursive: true, force: true })));
|
|
73
100
|
});
|
|
74
101
|
|
|
@@ -146,6 +173,84 @@ describe('FileWatcherManager', () => {
|
|
|
146
173
|
expect(fileWatcher.getDirtyFiles('p5').size).toBe(0);
|
|
147
174
|
});
|
|
148
175
|
|
|
176
|
+
test('watches a sub-repo created while the project is already open', async () => {
|
|
177
|
+
// `findNestedRepoPaths` caches its walk for a few seconds, and the panel
|
|
178
|
+
// warms that cache constantly — every `git:status` and `git:branches`
|
|
179
|
+
// goes through it. `scheduleGitTargetsRefresh` then re-resolves 1.5s
|
|
180
|
+
// after an unknown `.git` shows up, well inside the TTL, so it would be
|
|
181
|
+
// answered from a walk taken before the new repo existed. The git dir
|
|
182
|
+
// would stay unaccounted for, `syncGitWatchers` would file it under
|
|
183
|
+
// `rejectedGitDirs` — which is permanent — and `routeGitEvent` would
|
|
184
|
+
// then refuse to schedule another refresh for it. The sub-repo would go
|
|
185
|
+
// unwatched for as long as the project stayed open.
|
|
186
|
+
const root = await makeProject();
|
|
187
|
+
await initRepo(root);
|
|
188
|
+
|
|
189
|
+
// Warm the cache the way the panel does, before the sub-repo exists.
|
|
190
|
+
expect(await findNestedRepoPaths(root)).toEqual([]);
|
|
191
|
+
|
|
192
|
+
expect(await fileWatcher.startWatching('p7', root)).toBe(true);
|
|
193
|
+
|
|
194
|
+
const sub = join(root, 'packages', 'widget');
|
|
195
|
+
await initRepo(sub);
|
|
196
|
+
|
|
197
|
+
// The refresh announces itself by emitting for the project root once the
|
|
198
|
+
// repo set has been re-resolved.
|
|
199
|
+
await waitFor(() => gitRepoPathsFor('p7').includes(root), 10000);
|
|
200
|
+
|
|
201
|
+
emitted.length = 0;
|
|
202
|
+
// Space this out: the platform watchers coalesce bursts, and this write
|
|
203
|
+
// has to be seen on its own to mean anything.
|
|
204
|
+
await new Promise((resolve) => setTimeout(resolve, 400));
|
|
205
|
+
await writeFile(join(sub, '.git', 'index'), 'stand-in for a real index write');
|
|
206
|
+
|
|
207
|
+
await waitFor(() => gitRepoPathsFor('p7').includes(sub), 10000);
|
|
208
|
+
// 20s, not bun's 5s default: this test cannot finish faster than the
|
|
209
|
+
// watcher's own debounces (1.5s to re-resolve git targets, 0.5s to emit)
|
|
210
|
+
// plus two `git init`s and the spacing write.
|
|
211
|
+
}, 20000);
|
|
212
|
+
|
|
213
|
+
test('the watcher forwards path events to sub-repo discovery', async () => {
|
|
214
|
+
// Discovery leans on this watcher instead of a short clock, so raw paths
|
|
215
|
+
// have to reach it. There are two forwarding points — the working-tree
|
|
216
|
+
// handler and the git dir handles, which are a separate event source and
|
|
217
|
+
// the only one for `.git` on Linux — and this pins that AT LEAST ONE of
|
|
218
|
+
// them is live. It deliberately does not pin which: the two overlap on a
|
|
219
|
+
// real filesystem, and asserting on one would only pass by accident of
|
|
220
|
+
// which handle the platform happened to report an event through.
|
|
221
|
+
//
|
|
222
|
+
// Which path means what is pinned exactly, and without timing, by the
|
|
223
|
+
// `notifyPathChanged` tests in nested-repos.test.ts — `.gitignore`,
|
|
224
|
+
// `.git/info/exclude`, a `.git` appearing, and an ordinary write that
|
|
225
|
+
// must NOT invalidate anything.
|
|
226
|
+
//
|
|
227
|
+
// Direction matters. Going the other way — a repo that only becomes
|
|
228
|
+
// visible once an ignore rule is dropped — tests nothing: an unreported
|
|
229
|
+
// repo's `.git` is one the watcher does not know, so its first event
|
|
230
|
+
// triggers the unknown-git-dir refresh and the repo set is invalidated
|
|
231
|
+
// by that path whether or not anything is forwarded. Starting from a
|
|
232
|
+
// REPORTED repo keeps its git dir known.
|
|
233
|
+
const root = await makeProject();
|
|
234
|
+
await initRepo(root);
|
|
235
|
+
await initRepo(join(root, 'themes', 'mytheme'));
|
|
236
|
+
|
|
237
|
+
expect(await fileWatcher.startWatching('p8', root)).toBe(true);
|
|
238
|
+
expect((await findNestedRepoPaths(root)).map((repo) => relative(root, repo))).toEqual([
|
|
239
|
+
join('themes', 'mytheme')
|
|
240
|
+
]);
|
|
241
|
+
|
|
242
|
+
// Space it out: the platform watchers coalesce bursts, and this write has
|
|
243
|
+
// to be seen on its own to mean anything.
|
|
244
|
+
await new Promise((resolve) => setTimeout(resolve, 400));
|
|
245
|
+
// `themes/` is now ignored, so the still-pristine repo inside it has to
|
|
246
|
+
// prove local work before it is listed — and it has none.
|
|
247
|
+
await writeFile(join(root, '.gitignore'), 'themes/\n');
|
|
248
|
+
|
|
249
|
+
await waitForAsync(async () => (await findNestedRepoPaths(root)).length === 0);
|
|
250
|
+
// Same reason as the test above — the debounces alone outlast bun's 5s
|
|
251
|
+
// default.
|
|
252
|
+
}, 20000);
|
|
253
|
+
|
|
149
254
|
test('stops watching once the last viewer leaves', async () => {
|
|
150
255
|
const root = await makeProject();
|
|
151
256
|
expect(await fileWatcher.addViewer('conn-a', 'p6', root)).toBe(true);
|
|
@@ -34,6 +34,12 @@ import { join, relative, normalize, sep } from 'node:path';
|
|
|
34
34
|
import { ws } from '$backend/utils/ws';
|
|
35
35
|
import { debug } from '$shared/utils/logger';
|
|
36
36
|
import { resolveGitDirs, type GitDirTarget } from '$backend/git/git-dirs';
|
|
37
|
+
import {
|
|
38
|
+
beginWatchedDiscovery,
|
|
39
|
+
endWatchedDiscovery,
|
|
40
|
+
invalidateRepoSet,
|
|
41
|
+
notifyPathChanged
|
|
42
|
+
} from '$backend/git/nested-repos';
|
|
37
43
|
import type { FileChange } from '$shared/types/filesystem';
|
|
38
44
|
|
|
39
45
|
/**
|
|
@@ -350,6 +356,12 @@ class FileWatcherManager {
|
|
|
350
356
|
};
|
|
351
357
|
this.watchers.set(projectId, projectWatcher);
|
|
352
358
|
|
|
359
|
+
// From here on this watcher is the authority on when the project's
|
|
360
|
+
// sub-repo set and their working states change, so discovery can stop
|
|
361
|
+
// re-deriving them on a short clock. Paired with `endWatchedDiscovery`
|
|
362
|
+
// in `stopWatching`, which puts discovery back on the clock.
|
|
363
|
+
beginWatchedDiscovery(normalizedPath);
|
|
364
|
+
|
|
353
365
|
// Watch the root synchronously so events are never missed while the
|
|
354
366
|
// (async) subtree walk is still in progress.
|
|
355
367
|
if (!this.watchDir(projectWatcher, normalizedPath)) {
|
|
@@ -531,6 +543,9 @@ class FileWatcherManager {
|
|
|
531
543
|
}
|
|
532
544
|
projectWatcher.gitDirOwners.clear();
|
|
533
545
|
|
|
546
|
+
// No more signals from here, so discovery must not keep trusting them.
|
|
547
|
+
endWatchedDiscovery(projectWatcher.projectPath);
|
|
548
|
+
|
|
534
549
|
// Clear debounce timers
|
|
535
550
|
if (projectWatcher.debounceTimer) {
|
|
536
551
|
clearTimeout(projectWatcher.debounceTimer);
|
|
@@ -606,6 +621,12 @@ class FileWatcherManager {
|
|
|
606
621
|
// path: where the root watch is recursive it is the only thing that sees
|
|
607
622
|
// a sub-repo's git dir, so dropping it here is what left a commit made
|
|
608
623
|
// inside a nested repo completely unreported.
|
|
624
|
+
// Tell sub-repo discovery before anything below filters the path away.
|
|
625
|
+
// It decides for itself what a path means: `routeGitEvent` swallows every
|
|
626
|
+
// `.git` path and `shouldIgnore` every dotfile, so `.gitignore` — which
|
|
627
|
+
// moves the reported repo set — would otherwise never reach it.
|
|
628
|
+
notifyPathChanged(projectWatcher.projectPath, fullPath);
|
|
629
|
+
|
|
609
630
|
if (this.routeGitEvent(projectWatcher, relativePath, fullPath)) return;
|
|
610
631
|
|
|
611
632
|
if (this.shouldIgnore(relativePath)) return;
|
|
@@ -790,7 +811,17 @@ class FileWatcherManager {
|
|
|
790
811
|
try {
|
|
791
812
|
const watcher = watch(dirToWatch, { recursive }, (_eventType, filename) => {
|
|
792
813
|
if (!filename) return;
|
|
793
|
-
const
|
|
814
|
+
const fullPath = join(dirToWatch, String(filename));
|
|
815
|
+
|
|
816
|
+
// These handles are their own event source: nothing here reaches
|
|
817
|
+
// `handleFileChange`, and on Linux — where `.git` is pruned from the
|
|
818
|
+
// recursive walk — they are the ONLY source for it. Discovery has to
|
|
819
|
+
// be told from here too, before `isGitStateEvent` filters, since that
|
|
820
|
+
// filter answers 'does the panel show this' and drops `info/exclude`,
|
|
821
|
+
// which discovery very much cares about.
|
|
822
|
+
notifyPathChanged(projectWatcher.projectPath, fullPath);
|
|
823
|
+
|
|
824
|
+
const entryPath = relative(gitDirPath, fullPath);
|
|
794
825
|
if (!isGitStateEvent(entryPath)) return;
|
|
795
826
|
this.emitGitChanged(projectWatcher.projectId, repoPath);
|
|
796
827
|
});
|
|
@@ -832,6 +863,14 @@ class FileWatcherManager {
|
|
|
832
863
|
* Queue a re-resolve of the project's git directories, for when an event
|
|
833
864
|
* arrives from a `.git` we do not know about — `git init` or `git clone` run
|
|
834
865
|
* inside the project while it is open.
|
|
866
|
+
*
|
|
867
|
+
* This is the one signal that the project's repo SET changed, so it drops
|
|
868
|
+
* the cached sub-repo walk first. Without that, `resolveGitDirs` answers
|
|
869
|
+
* from a walk taken before the new repo existed, the git dir stays
|
|
870
|
+
* unaccounted for, and `syncGitWatchers` files it under `rejectedGitDirs` —
|
|
871
|
+
* which is permanent, and which `routeGitEvent` then uses to stop
|
|
872
|
+
* scheduling refreshes for it. A repo created in an open project would
|
|
873
|
+
* never be watched again.
|
|
835
874
|
*/
|
|
836
875
|
private scheduleGitTargetsRefresh(projectId: string, gitDirPath?: string): void {
|
|
837
876
|
const projectWatcher = this.watchers.get(projectId);
|
|
@@ -843,6 +882,7 @@ class FileWatcherManager {
|
|
|
843
882
|
projectWatcher.gitTargetsTimer = setTimeout(() => {
|
|
844
883
|
projectWatcher.gitTargetsTimer = null;
|
|
845
884
|
if (projectWatcher.closed) return;
|
|
885
|
+
invalidateRepoSet(projectWatcher.projectPath);
|
|
846
886
|
void this.syncGitWatchers(projectId).then(() => {
|
|
847
887
|
if (projectWatcher.closed) return;
|
|
848
888
|
// The repo set itself changed, so tell clients: this is what flips a
|
|
@@ -935,6 +975,10 @@ class FileWatcherManager {
|
|
|
935
975
|
projectId,
|
|
936
976
|
error: 'File watching stopped after repeated failures. Refresh to retry.'
|
|
937
977
|
});
|
|
978
|
+
// No more signals are coming, so sub-repo discovery must stop trusting
|
|
979
|
+
// this watcher and go back to re-deriving on its own clock. Without
|
|
980
|
+
// this the claim outlives the watcher that made it.
|
|
981
|
+
this.stopWatching(projectId);
|
|
938
982
|
return;
|
|
939
983
|
}
|
|
940
984
|
|
|
@@ -107,6 +107,39 @@ describe('undoLastCommit — with a parent commit', () => {
|
|
|
107
107
|
});
|
|
108
108
|
});
|
|
109
109
|
|
|
110
|
+
describe('getLog branch scoping', () => {
|
|
111
|
+
beforeEach(async () => {
|
|
112
|
+
await writeFile(path.join(repo, 'a.txt'), 'one\n');
|
|
113
|
+
await commitAll('on main');
|
|
114
|
+
await git('checkout', '-b', 'side');
|
|
115
|
+
await writeFile(path.join(repo, 'b.txt'), 'two\n');
|
|
116
|
+
await commitAll('on side');
|
|
117
|
+
await git('checkout', 'main');
|
|
118
|
+
});
|
|
119
|
+
|
|
120
|
+
test('defaults to HEAD, so another branch\'s commits stay out', async () => {
|
|
121
|
+
const log = await gitService.getLog(repo);
|
|
122
|
+
expect(log.commits.map(c => c.message)).toEqual(['on main']);
|
|
123
|
+
expect(log.total).toBe(1);
|
|
124
|
+
});
|
|
125
|
+
|
|
126
|
+
test('a named branch reports that branch', async () => {
|
|
127
|
+
const log = await gitService.getLog(repo, 50, 0, 'side');
|
|
128
|
+
expect(log.commits.map(c => c.message)).toEqual(['on side', 'on main']);
|
|
129
|
+
expect(log.total).toBe(2);
|
|
130
|
+
});
|
|
131
|
+
|
|
132
|
+
test('allBranches walks every ref and counts across all of them', async () => {
|
|
133
|
+
const log = await gitService.getLog(repo, 50, 0, undefined, true);
|
|
134
|
+
expect(log.commits.map(c => c.message).sort()).toEqual(['on main', 'on side']);
|
|
135
|
+
expect(log.total).toBe(2);
|
|
136
|
+
});
|
|
137
|
+
|
|
138
|
+
test('the branch argument still rejects option-shaped values', async () => {
|
|
139
|
+
await expect(gitService.getLog(repo, 50, 0, '--all')).rejects.toThrow(/option injection/i);
|
|
140
|
+
});
|
|
141
|
+
});
|
|
142
|
+
|
|
110
143
|
describe('other actions on a repo with no commits', () => {
|
|
111
144
|
test('getLog reports an empty history rather than throwing', async () => {
|
|
112
145
|
expect(await gitService.getLog(repo)).toEqual({ commits: [], total: 0, hasMore: false });
|
|
@@ -471,7 +471,7 @@ export class GitService {
|
|
|
471
471
|
// Log
|
|
472
472
|
// ============================================
|
|
473
473
|
|
|
474
|
-
async getLog(cwd: string, limit = 50, skip = 0, branch?: string): Promise<GitLogResult> {
|
|
474
|
+
async getLog(cwd: string, limit = 50, skip = 0, branch?: string, allBranches = false): Promise<GitLogResult> {
|
|
475
475
|
const SEPARATOR = '|||';
|
|
476
476
|
const format = `%H${SEPARATOR}%h${SEPARATOR}%an${SEPARATOR}%ae${SEPARATOR}%aI${SEPARATOR}%P${SEPARATOR}%D%n%s%x00`;
|
|
477
477
|
|
|
@@ -483,7 +483,11 @@ export class GitService {
|
|
|
483
483
|
`--skip=${skip}`
|
|
484
484
|
];
|
|
485
485
|
|
|
486
|
-
|
|
486
|
+
// `--all` is a flag, not a revision, so it stays out of the value slot that
|
|
487
|
+
// `assertSafeGitRevish` guards against option injection.
|
|
488
|
+
if (allBranches) {
|
|
489
|
+
args.push('--all');
|
|
490
|
+
} else if (branch) {
|
|
487
491
|
assertSafeGitRevish(branch, 'log branch');
|
|
488
492
|
args.push(branch);
|
|
489
493
|
}
|
|
@@ -503,7 +507,7 @@ export class GitService {
|
|
|
503
507
|
if (hasMore) commits.pop(); // Remove the extra one
|
|
504
508
|
|
|
505
509
|
// Get total count
|
|
506
|
-
const countRef = branch ?? 'HEAD';
|
|
510
|
+
const countRef = allBranches ? '--all' : (branch ?? 'HEAD');
|
|
507
511
|
const countResult = await execGit(['rev-list', '--count', countRef], cwd);
|
|
508
512
|
const total = parseInt(countResult.stdout.trim()) || commits.length;
|
|
509
513
|
|