Orkas is an open-source (MIT), local-first AI team for your desktop: a Commander turns your goal into to-dos and coordinates 16 built-in specialist agents plus Claude Code, Codex, OpenCode, OpenClaw and Hermes, with projects, scheduled automations and connectors. Free app for macOS & Windows; built-in models or your own keys.
JavaScript agent-collaborationagent-harnessagent-orchestrationagent-teamagent-workflowai-assistantai-automationai-employeeai-productivityai-teamai-workflowautonomous-agentsclaude-code-guiclaude-coworkdesktop-agentlocal-firstmulti-agentmulti-agent-systemself-evolving-agentstask-automation
feat: add Orkas official API setup
BlueSkyID66685903b23fd52
diff --git a/run.cmd b/run.cmdindex 73f121e2..6b21d3f1 100644--- a/run.cmd+++ b/run.cmd@@ -1,7 +1,7 @@@echo offREM Windows counterpart of run.sh. An in-app relaunch waits for its exact-REM owner process; it never terminates every electron.exe process because-REM other tasks can share the same bundled runtime.+REM owner process. A direct launch closes only the previous source instance+REM owned by this checkout.setlocal EnableExtensions EnableDelayedExpansionset "APP_DIR=%~dp0"if "%APP_DIR:~-1%"=="\" set "APP_DIR=%APP_DIR:~0,-1%"@@ -39,6 +39,9 @@ if defined ORKAS_RELAUNCH_OWNER_PID (set "ORKAS_RELAUNCH_OWNER_PID=")+call node "%APP_DIR%\scripts\stop-source-instance.cjs" --root "%APP_DIR%"+if errorlevel 1 exit /b 1+call node "%APP_DIR%\scripts\ensure-deps.cjs"if errorlevel 1 exit /b 1call node "%APP_DIR%\scripts\ensure-dev-dependencies.cjs"diff --git a/run.sh b/run.shindex 52d6e93d..80960da7 100755--- a/run.sh+++ b/run.sh@@ -1,9 +1,8 @@#!/bin/bash-# Orkas PC launcher. Lives under PC/; the script's own directory is the PC root.-# Behavior: an in-app relaunch waits for its exact owner process to exit, then-# starts a new instance in the foreground. It never kills Electron processes-# by image name or install-directory prefix because other tasks can share the-# same bundled runtime.+# Open-source Orkas launcher. The script's own directory is the checkout root.+# Behavior: an in-app relaunch waits for its exact owner process to exit. A+# direct launch closes only the previous source instance owned by this checkout,+# then starts a new instance in the foreground.## Usage:# ./run.sh@@ -14,7 +13,7 @@ set -eAPP_DIR="$(cd "$(dirname "$0")" && pwd)"if [ ! -f "$APP_DIR/package.json" ]; then- echo "[Orkas] $APP_DIR/package.json not found; check the PC/ directory layout." >&2+ echo "[Orkas] $APP_DIR/package.json not found; check the source directory layout." >&2exit 1fi@@ -74,6 +73,8 @@ if ! command -v node >/dev/null 2>&1; thenexit 1fi+node "$APP_DIR/scripts/stop-source-instance.cjs" --root "$APP_DIR"+if [ "$(uname -s)" = "Linux" ]; thennode "$APP_DIR/scripts/verify-linux-source-dependencies.cjs" --host-onlyfidiff --git a/scripts/stop-source-instance.cjs b/scripts/stop-source-instance.cjsnew file mode 100644index 00000000..c8c496bd--- /dev/null+++ b/scripts/stop-source-instance.cjs@@ -0,0 +1,205 @@+#!/usr/bin/env node+'use strict';++const { execFileSync } = require('node:child_process');+const path = require('node:path');++const GRACEFUL_TIMEOUT_MS = 4_000;+const POLL_INTERVAL_MS = 100;++function pathApiFor(platform) {+ return platform === 'win32' ? path.win32 : path.posix;+}++function normalizePath(value, platform) {+ const pathApi = pathApiFor(platform);+ const normalized = pathApi.normalize(String(value || '').trim());+ const withoutTrailingSeparators = normalized.replace(/[\\/]+$/, '');+ return platform === 'win32'+ ? withoutTrailingSeparators.toLowerCase()+ : withoutTrailingSeparators;+}++function tokenizeCommandLine(commandLine) {+ const tokens = [];+ const pattern = /"([^"]*)"|'([^']*)'|([^\s]+)/g;+ let match;+ while ((match = pattern.exec(String(commandLine || ''))) !== null) {+ tokens.push(match[1] ?? match[2] ?? match[3]);+ }+ return tokens;+}++function isBundledElectronExecutable(executablePath, appRoot, platform) {+ const pathApi = pathApiFor(platform);+ const normalizedExecutable = normalizePath(executablePath, platform);+ const electronDist = normalizePath(+ pathApi.join(appRoot, 'node_modules', 'electron', 'dist'),+ platform,+ );+ const relative = pathApi.relative(electronDist, normalizedExecutable);+ if (!relative || relative.startsWith('..') || pathApi.isAbsolute(relative)) return false;++ if (platform === 'win32') return relative.toLowerCase() === 'electron.exe';+ if (platform === 'linux') return relative === 'electron';+ if (platform === 'darwin') {+ return /^[^/]+\.app\/Contents\/MacOS\/Electron$/.test(relative);+ }+ return false;+}++function isAppRootArgument(argument, appRoot, platform) {+ const value = String(argument || '').replace(/^--app(?:-path)?=/, '');+ if (value === '.') return true;+ if (!value || value.startsWith('-')) return false;+ return normalizePath(value, platform) === normalizePath(appRoot, platform);+}++function isSourceMainProcess(processInfo, appRoot, platform = process.platform) {+ const pid = Number(processInfo?.pid);+ if (!Number.isSafeInteger(pid) || pid <= 0) return false;++ const commandLine = String(processInfo?.commandLine || '');+ if (!commandLine || /(?:^|\s)--type=/.test(commandLine)) return false;++ const tokens = tokenizeCommandLine(commandLine);+ const executablePath = processInfo?.executablePath || tokens[0];+ if (!isBundledElectronExecutable(executablePath, appRoot, platform)) return false;++ return tokens.slice(1).some((argument) => (+ isAppRootArgument(argument, appRoot, platform)+ ));+}++function parsePosixProcessList(output) {+ return String(output || '')+ .split(/\r?\n/)+ .map((line) => line.match(/^\s*(\d+)\s+(\d+)\s+(.+)$/))+ .filter(Boolean)+ .map((match) => ({+ pid: Number(match[1]),+ parentPid: Number(match[2]),+ commandLine: match[3],+ }));+}++function listProcesses(platform = process.platform) {+ if (platform === 'win32') {+ const script = [+ "$ErrorActionPreference = 'Stop';",+ 'Get-CimInstance Win32_Process',+ '| Select-Object ProcessId, ParentProcessId, ExecutablePath, CommandLine',+ '| ConvertTo-Json -Compress',+ ].join(' ');+ const output = execFileSync('powershell.exe', [+ '-NoLogo',+ '-NoProfile',+ '-NonInteractive',+ '-ExecutionPolicy',+ 'Bypass',+ '-Command',+ script,+ ], { encoding: 'utf8', windowsHide: true, maxBuffer: 16 * 1024 * 1024 });+ const decoded = JSON.parse(output || '[]');+ return (Array.isArray(decoded) ? decoded : [decoded]).map((entry) => ({+ pid: Number(entry.ProcessId),+ parentPid: Number(entry.ParentProcessId),+ executablePath: entry.ExecutablePath || '',+ commandLine: entry.CommandLine || '',+ }));+ }++ const output = execFileSync('ps', ['-axo', 'pid=,ppid=,command='], {+ encoding: 'utf8',+ maxBuffer: 16 * 1024 * 1024,+ });+ return parsePosixProcessList(output);+}++function sleep(milliseconds) {+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, milliseconds);+}++function stillMatches(pid, appRoot, platform) {+ return listProcesses(platform).some((entry) => (+ entry.pid === pid && isSourceMainProcess(entry, appRoot, platform)+ ));+}++function stopWindowsProcessTree(pid, appRoot) {+ try {+ execFileSync('taskkill.exe', ['/PID', String(pid), '/T', '/F'], {+ encoding: 'utf8',+ windowsHide: true,+ stdio: 'ignore',+ });+ } catch (error) {+ // The app can finish naturally between the final identity check and+ // taskkill. Treat that race as success; surface every other failure.+ if (!stillMatches(pid, appRoot, 'win32')) return;+ throw error;+ }+}++function stopPosixProcess(pid, appRoot, platform) {+ try {+ process.kill(pid, 'SIGTERM');+ } catch (error) {+ if (error?.code === 'ESRCH') return;+ throw error;+ }++ const deadline = Date.now() + GRACEFUL_TIMEOUT_MS;+ while (Date.now() < deadline) {+ if (!stillMatches(pid, appRoot, platform)) return;+ sleep(POLL_INTERVAL_MS);+ }++ // Revalidate the PID immediately before escalation so a recycled PID can+ // never cause an unrelated process to be terminated.+ if (stillMatches(pid, appRoot, platform)) process.kill(pid, 'SIGKILL');+}++function stopSourceInstances(appRoot, platform = process.platform) {+ const matches = listProcesses(platform).filter((entry) => (+ entry.pid !== process.pid+ && entry.pid !== process.ppid+ && isSourceMainProcess(entry, appRoot, platform)+ ));+ if (matches.length === 0) return [];++ const pids = matches.map((entry) => entry.pid);+ console.log(`[Orkas] Closing previous source instance${pids.length > 1 ? 's' : ''} (PID ${pids.join(', ')})...`);+ for (const { pid } of matches) {+ if (platform === 'win32') {+ if (stillMatches(pid, appRoot, platform)) stopWindowsProcessTree(pid, appRoot);+ } else {+ stopPosixProcess(pid, appRoot, platform);+ }+ }+ return pids;+}++function readAppRoot(argv) {+ const rootIndex = argv.indexOf('--root');+ if (rootIndex < 0 || !argv[rootIndex + 1]) {+ throw new Error('Usage: stop-source-instance.cjs --root <Orkas source directory>');+ }+ return path.resolve(argv[rootIndex + 1]);+}++if (require.main === module) {+ try {+ stopSourceInstances(readAppRoot(process.argv.slice(2)));+ } catch (error) {+ console.error(`[Orkas] Failed to close the previous source instance: ${error?.message || error}`);+ process.exitCode = 1;+ }+}++module.exports = {+ isSourceMainProcess,+ parsePosixProcessList,+ stopSourceInstances,+ tokenizeCommandLine,+};diff --git a/src/main/features/auth.ts b/src/main/features/auth.tsindex cbca1696..6e6a422c 100644--- a/src/main/features/auth.ts+++ b/src/main/features/auth.ts@@ -94,6 +94,15 @@ import type { KeyFailureKind } from '../model/core-agent/auth-error';import { createLogger } from '../logger';import { t } from '../i18n';import { sanitizeLogTextForUpload } from '../util/log-sanitize';+import {+ ORKAS_API_BASE_URL,+ ORKAS_API_DEFAULT_VOICE,+ ORKAS_API_IMAGE_MODEL,+ ORKAS_API_LLM_MODELS,+ ORKAS_API_PROVIDER,+ ORKAS_API_TTS_MODEL,+ ORKAS_API_VIDEO_MODEL,+} from './orkas_api';const log = createLogger('auth');@@ -437,6 +446,7 @@ function parseImageProfilesArray(arr: unknown): ImageProfile[] {out.push({id: String(p.id),provider: String(p.provider),+ ...(p.model ? { model: String(p.model) } : {}),apiKey: String(p.apiKey),label: String(p.label || 'default'),createdAt: typeof p.createdAt === 'number' ? p.createdAt : Date.now(),@@ -537,6 +547,133 @@ export function saveTtsProfiles(list: TtsProfile[]): void {saveProfiles(store);}+function nextOrkasServiceProfileId(prefix: 's' | 'img' | 'vid' | 'tts'): string {+ return `${prefix}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;+}++function updateOrAppendOrkasServiceProfile<T extends { provider: string; apiKey: string }>(+ list: T[],+ create: () => T,+ update: (profile: T) => T,+): T[] {+ let found = false;+ const updated = list.map((profile) => {+ if (profile.provider !== ORKAS_API_PROVIDER) return profile;+ found = true;+ return update(profile);+ });+ if (!found) updated.push(create());+ return updated;+}++/** Configure every public Orkas API surface using the same user-supplied key.+ * The data remains in the existing five profile collections; this function+ * only batches their normal auth-profiles.json write. Existing provider order+ * is preserved, and newly-created Orkas rows are appended as fallbacks. */+export function configureAllOrkasApiServices(rawApiKey: string): { configured: true } {+ const apiKey = String(rawApiKey || '').trim();+ if (!apiKey) throw new Error('api key required');++ const store = loadProfiles();+ const now = Date.now();+ const existingProfileEntries = Object.entries(store.profiles)+ .filter(([, profile]) => profile.provider === ORKAS_API_PROVIDER);+ let chatProfileId = existingProfileEntries[0]?.[0] || '';++ for (const [profileId, profile] of existingProfileEntries) {+ if (profile.type !== 'api_key') continue;+ store.profiles[profileId] = { ...profile, key: apiKey, lastUsed: 0 };+ }+ if (!chatProfileId || store.profiles[chatProfileId]?.type !== 'api_key') {+ chatProfileId = makeProfileId(ORKAS_API_PROVIDER, 'default');+ const existing = store.profiles[chatProfileId];+ store.profiles[chatProfileId] = {+ type: 'api_key',+ provider: ORKAS_API_PROVIDER,+ label: 'default',+ key: apiKey,+ createdAt: existing?.createdAt ?? now,+ lastUsed: 0,+ };+ }+ for (const model of ORKAS_API_LLM_MODELS) {+ if (store.entries.some((entry) => (+ entry.provider === ORKAS_API_PROVIDER+ && entry.model === model.id+ ))) continue;+ store.entries.push({+ entryId: nextEntryId(),+ provider: ORKAS_API_PROVIDER,+ model: model.id,+ profileId: chatProfileId,+ lastUsed: 0,+ createdAt: now,+ });+ }++ store.searchProfiles = updateOrAppendOrkasServiceProfile(+ store.searchProfiles || [],+ () => ({+ id: nextOrkasServiceProfileId('s'),+ provider: ORKAS_API_PROVIDER,+ apiKey,+ label: 'Orkas',+ createdAt: now,+ }),+ (profile) => ({ ...profile, apiKey }),+ );+ store.imageProfiles = updateOrAppendOrkasServiceProfile(+ store.imageProfiles || [],+ () => ({+ id: nextOrkasServiceProfileId('img'),+ provider: ORKAS_API_PROVIDER,+ model: ORKAS_API_IMAGE_MODEL,+ apiKey,+ label: 'Orkas',+ createdAt: now,+ }),+ (profile) => ({ ...profile, model: ORKAS_API_IMAGE_MODEL, apiKey }),+ );+ store.videoProfiles = updateOrAppendOrkasServiceProfile(+ store.videoProfiles || [],+ () => ({+ id: nextOrkasServiceProfileId('vid'),+ provider: ORKAS_API_PROVIDER,+ model: ORKAS_API_VIDEO_MODEL,+ apiKey,+ label: 'Orkas',+ createdAt: now,+ }),+ (profile) => ({ ...profile, model: ORKAS_API_VIDEO_MODEL, apiKey }),+ );+ store.ttsProfiles = updateOrAppendOrkasServiceProfile(+ store.ttsProfiles || [],+ () => ({+ id: nextOrkasServiceProfileId('tts'),+ provider: ORKAS_API_PROVIDER,+ baseUrl: ORKAS_API_BASE_URL,+ model: ORKAS_API_TTS_MODEL,+ apiKey,+ voice: ORKAS_API_DEFAULT_VOICE,+ format: 'mp3',+ label: 'Orkas',+ createdAt: now,+ }),+ (profile) => ({+ ...profile,+ baseUrl: ORKAS_API_BASE_URL,+ model: ORKAS_API_TTS_MODEL,+ apiKey,+ }),+ );++ saveProfiles(store);+ for (const [profileId] of existingProfileEntries) clearCooldown(profileId);+ clearCooldown(chatProfileId);+ invalidateCoreAgentRunner();+ return { configured: true };+}+function saveProfiles(store: ProfilesFile): void {ensureAuthDir();const json = JSON.stringify(store, null, 2);@@ -1210,6 +1347,9 @@ export interface EntryView {modelName: string;modelEditable: boolean;modelAvailable: boolean;+ includedModels: string[];+ official?: boolean;+ recommended?: boolean;profileId: string;profileAvailable: boolean;profileLabel: string;@@ -1227,6 +1367,7 @@ function entryToView(runtimeResolvable = true,): EntryView {const prof = store.profiles[e.profileId];+ const catalogModel = curatedModelsFor(e.provider).find((model) => model.id === e.model);const base = {entryId: e.entryId,provider: e.provider,@@ -1234,11 +1375,16 @@ function entryToView(providerLabelKey: providerLabelKey(e.provider),model: e.model,modelName: modelNameLookup(e.provider, e.model),- modelEditable: !providerUsesCustomOpenAIConfig(e.provider),+ modelEditable: e.provider !== ORKAS_API_PROVIDER && !providerUsesCustomOpenAIConfig(e.provider),modelAvailable: isSelectableModel(e.provider, e.model) && runtimeResolvable,+ includedModels: catalogModel?.includedModels ? [...catalogModel.includedModels] : [],+ ...(e.provider === ORKAS_API_PROVIDER && catalogModel ? { official: true } : {}),+ ...(catalogModel?.recommended ? { recommended: true } : {}),profileId: e.profileId,profileAvailable: !!prof,- profileLabel: prof?.label || e.profileId.split(':').slice(1).join(':') || '(missing)',+ profileLabel: e.provider === ORKAS_API_PROVIDER+ ? 'Orkas'+ : (prof?.label || e.profileId.split(':').slice(1).join(':') || '(missing)'),profileType: (prof?.type as 'api_key' | 'oauth') || 'api_key',createdAt: e.createdAt,lastUsed: e.lastUsed,@@ -1292,6 +1438,13 @@ export async function listEntries(};}+/** Composer model list for the open-source build. Every visible row is a+ * locally configured, runtime-selectable entry, so it shares the same filter+ * as the normal rotation list returned by listEntries(). */+export async function listComposerEntries(): Promise<{ entries: EntryView[] }> {+ return listEntries();+}+export async function addEntry({provider,model,@@ -2031,6 +2184,8 @@ export async function testConnection(let probeModel = modelForTest;if (pid === 'moonshot') {provider = await ext.createMoonshotProvider({ apiKey, modelId: probeModel });+ } else if (pid === ORKAS_API_PROVIDER) {+ provider = await ext.createOrkasApiProvider({ apiKey, modelId: probeModel });} else if (pid === 'deepseek') {provider = await ext.createDeepSeekProvider({ apiKey, modelId: probeModel });} else if (pid === 'doubao') {diff --git a/src/main/features/image_auth.ts b/src/main/features/image_auth.tsindex 26a84ecc..f1c69f2e 100644--- a/src/main/features/image_auth.ts+++ b/src/main/features/image_auth.ts@@ -25,10 +25,12 @@ import {callDoubaoImage,callGeminiImage,callOpenAIImage,+ callOrkasImage,isImageProviderModelAllowed,} from './image_gen';import { createLogger } from '../logger';import { logErrorSummary } from '../util/log-redact';+import { ORKAS_API_KEYS_URL } from './orkas_api';const log = createLogger('image-auth');@@ -145,6 +147,7 @@ export interface ImageProviderPickerOption {export function listImageProviderOptions(): Array<{ id: string; label: string; docs?: string }> {return [+ { id: 'orkas-api', label: 'Orkas · Image', docs: ORKAS_API_KEYS_URL },{ id: 'openai', label: 'OpenAI', docs: 'https://platform.openai.com/api-keys' },{ id: 'google', label: 'Google', docs: 'https://aistudio.google.com/app/apikey' },{@@ -206,6 +209,7 @@ export async function testImageProfile(id: string): Promise<TestImageProfileResuif (cap.api === 'openai') await callOpenAIImage(req);else if (cap.api === 'gemini') await callGeminiImage(req);else if (cap.api === 'doubao') await callDoubaoImage(req);+ else if (cap.api === 'orkas') await callOrkasImage(req);else throw new Error(`unknown image-gen api: ${cap.api}`);return { ok: true, durationMs: Date.now() - t0, provider: target.provider, model };} catch (err) {diff --git a/src/main/features/image_gen.ts b/src/main/features/image_gen.tsindex 443b4cd6..19f1d803 100644--- a/src/main/features/image_gen.ts+++ b/src/main/features/image_gen.ts@@ -27,6 +27,14 @@ import { listApiKeyEntries, loadImageProfiles, type ApiKeyEntryChoice } from './import { findImageGenCapability, type ImageGenCapability } from '../model/provider_catalog';import { createLogger } from '../logger';import { t } from '../i18n';+import { composeAbortSignal, fetchWithTimeout, throwIfAborted } from '../util/abort';+import { downloadBinaryWithProxyPolicy } from '../util/proxy-dispatcher';+import {+ ORKAS_API_BASE_URL,+ ORKAS_API_PROVIDER,+ orkasApiUsageHeaders,+ type OrkasApiUsageContext,+} from './orkas_api';const log = createLogger('image-gen');@@ -97,6 +105,8 @@ export interface GenerateImageInput {referenceImagePaths?: string[];/** Provider-side size hint. Default `1024x1024`. */size?: string;+ signal?: AbortSignal;+ usageContext?: OrkasApiUsageContext;}export type GenerateImageResult =@@ -165,6 +175,8 @@ export async function generateImage(input: GenerateImageInput): Promise<Generatemodel: capability.model,prompt: input.prompt,size,+ ...(input.signal ? { signal: input.signal } : {}),+ ...(input.usageContext ? { usageContext: input.usageContext } : {}),...(referenceBuffers ? { referenceImages: referenceBuffers } : {}),};@@ -176,6 +188,8 @@ export async function generateImage(input: GenerateImageInput): Promise<GenerateadapterRes = await callGeminiImage(adapterReq);} else if (capability.api === 'doubao') {adapterRes = await callDoubaoImage(adapterReq);+ } else if (capability.api === 'orkas') {+ adapterRes = await callOrkasImage(adapterReq);} else {return {ok: false,@@ -228,6 +242,8 @@ export interface AdapterRequest {prompt: string;size: string;referenceImages?: Buffer[];+ signal?: AbortSignal;+ usageContext?: OrkasApiUsageContext;}export interface AdapterResult {@@ -240,6 +256,9 @@ export interface AdapterResult {}export const IMAGE_MODELS_BY_PROVIDER: Readonly<Record<string, Array<{ id: string; name: string }>>> = {+ [ORKAS_API_PROVIDER]: [+ { id: 'orkas-image', name: 'Image' },+ ],openai: [{ id: 'gpt-image-2', name: 'GPT Image 2' },],@@ -262,6 +281,148 @@ const OPENAI_BASE = 'https://api.openai.com';const GEMINI_BASE = 'https://generativelanguage.googleapis.com';const DOUBAO_BASE = 'https://ark.cn-beijing.volces.com';+const ORKAS_IMAGE_CREATE_TIMEOUT_MS = 60_000;+const ORKAS_IMAGE_POLL_TIMEOUT_MS = 20_000;+const ORKAS_IMAGE_TOTAL_TIMEOUT_MS = 15 * 60_000;+const ORKAS_IMAGE_DOWNLOAD_TIMEOUT_MS = 10 * 60_000;++async function readOrkasImageResponse(resp: Response, phase: string): Promise<any> {+ const text = await resp.text();+ let data: any = {};+ try { data = text ? JSON.parse(text) : {}; } catch { /* handled below */ }+ if (!resp.ok) {+ const message = data?.error?.message || text || `request failed with HTTP ${resp.status}`;+ throw new Error(`Orkas Image ${phase} ${resp.status}: ${truncate(String(message), 500)}`);+ }+ return data;+}++function orkasImageDataUrl(buffer: Buffer): string {+ const mime = detectMimeType(buffer) || 'image/png';+ return `data:${mime};base64,${buffer.toString('base64')}`;+}++async function waitForOrkasImageTask(+ taskId: string,+ apiKey: string,+ signal: AbortSignal,+ usageContext?: OrkasApiUsageContext,+): Promise<any> {+ let data: any = {};+ while (!signal.aborted) {+ await sleepWithSignal(3_000, signal);+ const resp = await fetchWithTimeout(+ `${ORKAS_API_BASE_URL}/images/generations/${encodeURIComponent(taskId)}`,+ {+ method: 'GET',+ headers: {+ Authorization: `Bearer ${apiKey}`,+ ...orkasApiUsageHeaders(usageContext),+ },+ },+ ORKAS_IMAGE_POLL_TIMEOUT_MS,+ signal,+ 'Orkas Image status request timed out',+ );+ data = await readOrkasImageResponse(resp, 'status');+ const status = String(data?.status || '').toLowerCase();+ if (['failed', 'cancelled', 'canceled'].includes(status)) {+ throw new Error(`Orkas Image task ${taskId} ${status}: ${truncate(JSON.stringify(data?.error || data), 500)}`);+ }+ if (status === 'succeeded' || data?.data?.[0]?.url || data?.data?.[0]?.b64_json) return data;+ }+ throw new Error('operation aborted');+}++function sleepWithSignal(ms: number, signal: AbortSignal): Promise<void> {+ return new Promise((resolve, reject) => {+ const onAbort = () => {+ clearTimeout(timer);+ reject(new Error('operation aborted'));+ };+ const timer = setTimeout(() => {+ signal.removeEventListener('abort', onAbort);+ resolve();+ }, ms);+ signal.addEventListener('abort', onAbort, { once: true });+ if (signal.aborted) onAbort();+ });+}++export async function callOrkasImage(req: AdapterRequest): Promise<AdapterResult> {+ throwIfAborted(req.signal);+ const overall = composeAbortSignal(+ req.signal,+ ORKAS_IMAGE_TOTAL_TIMEOUT_MS,+ `Orkas Image timed out after ${Math.round(ORKAS_IMAGE_TOTAL_TIMEOUT_MS / 60_000)} minutes`,+ );+ try {+ const response = await fetchWithTimeout(+ `${ORKAS_API_BASE_URL}/images/generations`,+ {+ method: 'POST',+ headers: {+ Authorization: `Bearer ${req.apiKey}`,+ 'Content-Type': 'application/json',+ ...orkasApiUsageHeaders(req.usageContext),+ },+ body: JSON.stringify({+ prompt: req.prompt,+ size: req.size === '1024x1024' ? '2k' : req.size,+ response_format: 'url',+ async: true,+ ...(req.referenceImages?.length+ ? { reference_images: req.referenceImages.map(orkasImageDataUrl) }+ : {}),+ }),+ },+ ORKAS_IMAGE_CREATE_TIMEOUT_MS,+ overall.signal,+ 'Orkas Image create request timed out',+ );+ let data = await readOrkasImageResponse(response, 'create');+ const taskId = String(data?.id || '').trim();+ if (!data?.data?.[0]?.url && !data?.data?.[0]?.b64_json) {+ if (!taskId) throw new Error('Orkas Image create returned no task id');+ data = await waitForOrkasImageTask(taskId, req.apiKey, overall.signal, req.usageContext);+ }++ const b64 = String(data?.data?.[0]?.b64_json || '');+ let buffer: Buffer;+ if (b64) {+ buffer = Buffer.from(b64, 'base64');+ } else {+ const url = String(data?.data?.[0]?.url || '').trim();+ if (!url) throw new Error(`Orkas Image task ${taskId || '(sync)'} succeeded without image data`);+ const download = composeAbortSignal(+ overall.signal,+ ORKAS_IMAGE_DOWNLOAD_TIMEOUT_MS,+ 'Orkas Image download timed out',+ );+ try {+ const result = await downloadBinaryWithProxyPolicy(url, {+ label: 'Orkas Image download',+ signal: download.signal,+ maxBytes: 64 * 1024 * 1024,+ validate: (body) => {+ if (!body.length || !detectMimeType(body)) {+ throw new Error('Orkas Image download returned unsupported image bytes');+ }+ },+ });+ buffer = result.body;+ } finally {+ download.cleanup();+ }+ }+ const mimeType = detectMimeType(buffer) || 'image/png';+ const dim = parseImageDimensions(buffer, mimeType);+ return { buffer, mimeType, width: dim.width, height: dim.height };+ } finally {+ overall.cleanup();+ }+}+export async function callOpenAIImage(req: AdapterRequest): Promise<AdapterResult> {const hasRefs = !!(req.referenceImages && req.referenceImages.length);const url = hasRefsdiff --git a/src/main/features/orkas_api.ts b/src/main/features/orkas_api.tsnew file mode 100644index 00000000..cd5415e0--- /dev/null+++ b/src/main/features/orkas_api.ts@@ -0,0 +1,58 @@+/** Public Orkas API identifiers used by the open-source BYO-key adapters. */++export const ORKAS_API_PROVIDER = 'orkas-api';+export const ORKAS_API_BASE_URL = 'https://orkas.ai/v1';+export const ORKAS_API_KEYS_URL = 'https://orkas.ai/views/account/account.html#api-keys';++export const ORKAS_API_DEFAULT_LLM_MODEL = 'orkas-llm-1.5';+export const ORKAS_API_LLM_MODELS = [+ {+ id: ORKAS_API_DEFAULT_LLM_MODEL,+ name: 'Orkas-1.5',+ recommended: true,+ includedModels: [+ 'DeepSeek V4',+ 'GPT-5.6 Luna',+ 'Claude-Sonnet-5',+ 'Gemini-3.6 Flash',+ ],+ },+ {+ id: 'orkas-llm-1.5-pro',+ name: 'Orkas-1.5 Pro',+ includedModels: ['GPT-5.6 Sol', 'Claude Opus 5', 'Kimi K3'],+ },+];++export const ORKAS_API_IMAGE_MODEL = 'orkas-image';+export const ORKAS_API_TTS_MODEL = 'orkas-tts-1';+export const ORKAS_API_VIDEO_MODEL = 'orkas-video';+export const ORKAS_API_DEFAULT_VOICE = 'zh_female_vv_uranus_bigtts';++/**+ * Opaque billing context shared by Orkas public-API calls made during one+ * local conversation. Deliberately exclude the conversation title (and all+ * other user content): the open-source client only sends stable ids needed to+ * group credit consumption into the same session.+ */+export interface OrkasApiUsageContext {+ conversationId?: string;+ turnId?: string;+}++const ORKAS_API_CONTEXT_ID_RE = /^[A-Za-z0-9_-]{1,64}$/;++export function orkasApiUsageHeaders(+ context?: OrkasApiUsageContext,+): Record<string, string> {+ const conversationId = String(context?.conversationId || '').trim();+ const turnId = String(context?.turnId || '').trim();+ return {+ ...(ORKAS_API_CONTEXT_ID_RE.test(conversationId)+ ? { 'X-Orkas-Conversation-Id': conversationId }+ : {}),+ ...(ORKAS_API_CONTEXT_ID_RE.test(turnId)+ ? { 'X-Orkas-Turn-Id': turnId }+ : {}),+ };+}diff --git a/src/main/features/tts.ts b/src/main/features/tts.tsindex ef536fd2..2cac8a35 100644--- a/src/main/features/tts.ts+++ b/src/main/features/tts.ts@@ -28,6 +28,11 @@ import { probeMediaDurationSec } from '../util/media_probe';import { redactPaths } from '../util/redact';import { createLogger } from '../logger';import { resolveTtsSelection } from './tts_capabilities';+import {+ ORKAS_API_PROVIDER,+ orkasApiUsageHeaders,+ type OrkasApiUsageContext,+} from './orkas_api';const log = createLogger('tts');@@ -52,6 +57,7 @@ export interface TtsParams {format?: string;signal?: AbortSignal;onProgress?: (event: { phase: string; message: string }) => void;+ usageContext?: OrkasApiUsageContext;}export type TtsResult =@@ -432,7 +438,15 @@ function combineSignal(signal: AbortSignal | undefined, timeoutMs: number): Aborclass OpenAICompatibleTtsBackend implements TtsBackend {readonly id = 'openai-compatible';- constructor(private readonly profile: { baseUrl: string; apiKey: string; model: string; voice?: string; format?: string; label?: string }) {}+ constructor(private readonly profile: {+ baseUrl: string;+ apiKey: string;+ model: string;+ provider?: string;+ voice?: string;+ format?: string;+ label?: string;+ }) {}async synthesize(p: TtsParams): Promise<TtsResult> {const base = this.profile.baseUrl.replace(/\/+$/, '');@@ -452,7 +466,13 @@ class OpenAICompatibleTtsBackend implements TtsBackend {try {resp = await fetch(url, {method: 'POST',- headers: { 'Authorization': `Bearer ${this.profile.apiKey}`, 'Content-Type': 'application/json' },+ headers: {+ 'Authorization': `Bearer ${this.profile.apiKey}`,+ 'Content-Type': 'application/json',+ ...(this.profile.provider === ORKAS_API_PROVIDER+ ? orkasApiUsageHeaders(p.usageContext)+ : {}),+ },body: JSON.stringify(body),signal: combineSignal(p.signal, TTS_TIMEOUT_MS),});diff --git a/src/main/features/tts_auth.ts b/src/main/features/tts_auth.tsindex 179abbca..e173f02b 100644--- a/src/main/features/tts_auth.ts+++ b/src/main/features/tts_auth.ts@@ -1,13 +1,20 @@/*** Text-to-speech provider management for user-owned keys.*- * Open-source builds do not ship a hosted Orkas speech API. Users configure- * their own provider credentials here, and downstream speech tools read the- * ordered `ttsProfiles` list from auth.ts.+ * Open-source builds use user-supplied provider credentials here, including+ * public Orkas API keys. Downstream speech tools read the ordered+ * `ttsProfiles` list from auth.ts.*/import { loadTtsProfiles, saveTtsProfiles, type TtsProfile } from './auth';import { createLogger } from '../logger';+import {+ ORKAS_API_BASE_URL,+ ORKAS_API_DEFAULT_VOICE,+ ORKAS_API_KEYS_URL,+ ORKAS_API_PROVIDER,+ ORKAS_API_TTS_MODEL,+} from './orkas_api';const log = createLogger('tts-auth');@@ -144,6 +151,15 @@ export function listTtsProviderPresets(): Array<{defaultModel?: string; defaultVoice?: string; defaultFormat?: string; docs?: string;}> {return [+ {+ id: ORKAS_API_PROVIDER,+ label: 'Orkas · Voice',+ baseUrl: ORKAS_API_BASE_URL,+ defaultModel: ORKAS_API_TTS_MODEL,+ defaultVoice: ORKAS_API_DEFAULT_VOICE,+ defaultFormat: DEFAULT_TTS_FORMAT,+ docs: ORKAS_API_KEYS_URL,+ },{ id: 'doubao', label: 'DouBao · Voice', baseUrl: DOUBAO_TTS_BASE_URL, defaultVoice: DOUBAO_DEFAULT_VOICE, defaultFormat: DEFAULT_TTS_FORMAT, docs: 'https://www.volcengine.com/docs/6561/1598757' },{ id: 'elevenlabs', label: 'ElevenLabs', baseUrl: 'https://api.elevenlabs.io/v1', defaultModel: 'eleven_multilingual_v2', docs: 'https://elevenlabs.io/docs' },{ id: 'openai', label: 'OpenAI', baseUrl: 'https://api.openai.com/v1', defaultModel: 'tts-1', defaultVoice: 'alloy', defaultFormat: DEFAULT_TTS_FORMAT, docs: 'https://platform.openai.com/api-keys' },diff --git a/src/main/features/video_auth.ts b/src/main/features/video_auth.tsindex 2caa2061..cbb4ca48 100644--- a/src/main/features/video_auth.ts+++ b/src/main/features/video_auth.ts@@ -1,8 +1,9 @@/*** Video-generation API key management for BYO providers.*- * This is only the local credential/configuration layer. It deliberately does- * not expose any Orkas-managed video provider or Server proxy.+ * This is only the local credential/configuration layer. The open-source app+ * can use the public Orkas API with a user-supplied API key, but never exposes+ * the commercial app's managed provider or server-owned credentials.*/import {@@ -11,10 +12,18 @@ import {type VideoProfile,} from './auth';import { createLogger } from '../logger';+import {+ ORKAS_API_KEYS_URL,+ ORKAS_API_PROVIDER,+ ORKAS_API_VIDEO_MODEL,+} from './orkas_api';const log = createLogger('video-auth');const VIDEO_AUTH_MODELS_BY_PROVIDER: Readonly<Record<string, Array<{ id: string; name: string }>>> = {+ [ORKAS_API_PROVIDER]: [+ { id: ORKAS_API_VIDEO_MODEL, name: 'Video' },+ ],doubao: [{ id: 'doubao-seedance-2-0-260128', name: 'Seedance 2.0' },],@@ -96,6 +105,11 @@ export function reorderVideoProfiles(orderedIds: string[]): { ok: boolean } {export function listVideoProviderOptions(): Array<{ id: string; label: string; docs?: string }> {return [+ {+ id: ORKAS_API_PROVIDER,+ label: 'Orkas',+ docs: ORKAS_API_KEYS_URL,+ },{id: 'doubao',label: 'DouBao · Seedance',diff --git a/src/main/features/video_gen.ts b/src/main/features/video_gen.tsnew file mode 100644index 00000000..864ac42f--- /dev/null+++ b/src/main/features/video_gen.ts@@ -0,0 +1,472 @@+/** Video generation through the API-key authenticated Orkas public API. */++import * as fs from 'node:fs/promises';+import * as path from 'node:path';++import { loadVideoProfiles } from './auth';+import {+ ORKAS_API_BASE_URL,+ ORKAS_API_PROVIDER,+ ORKAS_API_VIDEO_MODEL,+ orkasApiUsageHeaders,+ type OrkasApiUsageContext,+} from './orkas_api';+import { prepareReferenceUrls, registerGeneratedMediaUrl } from './generation_reference_assets';+import { createLogger } from '../logger';+import { t } from '../i18n';+import { composeAbortSignal, fetchWithTimeout, throwIfAborted } from '../util/abort';+import { downloadBinaryWithProxyPolicy } from '../util/proxy-dispatcher';+import { logErrorSummary, logPathRef } from '../util/log-redact';+import { sanitizeLogTextForUpload } from '../util/log-sanitize';++const log = createLogger('video-gen');+const DEFAULT_POLL_INTERVAL_MS = 10_000;+const DEFAULT_TIMEOUT_MS = 60 * 60_000;+const CREATE_TIMEOUT_MS = 60_000;+const POLL_TIMEOUT_MS = 20_000;+const DOWNLOAD_TIMEOUT_MS = 10 * 60_000;+const MAX_CONSECUTIVE_POLL_TIMEOUTS = 5;++export interface GenerateVideoInput {+ prompt: string;+ outputAbsPath: string;+ referenceImageUrls?: string[];+ referenceImagePaths?: string[];+ referenceVideoUrls?: string[];+ referenceVideoPaths?: string[];+ operation?: 'generate' | 'edit';+ ratio?: string;+ duration?: number;+ resolution?: string;+ quality?: 'economy' | 'balanced' | 'quality';+ generateAudio?: boolean;+ seed?: number;+ pollIntervalMs?: number;+ timeoutMs?: number;+ signal?: AbortSignal;+ onProgress?: VideoProgressReporter;+ usageContext?: OrkasApiUsageContext;+}++export type VideoProgressReporter = (event: {+ phase: string;+ message: string;+ data?: Record<string, unknown>;+}) => void;++export type GenerateVideoResult =+ | {+ ok: true;+ path: string;+ bytes: number;+ provider: string;+ model: string;+ taskId: string;+ videoUrl: string;+ status: string;+ ratio?: string;+ duration?: number;+ resolution?: string;+ }+ | {+ ok: false;+ errorCode:+ | 'NO_CAPABLE_MODEL'+ | 'PROVIDER_API_ERROR'+ | 'DELIVERY_ERROR'+ | 'IO_ERROR'+ | 'BAD_INPUT'+ | 'TIMEOUT'+ | 'CREDITS_EXHAUSTED';+ message: string;+ taskId?: string;+ postDispatch?: boolean;+ };++class OrkasApiQuotaError extends Error {+ override readonly name = 'OrkasApiQuotaError';+}++class VideoDeliveryError extends Error {+ override readonly name = 'VideoDeliveryError';+ constructor(message: string, readonly taskId: string, options?: ErrorOptions) {+ super(message, options);+ }+}++interface NormalizedVideoInput {+ prompt: string;+ referenceImageUrls: string[];+ referenceVideoUrls: string[];+ operation: 'generate' | 'edit';+ ratio: string;+ duration: number;+ resolution: string;+ quality: 'balanced' | 'quality';+ generateAudio: boolean;+ seed?: number;+ pollIntervalMs: number;+ timeoutMs: number;+}++interface OrkasVideoRequest extends NormalizedVideoInput {+ apiKey: string;+ signal?: AbortSignal;+ onProgress?: VideoProgressReporter;+ usageContext?: OrkasApiUsageContext;+}++interface OrkasVideoResult {+ buffer: Buffer;+ taskId: string;+ videoUrl: string;+ status: string;+ ratio?: string;+ duration?: number;+ resolution?: string;+}++export async function generateVideo(input: GenerateVideoInput): Promise<GenerateVideoResult> {+ try {+ throwIfAborted(input.signal);+ if (!input.prompt?.trim()) return { ok: false, errorCode: 'BAD_INPUT', message: 'prompt is required' };+ if (!input.outputAbsPath) return { ok: false, errorCode: 'BAD_INPUT', message: 'outputAbsPath is required' };++ const profile = loadVideoProfiles().find((candidate) => (+ candidate.provider === ORKAS_API_PROVIDER && candidate.model === ORKAS_API_VIDEO_MODEL+ ));+ if (!profile) {+ return { ok: false, errorCode: 'NO_CAPABLE_MODEL', message: t('video_gen.no_capable_model') };+ }++ let normalized: NormalizedVideoInput;+ try {+ const refs = await resolveReferenceUrls(input);+ normalized = normalizeVideoInput({+ ...input,+ referenceImageUrls: refs.referenceImageUrls,+ referenceVideoUrls: refs.referenceVideoUrls,+ });+ } catch (err) {+ return {+ ok: false,+ errorCode: 'BAD_INPUT',+ message: sanitizeLogTextForUpload((err as Error).message || String(err)),+ };+ }+ const generated = await callOrkasApiVideo({+ ...normalized,+ apiKey: profile.apiKey,+ signal: input.signal,+ onProgress: input.onProgress,+ ...(input.usageContext ? { usageContext: input.usageContext } : {}),+ });++ const finalPath = ensureMp4Extension(input.outputAbsPath);+ try {+ throwIfAborted(input.signal);+ emitProgress(input.onProgress, 'save', 'Saving generated video');+ await fs.mkdir(path.dirname(finalPath), { recursive: true });+ await fs.writeFile(finalPath, generated.buffer);+ } catch (err) {+ log.error('video write failed after provider completed', {+ task_id: generated.taskId,+ path: logPathRef(finalPath),+ error: logErrorSummary(err),+ });+ return {+ ok: false,+ errorCode: 'IO_ERROR',+ message: sanitizeLogTextForUpload(+ `The provider completed this potentially billable video, but it could not be saved locally. Do not retry automatically. ${(err as Error).message}`,+ ),+ taskId: generated.taskId,+ postDispatch: true,+ };+ }++ registerGeneratedMediaUrl(finalPath, generated.videoUrl);+ return {+ ok: true,+ path: finalPath,+ bytes: generated.buffer.length,+ provider: ORKAS_API_PROVIDER,+ model: ORKAS_API_VIDEO_MODEL,+ taskId: generated.taskId,+ videoUrl: generated.videoUrl,+ status: generated.status,+ ...(generated.ratio ? { ratio: generated.ratio } : {}),+ ...(typeof generated.duration === 'number' ? { duration: generated.duration } : {}),+ ...(generated.resolution ? { resolution: generated.resolution } : {}),+ };+ } catch (err) {+ const message = sanitizeLogTextForUpload((err as Error).message || String(err));+ if (err instanceof VideoDeliveryError) {+ return {+ ok: false,+ errorCode: 'DELIVERY_ERROR',+ message,+ taskId: err.taskId,+ postDispatch: true,+ };+ }+ if (err instanceof OrkasApiQuotaError) {+ return { ok: false, errorCode: 'CREDITS_EXHAUSTED', message };+ }+ if (input.signal?.aborted || /operation aborted/i.test(message)) {+ return { ok: false, errorCode: 'BAD_INPUT', message };+ }+ return {+ ok: false,+ errorCode: /timed out|timeout/i.test(message) ? 'TIMEOUT' : 'PROVIDER_API_ERROR',+ message,+ };+ }+}++export const video_gen = generateVideo;++async function resolveReferenceUrls(input: GenerateVideoInput): Promise<{+ referenceImageUrls: string[];+ referenceVideoUrls: string[];+}> {+ const count = (input.referenceImageUrls?.length || 0)+ + (input.referenceImagePaths?.length || 0)+ + (input.referenceVideoUrls?.length || 0)+ + (input.referenceVideoPaths?.length || 0);+ if (count) emitProgress(input.onProgress, 'prepare_references', 'Preparing video references', { count });+ const referenceImageUrls = await prepareReferenceUrls({+ kind: 'image',+ urls: input.referenceImageUrls,+ paths: input.referenceImagePaths,+ maxItems: 9,+ signal: input.signal,+ onProgress: input.onProgress,+ });+ const referenceVideoUrls = await prepareReferenceUrls({+ kind: 'video',+ urls: input.referenceVideoUrls,+ paths: input.referenceVideoPaths,+ maxItems: 3,+ signal: input.signal,+ onProgress: input.onProgress,+ });+ if ([...referenceImageUrls, ...referenceVideoUrls].some((url) => !/^https:\/\//i.test(url))) {+ throw new Error('Orkas API video references must use public HTTPS URLs');+ }+ return { referenceImageUrls, referenceVideoUrls };+}++function normalizeVideoInput(input: GenerateVideoInput): NormalizedVideoInput {+ const operation = input.operation === 'edit' ? 'edit' : 'generate';+ const referenceVideoUrls = (input.referenceVideoUrls || []).slice(0, 3);+ if (operation === 'edit' && referenceVideoUrls.length < 1) {+ throw new Error('operation=edit requires at least one reference video');+ }+ return {+ prompt: input.prompt.trim(),+ referenceImageUrls: (input.referenceImageUrls || []).slice(0, 9),+ referenceVideoUrls,+ operation,+ ratio: choice(input.ratio, ['16:9', '9:16', '1:1', '4:3', '3:4', '21:9'], '16:9'),+ duration: integer(input.duration, 5, 4, 15),+ resolution: choice(input.resolution, ['480p', '720p', '1080p'], '720p'),+ quality: input.quality === 'quality' ? 'quality' : 'balanced',+ generateAudio: input.generateAudio !== false,+ ...(typeof input.seed === 'number' && Number.isFinite(input.seed) ? { seed: Math.trunc(input.seed) } : {}),+ pollIntervalMs: integer(input.pollIntervalMs, DEFAULT_POLL_INTERVAL_MS, 1_000, 30_000),+ timeoutMs: integer(input.timeoutMs, DEFAULT_TIMEOUT_MS, 30_000, DEFAULT_TIMEOUT_MS),+ };+}++async function callOrkasApiVideo(req: OrkasVideoRequest): Promise<OrkasVideoResult> {+ throwIfAborted(req.signal);+ emitProgress(req.onProgress, 'create_task', 'Creating Orkas API video task');+ const create = await fetchWithTimeout(+ `${ORKAS_API_BASE_URL}/videos`,+ {+ method: 'POST',+ headers: {+ Authorization: `Bearer ${req.apiKey}`,+ 'Content-Type': 'application/json',+ ...orkasApiUsageHeaders(req.usageContext),+ },+ body: JSON.stringify({+ prompt: req.prompt,+ duration: req.duration,+ resolution: req.resolution,+ ratio: req.ratio,+ quality: req.quality,+ generate_audio: req.generateAudio,+ reference_image_urls: req.referenceImageUrls,+ reference_video_urls: req.referenceVideoUrls,+ operation: req.operation,+ ...(typeof req.seed === 'number' ? { seed: req.seed } : {}),+ }),+ },+ CREATE_TIMEOUT_MS,+ req.signal,+ 'Orkas API video create request timed out',+ );+ let data = await readOrkasVideoResponse(create, 'create');+ const taskId = String(data?.id || '').trim();+ if (!taskId) throw new Error('Orkas API video create returned no task id');+ emitProgress(req.onProgress, 'task_created', `Video task created: ${taskId}`, { taskId });++ const started = Date.now();+ let attempts = 0;+ let consecutiveTimeouts = 0;+ while (Date.now() - started < req.timeoutMs) {+ throwIfAborted(req.signal);+ const status = String(data?.status || 'processing').toLowerCase();+ if (['failed', 'cancelled', 'canceled'].includes(status)) {+ throw new Error(`Orkas API video task ${taskId} ${status}: ${truncate(JSON.stringify(data?.error || data), 500)}`);+ }+ const url = String(data?.url || '').trim();+ if (url) {+ emitProgress(req.onProgress, 'task_succeeded', `Video task completed: ${taskId}`, { taskId });+ const buffer = await downloadVideo(url, taskId, req.signal, req.onProgress);+ return {+ buffer,+ taskId,+ videoUrl: url,+ status: status || 'succeeded',+ ...(typeof data?.ratio === 'string' ? { ratio: data.ratio } : {}),+ ...(typeof data?.duration === 'number' ? { duration: data.duration } : {}),+ ...(typeof data?.resolution === 'string' ? { resolution: data.resolution } : {}),+ };+ }++ attempts += 1;+ emitProgress(req.onProgress, 'poll_wait', 'Waiting before checking video status', { taskId, attempt: attempts });+ await sleep(req.pollIntervalMs, req.signal);+ try {+ const poll = await fetchWithTimeout(+ `${ORKAS_API_BASE_URL}/videos/${encodeURIComponent(taskId)}`,+ {+ method: 'GET',+ headers: {+ Authorization: `Bearer ${req.apiKey}`,+ ...orkasApiUsageHeaders(req.usageContext),+ },+ },+ POLL_TIMEOUT_MS,+ req.signal,+ 'Orkas API video status request timed out',+ );+ data = await readOrkasVideoResponse(poll, 'status');+ consecutiveTimeouts = 0;+ emitProgress(req.onProgress, 'poll_result', `Video task status: ${data?.status || 'processing'}`, {+ taskId,+ attempt: attempts,+ status: String(data?.status || 'processing'),+ });+ } catch (err) {+ if (req.signal?.aborted || !/timed out|timeout/i.test((err as Error).message)) throw err;+ consecutiveTimeouts += 1;+ if (consecutiveTimeouts >= MAX_CONSECUTIVE_POLL_TIMEOUTS) throw err;+ }+ }+ throw new Error(`Orkas API video task ${taskId} timed out after ${Math.round(req.timeoutMs / 1000)} seconds`);+}++async function readOrkasVideoResponse(resp: Response, phase: string): Promise<any> {+ const text = await resp.text();+ let data: any = {};+ try { data = text ? JSON.parse(text) : {}; } catch { /* handled below */ }+ if (!resp.ok) {+ const error = data?.error || {};+ const message = error.message || text || `HTTP ${resp.status}`;+ const detail = `Orkas API video ${phase} ${resp.status}: ${truncate(String(message), 500)}`;+ if (resp.status === 402 || error.type === 'insufficient_quota' || /quota_exceeded/.test(String(error.code || ''))) {+ throw new OrkasApiQuotaError(detail);+ }+ throw new Error(detail);+ }+ return data;+}++async function downloadVideo(+ url: string,+ taskId: string,+ signal?: AbortSignal,+ onProgress?: VideoProgressReporter,+): Promise<Buffer> {+ emitProgress(onProgress, 'download', 'Downloading generated video');+ const timeout = composeAbortSignal(signal, DOWNLOAD_TIMEOUT_MS, 'video download timed out');+ try {+ const result = await downloadBinaryWithProxyPolicy(url, {+ label: 'Orkas API generated video download',+ signal: timeout.signal,+ maxBytes: 512 * 1024 * 1024,+ validate: validateDownloadedVideo,+ });+ emitProgress(onProgress, 'download_done', `Video download complete: ${result.body.length} bytes`);+ return result.body;+ } catch (err) {+ throw new VideoDeliveryError(+ `The provider completed task ${taskId}, but the generated video could not be downloaded after bounded retries. Do not submit another generation task. ${(err as Error).message}`,+ taskId,+ { cause: err },+ );+ } finally {+ timeout.cleanup();+ }+}++export function validateDownloadedVideo(buffer: Buffer): void {+ const scanLimit = Math.min(buffer.length, 4096);+ let offset = 0;+ while (offset + 8 <= scanLimit) {+ const boxSize = buffer.readUInt32BE(offset);+ const boxType = buffer.toString('ascii', offset + 4, offset + 8);+ if (boxType === 'ftyp' && boxSize >= 16 && offset + boxSize <= buffer.length) return;+ if (boxSize < 8 || offset + boxSize > scanLimit) break;+ offset += boxSize;+ }+ throw new Error('video download returned invalid or unsupported MP4 bytes');+}++function integer(value: unknown, fallback: number, min: number, max: number): number {+ const number = typeof value === 'number' && Number.isFinite(value) ? Math.trunc(value) : fallback;+ return Math.max(min, Math.min(max, number));+}++function choice(value: unknown, allowed: string[], fallback: string): string {+ const normalized = typeof value === 'string' ? value.trim() : '';+ return allowed.includes(normalized) ? normalized : fallback;+}++function ensureMp4Extension(value: string): string {+ const extension = path.extname(value);+ if (extension.toLowerCase() === '.mp4') return value;+ return extension ? `${value.slice(0, -extension.length)}.mp4` : `${value}.mp4`;+}++function truncate(value: string, max: number): string {+ return value.length <= max ? value : `${value.slice(0, max)}…`;+}++function sleep(ms: number, signal?: AbortSignal): Promise<void> {+ return new Promise((resolve, reject) => {+ const onAbort = () => {+ clearTimeout(timer);+ reject(new Error('operation aborted'));+ };+ const timer = setTimeout(() => {+ signal?.removeEventListener('abort', onAbort);+ resolve();+ }, ms);+ signal?.addEventListener('abort', onAbort, { once: true });+ if (signal?.aborted) onAbort();+ });+}++function emitProgress(+ onProgress: VideoProgressReporter | undefined,+ phase: string,+ message: string,+ data?: Record<string, unknown>,+): void {+ onProgress?.({ phase, message, ...(data ? { data } : {}) });+}diff --git a/src/main/ipc/index.ts b/src/main/ipc/index.tsindex 18d1c85a..2bd46e07 100644--- a/src/main/ipc/index.ts+++ b/src/main/ipc/index.ts@@ -2689,13 +2689,19 @@ const invokeHandlers: Record<string, InvokeHandler> = {// consent page renders where the user is already logged in).'auth.openExternal': async ({ url }) => auth.openExternalUrl(url),// Priority list (entries) — ordered (provider, model, profile) tuples.- 'auth.listEntries': async () => auth.listEntries(),+ 'auth.listEntries': async ({ includeUnavailable } = {}) => (+ auth.listEntries({ includeUnavailable: !!includeUnavailable })+ ),+ 'auth.listComposerEntries': async () => auth.listComposerEntries(),'auth.addEntry': async ({ provider, model, profileId }) => auth.addEntry({ provider, model, profileId }),'auth.removeEntry': async ({ entryId }) => auth.removeEntry(entryId),'auth.reorderEntries': async ({ orderedIds }) => auth.reorderEntries(orderedIds || []),'auth.selectEntry': async ({ entryId, model }) => auth.selectEntry(entryId, model),'auth.updateEntryModel':async ({ entryId, model }) => auth.updateEntryModel(entryId, model),+ // ── Orkas public API key quick setup (open-source build only) ──+ 'orkasApi.configureAll': async ({ apiKey }) => auth.configureAllOrkasApiServices(apiKey),+// ── Image-generation API key (independent from chat entries) ──// `list` strips raw apiKey and replaces it with `apiKeyMasked` so// renderer never sees the full key (parity with chat entries' `profileMasked`).diff --git a/src/main/locales/en.json b/src/main/locales/en.jsonindex 9b01ca48..4d94b902 100644--- a/src/main/locales/en.json+++ b/src/main/locales/en.json@@ -41,6 +41,7 @@"process.skill.final_imported": "Skill import complete. Created {count} skills.","process.skill.final_no_changes": "No skill content was written. Check the process details.","image_gen.no_capable_model": "No image-generation capable model is configured. Please add an OpenAI or Google API key (subscription/OAuth credentials cannot access image generation).",+ "video_gen.no_capable_model": "No video generation service is configured. Configure Orkas API in Settings.","oauth.minimax.requesting": "Requesting authorization from MiniMax…","oauth.minimax.waiting": "Waiting for MiniMax authorization to complete…","oauth.minimax.instructions": "Enter the following code on the opened page:\n\n {code}\n\nAfter authorization, Orkas will continue automatically. No action is needed.",diff --git a/src/main/locales/ja.json b/src/main/locales/ja.jsonindex 2b753eff..8d75667f 100644--- a/src/main/locales/ja.json+++ b/src/main/locales/ja.json@@ -41,6 +41,7 @@"process.skill.final_imported": "スキルのインポートが完了しました。{count} 個のスキルを作成しました。","process.skill.final_no_changes": "スキル内容は書き込まれませんでした。過程情報を確認してください。","image_gen.no_capable_model": "画像生成に対応したモデルが設定されていません。OpenAI または Google の API キーを追加してください(サブスクリプション / OAuth 認証情報では画像生成を利用できません)。",+ "video_gen.no_capable_model": "動画生成サービスが設定されていません。「設定」で Orkas API を設定してください。","oauth.minimax.requesting": "MiniMax に認証をリクエストしています…","oauth.minimax.waiting": "MiniMax の認証完了を待っています…","oauth.minimax.instructions": "開いたページで次のコードを入力してください:\n\n {code}\n\n認証が完了すると、Orkas が自動で続行します。操作は不要です。",diff --git a/src/main/locales/pt.json b/src/main/locales/pt.jsonindex a7494620..74ab1184 100644--- a/src/main/locales/pt.json+++ b/src/main/locales/pt.json@@ -41,6 +41,7 @@"process.skill.final_imported": "Importação de habilidades concluída. {count} habilidades criadas.","process.skill.final_no_changes": "Nenhum conteúdo de habilidade foi escrito. Confira os detalhes do processo.","image_gen.no_capable_model": "Nenhum modelo com capacidade de geração de imagem está configurado. Adicione uma chave de API OpenAI ou Google (as credenciais de assinatura/OAuth não podem acessar a geração de imagens).",+ "video_gen.no_capable_model": "Nenhum serviço de geração de vídeo está configurado. Configure a API Orkas em Configurações.","oauth.minimax.requesting": "Solicitando autorização do MiniMax…","oauth.minimax.waiting": "Aguardando a conclusão da autorização do MiniMax…","oauth.minimax.instructions": "Digite o código abaixo na página aberta:\n\n {code}\n\nApós a autorização, o Orkas continuará automaticamente. Nenhuma ação é necessária.",diff --git a/src/main/locales/zh.json b/src/main/locales/zh.jsonindex f42bad6d..b365cd5d 100644--- a/src/main/locales/zh.json+++ b/src/main/locales/zh.json@@ -41,6 +41,7 @@"process.skill.final_imported": "已完成技能导入,共创建 {count} 个技能。","process.skill.final_no_changes": "未写入技能内容,请查看过程信息。","image_gen.no_capable_model": "当前模型列表无图像生成能力。请添加 OpenAI / Google 任一 API Key(订阅/OAuth 授权不提供图像生成)。",+ "video_gen.no_capable_model": "尚未配置可用的视频生成服务。请在「设置」中配置 Orkas API。","oauth.minimax.requesting": "向 MiniMax 申请授权…","oauth.minimax.waiting": "等待 MiniMax 授权完成…","oauth.minimax.instructions": "请在打开的页面中输入验证码:\n\n {code}\n\n授权完成后,Orkas 会自动继续,无需手动操作。",diff --git a/src/main/model/core-agent/external-providers.ts b/src/main/model/core-agent/external-providers.tsindex 2f458f51..cac298cd 100644--- a/src/main/model/core-agent/external-providers.ts+++ b/src/main/model/core-agent/external-providers.ts@@ -45,6 +45,12 @@ import {type CustomOpenAICompatibleRuntimeConfig,} from '../provider_catalog';import { repairOpenAIToolMessageOrder } from './openai-payload';+import {+ ORKAS_API_BASE_URL,+ ORKAS_API_PROVIDER,+ orkasApiUsageHeaders,+ type OrkasApiUsageContext,+} from '../../features/orkas_api';// core-agent is an ESM package and the Orkas main process is CJS, so// **static import is not allowed**. Reuse the dynamic-import + lazy cache@@ -100,6 +106,48 @@ export function repairOpenAICompatiblePayload(params: unknown): unknown {return repairOpenAIToolMessageOrder(params);}+// ── Orkas public API ───────────────────────────────────────────────────++export function buildOrkasApiModel(modelId: string): Model<'openai-completions'> {+ const curated = curatedModelsFor(ORKAS_API_PROVIDER).find((model) => model.id === modelId);+ return {+ id: modelId,+ name: curated?.name || modelId,+ api: 'openai-completions',+ provider: ORKAS_API_PROVIDER as any,+ baseUrl: ORKAS_API_BASE_URL,+ reasoning: true,+ compat: {+ supportsDeveloperRole: false,+ supportsStore: false,+ thinkingFormat: 'deepseek',+ requiresReasoningContentOnAssistantMessages: true,+ },+ input: ['text', 'image'],+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },+ contextWindow: configuredPositiveInteger(curated?.contextWindow, 1_048_576),+ maxTokens: configuredPositiveInteger(curated?.maxTokens, 32_000),+ };+}++export async function createOrkasApiProvider(config: {+ apiKey: string;+ modelId: string;+ usageContext?: OrkasApiUsageContext;+}): Promise<LLMProvider> {+ if (!config.apiKey) throw new Error('orkas-api: apiKey required');+ if (!isBearerTokenHeaderSafe(config.apiKey)) throw new Error('orkas-api: invalid API key');+ if (!config.modelId) throw new Error('orkas-api: modelId required');+ const mod = await ca();+ return mod.createPiProvider({+ provider: ORKAS_API_PROVIDER,+ apiKey: config.apiKey,+ customModel: buildOrkasApiModel(config.modelId),+ defaultReasoning: 'low',+ headers: orkasApiUsageHeaders(config.usageContext),+ });+}+// ── Moonshot open-platform (https://api.moonshot.cn/v1) ─────────────────const MOONSHOT_BASE_URL = 'https://api.moonshot.cn/v1';diff --git a/src/main/model/core-agent/generate-speech-tool.ts b/src/main/model/core-agent/generate-speech-tool.tsindex b95099c8..554063e3 100644--- a/src/main/model/core-agent/generate-speech-tool.ts+++ b/src/main/model/core-agent/generate-speech-tool.ts@@ -299,6 +299,10 @@ export function createGenerateSpeechTool(opts: GenerateSpeechToolOpts): AgentToo...(typeof speed === 'number' ? { speed } : {}),...(format ? { format } : {}),...(ctx.signal ? { signal: ctx.signal } : {}),+ usageContext: {+ conversationId: opts.cid,+ turnId: opts.turnId,+ },onProgress: (event) => ctx.emitProgress?.({ phase: event.phase, message: event.message }),});if (result.ok === false) {diff --git a/src/main/model/core-agent/image-gen-tool.ts b/src/main/model/core-agent/image-gen-tool.tsindex 6fd2f38e..d8af9430 100644--- a/src/main/model/core-agent/image-gen-tool.ts+++ b/src/main/model/core-agent/image-gen-tool.ts@@ -34,6 +34,7 @@ export interface ImageGenToolOpts {/** Conversation id — extends the path sandbox to allow writing into* the conv's attachment dir (and reading reference images from it). */cid?: string;+ turnId?: string;/** Project id of the current conversation, when it belongs to one.* Threaded through from group_chat so workspace resolution picks up* the project-scoped selection (per CLAUDE.md projects feature). */@@ -152,6 +153,11 @@ export function createImageGenTool(opts: ImageGenToolOpts): AgentTool {outputAbsPath: outputAbs,...(refAbs.length ? { referenceImagePaths: refAbs } : {}),...(sizeRaw ? { size: sizeRaw } : {}),+ ...(ctx.signal ? { signal: ctx.signal } : {}),+ usageContext: {+ conversationId: opts.cid,+ turnId: opts.turnId,+ },});if (result.ok === false) {diff --git a/src/main/model/core-agent/runner.ts b/src/main/model/core-agent/runner.tsindex cab75bb0..3d40461c 100644--- a/src/main/model/core-agent/runner.ts+++ b/src/main/model/core-agent/runner.ts@@ -74,6 +74,7 @@ import { officeCliAvailable } from '../../features/office/office_engine';import { createLibraryTool } from './kb-tools';import { createChatHistoryTool } from './chat-history-tools';import { createImageGenTool } from './image-gen-tool';+import { createVideoGenTool } from './video-gen-tool';import { createGenerateSpeechTool } from './generate-speech-tool';import {AGENT_DEPENDENCY_TOOL_GROUP_IDS,@@ -98,6 +99,8 @@ import {} from '../../util/tool-result-cap';import { createToolResultTools } from './tool-result-tools';import {+ buildOrkasApiModel,+ createOrkasApiProvider,buildMoonshotModel,buildDeepSeekModel,buildDoubaoModel,@@ -115,6 +118,7 @@ import {modelInputImageLimit,} from '../provider_catalog';import { readDisabledSets } from '../../features/component_enabled';+import type { OrkasApiUsageContext } from '../../features/orkas_api';import {nativeSearchToolForApi,nativeSearchToolName,@@ -154,6 +158,8 @@ function buildExternalProviderModel(customConfig?: ChatEntryChoice['customConfig'],): Model<Api> | null {switch (providerId) {+ case 'orkas-api':+ return buildOrkasApiModel(modelId);case 'moonshot':return buildMoonshotModel(modelId);case 'deepseek':@@ -928,6 +934,20 @@ export async function buildRunner(params: BuildRunnerParams): Promise<{...(params.hasProducedPath ? { hasProducedPath: params.hasProducedPath } : {}),})]: [];+ const videoGenTools: AgentTool[] = uid+ ? [createVideoGenTool({+ userId: uid,+ ...(params.cid ? { cid: params.cid } : {}),+ ...(params.conversationTitle ? { conversationTitle: params.conversationTitle } : {}),+ ...(params.conversationTitleUpdatedAt ? { conversationTitleUpdatedAt: params.conversationTitleUpdatedAt } : {}),+ ...(params.turnId ? { turnId: params.turnId } : {}),+ ...(agentId ? { agentId } : {}),+ ...(agentName ? { agentName } : {}),+ ...(params.projectId ? { projectId: params.projectId } : {}),+ ...(params.onFileWritten ? { onFileWritten: params.onFileWritten } : {}),+ ...(params.hasProducedPath ? { hasProducedPath: params.hasProducedPath } : {}),+ })]+ : [];const speechGenTools: AgentTool[] = uid? [createGenerateSpeechTool({userId: uid,@@ -1088,6 +1108,7 @@ export async function buildRunner(params: BuildRunnerParams): Promise<{...kbTools,...chatHistoryTools,...imageGenTools,+ ...videoGenTools,...speechGenTools,...videoStudioTools,...imageStudioTools,@@ -1473,6 +1494,10 @@ export async function buildRunner(params: BuildRunnerParams): Promise<{params.onCandidateChosen,params.onCandidatesObserved,params.providerFirstEventTimeoutMs,+ {+ conversationId: params.cid,+ turnId: params.turnId,+ },);// Inject the rotating provider into BOTH the factory slot AND the// pre-built instance cache. ProviderRegistry.get() short-circuits on@@ -1672,9 +1697,14 @@ export function openSkillSourcesExposureFromSessionId(sessionId: string): boolea* Extend the switch when a new id is added to `EXTERNAL_API_PROVIDERS`.* Async because the underlying factories await core-agent dynamic import.*/-async function buildExternalProvider(choice: ChatEntryChoice): Promise<LLMProvider> {+async function buildExternalProvider(+ choice: ChatEntryChoice,+ usageContext?: OrkasApiUsageContext,+): Promise<LLMProvider> {const { provider: providerId, apiKey, model: modelId } = choice;switch (providerId) {+ case 'orkas-api':+ return await createOrkasApiProvider({ apiKey, modelId, usageContext });case 'moonshot':return await createMoonshotProvider({ apiKey, modelId });case 'deepseek':@@ -1721,6 +1751,7 @@ async function buildRotatingProvider(onCandidateChosen?: (info: { profileId: string; providerId: string; modelId: string }) => void,onCandidatesObserved?: (info: { candidateCount: number; availableCandidateCount: number }) => void,firstEventTimeoutMs?: number,+ usageContext?: OrkasApiUsageContext,): Promise<LLMProvider> {const candidates: RotatingCandidate[] = group.map((choice) => {const candProviderId = choice.provider;@@ -1747,7 +1778,7 @@ async function buildRotatingProvider(: {}),build: async () => {if (isExternal) {- return buildExternalProvider(choice);+ return buildExternalProvider(choice, usageContext);}if (resolvedModel?.isConfiguredFallback) {log.info('using configured model fallback', {diff --git a/src/main/model/core-agent/search-adapters.ts b/src/main/model/core-agent/search-adapters.tsindex 43891345..20b4b432 100644--- a/src/main/model/core-agent/search-adapters.ts+++ b/src/main/model/core-agent/search-adapters.ts@@ -14,6 +14,13 @@import type { SearchProfile } from '../../features/auth';import { createLogger } from '../../logger';+import {+ ORKAS_API_BASE_URL,+ ORKAS_API_KEYS_URL,+ ORKAS_API_PROVIDER,+ orkasApiUsageHeaders,+ type OrkasApiUsageContext,+} from '../../features/orkas_api';const log = createLogger('search-adapters');@@ -52,6 +59,40 @@ function clamp(n: number, min: number, max: number): number {return Math.max(min, Math.min(max, n));}+// ── Orkas public search API ─────────────────────────────────────────────++async function orkasApiSearch(+ profile: SearchProfile,+ query: string,+ count: number,+ context?: OrkasApiUsageContext,+): Promise<SearchAdapterResult> {+ const resp = await fetchWithTimeout(`${ORKAS_API_BASE_URL}/search`, {+ method: 'POST',+ headers: {+ Authorization: `Bearer ${profile.apiKey}`,+ 'Content-Type': 'application/json',+ ...orkasApiUsageHeaders(context),+ },+ body: JSON.stringify({ query, max_results: clamp(count, 1, 20) }),+ });+ if (!resp.ok) {+ const text = await resp.text().catch(() => '');+ throw new Error(`Orkas Search ${resp.status}: ${text.slice(0, 300)}`);+ }+ const data = (await resp.json()) as {+ results?: Array<{ title?: string; url?: string; snippet?: string }>;+ };+ return {+ provider: ORKAS_API_PROVIDER,+ results: (data.results || []).map((result) => ({+ title: String(result.title || ''),+ url: String(result.url || ''),+ snippet: String(result.snippet || ''),+ })).filter((result) => result.url),+ };+}+// ── Tavily ──────────────────────────────────────────────────────────────async function tavilySearch(profile: SearchProfile, query: string, count: number): Promise<SearchAdapterResult> {@@ -241,9 +282,15 @@ async function metasoSearch(profile: SearchProfile, query: string, count: number// ── Registry ────────────────────────────────────────────────────────────-export type SearchAdapter = (profile: SearchProfile, query: string, count: number) => Promise<SearchAdapterResult>;+export type SearchAdapter = (+ profile: SearchProfile,+ query: string,+ count: number,+ context?: OrkasApiUsageContext,+) => Promise<SearchAdapterResult>;export const searchAdaptersByProvider: Record<string, SearchAdapter> = {+ [ORKAS_API_PROVIDER]: orkasApiSearch,tavily: tavilySearch,serper: serperSearch,'brave-search': braveApiSearch,@@ -254,6 +301,7 @@ export const searchAdaptersByProvider: Record<string, SearchAdapter> = {/** Display labels for provider ids — used by both the settings UI and the* formatted tool result so the LLM knows which API answered. */export const SEARCH_PROVIDER_LABEL: Record<string, string> = {+ [ORKAS_API_PROVIDER]: 'Orkas · Search',tavily: 'Tavily',serper: 'Serper','brave-search': 'Brave',@@ -263,6 +311,7 @@ export const SEARCH_PROVIDER_LABEL: Record<string, string> = {/** Documentation URL shown next to the API-key input in the settings UI. */export const SEARCH_PROVIDER_DOCS: Record<string, string> = {+ [ORKAS_API_PROVIDER]: ORKAS_API_KEYS_URL,tavily: 'https://tavily.com/',serper: 'https://serper.dev/','brave-search': 'https://brave.com/search/api/',@@ -274,10 +323,10 @@ export async function runSearchAdapter(profile: SearchProfile,query: string,count: number,- _context?: unknown,+ context?: OrkasApiUsageContext,): Promise<SearchAdapterResult> {const adapter = searchAdaptersByProvider[profile.provider];if (!adapter) throw new Error(`no search adapter registered for provider "${profile.provider}"`);log.debug('runSearchAdapter', { provider: profile.provider, count });- return adapter(profile, query, count);+ return adapter(profile, query, count, context);}diff --git a/src/main/model/core-agent/tool-catalog.ts b/src/main/model/core-agent/tool-catalog.tsindex 007b77d3..8980c546 100644--- a/src/main/model/core-agent/tool-catalog.ts+++ b/src/main/model/core-agent/tool-catalog.ts@@ -169,6 +169,7 @@ export const TOOL_CATALOG: readonly ToolCatalogEntry[] = [{ name: 'generate_image', loadGroups: ['media.image'], permission: 'localExec', summary: 'Generate an image into the workspace.' },{ name: 'image_studio', loadGroups: ['media.image'], permission: 'localExec', ownerAgent: IMAGE_STUDIO_AGENT_ID, summary: 'ImageStudio-owned QA and export runtime.' },+ { name: 'generate_video', loadGroups: ['media.video'], permission: 'localExec', summary: 'Generate or edit a short video into the workspace.' },{ name: 'video_studio', loadGroups: ['media.video'], permission: 'localExec', ownerAgent: VIDEO_STUDIO_AGENT_ID, summary: 'VideoStudio-owned production runtime.' },{ name: 'generate_speech', loadGroups: ['media.speech'], permission: 'localExec', summary: 'Generate speech audio.' },diff --git a/src/main/model/core-agent/video-gen-tool.ts b/src/main/model/core-agent/video-gen-tool.tsnew file mode 100644index 00000000..02b6f1aa--- /dev/null+++ b/src/main/model/core-agent/video-gen-tool.ts@@ -0,0 +1,355 @@+/** `generate_video` tool backed by the configured Orkas public API key. */++import * as fs from 'node:fs/promises';+import * as path from 'node:path';++import type { AgentTool, ToolContext, ToolResult } from '#core-agent';+import { generateVideo } from '../../features/video_gen';+import { isPathAllowed } from '../../util/path-sandbox';+import { uniquifyPath, renderRenameSignal } from '../../util/uniquify-path';+import { noteGeneration, regenerationWarning } from '../../util/generation-guard';+import { getWorkspacePath } from '../../features/user_workspace';+import { chatAttachmentDirForConversation } from '../../util/project-layout';+import { createLogger } from '../../logger';+import { logErrorRef, logPathRef, maskId } from '../../util/log-redact';+import { sanitizeLogTextForUpload } from '../../util/log-sanitize';+import { versionedChatMediaLocalUrl } from '../../util/chat-media-url';+import {+ beginVideoProductionGeneration,+ finishVideoProductionGeneration,+ videoProductionControlStatePath,+ type VideoProductionGenerationTransaction,+} from '../../features/video_production_control';+import { VIDEO_STUDIO_AGENT_ID } from './tool-catalog';++const log = createLogger('video-gen-tool');+const CREDITS_EXHAUSTED_MESSAGE =+ 'E_CREDITS_EXHAUSTED: The configured Orkas API key does not have enough credits for this clip. '+ + 'Do not retry until the user tops up the API account; already-produced clips remain saved.';++export interface VideoGenToolOpts {+ userId: string;+ cid?: string;+ conversationTitle?: string;+ conversationTitleUpdatedAt?: number;+ turnId?: string;+ agentId?: string;+ agentName?: string;+ projectId?: string;+ onFileWritten?: (absPath: string) => void | Promise<void>;+ hasProducedPath?: (absPath: string) => boolean;+}++function allowedRoots(opts: VideoGenToolOpts): string[] {+ const roots: string[] = [];+ try {+ const workspace = getWorkspacePath(opts.userId, opts.projectId);+ if (workspace) roots.push(workspace);+ } catch (err) {+ log.warn('resolve workspace failed', {+ user_id: maskId(opts.userId),+ project_id: maskId(opts.projectId),+ error: logErrorRef(err),+ });+ }+ if (opts.cid) {+ try { roots.push(chatAttachmentDirForConversation(opts.userId, opts.cid)); }+ catch (err) {+ log.warn('resolve attachment dir failed', {+ user_id: maskId(opts.userId),+ cid: maskId(opts.cid),+ error: logErrorRef(err),+ });+ }+ }+ return roots;+}++function resolveAbs(ctx: ToolContext, value: string): string {+ return path.resolve(ctx.workingDir ?? '.', value);+}++function withMp4Extension(value: string): string {+ const extension = path.extname(value);+ if (extension.toLowerCase() === '.mp4') return value;+ return extension ? `${value.slice(0, -extension.length)}.mp4` : `${value}.mp4`;+}++function stringList(value: unknown): string[] {+ return Array.isArray(value)+ ? value.map(String).map((item) => item.trim()).filter(Boolean)+ : [];+}++export function createVideoGenTool(opts: VideoGenToolOpts): AgentTool {+ return {+ name: 'generate_video',+ description: 'Generate or edit a short MP4 with the configured video service and save it locally.',+ inputSchema: {+ type: 'object',+ properties: {+ prompt: {+ type: 'string',+ description: 'Video description, including subject, motion, camera movement, scene, style, and timing.',+ },+ output_path: {+ type: 'string',+ description: 'Workspace/attachment output path. .mp4 is optional and collisions are auto-suffixed.',+ },+ reference_image_urls: {+ type: 'array',+ items: { type: 'string' },+ description: 'Optional public HTTPS image URLs, up to nine.',+ },+ reference_image_paths: {+ type: 'array',+ items: { type: 'string' },+ description: 'Optional local image paths. A reusable provider URL must be available for each file.',+ },+ reference_video_urls: {+ type: 'array',+ items: { type: 'string' },+ description: 'Optional public HTTPS video URLs, up to three.',+ },+ reference_video_paths: {+ type: 'array',+ items: { type: 'string' },+ description: 'Optional local video paths. A reusable provider URL must be available for each file.',+ },+ operation: {+ type: 'string',+ description: 'generate (default) or edit. edit requires a reference video.',+ },+ ratio: {+ type: 'string',+ description: '16:9, 9:16, 1:1, 4:3, 3:4, or 21:9.',+ },+ duration: {+ type: 'number',+ description: 'Duration from 4 to 15 seconds. Default 5.',+ },+ resolution: {+ type: 'string',+ description: '480p, 720p (default), or 1080p.',+ },+ quality: {+ type: 'string',+ description: 'balanced (default) or quality.',+ },+ generate_audio: {+ type: 'boolean',+ description: 'Whether to request generated audio. Default true.',+ },+ production_plan_path: {+ type: 'string',+ description: 'VideoStudio only: approved project/plan.json for this billable segment.',+ },+ production_segment_id: {+ type: 'string',+ description: 'VideoStudio only: approved generate-segment id.',+ },+ },+ required: ['prompt', 'output_path'],+ },+ async execute(input, ctx) {+ const prompt = String(input.prompt ?? '').trim();+ const outputPathRaw = String(input.output_path ?? '').trim();+ if (!prompt) return { content: 'prompt is required', isError: true } as ToolResult;+ if (!outputPathRaw) return { content: 'output_path is required', isError: true } as ToolResult;++ const requestedAbs = withMp4Extension(resolveAbs(ctx, outputPathRaw));+ const videoStudioControlled = opts.agentId === VIDEO_STUDIO_AGENT_ID;+ const unique = videoStudioControlled+ ? { finalPath: requestedAbs, renamed: false }+ : await uniquifyPath(requestedAbs, opts.hasProducedPath || (() => false));+ const outputAbs = unique.finalPath;+ const roots = allowedRoots(opts);+ if (!isPathAllowed(outputAbs, roots)) {+ return {+ content: `E_PATH_OUT_OF_SCOPE: output_path is outside the current scope (workspace + attachments): ${outputAbs}`,+ isError: true,+ } as ToolResult;+ }++ const referenceImageUrls = stringList(input.reference_image_urls);+ const referenceImageInputs = stringList(input.reference_image_paths);+ const referenceVideoUrls = stringList(input.reference_video_urls);+ const referenceVideoInputs = stringList(input.reference_video_paths);+ if (referenceImageUrls.length + referenceImageInputs.length > 9) {+ return { content: 'reference images: at most 9 entries allowed', isError: true } as ToolResult;+ }+ if (referenceVideoUrls.length + referenceVideoInputs.length > 3) {+ return { content: 'reference videos: at most 3 entries allowed', isError: true } as ToolResult;+ }+ const operation = input.operation === 'edit' ? 'edit' : 'generate';+ if (operation === 'edit' && referenceVideoUrls.length + referenceVideoInputs.length < 1) {+ return { content: 'operation=edit requires at least one reference video', isError: true } as ToolResult;+ }++ const resolveReferencePaths = async (values: string[], field: string): Promise<string[]> => {+ const out: string[] = [];+ for (const raw of values) {+ const absolute = resolveAbs(ctx, raw);+ if (!isPathAllowed(absolute, roots)) {+ throw new Error(`E_PATH_OUT_OF_SCOPE: ${field} is outside scope: ${absolute}`);+ }+ const stat = await fs.stat(absolute).catch(() => null);+ if (!stat?.isFile()) throw new Error(`${field} entry is not a file: ${absolute}`);+ out.push(absolute);+ }+ return out;+ };++ let referenceImagePaths: string[];+ let referenceVideoPaths: string[];+ try {+ referenceImagePaths = await resolveReferencePaths(referenceImageInputs, 'reference_image_paths');+ referenceVideoPaths = await resolveReferencePaths(referenceVideoInputs, 'reference_video_paths');+ } catch (err) {+ return { content: (err as Error).message, isError: true } as ToolResult;+ }++ let productionPlanAbs = '';+ let productionStatePath = '';+ let productionTransaction: VideoProductionGenerationTransaction | undefined;+ if (videoStudioControlled) {+ const planRaw = String(input.production_plan_path ?? '').trim();+ const segmentId = String(input.production_segment_id ?? '').trim();+ if (!planRaw || !segmentId) {+ return {+ content: 'E_VIDEO_PRODUCTION_CONTEXT_REQUIRED: VideoStudio generate_video requires production_plan_path and production_segment_id.',+ isError: true,+ } as ToolResult;+ }+ productionPlanAbs = resolveAbs(ctx, planRaw);+ if (!isPathAllowed(productionPlanAbs, roots)) {+ return { content: `E_PATH_OUT_OF_SCOPE: production_plan_path is outside scope: ${productionPlanAbs}`, isError: true } as ToolResult;+ }+ const planStat = await fs.stat(productionPlanAbs).catch(() => null);+ if (!planStat?.isFile()) {+ return { content: 'E_VIDEO_PRODUCTION_PLAN_MISSING: production_plan_path is not a file', isError: true } as ToolResult;+ }+ productionStatePath = videoProductionControlStatePath({+ userId: opts.userId,+ ...(opts.projectId ? { projectId: opts.projectId } : {}),+ planPath: productionPlanAbs,+ });+ try {+ const begun = await beginVideoProductionGeneration({+ statePath: productionStatePath,+ planPath: productionPlanAbs,+ segmentId,+ kind: 'video',+ outputPath: outputAbs,+ request: {+ prompt,+ operation,+ reference_image_urls: referenceImageUrls,+ reference_image_paths: referenceImageInputs,+ reference_video_urls: referenceVideoUrls,+ reference_video_paths: referenceVideoInputs,+ ...(typeof input.ratio === 'string' ? { ratio: input.ratio } : {}),+ ...(typeof input.duration === 'number' ? { duration: input.duration } : {}),+ ...(typeof input.resolution === 'string' ? { resolution: input.resolution } : {}),+ ...(typeof input.quality === 'string' ? { quality: input.quality } : {}),+ generate_audio: input.generate_audio !== false,+ },+ });+ if (begun.status === 'reused') {+ if (opts.onFileWritten) await opts.onFileWritten(begun.transaction.output_path);+ return {+ content: `VideoStudio reused the completed transaction for segment ${segmentId}: ${begun.transaction.output_path}. Show it with: [video](${versionedChatMediaLocalUrl(begun.transaction.output_path)})`,+ } as ToolResult;+ }+ productionTransaction = begun.transaction;+ } catch (err) {+ return { content: (err as Error).message, isError: true } as ToolResult;+ }+ }++ const result = await generateVideo({+ prompt,+ outputAbsPath: outputAbs,+ ...(referenceImageUrls.length ? { referenceImageUrls } : {}),+ ...(referenceImagePaths.length ? { referenceImagePaths } : {}),+ ...(referenceVideoUrls.length ? { referenceVideoUrls } : {}),+ ...(referenceVideoPaths.length ? { referenceVideoPaths } : {}),+ operation,+ ...(typeof input.ratio === 'string' ? { ratio: input.ratio } : {}),+ ...(typeof input.duration === 'number' ? { duration: input.duration } : {}),+ ...(typeof input.resolution === 'string' ? { resolution: input.resolution } : {}),+ ...(input.quality === 'balanced' || input.quality === 'quality' ? { quality: input.quality } : {}),+ generateAudio: input.generate_audio !== false,+ ...(ctx.signal ? { signal: ctx.signal } : {}),+ usageContext: {+ conversationId: opts.cid,+ turnId: opts.turnId,+ },+ onProgress: (event) => ctx.emitProgress?.({+ phase: event.phase,+ message: event.message,+ ...(event.data ? { data: event.data } : {}),+ }),+ });++ if (result.ok === false) {+ if (productionTransaction) {+ try {+ await finishVideoProductionGeneration({+ statePath: productionStatePath,+ planPath: productionPlanAbs,+ transactionId: productionTransaction.transaction_id,+ segmentId: productionTransaction.segment_id,+ kind: 'video',+ ok: false,+ errorCode: result.errorCode,+ ...(result.taskId ? { providerTaskId: result.taskId } : {}),+ });+ } catch (err) {+ return {+ content: `${sanitizeLogTextForUpload((err as Error).message)}; provider error=[${result.errorCode}] ${sanitizeLogTextForUpload(result.message)}`,+ isError: true,+ } as ToolResult;+ }+ }+ return {+ content: result.errorCode === 'CREDITS_EXHAUSTED'+ ? CREDITS_EXHAUSTED_MESSAGE+ : `[${result.errorCode}] ${sanitizeLogTextForUpload(result.message)}`,+ isError: true,+ } as ToolResult;+ }++ if (productionTransaction) {+ try {+ await finishVideoProductionGeneration({+ statePath: productionStatePath,+ planPath: productionPlanAbs,+ transactionId: productionTransaction.transaction_id,+ segmentId: productionTransaction.segment_id,+ kind: 'video',+ ok: true,+ outputPath: result.path,+ providerTaskId: result.taskId,+ });+ } catch (err) {+ return { content: sanitizeLogTextForUpload((err as Error).message), isError: true } as ToolResult;+ }+ }++ if (opts.onFileWritten) {+ try { await opts.onFileWritten(result.path); }+ catch (err) {+ log.warn('onFileWritten callback failed', { path: logPathRef(result.path), error: logErrorRef(err) });+ }+ }+ const guardNote = regenerationWarning(noteGeneration(opts.cid, requestedAbs), 'video');+ const summary = `Video written to ${result.path} (${result.bytes} bytes, task ${result.taskId}, ${result.provider}/${result.model}). `+ + `Show it to the user with: [video](${versionedChatMediaLocalUrl(result.path)})`+ + (guardNote ? `\n${guardNote}` : '');+ return {+ content: unique.renamed ? `${summary}${renderRenameSignal(requestedAbs, result.path)}` : summary,+ } as ToolResult;+ },+ };+}diff --git a/src/main/model/provider_catalog.ts b/src/main/model/provider_catalog.tsindex f28e555b..27e5cfdf 100644--- a/src/main/model/provider_catalog.ts+++ b/src/main/model/provider_catalog.ts@@ -40,6 +40,12 @@ import {getConfiguredProviderModels,} from '../features/client_config';import type { Api, Model } from '@earendil-works/pi-ai';+import {+ ORKAS_API_IMAGE_MODEL,+ ORKAS_API_KEYS_URL,+ ORKAS_API_LLM_MODELS,+ ORKAS_API_PROVIDER,+} from '../features/orkas_api';// ── Catalog entry shape ─────────────────────────────────────────────────@@ -77,6 +83,12 @@ export interface CatalogEntry {// Group 3: aggregators (OpenRouter)export const CATALOG: readonly CatalogEntry[] = [+ {+ id: ORKAS_API_PROVIDER,+ label: 'Orkas',+ docsUrl: ORKAS_API_KEYS_URL,+ recommended: true,+ },// DeepSeek direct (not in pi-ai 0.68.1; routed through the// openai-completions adapter in external-providers.ts).{ id: 'deepseek', label: 'DeepSeek', docsUrl: 'https://platform.deepseek.com/api_keys' },@@ -127,7 +139,10 @@ export const CATALOG: readonly CatalogEntry[] = [//// Providers without an entry here expose no selectable chat models.-export const CURATED_MODELS = DEFAULT_PROVIDER_MODELS;+export const CURATED_MODELS: Readonly<Record<string, readonly ProviderModelEntry[]>> = {+ ...DEFAULT_PROVIDER_MODELS,+ [ORKAS_API_PROVIDER]: ORKAS_API_LLM_MODELS,+};export function curatedModelsFor(providerId: string): ProviderModelEntry[] {const configured = getConfiguredProviderModels(providerId);@@ -706,7 +721,7 @@ export interface CustomOpenAICompatibleRuntimeConfig {* provider registry. `listProviders()` treats these as API-key-capable* even though `listPiProviders()` doesn't list them.*/-export const EXTERNAL_API_PROVIDERS: readonly string[] = ['moonshot', 'deepseek', 'doubao', 'custom'];+export const EXTERNAL_API_PROVIDERS: readonly string[] = [ORKAS_API_PROVIDER, 'moonshot', 'deepseek', 'doubao', 'custom'];// ── Image-generation capability map ─────────────────────────────────────//@@ -726,14 +741,24 @@ export const EXTERNAL_API_PROVIDERS: readonly string[] = ['moonshot', 'deepseek'// Adding a new provider: add an entry here AND a matching adapter in// `features/image_gen.ts::dispatchImageGen`.-export type ImageGenCapability = ConfigImageGenCapability;+export type ImageGenCapability = Omit<ConfigImageGenCapability, 'api'> & {+ api: ConfigImageGenCapability['api'] | 'orkas';+};-export const IMAGE_GEN_BY_PROVIDER = DEFAULT_IMAGE_GEN_BY_PROVIDER;+export const IMAGE_GEN_BY_PROVIDER: Readonly<Record<string, ImageGenCapability>> = {+ ...DEFAULT_IMAGE_GEN_BY_PROVIDER,+ [ORKAS_API_PROVIDER]: {+ model: ORKAS_API_IMAGE_MODEL,+ api: 'orkas',+ supportsEdit: true,+ },+};-export function findImageGenCapability(providerId: string): ConfigImageGenCapability | null {+export function findImageGenCapability(providerId: string): ImageGenCapability | null {const base = IMAGE_GEN_BY_PROVIDER[providerId] || null;const configured = getConfiguredImageGenCapability(providerId);if (!configured) return base;+ if (base?.api === 'orkas') return base;if (!base) {if (!configured.model || !configured.api) return null;return {diff --git a/src/renderer/index.html b/src/renderer/index.htmlindex c349c151..7d3faff8 100644--- a/src/renderer/index.html+++ b/src/renderer/index.html@@ -1101,6 +1101,20 @@<!-- ───────────────────────── 配置 ───────────────────────── --><div class="settings-tab-pane" data-settings-pane="credentials" hidden>+ <div class="settings-group settings-orkas-api-group" id="settings-orkas-api-group">+ <div class="settings-group-head settings-orkas-api-head">+ <div class="settings-group-head-main">+ <div class="settings-group-title" data-i18n="settings.orkas_api.title">Orkas official services</div>+ <div class="settings-group-sub" data-i18n="settings.orkas_api.sub">Use one API Key to quickly configure models, search, images, speech, and video.</div>+ </div>+ <button type="button" class="btn btn-sm" id="settings-orkas-api-create-key" data-i18n="settings.orkas_api.create_key">Create API Key</button>+ </div>+ <div class="settings-row settings-orkas-api-configure-row">+ <input type="password" class="form-input" id="settings-orkas-api-key-input" autocomplete="new-password" spellcheck="false" data-i18n-placeholder="settings.orkas_api.key_placeholder" placeholder="Enter API Key" />+ <button type="button" class="btn btn-primary" id="settings-orkas-api-configure" data-i18n="settings.orkas_api.configure">Configure</button>+ </div>+ <div class="settings-status settings-orkas-api-status" id="settings-orkas-api-status" aria-live="polite"></div>+ </div><div class="settings-section-note" data-i18n="settings.section.models_note">API keys and authorization data are stored only on this device — never synced or sent elsewhere.</div><div class="settings-group settings-model-auth-group">diff --git a/src/renderer/locales/en.json b/src/renderer/locales/en.jsonindex 229a9632..cd3beac8 100644--- a/src/renderer/locales/en.json+++ b/src/renderer/locales/en.json@@ -271,11 +271,17 @@"new_chat.model_picker.loading": "Loading…","new_chat.model_picker.aria_label": "Choose model","new_chat.model_picker.empty": "No available models",- "new_chat.model_picker.group_custom": "Custom models",+ "new_chat.model_picker.group_official": "Official models",+ "new_chat.model_picker.group_custom": "User-configured models","new_chat.model_picker.configure": "Configure models","new_chat.model_picker.switch_failed": "Could not switch models. Try again.","new_chat.model_picker.choose_version": "Choose a model version for {account}","new_chat.model_picker.version_list": "Model versions for {account}",+ "new_chat.model_picker.official_standard_description": "For everyday tasks like Q&A, writing, and office work.",+ "new_chat.model_picker.official_pro_description": "For complex tasks like research, video, and development.",+ "new_chat.model_picker.official_detail": "{description} {includes}",+ "new_chat.model_picker.includes": "Includes: {models}",+ "new_chat.model_picker.recommended": "Recommended","new_chat.model_picker.disabled": "Disabled","new_chat.model_picker.unavailable": "Unavailable","new_chat.external_agent_entry": "Connect Codex, Claude Code & other AI tools",@@ -1329,6 +1335,18 @@"settings.section.general": "General","settings.section.models": "Models & credentials","settings.section.models_note": "API keys and authorization data are stored only on this device — never synced or sent elsewhere.",+ "settings.orkas_api.title": "Orkas official services",+ "settings.orkas_api.sub": "Use one API Key to quickly configure models, search, images, speech, and video.",+ "settings.orkas_api.create_key": "Create API Key",+ "settings.orkas_api.key_placeholder": "Enter API Key",+ "settings.orkas_api.configure": "Configure",+ "settings.orkas_api.key_required": "Enter an API Key first",+ "settings.orkas_api.configuring": "Configuring…",+ "settings.orkas_api.configure_ok": "Orkas official services configured",+ "settings.orkas_api.configure_failed": "Configuration failed",+ "settings.orkas_api.open_failed": "Could not open the API Key page",+ "settings.orkas_api.recommended": "Recommended",+ "settings.orkas_api.includes": "Includes: {models}","settings.section.tools": "Tool capabilities","settings.section.tools_note": "Search, image-gen, and video-gen API keys are stored locally only — never synced or sent off-device.","settings.delete": "Delete",diff --git a/src/renderer/locales/ja.json b/src/renderer/locales/ja.jsonindex 47c5be21..114fbd23 100644--- a/src/renderer/locales/ja.json+++ b/src/renderer/locales/ja.json@@ -259,11 +259,17 @@"new_chat.model_picker.loading": "読み込み中…","new_chat.model_picker.aria_label": "モデルを選択","new_chat.model_picker.empty": "利用可能なモデルがありません",- "new_chat.model_picker.group_custom": "カスタムモデル",+ "new_chat.model_picker.group_official": "公式モデル",+ "new_chat.model_picker.group_custom": "ユーザー設定モデル","new_chat.model_picker.configure": "モデルを設定","new_chat.model_picker.switch_failed": "モデルを切り替えられませんでした。もう一度お試しください。","new_chat.model_picker.choose_version": "{account} のモデルバージョンを選択","new_chat.model_picker.version_list": "{account} のモデルバージョン",+ "new_chat.model_picker.official_standard_description": "質問、文章作成、オフィス業務などの日常タスク向け。",+ "new_chat.model_picker.official_pro_description": "調査、動画制作、開発などの複雑なタスク向け。",+ "new_chat.model_picker.official_detail": "{description}{includes}",+ "new_chat.model_picker.includes": "含まれるモデル:{models}",+ "new_chat.model_picker.recommended": "おすすめ","new_chat.model_picker.disabled": "無効","new_chat.model_picker.unavailable": "利用不可","new_chat.external_agent_entry": "Codex、Claude Code などの AI ツールを接続",@@ -1329,6 +1335,18 @@"settings.section.general": "一般","settings.section.models": "モデルと認証情報","settings.section.models_note": "API キーと認証情報はこの端末にのみ保存され、同期や外部送信はされません。",+ "settings.orkas_api.title": "Orkas 公式サービス",+ "settings.orkas_api.sub": "1 つの API Key でモデル、検索、画像、音声、動画をまとめて設定できます。",+ "settings.orkas_api.create_key": "API Key を作成",+ "settings.orkas_api.key_placeholder": "API Key を入力",+ "settings.orkas_api.configure": "設定",+ "settings.orkas_api.key_required": "先に API Key を入力してください",+ "settings.orkas_api.configuring": "設定中…",+ "settings.orkas_api.configure_ok": "Orkas 公式サービスを設定しました",+ "settings.orkas_api.configure_failed": "設定に失敗しました",+ "settings.orkas_api.open_failed": "API Key 作成ページを開けませんでした",+ "settings.orkas_api.recommended": "おすすめ",+ "settings.orkas_api.includes": "含まれるモデル:{models}","settings.section.tools": "ツール機能","settings.section.tools_note": "検索、画像生成、動画生成の API キーはローカルにのみ保存され、同期や外部送信はされません。","settings.delete": "削除",diff --git a/src/renderer/locales/pt.json b/src/renderer/locales/pt.jsonindex fdce9a0a..59382c4a 100644--- a/src/renderer/locales/pt.json+++ b/src/renderer/locales/pt.json@@ -266,11 +266,17 @@"new_chat.model_picker.loading": "Carregando…","new_chat.model_picker.aria_label": "Escolher modelo","new_chat.model_picker.empty": "Nenhum modelo disponível",- "new_chat.model_picker.group_custom": "Modelos personalizados",+ "new_chat.model_picker.group_official": "Modelos oficiais",+ "new_chat.model_picker.group_custom": "Modelos configurados pelo usuário","new_chat.model_picker.configure": "Configurar modelos","new_chat.model_picker.switch_failed": "Não foi possível trocar de modelo. Tente novamente.","new_chat.model_picker.choose_version": "Escolher uma versão do modelo para {account}","new_chat.model_picker.version_list": "Versões do modelo para {account}",+ "new_chat.model_picker.official_standard_description": "Para tarefas diárias, como perguntas, redação e trabalho de escritório.",+ "new_chat.model_picker.official_pro_description": "Para tarefas complexas, como pesquisa, vídeo e desenvolvimento.",+ "new_chat.model_picker.official_detail": "{description} {includes}",+ "new_chat.model_picker.includes": "Inclui: {models}",+ "new_chat.model_picker.recommended": "Recomendado","new_chat.model_picker.disabled": "Desativado","new_chat.model_picker.unavailable": "Indisponível","new_chat.external_agent_entry": "Conectar Codex, Claude Code e outras ferramentas de IA",@@ -1321,6 +1327,18 @@"settings.section.general": "Geral","settings.section.models": "Modelos e credenciais","settings.section.models_note": "As chaves de API e os dados de autorização ficam apenas neste dispositivo; não são sincronizados nem enviados para outros lugares.",+ "settings.orkas_api.title": "Serviços oficiais da Orkas",+ "settings.orkas_api.sub": "Use uma API Key para configurar rapidamente modelos, pesquisa, imagens, voz e vídeo.",+ "settings.orkas_api.create_key": "Criar API Key",+ "settings.orkas_api.key_placeholder": "Insira a API Key",+ "settings.orkas_api.configure": "Configurar",+ "settings.orkas_api.key_required": "Insira primeiro uma API Key",+ "settings.orkas_api.configuring": "Configurando…",+ "settings.orkas_api.configure_ok": "Serviços oficiais da Orkas configurados",+ "settings.orkas_api.configure_failed": "Falha na configuração",+ "settings.orkas_api.open_failed": "Não foi possível abrir a página de API Key",+ "settings.orkas_api.recommended": "Recomendado",+ "settings.orkas_api.includes": "Inclui: {models}","settings.section.tools": "Capacidades da ferramenta","settings.section.tools_note": "As chaves de API de pesquisa, geração de imagem e geração de vídeo são armazenadas apenas localmente – nunca sincronizadas ou enviadas para fora do dispositivo.","settings.delete": "Excluir",diff --git a/src/renderer/locales/zh.json b/src/renderer/locales/zh.jsonindex 99d2c9a8..b4c3a34c 100644--- a/src/renderer/locales/zh.json+++ b/src/renderer/locales/zh.json@@ -271,11 +271,17 @@"new_chat.model_picker.loading": "加载中…","new_chat.model_picker.aria_label": "选择模型","new_chat.model_picker.empty": "暂无可用模型",- "new_chat.model_picker.group_custom": "自定义模型",+ "new_chat.model_picker.group_official": "官方模型",+ "new_chat.model_picker.group_custom": "用户配置模型","new_chat.model_picker.configure": "配置模型","new_chat.model_picker.switch_failed": "切换模型失败,请稍后重试。","new_chat.model_picker.choose_version": "为 {account} 选择模型版本","new_chat.model_picker.version_list": "{account} 的模型版本",+ "new_chat.model_picker.official_standard_description": "适合问答、写作、办公等日常任务。",+ "new_chat.model_picker.official_pro_description": "适合研究、视频、研发等复杂任务。",+ "new_chat.model_picker.official_detail": "{description}{includes}",+ "new_chat.model_picker.includes": "包含:{models}",+ "new_chat.model_picker.recommended": "推荐","new_chat.model_picker.disabled": "已停用","new_chat.model_picker.unavailable": "不可用","new_chat.external_agent_entry": "接入 Codex、Claude Code 等 AI 编程工具",@@ -1329,6 +1335,18 @@"settings.section.general": "通用","settings.section.models": "模型与凭证","settings.section.models_note": "所有 API Key 与授权信息只保存在本机,不上云、不外发。",+ "settings.orkas_api.title": "Orkas 官方服务",+ "settings.orkas_api.sub": "一个 API Key 可快速配置模型、搜索、图片、语音和视频。",+ "settings.orkas_api.create_key": "创建 API Key",+ "settings.orkas_api.key_placeholder": "输入 API Key",+ "settings.orkas_api.configure": "配置",+ "settings.orkas_api.key_required": "请先输入 API Key",+ "settings.orkas_api.configuring": "配置中…",+ "settings.orkas_api.configure_ok": "Orkas 官方服务配置成功",+ "settings.orkas_api.configure_failed": "配置失败",+ "settings.orkas_api.open_failed": "无法打开 API Key 创建页面",+ "settings.orkas_api.recommended": "推荐",+ "settings.orkas_api.includes": "包含:{models}","settings.section.tools": "工具能力","settings.section.tools_note": "搜索、图片与视频 API Key 只保存在本机,不上云、不外发。","settings.delete": "删除",diff --git a/src/renderer/modules/composer-model-picker.js b/src/renderer/modules/composer-model-picker.jsindex 2efccc13..21249829 100644--- a/src/renderer/modules/composer-model-picker.js+++ b/src/renderer/modules/composer-model-picker.js@@ -78,6 +78,10 @@ function _syncComposerModelChipAvailability(target) {}function _composerModelEntryLabel(entry) {+ if (_composerModelEntryIsOfficial(entry)) {+ const officialModelName = String((entry && (entry.modelName || entry.model)) || '').trim();+ if (officialModelName) return officialModelName;+ }const model = String((entry && (entry.modelName || entry.model)) || '');const modelName = model.split(/\s*·\s*/)@@ -89,10 +93,24 @@ function _composerModelEntryLabel(entry) {|| t('new_chat.model_picker.configure');}-function _composerModelEntryIsOfficial(_entry) {- // Managed/official subscription entries are filtered from the open build;- // every remaining composer entry is configured by the user.- return false;+function _composerModelEntryIsOfficial(entry) {+ return !!entry && entry.official === true && entry.provider === 'orkas-api';+}++function _composerModelMenuGroups(entries) {+ const list = Array.isArray(entries) ? entries : [];+ return [+ {+ key: 'official',+ labelKey: 'new_chat.model_picker.group_official',+ entries: list.filter(_composerModelEntryIsOfficial),+ },+ {+ key: 'custom',+ labelKey: 'new_chat.model_picker.group_custom',+ entries: list.filter((entry) => !_composerModelEntryIsOfficial(entry)),+ },+ ].filter((group) => group.entries.length > 0);}function _composerModelProviderLabel(entry) {@@ -429,6 +447,34 @@ function _openComposerModelSettings() {if (typeof _activateModelCredentialsTab === 'function') _activateModelCredentialsTab();}+function _composerModelOfficialIncludedBody(entry) {+ const included = _composerModelEntryIsOfficial(entry) && Array.isArray(entry.includedModels)+ ? entry.includedModels.filter((item) => typeof item === 'string' && item.trim())+ : [];+ return included.join(' · ');+}++function _composerModelOfficialDescription(entry) {+ if (!_composerModelEntryIsOfficial(entry)) return '';+ const configured = String((entry && entry.description) || '').trim();+ if (configured) return configured;+ let key = '';+ if (entry.model === 'orkas-llm-1.5') {+ key = 'new_chat.model_picker.official_standard_description';+ } else if (entry.model === 'orkas-llm-1.5-pro') {+ key = 'new_chat.model_picker.official_pro_description';+ }+ if (!key) return '';+ const taskDescription = t(key);+ const included = _composerModelOfficialIncludedBody(entry);+ return included+ ? t('new_chat.model_picker.official_detail', {+ description: taskDescription,+ includes: t('new_chat.model_picker.includes', { models: included }),+ })+ : taskDescription;+}+function _buildComposerModelMenuItem(entry, activeEntryId, anchor) {const isActive = entry.entryId === activeEntryId;const item = document.createElement('div');@@ -445,37 +491,59 @@ function _buildComposerModelMenuItem(entry, activeEntryId, anchor) {select.disabled = disabled;select.setAttribute('aria-disabled', disabled ? 'true' : 'false');+ const official = _composerModelEntryIsOfficial(entry);const copy = document.createElement('span');copy.className = 'composer-model-menu-copy';const title = document.createElement('span');title.className = 'composer-model-menu-title';const titleName = document.createElement('span');titleName.className = 'composer-model-menu-title-name';- titleName.textContent = _composerModelProviderLabel(entry) || _composerModelEntryLabel(entry);+ titleName.textContent = official+ ? _composerModelEntryLabel(entry)+ : (_composerModelProviderLabel(entry) || _composerModelEntryLabel(entry));title.appendChild(titleName);+ if (official && entry && entry.recommended === true) {+ const recommended = document.createElement('span');+ recommended.className = 'composer-model-menu-recommended';+ recommended.textContent = t('new_chat.model_picker.recommended');+ title.appendChild(recommended);+ }copy.appendChild(title);- const account = String((entry && entry.profileLabel) || '').trim();- const currentModelName = _composerModelEntryLabel(entry);- if (account || currentModelName) {+ const officialDescription = _composerModelOfficialDescription(entry);+ const account = official+ ? _composerModelOfficialIncludedBody(entry)+ : String((entry && entry.profileLabel) || '').trim();+ const currentModelName = official ? '' : _composerModelEntryLabel(entry);+ if (officialDescription) {+ const description = document.createElement('span');+ description.className = 'composer-model-menu-description';+ description.textContent = officialDescription;+ copy.appendChild(description);+ }+ if ((account || currentModelName) && !officialDescription) {const meta = document.createElement('span');meta.className = 'composer-model-menu-meta';- if (account) {- const accountLabel = document.createElement('span');- accountLabel.className = 'composer-model-menu-account-label';- accountLabel.textContent = account;- meta.appendChild(accountLabel);- }- if (account && currentModelName) {- const separator = document.createElement('span');- separator.className = 'composer-model-menu-meta-separator';- separator.textContent = ' · ';- meta.appendChild(separator);- }- if (currentModelName) {- const modelLabel = document.createElement('span');- modelLabel.className = 'composer-model-menu-current-model';- modelLabel.textContent = currentModelName;- meta.appendChild(modelLabel);+ if (official) {+ meta.textContent = t('new_chat.model_picker.includes', { models: account });+ } else {+ if (account) {+ const accountLabel = document.createElement('span');+ accountLabel.className = 'composer-model-menu-account-label';+ accountLabel.textContent = account;+ meta.appendChild(accountLabel);+ }+ if (account && currentModelName) {+ const separator = document.createElement('span');+ separator.className = 'composer-model-menu-meta-separator';+ separator.textContent = ' · ';+ meta.appendChild(separator);+ }+ if (currentModelName) {+ const modelLabel = document.createElement('span');+ modelLabel.className = 'composer-model-menu-current-model';+ modelLabel.textContent = currentModelName;+ meta.appendChild(modelLabel);+ }}copy.appendChild(meta);}@@ -506,7 +574,7 @@ function _buildComposerModelMenuItem(entry, activeEntryId, anchor) {});item.appendChild(select);- const versions = entry.modelEditable !== false+ const versions = !official && entry.modelEditable !== false? _composerModelVersionOptions(entry): [];if (!disabled && versions.length > 1) {@@ -585,23 +653,23 @@ function _buildComposerModelMenuItem(entry, activeEntryId, anchor) {return item;}-function _buildComposerModelMenuGroup(entries, activeEntryId, anchor) {+function _buildComposerModelMenuGroup(group, activeEntryId, anchor) {const section = document.createElement('div');section.className = 'composer-model-menu-group';- section.dataset.modelGroup = 'custom';+ section.dataset.modelGroup = group.key;section.setAttribute('role', 'group');- section.setAttribute('aria-label', t('new_chat.model_picker.group_custom'));+ section.setAttribute('aria-label', t(group.labelKey));const header = document.createElement('div');header.className = 'composer-model-menu-group-header';const label = document.createElement('span');label.className = 'composer-model-menu-group-label';- label.textContent = t('new_chat.model_picker.group_custom');+ label.textContent = t(group.labelKey);label.setAttribute('aria-hidden', 'true');header.appendChild(label);section.appendChild(header);- entries.forEach((entry) => {+ group.entries.forEach((entry) => {section.appendChild(_buildComposerModelMenuItem(entry, activeEntryId, anchor));});return section;@@ -626,11 +694,9 @@ async function _toggleComposerModelMenu(anchor) {if (_composerModelEntries.length) {const activeEntryId = _composerModelEntries[0]?.entryId || '';- menu.appendChild(_buildComposerModelMenuGroup(- _composerModelEntries,- activeEntryId,- anchor,- ));+ _composerModelMenuGroups(_composerModelEntries).forEach((group) => {+ menu.appendChild(_buildComposerModelMenuGroup(group, activeEntryId, anchor));+ });} else {const empty = document.createElement('div');empty.className = 'composer-model-menu-empty';diff --git a/src/renderer/modules/settings.js b/src/renderer/modules/settings.jsindex 9a63f254..1e6ae1cb 100644--- a/src/renderer/modules/settings.js+++ b/src/renderer/modules/settings.js@@ -12,6 +12,8 @@const _settingsLog = createLogger('settings');const _OPENROUTER_CUSTOM_MODEL_VALUE = '__openrouter_custom_model__';+const _ORKAS_API_PROVIDER_ID = 'orkas-api';+const _ORKAS_API_KEYS_URL = 'https://orkas.ai/views/account/account.html#api-keys';function _settingsIsOpenRouterCustomModel(providerId, modelId) {return providerId === 'openrouter' && modelId === _OPENROUTER_CUSTOM_MODEL_VALUE;@@ -102,6 +104,7 @@ async function loadSettings() {_settingsBindTaskNotificationsOnce();_settingsBindClientConfigOnce();_settingsBindRecycleBinOnce();+ _settingsBindOrkasApiOnce();_settingsSyncLanguageRadio();await Promise.all([_settingsSafeCall('settings providers refresh', _settingsRefreshProviders),@@ -979,6 +982,8 @@ window.addEventListener('i18n-change', () => {_settingsRenderSearchSection();_settingsRenderImageSection();_settingsRenderVideoSection();+ _settingsRenderTtsEntries();+ _settingsRenderOrkasApiCard();_settingsRenderMetacognition();});@@ -991,6 +996,88 @@ async function _settingsRefreshEntries() {const res = await window.orkas.invoke('auth.listEntries', { includeUnavailable: true });_settingsState.entries = (res && res.ok && Array.isArray(res.entries)) ? res.entries : [];if (typeof trackModelConfigSnapshot === 'function') trackModelConfigSnapshot(_settingsState.entries);+ _settingsRenderOrkasApiCard();+}++function _settingsRenderOrkasApiCard() {+ const status = document.getElementById('settings-orkas-api-status');+ const key = status && status.getAttribute('data-i18n');+ if (status && key) status.textContent = t(key);+}++async function _settingsRefreshAllCredentialSections() {+ await Promise.all([+ _settingsRefreshProviders(),+ _settingsRefreshEntries(),+ _settingsRefreshSearchProfiles(),+ _settingsRefreshImageProfiles(),+ _settingsRefreshVideoProfiles(),+ _settingsRefreshTtsProfiles(),+ ]);+ await _settingsRenderPicker();+ await _settingsRenderEntries();+ _settingsRenderSearchSection();+ _settingsRenderImageSection();+ _settingsRenderVideoSection();+ _settingsRenderTtsEntries();+ _settingsRenderOrkasApiCard();+}++function _settingsBindOrkasApiOnce() {+ if (_settingsState.orkasApiBound) return;+ const createBtn = document.getElementById('settings-orkas-api-create-key');+ const configureBtn = document.getElementById('settings-orkas-api-configure');+ const keyInput = document.getElementById('settings-orkas-api-key-input');+ if (!createBtn || !configureBtn || !keyInput) return;+ _settingsState.orkasApiBound = true;++ createBtn.addEventListener('click', async () => {+ const res = await window.orkas.invoke('auth.openExternal', { url: _ORKAS_API_KEYS_URL });+ if (!res || !res.ok) {+ _settingsSetI18nStatus('settings-orkas-api-status', 'error', 'settings.orkas_api.open_failed');+ }+ });++ const configure = async () => {+ const apiKey = String(keyInput.value || '').trim();+ if (!apiKey) {+ _settingsSetI18nStatus('settings-orkas-api-status', 'error', 'settings.orkas_api.key_required');+ return;+ }+ configureBtn.disabled = true;+ _settingsSetI18nStatus('settings-orkas-api-status', 'busy', 'settings.orkas_api.configuring');+ try {+ const res = await window.orkas.invoke('orkasApi.configureAll', { apiKey });+ if (!res || !res.ok) {+ if (res && res.error) {+ _settingsSetStatus('settings-orkas-api-status', 'error', res.error);+ } else {+ _settingsSetI18nStatus('settings-orkas-api-status', 'error', 'settings.orkas_api.configure_failed');+ }+ return;+ }+ keyInput.value = '';+ await _settingsRefreshAllCredentialSections();+ if (typeof refreshModelGuard === 'function') {+ await Promise.resolve(refreshModelGuard()).catch(() => {});+ }+ _settingsSetI18nStatus('settings-orkas-api-status', 'ok', 'settings.orkas_api.configure_ok');+ } catch (err) {+ if (err && err.message) {+ _settingsSetStatus('settings-orkas-api-status', 'error', err.message);+ } else {+ _settingsSetI18nStatus('settings-orkas-api-status', 'error', 'settings.orkas_api.configure_failed');+ }+ } finally {+ configureBtn.disabled = false;+ }+ };+ configureBtn.addEventListener('click', configure);+ keyInput.addEventListener('keydown', (event) => {+ if (event.key !== 'Enter' || event.isComposing) return;+ event.preventDefault();+ void configure();+ });}async function _settingsGetModels(providerId) {@@ -1764,7 +1851,7 @@ function _settingsRenderEntries() {}const displayedEntries = _settingsState.entries.filter((entry) => (- entry && entry.official !== true && entry.profileType !== 'managed'+ entry && entry.profileType !== 'managed'));displayedEntries.forEach((entry, idx) => {container.appendChild(_settingsRenderEntryRow(entry, idx));@@ -1853,8 +1940,12 @@ function _settingsRenderEntryRow(entry, priorityIdx) {const primary = document.createElement('div');primary.className = 'entry-primary';const providerName = entry.providerLabelKey ? t(entry.providerLabelKey) : (entry.providerLabel || entry.provider);+ const isOrkasApi = entry.provider === _ORKAS_API_PROVIDER_ID;+ const recommendedModelTag = isOrkasApi && entry.recommended === true+ ? `<span class="entry-model-recommended">${escapeHtml(t('settings.orkas_api.recommended'))}</span>`+ : '';const modelControl = entry.modelEditable === false- ? `<span class="entry-model-static">${escapeHtml(entry.modelName || entry.model)}</span>`+ ? `<span class="entry-model-static"><span class="entry-model-static-name">${escapeHtml(entry.modelName || entry.model)}</span>${recommendedModelTag}</span>`: '<div class="ai-select ai-select-compact entry-model-select"></div>';primary.innerHTML = `<span class="entry-provider">${escapeHtml(providerName)}</span>@@ -1894,7 +1985,10 @@ function _settingsRenderEntryRow(entry, priorityIdx) {const meta = document.createElement('div');meta.className = 'entry-meta';const badge = document.createElement('span');- if (entry.profileType === 'oauth') {+ if (isOrkasApi) {+ badge.className = 'account-type-badge';+ badge.textContent = 'Orkas';+ } else if (entry.profileType === 'oauth') {badge.className = 'account-type-badge oauth' + (entry.oauthExpired ? ' expired' : '');badge.textContent = entry.oauthExpired ? t('settings.entries.oauth_expired') : t('settings.entries.oauth_badge');} else {@@ -1903,7 +1997,16 @@ function _settingsRenderEntryRow(entry, priorityIdx) {}meta.appendChild(badge);- if (entry.profileMasked) {+ if (isOrkasApi && Array.isArray(entry.includedModels) && entry.includedModels.length) {+ const included = document.createElement('span');+ included.className = 'entry-included-models';+ included.textContent = t('settings.orkas_api.includes', {+ models: entry.includedModels.join(' · '),+ });+ meta.appendChild(included);+ }++ if (entry.profileMasked && !isOrkasApi) {const mask = document.createElement('span');mask.className = 'account-mask';mask.textContent = entry.profileMasked;@@ -2075,10 +2178,19 @@ async function _settingsReload() {function _settingsSetStatus(id, kind, text) {const el = document.getElementById(id);if (!el) return;+ el.removeAttribute('data-i18n');el.textContent = text || '';el.className = 'settings-status' + (kind ? ` ${kind}` : '');}+function _settingsSetI18nStatus(id, kind, key) {+ const el = document.getElementById(id);+ if (!el) return;+ el.setAttribute('data-i18n', key);+ el.textContent = t(key);+ el.className = 'settings-status' + (kind ? ` ${kind}` : '');+}+function _settingsSetRowStatus(el, kind, text, baseCls = 'account-row-status') {if (!el) return;el.textContent = text || '';@@ -2098,7 +2210,12 @@ function _settingsVisibleApiProfiles(profiles) {));}+function _settingsOrkasServiceLabel(service) {+ return `Orkas · ${service}`;+}+const _SEARCH_PROVIDER_OPTIONS = [+ { id: 'orkas-api', label: _settingsOrkasServiceLabel('Search'), docs: _ORKAS_API_KEYS_URL },{ id: 'tavily', label: 'Tavily', docs: 'https://tavily.com/' },{ id: 'serper', label: 'Serper', docs: 'https://serper.dev/' },{ id: 'brave-search', label: 'Brave', docs: 'https://brave.com/search/api/' },@@ -2114,6 +2231,7 @@ function _searchProviderLabel(id) {async function _settingsRefreshSearchProfiles() {const res = await window.orkas.invoke('searchAuth.list');_settingsState.searchProfiles = (res && res.ok && Array.isArray(res.profiles)) ? res.profiles : [];+ _settingsRenderOrkasApiCard();}function _settingsRenderSearchSection() {@@ -2188,10 +2306,14 @@ function _settingsRenderSearchEntries() {main.className = 'entry-main';const primary = document.createElement('div');primary.className = 'entry-primary';+ const isOrkasApi = p.provider === _ORKAS_API_PROVIDER_ID;+ const providerLabel = isOrkasApi+ ? _settingsOrkasServiceLabel('Search')+ : _searchProviderLabel(p.provider);primary.innerHTML = `- <span class="entry-provider">${escapeHtml(_searchProviderLabel(p.provider))}</span>+ <span class="entry-provider">${escapeHtml(providerLabel)}</span><span class="entry-sep">·</span>- <span class="entry-account-chip">@ ${escapeHtml(p.label || 'default')}</span>+ <span class="entry-account-chip">@ ${escapeHtml(isOrkasApi ? 'Orkas' : (p.label || 'default'))}</span>${p.apiKeyMasked ? `<span class="account-mask">${escapeHtml(p.apiKeyMasked)}</span>` : ''}`;main.appendChild(primary);@@ -2236,6 +2358,7 @@ function _settingsRenderSearchEntries() {// still persists provider=doubao plus the selected model id.const _IMAGE_PROVIDER_OPTIONS = [+ { id: 'orkas-api', label: _settingsOrkasServiceLabel('Image'), docs: _ORKAS_API_KEYS_URL },{ id: 'openai', label: 'OpenAI · GPT Image 2', docs: 'https://platform.openai.com/api-keys' },{ id: 'google', label: 'Google · Nano Banana 2', docs: 'https://aistudio.google.com/app/apikey' },{ id: 'doubao', label: 'DouBao · Seedream', docs: 'https://console.volcengine.com/ark/region:ark+cn-beijing/apiKey' },@@ -2249,6 +2372,7 @@ function _imageProviderLabel(id) {async function _settingsRefreshImageProfiles() {const res = await window.orkas.invoke('imageAuth.list');_settingsState.imageProfiles = (res && res.ok && Array.isArray(res.profiles)) ? res.profiles : [];+ _settingsRenderOrkasApiCard();}function _settingsRenderImageSection() {@@ -2284,7 +2408,7 @@ async function _settingsClickAddImageKey() {if (!apiKey) { _settingsSetStatus('settings-image-status', 'error', t('settings.image.error_key_needed')); return; }_settingsSetStatus('settings-image-status', 'busy', t('settings.image.adding'));try {- const res = await window.orkas.invoke('imageAuth.add', { provider, model, apiKey, label: 'default' });+ const res = await window.orkas.invoke('imageAuth.add', { provider, apiKey, label: 'default' });if (!res || !res.ok) {_settingsSetStatus('settings-image-status', 'error', (res && res.error) || t('settings.image.add_failed'));return;@@ -2321,10 +2445,14 @@ function _settingsRenderImageEntries() {main.className = 'entry-main';const primary = document.createElement('div');primary.className = 'entry-primary';+ const isOrkasApi = p.provider === _ORKAS_API_PROVIDER_ID;+ const providerLabel = isOrkasApi+ ? _settingsOrkasServiceLabel('Image')+ : _imageProviderLabel(p.provider);primary.innerHTML = `- <span class="entry-provider">${escapeHtml(_imageProviderLabel(p.provider))}</span>+ <span class="entry-provider">${escapeHtml(providerLabel)}</span><span class="entry-sep">·</span>- <span class="entry-account-chip">@ ${escapeHtml(p.label || 'default')}</span>+ <span class="entry-account-chip">@ ${escapeHtml(isOrkasApi ? 'Orkas' : (p.label || 'default'))}</span>${p.apiKeyMasked ? `<span class="account-mask">${escapeHtml(p.apiKeyMasked)}</span>` : ''}`;main.appendChild(primary);@@ -2368,6 +2496,7 @@ function _settingsRenderImageEntries() {// User-owned provider keys only; bundled video providers stay stripped.const _VIDEO_AUTH_PROVIDER_OPTIONS = [+ { id: 'orkas-api', label: _settingsOrkasServiceLabel('Video'), docs: _ORKAS_API_KEYS_URL },{ id: 'doubao', label: 'DouBao · Seedance', docs: 'https://console.volcengine.com/ark/region:ark+cn-beijing/apiKey' },];@@ -2394,6 +2523,7 @@ async function _settingsRefreshVideoProfiles() {_settingsState.videoAuthProviderOptions = (res && res.ok && Array.isArray(res.providers) && res.providers.length)? res.providers: _VIDEO_AUTH_PROVIDER_OPTIONS;+ _settingsRenderOrkasApiCard();}function _settingsRenderVideoSection() {@@ -2474,10 +2604,14 @@ function _settingsRenderVideoEntries() {main.className = 'entry-main';const primary = document.createElement('div');primary.className = 'entry-primary';+ const isOrkasApi = p.provider === _ORKAS_API_PROVIDER_ID;+ const providerLabel = isOrkasApi+ ? _settingsOrkasServiceLabel('Video')+ : _videoProviderLabel(p.provider);primary.innerHTML = `- <span class="entry-provider">${escapeHtml(_videoProviderLabel(p.provider))}</span>+ <span class="entry-provider">${escapeHtml(providerLabel)}</span><span class="entry-sep">·</span>- <span class="entry-account-chip">@ ${escapeHtml(p.label || 'default')}</span>+ <span class="entry-account-chip">@ ${escapeHtml(isOrkasApi ? 'Orkas' : (p.label || 'default'))}</span>${p.apiKeyMasked ? `<span class="account-mask">${escapeHtml(p.apiKeyMasked)}</span>` : ''}`;main.appendChild(primary);@@ -2522,6 +2656,7 @@ async function _settingsRefreshTtsProfiles() {if (!res || !res.ok) return;_settingsState.ttsPresets = Array.isArray(res.presets) ? res.presets : [];_settingsState.ttsProfiles = Array.isArray(res.profiles) ? res.profiles : [];+ _settingsRenderOrkasApiCard();const providerEl = document.getElementById('settings-tts-provider');if (providerEl && !_settingsState.ttsProviderSel) {_settingsState.ttsProviderSel = _aiSelectMount(providerEl, { placeholder: t('settings.tts.pick_provider') });@@ -2552,7 +2687,7 @@ function _settingsTtsPreset(providerId) {}function _ttsProviderLabel(id) {- if (id === 'orkas-voice') return 'Orkas · Voice';+ if (id === _ORKAS_API_PROVIDER_ID || id === 'orkas-voice') return _settingsOrkasServiceLabel('Voice');const hit = (_settingsState.ttsPresets || []).find((p) => p.id === id);return hit ? hit.label : (id || 'custom');}@@ -2667,13 +2802,18 @@ function _settingsRenderTtsEntries() {main.className = 'entry-main';const primary = document.createElement('div');primary.className = 'entry-primary';- const detail = p.provider === 'doubao' ? (p.resourceId || '') : (p.model || '');+ const isOrkasApi = p.provider === _ORKAS_API_PROVIDER_ID;+ const detail = isOrkasApi+ ? ''+ : (p.provider === 'doubao' ? (p.resourceId || '') : (p.model || ''));+ const providerLabel = isOrkasApi+ ? _settingsOrkasServiceLabel('Voice')+ : _ttsProviderLabel(p.provider);primary.innerHTML = `- <span class="entry-provider">${escapeHtml(_ttsProviderLabel(p.provider))}</span>+ <span class="entry-provider">${escapeHtml(providerLabel)}</span>${detail ? `<span class="entry-sep">·</span><span class="entry-model">${escapeHtml(detail)}</span>` : ''}- ${p.voice ? `<span class="entry-sep">·</span><span class="entry-model">${escapeHtml(p.voice)}</span>` : ''}<span class="entry-sep">·</span>- <span class="entry-account-chip">@ ${escapeHtml(p.label || 'default')}</span>+ <span class="entry-account-chip">@ ${escapeHtml(isOrkasApi ? 'Orkas' : (p.label || 'default'))}</span>${p.apiKeyMasked ? `<span class="account-mask">${escapeHtml(p.apiKeyMasked)}</span>` : ''}`;main.appendChild(primary);diff --git a/src/renderer/style.css b/src/renderer/style.cssindex 7e64b40f..e039503d 100644--- a/src/renderer/style.css+++ b/src/renderer/style.css@@ -6135,6 +6135,11 @@ body.is-sidebar-resizing iframe { pointer-events: none; }.composer-model-menu-item.is-active {background: color-mix(in srgb, var(--primary-soft) 56%, var(--surface));}+.composer-model-menu-group + .composer-model-menu-group {+ margin-top: 4px;+ padding-top: 4px;+ border-top: 1px solid var(--border);+}.composer-model-menu-group-header {padding: 4px 10px 3px;display: flex;@@ -12897,6 +12902,73 @@ body.is-sidebar-resizing iframe { pointer-events: none; }margin-bottom: 14px;}.settings-group-head { margin-bottom: 14px; }+.settings-orkas-api-head {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 16px;+ margin-bottom: 14px;+}+.settings-orkas-api-head .settings-group-title {+ font-size: 14px;+ line-height: 1.4;+}+.settings-orkas-api-head .settings-group-sub {+ max-width: 720px;+}+.settings-orkas-api-head .btn {+ flex: 0 0 auto;+ min-height: 34px;+ padding-inline: 14px;+}+.settings-orkas-api-group .settings-orkas-api-configure-row {+ display: grid;+ grid-template-columns: minmax(0, 1fr) auto;+ align-items: stretch;+ gap: 10px;+ margin-bottom: 0;+}+.settings-orkas-api-group .settings-orkas-api-configure-row .form-input {+ flex: none;+ min-width: 0;+ height: 40px;+ padding: 0 12px;+ line-height: 38px;+ background: var(--surface);+}+.settings-orkas-api-configure-row .btn {+ height: 40px;+ min-width: 156px;+ padding: 0 18px;+ line-height: 38px;+ white-space: nowrap;+ box-shadow: 0 2px 5px rgba(73, 69, 192, 0.16);+}+.settings-orkas-api-status {+ display: block;+ min-height: 0;+ margin-top: 10px;+ line-height: 1.5;+}+.settings-orkas-api-status:empty {+ display: none;+}+@media (max-width: 720px) {+ .settings-orkas-api-head {+ align-items: stretch;+ flex-direction: column;+ }+ .settings-orkas-api-group .settings-orkas-api-configure-row {+ grid-template-columns: minmax(0, 1fr);+ }+ .settings-orkas-api-head .btn,+ .settings-orkas-api-configure-row .btn {+ width: 100%;+ }+ .settings-orkas-api-configure-row .btn {+ min-width: 0;+ }+}.settings-group-head-main {min-width: 0;}@@ -13353,6 +13425,17 @@ body.is-sidebar-resizing iframe { pointer-events: none; }flex-direction: column;gap: 8px;}+.entry-included-models {+ display: block;+ flex: 1 1 auto;+ min-width: 0;+ max-width: 100%;+ color: var(--text-2);+ font-size: 11px;+ line-height: 1.45;+ overflow-wrap: anywhere;+ white-space: normal;+}.entry-row {display: flex;align-items: center;@@ -13422,6 +13505,19 @@ body.is-sidebar-resizing iframe { pointer-events: none; }}.entry-sep { color: var(--border-strong); }.entry-model { color: var(--text); }+.entry-model-static {+ display: inline-flex;+ align-items: center;+ gap: 6px;+ min-width: 0;+ color: var(--text);+}+.entry-model-static-name {+ min-width: 0;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}.entry-account-chip {margin-left: 6px;padding: 1px 8px;@@ -13438,6 +13534,7 @@ body.is-sidebar-resizing iframe { pointer-events: none; }.entry-meta {display: flex;+ min-width: 0;align-items: center;gap: 8px;font-size: 11px;diff --git a/test/e2e/composer_e2e_interactions.spec.ts b/test/e2e/composer_e2e_interactions.spec.tsindex 9cc09211..cd6a0f66 100644--- a/test/e2e/composer_e2e_interactions.spec.ts+++ b/test/e2e/composer_e2e_interactions.spec.ts@@ -27,6 +27,47 @@ test.describe('persistent sidebar', () => {});test.describe('new chat composer', () => {+ test('groups both public Orkas API-key models as official models', async ({ appPage, orkas }) => {+ const configured = await orkas.invoke<{ ok: boolean; configured: boolean }>(+ 'orkasApi.configureAll',+ { apiKey: 'orkas-e2e-public-key-xxxxxxxx' },+ );+ expect(configured).toMatchObject({ ok: true, configured: true });++ const modelChip = appPage.locator('[data-composer-model-chip="new-chat"]');+ await modelChip.click();+ const officialGroup = appPage.locator(+ '.composer-model-menu-group[data-model-group="official"]',+ );+ await expect(officialGroup.locator('.composer-model-menu-group-label'))+ .toHaveText('Official models');+ const officialRows = officialGroup.locator('.composer-model-menu-item');+ await expect(officialRows).toHaveCount(2);+ await expect(officialRows.locator('.composer-model-menu-title-name'))+ .toHaveText(['Orkas-1.5', 'Orkas-1.5 Pro']);+ await expect(officialRows.nth(0).locator('.composer-model-menu-recommended'))+ .toHaveText('Recommended');+ await expect(officialRows.nth(0).locator('.composer-model-menu-description'))+ .toContainText('DeepSeek V4 · GPT-5.6 Luna · Claude-Sonnet-5 · Gemini-3.6 Flash');+ await expect(officialRows.nth(1).locator('.composer-model-menu-description'))+ .toContainText('GPT-5.6 Sol · Claude Opus 5 · Kimi K3');+ const customGroup = appPage.locator(+ '.composer-model-menu-group[data-model-group="custom"]',+ );+ await expect(customGroup.locator('.composer-model-menu-group-label'))+ .toHaveText('User-configured models');+ await appPage.keyboard.press('Escape');++ await appPage.locator('#settings-btn').click();+ await appPage.locator('.settings-tab[data-settings-tab="credentials"]').click();+ const settingsOfficialRows = appPage.locator('#settings-entries .entry-row').filter({+ has: appPage.locator('.entry-provider', { hasText: /^Orkas$/ }),+ });+ await expect(settingsOfficialRows).toHaveCount(2);+ await expect(settingsOfficialRows.locator('.entry-model-static-name'))+ .toHaveText(['Orkas-1.5', 'Orkas-1.5 Pro']);+ });+test('keeps CLI separate and shares BYO model priority selection across composers', async ({ appPage, orkas }) => {await expect(appPage.locator('.new-chat-model-choices')).toHaveCount(0);@@ -131,7 +172,7 @@ test.describe('new chat composer', () => {await expect(modelGroup).toHaveCount(1);await expect(modelGroup).toHaveAttribute('data-model-group', 'custom');await expect(modelGroup.locator('.composer-model-menu-group-label'))- .toHaveText('Custom models');+ .toHaveText('User-configured models');await expect(modelGroup.locator('.composer-model-menu-item')).toHaveCount(entriesBefore.entries.length);diff --git a/test/main/features/auth.test.ts b/test/main/features/auth.test.tsindex 56655657..9a71316f 100644--- a/test/main/features/auth.test.ts+++ b/test/main/features/auth.test.ts@@ -102,6 +102,7 @@ describe('auth › FEATURED_PROVIDERS', () => {// / Kimi-Coding / MiniMax / Doubao;去掉 oauthOnly 的 minimax-portal*)// → 聚合器 OpenRouter。必须严格跟 CATALOG 对齐(减 oauthOnly 项)。expect(a.FEATURED_PROVIDERS).toEqual([+ 'orkas-api','deepseek','openai','google',@@ -119,6 +120,103 @@ describe('auth › FEATURED_PROVIDERS', () => {});});+describe('auth › Orkas API quick setup', () => {+ it('configures all five public services idempotently with the documented model ids', async () => {+ const a = await import('../../../src/main/features/auth');+ await a.addApiKeyEntry('anthropic', 'claude-opus-4-8', 'third-party-key-xxxxxxxx', 'work');++ expect(a.configureAllOrkasApiServices(' orkas-key-first-xxxxxxxx ')).toEqual({ configured: true });+ a.saveImageProfiles(a.loadImageProfiles().map((profile) => (+ profile.provider === 'orkas-api' ? { ...profile, model: 'old-image-model' } : profile+ )));+ a.saveVideoProfiles(a.loadVideoProfiles().map((profile) => (+ profile.provider === 'orkas-api' ? { ...profile, model: 'old-video-model' } : profile+ )));+ a.saveTtsProfiles(a.loadTtsProfiles().map((profile) => (+ profile.provider === 'orkas-api'+ ? { ...profile, baseUrl: 'https://legacy.example/v1', model: 'old-tts-model' }+ : profile+ )));+ expect(a.configureAllOrkasApiServices('orkas-key-second-xxxxxxxx')).toEqual({ configured: true });++ const entries = (await a.listEntries({ includeUnavailable: true })).entries;+ expect(entries.filter((entry) => entry.provider === 'orkas-api')).toEqual([+ expect.objectContaining({+ model: 'orkas-llm-1.5',+ modelName: 'Orkas-1.5',+ official: true,+ profileLabel: 'Orkas',+ profileMasked: 'orka…xxxx',+ recommended: true,+ includedModels: ['DeepSeek V4', 'GPT-5.6 Luna', 'Claude-Sonnet-5', 'Gemini-3.6 Flash'],+ }),+ expect.objectContaining({+ model: 'orkas-llm-1.5-pro',+ modelName: 'Orkas-1.5 Pro',+ official: true,+ profileLabel: 'Orkas',+ profileMasked: 'orka…xxxx',+ includedModels: ['GPT-5.6 Sol', 'Claude Opus 5', 'Kimi K3'],+ }),+ ]);+ expect((await a.listComposerEntries()).entries).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ provider: 'orkas-api',+ model: 'orkas-llm-1.5',+ modelName: 'Orkas-1.5',+ official: true,+ }),+ expect.objectContaining({+ provider: 'orkas-api',+ model: 'orkas-llm-1.5-pro',+ modelName: 'Orkas-1.5 Pro',+ official: true,+ }),+ ]),+ );+ expect(entries[0]).toMatchObject({ provider: 'anthropic', model: 'claude-opus-4-8' });++ expect(a.loadSearchProfiles().filter((profile) => profile.provider === 'orkas-api')).toHaveLength(1);+ expect(a.loadImageProfiles().filter((profile) => profile.provider === 'orkas-api')).toEqual([+ expect.objectContaining({ model: 'orkas-image' }),+ ]);+ expect(a.loadVideoProfiles().filter((profile) => profile.provider === 'orkas-api')).toEqual([+ expect.objectContaining({ model: 'orkas-video' }),+ ]);+ expect(a.loadTtsProfiles().filter((profile) => profile.provider === 'orkas-api')).toEqual([+ expect.objectContaining({+ baseUrl: 'https://orkas.ai/v1',+ model: 'orkas-tts-1',+ voice: 'zh_female_vv_uranus_bigtts',+ }),+ ]);++ const paths = await import('../../../src/main/paths');+ const localSecrets = await import('../../../src/main/util/local-secret-store');+ const file = paths.userAuthProfilesFile(TEST_UID);+ const raw = fs.readFileSync(file, 'utf8');+ expect(localSecrets.isEncryptedSecret(raw)).toBe(true);+ expect(raw).not.toContain('orkas-key-second-xxxxxxxx');+ const persisted = JSON.parse(localSecrets.decryptLocalSecret(+ { namespace: 'auth.profiles', ownerId: TEST_UID, recordId: 'auth-profiles.json' },+ raw,+ { legacySeeds: [TEST_UID] },+ ));+ const orkasKeys = [+ ...Object.values(persisted.profiles as Record<string, any>)+ .filter((profile: any) => profile.provider === 'orkas-api')+ .map((profile: any) => profile.key),+ ...persisted.searchProfiles.filter((profile: any) => profile.provider === 'orkas-api').map((profile: any) => profile.apiKey),+ ...persisted.imageProfiles.filter((profile: any) => profile.provider === 'orkas-api').map((profile: any) => profile.apiKey),+ ...persisted.videoProfiles.filter((profile: any) => profile.provider === 'orkas-api').map((profile: any) => profile.apiKey),+ ...persisted.ttsProfiles.filter((profile: any) => profile.provider === 'orkas-api').map((profile: any) => profile.apiKey),+ ];+ expect(new Set(orkasKeys)).toEqual(new Set(['orkas-key-second-xxxxxxxx']));+ });++});+describe('auth › multi-profile store (addApiKey / removeCredential / renameProfile)', () => {it('addApiKey creates a default-labelled profile for a new provider', async () => {const a = await import('../../../src/main/features/auth');diff --git a/test/main/features/image_auth.test.ts b/test/main/features/image_auth.test.tsindex c1628a46..59912a84 100644--- a/test/main/features/image_auth.test.ts+++ b/test/main/features/image_auth.test.ts@@ -60,6 +60,7 @@ vi.mock('../../../src/main/logger', () => ({import {addImageProfile,flattenImageProviderOptions,+ listImageProviderOptions,listImageProfiles,removeImageProfile,reorderImageProfiles,@@ -191,4 +192,10 @@ describe('image auth profiles', () => {}),]);});++ it('labels the official picker option with its concrete service', () => {+ expect(listImageProviderOptions().find((option) => option.id === 'orkas-api')).toMatchObject({+ label: 'Orkas · Image',+ });+ });});diff --git a/test/main/features/image_gen.test.ts b/test/main/features/image_gen.test.tsindex 8bda6611..23201716 100644--- a/test/main/features/image_gen.test.ts+++ b/test/main/features/image_gen.test.ts@@ -149,6 +149,55 @@ describe('image_gen › pickImageGenProfile', () => {});});+// ── callOrkasImage (mock fetch) ──────────────────────────────────────────++describe('image_gen › callOrkasImage', () => {+ it('uses the public image contract without exposing a provider model id', async () => {+ const captured: { url?: string; init?: RequestInit } = {};+ vi.stubGlobal('fetch', async (url: string, init: RequestInit) => {+ captured.url = url;+ captured.init = init;+ const b64 =+ 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==';+ return new Response(JSON.stringify({+ id: 'img_public_test',+ status: 'succeeded',+ data: [{ b64_json: b64 }],+ }), { status: 202 });+ });+ try {+ const m = await import('../../../src/main/features/image_gen');+ const res = await m.callOrkasImage({+ apiKey: 'orkas-user-key',+ model: 'orkas-image',+ prompt: 'a blue circle',+ size: '1024x1024',+ usageContext: { conversationId: 'conv_123', turnId: 'turn-456' },+ });++ expect(captured.url).toBe('https://orkas.ai/v1/images/generations');+ expect(captured.init?.method).toBe('POST');+ expect(captured.init?.headers).toMatchObject({+ Authorization: 'Bearer orkas-user-key',+ 'Content-Type': 'application/json',+ 'X-Orkas-Conversation-Id': 'conv_123',+ 'X-Orkas-Turn-Id': 'turn-456',+ });+ const body = JSON.parse(String(captured.init?.body));+ expect(body).toEqual({+ prompt: 'a blue circle',+ size: '2k',+ response_format: 'url',+ async: true,+ });+ expect(body).not.toHaveProperty('model');+ expect(res).toMatchObject({ mimeType: 'image/png', width: 1, height: 1 });+ } finally {+ vi.unstubAllGlobals();+ }+ });+});+// ── callOpenAIImage (mock fetch) ─────────────────────────────────────────describe('image_gen › callOpenAIImage', () => {diff --git a/test/main/features/orkas_api.test.ts b/test/main/features/orkas_api.test.tsnew file mode 100644index 00000000..1e82ae76--- /dev/null+++ b/test/main/features/orkas_api.test.ts@@ -0,0 +1,22 @@+import { describe, expect, it } from 'vitest';++import { orkasApiUsageHeaders } from '../../../src/main/features/orkas_api';++describe('Orkas public API usage context', () => {+ it('sends only opaque conversation and turn ids', () => {+ expect(orkasApiUsageHeaders({+ conversationId: 'conv_123',+ turnId: 'turn-456',+ })).toEqual({+ 'X-Orkas-Conversation-Id': 'conv_123',+ 'X-Orkas-Turn-Id': 'turn-456',+ });+ });++ it('drops unsafe or overlong ids instead of uploading content', () => {+ expect(orkasApiUsageHeaders({+ conversationId: 'private conversation title',+ turnId: 'x'.repeat(65),+ })).toEqual({});+ });+});diff --git a/test/main/features/video_auth.test.ts b/test/main/features/video_auth.test.tsindex 29dc4f8c..001cce1c 100644--- a/test/main/features/video_auth.test.ts+++ b/test/main/features/video_auth.test.ts@@ -86,10 +86,17 @@ describe('video auth profiles', () => {it('exposes the concrete open-source video model in the picker', () => {const options = flattenVideoProviderOptions([+ { id: 'orkas-api', label: 'Orkas' },{ id: 'doubao', label: 'DouBao' },]);expect(options[0]).toMatchObject({+ id: 'orkas-api',+ provider: 'orkas-api',+ model: 'orkas-video',+ label: 'Orkas · Video',+ });+ expect(options[1]).toMatchObject({id: 'doubao',provider: 'doubao',model: 'doubao-seedance-2-0-260128',diff --git a/test/main/features/video_gen.test.ts b/test/main/features/video_gen.test.tsnew file mode 100644index 00000000..6b640ca3--- /dev/null+++ b/test/main/features/video_gen.test.ts@@ -0,0 +1,155 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import * as fs from 'node:fs';+import * as os from 'node:os';+import * as path from 'node:path';++const mocks = vi.hoisted(() => ({+ profiles: [] as Array<{+ id: string;+ provider: string;+ model: string;+ apiKey: string;+ label: string;+ createdAt: number;+ }>,+ registerGeneratedMediaUrl: vi.fn(),+ downloadBinaryWithProxyPolicy: vi.fn(),+}));++vi.mock('../../../src/main/features/auth', () => ({+ loadVideoProfiles: () => mocks.profiles.map((profile) => ({ ...profile })),+}));++vi.mock('../../../src/main/features/generation_reference_assets', () => ({+ prepareReferenceUrls: vi.fn(async ({ urls }: { urls?: string[] }) => [...(urls || [])]),+ registerGeneratedMediaUrl: mocks.registerGeneratedMediaUrl,+}));++vi.mock('../../../src/main/util/proxy-dispatcher', () => ({+ downloadBinaryWithProxyPolicy: mocks.downloadBinaryWithProxyPolicy,+}));++vi.mock('../../../src/main/logger', () => ({+ createLogger: () => ({ debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() }),+}));++import { generateVideo, validateDownloadedVideo } from '../../../src/main/features/video_gen';++let tmpDir: string;++function mp4Fixture(): Buffer {+ const out = Buffer.alloc(24);+ out.writeUInt32BE(24, 0);+ out.write('ftyp', 4, 'ascii');+ out.write('isom', 8, 'ascii');+ out.writeUInt32BE(0, 12);+ out.write('isom', 16, 'ascii');+ out.write('mp42', 20, 'ascii');+ return out;+}++beforeEach(() => {+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-video-gen-'));+ mocks.profiles = [{+ id: 'vid-orkas',+ provider: 'orkas-api',+ model: 'orkas-video',+ apiKey: 'orkas-user-key',+ label: 'Orkas',+ createdAt: 1,+ }];+ mocks.registerGeneratedMediaUrl.mockReset();+ mocks.downloadBinaryWithProxyPolicy.mockReset();+ mocks.downloadBinaryWithProxyPolicy.mockImplementation(async (_url, options) => {+ const body = mp4Fixture();+ options?.validate?.(body);+ return { body, finalUrl: 'https://cdn.example.test/video.mp4' };+ });+});++afterEach(() => {+ vi.unstubAllGlobals();+ fs.rmSync(tmpDir, { recursive: true, force: true });+});++describe('video_gen › Orkas public API', () => {+ it('creates, downloads, and saves a public API video without sending a model', async () => {+ const fetchStub = vi.fn(async () => new Response(JSON.stringify({+ id: 'video_public_test',+ status: 'succeeded',+ url: 'https://cdn.example.test/video.mp4',+ duration: 5,+ ratio: '16:9',+ resolution: '720p',+ }), { status: 202 }));+ vi.stubGlobal('fetch', fetchStub);+ const requestedPath = path.join(tmpDir, 'result.mov');++ const result = await generateVideo({+ prompt: 'a paper boat crosses a pond',+ outputAbsPath: requestedPath,+ quality: 'economy',+ generateAudio: false,+ usageContext: { conversationId: 'conv_123', turnId: 'turn-456' },+ });++ expect(result).toMatchObject({+ ok: true,+ path: path.join(tmpDir, 'result.mp4'),+ provider: 'orkas-api',+ model: 'orkas-video',+ taskId: 'video_public_test',+ });+ expect(fs.readFileSync(path.join(tmpDir, 'result.mp4'))).toEqual(mp4Fixture());+ expect(fetchStub).toHaveBeenCalledTimes(1);+ expect(fetchStub).toHaveBeenCalledWith(+ 'https://orkas.ai/v1/videos',+ expect.objectContaining({+ method: 'POST',+ headers: expect.objectContaining({+ 'X-Orkas-Conversation-Id': 'conv_123',+ 'X-Orkas-Turn-Id': 'turn-456',+ }),+ }),+ );+ const body = JSON.parse(String(fetchStub.mock.calls[0]?.[1]?.body));+ expect(body).toMatchObject({+ prompt: 'a paper boat crosses a pond',+ quality: 'balanced',+ generate_audio: false,+ });+ expect(body).not.toHaveProperty('model');+ expect(mocks.registerGeneratedMediaUrl).toHaveBeenCalledWith(+ path.join(tmpDir, 'result.mp4'),+ 'https://cdn.example.test/video.mp4',+ );+ });++ it('fails before dispatch when edit mode has no reference video', async () => {+ const fetchStub = vi.fn();+ vi.stubGlobal('fetch', fetchStub);++ await expect(generateVideo({+ prompt: 'change the ending',+ outputAbsPath: path.join(tmpDir, 'edit.mp4'),+ operation: 'edit',+ })).resolves.toMatchObject({+ ok: false,+ errorCode: 'BAD_INPUT',+ message: expect.stringContaining('requires at least one reference video'),+ });+ expect(fetchStub).not.toHaveBeenCalled();+ });++ it('returns NO_CAPABLE_MODEL when no Orkas public video profile exists', async () => {+ mocks.profiles = [];+ await expect(generateVideo({+ prompt: 'a quiet landscape',+ outputAbsPath: path.join(tmpDir, 'missing.mp4'),+ })).resolves.toMatchObject({ ok: false, errorCode: 'NO_CAPABLE_MODEL' });+ });++ it('rejects non-MP4 downloads', () => {+ expect(() => validateDownloadedVideo(Buffer.from('not a video'))).toThrow(/invalid or unsupported MP4/);+ });+});diff --git a/test/main/index-process.test.ts b/test/main/index-process.test.tsindex d3074591..1510c4cf 100644--- a/test/main/index-process.test.ts+++ b/test/main/index-process.test.ts@@ -51,8 +51,10 @@ describe('main process child-process ownership', () => {'utf8',);expect(shellLauncher).toContain('ORKAS_RELAUNCH_OWNER_PID');+ expect(shellLauncher).toContain('scripts/stop-source-instance.cjs');expect(shellLauncher).not.toMatch(/pkill[^\n]+electron\/dist/i);expect(windowsLauncher).toContain('ORKAS_RELAUNCH_OWNER_PID');+ expect(windowsLauncher).toContain('scripts\\stop-source-instance.cjs');expect(windowsLauncher).not.toMatch(/taskkill[^\n]+electron\.exe/i);});});diff --git a/test/main/ipc/orkas-api-quick-setup.test.ts b/test/main/ipc/orkas-api-quick-setup.test.tsnew file mode 100644index 00000000..e2cad58e--- /dev/null+++ b/test/main/ipc/orkas-api-quick-setup.test.ts@@ -0,0 +1,108 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import { trustedIpcSender } from '../../helpers/trusted-ipc-sender';++type InvokeFn = (+ event: unknown,+ req: { channel: string; payload?: unknown },+) => Promise<{ ok: boolean; error?: string } & Record<string, unknown>>;++let invokeHandler: InvokeFn | null = null;++vi.mock('electron', () => ({+ ipcMain: {+ handle: (channel: string, fn: InvokeFn) => {+ if (channel === 'orkas.invoke') invokeHandler = fn;+ },+ on: vi.fn(),+ },+ shell: { openExternal: vi.fn(async () => undefined), showItemInFolder: vi.fn() },+ BrowserWindow: { getAllWindows: vi.fn(() => []), getFocusedWindow: vi.fn(() => null) },+ dialog: { showOpenDialog: vi.fn(async () => ({ canceled: true, filePaths: [] })) },+}));++let tmpDir: string;+let previousWorkspaceRoot: string | undefined;++beforeEach(async () => {+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-open-model-ipc-'));+ previousWorkspaceRoot = process.env.ORKAS_WORKSPACE_ROOT;+ process.env.ORKAS_WORKSPACE_ROOT = tmpDir;+ invokeHandler = null;+ vi.resetModules();++ const users = await import('../../../src/main/features/users');+ users.activateUser('u_model_config');+ const ipc = await import('../../../src/main/ipc/index');+ ipc.register();+});++afterEach(() => {+ if (previousWorkspaceRoot === undefined) delete process.env.ORKAS_WORKSPACE_ROOT;+ else process.env.ORKAS_WORKSPACE_ROOT = previousWorkspaceRoot;+ fs.rmSync(tmpDir, { recursive: true, force: true });+});++function call(channel: string, payload: unknown = {}): ReturnType<InvokeFn> {+ if (!invokeHandler) throw new Error('invoke handler not registered');+ return invokeHandler(+ { sender: trustedIpcSender() },+ { channel, payload },+ );+}++describe('ipc › Orkas API quick setup', () => {+ it('returns the Orkas model to the composer immediately after quick setup', async () => {+ expect(await call('orkasApi.configureAll', {+ apiKey: 'orkas-composer-ipc-key-xxxxxxxx',+ })).toMatchObject({ ok: true, configured: true });++ expect(await call('auth.listComposerEntries')).toMatchObject({+ ok: true,+ entries: [+ expect.objectContaining({+ provider: 'orkas-api',+ model: 'orkas-llm-1.5',+ modelName: 'Orkas-1.5',+ official: true,+ profileLabel: 'Orkas',+ recommended: true,+ profileAvailable: true,+ }),+ expect.objectContaining({+ provider: 'orkas-api',+ model: 'orkas-llm-1.5-pro',+ modelName: 'Orkas-1.5 Pro',+ official: true,+ profileLabel: 'Orkas',+ profileAvailable: true,+ }),+ ],+ });++ expect(await call('imageAuth.list')).toMatchObject({+ ok: true,+ providers: expect.arrayContaining([+ expect.objectContaining({ id: 'orkas-api', label: 'Orkas · Image' }),+ ]),+ profiles: expect.arrayContaining([+ expect.objectContaining({ provider: 'orkas-api', model: 'orkas-image' }),+ ]),+ });+ expect(await call('ttsAuth.list')).toMatchObject({+ ok: true,+ presets: expect.arrayContaining([+ expect.objectContaining({ id: 'orkas-api', label: 'Orkas · Voice' }),+ ]),+ profiles: expect.arrayContaining([+ expect.objectContaining({ provider: 'orkas-api', model: 'orkas-tts-1' }),+ ]),+ });+ expect(await call('searchAuth.list')).toMatchObject({+ ok: true,+ profiles: expect.arrayContaining([expect.objectContaining({ provider: 'orkas-api' })]),+ });+ });+});diff --git a/test/main/model/core-agent/external-providers.test.ts b/test/main/model/core-agent/external-providers.test.tsindex f2f4dcfe..c91453c4 100644--- a/test/main/model/core-agent/external-providers.test.ts+++ b/test/main/model/core-agent/external-providers.test.ts@@ -4,6 +4,7 @@ import {buildDeepSeekModel,buildDoubaoModel,buildMoonshotModel,+ buildOrkasApiModel,createMoonshotProvider,} from '../../../../src/main/model/core-agent/external-providers';import { modelInputImageLimit } from '../../../../src/main/model/provider_catalog';@@ -59,6 +60,18 @@ describe('external-providers › custom OpenAI-compatible model', () => {});});+describe('external-providers › Orkas API model', () => {+ it('uses the public chat endpoint and preserves the selected public model id', () => {+ expect(buildOrkasApiModel('orkas-llm-1.5-pro')).toMatchObject({+ api: 'openai-completions',+ provider: 'orkas-api',+ id: 'orkas-llm-1.5-pro',+ baseUrl: 'https://orkas.ai/v1',+ input: ['text', 'image'],+ });+ });+});+describe('external-providers › DeepSeek model capabilities', () => {it('uses official V4 limits and keeps the text aliases text-only', () => {for (const modelId of ['deepseek-v4-pro', 'deepseek-v4-flash']) {diff --git a/test/main/model/core-agent/generate-speech-tool.test.ts b/test/main/model/core-agent/generate-speech-tool.test.tsindex a44133a7..511324ae 100644--- a/test/main/model/core-agent/generate-speech-tool.test.ts+++ b/test/main/model/core-agent/generate-speech-tool.test.ts@@ -86,7 +86,7 @@ afterEach(() => {fs.rmSync(tmpDir, { recursive: true, force: true });});-async function createTool(opts: { cid?: string; projectId?: string; agentId?: string }) {+async function createTool(opts: { cid?: string; turnId?: string; projectId?: string; agentId?: string }) {const mod = await import('../../../../src/main/model/core-agent/generate-speech-tool');return mod.createGenerateSpeechTool({ userId: UID, ...opts });}@@ -388,7 +388,7 @@ describe('generate_speech output paths', () => {it('writes relative output_path to the current conversation attachment dir', async () => {const paths = await import('../../../../src/main/paths');- const tool = await createTool({ cid: CID });+ const tool = await createTool({ cid: CID, turnId: 'turn-456' });const cwd = path.join(tmpDir, 'PC', 'bin');fs.mkdirSync(cwd, { recursive: true });@@ -399,6 +399,9 @@ describe('generate_speech output paths', () => {expect(result.isError).toBeFalsy();expect(speechMock.generateSpeech).toHaveBeenCalledTimes(1);+ expect(speechMock.generateSpeech.mock.calls[0]?.[0]).toMatchObject({+ usageContext: { conversationId: CID, turnId: 'turn-456' },+ });expect(lastOutputPath()).toBe(path.join(paths.chatAttachmentDir(UID, CID), 'morning.mp3'));});diff --git a/test/main/model/core-agent/image-gen-tool.test.ts b/test/main/model/core-agent/image-gen-tool.test.tsindex 7ad16737..3729aa50 100644--- a/test/main/model/core-agent/image-gen-tool.test.ts+++ b/test/main/model/core-agent/image-gen-tool.test.ts@@ -51,7 +51,12 @@ afterEach(() => {describe('generate_image tool in the open build', () => {it('dispatches a configured BYO provider and publishes the generated path', async () => {const published: string[] = [];- const tool = createImageGenTool({ userId: 'user-a', onFileWritten: (file) => published.push(file) });+ const tool = createImageGenTool({+ userId: 'user-a',+ cid: 'conv_123',+ turnId: 'turn-456',+ onFileWritten: (file) => published.push(file),+ });const result = await tool.execute({ prompt: 'a small red dot', output_path: 'image.png', size: '1024x1024' },{ workingDir: root } as any,@@ -62,6 +67,7 @@ describe('generate_image tool in the open build', () => {prompt: 'a small red dot',outputAbsPath: path.join(root, 'image.png'),size: '1024x1024',+ usageContext: { conversationId: 'conv_123', turnId: 'turn-456' },}));expect(published).toEqual([path.join(root, 'image.png')]);expect(String(result.content)).toContain('test-provider/test-model');diff --git a/test/main/model/core-agent/injected-tool-fixture.ts b/test/main/model/core-agent/injected-tool-fixture.tsindex 4bfa4e29..bbdd6ae0 100644--- a/test/main/model/core-agent/injected-tool-fixture.ts+++ b/test/main/model/core-agent/injected-tool-fixture.ts@@ -10,6 +10,7 @@ import { createFileTools, createLocalTools } from '../../../../src/main/model/coimport { createGenerateSpeechTool } from '../../../../src/main/model/core-agent/generate-speech-tool';import { createImageGenTool } from '../../../../src/main/model/core-agent/image-gen-tool';import { createImageStudioTool } from '../../../../src/main/model/core-agent/image-studio-tool';+import { createVideoGenTool } from '../../../../src/main/model/core-agent/video-gen-tool';import { createLibraryTool } from '../../../../src/main/model/core-agent/kb-tools';import { createOfficeTools } from '../../../../src/main/model/core-agent/office-tools';import { createPdfTools } from '../../../../src/main/model/core-agent/pdf-tools';@@ -68,6 +69,7 @@ export function enumerateAllInjectedTools(): AgentTool[] {tools.push(createChatHistoryTool({ userId }));tools.push(createImageGenTool({ userId, cid }));tools.push(createGenerateSpeechTool({ userId, cid }));+ tools.push(createVideoGenTool({ userId, cid }));tools.push(createImageStudioTool({ userId, cid }));tools.push(...createOfficeTools({ userId, cid }));tools.push(...createPdfTools({ userId, cid }));diff --git a/test/main/model/core-agent/search-adapters.test.ts b/test/main/model/core-agent/search-adapters.test.tsindex 7e4ca061..53bb2100 100644--- a/test/main/model/core-agent/search-adapters.test.ts+++ b/test/main/model/core-agent/search-adapters.test.ts@@ -6,6 +6,7 @@ vi.mock('../../../../src/main/logger', () => ({import {runSearchAdapter,+ SEARCH_PROVIDER_LABEL,searchAdaptersByProvider,} from '../../../../src/main/model/core-agent/search-adapters';@@ -14,6 +15,48 @@ afterEach(() => {});describe('open-source BYO search adapters', () => {+ it('labels the official provider with its concrete service', () => {+ expect(SEARCH_PROVIDER_LABEL['orkas-api']).toBe('Orkas · Search');+ });++ it('uses the public Orkas search contract without a capabilities request', async () => {+ const fetchStub = vi.fn(async () => new Response(JSON.stringify({+ results: [{ title: 'Orkas', url: 'https://orkas.ai/docs', snippet: 'Official result' }],+ }), { status: 200 }));+ vi.stubGlobal('fetch', fetchStub);++ const result = await runSearchAdapter({+ id: 'orkas-a',+ provider: 'orkas-api',+ apiKey: 'orkas-user-key',+ label: 'Orkas',+ createdAt: 0,+ }, 'public api', 4, {+ conversationId: 'conv_123',+ turnId: 'turn-456',+ });++ expect(result.results).toEqual([+ { title: 'Orkas', url: 'https://orkas.ai/docs', snippet: 'Official result' },+ ]);+ expect(fetchStub).toHaveBeenCalledTimes(1);+ expect(fetchStub).toHaveBeenCalledWith(+ 'https://orkas.ai/v1/search',+ expect.objectContaining({+ method: 'POST',+ headers: expect.objectContaining({+ Authorization: 'Bearer orkas-user-key',+ 'X-Orkas-Conversation-Id': 'conv_123',+ 'X-Orkas-Turn-Id': 'turn-456',+ }),+ }),+ );+ expect(JSON.parse(String(fetchStub.mock.calls[0]?.[1]?.body))).toEqual({+ query: 'public api',+ max_results: 4,+ });+ });+it('normalizes Tavily results and bounds the requested count', async () => {const fetchStub = vi.fn(async () => new Response(JSON.stringify({results: [@@ -79,6 +122,7 @@ describe('open-source BYO search adapters', () => {'baidu-ai-search','brave-search','metaso',+ 'orkas-api','serper','tavily',]);diff --git a/test/main/model/core-agent/tool-behavior-coverage.test.ts b/test/main/model/core-agent/tool-behavior-coverage.test.tsindex 08bfd13f..f475efab 100644--- a/test/main/model/core-agent/tool-behavior-coverage.test.ts+++ b/test/main/model/core-agent/tool-behavior-coverage.test.ts@@ -44,6 +44,7 @@ const BEHAVIOR_SUITE_BY_TOOL: Record<string, string> = {chat_history: 'test/main/model/core-agent/chat-history-tools.test.ts',generate_image: 'test/main/model/core-agent/image-gen-tool.test.ts',generate_speech: 'test/main/model/core-agent/generate-speech-tool.test.ts',+ generate_video: 'test/main/model/core-agent/video-gen-tool.test.ts',video_studio: 'test/main/model/core-agent/video-studio-state-tool.test.ts',image_studio: 'test/main/model/core-agent/image-studio-tool.test.ts',web_search: 'test/main/model/core-agent/search-tools.test.ts',diff --git a/test/main/model/core-agent/tool-catalog.test.ts b/test/main/model/core-agent/tool-catalog.test.tsindex b97d257b..33e64910 100644--- a/test/main/model/core-agent/tool-catalog.test.ts+++ b/test/main/model/core-agent/tool-catalog.test.ts@@ -121,7 +121,7 @@ describe('tool-catalog', () => {expect(missing, `Injected tools missing from TOOL_CATALOG: ${missing.join(', ')}`).toEqual([]);const stale = [...catalog].filter((n) => !injected.has(n));expect(stale, `Catalog tools missing from injected fixture: ${stale.join(', ')}`).toEqual([]);- expect(catalog.size).toBe(55);+ expect(catalog.size).toBe(56);});it('TOOL_CATALOG has no duplicate names', () => {@@ -317,10 +317,10 @@ describe('tool-catalog', () => {'bash', 'process_session', 'interactive_cli',]);expect(toolNamesForGroups(['media.image'])).toEqual(['generate_image', 'image_studio']);- expect(toolNamesForGroups(['media.video'])).toEqual(['video_studio']);+ expect(toolNamesForGroups(['media.video'])).toEqual(['generate_video', 'video_studio']);expect(toolNamesForGroups(['media.speech'])).toEqual(['generate_speech']);expect(toolNamesForGroups(['media'])).toEqual([- 'generate_image', 'image_studio', 'video_studio', 'generate_speech',+ 'generate_image', 'image_studio', 'generate_video', 'video_studio', 'generate_speech',]);expect(expandToolGroups(['workspace'])).toEqual([@@ -453,7 +453,7 @@ describe('tool-catalog', () => {expect(fingerprint,'A model-visible field, enum, bound, default, or required rule changed; review it as a schema change, not description cleanup.',- ).toBe('2a3e714b9c485eccabf1da1c0af75dd279fa62f5a959f4fead1f68461a3622bc');+ ).toBe('03aebb7d2ce9f2b428830abcdc07d5898f409d455d540b1ed5b6d3e6cac0026b');});it('keeps the reviewed stable tool corpus within the description budgets', () => {diff --git a/test/main/model/core-agent/video-gen-tool.test.ts b/test/main/model/core-agent/video-gen-tool.test.tsnew file mode 100644index 00000000..b2d92794--- /dev/null+++ b/test/main/model/core-agent/video-gen-tool.test.ts@@ -0,0 +1,113 @@+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++const h = vi.hoisted(() => ({+ generateVideo: vi.fn(),+ workspace: '',+}));++vi.mock('../../../../src/main/features/video_gen', () => ({+ generateVideo: h.generateVideo,+}));+vi.mock('../../../../src/main/features/user_workspace', () => ({+ getWorkspacePath: () => h.workspace,+}));+vi.mock('../../../../src/main/logger', () => ({+ createLogger: () => ({ warn: vi.fn(), info: vi.fn(), error: vi.fn(), debug: vi.fn() }),+}));++import { createVideoGenTool } from '../../../../src/main/model/core-agent/video-gen-tool';++let root = '';++beforeEach(() => {+ root = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-open-video-tool-'));+ h.workspace = root;+ h.generateVideo.mockReset().mockImplementation(async ({ outputAbsPath }) => ({+ ok: true,+ path: outputAbsPath,+ bytes: 256,+ provider: 'orkas-api',+ model: 'orkas-video',+ taskId: 'video-test-task',+ videoUrl: 'https://cdn.example.test/video.mp4',+ status: 'succeeded',+ }));+});++afterEach(() => {+ fs.rmSync(root, { recursive: true, force: true });+});++describe('generate_video tool in the open build', () => {+ it('dispatches the configured public provider and publishes an MP4 path', async () => {+ const published: string[] = [];+ const progress = vi.fn();+ const tool = createVideoGenTool({+ userId: 'user-a',+ cid: 'conv_123',+ turnId: 'turn-456',+ onFileWritten: (file) => published.push(file),+ });+ const result = await tool.execute(+ {+ prompt: 'a paper boat crosses a pond',+ output_path: 'clip.mov',+ duration: 6,+ quality: 'quality',+ generate_audio: false,+ },+ { workingDir: root, emitProgress: progress } as any,+ );++ expect(result.isError).not.toBe(true);+ expect(h.generateVideo).toHaveBeenCalledWith(expect.objectContaining({+ prompt: 'a paper boat crosses a pond',+ outputAbsPath: path.join(root, 'clip.mp4'),+ duration: 6,+ quality: 'quality',+ generateAudio: false,+ usageContext: { conversationId: 'conv_123', turnId: 'turn-456' },+ }));+ expect(published).toEqual([path.join(root, 'clip.mp4')]);+ expect(String(result.content)).toContain('orkas-api/orkas-video');+ expect(String(result.content)).toContain('[video](');+ });++ it('rejects out-of-scope outputs and invalid edit requests before dispatch', async () => {+ const tool = createVideoGenTool({ userId: 'user-a' });+ const outside = await tool.execute(+ { prompt: 'a dot', output_path: path.join(root, '..', 'outside.mp4') },+ { workingDir: root } as any,+ );+ const missingReference = await tool.execute(+ { prompt: 'change the ending', output_path: 'edit.mp4', operation: 'edit' },+ { workingDir: root } as any,+ );++ expect(outside.isError).toBe(true);+ expect(String(outside.content)).toContain('E_PATH_OUT_OF_SCOPE');+ expect(missingReference.isError).toBe(true);+ expect(String(missingReference.content)).toContain('requires at least one reference video');+ expect(h.generateVideo).not.toHaveBeenCalled();+ });++ it('turns exhausted public API credits into a non-retry instruction', async () => {+ h.generateVideo.mockResolvedValueOnce({+ ok: false,+ errorCode: 'CREDITS_EXHAUSTED',+ message: 'quota exhausted',+ });+ const tool = createVideoGenTool({ userId: 'user-a' });+ const result = await tool.execute(+ { prompt: 'a quiet landscape', output_path: 'clip.mp4' },+ { workingDir: root } as any,+ );++ expect(result.isError).toBe(true);+ expect(String(result.content)).toContain('E_CREDITS_EXHAUSTED');+ expect(String(result.content)).toContain('Do not retry');+ });+});diff --git a/test/main/model/provider_catalog.test.ts b/test/main/model/provider_catalog.test.tsindex 9367028b..f78a77a8 100644--- a/test/main/model/provider_catalog.test.ts+++ b/test/main/model/provider_catalog.test.ts@@ -30,6 +30,7 @@ describe('provider_catalog › CATALOG', () => {// OpenAI / Google / Anthropic),CN 主流(Zhipu / Moonshot / Kimi-Coding /// MiniMax × 3 / Doubao),最后聚合器(OpenRouter)。expect(ids).toEqual([+ 'orkas-api','deepseek','openai-codex','openai',@@ -83,6 +84,23 @@ describe('provider_catalog › CATALOG', () => {});describe('provider_catalog › CURATED_MODELS', () => {+ it('describes both Orkas official models with their product-facing names', () => {+ expect(providerLabel('orkas-api')).toBe('Orkas');+ expect(curatedModelsFor('orkas-api')).toEqual([+ expect.objectContaining({+ id: 'orkas-llm-1.5',+ name: 'Orkas-1.5',+ recommended: true,+ includedModels: ['DeepSeek V4', 'GPT-5.6 Luna', 'Claude-Sonnet-5', 'Gemini-3.6 Flash'],+ }),+ expect.objectContaining({+ id: 'orkas-llm-1.5-pro',+ name: 'Orkas-1.5 Pro',+ includedModels: ['GPT-5.6 Sol', 'Claude Opus 5', 'Kimi K3'],+ }),+ ]);+ });+it('curates every visible non-oauth-only provider', () => {// Every visible provider should have a curated list — no silent fall-// through to pickLatestGenerations for providers we advertise.@@ -464,9 +482,14 @@ describe('provider_catalog › EXTERNAL_API_PROVIDERS', () => {// `auth.ts::testConnection` 的分发依据——名单必须和 CATALOG 里真实// 标记为"外部"的 provider 严格一致,否则会出现"能选但调用报// No model found for provider"。- // 当前外部适配层支持:moonshot(OpenAI 兼容 endpoint)+ deepseek(pi-ai- // 0.68.1 不带)+ doubao(火山方舟)。- expect([...EXTERNAL_API_PROVIDERS]).toEqual(['moonshot', 'deepseek', 'doubao', 'custom']);+ // 当前外部适配层还包含公开 Orkas API(OpenAI-compatible chat)。+ expect([...EXTERNAL_API_PROVIDERS]).toEqual([+ 'orkas-api',+ 'moonshot',+ 'deepseek',+ 'doubao',+ 'custom',+ ]);});it('每个外部 provider 都在 CATALOG + CURATED_MODELS 有对应条目', () => {diff --git a/test/main/quality/tool-surface-budget.test.ts b/test/main/quality/tool-surface-budget.test.tsindex 2140ab01..a0d52e0c 100644--- a/test/main/quality/tool-surface-budget.test.ts+++ b/test/main/quality/tool-surface-budget.test.ts@@ -119,9 +119,9 @@ describe('injected tool surface budget', () => {// A silent empty/short corpus would make every assertion below vacuous:// a factory signature change that returns [] must fail here, not pass// quietly with a 0-char surface.- // The open build intentionally omits the release-only video generation tool;- // the remaining 36-tool corpus must still be complete and non-vacuous.- expect(tools).toHaveLength(36);+ // The open build includes its public API-key video generation tool;+ // the 37-tool corpus must still be complete and non-vacuous.+ expect(tools).toHaveLength(37);expect(tools.some((tool) => tool.name === 'create_xlsx')).toBe(true);expect(tools.some((tool) => tool.name === 'read_files')).toBe(true);});diff --git a/test/main/util/stop-source-instance.test.ts b/test/main/util/stop-source-instance.test.tsnew file mode 100644index 00000000..b1809dd4--- /dev/null+++ b/test/main/util/stop-source-instance.test.ts@@ -0,0 +1,112 @@+import { createRequire } from 'node:module';+import fs from 'node:fs';+import path from 'node:path';+import { describe, expect, it } from 'vitest';++const requireModule = createRequire(import.meta.url);+const {+ isSourceMainProcess,+ parsePosixProcessList,+ tokenizeCommandLine,+} = requireModule('../../../scripts/stop-source-instance.cjs') as {+ isSourceMainProcess: (+ processInfo: { pid: number; executablePath?: string; commandLine: string },+ appRoot: string,+ platform: NodeJS.Platform,+ ) => boolean;+ parsePosixProcessList: (output: string) => Array<{+ pid: number;+ parentPid: number;+ commandLine: string;+ }>;+ tokenizeCommandLine: (commandLine: string) => string[];+};++describe('source launcher previous-instance cleanup', () => {+ it('matches only the Electron main process owned by the current macOS checkout', () => {+ const appRoot = '/Users/test/Projects/OrkasSource';+ const executable = `${appRoot}/node_modules/electron/dist/Orkas.app/Contents/MacOS/Electron`;++ expect(isSourceMainProcess({+ pid: 120,+ commandLine: `${executable} ${appRoot}`,+ }, appRoot, 'darwin')).toBe(true);++ expect(isSourceMainProcess({+ pid: 121,+ commandLine: `${executable} ${appRoot} --type=renderer`,+ }, appRoot, 'darwin')).toBe(false);++ expect(isSourceMainProcess({+ pid: 122,+ commandLine: `${executable} /Users/test/Projects/OtherCheckout`,+ }, appRoot, 'darwin')).toBe(false);++ expect(isSourceMainProcess({+ pid: 123,+ commandLine: `${appRoot}/node_modules/electron/dist/Orkas.app/Contents/Frameworks/Electron Helper.app/Contents/MacOS/Electron Helper --type=gpu-process`,+ }, appRoot, 'darwin')).toBe(false);+ });++ it('supports Linux dot launches without matching a sibling Electron runtime', () => {+ const appRoot = '/opt/work/OrkasSource';+ const executable = `${appRoot}/node_modules/electron/dist/electron`;++ expect(isSourceMainProcess({+ pid: 220,+ commandLine: `${executable} .`,+ }, appRoot, 'linux')).toBe(true);+ expect(isSourceMainProcess({+ pid: 221,+ commandLine: '/opt/work/Orkas/node_modules/electron/dist/electron .',+ }, appRoot, 'linux')).toBe(false);+ });++ it('uses the exact Windows executable path and accepts paths with spaces', () => {+ const appRoot = String.raw`C:\Work Trees\OrkasSource`;+ const executable = path.win32.join(appRoot, 'node_modules', 'electron', 'dist', 'electron.exe');++ expect(isSourceMainProcess({+ pid: 320,+ executablePath: executable,+ commandLine: `"${executable}" "${appRoot}"`,+ }, appRoot, 'win32')).toBe(true);+ expect(isSourceMainProcess({+ pid: 321,+ executablePath: String.raw`C:\Work Trees\Orkas\node_modules\electron\dist\electron.exe`,+ commandLine: String.raw`"C:\Work Trees\Orkas\node_modules\electron\dist\electron.exe" .`,+ }, appRoot, 'win32')).toBe(false);+ });++ it('parses process inventory and quoted launcher arguments', () => {+ expect(parsePosixProcessList([+ ' 10 1 /opt/OrkasSource/node_modules/electron/dist/electron .',+ ' 11 10 helper --type=renderer',+ '',+ ].join('\n'))).toEqual([+ {+ pid: 10,+ parentPid: 1,+ commandLine: '/opt/OrkasSource/node_modules/electron/dist/electron .',+ },+ {+ pid: 11,+ parentPid: 10,+ commandLine: 'helper --type=renderer',+ },+ ]);+ expect(tokenizeCommandLine('"/Work Trees/electron" "/Work Trees/OrkasSource"'))+ .toEqual(['/Work Trees/electron', '/Work Trees/OrkasSource']);+ });++ it('terminates the Windows process tree by validated PID rather than image name', () => {+ const source = fs.readFileSync(+ path.resolve(process.cwd(), 'scripts/stop-source-instance.cjs'),+ 'utf8',+ );++ expect(source).toContain("execFileSync('taskkill.exe', ['/PID', String(pid), '/T', '/F']");+ expect(source).toContain('Get-CimInstance Win32_Process');+ expect(source).not.toMatch(/taskkill[^\n]+\/IM/i);+ });+});diff --git a/test/renderer/composer-model-picker.test.ts b/test/renderer/composer-model-picker.test.tsindex db122793..6cc64947 100644--- a/test/renderer/composer-model-picker.test.ts+++ b/test/renderer/composer-model-picker.test.ts@@ -1,10 +1,24 @@import * as fs from 'node:fs';import * as path from 'node:path';+import vm from 'node:vm';import { describe, expect, it } from 'vitest';const rendererRoot = path.join(process.cwd(), 'src', 'renderer');+function extractFunction(source: string, name: string): string {+ const start = source.indexOf(`function ${name}(`);+ if (start < 0) throw new Error(`missing ${name}`);+ const bodyStart = source.indexOf('{', start);+ let depth = 0;+ for (let index = bodyStart; index < source.length; index += 1) {+ if (source[index] === '{') depth += 1;+ if (source[index] === '}') depth -= 1;+ if (depth === 0) return source.slice(start, index + 1);+ }+ throw new Error(`unterminated ${name}`);+}+describe('open-source composer model picker', () => {it('loads on every composer after dropdown placement support', () => {const html = fs.readFileSync(path.join(rendererRoot, 'index.html'), 'utf8');@@ -15,7 +29,7 @@ describe('open-source composer model picker', () => {expect(picker).toBeGreaterThan(placement);});- it('uses only locally configured entries and never exposes managed credits', () => {+ it('separates public official models from user-configured models without managed credits', () => {const source = fs.readFileSync(path.join(rendererRoot, 'modules', 'composer-model-picker.js'),'utf8',@@ -26,6 +40,97 @@ describe('open-source composer model picker', () => {expect(source).toContain("window.orkas.invoke('auth.selectEntry'");expect(source).not.toContain('getSubscription');expect(source).not.toContain('credits_remaining');- expect(source).not.toContain('group_official');+ expect(source).toContain('new_chat.model_picker.group_official');+ expect(source).toContain("entry.official === true && entry.provider === 'orkas-api'");+ });++ it('matches the commercial official-model grouping, recommendation, and descriptions', () => {+ const source = fs.readFileSync(+ path.join(rendererRoot, 'modules', 'composer-model-picker.js'),+ 'utf8',+ );+ const zh = JSON.parse(fs.readFileSync(path.join(rendererRoot, 'locales', 'zh.json'), 'utf8'));+ const style = fs.readFileSync(path.join(rendererRoot, 'style.css'), 'utf8');++ class Element {+ type = '';+ className = '';+ textContent = '';+ innerHTML = '';+ disabled = false;+ dataset: Record<string, string> = {};+ children: Element[] = [];+ attributes = new Map<string, string>();+ listeners = new Map<string, () => unknown>();+ classList = { add: (name: string) => { this.className += ` ${name}`; } };+ setAttribute(name: string, value: string) { this.attributes.set(name, value); }+ appendChild(child: Element) { this.children.push(child); return child; }+ addEventListener(name: string, handler: () => unknown) { this.listeners.set(name, handler); }+ }+ const interpolate = (key: string, values: Record<string, string> = {}) => (+ String(zh[key] || key).replace(/\{(\w+)\}/g, (_: string, name: string) => values[name] || '')+ );+ const context: any = {+ document: { createElement: () => new Element() },+ window: {},+ t: interpolate,+ _closeComposerModelMenu() {},+ _selectComposerModel() {},+ };+ vm.createContext(context);+ vm.runInContext([+ extractFunction(source, '_composerModelEntryIsOfficial'),+ extractFunction(source, '_composerModelMenuGroups'),+ extractFunction(source, '_composerModelEntryLabel'),+ extractFunction(source, '_composerModelOfficialIncludedBody'),+ extractFunction(source, '_composerModelOfficialDescription'),+ extractFunction(source, '_buildComposerModelMenuItem'),+ ].join('\n'), context);++ const standard = {+ entryId: 'official-standard',+ provider: 'orkas-api',+ model: 'orkas-llm-1.5',+ modelName: 'Orkas-1.5',+ official: true,+ recommended: true,+ modelEditable: false,+ includedModels: ['DeepSeek V4', 'GPT-5.6 Luna', 'Claude-Sonnet-5', 'Gemini-3.6 Flash'],+ };+ const pro = {+ entryId: 'official-pro',+ provider: 'orkas-api',+ model: 'orkas-llm-1.5-pro',+ modelName: 'Orkas-1.5 Pro',+ official: true,+ modelEditable: false,+ includedModels: ['GPT-5.6 Sol', 'Claude Opus 5', 'Kimi K3'],+ };+ const custom = {+ entryId: 'custom-model', provider: 'anthropic', model: 'claude-opus-4-8',+ };+ const groups = context._composerModelMenuGroups([standard, custom, pro]);+ expect(groups.map((group: { key: string }) => group.key)).toEqual(['official', 'custom']);+ expect(groups[0].entries.map((entry: { entryId: string }) => entry.entryId))+ .toEqual(['official-standard', 'official-pro']);+ expect(groups[1].entries.map((entry: { entryId: string }) => entry.entryId))+ .toEqual(['custom-model']);++ const item = context._buildComposerModelMenuItem(+ standard,+ '',+ { dataset: { composerModelChip: 'conversation' }, focus() {} },+ );+ const title = item.children[0].children[0].children[0];+ expect(title.children[0].textContent).toBe('Orkas-1.5');+ expect(title.children[1].className).toBe('composer-model-menu-recommended');+ expect(title.children[1].textContent).toBe('推荐');+ expect(item.children[0].children[0].children[1].textContent).toBe(+ '适合问答、写作、办公等日常任务。包含:DeepSeek V4 · GPT-5.6 Luna · Claude-Sonnet-5 · Gemini-3.6 Flash',+ );+ expect(context._composerModelOfficialDescription(pro)).toBe(+ '适合研究、视频、研发等复杂任务。包含:GPT-5.6 Sol · Claude Opus 5 · Kimi K3',+ );+ expect(style).toMatch(/\.composer-model-menu-group \+ \.composer-model-menu-group\s*\{[^}]*border-top:\s*1px solid var\(--border\)/s);});});diff --git a/test/renderer/model-availability-hot-update.test.ts b/test/renderer/model-availability-hot-update.test.tsindex 7b4a2fef..a33282c1 100644--- a/test/renderer/model-availability-hot-update.test.ts+++ b/test/renderer/model-availability-hot-update.test.ts@@ -3,12 +3,11 @@ import { resolve } from 'node:path';import { describe, expect, it } from 'vitest';describe('open-source model availability wiring', () => {- it('does not subscribe picker, settings, or guard to Orkas-managed model availability', () => {+ it('does not subscribe picker, settings, or guard to managed model availability', () => {const root = resolve(__dirname, '../../src/renderer/modules');for (const name of ['composer-model-picker.js', 'settings.js', 'model-guard.js']) {const source = readFileSync(resolve(root, name), 'utf8');expect(source).not.toContain(['model', ['orkas', 'llm'].join('_'), 'availability'].join('.'));- expect(source).not.toContain(['orkas', 'llm'].join('-'));}});});diff --git a/test/renderer/settings-add-account.test.ts b/test/renderer/settings-add-account.test.tsindex 2cd38dab..db8b228f 100644--- a/test/renderer/settings-add-account.test.ts+++ b/test/renderer/settings-add-account.test.ts@@ -64,6 +64,10 @@ class FakeElement {return this.attributes.get(name) || null;}+ removeAttribute(name: string) {+ this.attributes.delete(name);+ }+querySelector(selector: string) {return this.queryResults.get(selector) || null;}diff --git a/test/renderer/settings-orkas-api.test.ts b/test/renderer/settings-orkas-api.test.tsnew file mode 100644index 00000000..848de207--- /dev/null+++ b/test/renderer/settings-orkas-api.test.ts@@ -0,0 +1,231 @@+import { readFileSync } from 'node:fs';+import { resolve } from 'node:path';+import vm from 'node:vm';+import { describe, expect, it, vi } from 'vitest';++class FakeElement {+ value = '';+ hidden = false;+ disabled = false;+ textContent = '';+ className = '';+ innerHTML = '';+ dataset: Record<string, string> = {};+ style: Record<string, string> = {};+ children: FakeElement[] = [];+ private readonly attributes = new Map<string, string>();+ private readonly listeners = new Map<string, Array<(event?: any) => unknown>>();++ setAttribute(name: string, value: string) { this.attributes.set(name, value); }+ getAttribute(name: string) { return this.attributes.get(name) || null; }+ removeAttribute(name: string) { this.attributes.delete(name); }+ appendChild(child: FakeElement) { this.children.push(child); return child; }+ querySelector() { return null; }++ addEventListener(type: string, handler: (event?: any) => unknown) {+ const handlers = this.listeners.get(type) || [];+ handlers.push(handler);+ this.listeners.set(type, handlers);+ }++ async dispatch(type: string, event: Record<string, unknown> = {}) {+ for (const handler of this.listeners.get(type) || []) {+ await handler({ currentTarget: this, target: this, preventDefault: vi.fn(), ...event });+ }+ }++ click() { return this.dispatch('click'); }+}++function loadQuickSetupHarness() {+ const source = readFileSync(resolve(__dirname, '../../src/renderer/modules/settings.js'), 'utf8');+ const html = readFileSync(resolve(__dirname, '../../src/renderer/index.html'), 'utf8');+ const elements = new Map<string, FakeElement>();+ for (const id of [+ 'settings-orkas-api-create-key',+ 'settings-orkas-api-key-input',+ 'settings-orkas-api-configure',+ 'settings-orkas-api-status',+ 'settings-entries',+ 'settings-search-entries',+ 'settings-image-entries',+ 'settings-video-entries',+ 'settings-tts-entries',+ ]) elements.set(id, new FakeElement());++ const invoke = vi.fn(async () => ({ ok: true }));+ const refreshModelGuard = vi.fn(async () => true);+ const context: any = {+ console,+ createLogger: () => ({ info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }),+ escapeHtml: (value: unknown) => String(value ?? ''),+ t: (key: string) => key,+ document: {+ getElementById: (id: string) => elements.get(id) || null,+ createElement: () => new FakeElement(),+ querySelectorAll: () => [],+ addEventListener: vi.fn(),+ removeEventListener: vi.fn(),+ },+ window: {+ addEventListener: vi.fn(),+ orkas: { invoke },+ },+ setTimeout,+ clearTimeout,+ setInterval,+ clearInterval,+ URL,+ refreshModelGuard,+ };+ vm.createContext(context);+ vm.runInContext(source, context, { filename: 'settings.js' });+ vm.runInContext(`+ window.__orkasApiRefreshes = 0;+ _settingsRefreshAllCredentialSections = async () => { window.__orkasApiRefreshes += 1; };+ _settingsBindOrkasApiOnce();+ `, context);+ return { context, elements, html, source, invoke, refreshModelGuard };+}++describe('Orkas public API quick setup', () => {+ it('uses concise configure copy in every supported locale', () => {+ const html = readFileSync(resolve(__dirname, '../../src/renderer/index.html'), 'utf8');+ expect(html).toContain('data-i18n="settings.orkas_api.configure">Configure</button>');++ const expected = { en: 'Configure', zh: '配置', ja: '設定', pt: 'Configurar' };+ for (const [locale, copy] of Object.entries(expected)) {+ const catalog = JSON.parse(readFileSync(+ resolve(__dirname, `../../src/renderer/locales/${locale}.json`),+ 'utf8',+ ));+ expect(catalog['settings.orkas_api.configure']).toBe(copy);+ expect(catalog).not.toHaveProperty('settings.orkas_api.configure_all');+ }+ });++ it('uses the standard settings card background and border', () => {+ const css = readFileSync(resolve(__dirname, '../../src/renderer/style.css'), 'utf8');+ expect(css).toMatch(/\.settings-group\s*{[^}]*background:\s*var\(--surface\);[^}]*border:\s*1px solid var\(--border\);/s);+ expect(css).not.toContain('.settings-orkas-api-group::before');+ expect(css).not.toMatch(/\.settings-orkas-api-group\s*{[^}]*(?:linear-gradient|border-color)/s);+ });++ it('uses the complete Orkas service labels in pickers and configured rows', () => {+ const { context, elements, source } = loadQuickSetupHarness();+ expect(source).not.toContain("label: 'Orkas API'");+ expect(vm.runInContext("_SEARCH_PROVIDER_OPTIONS.find((p) => p.id === 'orkas-api').label", context))+ .toBe('Orkas · Search');+ expect(vm.runInContext("_IMAGE_PROVIDER_OPTIONS.find((p) => p.id === 'orkas-api').label", context))+ .toBe('Orkas · Image');+ expect(vm.runInContext("_VIDEO_AUTH_PROVIDER_OPTIONS.find((p) => p.id === 'orkas-api').label", context))+ .toBe('Orkas · Video');+ expect(vm.runInContext("_ttsProviderLabel('orkas-api')", context)).toBe('Orkas · Voice');++ vm.runInContext(`+ _settingsAttachReorderDnd = () => {};+ _settingsState.searchProfiles = [{ id: 's1', provider: 'orkas-api', label: 'Orkas', apiKeyMasked: 'sk-…1' }];+ _settingsState.imageProfiles = [{ id: 'i1', provider: 'orkas-api', model: 'orkas-image', label: 'Orkas', apiKeyMasked: 'sk-…1' }];+ _settingsState.videoProfiles = [{ id: 'v1', provider: 'orkas-api', model: 'orkas-video', label: 'Orkas', apiKeyMasked: 'sk-…1' }];+ _settingsState.ttsProfiles = [{ id: 't1', provider: 'orkas-api', model: 'orkas-tts-1', label: 'Orkas', apiKeyMasked: 'sk-…1' }];+ _settingsRenderSearchEntries();+ _settingsRenderImageEntries();+ _settingsRenderVideoEntries();+ _settingsRenderTtsEntries();+ `, context);++ const configuredLabel = (id: string) => elements.get(id)!+ .children[0]!.children[1]!.children[0]!.innerHTML;+ expect(configuredLabel('settings-search-entries')).toContain('>Orkas · Search</span>');+ expect(configuredLabel('settings-image-entries')).toContain('>Orkas · Image</span>');+ expect(configuredLabel('settings-video-entries')).toContain('>Orkas · Video</span>');+ expect(configuredLabel('settings-tts-entries')).toContain('>Orkas · Voice</span>');+ expect(source).toContain('settings.orkas_api.recommended');+ expect(source).toContain('settings.orkas_api.includes');+ });++ it('renders both configured official model rows in Settings', () => {+ const { context, elements } = loadQuickSetupHarness();+ context.t = (key: string, values?: { models?: string }) => (+ values?.models ? `${key}: ${values.models}` : key+ );+ vm.runInContext(`+ _settingsAttachReorderDnd = () => {};+ _settingsState.entries = [+ {+ entryId: 'orkas-standard', provider: 'orkas-api', providerLabel: 'Orkas',+ model: 'orkas-llm-1.5', modelName: 'Orkas-1.5', modelEditable: false,+ modelAvailable: true, official: true, recommended: true,+ includedModels: ['DeepSeek V4', 'GPT-5.6 Luna', 'Claude-Sonnet-5', 'Gemini-3.6 Flash'],+ profileType: 'api_key', profileAvailable: true, profileLabel: 'Orkas'+ },+ {+ entryId: 'orkas-pro', provider: 'orkas-api', providerLabel: 'Orkas',+ model: 'orkas-llm-1.5-pro', modelName: 'Orkas-1.5 Pro', modelEditable: false,+ modelAvailable: true, official: true,+ includedModels: ['GPT-5.6 Sol', 'Claude Opus 5', 'Kimi K3'],+ profileType: 'api_key', profileAvailable: true, profileLabel: 'Orkas'+ }+ ];+ _settingsRenderEntries();+ `, context);++ const rows = elements.get('settings-entries')!.children;+ expect(rows).toHaveLength(2);+ expect(rows[0]!.children[1]!.children[0]!.innerHTML).toContain('Orkas-1.5');+ expect(rows[1]!.children[1]!.children[0]!.innerHTML).toContain('Orkas-1.5 Pro');+ expect(rows[0]!.children[1]!.children[1]!.children[1]!.textContent)+ .toContain('DeepSeek V4 · GPT-5.6 Luna · Claude-Sonnet-5 · Gemini-3.6 Flash');+ expect(rows[1]!.children[1]!.children[1]!.children[1]!.textContent)+ .toContain('GPT-5.6 Sol · Claude Opus 5 · Kimi K3');+ });++ it('configures all services from the real card click binding without exposing a clear action', async () => {+ const { context, elements, html, source, invoke, refreshModelGuard } = loadQuickSetupHarness();+ for (const id of [+ 'settings-orkas-api-group',+ 'settings-orkas-api-key-input',+ 'settings-orkas-api-configure',+ ]) expect(html).toContain(`id="${id}"`);+ expect(html).not.toContain('settings-orkas-api-clear');+ expect(source).not.toContain('orkasApi.clearAll');+ expect(source).not.toContain('/v1/capabilities');++ elements.get('settings-orkas-api-key-input')!.value = ' public-orkas-key ';+ await elements.get('settings-orkas-api-create-key')!.click();+ await elements.get('settings-orkas-api-configure')!.click();++ expect(invoke).toHaveBeenCalledWith('auth.openExternal', {+ url: 'https://orkas.ai/views/account/account.html#api-keys',+ });+ expect(invoke).toHaveBeenCalledWith('orkasApi.configureAll', {+ apiKey: 'public-orkas-key',+ });+ expect(elements.get('settings-orkas-api-key-input')!.value).toBe('');+ expect(vm.runInContext('window.__orkasApiRefreshes', context)).toBe(1);+ expect(refreshModelGuard).toHaveBeenCalledOnce();+ });++ it('keeps dynamic setup status bound to an i18n key after language changes', async () => {+ const { context, elements } = loadQuickSetupHarness();+ elements.get('settings-orkas-api-key-input')!.value = 'public-orkas-key';+ await elements.get('settings-orkas-api-configure')!.click();++ const status = elements.get('settings-orkas-api-status')!;+ expect(status.getAttribute('data-i18n')).toBe('settings.orkas_api.configure_ok');+ context.t = (key: string) => `translated:${key}`;+ vm.runInContext('_settingsRenderOrkasApiCard()', context);+ expect(status.textContent).toBe('translated:settings.orkas_api.configure_ok');+ });++ it('supports Enter to configure and blocks an empty key before IPC', async () => {+ const { elements, invoke } = loadQuickSetupHarness();+ const keyInput = elements.get('settings-orkas-api-key-input')!;+ await keyInput.dispatch('keydown', { key: 'Enter', isComposing: false });+ expect(invoke).not.toHaveBeenCalledWith('orkasApi.configureAll', expect.anything());++ keyInput.value = 'enter-key';+ await keyInput.dispatch('keydown', { key: 'Enter', isComposing: false });+ expect(invoke).toHaveBeenCalledWith('orkasApi.configureAll', { apiKey: 'enter-key' });+ });+});diff --git a/test/renderer/settings-tts-errors.test.ts b/test/renderer/settings-tts-errors.test.tsindex 73620bfd..68f377a7 100644--- a/test/renderer/settings-tts-errors.test.ts+++ b/test/renderer/settings-tts-errors.test.ts@@ -62,4 +62,10 @@ describe('TTS settings failure display', () => {expect(addFlow).not.toContain('res.error');expect(addFlow).not.toContain('err.message');});++ it('does not display a configured voice identifier in speech rows', () => {+ const renderFlow = extractFunction('_settingsRenderTtsEntries');+ expect(renderFlow).not.toContain('p.voice');+ expect(renderFlow).toContain("_settingsOrkasServiceLabel('Voice')");+ });});diff --git a/test/renderer/synced-surface-regression.test.ts b/test/renderer/synced-surface-regression.test.tsindex bdfb029b..312c2311 100644--- a/test/renderer/synced-surface-regression.test.ts+++ b/test/renderer/synced-surface-regression.test.ts@@ -162,7 +162,7 @@ describe('synced PC surface regressions', () => {}});- it('restores user-owned speech key configuration without exposing managed Orkas voice', () => {+ it('restores user-owned speech key configuration with the public Orkas voice preset', () => {const html = read('src/renderer/index.html');const settings = read('src/renderer/modules/settings.js');const auth = read('src/main/features/auth.ts');@@ -189,8 +189,9 @@ describe('synced PC surface regressions', () => {expect(ipc).toContain("'ttsAuth.list'");expect(ttsAuth).toContain("id: 'doubao'");expect(ttsAuth).toContain("id: 'openai'");+ expect(ttsAuth).toContain('ORKAS_API_PROVIDER');+ expect(ttsAuth).toContain('Orkas · Voice');expect(ttsAuth).not.toContain('ORKAS_VOICE');- expect(ttsAuth).not.toContain('Orkas · Voice');});it('keeps Settings local execution modes and edits the commander avatar from AI Team', () => {