@takboo/dsh-coopanion 0.4.19 → 0.4.21
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/README.md +3 -2
- package/THIRD_PARTY_NOTICES.md +4 -0
- package/assets/coopanion.png +0 -0
- package/assets/coopanion.svg +9 -0
- package/dist/bridge.js +38 -6
- package/dist/bridge.js.map +2 -2
- package/dist/build-info.json +2 -2
- package/dist/client.js +30 -1
- package/dist/index.js +47 -11
- package/dist/index.js.map +2 -2
- package/docs/README.md +2 -0
- package/docs/compatibility.md +41 -27
- package/docs/desktop-recovery-contract.md +1 -1
- package/docs/development.md +22 -3
- package/docs/market/takboo__dsh-coopanion.yml +1 -0
- package/docs/notification-contract.md +1 -1
- package/docs/release-notes.md +16 -0
- package/docs/releasing.md +32 -5
- package/docs/session-chat-contract.md +1 -1
- package/docs/usage.md +7 -7
- package/npm-shrinkwrap.json +2 -2
- package/package.json +5 -1
- package/scripts/check-package.mjs +9 -0
- package/scripts/compatibility/check.mjs +10 -2
- package/scripts/compatibility/discover.mjs +8 -0
- package/scripts/compatibility/planning.mjs +1 -1
- package/scripts/compatibility/published.mjs +157 -0
- package/scripts/compatibility/report.mjs +39 -9
- package/scripts/compatibility/runner.mjs +6 -3
- package/scripts/verify-engineering.sh +91 -0
- package/src/client/Settings.tsx +8 -1
- package/src/client/locales.ts +6 -0
- package/src/controls.ts +17 -11
- package/src/desktop-lifecycle.ts +11 -0
- package/src/electron-runtime.ts +25 -7
- package/tests/compatibility-monitor.mjs +32 -0
- package/tests/electron-startup.test.ts +29 -4
- package/tests/engineering-targets.json +12 -0
- package/tests/engineering-web-probe.mjs +58 -0
- package/tests/install.mjs +11 -0
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
import assert from 'node:assert/strict';
|
|
2
|
+
import { spawn } from 'node:child_process';
|
|
3
|
+
import { createHash } from 'node:crypto';
|
|
4
|
+
import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
|
|
5
|
+
import { tmpdir } from 'node:os';
|
|
6
|
+
import { delimiter, join, resolve } from 'node:path';
|
|
7
|
+
import { setTimeout as delay } from 'node:timers/promises';
|
|
8
|
+
import { pathToFileURL } from 'node:url';
|
|
9
|
+
import { chromium } from 'playwright-core';
|
|
10
|
+
import { discover } from './discover.mjs';
|
|
11
|
+
import { FetchError, request } from './common.mjs';
|
|
12
|
+
import { hostDependencies } from './reviewed-dependencies.mjs';
|
|
13
|
+
import { commit, isolatedEnv, command, npmCli, StageError } from './runner.mjs';
|
|
14
|
+
import { packageName } from '../release-support.mjs';
|
|
15
|
+
|
|
16
|
+
const scratch = await mkdtemp(join(tmpdir(), 'coopanion-published-'));
|
|
17
|
+
const output = resolve(process.env.DSH_REPORT_DIR ?? 'artifacts/compat-published');
|
|
18
|
+
const runtime = join(scratch, 'runtime');
|
|
19
|
+
const report = { schema: 1, kind: 'published', sourceCommit: commit(), platform: process.platform, arch: process.arch, status: 'running', stages: [] };
|
|
20
|
+
const env = await isolatedEnv(scratch);
|
|
21
|
+
env.PATH = join(runtime, 'node_modules', '.bin') + delimiter + env.PATH;
|
|
22
|
+
env.npm_config_ignore_scripts = 'true';
|
|
23
|
+
const run = (name, file, args, options) => command(report, output, name, file, args, { cwd: scratch, env, ...options });
|
|
24
|
+
const npm = (name, args) => run(name, process.execPath, [npmCli(), ...args], { setup: true });
|
|
25
|
+
let phase = 'setup', browser, host;
|
|
26
|
+
|
|
27
|
+
async function snapshot(path) {
|
|
28
|
+
return readFile(path).catch(error => {
|
|
29
|
+
if (error.code !== 'ENOENT') throw error;
|
|
30
|
+
return null;
|
|
31
|
+
});
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
async function probeWeb(cli, packedProbe) {
|
|
35
|
+
phase = 'browser';
|
|
36
|
+
browser = await chromium.launch({ headless: true, env });
|
|
37
|
+
report.browser = browser.version();
|
|
38
|
+
report.stages.push({ name: phase, status: 'passed' });
|
|
39
|
+
phase = 'web-boot';
|
|
40
|
+
host = spawn(process.execPath, [cli, '--profile', 'probe', '--port', '0', '--no-open'], { cwd: scratch, env, detached: true, stdio: ['ignore', 'pipe', 'pipe'] });
|
|
41
|
+
const url = await new Promise((resolve, reject) => {
|
|
42
|
+
let output = '';
|
|
43
|
+
const timer = setTimeout(() => finish(new StageError('web-boot timeout', 'retry')), 60_000);
|
|
44
|
+
function finish(error, url) {
|
|
45
|
+
clearTimeout(timer);
|
|
46
|
+
if (error) reject(error);
|
|
47
|
+
else resolve(url);
|
|
48
|
+
}
|
|
49
|
+
const observe = chunk => {
|
|
50
|
+
output = (output + chunk).slice(-16000);
|
|
51
|
+
const url = output.match(/http:\/\/127\.0\.0\.1:\d+\/\?token=[A-Za-z0-9_-]+/)?.[0];
|
|
52
|
+
if (url) finish(null, url);
|
|
53
|
+
};
|
|
54
|
+
host.stdout.on('data', observe);
|
|
55
|
+
host.stderr.on('data', observe);
|
|
56
|
+
host.once('error', error => finish(new StageError(error.code, 'retry')));
|
|
57
|
+
host.once('exit', (code, signal) => finish(new StageError(`web-boot exited ${code ?? signal}`, signal ? 'retry' : 'failed')));
|
|
58
|
+
});
|
|
59
|
+
report.stages.push({ name: phase, status: 'passed' });
|
|
60
|
+
phase = 'web-navigation';
|
|
61
|
+
const page = await browser.newPage({ locale: 'en-US' });
|
|
62
|
+
page.setDefaultTimeout(15_000);
|
|
63
|
+
assert((await page.goto(url, { timeout: 30_000 }))?.ok(), 'DSH browser navigation failed');
|
|
64
|
+
report.stages.push({ name: phase, status: 'passed' });
|
|
65
|
+
phase = 'web-ready';
|
|
66
|
+
await packedProbe.prepareClient(page);
|
|
67
|
+
report.stages.push({ name: phase, status: 'passed' });
|
|
68
|
+
phase = 'plugin-web';
|
|
69
|
+
report.observed = await packedProbe.verifyClient(page);
|
|
70
|
+
report.stages.push({ name: phase, status: 'passed' });
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
try {
|
|
74
|
+
assert.equal(process.platform, 'linux', 'Run the published browser track in Linux Docker');
|
|
75
|
+
report.target = process.env.DSH_TARGET_JSON ? JSON.parse(process.env.DSH_TARGET_JSON)
|
|
76
|
+
: (await discover({ manual: process.env.DSH_VERSION, token: process.env.GH_TOKEN, local: true }))[0];
|
|
77
|
+
assert(report.target, 'Choose an exact DSH target');
|
|
78
|
+
const { version, published } = report.target;
|
|
79
|
+
report.version = version;
|
|
80
|
+
if (!published || !report.target.npm?.integrity) throw new FetchError('Wait for both exact npm publications');
|
|
81
|
+
const metadata = await request(`https://registry.npmjs.org/${encodeURIComponent(packageName)}/${encodeURIComponent(published.version)}`);
|
|
82
|
+
assert.equal(metadata.name, packageName);
|
|
83
|
+
assert.equal(metadata.version, published.version);
|
|
84
|
+
assert.equal(metadata.dist.integrity, published.integrity);
|
|
85
|
+
const bytes = await request(metadata.dist.tarball, { responseType: 'bytes' });
|
|
86
|
+
assert.equal(`sha512-${createHash('sha512').update(bytes).digest('base64')}`, published.integrity);
|
|
87
|
+
report.package = { ...published, sha256: createHash('sha256').update(bytes).digest('hex') };
|
|
88
|
+
const archive = join(scratch, 'published.tgz');
|
|
89
|
+
await writeFile(archive, bytes);
|
|
90
|
+
const readPacked = async path => run('packed-' + path.split('/').at(-1), 'tar', ['-xOf', archive, `package/${path}`], { captureStdout: true });
|
|
91
|
+
const manifest = JSON.parse(await readPacked('package.json'));
|
|
92
|
+
assert.equal(manifest.name, packageName);
|
|
93
|
+
assert.equal(manifest.version, published.version);
|
|
94
|
+
const build = JSON.parse(await readPacked('dist/build-info.json'));
|
|
95
|
+
assert.match(build.commit, /^[a-f0-9]{40}$/);
|
|
96
|
+
assert.equal(build.dirty, false);
|
|
97
|
+
report.package.sourceCommit = build.commit;
|
|
98
|
+
|
|
99
|
+
report.hostDependencies = hostDependencies(version);
|
|
100
|
+
await npm('host-install', ['install', '--prefix', runtime, '--no-audit', '--no-fund', 'pnpm@11.28.5', ...Object.entries(report.hostDependencies).map(([name, exact]) => `${name}@${exact}`)]);
|
|
101
|
+
const lock = JSON.parse(await readFile(join(runtime, 'package-lock.json'), 'utf8'));
|
|
102
|
+
assert.equal(lock.packages['node_modules/@deepseek-ai/dsh'].integrity, report.target.npm.integrity);
|
|
103
|
+
await npm('host-dependency-tree', ['ls', '--all', '--prefix', runtime]);
|
|
104
|
+
const cli = join(runtime, 'node_modules/@deepseek-ai/dsh/lib/bin.js');
|
|
105
|
+
const dsh = (name, args, options) => run(name, process.execPath, [cli, ...args], options);
|
|
106
|
+
assert.equal((await dsh('host-version', ['--version'], { captureStdout: true })).trim(), version);
|
|
107
|
+
const { evaluatePluginCompatibility } = await import(pathToFileURL(join(runtime, 'node_modules/@deepseek-ai/dsh-app-boot/lib/index.js')).href);
|
|
108
|
+
const refusal = evaluatePluginCompatibility(manifest, {}, version);
|
|
109
|
+
const dump = ['--profile', 'probe', '--dump-config'];
|
|
110
|
+
await dsh('profile-setup', ['--from-default-profile', 'web', ...dump], { setup: true });
|
|
111
|
+
const profile = join(env.DSH_HOME, 'profiles', 'probe');
|
|
112
|
+
const profilePaths = ['package.json', 'pnpm-lock.yaml', 'cordis.patch.yml'].map(name => join(profile, name));
|
|
113
|
+
const before = await Promise.all(profilePaths.map(snapshot));
|
|
114
|
+
phase = 'admission';
|
|
115
|
+
await dsh('admission', ['plugin', '--profile', 'probe', 'add', archive], refusal ? {
|
|
116
|
+
expectedRefusal: log => log.includes('engines.dsh') && log.includes(`${manifest.name}@${manifest.version}`)
|
|
117
|
+
&& log.includes(version) && log.includes(manifest.engines.dsh),
|
|
118
|
+
} : {});
|
|
119
|
+
assert.equal(await snapshot(join(profile, 'compatibility.json')), null, 'No compatibility override may be written');
|
|
120
|
+
if (refusal) {
|
|
121
|
+
assert.deepEqual(await Promise.all(profilePaths.map(snapshot)), before, 'Refusal altered profile files');
|
|
122
|
+
assert(!(await dsh('refusal-profile', dump)).includes(packageName), 'Refused package survived in composed profile');
|
|
123
|
+
report.admission = 'refused-as-expected';
|
|
124
|
+
} else {
|
|
125
|
+
const installed = JSON.parse(await readFile(join(profile, 'node_modules', packageName, 'package.json'), 'utf8'));
|
|
126
|
+
assert.equal(installed.version, published.version);
|
|
127
|
+
assert.equal(JSON.parse(await readFile(profilePaths[0], 'utf8')).dependencies[packageName], `file:${archive}`);
|
|
128
|
+
assert((await dsh('admitted-profile', dump)).includes(packageName));
|
|
129
|
+
report.admission = 'admitted';
|
|
130
|
+
const source = await readPacked('tests/engineering-web-probe.mjs');
|
|
131
|
+
report.probeSha256 = createHash('sha256').update(source).digest('hex');
|
|
132
|
+
const probe = join(scratch, 'published-probe.mjs');
|
|
133
|
+
await writeFile(probe, source);
|
|
134
|
+
await probeWeb(cli, await import(pathToFileURL(probe).href));
|
|
135
|
+
}
|
|
136
|
+
report.status = 'passed';
|
|
137
|
+
} catch (error) {
|
|
138
|
+
report.status = error instanceof StageError ? error.status : error instanceof FetchError || phase === 'browser' ? 'retry' : 'failed';
|
|
139
|
+
report.failurePhase = phase;
|
|
140
|
+
// The launch URL is local and contains a one-time token.
|
|
141
|
+
report.reason = String(error.message).replace(/https?:\/\/[^\s"'<>]+/g, '[url]').slice(0, 2000);
|
|
142
|
+
} finally {
|
|
143
|
+
if (host?.pid && host.exitCode === null && host.signalCode === null) {
|
|
144
|
+
const stop = signal => {
|
|
145
|
+
try { process.kill(-host.pid, signal); } catch (error) { if (error.code !== 'ESRCH') throw error; }
|
|
146
|
+
};
|
|
147
|
+
stop('SIGTERM');
|
|
148
|
+
await delay(500);
|
|
149
|
+
stop('SIGKILL');
|
|
150
|
+
}
|
|
151
|
+
await browser?.close();
|
|
152
|
+
await rm(scratch, { recursive: true, force: true });
|
|
153
|
+
await mkdir(output, { recursive: true });
|
|
154
|
+
await writeFile(join(output, 'report.json'), JSON.stringify(report, null, 2) + '\n');
|
|
155
|
+
console.log(JSON.stringify({ status: report.status, admission: report.admission, reason: report.reason }));
|
|
156
|
+
process.exitCode = report.status === 'passed' ? 0 : 1;
|
|
157
|
+
}
|
|
@@ -18,7 +18,7 @@ export function issueBody(target, reports, { status, attempts, runUrl, sourceCom
|
|
|
18
18
|
`Upstream commit: ${safe(target.commit ?? target.npm.commit ?? 'not available; npm publication only')}`,
|
|
19
19
|
`Plugin source commit: \`${safe(sourceCommit)}\`; [Actions evidence](${runUrl})`,
|
|
20
20
|
`Result: **${status}** (attempt ${attempts})`, '',
|
|
21
|
-
...reports.map(r => `- ${r.kind === 'desktop' ? 'Desktop ' : 'SDK '}${safe(r.platform)}/${safe(r.arch)}: **${safe(r.status)}** — ${safe(r.reason)}`), '',
|
|
21
|
+
...reports.map(r => `- ${r.kind === 'desktop' ? 'Desktop ' : r.kind === 'published' ? 'Published npm ' : 'SDK candidate '}${safe(r.platform)}/${safe(r.arch)}: **${safe(r.status)}** — ${safe(r.reason ?? r.admission)}`), '',
|
|
22
22
|
...componentLines(components),
|
|
23
23
|
proposalUrl ? `Dependency proposal: ${proposalUrl}` : '', safe(details), '',
|
|
24
24
|
'This is candidate evidence, not a production compatibility declaration. Formal host support is unchanged. No automatic merge, tag or release.',
|
|
@@ -38,6 +38,26 @@ function componentLines(components = {}) {
|
|
|
38
38
|
export function validateReport(r, target, sourceCommit, kind) {
|
|
39
39
|
assert.equal(r.version, target.version); assert.equal(r.sourceCommit, sourceCommit);
|
|
40
40
|
assert.equal(r.target?.identity, target.identity);
|
|
41
|
+
if (kind === 'published') {
|
|
42
|
+
assert.deepEqual(r.target.published, target.published);
|
|
43
|
+
assert.equal(r.target.npm.integrity, target.npm.integrity);
|
|
44
|
+
assert.equal(r.kind, 'published');
|
|
45
|
+
assert.equal(r.platform, 'linux');
|
|
46
|
+
assert(['passed', 'failed', 'retry'].includes(r.status));
|
|
47
|
+
if (r.status === 'passed') {
|
|
48
|
+
const { sha256, sourceCommit: publishedCommit, ...publication } = r.package;
|
|
49
|
+
assert.deepEqual(publication, target.published);
|
|
50
|
+
assert.match(sha256, /^[a-f\d]{64}$/);
|
|
51
|
+
assert.match(publishedCommit, /^[a-f\d]{40}$/);
|
|
52
|
+
assert(['admitted', 'refused-as-expected'].includes(r.admission));
|
|
53
|
+
assert(r.stages.some(stage => stage.name === 'admission' && stage.status === (r.admission === 'admitted' ? 'passed' : r.admission)));
|
|
54
|
+
if (r.admission === 'admitted') {
|
|
55
|
+
assert.match(r.probeSha256, /^[a-f\d]{64}$/);
|
|
56
|
+
assert(r.stages.some(stage => stage.name === 'plugin-web' && stage.status === 'passed'));
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
return r;
|
|
60
|
+
}
|
|
41
61
|
assert.equal(r.productionAdmissionChanged, false); assert.equal(r.productionSourcesStable, true);
|
|
42
62
|
assert(['passed', 'partial', 'failed', 'retry'].includes(r.status));
|
|
43
63
|
if (['passed', 'partial'].includes(r.status) && reviewedDependencies(target.version)) {
|
|
@@ -55,7 +75,15 @@ export function validateReport(r, target, sourceCommit, kind) {
|
|
|
55
75
|
}
|
|
56
76
|
} else {
|
|
57
77
|
assert(!r.kind); assert(['darwin/arm64','win32/x64','linux/x64'].includes(`${r.platform}/${r.arch}`));
|
|
58
|
-
if (['passed', 'partial'].includes(r.status))
|
|
78
|
+
if (['passed', 'partial'].includes(r.status)) {
|
|
79
|
+
for (const name of ['host-install', 'normal-admission', 'candidate-installation']) assert(r.stages.some(s => s.name === name && s.status === 'passed'), `Missing SDK stage ${name}`);
|
|
80
|
+
if (target.published) {
|
|
81
|
+
assert.deepEqual(r.candidatePhases, ['admitted', 'host-contracts', 'web-settings-and-native-window']);
|
|
82
|
+
assert.equal(r.package?.sha256, r.archiveSha256);
|
|
83
|
+
assert.equal(r.package?.sourceCommit, sourceCommit);
|
|
84
|
+
assert.match(r.package?.integrity, /^sha512-[A-Za-z0-9+/]{86}==$/);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
59
87
|
}
|
|
60
88
|
if (['passed', 'partial'].includes(r.status)) assert(/^[a-f\d]{64}$/.test(r.archiveSha256));
|
|
61
89
|
return r;
|
|
@@ -70,12 +98,14 @@ export function completedComponents(target, reports, previous, { run, sourceComm
|
|
|
70
98
|
continue;
|
|
71
99
|
}
|
|
72
100
|
const rows = reports.filter(r => key === 'desktop' ? r.kind === 'desktop' : !r.kind);
|
|
73
|
-
|
|
74
|
-
|
|
101
|
+
const published = reports.find(r => r.kind === 'published');
|
|
102
|
+
const hasPublished = key === 'sdk' && Boolean(target.published);
|
|
103
|
+
let status = hasPublished ? aggregate([...rows, published], 4) : aggregate(rows, key === 'desktop' ? 1 : 3);
|
|
104
|
+
if (rows.length > 1 && new Set(rows.map(r => r.archiveSha256)).size !== 1) status = 'failed';
|
|
75
105
|
components[key] = { identity: identities[key], status,
|
|
76
106
|
attempts: old?.identity === identities[key] ? old.attempts + (old.run === run ? 0 : 1) : 1,
|
|
77
107
|
run, sourceCommit, updatedAt: now,
|
|
78
|
-
reason: key === 'desktop' && rows[0]?.reason ? safe(rows[0].reason) : `${rows.length}/${key === 'desktop' ? 1 : 3} component reports received`,
|
|
108
|
+
reason: key === 'desktop' && rows[0]?.reason ? safe(rows[0].reason) : `${rows.length}/${key === 'desktop' ? 1 : 3} component reports received${hasPublished ? `; published npm: ${published?.admission ?? published?.status ?? 'missing'}` : ''}`,
|
|
79
109
|
...(key === 'desktop' && rows[0]?.artifact ? { artifactSha256: rows[0].artifact.sha256 } : {}) };
|
|
80
110
|
}
|
|
81
111
|
return validComponents(components);
|
|
@@ -150,17 +180,17 @@ export async function readArtifacts(directory, target, sourceCommit) {
|
|
|
150
180
|
const candidateDirectory = single?.kind === 'prepare' ? directory : join(directory, 'dsh-candidate-' + target.version);
|
|
151
181
|
try { candidate = JSON.parse(await readFile(join(candidateDirectory, 'candidate.json'), 'utf8')); } catch {}
|
|
152
182
|
const entries = (await readdir(directory).catch(() => [])).map(name => ({ name,
|
|
153
|
-
kind: name.startsWith('dsh-desktop-') ? 'desktop' : name.startsWith('dsh-check-') ? 'sdk' : null }));
|
|
154
|
-
if (single && single.kind !== 'prepare') entries.push({ name: '.', kind: single.kind
|
|
183
|
+
kind: name.startsWith('dsh-desktop-') ? 'desktop' : name.startsWith('dsh-check-') ? 'sdk' : name.startsWith('dsh-published-') ? 'published' : null }));
|
|
184
|
+
if (single && single.kind !== 'prepare') entries.push({ name: '.', kind: single.kind ?? 'sdk' });
|
|
155
185
|
for (const { name, kind } of entries) {
|
|
156
186
|
if (!kind) continue;
|
|
157
187
|
try {
|
|
158
188
|
const r = validateReport(JSON.parse(await readFile(join(directory, name, 'report.json'), 'utf8')), target, sourceCommit, kind);
|
|
159
|
-
if (['passed', 'partial'].includes(r.status)) {
|
|
189
|
+
if (kind !== 'published' && ['passed', 'partial'].includes(r.status)) {
|
|
160
190
|
assert.equal(candidate?.sourceCommit, sourceCommit); assert.equal(candidate?.targetIdentity, target.identity);
|
|
161
191
|
assert.equal(r.archiveSha256, candidate?.archiveSha256, 'All component reports must consume the prepared archive');
|
|
162
192
|
}
|
|
163
|
-
assert(!reports.some(old =>
|
|
193
|
+
assert(!reports.some(old => old.kind === r.kind && old.platform === r.platform && old.arch === r.arch));
|
|
164
194
|
reports.push(r);
|
|
165
195
|
} catch (error) { console.error(`Incomplete report ${name}: ${safe(error.message)}`); }
|
|
166
196
|
}
|
|
@@ -30,7 +30,7 @@ export async function isolatedEnv(scratch) {
|
|
|
30
30
|
return env;
|
|
31
31
|
}
|
|
32
32
|
export class StageError extends Error { constructor(name, status) { super(`${name}: ${status}`); this.status = status; } }
|
|
33
|
-
export async function command(report, output, name, file, args, { cwd = root, env = process.env, setup = false, captureStdout = false, timeout = 15 * 60000 } = {}) {
|
|
33
|
+
export async function command(report, output, name, file, args, { cwd = root, env = process.env, setup = false, captureStdout = false, expectedRefusal, timeout = 15 * 60000 } = {}) {
|
|
34
34
|
await mkdir(output, { recursive: true });
|
|
35
35
|
let log = '', stdout = '', timedOut = false, error;
|
|
36
36
|
const result = await new Promise(done => {
|
|
@@ -49,11 +49,14 @@ export async function command(report, output, name, file, args, { cwd = root, en
|
|
|
49
49
|
});
|
|
50
50
|
log = log.replace(/(token|password|authorization)\s*[=:]\s*[^\s]+/gi, '$1=[redacted]');
|
|
51
51
|
await writeFile(join(output, name + '.log'), log);
|
|
52
|
-
const
|
|
52
|
+
const refused = result.code > 0 && !result.signal && !error && !timedOut && expectedRefusal?.(log);
|
|
53
|
+
let status = subprocessStatus({ ...result, error, timedOut, setup, log });
|
|
54
|
+
if (refused) status = 'refused-as-expected';
|
|
55
|
+
else if (expectedRefusal && status === 'passed') status = 'failed';
|
|
53
56
|
report.stages.push({ name, status, exitCode: result.code, signal: result.signal, timedOut });
|
|
54
57
|
await writeFile(join(output, 'report.json'), JSON.stringify(report, null, 2) + '\n');
|
|
55
58
|
console.log(`${name}: ${status}`);
|
|
56
|
-
if (status !== 'passed') { console.error(log.slice(-6000)); throw new StageError(name, status); }
|
|
59
|
+
if (status !== 'passed' && status !== 'refused-as-expected') { console.error(log.slice(-6000)); throw new StageError(name, status); }
|
|
57
60
|
return captureStdout ? stdout : log;
|
|
58
61
|
}
|
|
59
62
|
export const npmCli = () => { if (!process.env.npm_execpath) throw new Error('Run through npm run compat:<command>'); return process.env.npm_execpath; };
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
#!/usr/bin/env bash
|
|
2
|
+
set -euo pipefail
|
|
3
|
+
|
|
4
|
+
if [[ $# -ne 3 ]]; then
|
|
5
|
+
echo 'Usage: bash scripts/verify-engineering.sh <engineering-checkout> <candidate.tgz> <new-report-directory>' >&2
|
|
6
|
+
exit 2
|
|
7
|
+
fi
|
|
8
|
+
|
|
9
|
+
root="$(cd "$(dirname "$0")/.." && pwd -P)"
|
|
10
|
+
engineering_commit=9ed36752356975cd7d47c11d63744220443c1bf7
|
|
11
|
+
targets="$root/tests/engineering-targets.json"
|
|
12
|
+
probe="$root/tests/engineering-web-probe.mjs"
|
|
13
|
+
report_dir=$3
|
|
14
|
+
|
|
15
|
+
if ! git -C "$root" diff --quiet HEAD -- tests/engineering-targets.json tests/engineering-web-probe.mjs; then
|
|
16
|
+
echo 'Commit the host targets and Web probe before verification.' >&2
|
|
17
|
+
exit 2
|
|
18
|
+
fi
|
|
19
|
+
|
|
20
|
+
scratch="$(mktemp -d)"
|
|
21
|
+
trap 'rm -rf -- "$scratch"' EXIT
|
|
22
|
+
base="$scratch/engineering"
|
|
23
|
+
candidate="$scratch/candidate.tgz"
|
|
24
|
+
mkdir "$base"
|
|
25
|
+
git -C "$1" archive "$engineering_commit" | tar -xf - -C "$base"
|
|
26
|
+
cp -- "$2" "$candidate"
|
|
27
|
+
|
|
28
|
+
source_commit="$(tar -xOf "$candidate" package/dist/build-info.json | node -e '
|
|
29
|
+
const { schema, commit, dirty } = JSON.parse(require("node:fs").readFileSync(0, "utf8"));
|
|
30
|
+
if (schema !== 1 || dirty !== false || !/^[0-9a-f]{40}$/.test(commit)) {
|
|
31
|
+
throw new Error("Expected a candidate built from a clean, identified commit");
|
|
32
|
+
}
|
|
33
|
+
console.log(commit);
|
|
34
|
+
')"
|
|
35
|
+
if ! git -C "$root" merge-base --is-ancestor "$source_commit" HEAD; then
|
|
36
|
+
echo 'The candidate source commit must be in this checkout history.' >&2
|
|
37
|
+
exit 2
|
|
38
|
+
fi
|
|
39
|
+
|
|
40
|
+
for input in "$targets" "$probe"; do
|
|
41
|
+
relative=${input#"$root/"}
|
|
42
|
+
git -C "$root" show "$source_commit:$relative" > "$scratch/source-input"
|
|
43
|
+
tar -xOf "$candidate" "package/$relative" > "$scratch/packed-input"
|
|
44
|
+
cmp "$scratch/source-input" "$scratch/packed-input"
|
|
45
|
+
cmp "$scratch/source-input" "$input"
|
|
46
|
+
done
|
|
47
|
+
|
|
48
|
+
mkdir -p -- "$(dirname "$report_dir")"
|
|
49
|
+
mkdir -m 700 -- "$report_dir"
|
|
50
|
+
report="$report_dir/host.json"
|
|
51
|
+
bash "$base/scripts/run-container.sh" all "$targets" "$probe" "$candidate" "$source_commit" "$report"
|
|
52
|
+
|
|
53
|
+
# Reuse the local image from the shared runner. The package lock controls the
|
|
54
|
+
# Playwright version for Coopanion's browser regression.
|
|
55
|
+
image_and_digest="$(node -e '
|
|
56
|
+
const { image, provenance } = JSON.parse(require("node:fs").readFileSync(process.argv[1], "utf8"));
|
|
57
|
+
const digest = provenance.inputs.tarballSha256;
|
|
58
|
+
if (provenance.producer.commit !== process.argv[2] || provenance.inputs.sourceCommit !== process.argv[3]) {
|
|
59
|
+
throw new Error("Report producer or candidate source commit does not match the verification inputs");
|
|
60
|
+
}
|
|
61
|
+
if (!/^sha256:[0-9a-f]{64}$/.test(image) || !/^[0-9a-f]{64}$/.test(digest)) {
|
|
62
|
+
throw new Error("Expected a local image ID and candidate SHA-256");
|
|
63
|
+
}
|
|
64
|
+
console.log(image, digest);
|
|
65
|
+
' "$report" "$engineering_commit" "$source_commit")"
|
|
66
|
+
read -r image package_sha256 <<< "$image_and_digest"
|
|
67
|
+
|
|
68
|
+
docker run --rm --init -i --shm-size=1g --cap-drop=ALL --security-opt=no-new-privileges \
|
|
69
|
+
--mount "type=bind,src=$candidate,dst=/input/candidate.tgz,readonly" \
|
|
70
|
+
"$image" bash -s -- "$image" "$package_sha256" <<'CONTAINER' 2>&1 | tee "$report_dir/inbox-ui.log"
|
|
71
|
+
set -euo pipefail
|
|
72
|
+
printf 'Image: %s\nCandidate SHA-256: %s\n' "$1" "$2"
|
|
73
|
+
echo "$2 /input/candidate.tgz" | sha256sum --check --status
|
|
74
|
+
work="$(mktemp -d)"
|
|
75
|
+
cd "$work"
|
|
76
|
+
tar -xf /input/candidate.tgz
|
|
77
|
+
cd package
|
|
78
|
+
export PLAYWRIGHT_BROWSERS_PATH="$work/browsers"
|
|
79
|
+
npm ci --ignore-scripts --no-audit --no-fund
|
|
80
|
+
./node_modules/.bin/playwright-core install chromium
|
|
81
|
+
node --input-type=module <<'JS'
|
|
82
|
+
import { chromium } from 'playwright-core';
|
|
83
|
+
const browser = await chromium.launch({ headless: true, args: ['--no-sandbox'] });
|
|
84
|
+
try {
|
|
85
|
+
console.log('Chromium:', browser.version());
|
|
86
|
+
} finally {
|
|
87
|
+
await browser.close();
|
|
88
|
+
}
|
|
89
|
+
JS
|
|
90
|
+
npm run test:inbox-ui
|
|
91
|
+
CONTAINER
|
package/src/client/Settings.tsx
CHANGED
|
@@ -91,6 +91,10 @@ export function Settings({ form, call, local, notifier, t }: SettingsProps) {
|
|
|
91
91
|
const running = status?.phase === 'running';
|
|
92
92
|
const disabled = !local || busy || status?.phase === 'starting' || status?.phase === 'stopping';
|
|
93
93
|
const statusText = !status ? t('loading') : status.phase === 'running' ? t(status.visible ? 'running' : 'hidden') : t(status.phase);
|
|
94
|
+
const runtimeFailure = status?.runtimeFailure;
|
|
95
|
+
const runtimeReason = runtimeFailure && (runtimeFailure.reason === 'http' ? `${t('runtimeHttp')} (HTTP ${runtimeFailure.httpStatus})` : t(({
|
|
96
|
+
network: 'runtimeNetwork', timeout: 'runtimeTimeout', unavailable: 'runtimeUnavailable', install: 'runtimeInstall',
|
|
97
|
+
} as const)[runtimeFailure.reason]));
|
|
94
98
|
return <div className="dsh-coopanion-settings" data-testid="coopanion-settings">
|
|
95
99
|
<h2>{t('title')}</h2><p>{t('intro')} {t('languageHint')}</p>
|
|
96
100
|
<section className="pet-card" aria-label={t('runtime')}>
|
|
@@ -103,7 +107,10 @@ export function Settings({ form, call, local, notifier, t }: SettingsProps) {
|
|
|
103
107
|
<Button disabled={!local || status?.phase === 'stopped' || status?.phase === 'stopping'} onClick={() => void command('stop')}>{t('stop')}</Button>
|
|
104
108
|
</div>
|
|
105
109
|
{status?.recoveryAttempt ? <p role="status">{t('recoveryHint')}: {status.recoveryAttempt} / 3</p> : null}
|
|
106
|
-
{
|
|
110
|
+
{runtimeReason ? <p className="pet-error" role="alert" data-testid="pet-runtime-failure">
|
|
111
|
+
{t('runtimeMissing')}{runtimeReason}{t('runtimeRetry')}{' '}
|
|
112
|
+
<a href="https://github.com/takboo/dsh-coopanion/blob/main/docs/usage.md#electron-运行时准备" target="_blank" rel="noreferrer">{t('runtimeGuide')}</a>
|
|
113
|
+
</p> : failure || status?.error ? <p className="pet-error" role="alert">{failure || status?.error}</p> : null}
|
|
107
114
|
</section>
|
|
108
115
|
<section className="pet-card" aria-label={t('preferences')}>
|
|
109
116
|
<h3>{t('preferences')}</h3>
|
package/src/client/locales.ts
CHANGED
|
@@ -5,6 +5,9 @@ export const zh = {
|
|
|
5
5
|
start: '启动桌宠', show: '显示桌宠', hide: '隐藏桌宠', restart: '重启', stop: '关闭桌宠',
|
|
6
6
|
recovering: '等待自动恢复…', recoveryHint: '自动恢复次数(最多 3 次)',
|
|
7
7
|
runtimeHint: '意外退出会有限重试,失败后可手动重启。隐藏时按系统通知开关接收提醒;进程退出会丢失窗口内草稿。',
|
|
8
|
+
runtimeMissing: '缺少 Electron 运行时:', runtimeHttp: '下载被拒绝', runtimeNetwork: '下载连接失败',
|
|
9
|
+
runtimeTimeout: '下载或安装超过四分钟', runtimeUnavailable: '找不到可用的安装器或运行时', runtimeInstall: '安装失败',
|
|
10
|
+
runtimeRetry: '。检查网络后点击“启动桌宠”,或按指南设置镜像、手动安装或配置 electronPath。', runtimeGuide: 'Electron 运行时准备指南',
|
|
8
11
|
preferences: '偏好设置', autoStart: '随 Harness 启动', autoStartHint: '下次启动 Harness 时自动打开桌宠。',
|
|
9
12
|
roam: '闲时走动', roamHint: '自主活动和邀请的总许可;需选择安静陪伴或互动陪伴。', notifications: '任务通知', notificationsHint: '任务完成、出错、审批和 AI 提问时提醒你。',
|
|
10
13
|
diagnostics: '本地诊断', diagnosticsHint: '默认关闭。允许本机独立采样器读取资源和活动计数,不记录聊天内容;关闭后停止提供数据。',
|
|
@@ -31,6 +34,9 @@ export const en: Record<LocaleKey, string> = {
|
|
|
31
34
|
start: 'Start pet', show: 'Show pet', hide: 'Hide pet', restart: 'Restart', stop: 'Close pet',
|
|
32
35
|
recovering: 'Waiting to recover…', recoveryHint: 'Automatic recovery attempts (up to 3)',
|
|
33
36
|
runtimeHint: 'Unexpected exits retry a limited number of times. You can restart manually after failure. Hidden pets follow system notification settings. Window drafts are lost when the process exits.',
|
|
37
|
+
runtimeMissing: 'Electron runtime is missing: ', runtimeHttp: 'download rejected', runtimeNetwork: 'download connection failed',
|
|
38
|
+
runtimeTimeout: 'download or installation timed out after four minutes', runtimeUnavailable: 'installer or executable unavailable', runtimeInstall: 'installation failed',
|
|
39
|
+
runtimeRetry: '. Check your connection and click Start pet, or follow the guide to use a mirror, install manually, or configure electronPath.', runtimeGuide: 'Electron setup guide',
|
|
34
40
|
preferences: 'Preferences', autoStart: 'Start with Harness', autoStartHint: 'Open the pet automatically the next time Harness starts.',
|
|
35
41
|
roam: 'Roam when idle', roamHint: 'Allow automatic NPC activity and invitations when Quiet or Interactive companionship is selected.', notifications: 'Task notifications', notificationsHint: 'Remind you about completion, errors, approvals and AI questions.',
|
|
36
42
|
diagnostics: 'Local diagnostics', diagnosticsHint: 'Off by default. Allow a separate local sampler to read resource and activity counts without chat content. Turn off to stop providing data.',
|
package/src/controls.ts
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import type { DesktopOptions, PetBridge } from './bridge.ts';
|
|
2
2
|
import type { NotificationRuntime } from './notification-contract.ts';
|
|
3
|
-
import { NativeStartError, type NativeLifecycle } from './desktop-lifecycle.ts';
|
|
3
|
+
import { NativeStartError, RuntimePreparationError, type NativeLifecycle, type RuntimeFailure } from './desktop-lifecycle.ts';
|
|
4
4
|
export { NativeStartError, type NativeLifecycle, type StartLifetime } from './desktop-lifecycle.ts';
|
|
5
5
|
|
|
6
6
|
export type PetCommand = 'start' | 'show' | 'hide' | 'restart' | 'stop' | 'characters';
|
|
7
|
-
export type PetStatus = NotificationRuntime;
|
|
7
|
+
export type PetStatus = NotificationRuntime & { runtimeFailure?: RuntimeFailure };
|
|
8
8
|
/** A host-authored hint. Views render it as a transient toast; it never carries task state or delivery claims. */
|
|
9
9
|
export interface PetHint {
|
|
10
10
|
/** One-line headline. Blank headlines are dropped. */
|
|
@@ -18,7 +18,8 @@ export interface ControlLimits { startTimeoutMs?: number; cleanupTimeoutMs?: num
|
|
|
18
18
|
|
|
19
19
|
/** Commands own a cancellable native generation. Lifecycle acknowledgements alone establish visibility. */
|
|
20
20
|
export class PetControls {
|
|
21
|
-
private state:
|
|
21
|
+
private state: NotificationRuntime = { phase: 'stopped', visible: false, desiredVisible: true, recoveryAttempt: 0, generation: 0, visibilityRevision: 0, suspended: false };
|
|
22
|
+
private runtimeFailure?: RuntimeFailure;
|
|
22
23
|
private queue: Promise<unknown> = Promise.resolve();
|
|
23
24
|
private disposed = false;
|
|
24
25
|
private startup?: AbortController;
|
|
@@ -28,7 +29,7 @@ export class PetControls {
|
|
|
28
29
|
private epoch = 0;
|
|
29
30
|
private wanted = false;
|
|
30
31
|
private cleanupBlocked = false;
|
|
31
|
-
private readonly listeners = new Set<(status:
|
|
32
|
+
private readonly listeners = new Set<(status: NotificationRuntime) => void>();
|
|
32
33
|
private readonly changed = (event: NativeLifecycle) => {
|
|
33
34
|
if (this.disposed || event.generation !== this.state.generation || !Number.isSafeInteger(event.visibilityRevision) || event.visibilityRevision! < this.state.visibilityRevision) return;
|
|
34
35
|
if (event.visibilityRevision === this.state.visibilityRevision && event.visible !== this.state.visible) return;
|
|
@@ -47,10 +48,10 @@ export class PetControls {
|
|
|
47
48
|
constructor(private readonly bridge: PetBridge, private readonly options: () => DesktopOptions, private readonly limits: ControlLimits = {}) {
|
|
48
49
|
bridge.onLifecycle?.(this.changed);
|
|
49
50
|
}
|
|
50
|
-
status(): PetStatus { return { ...this.state }; }
|
|
51
|
+
status(): PetStatus { return { ...this.state, ...(this.runtimeFailure && { runtimeFailure: { ...this.runtimeFailure } }) }; }
|
|
51
52
|
/** Root assembly registers this listener as a context-owned effect. */
|
|
52
|
-
onState(listener: (status:
|
|
53
|
-
this.listeners.add(listener); try { listener(this.
|
|
53
|
+
onState(listener: (status: NotificationRuntime) => void): () => void {
|
|
54
|
+
this.listeners.add(listener); try { listener({ ...this.state }); } catch { /* A view is optional. */ } return () => this.listeners.delete(listener);
|
|
54
55
|
}
|
|
55
56
|
configure(): void { this.bridge.configure?.(this.options()); }
|
|
56
57
|
/**
|
|
@@ -69,9 +70,10 @@ export class PetControls {
|
|
|
69
70
|
if (!title) return false;
|
|
70
71
|
const sessionId = hintSessionId(value.sessionId);
|
|
71
72
|
if (sessionId === false) return false;
|
|
72
|
-
return this.bridge.notify({ title, body, sessionId: sessionId ?? '', kind: 'message' }, this.
|
|
73
|
+
return this.bridge.notify({ title, body, sessionId: sessionId ?? '', kind: 'message' }, { ...this.state });
|
|
73
74
|
}
|
|
74
75
|
command(command: PetCommand): Promise<PetStatus> {
|
|
76
|
+
const alreadyStarting = this.state.phase === 'starting';
|
|
75
77
|
// Intent and cancellation take effect before queued work, including queued starts.
|
|
76
78
|
if (command === 'hide') this.set({ ...this.state, desiredVisible: false });
|
|
77
79
|
else if (command === 'start' || command === 'show' || command === 'characters') this.set({ ...this.state, desiredVisible: true });
|
|
@@ -90,7 +92,9 @@ export class PetControls {
|
|
|
90
92
|
await this.cleanup();
|
|
91
93
|
this.set({ ...this.state, phase: 'stopped', visible: false, suspended: false });
|
|
92
94
|
}
|
|
93
|
-
|
|
95
|
+
// A start/show/characters request received during startup shares that
|
|
96
|
+
// outcome. A fresh command after failure (or a restart) may try again.
|
|
97
|
+
if (command !== 'stop' && command !== 'hide' && this.state.phase !== 'running' && (!alreadyStarting || command === 'restart')) {
|
|
94
98
|
if (this.cleanupBlocked) await this.cleanup();
|
|
95
99
|
this.set({ ...this.state, recoveryAttempt: 0, retryAt: undefined });
|
|
96
100
|
await this.launch(epoch); launched = true;
|
|
@@ -132,6 +136,7 @@ export class PetControls {
|
|
|
132
136
|
const diagnostic = this.message(error).slice(0, 600 - cleanup.length) + cleanup;
|
|
133
137
|
const attempt = this.state.recoveryAttempt ?? 0;
|
|
134
138
|
if (!this.wanted || !recoverable || cleanup || attempt >= 3) {
|
|
139
|
+
this.runtimeFailure = !cleanup && error instanceof RuntimePreparationError ? error.failure : undefined;
|
|
135
140
|
this.set({ ...this.state, phase: 'error', visible: false, suspended: false, retryAt: undefined, error: diagnostic }); return;
|
|
136
141
|
}
|
|
137
142
|
const delay = (this.limits.retryDelaysMs ?? [1000, 3000, 10000])[attempt]!;
|
|
@@ -177,9 +182,10 @@ export class PetControls {
|
|
|
177
182
|
task.then(value => finish(undefined, value), error => finish(error));
|
|
178
183
|
});
|
|
179
184
|
}
|
|
180
|
-
private set(state:
|
|
185
|
+
private set(state: NotificationRuntime): void {
|
|
181
186
|
this.state = state;
|
|
182
|
-
|
|
187
|
+
if (state.phase !== 'error') this.runtimeFailure = undefined;
|
|
188
|
+
for (const listener of this.listeners) { try { listener({ ...state }); } catch { /* View errors cannot stall native cleanup. */ } }
|
|
183
189
|
}
|
|
184
190
|
private enqueue<T>(operation: () => Promise<T>): Promise<T> {
|
|
185
191
|
const pending = this.queue.then(operation); this.queue = pending.catch(() => undefined); return pending;
|
package/src/desktop-lifecycle.ts
CHANGED
|
@@ -8,3 +8,14 @@ export interface NativeLifecycle {
|
|
|
8
8
|
export class NativeStartError extends Error {
|
|
9
9
|
constructor(message: string, readonly recoverable: boolean) { super(message); this.name = 'NativeStartError'; }
|
|
10
10
|
}
|
|
11
|
+
|
|
12
|
+
export type RuntimeFailure = { reason: 'http'; httpStatus: number } | { reason: 'network' | 'timeout' | 'unavailable' | 'install' };
|
|
13
|
+
export class RuntimePreparationError extends NativeStartError {
|
|
14
|
+
constructor(readonly failure: RuntimeFailure, detail?: string) {
|
|
15
|
+
const cause = failure.reason === 'http' ? `download rejected (HTTP ${failure.httpStatus})` : {
|
|
16
|
+
network: 'download connection failed', timeout: 'download or installation timed out (240 seconds)',
|
|
17
|
+
unavailable: 'installer or executable unavailable', install: 'installation failed',
|
|
18
|
+
}[failure.reason];
|
|
19
|
+
super(`Electron runtime is missing: ${cause}${detail ? ` (${detail})` : ''}. Prepare Electron or configure electronPath, then start the pet again.`, false);
|
|
20
|
+
}
|
|
21
|
+
}
|
package/src/electron-runtime.ts
CHANGED
|
@@ -2,12 +2,26 @@ import { spawn } from 'node:child_process';
|
|
|
2
2
|
import { access, readFile } from 'node:fs/promises';
|
|
3
3
|
import { createRequire } from 'node:module';
|
|
4
4
|
import { dirname, join } from 'node:path';
|
|
5
|
-
import {
|
|
5
|
+
import { RuntimePreparationError } from './desktop-lifecycle.ts';
|
|
6
|
+
|
|
7
|
+
function installerFailure(stderr: string, code: number | null): RuntimePreparationError {
|
|
8
|
+
// Electron prints the error before its stack. Only extract allowlisted
|
|
9
|
+
// diagnostics: URLs can contain credentials and stacks expose local paths.
|
|
10
|
+
const summary = stderr.split(/\r?\n/, 1)[0] ?? '';
|
|
11
|
+
const status = /^HTTPError: Response code ([45]\d\d)\b/.exec(summary);
|
|
12
|
+
if (status) return new RuntimePreparationError({ reason: 'http', httpStatus: Number(status[1]) });
|
|
13
|
+
if (/\b(?:ENOTFOUND|EAI_AGAIN|ECONNREFUSED|ECONNRESET|ENETUNREACH|ETIMEDOUT)\b|^TypeError: fetch failed\b/.test(summary)) {
|
|
14
|
+
return new RuntimePreparationError({ reason: 'network' });
|
|
15
|
+
}
|
|
16
|
+
return new RuntimePreparationError({ reason: 'install' }, code === null ? undefined : String(code));
|
|
17
|
+
}
|
|
6
18
|
|
|
7
19
|
// Electron 44's index.js may spawnSync its installer. Resolve files without
|
|
8
20
|
// executing that entrypoint, then prepare missing binaries off the Host loop.
|
|
9
21
|
export async function electronExecutable(signal: AbortSignal): Promise<string> {
|
|
10
|
-
|
|
22
|
+
let directory: string;
|
|
23
|
+
try { directory = dirname(createRequire(import.meta.url).resolve('electron')); }
|
|
24
|
+
catch { throw new RuntimePreparationError({ reason: 'unavailable' }); }
|
|
11
25
|
async function installed(): Promise<string | undefined> {
|
|
12
26
|
let relative: string;
|
|
13
27
|
try { relative = await readFile(join(directory, 'path.txt'), 'utf8'); }
|
|
@@ -24,7 +38,11 @@ export async function electronExecutable(signal: AbortSignal): Promise<string> {
|
|
|
24
38
|
await new Promise<void>((resolve, reject) => {
|
|
25
39
|
if (signal.aborted) { reject(new Error('桌宠启动已取消')); return; }
|
|
26
40
|
const child = spawn(process.execPath, [join(directory, 'install.js')], {
|
|
27
|
-
env: { ...process.env, ELECTRON_RUN_AS_NODE: '1' }, stdio: 'ignore', windowsHide: true,
|
|
41
|
+
env: { ...process.env, ELECTRON_RUN_AS_NODE: '1' }, stdio: ['ignore', 'ignore', 'pipe'], windowsHide: true,
|
|
42
|
+
});
|
|
43
|
+
let stderr = '';
|
|
44
|
+
child.stderr.on('data', (data: Buffer) => {
|
|
45
|
+
if (stderr.length < 512) stderr += data.subarray(0, 512 - stderr.length).toString();
|
|
28
46
|
});
|
|
29
47
|
let failure: Error | undefined, killTimer: ReturnType<typeof setTimeout> | undefined;
|
|
30
48
|
const stop = (error: Error) => {
|
|
@@ -33,18 +51,18 @@ export async function electronExecutable(signal: AbortSignal): Promise<string> {
|
|
|
33
51
|
killTimer = setTimeout(() => child.kill('SIGKILL'), 1000);
|
|
34
52
|
};
|
|
35
53
|
const aborted = () => stop(new Error('桌宠启动已取消'));
|
|
36
|
-
const timer = setTimeout(() => stop(new
|
|
54
|
+
const timer = setTimeout(() => stop(new RuntimePreparationError({ reason: 'timeout' })), 240_000);
|
|
37
55
|
signal.addEventListener('abort', aborted, { once: true });
|
|
38
56
|
const finish = (error?: Error) => {
|
|
39
57
|
clearTimeout(timer); clearTimeout(killTimer); signal.removeEventListener('abort', aborted);
|
|
40
58
|
if (failure || error) reject(failure ?? error); else resolve();
|
|
41
59
|
};
|
|
42
|
-
child.once('error',
|
|
43
|
-
child.once('
|
|
60
|
+
child.once('error', () => { failure ??= new RuntimePreparationError({ reason: 'unavailable' }); });
|
|
61
|
+
child.once('close', code => finish(code === 0 ? undefined : installerFailure(stderr, code)));
|
|
44
62
|
if (signal.aborted) aborted();
|
|
45
63
|
});
|
|
46
64
|
if (signal.aborted) throw new Error('桌宠启动已取消');
|
|
47
65
|
const executable = await installed();
|
|
48
|
-
if (!executable) throw new
|
|
66
|
+
if (!executable) throw new RuntimePreparationError({ reason: 'unavailable' });
|
|
49
67
|
return executable;
|
|
50
68
|
}
|
|
@@ -274,3 +274,35 @@ test('Desktop resolution preserves package subpath exports, relative chunks and
|
|
|
274
274
|
const result = spawnSync(process.execPath, ['--import='+bootstrap, probe], { env: { ...process.env, COOPANION_ASAR_SDK: sdk }, encoding: 'utf8' });
|
|
275
275
|
assert.equal(result.status, 0, result.stderr); assert.deepEqual(JSON.parse(result.stdout), ['asar','asar-operation','asar']);
|
|
276
276
|
});
|
|
277
|
+
|
|
278
|
+
test('published npm evidence binds the selected artifact and does not substitute for the candidate', () => {
|
|
279
|
+
const published = { name: baseline.name, version: '0.4.20', integrity: 'sha512-test-publication' };
|
|
280
|
+
const observedTarget = { ...target, published };
|
|
281
|
+
assert.notEqual(componentIdentities(observedTarget).sdk, componentIdentities(target).sdk);
|
|
282
|
+
const report = {
|
|
283
|
+
kind: 'published', platform: 'linux', arch: 'x64', sourceCommit, version, target: observedTarget,
|
|
284
|
+
status: 'passed', admission: 'refused-as-expected',
|
|
285
|
+
package: { ...published, sha256: 'c'.repeat(64), sourceCommit: 'd'.repeat(40) },
|
|
286
|
+
stages: [{ name: 'admission', status: 'refused-as-expected' }],
|
|
287
|
+
};
|
|
288
|
+
assert.equal(validateReport(report, observedTarget, sourceCommit, 'published'), report);
|
|
289
|
+
assert.throws(() => validateReport({ ...report, package: { ...report.package, integrity: 'other' } }, observedTarget, sourceCommit, 'published'));
|
|
290
|
+
const candidates = Array.from({ length: 3 }, () => ({ status: 'partial', archiveSha256: 'e'.repeat(64) }));
|
|
291
|
+
const outcome = reports => completedComponents(observedTarget, reports, {}, { run: '123', sourceCommit }).sdk.status;
|
|
292
|
+
assert.equal(outcome(candidates), 'retry');
|
|
293
|
+
assert.equal(outcome([report]), 'retry');
|
|
294
|
+
assert.equal(outcome([...candidates, report]), 'partial');
|
|
295
|
+
assert.equal(outcome([...candidates, { ...report, status: 'failed' }]), 'failed');
|
|
296
|
+
});
|
|
297
|
+
|
|
298
|
+
test('only an actual Host refusal counts as expected', async t => {
|
|
299
|
+
const directory = await mkdtemp(join(tmpdir(), 'coopanion-refusal-'));
|
|
300
|
+
t.after(() => rm(directory, { recursive: true, force: true }));
|
|
301
|
+
const report = { stages: [] };
|
|
302
|
+
const opts = { expectedRefusal: log => log.includes('engines.dsh rejection') };
|
|
303
|
+
const run = source => command(report, directory, 'admission', process.execPath, ['-e', source], opts);
|
|
304
|
+
await run('console.error("engines.dsh rejection"); process.exitCode = 1');
|
|
305
|
+
await assert.rejects(run('console.error("engines.dsh rejection")'), { status: 'failed' });
|
|
306
|
+
await assert.rejects(run('console.error("ECONNRESET"); process.exitCode = 1'), { status: 'retry' });
|
|
307
|
+
assert.deepEqual(report.stages.map(stage => stage.status), ['refused-as-expected', 'failed', 'retry']);
|
|
308
|
+
});
|