Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions apps/desktop/scripts/smoke-window.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,18 @@ export async function smokeWindow({ window, host, getLocale }) {
if (fixture) result.largeVideo = await smokeLargeVideo(window, host, projectId, JSON.parse(fixture), result.projectIds.length === 1);
}
if (result.projectIds.length === 1) await smokeTraceWindows(window, result.projectIds[0]);
if (process.env.OPENDIRECTOR_DESKTOP_SMOKE_USER_PATH === '1') {
const projectId = result.projectIds[0];
const headers = { 'X-OpenDirector-Request': '1', 'X-OpenDirector-Desktop': host.token };
const statusResponse = await fetch(`${host.url}/api/creation/projects/${projectId}/assistant/runtimes/pi/status`, { headers });
const statusPayload = statusResponse.ok ? await statusResponse.json() : { status: `http-${statusResponse.status}` };
const modelsResponse = await fetch(`${host.url}/api/creation/projects/${projectId}/assistant/runtimes/pi/models`, { headers });
const modelsPayload = modelsResponse.ok ? await modelsResponse.json() : [];
result.inheritedUserPath = {
status: statusPayload.status,
models: Array.isArray(modelsPayload) ? modelsPayload.map(item => item.id) : [],
};
}
result.sidebarInitiallyOpen = await window.webContents.executeJavaScript("document.querySelector('.cw-workspace').dataset.desktopSidebar === 'open'");
if (!result.sidebarInitiallyOpen) {
await window.webContents.executeJavaScript("document.querySelector('.od-caption-actions button').click()");
Expand Down
47 changes: 46 additions & 1 deletion apps/desktop/scripts/smoke.mjs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { access, copyFile, mkdtemp, readFile, realpath, rm } from 'node:fs/promises';
import { access, chmod, copyFile, mkdir, mkdtemp, readFile, realpath, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { delimiter, dirname, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
Expand Down Expand Up @@ -43,11 +43,51 @@ try {
for (const [name, source] of fixtures) {
await copyFile(fileURLToPath(new URL(source, import.meta.url)), join(directory, name));
}
let userShellEnv = {};
if (process.platform !== 'win32') {
const shellHome = join(directory, 'smoke-home');
const userCliBin = join(directory, 'smoke-user-cli-bin');
const userInterpBin = join(directory, 'smoke-user-interp-bin');
await mkdir(shellHome, { recursive: true });
await mkdir(userCliBin, { recursive: true });
await mkdir(userInterpBin, { recursive: true });
const interp = join(userInterpBin, 'od-smoke-node');
await writeFile(interp, `#!/bin/sh\nexec "${pythonBinary}" -I -B "$@"\n`, 'utf8');
await chmod(interp, 0o755);
const piShim = join(userCliBin, 'pi');
await writeFile(piShim, [
'#!/usr/bin/env od-smoke-node',
'import sys',
'args = sys.argv[1:]',
'if "--version" in args:',
' print("1.8.0")',
' raise SystemExit(0)',
'if "--list-models" in args:',
' print("provider model context max-out thinking images")',
' print("smoke smoke-model 1M 32K yes no")',
' raise SystemExit(0)',
'if args[:2] == ["auth", "check"]:',
' raise SystemExit(0)',
'raise SystemExit(1)',
].join('\n') + '\n', 'utf8');
await chmod(piShim, 0o755);
const profile = `export PATH="${harnessBin}:${userCliBin}:${userInterpBin}:$PATH"\n`;
for (const name of ['.zshrc', '.zprofile', '.profile', '.bashrc', '.bash_profile']) {
await writeFile(join(shellHome, name), profile, 'utf8');
}
userShellEnv = {
PATH: '/usr/bin:/bin:/usr/sbin:/sbin',
SHELL: process.platform === 'darwin' ? '/bin/zsh' : '/bin/sh',
...(process.platform === 'darwin' ? { ZDOTDIR: shellHome } : { ENV: join(shellHome, '.profile') }),
OPENDIRECTOR_DESKTOP_SMOKE_USER_PATH: '1',
};
}
for (let attempt = 0; attempt < 3; attempt++) {
const child = spawn(binary, ['--smoke'], {
env: {
...process.env,
PATH: [harnessBin, process.env.PATH].filter(Boolean).join(delimiter),
...userShellEnv,
OPENCODE_DISABLE_MODELS_FETCH: '1',
OPENCODE_PURE: '1',
OPENDIRECTOR_DESKTOP_DATA: directory,
Expand All @@ -68,6 +108,11 @@ try {
logOffset = log.length;
if (result !== 0 || !latest) throw new Error(`Packaged desktop smoke failed on launch ${attempt + 1} (${result}):\n${log}`);
const receipt = JSON.parse(latest.slice(6));
if (process.platform !== 'win32') {
if (receipt.inheritedUserPath?.status !== 'ready' || !receipt.inheritedUserPath?.models?.includes('smoke/smoke-model')) {
throw new Error(`Desktop Host did not inherit user shell PATH: ${JSON.stringify(receipt.inheritedUserPath)}`);
}
}
if (!receipt.mediaDrop || (mediaProject && receipt.mediaDrop !== mediaProject)) throw new Error('Desktop media drop was not verified');
mediaProject = receipt.mediaDrop;
if (video) {
Expand Down
152 changes: 152 additions & 0 deletions apps/desktop/src/environment.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
import { spawn } from 'node:child_process';

const START_MARKER = '__OPENDIRECTOR_PATH_START__';
const END_MARKER = '__OPENDIRECTOR_PATH_END__';
const PROBE_COMMAND = `printf '${START_MARKER}\\n'; /usr/bin/env; printf '${END_MARKER}\\n'`;

export function extractShellPath(output) {
const start = output.lastIndexOf(START_MARKER);
if (start === -1) return null;
const end = output.indexOf(END_MARKER, start + START_MARKER.length);
if (end === -1) return null;
const block = output.slice(start + START_MARKER.length, end);
for (const line of block.split(/\r?\n/)) {
if (line.startsWith('PATH=')) return line.slice(5);
}
return null;
}

export function mergePath(segments, { platform = process.platform } = {}) {
const sep = platform === 'win32' ? ';' : ':';
const seen = new Set();
const entries = [];
for (const segment of segments) {
if (typeof segment !== 'string' || !segment) continue;
for (const raw of segment.split(sep)) {
if (!raw) continue;
const key = platform === 'win32' ? raw.toLowerCase() : raw;
if (seen.has(key)) continue;
seen.add(key);
entries.push(raw);
}
}
return entries.join(sep);
}

function candidateShells(platform, env) {
const fallback = platform === 'darwin' ? '/bin/zsh' : '/bin/sh';
const configured = env?.SHELL;
if (typeof configured === 'string' && configured.startsWith('/') && configured !== fallback) {
return [configured, fallback];
}
return [fallback];
}

function runShellProbe(shell, args, env, timeoutMs) {
return new Promise((resolve, reject) => {
const child = spawn(shell, args, {
env: { ...env, TERM: 'dumb' },
stdio: ['ignore', 'pipe', 'ignore'],
detached: true,
});
let output = '';
let settled = false;
const finish = (error, value) => {
if (settled) return;
settled = true;
clearTimeout(timer);
if (error) reject(error);
else resolve(value);
};
const killGroup = () => {
if (child.pid) {
try {
process.kill(-child.pid, 'SIGKILL');
return;
} catch {}
}
try { child.kill('SIGKILL'); } catch {}
};
const timer = setTimeout(() => {
killGroup();
finish(new Error(`Shell PATH probe timed out after ${timeoutMs}ms`));
}, timeoutMs);
child.stdout.setEncoding('utf8');
child.stdout.on('data', chunk => {
output += chunk;
if (output.length > 1024 * 1024) {
killGroup();
finish(new Error('Shell PATH probe exceeded output limit'));
}
});
child.once('error', error => finish(error));
child.once('close', code => {
if (code !== 0) finish(new Error(`Shell PATH probe exited (${code})`));
else finish(null, output);
});
});
}

export async function resolveUserShellPath({
platform = process.platform,
env = process.env,
probe = runShellProbe,
timeoutMs = 3000,
log,
} = {}) {
if (platform === 'win32') return null;
let lastError;
for (const shell of candidateShells(platform, env)) {
for (const args of [['-ilc', PROBE_COMMAND], ['-lc', PROBE_COMMAND]]) {
try {
const output = await probe(shell, args, env, timeoutMs);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

这里的 3 秒是每次 probe 的上限。自定义 shell 和 fallback 各试两种模式,Host 启动前最坏会阻塞约 12 秒。建议共用一个总 deadline,到点直接走原 PATH,并加一个连续超时仍能及时启动的测试。 (Use one total startup deadline.)

const resolved = extractShellPath(output);
if (resolved) return resolved;
lastError = new Error('Shell PATH probe returned no PATH entry');
} catch (error) {
lastError = error;
}
}
}
if (lastError) log?.write(`User shell PATH probe failed: ${lastError.message}\n`);
return null;
}

export function buildHostEnv({
runtimeBin,
workspace,
platform = process.platform,
env = process.env,
userPath = null,
} = {}) {
const result = {};
const sep = platform === 'win32' ? ';' : ':';
let existingPath = '';
let pathKey = 'PATH';
for (const [key, value] of Object.entries(env ?? {})) {
if (platform === 'win32' ? key.toLowerCase() === 'path' : key === 'PATH') {
if (typeof value === 'string' && value) {
existingPath = existingPath ? `${existingPath}${sep}${value}` : value;
}
if (platform === 'win32') pathKey = key;
continue;
}
result[key] = value;
}
result.OPENDIRECTOR_ROOT = workspace;
result[pathKey] = mergePath([runtimeBin, userPath, existingPath], { platform });
return result;
}

export async function resolveHostEnv({
runtimeBin,
workspace,
platform = process.platform,
env = process.env,
probe = runShellProbe,
timeoutMs = 3000,
log,
} = {}) {
const userPath = await resolveUserShellPath({ platform, env, probe, timeoutMs, log });
return buildHostEnv({ runtimeBin, workspace, platform, env, userPath });
}
5 changes: 3 additions & 2 deletions apps/desktop/src/main.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { join, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
import { homedir } from 'node:os';
import { Host, ownedURL, proxyRequest } from './host.mjs';
import { resolveHostEnv } from './environment.mjs';
import { messages, localeFor } from './locale.mjs';
import { registerCommand, commandPath } from './command.mjs';

Expand Down Expand Up @@ -126,9 +127,9 @@ async function start() {
const manifest = JSON.parse(readFileSync(join(runtime, 'manifest.json'), 'utf8'));
if (typeof manifest.python !== 'string' || manifest.python.startsWith('/') || manifest.python.split(/[\\/]/).includes('..')) throw new Error('Invalid runtime Python path');
if (manifest.version !== 1 || manifest.platform !== process.platform || manifest.arch !== process.arch) throw new Error('Runtime platform does not match this application');
const hostEnv = await resolveHostEnv({ runtimeBin: join(runtime, 'bin'), workspace, log });
host = new Host({ python: join(runtime, manifest.python), directory: workspace, log,
env: { ...process.env, OPENDIRECTOR_ROOT: workspace,
PATH: join(runtime, 'bin') + (process.platform === 'win32' ? ';' : ':') + process.env.PATH },
env: hostEnv,
onExit: () => { if (!quitting) void fatal(new Error(text().interrupted)); },
});
await host.ready;
Expand Down
Loading
Loading