@kosuke-ai/kosuke 1.0.81 → 1.0.82
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/CHANGELOG.md +7 -0
- package/dist/generated/commands/index.js +124 -118
- package/dist/generated/commands/projects/batch-merging-members-delete.js +7 -0
- package/dist/generated/commands/prototypes/create.js +32 -0
- package/dist/generated/commands/sensei/reels-activity-list.js +1 -1
- package/dist/generated/commands/sensei/reels-later-holds-create.js +43 -0
- package/dist/generated/commands/sensei/reels-later-holds-delete.js +29 -0
- package/dist/generated/commands/sensei/reels-later-holds-list.js +17 -0
- package/dist/generated/commands/sensei/widgets-get.js +1 -1
- package/dist/runtime/arguments.js +2 -0
- package/dist/runtime/attach.js +6 -12
- package/dist/runtime/option-parsers.js +14 -0
- package/dist/runtime/prototype-create.js +47 -0
- package/dist/runtime/prototype-styles-scope.js +342 -0
- package/dist/runtime/prototype-styles.js +166 -0
- package/dist/runtime/prototype-visual-browser.js +87 -0
- package/dist/runtime/prototype-visual-check.js +388 -0
- package/dist/runtime/prototype-visual-preview.js +159 -0
- package/dist/runtime/prototype-visual-scripts.js +174 -0
- package/openapi.json +228 -2
- package/package.json +7 -6
|
@@ -0,0 +1,388 @@
|
|
|
1
|
+
import { randomBytes } from 'node:crypto';
|
|
2
|
+
import { copyFileSync, existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync, } from 'node:fs';
|
|
3
|
+
import { tmpdir } from 'node:os';
|
|
4
|
+
import { extname, join } from 'node:path';
|
|
5
|
+
import { pathToFileURL } from 'node:url';
|
|
6
|
+
import { operations } from '../generated/commands/index.js';
|
|
7
|
+
import { buildRequest, execute } from './invoke.js';
|
|
8
|
+
import { browser, evaluate, hasBrowser, launchHash, runningSessions, } from './prototype-visual-browser.js';
|
|
9
|
+
import { findPreview, reachable } from './prototype-visual-preview.js';
|
|
10
|
+
import { compareScript, realThemeScript, settleScript, showStateScript, } from './prototype-visual-scripts.js';
|
|
11
|
+
/** Over this share of differing pixels the save needs a written reason (`src/lib/prototypes/record.ts`). */
|
|
12
|
+
const THRESHOLD = 3;
|
|
13
|
+
/** The whole check, both screenshots and the image's save included. */
|
|
14
|
+
const CHECK_TIMEOUT_MS = 90_000;
|
|
15
|
+
/** Where a session sandbox's agent writes artifacts: the Turn publishes each file at its slug. */
|
|
16
|
+
const SESSION_ARTIFACTS_DIR = '/tmp/kosuke-artifacts';
|
|
17
|
+
const ARTIFACT_SLUG_MAX = 64;
|
|
18
|
+
const SUFFIX = '-visual-check';
|
|
19
|
+
const isRecord = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
20
|
+
const notCompared = (why, notice) => ({
|
|
21
|
+
result: { status: 'not-compared', why },
|
|
22
|
+
...(notice ? { notice: `Visual check: not compared: ${notice}` } : {}),
|
|
23
|
+
});
|
|
24
|
+
class CheckError extends Error {
|
|
25
|
+
why;
|
|
26
|
+
detail;
|
|
27
|
+
constructor(why, detail) {
|
|
28
|
+
super(detail);
|
|
29
|
+
this.why = why;
|
|
30
|
+
this.detail = detail;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* The comparison of a prototype's baseline state with the real screen, as the save records it
|
|
35
|
+
* (`src/lib/prototypes/record.ts`, `PrototypeVisualCheck`), or null when none was attempted.
|
|
36
|
+
*
|
|
37
|
+
* 1. prototype.json declares no `baseline`: not compared.
|
|
38
|
+
* 2. No `agent-browser` on PATH (a Sensei home): not compared, no browser.
|
|
39
|
+
* 3. The preview: `--preview-url`, else this sandbox's app preview, else `kosuke preview get`;
|
|
40
|
+
* none, or no answer within 10 s: not compared.
|
|
41
|
+
* 4. Renders the page without saving it (`dryRun`) and opens it from a temp file in the check's
|
|
42
|
+
* own browser session.
|
|
43
|
+
* 5. At the prototype's main device width, for each theme it declares that the app has (light,
|
|
44
|
+
* then dark), screenshots the baseline state's canvas and the real screen.
|
|
45
|
+
* 6. Compares them in the browser and draws the side-by-side picture of the worst theme.
|
|
46
|
+
* 7. Saves the picture as the session's `<name>-visual-check` artifact, or the File
|
|
47
|
+
* `prototypes/<name>-visual-check.png`; a failed save keeps the result with no image.
|
|
48
|
+
* Any other failure is not compared, with a notice: the save itself goes on.
|
|
49
|
+
*/
|
|
50
|
+
export async function runVisualCheck(input) {
|
|
51
|
+
const baseline = readBaseline(input.input.attachments);
|
|
52
|
+
if (!baseline)
|
|
53
|
+
return { result: { status: 'not-compared', why: 'no baseline declared' } };
|
|
54
|
+
if (!hasBrowser()) {
|
|
55
|
+
return notCompared('no browser', 'no browser here (agent-browser is not on PATH).');
|
|
56
|
+
}
|
|
57
|
+
const work = mkdtempSync(join(tmpdir(), 'kosuke-visual-check-'));
|
|
58
|
+
const opened = [];
|
|
59
|
+
let timer;
|
|
60
|
+
try {
|
|
61
|
+
const deadline = Date.now() + CHECK_TIMEOUT_MS;
|
|
62
|
+
const timeout = new Promise((_, reject) => {
|
|
63
|
+
timer = setTimeout(() => reject(new CheckError('timed out', 'the check took over 90 s.')), CHECK_TIMEOUT_MS);
|
|
64
|
+
});
|
|
65
|
+
return await Promise.race([check({ ...input, baseline, work, opened, deadline }), timeout]);
|
|
66
|
+
}
|
|
67
|
+
catch (error) {
|
|
68
|
+
if (error instanceof CheckError)
|
|
69
|
+
return notCompared(error.why, error.detail);
|
|
70
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
71
|
+
return notCompared('the check failed', `${message.slice(0, 300)}.`);
|
|
72
|
+
}
|
|
73
|
+
finally {
|
|
74
|
+
clearTimeout(timer);
|
|
75
|
+
for (const session of opened) {
|
|
76
|
+
await browser(session, ['close'], { timeoutMs: 10_000 }).catch(() => undefined);
|
|
77
|
+
}
|
|
78
|
+
rmSync(work, { recursive: true, force: true });
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
async function check(input) {
|
|
82
|
+
const { runtime, baseline, work, deadline } = input;
|
|
83
|
+
const fields = input.input.fields;
|
|
84
|
+
const left = (most) => Math.max(1_000, Math.min(most, deadline - Date.now()));
|
|
85
|
+
const text = (value) => (typeof value === 'string' && value ? value : undefined);
|
|
86
|
+
const preview = await findPreview({
|
|
87
|
+
runtime,
|
|
88
|
+
flag: input.previewUrl,
|
|
89
|
+
projectId: text(fields.projectId),
|
|
90
|
+
sessionId: text(fields.sessionId),
|
|
91
|
+
}).catch(() => null);
|
|
92
|
+
if (!preview)
|
|
93
|
+
return notCompared('no preview reachable', 'no app preview is known here.');
|
|
94
|
+
if (!(await reachable(preview))) {
|
|
95
|
+
return notCompared('no preview reachable', `${preview.url} did not answer.`);
|
|
96
|
+
}
|
|
97
|
+
const page = await dryRun(input);
|
|
98
|
+
if (!page)
|
|
99
|
+
return { result: null };
|
|
100
|
+
const inventory = readInventory(page);
|
|
101
|
+
const device = mainDevice(inventory);
|
|
102
|
+
const themes = comparedThemes(inventory);
|
|
103
|
+
if (!device || !themes.length) {
|
|
104
|
+
throw new CheckError('the check failed', 'the page declares no device or no light or dark theme.');
|
|
105
|
+
}
|
|
106
|
+
const phone = device.kind === 'phone';
|
|
107
|
+
const width = device.px ?? (phone ? 390 : 1280);
|
|
108
|
+
const height = device.height ?? (phone ? 844 : 900);
|
|
109
|
+
const pagePath = join(work, 'prototype.html');
|
|
110
|
+
writeFileSync(pagePath, page);
|
|
111
|
+
// The check's own session, so the agent's browser is left as it is.
|
|
112
|
+
const own = {
|
|
113
|
+
name: `kosuke-prototype-check-${process.pid}-${randomBytes(3).toString('hex')}`,
|
|
114
|
+
launch: preview.launch,
|
|
115
|
+
};
|
|
116
|
+
input.opened.push(own);
|
|
117
|
+
await browser(own, ['open', pathToFileURL(pagePath).href], { timeoutMs: left(30_000) });
|
|
118
|
+
await browser(own, ['set', 'viewport', String(width), String(height)], {
|
|
119
|
+
timeoutMs: left(10_000),
|
|
120
|
+
});
|
|
121
|
+
const real = await realScreenSession(own, preview, left);
|
|
122
|
+
let worst = null;
|
|
123
|
+
for (const theme of themes) {
|
|
124
|
+
const protoShot = join(work, `prototype-${theme.id}.png`);
|
|
125
|
+
const realShot = join(work, `real-${theme.id}.png`);
|
|
126
|
+
await browser(own, ['open', pathToFileURL(pagePath).href], { timeoutMs: left(30_000) });
|
|
127
|
+
await browser(own, ['set', 'media', theme.scheme], { timeoutMs: left(10_000) });
|
|
128
|
+
const shown = (await evaluate(own, showStateScript({ ...baseline, theme: theme.id, width, height }), left(20_000)));
|
|
129
|
+
if (!shown?.reached) {
|
|
130
|
+
throw new CheckError('baseline state not reached', // The server refuses the save on these words (BASELINE_NOT_REACHED).
|
|
131
|
+
`the page could not show the baseline state "${baseline.state}"; it showed "${shown?.current ?? 'nothing'}".`);
|
|
132
|
+
}
|
|
133
|
+
await browser(own, ['screenshot', '--full', protoShot], { timeoutMs: left(20_000) });
|
|
134
|
+
await shootRealScreen(real.session, {
|
|
135
|
+
url: preview.url + baseline.path,
|
|
136
|
+
scheme: theme.scheme,
|
|
137
|
+
width,
|
|
138
|
+
height,
|
|
139
|
+
file: realShot,
|
|
140
|
+
left,
|
|
141
|
+
});
|
|
142
|
+
await browser(own, ['open', 'about:blank'], { timeoutMs: left(30_000) });
|
|
143
|
+
const comparison = (await evaluate(own, compareScript({
|
|
144
|
+
real: dataUrl(realShot),
|
|
145
|
+
prototype: dataUrl(protoShot),
|
|
146
|
+
box: shown.box,
|
|
147
|
+
maxHeight: height * 2 * Math.max(1, Math.round(shown.box.width / width)),
|
|
148
|
+
labels: [
|
|
149
|
+
`Real screen ${baseline.path}`,
|
|
150
|
+
`Prototype ${baseline.state}${baseline.variant ? ` (${baseline.variant})` : ''}`,
|
|
151
|
+
`Difference, ${theme.id}`,
|
|
152
|
+
],
|
|
153
|
+
}), left(30_000)));
|
|
154
|
+
if (typeof comparison?.diffPercent !== 'number' || typeof comparison.png !== 'string') {
|
|
155
|
+
throw new CheckError('the check failed', 'the comparison gave no result.');
|
|
156
|
+
}
|
|
157
|
+
if (!worst || comparison.diffPercent > worst.comparison.diffPercent) {
|
|
158
|
+
worst = { theme, comparison };
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
if (!worst)
|
|
162
|
+
throw new CheckError('the check failed', 'nothing was compared.');
|
|
163
|
+
const image = join(work, 'side-by-side.png');
|
|
164
|
+
writeFileSync(image, Buffer.from(worst.comparison.png.replace(/^data:image\/png;base64,/, ''), 'base64'));
|
|
165
|
+
const saved = await saveImage({ runtime, fields, image }).catch((error) => ({
|
|
166
|
+
image: null,
|
|
167
|
+
notice: `the side-by-side image was not saved: ${error instanceof Error ? error.message : String(error)}.`,
|
|
168
|
+
}));
|
|
169
|
+
const diffPercent = worst.comparison.diffPercent;
|
|
170
|
+
const notices = [saved.notice, diffPercent > THRESHOLD ? real.signedOut : undefined]
|
|
171
|
+
.filter((line) => !!line)
|
|
172
|
+
.map((line) => line.charAt(0).toUpperCase() + line.slice(1));
|
|
173
|
+
return {
|
|
174
|
+
result: {
|
|
175
|
+
status: 'compared',
|
|
176
|
+
diffPercent,
|
|
177
|
+
threshold: THRESHOLD,
|
|
178
|
+
state: baseline.state,
|
|
179
|
+
variant: baseline.variant,
|
|
180
|
+
device: device.id,
|
|
181
|
+
width,
|
|
182
|
+
theme: worst.theme.id,
|
|
183
|
+
path: baseline.path,
|
|
184
|
+
image: saved.image,
|
|
185
|
+
},
|
|
186
|
+
...(notices.length ? { notice: `Visual check: ${notices.join(' ')}` } : {}),
|
|
187
|
+
};
|
|
188
|
+
}
|
|
189
|
+
/**
|
|
190
|
+
* The real screen needs the agent's sign-in, so it is taken in the agent's own browser session
|
|
191
|
+
* (`$AGENT_BROWSER_SESSION`, else `default`), in a tab of its own that is closed after; the skill
|
|
192
|
+
* tells the agent to sign in to the preview there first. agent-browser relaunches a session
|
|
193
|
+
* whose launch flags differ from a call's, which would drop that sign-in, so the agent's session
|
|
194
|
+
* is used only when it runs with the flags the preview needs. Otherwise the real screen is taken
|
|
195
|
+
* signed out in the check's own session.
|
|
196
|
+
*/
|
|
197
|
+
async function realScreenSession(own, preview, left) {
|
|
198
|
+
const name = process.env.AGENT_BROWSER_SESSION || 'default';
|
|
199
|
+
const agent = { name, launch: preview.launch };
|
|
200
|
+
const flags = preview.launch.length
|
|
201
|
+
? ` opened with ${preview.launch.map((flag) => (flag.includes(' ') ? `"${flag}"` : flag)).join(' ')}`
|
|
202
|
+
: '';
|
|
203
|
+
const signedOut = {
|
|
204
|
+
session: own,
|
|
205
|
+
signedOut: `the real screen was taken signed out. To compare a signed-in screen, sign in to the preview in the agent-browser session "${name}"${flags}, then save again.`,
|
|
206
|
+
};
|
|
207
|
+
const running = await runningSessions(left(10_000)).catch(() => new Set());
|
|
208
|
+
if (!running.has(name))
|
|
209
|
+
return signedOut;
|
|
210
|
+
const [theirs, ours] = await Promise.all([
|
|
211
|
+
launchHash(name, left(10_000)).catch(() => null),
|
|
212
|
+
launchHash(own.name, left(10_000)).catch(() => null),
|
|
213
|
+
]);
|
|
214
|
+
if (!theirs || theirs !== ours)
|
|
215
|
+
return signedOut;
|
|
216
|
+
return { session: agent };
|
|
217
|
+
}
|
|
218
|
+
/** Opens the real screen in a tab of its own, screenshots the viewport, and closes the tab. */
|
|
219
|
+
async function shootRealScreen(session, shot) {
|
|
220
|
+
const { left } = shot;
|
|
221
|
+
const before = await browser(session, ['tab', 'list'], { timeoutMs: left(10_000) });
|
|
222
|
+
const tabs = Array.isArray(before.tabs) ? before.tabs.filter(isRecord) : [];
|
|
223
|
+
const active = tabs.find((tab) => tab.active === true)?.tabId;
|
|
224
|
+
// A first compile of the page in a dev server can take a while.
|
|
225
|
+
const opened = await browser(session, ['tab', 'new', shot.url], { timeoutMs: left(45_000) });
|
|
226
|
+
const tab = typeof opened.tabId === 'string' ? opened.tabId : null;
|
|
227
|
+
try {
|
|
228
|
+
await browser(session, ['set', 'viewport', String(shot.width), String(shot.height)], {
|
|
229
|
+
timeoutMs: left(10_000),
|
|
230
|
+
});
|
|
231
|
+
await browser(session, ['set', 'media', shot.scheme], { timeoutMs: left(10_000) });
|
|
232
|
+
const href = await settled(session, left);
|
|
233
|
+
if (typeof href !== 'string' || href.startsWith('chrome-error:')) {
|
|
234
|
+
throw new CheckError('no preview reachable', `the browser could not open ${shot.url}.`);
|
|
235
|
+
}
|
|
236
|
+
await evaluate(session, realThemeScript(shot.scheme), left(15_000));
|
|
237
|
+
await browser(session, ['screenshot', shot.file], { timeoutMs: left(20_000) });
|
|
238
|
+
}
|
|
239
|
+
finally {
|
|
240
|
+
if (tab)
|
|
241
|
+
await browser(session, ['tab', 'close', tab], { timeoutMs: left(10_000) }).catch(() => undefined);
|
|
242
|
+
if (typeof active === 'string') {
|
|
243
|
+
await browser(session, ['tab', active], { timeoutMs: left(10_000) }).catch(() => undefined);
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
/**
|
|
248
|
+
* The page once it stops loading. A page that redirects as it loads (a sign-in cookie set on the
|
|
249
|
+
* first visit) destroys the context the wait ran in: wait again, at most three times.
|
|
250
|
+
*/
|
|
251
|
+
async function settled(session, left) {
|
|
252
|
+
for (let attempt = 1;; attempt++) {
|
|
253
|
+
try {
|
|
254
|
+
return await evaluate(session, settleScript(10_000), left(20_000));
|
|
255
|
+
}
|
|
256
|
+
catch (error) {
|
|
257
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
258
|
+
if (attempt >= 3 || !/context was destroyed|navigat/i.test(message))
|
|
259
|
+
throw error;
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
/** The page as the save would write it, rendered and checked but not saved; null when it fails its check. */
|
|
264
|
+
async function dryRun(input) {
|
|
265
|
+
const { visualCheck: _sent, visualCheckReason: _reason, ...fields } = input.input.fields;
|
|
266
|
+
const request = buildRequest(input.operation, {
|
|
267
|
+
...input.input,
|
|
268
|
+
fields: { ...fields, dryRun: 'true' },
|
|
269
|
+
});
|
|
270
|
+
const outcome = await execute(input.runtime.client({ answerTimeoutMs: input.operation.answerTimeoutMs }), request);
|
|
271
|
+
// A page that fails its check fails the save the same way: the save reports it.
|
|
272
|
+
if (!outcome.ok)
|
|
273
|
+
return null;
|
|
274
|
+
const body = isRecord(outcome.body) ? outcome.body : {};
|
|
275
|
+
const data = isRecord(body.data) ? body.data : body;
|
|
276
|
+
const pages = Array.isArray(data.pages) ? data.pages.filter(isRecord) : [];
|
|
277
|
+
const html = pages[0]?.html;
|
|
278
|
+
if (typeof html !== 'string' || !html) {
|
|
279
|
+
throw new CheckError('the check failed', 'the dry run answered no page.');
|
|
280
|
+
}
|
|
281
|
+
return html;
|
|
282
|
+
}
|
|
283
|
+
/** prototype.json's `baseline`, from the attachment ending in .json; null when there is none. */
|
|
284
|
+
function readBaseline(attachments) {
|
|
285
|
+
const file = attachments.find((path) => extname(path).toLowerCase() === '.json');
|
|
286
|
+
if (!file)
|
|
287
|
+
return null;
|
|
288
|
+
let config;
|
|
289
|
+
try {
|
|
290
|
+
config = JSON.parse(readFileSync(file, 'utf8'));
|
|
291
|
+
}
|
|
292
|
+
catch {
|
|
293
|
+
return null;
|
|
294
|
+
}
|
|
295
|
+
const baseline = isRecord(config) ? config.baseline : undefined;
|
|
296
|
+
if (!isRecord(baseline))
|
|
297
|
+
return null;
|
|
298
|
+
const { state, path, variant } = baseline;
|
|
299
|
+
if (typeof state !== 'string' || !state || typeof path !== 'string' || !path.startsWith('/')) {
|
|
300
|
+
return null;
|
|
301
|
+
}
|
|
302
|
+
return { state, path, variant: typeof variant === 'string' && variant ? variant : null };
|
|
303
|
+
}
|
|
304
|
+
const INVENTORY = /<script\b[^>]*\bid\s*=\s*["']prototype-inventory["'][^>]*>([\s\S]*?)<\/script>/i;
|
|
305
|
+
/** The configuration as the renderer wrote it into the page: devices and themes normalized. */
|
|
306
|
+
function readInventory(page) {
|
|
307
|
+
try {
|
|
308
|
+
const value = JSON.parse(INVENTORY.exec(page)?.[1] ?? '');
|
|
309
|
+
return isRecord(value) ? value : {};
|
|
310
|
+
}
|
|
311
|
+
catch {
|
|
312
|
+
return {};
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
function mainDevice(inventory) {
|
|
316
|
+
const first = Array.isArray(inventory.devices) ? inventory.devices[0] : undefined;
|
|
317
|
+
if (!isRecord(first) || typeof first.id !== 'string')
|
|
318
|
+
return null;
|
|
319
|
+
return {
|
|
320
|
+
id: first.id,
|
|
321
|
+
kind: typeof first.kind === 'string' ? first.kind : 'desktop',
|
|
322
|
+
...(typeof first.px === 'number' ? { px: first.px } : {}),
|
|
323
|
+
...(typeof first.height === 'number' ? { height: first.height } : {}),
|
|
324
|
+
};
|
|
325
|
+
}
|
|
326
|
+
/** The first light and the first dark theme the prototype declares, light first. */
|
|
327
|
+
function comparedThemes(inventory) {
|
|
328
|
+
const themes = (Array.isArray(inventory.themes) ? inventory.themes : []).filter(isRecord);
|
|
329
|
+
return ['light', 'dark'].flatMap((scheme) => {
|
|
330
|
+
const theme = themes.find((item) => item.scheme === scheme && typeof item.id === 'string');
|
|
331
|
+
return theme ? [{ id: theme.id, scheme }] : [];
|
|
332
|
+
});
|
|
333
|
+
}
|
|
334
|
+
function dataUrl(path) {
|
|
335
|
+
return `data:image/png;base64,${readFileSync(path).toString('base64')}`;
|
|
336
|
+
}
|
|
337
|
+
/** `<name>-visual-check`, the name shortened at a hyphen to fit an artifact slug. */
|
|
338
|
+
function imageSlug(name) {
|
|
339
|
+
let base = name.toLowerCase();
|
|
340
|
+
while (base.length + SUFFIX.length > ARTIFACT_SLUG_MAX && base.includes('-')) {
|
|
341
|
+
base = base.slice(0, base.lastIndexOf('-'));
|
|
342
|
+
}
|
|
343
|
+
return `${base.slice(0, ARTIFACT_SLUG_MAX - SUFFIX.length)}${SUFFIX}`;
|
|
344
|
+
}
|
|
345
|
+
/**
|
|
346
|
+
* The side-by-side picture, next to the prototype. A session's artifacts are published by the
|
|
347
|
+
* Turn from the sandbox's artifacts folder (no route takes an image's bytes), so a session's
|
|
348
|
+
* picture is written there, which only its own sandbox can do. Files take it through
|
|
349
|
+
* `kosuke files set`.
|
|
350
|
+
*/
|
|
351
|
+
async function saveImage(input) {
|
|
352
|
+
const { fields } = input;
|
|
353
|
+
const name = typeof fields.name === 'string' ? fields.name : 'prototype';
|
|
354
|
+
if (typeof fields.workspaceId === 'string' && fields.workspaceId) {
|
|
355
|
+
const path = `prototypes/${name}${SUFFIX}.png`;
|
|
356
|
+
const upload = join(input.image, '..', `${name}${SUFFIX}.png`);
|
|
357
|
+
copyFileSync(input.image, upload);
|
|
358
|
+
// The workspace form of `kosuke files set`, read from the registry like every command.
|
|
359
|
+
const filesSet = operations.find((operation) => operation.command.join(' ') === 'files set' && !operation.personalSpace);
|
|
360
|
+
if (!filesSet)
|
|
361
|
+
return { image: null, notice: 'the side-by-side image was not saved.' };
|
|
362
|
+
const outcome = await execute(input.runtime.client(), buildRequest(filesSet, {
|
|
363
|
+
pathParams: { workspaceId: fields.workspaceId },
|
|
364
|
+
fields: { path, mediaType: 'image/png' },
|
|
365
|
+
attachments: [upload],
|
|
366
|
+
}));
|
|
367
|
+
if (!outcome.ok) {
|
|
368
|
+
return {
|
|
369
|
+
image: null,
|
|
370
|
+
notice: `the side-by-side image was not saved (HTTP ${outcome.status}).`,
|
|
371
|
+
};
|
|
372
|
+
}
|
|
373
|
+
return { image: { kind: 'file', ref: path } };
|
|
374
|
+
}
|
|
375
|
+
const sessionId = fields.sessionId;
|
|
376
|
+
const ownSandbox = typeof sessionId === 'string' &&
|
|
377
|
+
sessionId === process.env.KOSUKE_SANDBOX_KEY &&
|
|
378
|
+
existsSync(SESSION_ARTIFACTS_DIR);
|
|
379
|
+
if (!ownSandbox) {
|
|
380
|
+
return {
|
|
381
|
+
image: null,
|
|
382
|
+
notice: "the side-by-side image is saved only from the session's own sandbox.",
|
|
383
|
+
};
|
|
384
|
+
}
|
|
385
|
+
const slug = imageSlug(name);
|
|
386
|
+
copyFileSync(input.image, join(SESSION_ARTIFACTS_DIR, `${slug}.png`));
|
|
387
|
+
return { image: { kind: 'artifact', ref: slug } };
|
|
388
|
+
}
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
2
|
+
import { request as httpRequest } from 'node:http';
|
|
3
|
+
import { request as httpsRequest } from 'node:https';
|
|
4
|
+
import { rootCertificates } from 'node:tls';
|
|
5
|
+
import { execute } from './invoke.js';
|
|
6
|
+
/**
|
|
7
|
+
* Where the real screen of the visual check is: the `--preview-url` flag, else this session
|
|
8
|
+
* sandbox's app preview, else the session's preview as `kosuke preview get` reads it. Inside a
|
|
9
|
+
* sandbox a preview host answers only through the sandbox's own HTTPS proxy, so the browser is
|
|
10
|
+
* launched with a resolver rule and the proxy's CA, and the reachability probe takes that route.
|
|
11
|
+
*/
|
|
12
|
+
/** The sandbox's configuration; older images wrote the dotted name. */
|
|
13
|
+
const SANDBOX_CONFIGS = ['/tmp/kosuke.config.json', '/tmp/kosuke-config.json'];
|
|
14
|
+
const PROXY_MAP = '/tmp/kosuke-proxy-map.json';
|
|
15
|
+
const PROXY_CA = '/etc/kosuke/sandbox-proxy-certs/ca.crt';
|
|
16
|
+
const SYSTEM_CAS = ['/etc/ssl/certs/ca-certificates.crt', '/etc/pki/tls/certs/ca-bundle.crt'];
|
|
17
|
+
const PROBE_TIMEOUT_MS = 10_000;
|
|
18
|
+
const isRecord = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
19
|
+
function readJson(path) {
|
|
20
|
+
try {
|
|
21
|
+
const value = JSON.parse(readFileSync(path, 'utf8'));
|
|
22
|
+
return isRecord(value) ? value : null;
|
|
23
|
+
}
|
|
24
|
+
catch {
|
|
25
|
+
return null;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* The app's web service route in the sandbox: the first service with an endpoint exposed as the
|
|
30
|
+
* preview, else one named `web` or `app`. A service's first endpoint routes by the service's
|
|
31
|
+
* name, a later one by `<service>-<endpoint>`.
|
|
32
|
+
*/
|
|
33
|
+
function sandboxRoute(config) {
|
|
34
|
+
const services = isRecord(config.services) ? config.services : {};
|
|
35
|
+
const endpointsOf = (service) => isRecord(service) && Array.isArray(service.endpoints) ? service.endpoints.filter(isRecord) : [];
|
|
36
|
+
for (const [name, service] of Object.entries(services)) {
|
|
37
|
+
const endpoints = endpointsOf(service);
|
|
38
|
+
const index = endpoints.findIndex((endpoint) => endpoint.exposure === 'preview');
|
|
39
|
+
if (index === 0)
|
|
40
|
+
return name;
|
|
41
|
+
if (index > 0)
|
|
42
|
+
return `${name}-${String(endpoints[index].name)}`;
|
|
43
|
+
}
|
|
44
|
+
for (const name of ['web', 'app'])
|
|
45
|
+
if (endpointsOf(services[name]).length)
|
|
46
|
+
return name;
|
|
47
|
+
return null;
|
|
48
|
+
}
|
|
49
|
+
function sandboxProxyPort(config) {
|
|
50
|
+
const fromConfig = isRecord(config?.sandboxProxy) ? config.sandboxProxy.port : undefined;
|
|
51
|
+
const fromMap = readJson(PROXY_MAP)?.port;
|
|
52
|
+
const port = [fromConfig, fromMap].find((value) => typeof value === 'number');
|
|
53
|
+
return port ?? 443;
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* A preview host this sandbox serves (`local--<route>` or `<this sandbox>--<route>` under the
|
|
57
|
+
* preview domain) goes through the sandbox proxy; anything else is reached directly.
|
|
58
|
+
*/
|
|
59
|
+
function previewOf(url, env, config) {
|
|
60
|
+
const origin = new URL(url);
|
|
61
|
+
const domain = env.KOSUKE_PREVIEW_DOMAIN;
|
|
62
|
+
const host = origin.hostname;
|
|
63
|
+
const local = !!domain &&
|
|
64
|
+
origin.protocol === 'https:' &&
|
|
65
|
+
host.endsWith(`.${domain}`) &&
|
|
66
|
+
existsSync(PROXY_CA) &&
|
|
67
|
+
(host.startsWith('local--') ||
|
|
68
|
+
(!!env.KOSUKE_SANDBOX_KEY && host.startsWith(`${env.KOSUKE_SANDBOX_KEY}--`)));
|
|
69
|
+
const base = `${origin.protocol}//${origin.host}${origin.pathname.replace(/\/+$/, '')}`;
|
|
70
|
+
if (!local)
|
|
71
|
+
return { url: base, launch: [], proxyPort: null };
|
|
72
|
+
const port = sandboxProxyPort(config);
|
|
73
|
+
const route = host.slice(0, -domain.length - 1).split('--')[1];
|
|
74
|
+
// One rule per switch: agent-browser splits `--args` on commas.
|
|
75
|
+
return {
|
|
76
|
+
url: base,
|
|
77
|
+
launch: [
|
|
78
|
+
'--ca-cert',
|
|
79
|
+
PROXY_CA,
|
|
80
|
+
'--args',
|
|
81
|
+
`--host-resolver-rules=MAP *--${route}.${domain} 127.0.0.1:${port}`,
|
|
82
|
+
],
|
|
83
|
+
proxyPort: port,
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
/** The preview to compare with, or null when none is known. */
|
|
87
|
+
export async function findPreview(input) {
|
|
88
|
+
const env = input.env ?? process.env;
|
|
89
|
+
const config = SANDBOX_CONFIGS.map(readJson).find(Boolean) ?? null;
|
|
90
|
+
if (input.flag) {
|
|
91
|
+
try {
|
|
92
|
+
return previewOf(input.flag, env, config);
|
|
93
|
+
}
|
|
94
|
+
catch {
|
|
95
|
+
return null;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
const route = config && sandboxRoute(config);
|
|
99
|
+
if (route && env.KOSUKE_PREVIEW_DOMAIN) {
|
|
100
|
+
return previewOf(`https://local--${route}.${env.KOSUKE_PREVIEW_DOMAIN}`, env, config);
|
|
101
|
+
}
|
|
102
|
+
if (!input.projectId)
|
|
103
|
+
return null;
|
|
104
|
+
const outcome = await execute(input.runtime.client(), {
|
|
105
|
+
method: 'get',
|
|
106
|
+
path: '/api/projects/{projectId}/preview',
|
|
107
|
+
pathParams: { projectId: input.projectId },
|
|
108
|
+
query: input.sessionId ? { sessionId: input.sessionId } : {},
|
|
109
|
+
body: null,
|
|
110
|
+
});
|
|
111
|
+
if (!outcome.ok || !isRecord(outcome.body))
|
|
112
|
+
return null;
|
|
113
|
+
const data = isRecord(outcome.body.data) ? outcome.body.data : outcome.body;
|
|
114
|
+
const urls = isRecord(data.frontendUrls) ? data.frontendUrls : {};
|
|
115
|
+
const url = urls.web ?? urls.app ?? Object.values(urls)[0];
|
|
116
|
+
if (typeof url !== 'string' || !url)
|
|
117
|
+
return null;
|
|
118
|
+
try {
|
|
119
|
+
return previewOf(url, env, config);
|
|
120
|
+
}
|
|
121
|
+
catch {
|
|
122
|
+
return null;
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
function trustedCas() {
|
|
126
|
+
const cas = [...rootCertificates];
|
|
127
|
+
for (const path of [...SYSTEM_CAS, PROXY_CA]) {
|
|
128
|
+
try {
|
|
129
|
+
cas.push(readFileSync(path, 'utf8'));
|
|
130
|
+
}
|
|
131
|
+
catch {
|
|
132
|
+
// Not on this machine.
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
return cas;
|
|
136
|
+
}
|
|
137
|
+
/** Whether the app answers at all within 10 s: any HTTP status counts, a redirect included. */
|
|
138
|
+
export function reachable(preview) {
|
|
139
|
+
const url = new URL(preview.url + '/');
|
|
140
|
+
const secure = url.protocol === 'https:';
|
|
141
|
+
const send = secure ? httpsRequest : httpRequest;
|
|
142
|
+
return new Promise((resolve) => {
|
|
143
|
+
const req = send({
|
|
144
|
+
host: preview.proxyPort ? '127.0.0.1' : url.hostname,
|
|
145
|
+
port: preview.proxyPort ?? (url.port || (secure ? 443 : 80)),
|
|
146
|
+
path: url.pathname,
|
|
147
|
+
method: 'GET',
|
|
148
|
+
headers: { host: url.host },
|
|
149
|
+
...(secure ? { servername: url.hostname, ca: trustedCas() } : {}),
|
|
150
|
+
timeout: PROBE_TIMEOUT_MS,
|
|
151
|
+
}, (response) => {
|
|
152
|
+
response.resume();
|
|
153
|
+
resolve(true);
|
|
154
|
+
});
|
|
155
|
+
req.on('timeout', () => req.destroy(new Error('timeout')));
|
|
156
|
+
req.on('error', () => resolve(false));
|
|
157
|
+
req.end();
|
|
158
|
+
});
|
|
159
|
+
}
|