diff --git a/apps/desktop/scripts/native/office-driver/macos/main.swift b/apps/desktop/scripts/native/office-driver/macos/main.swift index 343496da8..bd9c5cb65 100644 --- a/apps/desktop/scripts/native/office-driver/macos/main.swift +++ b/apps/desktop/scripts/native/office-driver/macos/main.swift @@ -121,7 +121,9 @@ final class OfficeDriver { let source = """ tell application id "com.microsoft.Excel" set output to {} - repeat with wb in workbooks + set openWorkbooks to get every workbook + repeat with workbookRef in openWorkbooks + set wb to contents of workbookRef set workbookPath to "" try set workbookPath to full name of wb as text diff --git a/packages/core/src/official-plugin-runtime.ts b/packages/core/src/official-plugin-runtime.ts index 55549d47b..7d5994e9f 100644 --- a/packages/core/src/official-plugin-runtime.ts +++ b/packages/core/src/official-plugin-runtime.ts @@ -173,7 +173,7 @@ async function readMetadata(path: string): Promise { function safeRuntimePath(value: string): boolean { return value.startsWith("runtime/") && !isAbsolute(value) - && value.split("/").every((part) => /^[A-Za-z0-9_. -]+$/u.test(part) && part !== "." && part !== ".."); + && value.split("/").every((part) => /^[A-Za-z0-9_@. -]+$/u.test(part) && part !== "." && part !== ".."); } async function listRuntimeFiles(root: string, directory: string, depth = 0): Promise { diff --git a/packages/core/src/storage/sqlite/delegation-migration.ts b/packages/core/src/storage/sqlite/delegation-migration.ts index fcf06f0de..089a8df0f 100644 --- a/packages/core/src/storage/sqlite/delegation-migration.ts +++ b/packages/core/src/storage/sqlite/delegation-migration.ts @@ -226,8 +226,7 @@ export function applyDelegationMigration(input: DelegationMigrationInput): boole if (input.hasMigration(DELEGATION_MIGRATION_VERSION) !== recorded) { throw new Error("Delegation migration marker state mismatch."); } - const missing = inspectDefinitions(database, recorded); - if (recorded && missing.length === 0) { + if (recorded && inspectDefinitions(database, true).length === 0) { assertPostconditions(database); return false; } @@ -237,6 +236,7 @@ export function applyDelegationMigration(input: DelegationMigrationInput): boole database.exec("BEGIN IMMEDIATE;"); try { const currentMarker = readMigrationMarker(database); + if (!currentMarker) replaceEmptyDevelopmentDelegationTables(database); const currentMissing = inspectDefinitions(database, currentMarker); for (const definition of currentMissing) database.exec(definition.sql); assertPostconditions(database); @@ -253,6 +253,31 @@ export function applyDelegationMigration(input: DelegationMigrationInput): boole } } +/** The 139 development schema stored budget counters inline and linked steps through delegation_roots. */ +function replaceEmptyDevelopmentDelegationTables(database: DatabaseSync): void { + const legacyMarker = database.prepare("SELECT name FROM schema_migrations WHERE version=139").get()?.name; + if (legacyMarker !== "create_delegation_tree") return; + const budgetColumnEnd = stepColumns.indexOf("idempotency_key"); + const legacyStepColumns = [...stepColumns.slice(0, budgetColumnEnd), + "consumed_token_count", "consumed_cost_micros", "consumed_wall_time_ms", "budget_settled_at", ...stepColumns.slice(budgetColumnEnd)]; + const readColumns = database.prepare("SELECT name FROM pragma_table_info(?) ORDER BY cid"); + for (const [table, columns] of [["delegation_steps", legacyStepColumns], ["delegation_messages", messageColumns]] as const) { + const actual = readColumns.all(table); + if (actual.length !== columns.length || actual.some((row, index) => row.name !== columns[index])) return; + } + if (!database.prepare(`SELECT 1 FROM pragma_foreign_key_list('delegation_steps') + WHERE "from"='root_run_id' AND "table"='delegation_roots' AND "to"='root_run_id'`).get()) return; + + const exists = database.prepare("SELECT 1 FROM sqlite_schema WHERE type='table' AND name=?"); + for (const table of ["delegation_steps", "delegation_messages", "delegation_roots", "delegation_operations", "delegation_message_deliveries"]) { + if (!exists.get(table)) return; + if (database.prepare(`SELECT 1 FROM ${table} LIMIT 1`).get()) { + throw new Error("Delegation migration cannot replace a populated historical development schema."); + } + } + database.exec("DROP TABLE delegation_messages; DROP TABLE delegation_steps;"); +} + /** Reject both a conflicting version owner and a reused migration name at another version. */ function readMigrationMarker(database: DatabaseSync): boolean { const rows = database.prepare("SELECT version, name FROM schema_migrations WHERE version = ? OR name = ?") diff --git a/packages/core/src/storage/sqlite/migrations.ts b/packages/core/src/storage/sqlite/migrations.ts index 1b60d7482..978135679 100644 --- a/packages/core/src/storage/sqlite/migrations.ts +++ b/packages/core/src/storage/sqlite/migrations.ts @@ -281,6 +281,7 @@ const AUTOMATION_MONITOR_SNAPSHOTS_MIGRATION_VERSION = 142; const AUTOMATION_MONITOR_SNAPSHOTS_MIGRATION_NAME = "create_automation_monitor_snapshots"; const PLUGIN_DISTRIBUTION_FIELDS_MIGRATION_VERSION = 143; const PLUGIN_DISTRIBUTION_FIELDS_MIGRATION_NAME = "add_plugin_distribution_fields"; +const PLUGIN_DISTRIBUTION_FIELDS = ["artifact_id", "platform", "arch", "source_url", "catalog_version", "previous_version"] as const; export function configureSqliteRunStoreDatabase(database: DatabaseSync): void { database.exec(` @@ -2456,31 +2457,13 @@ export function applySqliteRunStoreMigrations(context: SqliteRunStoreMigrationCo } } - const hasPluginDistributionFieldsMigration = context.hasMigration(PLUGIN_DISTRIBUTION_FIELDS_MIGRATION_VERSION); - if (!hasPluginDistributionFieldsMigration || !context.hasTable("managed_plugin_packages")) { - if (context.hasTable("managed_plugin_packages")) { - if (!context.hasColumn("managed_plugin_packages", "artifact_id")) { - database.exec("ALTER TABLE managed_plugin_packages ADD COLUMN artifact_id TEXT;"); - } - if (!context.hasColumn("managed_plugin_packages", "platform")) { - database.exec("ALTER TABLE managed_plugin_packages ADD COLUMN platform TEXT;"); - } - if (!context.hasColumn("managed_plugin_packages", "arch")) { - database.exec("ALTER TABLE managed_plugin_packages ADD COLUMN arch TEXT;"); - } - if (!context.hasColumn("managed_plugin_packages", "source_url")) { - database.exec("ALTER TABLE managed_plugin_packages ADD COLUMN source_url TEXT;"); - } - if (!context.hasColumn("managed_plugin_packages", "catalog_version")) { - database.exec("ALTER TABLE managed_plugin_packages ADD COLUMN catalog_version TEXT;"); - } - if (!context.hasColumn("managed_plugin_packages", "previous_version")) { - database.exec("ALTER TABLE managed_plugin_packages ADD COLUMN previous_version TEXT;"); - } - } - if (!hasPluginDistributionFieldsMigration) { - context.recordMigration(PLUGIN_DISTRIBUTION_FIELDS_MIGRATION_VERSION, PLUGIN_DISTRIBUTION_FIELDS_MIGRATION_NAME); - } + // Historical development profiles can already record compaction recovery at 143. + const packageColumns = new Set(database.prepare("PRAGMA table_info(managed_plugin_packages)").all().map(row => row.name)); + for (const field of PLUGIN_DISTRIBUTION_FIELDS) { + if (!packageColumns.has(field)) database.exec(`ALTER TABLE managed_plugin_packages ADD COLUMN ${field} TEXT`); + } + if (!context.hasMigration(PLUGIN_DISTRIBUTION_FIELDS_MIGRATION_VERSION)) { + context.recordMigration(PLUGIN_DISTRIBUTION_FIELDS_MIGRATION_VERSION, PLUGIN_DISTRIBUTION_FIELDS_MIGRATION_NAME); } const hasSkillAwareRunMigration = context.hasMigration(SKILL_AWARE_RUN_MIGRATION_VERSION); @@ -6145,6 +6128,23 @@ export function applySqliteRunStoreMigrations(context: SqliteRunStoreMigrationCo hasTable: context.hasTable.bind(context), recordMigration: context.recordMigration.bind(context), }); + // An archived cron definition with no runs can supply the metadata for its missing owner thread. + database.exec(` + INSERT INTO ling_threads (id, workspace_id, kind, channel_id, title, objective, status, created_at, updated_at, archived_at) + SELECT automation.thread_id, automation.workspace_id, 'automation', automation.channel_id, automation.title, + json_extract(automation.prompt_template_json, '$.promptMarkdown'), + 'archived', automation.created_at, automation.updated_at, automation.updated_at + FROM automation_definitions AS automation + WHERE automation.status = 'archived' AND automation.automation_mode = 'cron' + AND automation.target_thread_id IS NULL AND automation.last_run_id IS NULL + AND automation.thread_id <> '' + AND CASE WHEN json_valid(automation.prompt_template_json) + THEN json_type(automation.prompt_template_json, '$.promptMarkdown') = 'text' ELSE 0 END + AND NOT EXISTS (SELECT 1 FROM ling_threads WHERE id = automation.thread_id) + AND NOT EXISTS (SELECT 1 FROM automation_runs WHERE automation_id = automation.id) + AND NOT EXISTS (SELECT 1 FROM automation_definitions AS other WHERE other.thread_id = automation.thread_id AND other.id <> automation.id) + AND NOT EXISTS (SELECT 1 FROM retention_tombstones WHERE entity_type = 'conversation-thread' AND entity_id = automation.thread_id) + `); ensureHostCommandJournalIndex(database); ensureLingTurnCursorIndexes(database); applyHostOperationJournalMigration({ diff --git a/packages/core/test/sqlite-legacy-upgrade.test.ts b/packages/core/test/sqlite-legacy-upgrade.test.ts new file mode 100644 index 000000000..9c08f0893 --- /dev/null +++ b/packages/core/test/sqlite-legacy-upgrade.test.ts @@ -0,0 +1,129 @@ +import assert from "node:assert/strict"; +import { mkdtemp, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { DatabaseSync } from "node:sqlite"; +import test, { type TestContext } from "node:test"; +import { createSqliteRunStore, DEFAULT_WORKSPACE_ID } from "../dist/index.js"; +import { testDatabase } from "./support/sqlite-test-database.ts"; + +const now = "2026-10-01T00:00:00.000Z"; + +async function fixture(t: TestContext) { + const cwd = await mkdtemp(join(tmpdir(), "ling-legacy-upgrade-")); + const store = createSqliteRunStore(cwd); + t.after(async () => { + if (testDatabase(store).isOpen) store.close(); + await rm(cwd, { recursive: true, force: true }); + }); + return { cwd, store }; +} + +test("startup restores a missing archived automation thread from its definition", async t => { + const { cwd, store } = await fixture(t); + const thread = store.createLingThread({ kind: "automation", title: "Archived check", objective: "Check status" }, now); + const definition = store.createAutomationDefinition({ + threadId: thread.id, title: thread.title, kind: "custom_prompt", status: "archived", trigger: { type: "manual" }, + target: { scope: "workspace", workspaceId: DEFAULT_WORKSPACE_ID, cwd }, + promptTemplate: { templateVersion: 1, promptMarkdown: thread.objective, contextSelectors: [] }, + executionPolicy: {}, outputPolicy: { destinations: [{ type: "automation_thread" }], artifactFormat: "markdown" }, + }, now); + const database = testDatabase(store); + database.exec("PRAGMA foreign_keys=OFF"); + database.prepare("DELETE FROM ling_threads WHERE id=?").run(thread.id); + assert.equal(database.prepare("PRAGMA foreign_key_check(automation_definitions)").all().length, 1); + store.close(); + + for (let attempt = 0; attempt < 2; attempt++) { + const reopened = createSqliteRunStore(cwd); + try { + assert.deepEqual(reopened.getAutomationDefinition(definition.id), definition); + const restored = reopened.getLingThread(thread.id); + assert.equal(restored?.status, "archived"); + assert.equal(restored?.archivedAt, now); + assert.equal(restored?.kind, "automation"); + assert.equal(restored?.title, thread.title); + assert.equal(restored?.objective, thread.objective); + assert.deepEqual(testDatabase(reopened).prepare("PRAGMA foreign_key_check").all(), []); + } finally { reopened.close(); } + } +}); + +test("startup repairs missing plugin package fields even when 143 records compaction recovery", async t => { + const { cwd, store } = await fixture(t); + const database = testDatabase(store); + database.exec(` + ALTER TABLE managed_plugin_packages DROP COLUMN artifact_id; + ALTER TABLE managed_plugin_packages DROP COLUMN platform; + ALTER TABLE managed_plugin_packages DROP COLUMN source_url; + ALTER TABLE managed_plugin_packages DROP COLUMN catalog_version; + ALTER TABLE managed_plugin_packages DROP COLUMN previous_version; + UPDATE schema_migrations SET name='create_runtime_compaction_recovery_evidence' WHERE version=143; + `); + database.prepare(`INSERT INTO managed_plugin_packages (plugin_id, source_kind, version, status, cache_ref, arch, + manifest_json, installed_at, updated_at) VALUES ('official:pdf-documents','official-remote','0.1.0','installed', + 'official-remote/pdf-documents', 'arm64', '{}', ?, ?)`).run(now, now); + const marker = database.prepare("SELECT * FROM schema_migrations WHERE version=143").get(); + assert.equal(marker?.name, "create_runtime_compaction_recovery_evidence"); + store.close(); + + const reopened = createSqliteRunStore(cwd); + try { + const plugin = reopened.getManagedPluginPackage("official:pdf-documents"); + assert.equal(plugin?.status, "installed"); + assert.equal(plugin?.version, "0.1.0"); + assert.equal(plugin?.arch, "arm64"); + assert.equal(plugin?.installedAt, now); + assert.deepEqual(testDatabase(reopened).prepare("SELECT * FROM schema_migrations WHERE version=143").get(), marker); + } finally { reopened.close(); } +}); + +for (const hasHistory of [false, true]) { + test(`startup ${hasHistory ? "preserves populated legacy delegation history on refusal" : "upgrades empty 139 delegation tables and reopens"}`, async t => { + const { cwd, store } = await fixture(t); + const path = store.paths.databasePath; + const database = testDatabase(store); + const table = database.prepare("SELECT sql FROM sqlite_schema WHERE type='table' AND name=?"); + const steps = table.get("delegation_steps")?.sql; + const messages = table.get("delegation_messages")?.sql; + assert.ok(typeof steps === "string" && typeof messages === "string"); + const legacySteps = steps + .replace("idempotency_key TEXT", `consumed_token_count INTEGER NOT NULL DEFAULT 0, + consumed_cost_micros INTEGER NOT NULL DEFAULT 0, consumed_wall_time_ms INTEGER NOT NULL DEFAULT 0, + budget_settled_at TEXT, idempotency_key TEXT`) + .replace("FOREIGN KEY(root_run_id) REFERENCES run_sessions(id)", "FOREIGN KEY(root_run_id) REFERENCES delegation_roots(root_run_id)"); + database.exec(`PRAGMA foreign_keys=OFF; + DROP TABLE delegation_messages; + DROP TABLE delegation_steps; + CREATE TABLE delegation_roots (root_run_id TEXT PRIMARY KEY); + CREATE TABLE delegation_operations (id TEXT PRIMARY KEY, delegation_step_id TEXT REFERENCES delegation_steps(id)); + CREATE TABLE delegation_message_deliveries (id TEXT PRIMARY KEY, delegation_message_id TEXT REFERENCES delegation_messages(id)); + ${legacySteps}; ${messages}; + DELETE FROM schema_migrations WHERE version=154; + `); + database.prepare("INSERT INTO schema_migrations VALUES (139, 'create_delegation_tree', ?)").run(now); + if (hasHistory) database.exec("INSERT INTO delegation_roots VALUES ('retained-root')"); + store.close(); + + if (hasHistory) { + assert.throws(() => createSqliteRunStore(cwd), /populated historical development schema/u); + const legacy = new DatabaseSync(path, { readOnly: true }); + try { + assert.equal(legacy.prepare("SELECT root_run_id FROM delegation_roots").get()?.root_run_id, "retained-root"); + assert.equal(legacy.prepare("SELECT 1 FROM schema_migrations WHERE version=154").get(), undefined); + } finally { legacy.close(); } + return; + } + + for (let attempt = 0; attempt < 2; attempt++) { + const reopened = createSqliteRunStore(cwd); + try { + const migrated = testDatabase(reopened); + assert.equal(migrated.prepare("SELECT name FROM schema_migrations WHERE version=139").get()?.name, "create_delegation_tree"); + assert.equal(migrated.prepare("SELECT name FROM schema_migrations WHERE version=154").get()?.name, "create_delegation_tree_v1"); + assert.equal(migrated.prepare("SELECT 1 FROM delegation_steps LIMIT 1").get(), undefined); + assert.deepEqual(migrated.prepare("PRAGMA foreign_key_check").all(), []); + } finally { reopened.close(); } + } + }); +} diff --git a/packages/daemon/src/features/document-processing/plugin-state.ts b/packages/daemon/src/features/document-processing/plugin-state.ts index 081359a35..409e5064f 100644 --- a/packages/daemon/src/features/document-processing/plugin-state.ts +++ b/packages/daemon/src/features/document-processing/plugin-state.ts @@ -57,18 +57,16 @@ export function resolveDocumentProcessingPluginAvailability( }; } if (process.env.LING_DOCUMENT_PROCESSING_MODE === "plugin") { - const getManagedPluginPackage = store?.getManagedPluginPackage; - const packageRecord = getManagedPluginPackage?.(pluginId); - if (getManagedPluginPackage && (!packageRecord || packageRecord.status !== "installed")) { + const packageRecord = store?.getManagedPluginPackage?.(pluginId); + if (store?.getManagedPluginPackage && packageRecord?.status !== "installed") { return { enabled: false, errorCode: "document_processing_plugin_not_installed", errorMessage: `${label} document processing package is not installed for this workspace.`, }; } - const getManagedPluginHealthSnapshot = store?.getManagedPluginHealthSnapshot; - const health = getManagedPluginHealthSnapshot?.(pluginId, new Date().toISOString()); - if (getManagedPluginHealthSnapshot && health?.status !== "ready") { + const health = store?.getManagedPluginHealthSnapshot?.(pluginId, new Date().toISOString()); + if (store?.getManagedPluginHealthSnapshot && health?.status !== "ready") { const errorCode = health?.status === "failed" || health?.status === "expired" ? documentProcessingHealthErrorCode(health.details) : "document_processing_plugin_health_unknown"; @@ -78,7 +76,7 @@ export function resolveDocumentProcessingPluginAvailability( errorMessage: health?.message ?? `${label} document processing runtime health has not been verified.`, }; } - if (getManagedPluginHealthSnapshot && packageRecord && usesHostPluginCache(packageRecord.cacheRef)) { + if (store?.getManagedPluginHealthSnapshot && packageRecord && usesHostPluginCache(packageRecord.cacheRef)) { const selectionError = resolveHostSelectionError(pluginId, packageRecord, health); if (selectionError) return { enabled: false, ...selectionError }; } diff --git a/packages/daemon/src/features/document-processing/runtime-client.ts b/packages/daemon/src/features/document-processing/runtime-client.ts index c12cb456d..0c4307eb3 100644 --- a/packages/daemon/src/features/document-processing/runtime-client.ts +++ b/packages/daemon/src/features/document-processing/runtime-client.ts @@ -300,8 +300,9 @@ class PluginProcess { constructor(pluginId: string, executablePath: string, version: string) { this.pluginId = pluginId; - const command = executablePath.endsWith(".mjs") ? process.execPath : executablePath; - const args = executablePath.endsWith(".mjs") ? [executablePath] : []; + const nodeWorker = executablePath.endsWith(".mjs"); + const command = nodeWorker ? process.execPath : executablePath; + const args = nodeWorker ? [executablePath] : []; const env: NodeJS.ProcessEnv = {}; for (const key of CHILD_ENV_KEYS) { const value = process.env[key]; @@ -309,6 +310,7 @@ class PluginProcess { } this.child = spawn(command, args, { stdio: ["pipe", "pipe", "pipe"], env: { ...env, + ...(nodeWorker && process.versions.electron ? { ELECTRON_RUN_AS_NODE: "1" } : {}), LING_DOCUMENT_PROCESSING_PLUGIN: "1", LING_DOCUMENT_PROCESSING_PLUGIN_ID: pluginId, LING_DOCUMENT_PROCESSING_PLUGIN_VERSION: version, diff --git a/packages/daemon/src/features/providers/startup-refresh.ts b/packages/daemon/src/features/providers/startup-refresh.ts index b729e0378..5bc4f78e7 100644 --- a/packages/daemon/src/features/providers/startup-refresh.ts +++ b/packages/daemon/src/features/providers/startup-refresh.ts @@ -20,7 +20,7 @@ export class ProviderStartupRefreshService { private readonly refreshesByCwd = new Map>(); private readonly refreshGenerationsByCwd = new Map(); private readonly inFlight = new Set>(); - private stopped = false; + private readonly shutdownController = new AbortController(); constructor( private readonly dependencies: { @@ -31,7 +31,8 @@ export class ProviderStartupRefreshService { ) {} start(cwd: string, store: ProviderStartupRefreshStore, options: { readonly force?: boolean } = {}): Promise { - if (this.stopped) return Promise.resolve([]); + const signal = this.shutdownController.signal; + if (signal.aborted) return Promise.resolve([]); const existing = this.refreshesByCwd.get(cwd); if (existing && !options.force) { return existing; @@ -39,7 +40,7 @@ export class ProviderStartupRefreshService { const generation = (this.refreshGenerationsByCwd.get(cwd) ?? 0) + 1; if (!Number.isSafeInteger(generation)) throw new Error("Provider startup refresh generation exhausted."); this.refreshGenerationsByCwd.set(cwd, generation); - const isCurrent = (): boolean => !this.stopped && this.refreshGenerationsByCwd.get(cwd) === generation; + const isCurrent = (): boolean => !signal.aborted && this.refreshGenerationsByCwd.get(cwd) === generation; this.markWarming(cwd); const refresh = refreshProvidersOnStartup({ cwd, @@ -47,6 +48,7 @@ export class ProviderStartupRefreshService { secretResolver: this.dependencies.secretResolver, controlPlaneEvents: this.dependencies.controlPlaneEvents, isCurrent, + signal, }) .then((results) => { if (isCurrent()) this.markFinished(cwd, store); @@ -63,7 +65,7 @@ export class ProviderStartupRefreshService { return refresh; } - beginShutdown(): void { this.stopped = true; } + beginShutdown(): void { this.shutdownController.abort(); } async waitForIdle(): Promise { while (this.inFlight.size) await Promise.allSettled([...this.inFlight]); } @@ -128,19 +130,21 @@ export async function refreshProvidersOnStartup(input: { readonly controlPlaneEvents: ControlPlaneEventHub; /** A superseded workspace refresh must not admit its remaining candidates. */ readonly isCurrent?: () => boolean; + readonly signal?: AbortSignal; }): Promise { const candidates = input.store .listProviderPresets() .filter((provider) => shouldRefreshProviderOnStartup(input.store, provider, input.secretResolver)); const results: ProviderCheckResult[] = []; for (const provider of candidates) { - if (input.isCurrent && !input.isCurrent()) break; + if (input.signal?.aborted || (input.isCurrent && !input.isCurrent())) break; const current = input.store.getProviderPreset(provider.id); if (!current || !shouldRefreshProviderOnStartup(input.store, current, input.secretResolver)) continue; const admission = input.store.beginProviderCheckRequest(provider.id, "startup"); if (!admission) continue; - const result = withStartupRefreshMessage(await checkProviderPreset(input.store, admission.provider, input.secretResolver)); - const publication = publishProviderCheckResult(input.store, input.controlPlaneEvents, admission.ticket, result, input.cwd); + const result = await checkProviderPreset(input.store, admission.provider, input.secretResolver, { signal: input.signal }); + if (input.signal?.aborted) break; + const publication = publishProviderCheckResult(input.store, input.controlPlaneEvents, admission.ticket, withStartupRefreshMessage(result), input.cwd); if (publication.status === "published" && publication.provider.lastCheck) results.push(publication.provider.lastCheck); } return results; diff --git a/packages/daemon/test/document-processing-plugin-state.test.ts b/packages/daemon/test/document-processing-plugin-state.test.ts index b54870252..05fe0e09b 100644 --- a/packages/daemon/test/document-processing-plugin-state.test.ts +++ b/packages/daemon/test/document-processing-plugin-state.test.ts @@ -24,6 +24,28 @@ function withPluginMode(t: TestContext): void { }); } +test("document processing availability reads package and health from the owning store", (t) => { + withPluginMode(t); + const store = { + enabledPluginId: pluginId, + getManagedPlugin(id: string) { + return id === this.enabledPluginId ? { enabled: true } as never : undefined; + }, + getManagedPluginPackage(id: string) { + return id === this.enabledPluginId ? { status: "installed" } as never : undefined; + }, + getManagedPluginHealthSnapshot(id: string) { + return id === this.enabledPluginId ? { status: "ready" } as never : undefined; + }, + }; + + assert.deepEqual(resolveDocumentProcessingPluginAvailability(store, "office"), { + enabled: true, + pluginId, + runtimeMode: "plugin", + }); +}); + test("document processing availability rejects an installed plugin with failed health", (t) => { withPluginMode(t); const availability = resolveDocumentProcessingPluginAvailability({ diff --git a/packages/daemon/test/plugin-native-runtime.test.ts b/packages/daemon/test/plugin-native-runtime.test.ts index 1532a09c2..cbb1313dd 100644 --- a/packages/daemon/test/plugin-native-runtime.test.ts +++ b/packages/daemon/test/plugin-native-runtime.test.ts @@ -475,6 +475,7 @@ async function createArtifact(key: KeyObject, version: string, payload: string, }); const files = { [manifestPath]: manifest, [executable]: payload, + "runtime/node_modules/@napi-rs/canvas/package.json": "{}", "mcp-server.json": id === pluginId ? "{}" : JSON.stringify({ transport: { type: "streamable-http", url: "http://127.0.0.1:1/" } }), }; const checksums = Buffer.from(JSON.stringify({ diff --git a/packages/daemon/test/provider-startup-shutdown.test.ts b/packages/daemon/test/provider-startup-shutdown.test.ts new file mode 100644 index 000000000..966fe4b49 --- /dev/null +++ b/packages/daemon/test/provider-startup-shutdown.test.ts @@ -0,0 +1,57 @@ +import assert from "node:assert/strict"; +import { once } from "node:events"; +import { mkdtemp, rm } from "node:fs/promises"; +import { createServer, type ServerResponse } from "node:http"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { test } from "node:test"; +import { setTimeout } from "node:timers/promises"; +import { createSqliteRunStore, resolveStoragePaths, type SecretResolver } from "@ling-stack/core"; +import { ControlPlaneEventHub } from "../dist/features/control-plane/events.js"; +import { ProviderStartupRefreshService } from "../dist/features/providers/startup-refresh.js"; + +test("provider startup shutdown disconnects an in-flight check without publishing a failure", { timeout: 10_000 }, async t => { + const cwd = await mkdtemp(join(tmpdir(), "ling-provider-startup-shutdown-")); + t.after(() => rm(cwd, { recursive: true, force: true })); + const paths = resolveStoragePaths(cwd, { userRootDir: join(cwd, "home"), workspaceStateLocation: "user-data-dir", env: {} }); + const store = createSqliteRunStore(cwd, paths.workspace); + const modelServer = createServer(); + const secretResolver: SecretResolver = { + status: ref => ({ ref, kind: "env", configured: false, errorCode: "secret_missing" }), + resolve: ref => ({ ref, configured: false }), + }; + const service = new ProviderStartupRefreshService({ secretResolver, controlPlaneEvents: new ControlPlaneEventHub() }); + let refresh: ReturnType | undefined; + + try { + modelServer.listen(0, "127.0.0.1"); + await once(modelServer, "listening", { signal: t.signal }); + const address = modelServer.address(); + assert.ok(address && typeof address === "object"); + const provider = store.createProviderPreset({ + kind: "openai-compatible", displayName: "Startup check fixture", providerId: "startup-fixture", + model: "fixture-model", api: "openai-completions", baseUrl: `http://127.0.0.1:${address.port}`, + authHeader: false, capabilities: ["chat"], enabled: true, + }, new Date().toISOString()); + const accepted = once(modelServer, "request", { signal: t.signal }); + refresh = service.start(cwd, store); + const [, response] = await accepted as [unknown, ServerResponse]; + const disconnected = once(response, "close", { signal: t.signal }); + + service.beginShutdown(); + const drained = await Promise.race([ + Promise.all([disconnected, service.waitForIdle()]).then(() => true), + setTimeout(2_000, false, { ref: false }), + ]); + + assert.equal(drained, true, "shutdown must close the request within Desktop's stop window"); + assert.deepEqual(await refresh, []); + assert.equal(store.getProviderPreset(provider.id)?.lastCheck, undefined); + } finally { + const closed = new Promise((resolve, reject) => modelServer.close(error => error ? reject(error) : resolve())); + modelServer.closeAllConnections(); + await refresh; + store.close(); + await closed; + } +}); diff --git a/scripts/ci/daemon-test-platforms.json b/scripts/ci/daemon-test-platforms.json index 5aed5970b..62a7ad87b 100644 --- a/scripts/ci/daemon-test-platforms.json +++ b/scripts/ci/daemon-test-platforms.json @@ -362,6 +362,7 @@ "test/provider-runtime-invocations.test.mjs", "test/provider-runtime-observation-scope.test.mjs", "test/provider-runtime-orchestrator.test.mjs", + "test/provider-startup-shutdown.test.ts", "test/providers-api.test.mjs", "test/providers-model-metadata.test.mjs", "test/providers-model-pagination.test.mjs",