diff --git a/.agents/notes/implemented/architecture/2026-07-23-client-plugin-loading-model.i18n.yaml b/.agents/notes/implemented/architecture/2026-07-23-client-plugin-loading-model.i18n.yaml index 730cfb413c..608fe717d5 100644 --- a/.agents/notes/implemented/architecture/2026-07-23-client-plugin-loading-model.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-07-23-client-plugin-loading-model.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-07-23-client-plugin-loading-model.md -2026-07-23-client-plugin-loading-model.md: a8d016a70792ad4ac6a71083677ce5d82a30af0a -2026-07-23-client-plugin-loading-model.zh.md: 1b94909c9611f01e5a6d7fcb50ec3f91ee88fab1 +2026-07-23-client-plugin-loading-model.md: b8c23108a7a1cf3a04ded373d8705bae626c70c2 +2026-07-23-client-plugin-loading-model.zh.md: efaea843120e5b023bbc8f59663ea47468944c71 diff --git a/.agents/notes/implemented/architecture/2026-07-23-client-plugin-loading-model.md b/.agents/notes/implemented/architecture/2026-07-23-client-plugin-loading-model.md index a8d016a707..b8c23108a7 100644 --- a/.agents/notes/implemented/architecture/2026-07-23-client-plugin-loading-model.md +++ b/.agents/notes/implemented/architecture/2026-07-23-client-plugin-loading-model.md @@ -46,7 +46,7 @@ A `require.async("./client..js")` call requests the exact revisioned `/plu The shared tsdown preset emits a map for every plugin entry and chunk and rewrites first-party source paths into the browser-resolvable repository form `/packages///src/...`. The production Client pass consumes `lib/types`; the preset supplies each tsc map to Rolldown and fills `sourcesContent` from the original files, so the final map reaches TypeScript/TSX instead of stopping at emitted JavaScript. Other workspace sources inlined into a bundle likewise resolve to their `packages/` owner, while dependency paths remain unchanged. Combo generation strips each local debug directive, records its generated-line offset, resolves every authored source against the original per-plugin map URL, and emits an Indexed Source Map v3. An authored map supplies its section; otherwise an identity section embeds the generated bundle and uses the packer's `sourceURL` as its source name when present. The absolute combo map URL mirrors the script resource list by changing every `client.js` suffix to `client.js.map`, so `/plugins/??/client.js,/client.js&rev=` points to `/plugins/??/client.js.map,/client.js.map&rev=`. A chunk script likewise points to its own map URL. Source-map files are read and combined only when those map URLs receive `GET`; `HEAD` materializes neither script nor map bodies. The Vite shell also emits source maps, letting shell code and externally loaded plugins map stacks and performance profiles back to TypeScript/TSX. -The graph retains each row's revisioned one-resource combo URL for HMR and adds a revisioned descriptor for every startup combo request; several descriptors may carry the same scheduling phase. Initial row revisions are opaque process nonces rather than content hashes; they keep the snapshotted one-resource response immutable without hashing every plugin at startup. The shared preset stamps the entry after every package output is written. After the watcher observes that completed-build stamp, `rebuilt(id)` hashes the entry bytes together with its timestamp and publishes the resulting revision; a chunk-only build therefore advances the owner revision without a Host-side sibling scan. Startup combo revisions derive from the ordered row revisions. Script bodies are assembled on their first `GET`; source-map files are read and combined separately on their first map `GET`. `HEAD` materializes neither body. Versioned scripts and maps use immutable caching, and unrelated graph recomposition retains already-materialized chunk responses at the same revision. The Host serves only exact generated URLs; stale revisions and unadvertised resource lists return 404 instead of aliasing different bytes. An external script's `error` event exposes neither response status nor body, so failure diagnostics name only the URL; the same-origin Host and build-stamped registration id form the identity boundary, while the post-`load` factory-presence check rejects an artifact that did not register the expected id. +The graph retains each row's revisioned one-resource combo URL for HMR and adds a revisioned descriptor for every startup combo request; several descriptors may carry the same scheduling phase. Initial publication and `rebuilt(id)` use the same hash of entry mtime, ctime, and size; artifact contents never enter the hash. Ctime distinguishes rewrites that preserve mtime and size. A Host restart over unchanged artifacts therefore retains every row revision, so the reconnecting SSE snapshot does not trigger browser plugin replacement. The shared preset stamps the entry after every package output is written; a chunk-only build therefore advances the owner revision without a Host-side sibling scan. Startup combo revisions derive from the ordered row revisions. Script bodies are assembled on their first `GET`; source-map files are read and combined separately on their first map `GET`. `HEAD` materializes neither body. Versioned scripts and maps use immutable caching, and unrelated graph recomposition retains already-materialized chunk responses at the same revision. The Host serves only exact generated URLs; stale revisions and unadvertised resource lists return 404 instead of aliasing different bytes. An external script's `error` event exposes neither response status nor body, so failure diagnostics name only the URL; the same-origin Host and build-stamped registration id form the identity boundary, while the post-`load` factory-presence check rejects an artifact that did not register the expected id. ### The loading flow, end to end @@ -56,7 +56,7 @@ What happens between `dsh web` starting and the UI appearing? Three stages: the 1. The composing app (`apps/cli`) ships the roster as ordinary rows in its `cordis.yml` config tree — client plugin packages are entry rows like every host plugin, including the always-mounted `client-hmr` row. `auditStartupEntries` reports failed imports, activation errors with their original stacks, and pending dependencies; optional entries warn and required entries reject startup ([startup policy](2026-09-09-consumer-owned-startup-strictness.md)). 2. The `dsh-client-modules` node half (the package is dual-face: its browser half is the module table) resolves each live Loader entry through the same `name` and owning-tree `baseUrl` inputs that imported its Host face, then reads the nearest owning package.json `dsh.client` declaration and composes `window.__DSH_BOOT__`: `{ rev, entries: [{ id, url, rev, inject?, immediately?, external? }], batches: [{ phase, url, rev, entries }] }`. The manifest package name is the browser module identity even when an overlay names a relative source or built entry file. Distinct active Loader sources resolving to one package name fail composition; after one source unloads, the surviving source supplies the row without a fiber restart. The row's three optional fields come from manifests, never hand-copied. Composition orders requested dynamic rows before their consumers, rejects synchronous request cycles, and assigns every row to exactly one initial batch. It refuses declared plugins without built `./client` bundles and groups their package/path rows under one required source-build instruction; malformed declaration fields also fail activation, and the Host audit reports either error from the FAILED fiber. -3. Scanning is incremental per package — there is no full-rescan code path. Each cordis `internal/plugin` emission marks the fiber's entry name dirty (entry-less fibers drop O(1)); a microtask flush reconciles each dirty name against live loader entries, with package metadata (including the negative "not a client package" verdict) cached per entry name and owning-tree base URL for the process lifetime and bundle re-hashing reachable only through `rebuilt(id)`. The activation pass seeds the same dirty set from current entries and flushes synchronously, so first scan and steady state share one implementation. Initial rows receive an opaque process nonce plus sequence without hashing their artifacts; startup combo revisions hash the combined script inputs plus indexed map, and the rows plus batch descriptors hash into `graph.rev`. The graph types are single-sourced in the modules package's `./client` export — the webserver knows nothing about the graph, while modules registers the combo route and contributes structured index-injection rows. +3. Scanning is incremental per package — there is no full-rescan code path. Each cordis `internal/plugin` emission marks the fiber's entry name dirty (entry-less fibers drop O(1)); a microtask flush reconciles each dirty name against live loader entries, with package metadata (including the negative "not a client package" verdict) cached per entry name and owning-tree base URL for the process lifetime and changed bundle publication reachable only through `rebuilt(id)`. The activation pass seeds the same dirty set from current entries and flushes synchronously, so first scan and steady state share one implementation. Initial rows hash their pre-read filesystem metadata; startup combo revisions hash the ordered row identities and revisions, and the rows plus batch descriptors hash into `graph.rev`. The graph types are single-sourced in the modules package's `./client` export — the webserver knows nothing about the graph, while modules registers the combo route and contributes structured index-injection rows. Why is the roster yml rows and not a scan? Because which plugins compose into a deployment is a composition decision, not a package property — a package declaring `dsh.client` in the repo does not mean this deployment mounts it, so discovery-by-scan cannot make that call; the node half scans only what the tree actually mounted. @@ -80,7 +80,7 @@ The Host SSE adapter forwards existing graph-change notifications and sends the Hot reload is a composition decision: the web bundle mounts the `client-hmr` row (a normal plugin package) unconditionally; its node half brings the bundle watch and the SSE channel, and the chain stays idle until a rebuild watcher rewrites client bundles. A composition that must not expose it disables the row. -How does a rebuilt bundle become a reload signal? The hmr node half observes it itself — no builder tells it. Before reading each startup snapshot, the module host captures the entry stat baseline and exposes it through `ctx.clientModules.artifactBaseline(id)`. One HMR-owned interval compares every current graph row with that baseline. An unchanged row starts watching without a content read or hash; a write after baseline capture is already a stat delta and only that row enters `rebuilt(id)`. This avoids both an initial all-row re-hash and `fs.watchFile`, whose asynchronous first baseline can silently absorb a construction-time rebuild. Watch membership follows `onGraphChanged`; vanished rows drop out, and an entry missing at poll time keeps its row dirty so reappearance forces a new revision even with identical metadata. The shared tsdown preset stamps `client.js` after every sibling output has been written; on an entry mtime or size delta, or a dirty row, `rebuilt(id)` derives the revision from the entry bytes and completed-build timestamp. A chunk-only edit therefore changes the revision, and a partial write followed by the completion stamp supplies a later stat change that self-heals. When the `rev` changes, the node half broadcasts a `rebuilt` frame on `GET /plugins/events` — a system SSE channel that sends the full graph on connect and `rebuilt` frames on change, presentation-only wire that never enters the session log. Polling is deliberate because inotify does not fire on the weka network mount, the same reason the build-side watcher needs `--poll`; one entry stat per row and interval is sufficient, the interval is a validated config field (default 500ms), and disposal clears the one timer. Rebuilding artifacts is any process using the shared Client tsdown preset — `scripts/dev-web.ts` remains the watch-build entry point, discovering its package list through `dsh.client` while scanning `packages/*/*/package.json` at startup — and builder and host share no notification protocol. +How does a rebuilt bundle become a reload signal? The hmr node half observes it itself — no builder tells it. Before reading each startup snapshot, the module host captures the entry stat baseline and exposes it through `ctx.clientModules.artifactBaseline(id)`. One HMR-owned interval compares every current graph row with that baseline. An unchanged row starts watching without a content read or hash; a write after baseline capture is already a stat delta and only that row enters `rebuilt(id)`. This avoids redundant reads when installing the watcher and avoids `fs.watchFile`, whose asynchronous first baseline can silently absorb a construction-time rebuild. Watch membership follows `onGraphChanged`; vanished rows drop out, and an entry missing at poll time keeps its row dirty so reappearance retries publication even when mtime and size match the baseline. The shared tsdown preset stamps `client.js` after every sibling output has been written; on an entry mtime, ctime, or size delta, or a dirty row, `rebuilt(id)` derives the revision from those three metadata values. It reads the new bundle snapshot only if the revision changes. A chunk-only edit therefore changes the revision, and a partial write followed by the completion stamp supplies a later stat change that self-heals. When the `rev` changes, the node half broadcasts a `rebuilt` frame on `GET /plugins/events` — a system SSE channel that sends the full graph on connect and `rebuilt` frames on change, presentation-only wire that never enters the session log. Polling is deliberate because inotify does not fire on the weka network mount, the same reason the build-side watcher needs `--poll`; one entry stat per row and interval is sufficient, the interval is a validated config field (default 500ms), and disposal clears the one timer. Rebuilding artifacts is any process using the shared Client tsdown preset — `scripts/dev-web.ts` remains the watch-build entry point, discovering its package list through `dsh.client` while scanning `packages/*/*/package.json` at startup — and builder and host share no notification protocol. On the browser side, the transport delegates code replacement to the same modules controller that owns graph reconciliation: @@ -120,4 +120,4 @@ Roster: it lives in the web bundle's config tree (`packages/bundle/web-app/cordi | Full ctx-ification now (React and libraries via services, no module table) | Static UI libraries still expose synchronous values, so removing the table would leave those imports without a shared identity | | Eager instantiation with a frozen table | Runs bundle side effects at script arrival; lazy registration keeps execution at Cordis import while recursive `require` materializes registered requests | | Fetch response text, then inject an inline ` + + +
+ + diff --git a/apps/desktop/scripts/desktop-package-environment.mjs b/apps/desktop/scripts/desktop-package-environment.mjs index 71dd9a6655..3addf3ff65 100644 --- a/apps/desktop/scripts/desktop-package-environment.mjs +++ b/apps/desktop/scripts/desktop-package-environment.mjs @@ -4,7 +4,7 @@ import { accessSync, constants, readFileSync, statSync } from 'node:fs' import { dirname, join, resolve } from 'node:path' import { fileURLToPath } from 'node:url' import { parseEnv } from 'node:util' -import { resolveDesktopAppId, resolveMacOSNotarizationEnvironment, resolveMacOSSigningEnvironment } from './desktop-release-environment.mjs' +import { resolveDesktopAppId, resolveMacOSNotarizationEnvironment, resolveMacOSSigningEnvironment, resolveNpmRegistry } from './desktop-release-environment.mjs' import { resolveDesktopAutoUpdateConfig } from './desktop-auto-update-environment.mjs' import { createWindowsTokenSigner } from './windows-sign.mjs' import { resolveDesktopPolicyEnvironment } from './desktop-policy-environment.mjs' @@ -13,7 +13,7 @@ import { resolveWindowsSignatureCacheDirectory } from './windows-signature-cache import { resolveWindowsPackageSettings } from './windows-package-settings.mjs' const APP_ROOT = fileURLToPath(new URL('..', import.meta.url)) -const SHARED_SETTING = /^(?:DSH_DESKTOP_(?:APP_ID|AUTO_UPDATE_ENV|MANDATORY_UPDATE_(?:CONFIG|(?:TEST|PROD)_ORIGIN))|DOWNLOAD_TEST_RELEASE_ID|DOWNLOAD_(?:TEST|PROD)_(?:ORIGIN|COS_BUCKET|COS_SECRET_ID|COS_SECRET_KEY))$/u +const SHARED_SETTING = /^(?:DSH_DESKTOP_(?:APP_ID|AUTO_UPDATE_ENV|NPM_REGISTRY|MANDATORY_UPDATE_(?:CONFIG|(?:TEST|PROD)_ORIGIN))|DOWNLOAD_TEST_RELEASE_ID|DOWNLOAD_(?:TEST|PROD)_(?:ORIGIN|COS_BUCKET|COS_SECRET_ID|COS_SECRET_KEY))$/u const WINDOWS_SETTING = /^DSH_DESKTOP_WINDOWS_(?:CER_FILE|SIGNTOOL|KEY_CONTAINER|TOKEN_PIN|SIGNATURE_CACHE_DIR|SIGNATURE_CACHE_CONCURRENCY)$/u const MACOS_SETTING = /^(?:DSH_DESKTOP_MACOS_(?:SIGNING_IDENTITY|TEAM_ID|PACK_CONCURRENCY|DOWNLOAD_PROXY|NOTARIZATION_PROXY)|APPLE_(?:API_KEY|API_KEY_ID|API_ISSUER|ID|APP_SPECIFIC_PASSWORD|TEAM_ID|KEYCHAIN|KEYCHAIN_PROFILE)|CSC_(?:LINK|KEY_PASSWORD))$/u const AMBIENT_RELEASE_SETTING = /^(?:DSH_DESKTOP_(?:APP_ID|AUTO_UPDATE_ENV|MANDATORY_UPDATE_.*|WINDOWS_.*|MACOS_.*)|APPLE_.*|(?:WIN_)?CSC_.*|DOWNLOAD_(?:TEST|PROD)_.*)$/iu @@ -78,6 +78,7 @@ function requireReadableFile(environment, name) { */ export function validateDesktopPackageEnvironment(environment, target, options = {}) { resolveDesktopAppId(environment) + resolveNpmRegistry(environment) resolveDesktopPolicyEnvironment(environment) if (target.platform === 'darwin') resolveMacOSPackageSettings(environment) else resolveWindowsPackageSettings(environment) diff --git a/apps/desktop/scripts/desktop-release-environment.d.mts b/apps/desktop/scripts/desktop-release-environment.d.mts index ad48933f65..26190ab2b8 100644 --- a/apps/desktop/scripts/desktop-release-environment.d.mts +++ b/apps/desktop/scripts/desktop-release-environment.d.mts @@ -7,6 +7,9 @@ export const MACOS_SIGNING_IDENTITY_ENV: 'DSH_DESKTOP_MACOS_SIGNING_IDENTITY' /** Environment variable that supplies the expected Apple Developer Team ID. */ export const MACOS_TEAM_ID_ENV: 'DSH_DESKTOP_MACOS_TEAM_ID' +/** Environment variable that selects the npm registry used for the bundled runtime install. */ +export const NPM_REGISTRY_ENV: 'DSH_DESKTOP_NPM_REGISTRY' + /** Public identity expected on a macOS release. */ export interface MacOSSigningEnvironment { readonly signingIdentity: string @@ -46,6 +49,13 @@ export type MacOSNotarizationEnvironment = */ export function resolveDesktopAppId(env: NodeJS.ProcessEnv): string +/** + * Resolve the npm registry used to materialize the bundled runtime and its external dependencies. + * @param env - Packaging environment. + * @returns Registry origin; the public registry unless a local mirror is configured. + */ +export function resolveNpmRegistry(env: NodeJS.ProcessEnv): string + /** * Resolve and validate the public identity expected on a macOS release. * @param env - Packaging environment. diff --git a/apps/desktop/scripts/desktop-release-environment.mjs b/apps/desktop/scripts/desktop-release-environment.mjs index 46746428d9..635a57a3c9 100644 --- a/apps/desktop/scripts/desktop-release-environment.mjs +++ b/apps/desktop/scripts/desktop-release-environment.mjs @@ -9,6 +9,11 @@ export const MACOS_SIGNING_IDENTITY_ENV = 'DSH_DESKTOP_MACOS_SIGNING_IDENTITY' /** Environment variable that supplies the expected Apple Developer Team ID. */ export const MACOS_TEAM_ID_ENV = 'DSH_DESKTOP_MACOS_TEAM_ID' +/** Environment variable that selects the npm registry used for the bundled runtime install. */ +export const NPM_REGISTRY_ENV = 'DSH_DESKTOP_NPM_REGISTRY' + +const DEFAULT_NPM_REGISTRY = 'https://registry.npmjs.org/' + const APPLE_API_KEY_ENV = 'APPLE_API_KEY' const APPLE_API_KEY_ID_ENV = 'APPLE_API_KEY_ID' const APPLE_API_ISSUER_ENV = 'APPLE_API_ISSUER' @@ -32,6 +37,24 @@ function requireEnvironmentValue(env, name) { return value } +/** + * Resolve the npm registry used to materialize the bundled runtime and its external dependencies. + * @param {NodeJS.ProcessEnv} env - Packaging environment. + * @returns {string} Registry origin; the public registry unless a local mirror is configured. + */ +export function resolveNpmRegistry(env) { + const configured = env[NPM_REGISTRY_ENV]?.trim() ?? '' + if (configured === '') return DEFAULT_NPM_REGISTRY + let url + try { url = new URL(configured) } + catch { throw new Error(`desktop release environment: ${NPM_REGISTRY_ENV} must be an HTTPS origin`) } + if (url.protocol !== 'https:' || url.username !== '' || url.password !== '' || url.search !== '' || url.hash !== '' + || (url.pathname !== '/' && url.pathname !== '')) { + throw new Error(`desktop release environment: ${NPM_REGISTRY_ENV} must be an HTTPS origin without credentials, path, query, or fragment`) + } + return url.origin +} + /** * Resolve and validate the application identifier shared by every platform target. * @param {NodeJS.ProcessEnv} env - Packaging environment. diff --git a/apps/desktop/scripts/dev.ts b/apps/desktop/scripts/dev.ts index 05e1bdbf0e..36d57325dc 100644 --- a/apps/desktop/scripts/dev.ts +++ b/apps/desktop/scripts/dev.ts @@ -8,6 +8,7 @@ import { parseArgs } from 'node:util' import { DESKTOP_HOST_PROTOCOL_VERSION } from '../src/host-protocol.ts' import type { DesktopRelease } from '../src/release.ts' import { prepareDevelopmentProject } from './development-project.ts' +import { prepareDevelopmentApp } from './development-app.ts' import { preparePrimaryRuntime } from './prepare-primary-runtime.ts' const APP_ROOT = resolve(import.meta.dirname, '..') @@ -62,7 +63,7 @@ async function launchElectron(): Promise { const rendererPort = debugPort('DSH_DESKTOP_RENDERER_DEBUG_PORT', 9222) const hostPort = debugPort('DSH_DESKTOP_HOST_INSPECT_PORT', 9230) const home = resolve(process.env.DSH_HOME ?? join(DEVELOPMENT_ROOT, 'home')) - const userData = join(DEVELOPMENT_ROOT, 'electron-user-data') + const userData = resolve(process.env.DSH_DESKTOP_USER_DATA_DIR ?? join(DEVELOPMENT_ROOT, 'electron-user-data')) const environment: NodeJS.ProcessEnv = { ...process.env, DSH_HOME: home, @@ -71,7 +72,14 @@ async function launchElectron(): Promise { ELECTRON_ENABLE_LOGGING: process.env.ELECTRON_ENABLE_LOGGING ?? '1', } console.log(`desktop development: DSH_HOME=${home}`) + console.log(`desktop development: userData=${userData}`) console.log(`desktop development: inspectors main=${String(mainPort)}, renderer=${String(rendererPort)}, host=${String(hostPort)}`) + if (process.platform === 'darwin') { + const executable = prepareDevelopmentApp({ electron, appRoot: APP_ROOT, directory: DEVELOPMENT_ROOT, home, userData, + mainPort, rendererPort, hostPort, openDevtools: environment.DSH_DESKTOP_OPEN_DEVTOOLS! }) + await run(executable, [], APP_ROOT, environment) + return + } await run(electron, [ `--inspect=127.0.0.1:${String(mainPort)}`, `--remote-debugging-port=${String(rendererPort)}`, diff --git a/apps/desktop/scripts/development-app.ts b/apps/desktop/scripts/development-app.ts new file mode 100644 index 0000000000..ff09b8b783 --- /dev/null +++ b/apps/desktop/scripts/development-app.ts @@ -0,0 +1,84 @@ +/** macOS development bundle that loads the current workspace through Electron. */ +import { execFileSync } from 'node:child_process' +import { createHash } from 'node:crypto' +import { existsSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { dirname, join } from 'node:path' + +/** Workspace and runtime settings captured for Launch Services cold starts. */ +export interface DevelopmentAppOptions { + readonly electron: string + readonly appRoot: string + readonly directory: string + readonly home: string + readonly userData: string + readonly mainPort: number + readonly rendererPort: number + readonly hostPort: number + readonly openDevtools: string +} + +function quote(value: string): string { return `'${value.replaceAll("'", "'\\''")}'` } + +/** + * Prepare and register a disposable .app without changing the installed Electron package. + * @param options - Current workspace, Electron binary, and private development locations. + * @returns executable used by the supported desktop development launcher. + */ +export function prepareDevelopmentApp(options: DevelopmentAppOptions): string { + const source = dirname(dirname(dirname(options.electron))) + const bundle = join(options.directory, 'Harness Dev.app') + const executable = join(bundle, 'Contents', 'MacOS', 'HarnessDev') + const stamp = join(bundle, 'Contents', 'Resources', 'dsh-development.json') + const launcher = developmentLauncher(options, bundle) + const identity = JSON.stringify({ ...options, launcher, plist: readFileSync(join(source, 'Contents', 'Info.plist'), 'utf8') }) + if (!existsSync(stamp) || readFileSync(stamp, 'utf8') !== identity) { + rmSync(bundle, { recursive: true, force: true }) + execFileSync('/usr/bin/ditto', [source, bundle]) + const plist = join(bundle, 'Contents', 'Info.plist') + const values = { + CFBundleIdentifier: `com.deepseek.harness.dev.${createHash('sha256').update(options.appRoot).digest('hex').slice(0, 12)}`, + CFBundleName: 'Harness Dev', + CFBundleDisplayName: 'Harness Dev', + CFBundleExecutable: 'HarnessDev', + CFBundleURLTypes: [{ CFBundleURLName: 'DeepSeek Harness', CFBundleURLSchemes: ['dsh'], CFBundleTypeRole: 'Viewer' }], + } + for (const [key, value] of Object.entries(values)) { + execFileSync('/usr/bin/plutil', ['-replace', key, '-json', JSON.stringify(value), plist]) + } + writeFileSync(executable, launcher, { mode: 0o755 }) + writeFileSync(stamp, identity, { mode: 0o600 }) + execFileSync('/usr/bin/codesign', ['--force', '--deep', '--sign', '-', bundle], { stdio: 'pipe' }) + } + execFileSync('/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister', ['-f', bundle]) + return executable +} + +/** + * Create the development executable used by both the CLI and Launch Services. + * @param options - Persisted development locations and debugging settings. + * @param bundle - Generated application bundle. + * @returns shell program with literal arguments and environment values. + */ +export function developmentLauncher(options: DevelopmentAppOptions, bundle: string): string { + const environment = { + DSH_HOME: options.home, + DSH_DESKTOP_DEV_APP: '1', + DSH_DESKTOP_HOST_INSPECT_PORT: String(options.hostPort), + DSH_DESKTOP_OPEN_DEVTOOLS: options.openDevtools, + ELECTRON_ENABLE_LOGGING: '1', + } + const args = [ + join(bundle, 'Contents', 'MacOS', 'Electron'), + `--inspect=127.0.0.1:${String(options.mainPort)}`, + `--remote-debugging-port=${String(options.rendererPort)}`, + `--user-data-dir=${options.userData}`, + options.appRoot, + ] + return [ + '#!/bin/sh', + ...Object.entries(environment).map(([key, value]) => `export ${key}=${quote(value)}`), + `cd ${quote(options.appRoot)}`, + `exec ${args.map(quote).join(' ')} "$@"`, + '', + ].join('\n') +} diff --git a/apps/desktop/scripts/development-project.ts b/apps/desktop/scripts/development-project.ts index eddd683161..36c70baff0 100644 --- a/apps/desktop/scripts/development-project.ts +++ b/apps/desktop/scripts/development-project.ts @@ -20,6 +20,7 @@ import { DESKTOP_RUNTIME_FILE, type DesktopRuntimeDescriptor } from '../src/runt interface PackageManifest { readonly name?: string readonly version?: string + readonly dependencies?: Readonly> } /** Inputs whose locations differ between the launcher and isolated tests. */ @@ -86,6 +87,32 @@ function mirrorDependencyLinks(sourceRoot: string, destinationRoot: string): str return names } +/** Configured workspace plugins must resolve from the profile even when pnpm does not hoist them. */ +function mirrorWorkspaceDependencies(roots: readonly string[], destinationRoot: string): string[] { + const names: string[] = [] + const visited = new Set() + const visit = (directory: string): void => { + const source = realpathSync(directory) + if (visited.has(source)) return + visited.add(source) + const manifest = readManifest(join(source, 'package.json')) + for (const [name, specifier] of Object.entries(manifest.dependencies ?? {})) { + if (!specifier.startsWith('workspace:')) continue + const dependency = join(source, 'node_modules', ...name.split('/')) + if (!existsSync(dependency)) { + throw new Error(`desktop development: ${name} is missing from ${source}; run pnpm install`) + } + const destination = join(destinationRoot, ...name.split('/')) + removeOwnedPath(destination) + linkDirectory(dependency, destination) + names.push(name) + visit(dependency) + } + } + for (const directory of roots) visit(directory) + return names +} + /** * Replace one disposable project with links to the current built workspace. * @param options - Project destination, CLI package, and release identity. @@ -117,7 +144,10 @@ export function prepareDevelopmentProject(options: DevelopmentProjectOptions): s createDevelopmentProjectMetadata(options.projectDir, options.release) const destinationModules = join(options.projectDir, 'node_modules') mkdirSync(destinationModules, { recursive: true }) - const names = mirrorDependencyLinks(options.dependencyDir, destinationModules) + const names = [ + ...mirrorDependencyLinks(options.dependencyDir, destinationModules), + ...mirrorWorkspaceDependencies([options.cliDir, options.hostDir], destinationModules), + ] const dshLink = join(destinationModules, '@deepseek-ai', 'dsh') removeOwnedPath(dshLink) linkDirectory(options.cliDir, dshLink) diff --git a/apps/desktop/scripts/electron-builder-config.mjs b/apps/desktop/scripts/electron-builder-config.mjs index 118bae070b..e3873de35f 100644 --- a/apps/desktop/scripts/electron-builder-config.mjs +++ b/apps/desktop/scripts/electron-builder-config.mjs @@ -68,7 +68,7 @@ export function createElectronBuilderConfig( let primaryRuntimeDestination let dshDestination let windowsCode = [] - const unpack = ['**/*.{node,dylib,dll,so,exe}', '**/*.so.*', '**/spawn-helper', '**/@vscode/ripgrep/bin/rg', + const unpack = ['**/*.{node,dylib,dll,so,exe}', '**/*.so.*', '**/spawn-helper', '**/@vscode/ripgrep-*/bin/rg', `**/node_modules/@deepseek-ai/libreoffice-kit-${resolvedPlatform}-${resolvedArch}/**/*`] const windowsSigner = packagesWindows && !unsigned ? createWindowsTokenSigner({ @@ -98,6 +98,7 @@ export function createElectronBuilderConfig( const packaged = resolveDesktopBuildCommit(env) return { appId, + protocols: [{ name: 'DeepSeek Harness', schemes: ['dsh'] }], extraMetadata: { dshDesktopAppId: appId, dshMandatoryUpdatePolicy: policy, @@ -125,9 +126,12 @@ export function createElectronBuilderConfig( }, files: [ 'lib/main.js', + 'lib/welcome/**/*', 'lib/preload-app.cjs', 'lib/preload-mandatory.cjs', + 'lib/preload-platform-account.cjs', 'lib/preload-update-dialog.cjs', + 'lib/preload-welcome.cjs', 'renderer/**/*', 'package.json', { from: buildPaths.dsh, to: 'dsh', filter: ['**/*'] }, diff --git a/apps/desktop/scripts/macos-signing-keychain.d.mts b/apps/desktop/scripts/macos-signing-keychain.d.mts index 452878aad1..f95a370c98 100644 --- a/apps/desktop/scripts/macos-signing-keychain.d.mts +++ b/apps/desktop/scripts/macos-signing-keychain.d.mts @@ -3,14 +3,15 @@ /** * Import and authorize the required p12 before work; delete the owned keychain after work settles. * Children receive only its path, never the p12 password. Existing login keychains are not unlocked. + * The owned keychain is prepended to the user search list for the run and the previous list is restored. * Abrupt process termination requires the CI runner to clean its temporary directory. * @param environment Validated platform configuration with local CSC_LINK and CSC_KEY_PASSWORD. * @param action All signing work, settled before cleanup. - * @param run Apple command executor. + * @param run Apple command executor returning command standard output. * @returns Resolves after work and cleanup; rejects on setup, work, or cleanup failure. */ export function withMacOSSigningKeychain( environment: NodeJS.ProcessEnv, action: (environment: NodeJS.ProcessEnv) => Promise, - run?: (command: string, args: string[]) => void, + run?: (command: string, args: string[]) => string, ): Promise diff --git a/apps/desktop/scripts/macos-signing-keychain.mjs b/apps/desktop/scripts/macos-signing-keychain.mjs index e71d469395..425eb6a96c 100644 --- a/apps/desktop/scripts/macos-signing-keychain.mjs +++ b/apps/desktop/scripts/macos-signing-keychain.mjs @@ -9,23 +9,40 @@ import { join } from 'node:path' * Execute a credential-bearing Apple command without exposing arguments or tool output on failure. * @param {string} command Absolute executable path. * @param {string[]} args Command arguments, potentially containing secrets. - * @returns {void} + * @returns {string} Command standard output, needed when the caller reads a security query. */ function execute(command, args) { - try { execFileSync(command, args, { stdio: 'pipe', timeout: 120_000 }) } + try { + return execFileSync(command, args, { stdio: 'pipe', timeout: 120_000, encoding: 'utf8' }) + } catch (error) { // execFile errors contain the command line, including private-key passwords. throw new Error(`desktop macOS signing: ${command} ${args[0]} failed; check certificate, password, and signing access`) } } +/** + * Read the user's keychain search list so this invocation can extend and later restore it. + * @param {(command: string, args: string[]) => string} run Apple command executor. + * @returns {string[]} Keychain paths on the user search list. + */ +function readUserKeychains(run) { + const output = run('/usr/bin/security', ['list-keychains', '-d', 'user']) + if (typeof output !== 'string') { + throw new Error('desktop macOS signing: the user keychain search list could not be read') + } + return output.split('\n').map(line => line.trim().replace(/^"|"$/gu, '')).filter(path => path !== '') +} + /** * Import and authorize the required p12 before work; delete the owned keychain after work settles. * Children receive only its path, never the p12 password. Existing login keychains are not unlocked. + * codesign resolves an identity only from a keychain on the user search list, so the owned keychain + * is prepended during the run and the previous list is restored before deletion. * Abrupt process termination requires the CI runner to clean its temporary directory. * @param {NodeJS.ProcessEnv} environment Validated platform configuration with local CSC_LINK and CSC_KEY_PASSWORD. * @param {(environment: NodeJS.ProcessEnv) => Promise} action All signing work, settled before cleanup. - * @param {(command: string, args: string[]) => void} run Apple command executor. + * @param {(command: string, args: string[]) => string} run Apple command executor. * @returns {Promise} Resolves after work and cleanup; rejects on setup, work, or cleanup failure. */ export async function withMacOSSigningKeychain(environment, action, run = execute) { @@ -38,6 +55,7 @@ export async function withMacOSSigningKeychain(environment, action, run = execut /** @param {string[]} args Security command arguments. */ const security = args => run('/usr/bin/security', args) let created = false + let previousKeychains try { security(['create-keychain', '-p', password, keychain]) created = true @@ -45,6 +63,10 @@ export async function withMacOSSigningKeychain(environment, action, run = execut security(['set-keychain-settings', keychain]) security(['import', certificate, '-k', keychain, '-P', exportPassword, '-T', '/usr/bin/codesign', '-T', '/usr/bin/productbuild']) security(['set-key-partition-list', '-S', 'apple-tool:,apple:', '-s', '-k', password, keychain]) + // codesign ignores --keychain unless that file is also on the search list + // (https://github.com/electron-userland/electron-builder/issues/1457). + previousKeychains = readUserKeychains(run) + security(['list-keychains', '-d', 'user', '-s', keychain, ...previousKeychains]) const probe = join(directory, 'probe') run('/bin/cp', ['/usr/bin/true', probe]) run('/usr/bin/codesign', ['--force', '--sign', `Developer ID Application: ${environment.DSH_DESKTOP_MACOS_SIGNING_IDENTITY}`, '--keychain', keychain, '--timestamp', '--options', 'runtime', probe]) @@ -54,7 +76,10 @@ export async function withMacOSSigningKeychain(environment, action, run = execut delete childEnvironment.CSC_KEY_PASSWORD await action(childEnvironment) } finally { - try { if (created) security(['delete-keychain', keychain]) } + try { + if (previousKeychains !== undefined) security(['list-keychains', '-d', 'user', '-s', ...previousKeychains]) + if (created) security(['delete-keychain', keychain]) + } finally { rmSync(directory, { recursive: true, force: true }) } } } diff --git a/apps/desktop/scripts/prepare-dsh.ts b/apps/desktop/scripts/prepare-dsh.ts index 23099a5b46..a89247ad18 100644 --- a/apps/desktop/scripts/prepare-dsh.ts +++ b/apps/desktop/scripts/prepare-dsh.ts @@ -24,6 +24,7 @@ import { writeDesktopRuntime, verifyDesktopRuntime } from '../src/runtime-tree.t import { resolveDesktopAppId, resolveMacOSSigningEnvironment, + resolveNpmRegistry, } from './desktop-release-environment.mjs' import { signMacOSRuntime, @@ -69,6 +70,7 @@ function runPnpm(args: readonly string[]): Promise { return new Promise((resolvePromise, reject) => { const [command, ...commandArgs] = args if (command === undefined) throw new Error('desktop runtime: pnpm command is required') + const registry = resolveNpmRegistry(process.env) const config = join(PNPM_BUILD_STATE, 'config') const userConfig = join(config, 'npmrc') mkdirSync(config, { recursive: true }) @@ -76,7 +78,7 @@ function runPnpm(args: readonly string[]): Promise { const child = spawn(NODE, [ '--expose-internals', PNPM, - '--config.registry=https://registry.npmjs.org/', + `--config.registry=${registry}`, `--config.store-dir=${STORE_ROOT}`, '--config.enable-global-virtual-store=false', `--config.userconfig=${userConfig}`, @@ -88,7 +90,7 @@ function runPnpm(args: readonly string[]): Promise { ...Object.fromEntries(Object.entries(process.env).filter(([name]) => ( name !== 'NODE_OPTIONS' && name !== 'NODE_PATH' && !/^DSH_DESKTOP_/u.test(name) && !/^(?:npm|pnpm|corepack)_/iu.test(name) ))), - NPM_CONFIG_REGISTRY: 'https://registry.npmjs.org/', + NPM_CONFIG_REGISTRY: registry, NPM_CONFIG_STORE_DIR: STORE_ROOT, NPM_CONFIG_USERCONFIG: userConfig, ...desktopNodeEnvironment(NODE, join(RUNTIME_ROOT, 'bin'), {}), diff --git a/apps/desktop/src/account-backend.ts b/apps/desktop/src/account-backend.ts new file mode 100644 index 0000000000..0db791f631 --- /dev/null +++ b/apps/desktop/src/account-backend.ts @@ -0,0 +1,112 @@ +/** Native account commands and Gateway state stream; no renderer receives credentials. */ +import { randomUUID } from 'node:crypto' +import WebSocket from 'ws' +import { parseRemoteStreamServerMessage, REMOTE_STREAM_MUX_PATH } from '@deepseek-ai/dsh-api-gateway/stream-protocol' +import type { AccountView, SignInAttemptId } from '@deepseek-ai/dsh-deepseek-account/types' + +/** Authenticated unary caller shared with native onboarding. */ +export type AccountInvoke = (request: { namespace: string; method: string; args: Record }) => Promise + +/** Decode the UI-safe state received across HTTP or WebSocket. @param value - wire value. @returns account projection. */ +export function accountView(value: unknown): AccountView { + if (typeof value !== 'object' || value === null || !('status' in value) + || !['signed-out', 'credential-stored'].includes(String(value.status)) || !('attempt' in value)) { + throw new Error('desktop account: invalid state') + } + if (!('links' in value) || typeof value.links !== 'object' || value.links === null + || !('usageUrl' in value.links) || typeof value.links.usageUrl !== 'string' + || !('topUpUrl' in value.links) || typeof value.links.topUpUrl !== 'string') { + throw new Error('desktop account: invalid platform links') + } + validateBrowserDestination(value.links.usageUrl) + validateBrowserDestination(value.links.topUpUrl) + const attempt = value.attempt + if (attempt !== null && (typeof attempt !== 'object' || !('id' in attempt) || typeof attempt.id !== 'string' + || !('phase' in attempt) || !['initializing', 'waiting-browser', 'exchanging', 'committing', 'succeeded', 'cancelled', 'expired', 'failed'].includes(String(attempt.phase)) + || ('authorizeUrl' in attempt && typeof attempt.authorizeUrl !== 'string') + || ('expiresAt' in attempt && (typeof attempt.expiresAt !== 'number' || !Number.isFinite(attempt.expiresAt))) + || ('errorCode' in attempt && !['network', 'protocol', 'expired', 'storage'].includes(String(attempt.errorCode))))) { + throw new Error('desktop account: invalid attempt') + } + if (attempt !== null && 'authorizeUrl' in attempt) { + validateBrowserDestination(String(attempt.authorizeUrl)) + } + const parsed = value as AccountView + return { + status: parsed.status, + links: { usageUrl: parsed.links.usageUrl, topUpUrl: parsed.links.topUpUrl }, + attempt: parsed.attempt === null ? null : { + id: parsed.attempt.id, phase: parsed.attempt.phase, + ...parsed.attempt.authorizeUrl === undefined ? {} : { authorizeUrl: parsed.attempt.authorizeUrl }, + ...parsed.attempt.expiresAt === undefined ? {} : { expiresAt: parsed.attempt.expiresAt }, + ...parsed.attempt.errorCode === undefined ? {} : { errorCode: parsed.attempt.errorCode }, + }, + } +} + +/** Only HTTP loopback or HTTPS destinations can leave the native app. */ +function validateBrowserDestination(value: string): void { + const url = new URL(value) + const loopback = ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname) + if (url.username || url.password || !(url.protocol === 'https:' || (loopback && url.protocol === 'http:'))) { + throw new Error('desktop account: invalid browser destination') + } +} + +/** Native account operations and explicitly owned stream lifetime. */ +export interface DesktopAccountBackend { + /** @returns current account snapshot. */ + state(): Promise + /** @param locale - active desktop UI language. @returns new or already-running login attempt. */ + start(locale: string): Promise + /** @param id - attempt to cancel. @returns cancellation or completed commit state. */ + cancel(id: SignInAttemptId): Promise + /** @returns state after local sign-out. */ + signOut(): Promise + /** @param listener - state recipient. @param failed - stream failure recipient. @returns stream disposer. */ + watch(listener: (state: AccountView) => void, failed: () => void): () => void +} + +/** + * Connect native account operations to the standard authenticated Web backend. + * @param origin - Host Web origin. + * @param invoke - validated unary RPC caller. + * @param cookies - Electron session cookie reader. + * @returns account operations; watch callers own their subscriptions. + */ +export function desktopAccountBackend(origin: string, invoke: AccountInvoke, cookies: () => Promise): DesktopAccountBackend { + const call = async (method: string, args: Record = {}): Promise => + accountView(await invoke({ namespace: 'account', method, args })) + return { + state: () => call('getState'), start: locale => call('startSignIn', { locale, callbackOrigin: new URL(origin).origin, loginSource: 'desktop' }), + cancel: attemptId => call('cancelSignIn', { attemptId }), signOut: () => call('signOut'), + watch(listener, failed) { + let closed = false + let socket: WebSocket | undefined + let retry: ReturnType | undefined + const connect = (): void => { + const streamId = randomUUID() + void cookies().then((cookie) => { + if (closed) return + const url = new URL(REMOTE_STREAM_MUX_PATH, origin) + url.protocol = url.protocol === 'https:' ? 'wss:' : 'ws:' + socket = new WebSocket(url, { headers: { cookie, origin }, maxPayload: 65_536 }) + socket.on('open', () => socket?.send(JSON.stringify({ type: 'open', streamId, endpoint: 'account/watch', payload: { args: {} } }))) + socket.on('message', (data) => { + try { + const bytes = Array.isArray(data) ? Buffer.concat(data) : Buffer.isBuffer(data) ? data : Buffer.from(data) + const frame = parseRemoteStreamServerMessage(bytes.toString('utf8')) + if (frame.streamId !== streamId) throw new Error('desktop account: unexpected stream') + if (frame.type === 'item') listener(accountView(frame.value)) + else socket?.close() + } catch { socket?.close() } + }) + socket.on('error', () => { socket?.close() }) + socket.on('close', () => { if (!closed) { failed(); retry = setTimeout(connect, 1000) } }) + }).catch(() => { if (!closed) { failed(); retry = setTimeout(connect, 1000) } }) + } + connect() + return () => { closed = true; clearTimeout(retry); socket?.close() } + }, + } +} diff --git a/apps/desktop/src/browser-guests.ts b/apps/desktop/src/browser-guests.ts index 027b7cee5b..c3f0b10eea 100644 --- a/apps/desktop/src/browser-guests.ts +++ b/apps/desktop/src/browser-guests.ts @@ -9,6 +9,7 @@ interface GuestLease { readonly partition: string attached: boolean guest?: WebContents + releaseInput?: () => void } /** Owns workspace storage partitions independently from individual tab guests. */ @@ -51,6 +52,7 @@ export class DesktopBrowserGuests { const lease = this.leases.get(key) if (lease === undefined) return if (lease.owner !== owner) throw new Error('desktop browser: guest belongs to another window') + lease.releaseInput?.() this.leases.delete(key) const guest = lease.guest if (guest !== undefined && !guest.isDestroyed()) { @@ -63,8 +65,9 @@ export class DesktopBrowserGuests { /** * Install attachment checks before the application document can create a webview. * @param window - primary application window. + * @param attachInput - attaches native input after guest ownership is verified and returns its disposer. */ - bind(window: BrowserWindow): void { + bind(window: BrowserWindow, attachInput: (guest: WebContents, name: DesktopBrowserLeaseId) => () => void): void { const owner = window.webContents owner.on('will-attach-webview', (event, preferences, params) => { const id = typeof params.src === 'string' && params.src.startsWith('about:blank#') @@ -102,7 +105,8 @@ export class DesktopBrowserGuests { } lease.guest = guest attachedLease = id - guest.once('destroyed', () => { this.leases.delete(id) }) + lease.releaseInput = attachInput(guest, id) + guest.once('destroyed', () => { lease.releaseInput?.(); this.leases.delete(id) }) }) guest.setWindowOpenHandler(({ url, postBody }) => { const lease = attachedLease === undefined ? undefined : this.leases.get(attachedLease) diff --git a/apps/desktop/src/client/WelcomePage.tsx b/apps/desktop/src/client/WelcomePage.tsx new file mode 100644 index 0000000000..179bc4ef09 --- /dev/null +++ b/apps/desktop/src/client/WelcomePage.tsx @@ -0,0 +1,208 @@ +/** Desktop welcome presentation; account and credential operations stay in the preload. */ +import { useEffect, useRef, useState } from 'react' +import type { FormEvent } from 'react' +import { StateDot } from '@deepseek-ai/dsh-client-ui-primitives/src/StateDot.tsx' +import type { AccountView } from '@deepseek-ai/dsh-deepseek-account/types' +import type { WelcomeApi } from '../welcome-api.ts' + +type Page = 'entry' | 'key' | 'account' + +/** + * Render the standalone welcome flow using shell-owned operations and localized copy. + * @param props.api - isolated preload API; no account credentials reach the renderer. + * @returns welcome pages with fixed bottom actions. + */ +export function Welcome({ api }: { api: WelcomeApi }) { + const { messages: m } = api + const [page, setPage] = useState('entry') + const pageRef = useRef('entry') + const [attempt, setAttempt] = useState(null) + const attemptRef = useRef(null) + const [starting, setStarting] = useState(false) + const [cancelling, setCancelling] = useState(false) + const [copyFeedback, setCopyFeedback] = useState<{ status: 'idle' | 'busy' | 'copied' | 'failed' }>({ status: 'idle' }) + const copyState = copyFeedback.status + const [draft, setDraft] = useState('') + const [error, setError] = useState('') + const [busy, setBusy] = useState(false) + const busyRef = useRef(false) + const mounted = useRef(true) + const revision = useRef(0) + const input = useRef(null) + const keyButton = useRef(null) + const focusEntry = useRef(false) + + function navigate(next: Page) { + pageRef.current = next + setPage(next) + } + function showAccount(state: AccountView) { + if (pageRef.current === 'key' || (state.attempt === null && pageRef.current === 'entry')) return + attemptRef.current = state.attempt + setAttempt(state.attempt) + setStarting(false) + setCopyFeedback({ status: 'idle' }) + navigate(state.attempt?.phase === 'cancelled' ? 'entry' : 'account') + } + + useEffect(() => { + mounted.current = true + document.documentElement.lang = api.id + document.title = m.welcomeTitle + const stop = api.onAccountState((state) => { + revision.current++ + showAccount(state) + }) + return () => { mounted.current = false; stop() } + }, [api, m.welcomeTitle]) + + useEffect(() => { + if (page === 'key') input.current?.focus() + else if (page === 'entry' && focusEntry.current) { + focusEntry.current = false + keyButton.current?.focus() + } + }, [page]) + + useEffect(() => { + if (copyState !== 'copied' && copyState !== 'failed') return + const timer = setTimeout(() => { setCopyFeedback({ status: 'idle' }) }, 2000) + return () => { clearTimeout(timer) } + }, [copyFeedback]) + + async function saveKey(event: FormEvent) { + event.preventDefault() + if (busyRef.current) return + const value = draft.trim() + if (!/^[\x21-\x7e]+$/.test(value) || /^[A-Z][A-Z0-9_]*=[^=]/.test(value) + || ((value.startsWith('"') || value.startsWith("'") || value.charCodeAt(0) === 96) && value.at(-1) === value[0])) { + setError(value === '' ? m.welcomeKeyBlank : m.welcomeKeyInvalid) + input.current?.focus() + return + } + busyRef.current = true + setBusy(true) + setError('') + try { + const result = await api.saveApiKey(value) + if (!mounted.current) return + if (result.ok) setDraft('') + else setError(m.welcomeKeyFailed) + } catch { + if (mounted.current) setError(m.welcomeKeyFailed) + } finally { + busyRef.current = false + if (mounted.current) setBusy(false) + } + } + async function skip() { + if (busyRef.current) return + busyRef.current = true + setBusy(true) + try { + await api.skip() + if (mounted.current) setDraft('') + } catch { + if (mounted.current) setError(m.welcomeContinueFailed) + } finally { + busyRef.current = false + if (mounted.current) setBusy(false) + } + } + async function start() { + navigate('account') + setStarting(true) + setAttempt(null) + attemptRef.current = null + const current = ++revision.current + try { + const state = await api.startSignIn() + if (mounted.current && revision.current === current) showAccount(state) + } catch { + if (mounted.current && revision.current === current) setStarting(false) + } + } + async function cancel() { + if (cancelling || attemptRef.current === null) return + setCancelling(true) + const current = ++revision.current + try { + const state = await api.cancelSignIn(attemptRef.current.id) + if (mounted.current && revision.current === current) showAccount(state) + } catch { + // The current attempt remains visible so cancellation can be retried. + } finally { + if (mounted.current) setCancelling(false) + } + } + async function copyLink() { + const current = attemptRef.current + if (current?.phase !== 'waiting-browser' || (copyState === 'busy' || copyState === 'copied')) return + setCopyFeedback({ status: 'busy' }) + try { + await api.copySignInLink(current.id) + if (mounted.current && attemptRef.current === current) setCopyFeedback({ status: 'copied' }) + } catch { + if (mounted.current && attemptRef.current === current) setCopyFeedback({ status: 'failed' }) + } + } + + const phase = starting ? 'initializing' : attempt?.phase ?? 'failed' + const waiting = phase === 'waiting-browser' + const failed = phase === 'expired' || phase === 'failed' + const title = phase === 'initializing' ? m.welcomeAuthStarting + : waiting ? m.welcomeAuthWaiting : phase === 'expired' ? m.welcomeAuthExpired + : phase === 'failed' ? m.welcomeAuthFailed : m.welcomeAuthExchanging + const heading = page === 'entry' ? 'welcome-heading' : page === 'key' ? 'key-title' : 'auth-status' + + return <> +