AI-native design editor. Open-source Figma alternative.
feat(ai): sign in with ChatGPT to use a ChatGPT plan's models (#1405)
Danila Poyarkov81aabbdd3364
diff --git a/changes/1405/added.md b/changes/1405/added.mdnew file mode 100644index 000000000..b9eba13e3--- /dev/null+++ b/changes/1405/added.md@@ -0,0 +1 @@+- The desktop app signs in with ChatGPT, so OpenPencil's agent can use the models of a ChatGPT plan without an API key; the model list comes from the account.diff --git a/desktop/src/lib.rs b/desktop/src/lib.rsindex 1c6e08226..1c44eb9a3 100644--- a/desktop/src/lib.rs+++ b/desktop/src/lib.rs@@ -3,9 +3,9 @@ mod credentials;mod deep_link;mod fig_container;mod fonts;-mod http;mod menu;mod menu_events;+mod network;mod opener;#[cfg(target_os = "macos")]mod window;@@ -17,12 +17,12 @@ use credentials::{use deep_link::path_matches_suffix;use fig_container::build_fig_file;use fonts::{list_system_fonts, load_system_font};-use http::{cancel_http_request, proxy_http_request, ProxyHttpRequests};use menu::{install_app_menu, native_menu_checked, set_native_menu_checked, set_native_menu_features,update_app_menu, NativeMenuInputs, NativeMenuState,};use menu_events::handle_menu_event;+use network::http::{cancel_http_request, proxy_http_request, ProxyHttpRequests};use std::{path::{Path, PathBuf},sync::Mutex,@@ -107,7 +107,12 @@ fn sharing_disabled_by_env() -> bool {.unwrap_or(false)};let do_not_track = std::env::var("DO_NOT_TRACK")- .map(|value| !matches!(value.trim().to_ascii_lowercase().as_str(), "" | "0" | "false"))+ .map(|value| {+ !matches!(+ value.trim().to_ascii_lowercase().as_str(),+ "" | "0" | "false"+ )+ }).unwrap_or(false);is_off("OPENPENCIL_TELEMETRY", &["0", "false", "no"]) || do_not_track}@@ -412,6 +417,7 @@ pub fn run() {builder.manage(PendingOpen(Mutex::new(Vec::new()))).manage(ProxyHttpRequests::default())+ .manage(network::oauth::ChatGPTOAuthLoopback::default()).manage(PendingRooms(Mutex::new(Vec::new()))).manage(NativeMenuState(Mutex::new(NativeMenuInputs::default()))).manage(PendingCloudLinks(Mutex::new(Vec::new())))@@ -419,6 +425,9 @@ pub fn run() {agents::agent_lookup,agents::agent_workspace,build_fig_file,+ network::oauth::chatgpt_oauth_listen,+ network::oauth::chatgpt_oauth_wait,+ network::oauth::chatgpt_oauth_cancel,credential_read,credential_access_paused,credential_retry_access,diff --git a/desktop/src/http.rs b/desktop/src/network/http.rssimilarity index 100%rename from desktop/src/http.rsrename to desktop/src/network/http.rsdiff --git a/desktop/src/network/mod.rs b/desktop/src/network/mod.rsnew file mode 100644index 000000000..c3a7a2be5--- /dev/null+++ b/desktop/src/network/mod.rs@@ -0,0 +1,5 @@+//! Network access the webview cannot do itself: proxied HTTP requests that skip CORS, and the+//! loopback port that receives the ChatGPT sign-in redirect.++pub mod http;+pub mod oauth;diff --git a/desktop/src/network/oauth.rs b/desktop/src/network/oauth.rsnew file mode 100644index 000000000..f710a1873--- /dev/null+++ b/desktop/src/network/oauth.rs@@ -0,0 +1,370 @@+//! Receives the ChatGPT sign-in redirect. OpenAI registers one redirect for the Codex client,+//! `http://localhost:1455/auth/callback`, so the app listens there for the single request that+//! carries the authorization code, then closes the port.++use std::io::{ErrorKind, Read, Write};+use std::net::{TcpListener, TcpStream};+use std::sync::atomic::{AtomicBool, Ordering};+use std::sync::{Arc, Mutex};+use std::time::{Duration, Instant};++use url::Url;++const CALLBACK_ADDRESS: &str = "127.0.0.1:1455";+const CALLBACK_PATH: &str = "/auth/callback";+/// Codes expire after ten minutes; a sign-in left open longer has to start again.+const WAIT_LIMIT: Duration = Duration::from_secs(10 * 60);+const POLL_INTERVAL: Duration = Duration::from_millis(100);+/// A previous sign-in releases the port within one poll after it is cancelled.+const REBIND_LIMIT: Duration = Duration::from_millis(500);+const READ_TIMEOUT: Duration = Duration::from_secs(5);+const MAX_REQUEST_BYTES: usize = 16 * 1024;++/// What the browser tab shows after the redirect, in the app's language.+#[derive(Debug, Clone, serde::Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct CallbackPages {+ signed_in: String,+ cancelled: String,+ stale: String,+}++struct Pending {+ listener: TcpListener,+ state: String,+ pages: CallbackPages,+ cancelled: Arc<AtomicBool>,+}++/// The listener between `chatgpt_oauth_listen` and `chatgpt_oauth_wait`, and the flag that+/// cancels whichever wait is running.+#[derive(Default)]+pub struct ChatGPTOAuthLoopback {+ pending: Mutex<Option<Pending>>,+ /// The attempt listening or waiting, by its state, and the flag that cancels it.+ current: Mutex<Option<(String, Arc<AtomicBool>)>>,+}++#[derive(Debug, PartialEq, Eq, serde::Serialize)]+#[serde(tag = "kind", rename_all = "kebab-case")]+pub enum LoopbackOutcome {+ Code { code: String },+ Denied,+ Expired,+ Cancelled,+}++#[derive(Debug, PartialEq, Eq, serde::Serialize)]+#[serde(rename_all = "kebab-case")]+pub enum LoopbackError {+ /// Another program, usually `codex login`, holds port 1455.+ PortInUse,+ NotListening,+ Failed,+}++#[derive(Debug, PartialEq, Eq)]+enum CallbackRequest {+ Code(String),+ Denied,+ Mismatch,+ Other,+}++/// Reads the request target of a redirect: a code for this attempt, a refusal, or noise.+fn callback_request(target: &str, state: &str) -> CallbackRequest {+ let Ok(url) = Url::parse(&format!("http://localhost{target}")) else {+ return CallbackRequest::Other;+ };+ if url.path() != CALLBACK_PATH {+ return CallbackRequest::Other;+ }+ let param = |name: &str| {+ url.query_pairs()+ .find(|(key, _)| key == name)+ .map(|(_, value)| value.into_owned())+ };+ if param("state").as_deref() != Some(state) {+ return CallbackRequest::Mismatch;+ }+ match param("code") {+ Some(code) if !code.is_empty() => CallbackRequest::Code(code),+ _ => CallbackRequest::Denied,+ }+}++/// The target of an HTTP request line such as `GET /auth/callback?code=… HTTP/1.1`.+fn request_target(head: &str) -> Option<&str> {+ let mut parts = head.lines().next()?.split(' ');+ let method = parts.next()?;+ let target = parts.next()?;+ (method == "GET").then_some(target)+}++fn read_head(stream: &mut TcpStream) -> Option<String> {+ stream.set_nonblocking(false).ok()?;+ stream.set_read_timeout(Some(READ_TIMEOUT)).ok()?;+ let mut head = Vec::new();+ let mut buffer = [0; 1024];+ while !head.windows(4).any(|window| window == b"\r\n\r\n") {+ let read = stream.read(&mut buffer).ok()?;+ if read == 0 || head.len() + read > MAX_REQUEST_BYTES {+ break;+ }+ head.extend_from_slice(&buffer[..read]);+ }+ String::from_utf8(head).ok()+}++fn escape_html(text: &str) -> String {+ text.replace('&', "&")+ .replace('<', "<")+ .replace('>', ">")+ .replace('"', """)+}++fn respond(stream: &mut TcpStream, status: &str, message: &str) {+ let message = escape_html(message);+ let body = format!(+ "<!doctype html><meta charset=\"utf-8\"><title>OpenPencil</title>\+ <p style=\"font:16px system-ui;margin:48px auto;max-width:480px\">{message}</p>"+ );+ let response = format!(+ "HTTP/1.1 {status}\r\nContent-Type: text/html; charset=utf-8\r\n\+ Content-Length: {}\r\nConnection: close\r\n\r\n{body}",+ body.len()+ );+ let _ = stream.write_all(response.as_bytes());+}++fn bind() -> Result<TcpListener, LoopbackError> {+ let started = Instant::now();+ loop {+ match TcpListener::bind(CALLBACK_ADDRESS) {+ Ok(listener) => return Ok(listener),+ Err(error) if error.kind() == ErrorKind::AddrInUse => {+ if started.elapsed() >= REBIND_LIMIT {+ return Err(LoopbackError::PortInUse);+ }+ std::thread::sleep(POLL_INTERVAL);+ }+ Err(_) => return Err(LoopbackError::Failed),+ }+ }+}++fn wait(pending: Pending) -> Result<LoopbackOutcome, LoopbackError> {+ let Pending {+ listener,+ state,+ pages,+ cancelled,+ } = pending;+ listener+ .set_nonblocking(true)+ .map_err(|_| LoopbackError::Failed)?;+ let started = Instant::now();+ loop {+ if cancelled.load(Ordering::SeqCst) {+ return Ok(LoopbackOutcome::Cancelled);+ }+ if started.elapsed() >= WAIT_LIMIT {+ return Ok(LoopbackOutcome::Expired);+ }+ let mut stream = match listener.accept() {+ Ok((stream, _)) => stream,+ Err(error) if error.kind() == ErrorKind::WouldBlock => {+ std::thread::sleep(POLL_INTERVAL);+ continue;+ }+ Err(_) => return Err(LoopbackError::Failed),+ };+ let request = read_head(&mut stream)+ .as_deref()+ .and_then(request_target)+ .map(|target| callback_request(target, &state))+ .unwrap_or(CallbackRequest::Other);+ match request {+ CallbackRequest::Code(code) => {+ respond(&mut stream, "200 OK", &pages.signed_in);+ return Ok(LoopbackOutcome::Code { code });+ }+ CallbackRequest::Denied => {+ respond(&mut stream, "200 OK", &pages.cancelled);+ return Ok(LoopbackOutcome::Denied);+ }+ CallbackRequest::Mismatch => respond(&mut stream, "400 Bad Request", &pages.stale),+ CallbackRequest::Other => respond(&mut stream, "404 Not Found", ""),+ }+ }+}++/// Takes the port before the browser opens, so a busy port is reported instead of a redirect+/// that never arrives. A sign-in still waiting is cancelled.+#[tauri::command]+pub async fn chatgpt_oauth_listen(+ loopback: tauri::State<'_, ChatGPTOAuthLoopback>,+ state: String,+ pages: CallbackPages,+) -> Result<(), LoopbackError> {+ let cancelled = Arc::new(AtomicBool::new(false));+ if let Some((_, previous)) = loopback+ .current+ .lock()+ .map_err(|_| LoopbackError::Failed)?+ .replace((state.clone(), cancelled.clone()))+ {+ previous.store(true, Ordering::SeqCst);+ }+ // A listener taken but never waited on still holds the port.+ loopback+ .pending+ .lock()+ .map_err(|_| LoopbackError::Failed)?+ .take();+ let listener = tauri::async_runtime::spawn_blocking(bind)+ .await+ .map_err(|_| LoopbackError::Failed)??;+ // Cancelled while binding: drop the port rather than hold it for an attempt that is over.+ if cancelled.load(Ordering::SeqCst) {+ return Err(LoopbackError::Failed);+ }+ *loopback.pending.lock().map_err(|_| LoopbackError::Failed)? = Some(Pending {+ listener,+ state,+ pages,+ cancelled,+ });+ Ok(())+}++/// Waits for the redirect on the port `chatgpt_oauth_listen` took, then releases it.+#[tauri::command]+pub async fn chatgpt_oauth_wait(+ loopback: tauri::State<'_, ChatGPTOAuthLoopback>,+) -> Result<LoopbackOutcome, LoopbackError> {+ let pending = loopback+ .pending+ .lock()+ .map_err(|_| LoopbackError::Failed)?+ .take()+ .ok_or(LoopbackError::NotListening)?;+ tauri::async_runtime::spawn_blocking(move || wait(pending))+ .await+ .map_err(|_| LoopbackError::Failed)?+}++impl ChatGPTOAuthLoopback {+ /// Cancels the attempt with this state. A late cancel from an earlier attempt leaves a newer+ /// one alone.+ fn cancel(&self, state: &str) {+ if let Ok(mut current) = self.current.lock() {+ if current.as_ref().is_some_and(|(owner, _)| owner == state) {+ if let Some((_, flag)) = current.take() {+ flag.store(true, Ordering::SeqCst);+ }+ }+ }+ if let Ok(mut pending) = self.pending.lock() {+ if pending+ .as_ref()+ .is_some_and(|listening| listening.state == state)+ {+ pending.take();+ }+ }+ }+}++#[tauri::command]+pub fn chatgpt_oauth_cancel(loopback: tauri::State<'_, ChatGPTOAuthLoopback>, state: String) {+ loopback.cancel(&state);+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn reads_the_code_for_this_attempt() {+ assert_eq!(+ callback_request("/auth/callback?code=abc%2B1&state=s1", "s1"),+ CallbackRequest::Code("abc+1".into())+ );+ }++ #[test]+ fn rejects_another_attempts_state() {+ assert_eq!(+ callback_request("/auth/callback?code=abc&state=old", "s1"),+ CallbackRequest::Mismatch+ );+ assert_eq!(+ callback_request("/auth/callback?code=abc", "s1"),+ CallbackRequest::Mismatch+ );+ }++ #[test]+ fn treats_a_redirect_without_a_code_as_denied() {+ assert_eq!(+ callback_request("/auth/callback?error=access_denied&state=s1", "s1"),+ CallbackRequest::Denied+ );+ }++ #[test]+ fn ignores_other_paths() {+ assert_eq!(+ callback_request("/favicon.ico", "s1"),+ CallbackRequest::Other+ );+ assert_eq!(+ callback_request("/auth/callback/extra?code=a&state=s1", "s1"),+ CallbackRequest::Other+ );+ }++ #[test]+ fn a_late_cancel_leaves_a_newer_attempt_alone() {+ let loopback = ChatGPTOAuthLoopback::default();+ let newer = Arc::new(AtomicBool::new(false));+ *loopback.current.lock().unwrap() = Some(("s2".into(), newer.clone()));+ *loopback.pending.lock().unwrap() = Some(Pending {+ listener: TcpListener::bind("127.0.0.1:0").unwrap(),+ state: "s2".into(),+ pages: CallbackPages {+ signed_in: String::new(),+ cancelled: String::new(),+ stale: String::new(),+ },+ cancelled: newer.clone(),+ });++ loopback.cancel("s1");+ assert!(!newer.load(Ordering::SeqCst));+ assert!(loopback.pending.lock().unwrap().is_some());++ loopback.cancel("s2");+ assert!(newer.load(Ordering::SeqCst));+ assert!(loopback.pending.lock().unwrap().is_none());+ }++ #[test]+ fn escapes_page_text() {+ assert_eq!(+ escape_html("<b>\"Tom & Jerry\"</b>"),+ "<b>"Tom & Jerry"</b>"+ );+ }++ #[test]+ fn reads_only_get_request_targets() {+ assert_eq!(+ request_target("GET /auth/callback?code=a HTTP/1.1\r\nHost: localhost\r\n\r\n"),+ Some("/auth/callback?code=a")+ );+ assert_eq!(request_target("POST /auth/callback HTTP/1.1\r\n\r\n"), None);+ assert_eq!(request_target(""), None);+ }+}diff --git a/packages/core/src/ai/providers.ts b/packages/core/src/ai/providers.tsindex 6ea2dda17..5b9beaee5 100644--- a/packages/core/src/ai/providers.ts+++ b/packages/core/src/ai/providers.ts@@ -63,6 +63,7 @@ export type AIProviderID =| 'openrouter'| 'anthropic'| 'openai'+ | 'chatgpt'| 'google'| 'deepseek'| 'openai-compatible'@@ -96,8 +97,28 @@ export interface AIProviderDef {defaultModel: stringsupportsCustomBaseURL?: booleansupportsCustomModel?: boolean+ /** The credential comes from signing in to an account; there is no key to paste. */+ signInOnly?: boolean}+const OPENAI_MODELS: ModelOption[] = [+ {+ id: 'gpt-6.1-sol',+ name: 'GPT-6.1 Sol',+ tag: 'Best',+ capabilities: ['tools', 'vision'],+ minReasoningEffort: 'low'+ },+ {+ id: 'gpt-6-astra',+ name: 'GPT-6 Astra',+ tag: 'Smartest',+ capabilities: ['tools', 'vision'],+ minReasoningEffort: 'low'+ },+ { id: 'gpt-6-luna', name: 'GPT-6 Luna', tag: 'Fast', capabilities: ['tools', 'vision'] }+]+export const HARNESS_PROVIDER_ID = 'harness:pi' as constexport const AI_PROVIDERS: AIProviderDef[] = [@@ -220,23 +241,17 @@ export const AI_PROVIDERS: AIProviderDef[] = [keyPlaceholder: 'sk-…',keyURL: 'https://platform.openai.com/api-keys',defaultModel: 'gpt-6.1-sol',- models: [- {- id: 'gpt-6.1-sol',- name: 'GPT-6.1 Sol',- tag: 'Best',- capabilities: ['tools', 'vision'],- minReasoningEffort: 'low'- },- {- id: 'gpt-6-astra',- name: 'GPT-6 Astra',- tag: 'Smartest',- capabilities: ['tools', 'vision'],- minReasoningEffort: 'low'- },- { id: 'gpt-6-luna', name: 'GPT-6 Luna', tag: 'Fast', capabilities: ['tools', 'vision'] }- ]+ models: OPENAI_MODELS+ },+ {+ id: 'chatgpt',+ name: 'ChatGPT',+ keyPlaceholder: '',+ keyURL: '',+ defaultModel: 'gpt-6.1-sol',+ signInOnly: true,+ // The Codex backend rejects minimal effort on every model.+ models: OPENAI_MODELS.map((model) => ({ ...model, minReasoningEffort: 'low' }))},{id: 'google',diff --git a/packages/docs/programmable/ai-chat.md b/packages/docs/programmable/ai-chat.mdindex f0500d703..a090ed4a6 100644--- a/packages/docs/programmable/ai-chat.md+++ b/packages/docs/programmable/ai-chat.md@@ -51,6 +51,7 @@ In the Chat settings beside the model overview, choose whether reasoning is **Co| **OpenRouter** | Claude, GPT, Gemini, DeepSeek, Qwen, and others | API key from [openrouter.ai](https://openrouter.ai) || **Anthropic** | Claude Sonnet 5.5, Claude Opus 5.5, Claude Fable 5.1, Claude Haiku 5.5 | API key from [console.anthropic.com](https://console.anthropic.com) || **OpenAI** | GPT-6.1 Sol, GPT-6 Astra, GPT-6 Luna | API key from [platform.openai.com](https://platform.openai.com) |+| **ChatGPT** | The models your ChatGPT plan offers in Codex, listed live | Desktop app: **Sign in with ChatGPT**. Replies count toward the plan's usage limits. || **Google AI** | Gemini 3.8 Flash, Gemini 4 Argon | API key from [aistudio.google.dev](https://aistudio.google.dev) || **DeepSeek** | DeepSeek Flash, DeepSeek V4 Pro | API key from [platform.deepseek.com](https://platform.deepseek.com/api_keys) || **Z.ai** | GLM-5.3, GLM-5.3-Flash, GLM-5.3-FlashX, GLM-5V-Turbo | API key from [docs.z.ai](https://docs.z.ai/devpack/quick-start) |@@ -58,7 +59,9 @@ In the Chat settings beside the model overview, choose whether reasoning is **Co| **OpenAI-compatible** | Any endpoint with OpenAI API format | Custom base URL + key. Supports Completions and Responses API toggle. || **Anthropic-compatible** | Any endpoint with Anthropic API format | Custom base URL + key |-No backend, no subscription — your key talks directly to the provider. Browser requests are subject to each provider's CORS policy, and model deployments vary in how reliably they stream tool calls. See [BYOK provider and model compatibility](./byok-provider-compatibility) for measured results and reproduction steps.+No backend — your key or sign-in talks directly to the provider. Browser requests are subject to each provider's CORS policy, and model deployments vary in how reliably they stream tool calls. See [BYOK provider and model compatibility](./byok-provider-compatibility) for measured results and reproduction steps.++**ChatGPT** uses your ChatGPT plan instead of an API key, through the same backend and sign-in as OpenAI's Codex CLI. Signing in opens the browser and returns to the desktop app on `localhost:1455`, the only address OpenAI accepts for it, so close a running `codex login` first. The sign-in is stored like a key and refreshes itself; the model list comes from your account. The browser app does not offer it.## External MCP connectionsdiff --git a/packages/feedback/src/contract/schema.ts b/packages/feedback/src/contract/schema.tsindex 6ef995706..2a7bb4e5a 100644--- a/packages/feedback/src/contract/schema.ts+++ b/packages/feedback/src/contract/schema.ts@@ -26,6 +26,7 @@ export const AI_PROVIDERS = ['openrouter','anthropic','openai',+ 'chatgpt','google','deepseek','openai-compatible',diff --git a/packages/vue/src/i18n/locales/de/ai.json b/packages/vue/src/i18n/locales/de/ai.jsonindex 37151068a..b651f310d 100644--- a/packages/vue/src/i18n/locales/de/ai.json+++ b/packages/vue/src/i18n/locales/de/ai.json@@ -4,10 +4,13 @@"maxAgentStepsRange": "Gib eine ganze Zahl von {min} bis {max} ein.","connectionTestSuccess": "Verbindung erfolgreich. Das Modell ist erreichbar.","connectionTestMissingAPIKey": "Gib vor dem Testen einen API-Schlüssel ein.",+ "connectionTestMissingSignIn": "Melde dich vor dem Testen an.","connectionTestMissingBaseURL": "Gib vor dem Testen eine Basis-URL ein.","connectionTestMissingModel": "Gib vor dem Testen eine Modell-ID ein.","connectionTestInvalidBaseURL": "Die Basis-URL ist ungültig. Verwende eine vollständige URL wie https://api.example.com/v1.","connectionTestAuthFailed": "Authentifizierung fehlgeschlagen. Prüfe deinen API-Schlüssel.",+ "connectionTestSignInExpired": "Die Anmeldung ist abgelaufen. Melde dich erneut an.",+ "connectionTestPlanForbidden": "Dein Tarif kann dieses Modell nicht nutzen. Wähle ein anderes Modell.","connectionTestInsufficientCredit": "Das Anbieterkonto hat nicht genügend Guthaben oder Kontingent. Lade es auf und versuche es erneut.","connectionTestModelNotFound": "Modell nicht gefunden. Prüfe die Modell-ID.","connectionTestAPITypeMismatch": "Dieser Endpunkt scheint den ausgewählten API-Typ nicht zu unterstützen. Versuche Completions oder Responses.",@@ -134,6 +137,8 @@"outputLimitAutomatic": "Automatische Empfehlung","maxOutputTokens": "Maximale Ausgabetoken","chatAuthenticationFailed": "Der API-Schlüssel des Anbieters ist ungültig oder abgelaufen. Ersetze ihn in den Einstellungen.",+ "chatSignInExpired": "Deine Anmeldung ist abgelaufen. Melde dich in den Einstellungen erneut an.",+ "chatPlanForbidden": "Dein Tarif kann das ausgewählte Modell nicht nutzen. Wähle in den Einstellungen ein anderes Modell.","chatForbidden": "Dieser API-Schlüssel kann das ausgewählte Modell nicht verwenden. Prüfe den Modellzugriff.","chatModelNotFound": "Das ausgewählte Modell ist nicht verfügbar. Wähle in den Einstellungen ein anderes Modell.","chatNetworkFailed": "OpenPencil konnte den Anbieter nicht erreichen. Prüfe die Verbindung und den Endpunkt.",@@ -235,18 +240,31 @@"aiSetupAlreadyConnected": "Alles, was du ausgewählt hast, ist bereits verbunden.","aiSetupOpenRouterSignIn": "Mit OpenRouter anmelden","aiSetupOpenRouterWaiting": "Schließe die Anmeldung bei OpenRouter in deinem Browser ab.",- "aiSetupOpenRouterReopen": "Erneut öffnen",+ "aiSetupSignInReopen": "Erneut öffnen","aiSetupOpenRouterOrKey": "Oder einen API-Schlüssel einfügen","aiSetupOpenRouterBlocked": "Dein Browser hat das Anmeldefenster blockiert. Erlaube Pop-ups für OpenPencil und versuche es erneut.",- "aiSetupOpenRouterCancelled": "Die Anmeldung wurde abgebrochen.",- "aiSetupOpenRouterExpired": "Die Anmeldung hat zu lange gedauert. Versuche es erneut.",+ "aiSetupSignInCancelled": "Die Anmeldung wurde abgebrochen.",+ "aiSetupSignInExpired": "Die Anmeldung hat zu lange gedauert. Versuche es erneut.","aiSetupOpenRouterFailed": "Die Anmeldung bei OpenRouter ist fehlgeschlagen. Versuche es erneut oder füge einen API-Schlüssel ein.","aiSetupOpenRouterSignedInTitle": "Bei OpenRouter angemeldet","aiSetupSavedKeyHint": "Leer lassen, um den gespeicherten Schlüssel zu behalten.","aiSetupOpenRouterKeyLabel": "· Schlüssel „{label}“","aiSetupOpenRouterVerifying": "Dein OpenRouter-Schlüssel wird geprüft…","aiSetupOpenRouterNoCredits": "Dieses OpenRouter-Konto hat noch kein Guthaben. Lade bei OpenRouter Guthaben auf, um kostenpflichtige Modelle wie das empfohlene zu nutzen.",- "aiSetupOpenRouterChange": "Anderes Konto verwenden",+ "aiSetupSignInChange": "Anderes Konto verwenden",+ "aiSetupSignOut": "Abmelden",+ "aiSetupAccessSubscriptions": "Abos",+ "aiSetupAccessChatGPT": "Nutze die Modelle deines ChatGPT-Abos im eigenen Agenten von OpenPencil.",+ "aiSetupChatGPTSignIn": "Mit ChatGPT anmelden",+ "aiSetupChatGPTWaiting": "Schließe die Anmeldung bei ChatGPT in deinem Browser ab.",+ "aiSetupChatGPTSignedInTitle": "Bei ChatGPT angemeldet",+ "aiSetupChatGPTFailed": "Anmeldung bei ChatGPT fehlgeschlagen. Versuche es erneut.",+ "aiSetupChatGPTPortInUse": "Eine andere Anmeldung, etwa `codex login`, belegt Port 1455. Schließe sie ab oder beende sie und versuche es erneut.",+ "aiSetupChatGPTCallbackSignedIn": "Bei ChatGPT angemeldet. Du kannst diesen Tab schließen und zu OpenPencil zurückkehren.",+ "aiSetupChatGPTCallbackCancelled": "Die Anmeldung bei ChatGPT wurde abgebrochen. Du kannst diesen Tab schließen.",+ "aiSetupChatGPTCallbackStale": "Dieser Anmeldelink gehört zu einem früheren Versuch. Starte erneut in OpenPencil.",+ "aiSetupChatGPTUsage": "Antworten zählen zu den Nutzungslimits deines ChatGPT-Abos.",+ "aiSetupSavedSignInHint": "Deine gespeicherte Anmeldung wird verwendet.","aiSetupUseRecommended": "Empfohlene Einrichtung verwenden","aiSetupRolesDescription": "Wähle für jede Art von Arbeit ein Modell. Wir haben aus deinen Verbindungen empfohlene ausgewählt; alles andere, was du eingerichtet hast, bleibt unverändert.","aiSetupGapDesign": "Nichts von deiner Auswahl kann Designs erstellen und bearbeiten.",diff --git a/packages/vue/src/i18n/locales/de/common.json b/packages/vue/src/i18n/locales/de/common.jsonindex 2904ccbc4..af1b2a662 100644--- a/packages/vue/src/i18n/locales/de/common.json+++ b/packages/vue/src/i18n/locales/de/common.json@@ -32,6 +32,7 @@"noResults": "Keine Ergebnisse","save": "Speichern","done": "Fertig",+ "task": "Aufgabe","back": "Zurück","supported": "Unterstützt","unsupported": "Nicht unterstützt",diff --git a/packages/vue/src/i18n/locales/es/ai.json b/packages/vue/src/i18n/locales/es/ai.jsonindex de7d326c9..544ad0c36 100644--- a/packages/vue/src/i18n/locales/es/ai.json+++ b/packages/vue/src/i18n/locales/es/ai.json@@ -4,10 +4,13 @@"maxAgentStepsRange": "Introduce un número entero entre {min} y {max}.","connectionTestSuccess": "Conexión correcta. Se puede acceder al modelo.","connectionTestMissingAPIKey": "Introduce una clave API antes de probar.",+ "connectionTestMissingSignIn": "Inicia sesión antes de probar.","connectionTestMissingBaseURL": "Introduce una URL base antes de probar.","connectionTestMissingModel": "Introduce un ID de modelo antes de probar.","connectionTestInvalidBaseURL": "La URL base no es válida. Usa una URL completa como https://api.example.com/v1.","connectionTestAuthFailed": "Error de autenticación. Comprueba tu clave API.",+ "connectionTestSignInExpired": "La sesión ha caducado. Vuelve a iniciar sesión.",+ "connectionTestPlanForbidden": "Tu plan no puede usar este modelo. Elige otro modelo.","connectionTestInsufficientCredit": "La cuenta del proveedor no tiene suficiente saldo o cuota. Recárgala e inténtalo de nuevo.","connectionTestModelNotFound": "No se ha encontrado el modelo. Comprueba el ID del modelo.","connectionTestAPITypeMismatch": "Este endpoint no parece admitir el tipo de API seleccionado. Prueba Completions o Responses.",@@ -140,6 +143,8 @@"outputLimitAutomatic": "Recomendación automática","maxOutputTokens": "Tokens de salida máx.","chatAuthenticationFailed": "La clave API del proveedor no es válida o ha caducado. Sustitúyela en Ajustes.",+ "chatSignInExpired": "Tu sesión ha caducado. Vuelve a iniciar sesión en Ajustes.",+ "chatPlanForbidden": "Tu plan no puede usar el modelo seleccionado. Elige otro modelo en Ajustes.","chatForbidden": "Esta clave API no puede usar el modelo seleccionado. Comprueba el acceso al modelo.","chatModelNotFound": "El modelo seleccionado no está disponible. Elige otro modelo en Ajustes.","chatNetworkFailed": "OpenPencil no pudo acceder al proveedor. Comprueba la conexión y el endpoint.",@@ -235,18 +240,31 @@"aiSetupAlreadyConnected": "Todo lo que seleccionaste ya está conectado.","aiSetupOpenRouterSignIn": "Iniciar sesión con OpenRouter","aiSetupOpenRouterWaiting": "Termina de iniciar sesión en OpenRouter en tu navegador.",- "aiSetupOpenRouterReopen": "Abrir de nuevo",+ "aiSetupSignInReopen": "Abrir de nuevo","aiSetupOpenRouterOrKey": "O pega una clave de API","aiSetupOpenRouterBlocked": "Tu navegador bloqueó la ventana de inicio de sesión. Permite ventanas emergentes para OpenPencil y vuelve a intentarlo.",- "aiSetupOpenRouterCancelled": "Se canceló el inicio de sesión.",- "aiSetupOpenRouterExpired": "El inicio de sesión tardó demasiado. Vuelve a intentarlo.",+ "aiSetupSignInCancelled": "Se canceló el inicio de sesión.",+ "aiSetupSignInExpired": "El inicio de sesión tardó demasiado. Vuelve a intentarlo.","aiSetupOpenRouterFailed": "No se pudo iniciar sesión en OpenRouter. Vuelve a intentarlo o pega una clave de API.","aiSetupOpenRouterSignedInTitle": "Sesión iniciada en OpenRouter","aiSetupSavedKeyHint": "Déjalo en blanco para conservar la clave guardada.","aiSetupOpenRouterKeyLabel": "· clave «{label}»","aiSetupOpenRouterVerifying": "Comprobando tu clave de OpenRouter…","aiSetupOpenRouterNoCredits": "Esta cuenta de OpenRouter aún no tiene créditos. Añade créditos en OpenRouter para usar modelos de pago como el recomendado.",- "aiSetupOpenRouterChange": "Usar otra cuenta",+ "aiSetupSignInChange": "Usar otra cuenta",+ "aiSetupSignOut": "Cerrar sesión",+ "aiSetupAccessSubscriptions": "Suscripciones",+ "aiSetupAccessChatGPT": "Usa los modelos de tu plan de ChatGPT en el agente propio de OpenPencil.",+ "aiSetupChatGPTSignIn": "Iniciar sesión con ChatGPT",+ "aiSetupChatGPTWaiting": "Termina de iniciar sesión en ChatGPT en tu navegador.",+ "aiSetupChatGPTSignedInTitle": "Sesión iniciada en ChatGPT",+ "aiSetupChatGPTFailed": "No se pudo iniciar sesión en ChatGPT. Inténtalo de nuevo.",+ "aiSetupChatGPTPortInUse": "Otro inicio de sesión, como `codex login`, está usando el puerto 1455. Termínalo o ciérralo y vuelve a intentarlo.",+ "aiSetupChatGPTCallbackSignedIn": "Sesión iniciada en ChatGPT. Puedes cerrar esta pestaña y volver a OpenPencil.",+ "aiSetupChatGPTCallbackCancelled": "Se canceló el inicio de sesión en ChatGPT. Puedes cerrar esta pestaña.",+ "aiSetupChatGPTCallbackStale": "Este enlace de inicio de sesión pertenece a un intento anterior. Vuelve a empezar desde OpenPencil.",+ "aiSetupChatGPTUsage": "Las respuestas cuentan para los límites de uso de tu plan de ChatGPT.",+ "aiSetupSavedSignInHint": "Se usará tu sesión guardada.","aiSetupUseRecommended": "Usar la configuración recomendada","aiSetupRolesDescription": "Elige un modelo para cada tipo de trabajo. Elegimos los recomendados entre lo que conectaste; todo lo demás que configuraste se mantiene igual.","aiSetupGapDesign": "Nada de lo que elegiste puede crear y editar diseños.",diff --git a/packages/vue/src/i18n/locales/es/common.json b/packages/vue/src/i18n/locales/es/common.jsonindex e1afff928..544b5fc26 100644--- a/packages/vue/src/i18n/locales/es/common.json+++ b/packages/vue/src/i18n/locales/es/common.json@@ -32,6 +32,7 @@"noResults": "Sin resultados","save": "Guardar","done": "Hecho",+ "task": "Tarea","back": "Atrás","supported": "Compatible","unsupported": "No compatible",diff --git a/packages/vue/src/i18n/locales/fr/ai.json b/packages/vue/src/i18n/locales/fr/ai.jsonindex e7531cea0..8131fcc6b 100644--- a/packages/vue/src/i18n/locales/fr/ai.json+++ b/packages/vue/src/i18n/locales/fr/ai.json@@ -4,10 +4,13 @@"maxAgentStepsRange": "Saisissez un nombre entier entre {min} et {max}.","connectionTestSuccess": "Connexion réussie. Le modèle est accessible.","connectionTestMissingAPIKey": "Saisissez une clé API avant le test.",+ "connectionTestMissingSignIn": "Connectez-vous avant le test.","connectionTestMissingBaseURL": "Saisissez une URL de base avant le test.","connectionTestMissingModel": "Saisissez un ID de modèle avant le test.","connectionTestInvalidBaseURL": "L’URL de base est invalide. Utilisez une URL complète comme https://api.example.com/v1.","connectionTestAuthFailed": "Échec de l’authentification. Vérifiez votre clé API.",+ "connectionTestSignInExpired": "La connexion a expiré. Reconnectez-vous.",+ "connectionTestPlanForbidden": "Votre forfait ne permet pas d’utiliser ce modèle. Choisissez-en un autre.","connectionTestInsufficientCredit": "Le compte du fournisseur n’a pas assez de crédit ou de quota. Rechargez-le et réessayez.","connectionTestModelNotFound": "Modèle introuvable. Vérifiez son ID.","connectionTestAPITypeMismatch": "Ce point de terminaison ne semble pas prendre en charge le type d’API sélectionné. Essayez Completions ou Responses.",@@ -134,6 +137,8 @@"outputLimitAutomatic": "Recommandation automatique","maxOutputTokens": "Jetons de sortie maximum","chatAuthenticationFailed": "La clé API du fournisseur est invalide ou expirée. Remplacez-la dans les paramètres.",+ "chatSignInExpired": "Votre connexion a expiré. Reconnectez-vous dans les paramètres.",+ "chatPlanForbidden": "Votre forfait ne permet pas d’utiliser le modèle sélectionné. Choisissez-en un autre dans les paramètres.","chatForbidden": "Cette clé API ne peut pas utiliser le modèle sélectionné. Vérifiez son accès au modèle.","chatModelNotFound": "Le modèle sélectionné est indisponible. Choisissez-en un autre dans les paramètres.","chatNetworkFailed": "OpenPencil n’a pas pu joindre le fournisseur. Vérifiez la connexion et le point de terminaison.",@@ -235,18 +240,31 @@"aiSetupAlreadyConnected": "Tout ce que vous avez sélectionné est déjà connecté.","aiSetupOpenRouterSignIn": "Se connecter avec OpenRouter","aiSetupOpenRouterWaiting": "Terminez la connexion à OpenRouter dans votre navigateur.",- "aiSetupOpenRouterReopen": "Rouvrir",+ "aiSetupSignInReopen": "Rouvrir","aiSetupOpenRouterOrKey": "Ou collez une clé API","aiSetupOpenRouterBlocked": "Votre navigateur a bloqué la fenêtre de connexion. Autorisez les fenêtres contextuelles pour OpenPencil, puis réessayez.",- "aiSetupOpenRouterCancelled": "La connexion a été annulée.",- "aiSetupOpenRouterExpired": "La connexion a pris trop de temps. Réessayez.",+ "aiSetupSignInCancelled": "La connexion a été annulée.",+ "aiSetupSignInExpired": "La connexion a pris trop de temps. Réessayez.","aiSetupOpenRouterFailed": "Impossible de se connecter à OpenRouter. Réessayez ou collez une clé API.","aiSetupOpenRouterSignedInTitle": "Connecté à OpenRouter","aiSetupSavedKeyHint": "Laissez vide pour conserver la clé enregistrée.","aiSetupOpenRouterKeyLabel": "· clé « {label} »","aiSetupOpenRouterVerifying": "Vérification de votre clé OpenRouter…","aiSetupOpenRouterNoCredits": "Ce compte OpenRouter n’a pas encore de crédits. Ajoutez des crédits sur OpenRouter pour utiliser des modèles payants comme celui recommandé.",- "aiSetupOpenRouterChange": "Utiliser un autre compte",+ "aiSetupSignInChange": "Utiliser un autre compte",+ "aiSetupSignOut": "Se déconnecter",+ "aiSetupAccessSubscriptions": "Abonnements",+ "aiSetupAccessChatGPT": "Utilisez les modèles de votre forfait ChatGPT dans l’agent d’OpenPencil.",+ "aiSetupChatGPTSignIn": "Se connecter avec ChatGPT",+ "aiSetupChatGPTWaiting": "Terminez la connexion à ChatGPT dans votre navigateur.",+ "aiSetupChatGPTSignedInTitle": "Connecté à ChatGPT",+ "aiSetupChatGPTFailed": "Impossible de se connecter à ChatGPT. Réessayez.",+ "aiSetupChatGPTPortInUse": "Une autre connexion, comme `codex login`, utilise le port 1455. Terminez-la ou fermez-la, puis réessayez.",+ "aiSetupChatGPTCallbackSignedIn": "Connecté à ChatGPT. Vous pouvez fermer cet onglet et revenir à OpenPencil.",+ "aiSetupChatGPTCallbackCancelled": "La connexion à ChatGPT a été annulée. Vous pouvez fermer cet onglet.",+ "aiSetupChatGPTCallbackStale": "Ce lien de connexion appartient à une tentative précédente. Recommencez depuis OpenPencil.",+ "aiSetupChatGPTUsage": "Les réponses sont décomptées des limites d’utilisation de votre forfait ChatGPT.",+ "aiSetupSavedSignInHint": "Votre connexion enregistrée sera utilisée.","aiSetupUseRecommended": "Utiliser la configuration recommandée","aiSetupRolesDescription": "Choisissez un modèle pour chaque type de travail. Nous avons choisi ceux recommandés parmi ce que vous avez connecté ; tout le reste de votre configuration reste inchangé.","aiSetupGapDesign": "Rien de ce que vous avez choisi ne peut créer et modifier des designs.",diff --git a/packages/vue/src/i18n/locales/fr/common.json b/packages/vue/src/i18n/locales/fr/common.jsonindex e62208ad8..637c4da8e 100644--- a/packages/vue/src/i18n/locales/fr/common.json+++ b/packages/vue/src/i18n/locales/fr/common.json@@ -32,6 +32,7 @@"noResults": "Aucun résultat","save": "Enregistrer","done": "Terminé",+ "task": "Tâche","back": "Retour","supported": "Pris en charge","unsupported": "Non pris en charge",diff --git a/packages/vue/src/i18n/locales/it/ai.json b/packages/vue/src/i18n/locales/it/ai.jsonindex dc92cf21b..11679c97c 100644--- a/packages/vue/src/i18n/locales/it/ai.json+++ b/packages/vue/src/i18n/locales/it/ai.json@@ -4,10 +4,13 @@"maxAgentStepsRange": "Inserisci un numero intero da {min} a {max}.","connectionTestSuccess": "Connessione riuscita. Il modello è raggiungibile.","connectionTestMissingAPIKey": "Inserisci una chiave API prima della verifica.",+ "connectionTestMissingSignIn": "Accedi prima della verifica.","connectionTestMissingBaseURL": "Inserisci un URL di base prima della verifica.","connectionTestMissingModel": "Inserisci un ID modello prima della verifica.","connectionTestInvalidBaseURL": "L’URL di base non è valido. Usa un URL completo come https://api.example.com/v1.","connectionTestAuthFailed": "Autenticazione non riuscita. Controlla la chiave API.",+ "connectionTestSignInExpired": "L’accesso è scaduto. Accedi di nuovo.",+ "connectionTestPlanForbidden": "Il tuo piano non può usare questo modello. Scegline un altro.","connectionTestInsufficientCredit": "L’account del provider non dispone di credito o quota sufficiente. Ricaricalo e riprova.","connectionTestModelNotFound": "Modello non trovato. Controlla l’ID modello.","connectionTestAPITypeMismatch": "Questo endpoint non sembra supportare il tipo di API selezionato. Prova Completions o Responses.",@@ -140,6 +143,8 @@"outputLimitAutomatic": "Raccomandazione automatica","maxOutputTokens": "Token di output massimi","chatAuthenticationFailed": "La chiave API del provider non è valida o è scaduta. Sostituiscila nelle Impostazioni.",+ "chatSignInExpired": "Il tuo accesso è scaduto. Accedi di nuovo nelle Impostazioni.",+ "chatPlanForbidden": "Il tuo piano non può usare il modello selezionato. Scegline un altro nelle Impostazioni.","chatForbidden": "Questa chiave API non può usare il modello selezionato. Controlla l’accesso al modello.","chatModelNotFound": "Il modello selezionato non è disponibile. Scegli un altro modello nelle Impostazioni.","chatNetworkFailed": "OpenPencil non ha raggiunto il provider. Controlla connessione ed endpoint.",@@ -235,18 +240,31 @@"aiSetupAlreadyConnected": "Tutto ciò che hai selezionato è già collegato.","aiSetupOpenRouterSignIn": "Accedi con OpenRouter","aiSetupOpenRouterWaiting": "Completa l’accesso a OpenRouter nel browser.",- "aiSetupOpenRouterReopen": "Apri di nuovo",+ "aiSetupSignInReopen": "Apri di nuovo","aiSetupOpenRouterOrKey": "Oppure incolla una chiave API","aiSetupOpenRouterBlocked": "Il browser ha bloccato la finestra di accesso. Consenti i pop-up per OpenPencil e riprova.",- "aiSetupOpenRouterCancelled": "L’accesso è stato annullato.",- "aiSetupOpenRouterExpired": "L’accesso ha richiesto troppo tempo. Riprova.",+ "aiSetupSignInCancelled": "L’accesso è stato annullato.",+ "aiSetupSignInExpired": "L’accesso ha richiesto troppo tempo. Riprova.","aiSetupOpenRouterFailed": "Impossibile accedere a OpenRouter. Riprova o incolla una chiave API.","aiSetupOpenRouterSignedInTitle": "Accesso a OpenRouter eseguito","aiSetupSavedKeyHint": "Lascia vuoto per mantenere la chiave salvata.","aiSetupOpenRouterKeyLabel": "· chiave «{label}»","aiSetupOpenRouterVerifying": "Verifica della chiave OpenRouter…","aiSetupOpenRouterNoCredits": "Questo account OpenRouter non ha ancora crediti. Aggiungi crediti su OpenRouter per usare modelli a pagamento come quello consigliato.",- "aiSetupOpenRouterChange": "Usa un altro account",+ "aiSetupSignInChange": "Usa un altro account",+ "aiSetupSignOut": "Esci",+ "aiSetupAccessSubscriptions": "Abbonamenti",+ "aiSetupAccessChatGPT": "Usa i modelli del tuo piano ChatGPT nell’agente di OpenPencil.",+ "aiSetupChatGPTSignIn": "Accedi con ChatGPT",+ "aiSetupChatGPTWaiting": "Completa l’accesso a ChatGPT nel browser.",+ "aiSetupChatGPTSignedInTitle": "Accesso a ChatGPT eseguito",+ "aiSetupChatGPTFailed": "Impossibile accedere a ChatGPT. Riprova.",+ "aiSetupChatGPTPortInUse": "Un altro accesso, come `codex login`, sta usando la porta 1455. Completalo o chiudilo, poi riprova.",+ "aiSetupChatGPTCallbackSignedIn": "Accesso a ChatGPT eseguito. Puoi chiudere questa scheda e tornare a OpenPencil.",+ "aiSetupChatGPTCallbackCancelled": "L’accesso a ChatGPT è stato annullato. Puoi chiudere questa scheda.",+ "aiSetupChatGPTCallbackStale": "Questo link di accesso appartiene a un tentativo precedente. Ricomincia da OpenPencil.",+ "aiSetupChatGPTUsage": "Le risposte rientrano nei limiti di utilizzo del tuo piano ChatGPT.",+ "aiSetupSavedSignInHint": "Verrà usato l’accesso salvato.","aiSetupUseRecommended": "Usa la configurazione consigliata","aiSetupRolesDescription": "Scegli un modello per ogni tipo di lavoro. Abbiamo scelto quelli consigliati tra ciò che hai collegato; tutto il resto che hai configurato resta invariato.","aiSetupGapDesign": "Nulla di ciò che hai scelto può creare e modificare design.",diff --git a/packages/vue/src/i18n/locales/it/common.json b/packages/vue/src/i18n/locales/it/common.jsonindex ddb3b892a..9ee9ba5cb 100644--- a/packages/vue/src/i18n/locales/it/common.json+++ b/packages/vue/src/i18n/locales/it/common.json@@ -32,6 +32,7 @@"noResults": "Nessun risultato","save": "Salva","done": "Fatto",+ "task": "Attività","back": "Indietro","supported": "Supportato","unsupported": "Non supportato",diff --git a/packages/vue/src/i18n/locales/ja/ai.json b/packages/vue/src/i18n/locales/ja/ai.jsonindex d7afeaf8b..be1b3292c 100644--- a/packages/vue/src/i18n/locales/ja/ai.json+++ b/packages/vue/src/i18n/locales/ja/ai.json@@ -4,10 +4,13 @@"maxAgentStepsRange": "{min} から {max} までの整数を入力してください。","connectionTestSuccess": "接続しました。モデルにアクセスできます。","connectionTestMissingAPIKey": "テストする前にAPIキーを入力してください。",+ "connectionTestMissingSignIn": "テストする前にサインインしてください。","connectionTestMissingBaseURL": "テストする前にベースURLを入力してください。","connectionTestMissingModel": "テストする前にモデルIDを入力してください。","connectionTestInvalidBaseURL": "ベースURLが無効です。https://api.example.com/v1 のような完全なURLを使用してください。","connectionTestAuthFailed": "認証に失敗しました。APIキーを確認してください。",+ "connectionTestSignInExpired": "サインインの有効期限が切れました。もう一度サインインしてください。",+ "connectionTestPlanForbidden": "ご利用のプランではこのモデルを使用できません。別のモデルを選んでください。","connectionTestInsufficientCredit": "プロバイダーのアカウントに十分なクレジットまたは割り当てがありません。チャージして再試行してください。","connectionTestModelNotFound": "モデルが見つかりません。モデルIDを確認してください。","connectionTestAPITypeMismatch": "このエンドポイントは選択したAPIタイプに対応していないようです。CompletionsまたはResponsesをお試しください。",@@ -140,6 +143,8 @@"outputLimitAutomatic": "自動推奨値","maxOutputTokens": "最大出力トークン数","chatAuthenticationFailed": "プロバイダーのAPIキーが無効か期限切れです。設定で置き換えてください。",+ "chatSignInExpired": "サインインの有効期限が切れました。設定でもう一度サインインしてください。",+ "chatPlanForbidden": "ご利用のプランでは選択したモデルを使用できません。設定で別のモデルを選んでください。","chatForbidden": "このAPIキーでは選択したモデルを使用できません。モデルへのアクセス権を確認してください。","chatModelNotFound": "選択したモデルは利用できません。設定で別のモデルを選択してください。","chatNetworkFailed": "OpenPencilからプロバイダーに接続できませんでした。接続とエンドポイントを確認してください。",@@ -235,18 +240,31 @@"aiSetupAlreadyConnected": "選んだものはすべて接続済みです。","aiSetupOpenRouterSignIn": "OpenRouter でサインイン","aiSetupOpenRouterWaiting": "ブラウザで OpenRouter へのサインインを完了してください。",- "aiSetupOpenRouterReopen": "もう一度開く",+ "aiSetupSignInReopen": "もう一度開く","aiSetupOpenRouterOrKey": "または API キーを貼り付け","aiSetupOpenRouterBlocked": "ブラウザがサインイン用のウィンドウをブロックしました。OpenPencil のポップアップを許可してから、もう一度お試しください。",- "aiSetupOpenRouterCancelled": "サインインはキャンセルされました。",- "aiSetupOpenRouterExpired": "サインインに時間がかかりすぎました。もう一度お試しください。",+ "aiSetupSignInCancelled": "サインインはキャンセルされました。",+ "aiSetupSignInExpired": "サインインに時間がかかりすぎました。もう一度お試しください。","aiSetupOpenRouterFailed": "OpenRouter にサインインできませんでした。もう一度試すか、API キーを貼り付けてください。","aiSetupOpenRouterSignedInTitle": "OpenRouter にサインインしました","aiSetupSavedKeyHint": "保存済みのキーを使う場合は空欄のままにしてください。","aiSetupOpenRouterKeyLabel": "・キー「{label}」","aiSetupOpenRouterVerifying": "OpenRouter のキーを確認しています…","aiSetupOpenRouterNoCredits": "この OpenRouter アカウントにはまだクレジットがありません。推奨モデルなどの有料モデルを使うには、OpenRouter でクレジットを追加してください。",- "aiSetupOpenRouterChange": "別のアカウントを使う",+ "aiSetupSignInChange": "別のアカウントを使う",+ "aiSetupSignOut": "サインアウト",+ "aiSetupAccessSubscriptions": "サブスクリプション",+ "aiSetupAccessChatGPT": "ChatGPT プランのモデルを OpenPencil のエージェントで使います。",+ "aiSetupChatGPTSignIn": "ChatGPT でサインイン",+ "aiSetupChatGPTWaiting": "ブラウザで ChatGPT へのサインインを完了してください。",+ "aiSetupChatGPTSignedInTitle": "ChatGPT にサインインしました",+ "aiSetupChatGPTFailed": "ChatGPT にサインインできませんでした。もう一度お試しください。",+ "aiSetupChatGPTPortInUse": "別のサインイン(`codex login` など)がポート 1455 を使用しています。完了するか閉じてから、もう一度お試しください。",+ "aiSetupChatGPTCallbackSignedIn": "ChatGPT にサインインしました。このタブを閉じて OpenPencil に戻ってください。",+ "aiSetupChatGPTCallbackCancelled": "ChatGPT へのサインインはキャンセルされました。このタブを閉じてください。",+ "aiSetupChatGPTCallbackStale": "このサインインリンクは以前の試行のものです。OpenPencil からやり直してください。",+ "aiSetupChatGPTUsage": "応答は ChatGPT プランの利用上限にカウントされます。",+ "aiSetupSavedSignInHint": "保存済みのサインインを使用します。","aiSetupUseRecommended": "推奨の設定を使う","aiSetupRolesDescription": "作業の種類ごとにモデルを選んでください。接続したものから推奨モデルを選んであります。ほかに設定した内容はそのまま残ります。","aiSetupGapDesign": "選んだものではデザインの作成と編集ができません。",diff --git a/packages/vue/src/i18n/locales/ja/common.json b/packages/vue/src/i18n/locales/ja/common.jsonindex b561bec02..f552ba673 100644--- a/packages/vue/src/i18n/locales/ja/common.json+++ b/packages/vue/src/i18n/locales/ja/common.json@@ -32,6 +32,7 @@"noResults": "結果がありません","save": "保存","done": "完了",+ "task": "タスク","back": "戻る","supported": "対応","unsupported": "非対応",diff --git a/packages/vue/src/i18n/locales/pl/ai.json b/packages/vue/src/i18n/locales/pl/ai.jsonindex 624160183..69826a6f2 100644--- a/packages/vue/src/i18n/locales/pl/ai.json+++ b/packages/vue/src/i18n/locales/pl/ai.json@@ -4,10 +4,13 @@"maxAgentStepsRange": "Wpisz liczbę całkowitą od {min} do {max}.","connectionTestSuccess": "Połączono pomyślnie. Model jest dostępny.","connectionTestMissingAPIKey": "Wprowadź klucz API przed rozpoczęciem testu.",+ "connectionTestMissingSignIn": "Zaloguj się przed rozpoczęciem testu.","connectionTestMissingBaseURL": "Wprowadź bazowy adres URL przed rozpoczęciem testu.","connectionTestMissingModel": "Wprowadź identyfikator modelu przed rozpoczęciem testu.","connectionTestInvalidBaseURL": "Bazowy adres URL jest nieprawidłowy. Użyj pełnego adresu, np. https://api.example.com/v1.","connectionTestAuthFailed": "Uwierzytelnianie nie powiodło się. Sprawdź klucz API.",+ "connectionTestSignInExpired": "Logowanie wygasło. Zaloguj się ponownie.",+ "connectionTestPlanForbidden": "Twój plan nie pozwala używać tego modelu. Wybierz inny model.","connectionTestInsufficientCredit": "Konto dostawcy nie ma wystarczających środków lub limitu. Doładuj je i spróbuj ponownie.","connectionTestModelNotFound": "Nie znaleziono modelu. Sprawdź jego identyfikator.","connectionTestAPITypeMismatch": "Ten punkt końcowy prawdopodobnie nie obsługuje wybranego typu API. Spróbuj Completions lub Responses.",@@ -134,6 +137,8 @@"outputLimitAutomatic": "Automatyczna rekomendacja","maxOutputTokens": "Maks. tokenów wyjściowych","chatAuthenticationFailed": "Klucz API dostawcy jest nieprawidłowy lub wygasł. Zastąp go w Ustawieniach.",+ "chatSignInExpired": "Twoje logowanie wygasło. Zaloguj się ponownie w Ustawieniach.",+ "chatPlanForbidden": "Twój plan nie pozwala używać wybranego modelu. Wybierz inny model w Ustawieniach.","chatForbidden": "Ten klucz API nie może używać wybranego modelu. Sprawdź dostęp do modelu.","chatModelNotFound": "Wybrany model jest niedostępny. Wybierz inny model w Ustawieniach.","chatNetworkFailed": "OpenPencil nie mógł połączyć się z dostawcą. Sprawdź połączenie i endpoint.",@@ -235,18 +240,31 @@"aiSetupAlreadyConnected": "Wszystko, co wybrano, jest już połączone.","aiSetupOpenRouterSignIn": "Zaloguj się przez OpenRouter","aiSetupOpenRouterWaiting": "Dokończ logowanie do OpenRouter w przeglądarce.",- "aiSetupOpenRouterReopen": "Otwórz ponownie",+ "aiSetupSignInReopen": "Otwórz ponownie","aiSetupOpenRouterOrKey": "Lub wklej klucz API","aiSetupOpenRouterBlocked": "Przeglądarka zablokowała okno logowania. Zezwól na wyskakujące okna dla OpenPencil i spróbuj ponownie.",- "aiSetupOpenRouterCancelled": "Logowanie zostało anulowane.",- "aiSetupOpenRouterExpired": "Logowanie trwało zbyt długo. Spróbuj ponownie.",+ "aiSetupSignInCancelled": "Logowanie zostało anulowane.",+ "aiSetupSignInExpired": "Logowanie trwało zbyt długo. Spróbuj ponownie.","aiSetupOpenRouterFailed": "Nie udało się zalogować do OpenRouter. Spróbuj ponownie lub wklej klucz API.","aiSetupOpenRouterSignedInTitle": "Zalogowano do OpenRouter","aiSetupSavedKeyHint": "Pozostaw puste, aby zachować zapisany klucz.","aiSetupOpenRouterKeyLabel": "· klucz „{label}”","aiSetupOpenRouterVerifying": "Sprawdzanie klucza OpenRouter…","aiSetupOpenRouterNoCredits": "To konto OpenRouter nie ma jeszcze środków. Doładuj je w OpenRouter, aby korzystać z płatnych modeli, takich jak polecany.",- "aiSetupOpenRouterChange": "Użyj innego konta",+ "aiSetupSignInChange": "Użyj innego konta",+ "aiSetupSignOut": "Wyloguj się",+ "aiSetupAccessSubscriptions": "Subskrypcje",+ "aiSetupAccessChatGPT": "Używaj modeli ze swojego planu ChatGPT we własnym agencie OpenPencil.",+ "aiSetupChatGPTSignIn": "Zaloguj się przez ChatGPT",+ "aiSetupChatGPTWaiting": "Dokończ logowanie do ChatGPT w przeglądarce.",+ "aiSetupChatGPTSignedInTitle": "Zalogowano do ChatGPT",+ "aiSetupChatGPTFailed": "Nie udało się zalogować do ChatGPT. Spróbuj ponownie.",+ "aiSetupChatGPTPortInUse": "Inne logowanie, np. `codex login`, używa portu 1455. Dokończ je lub zamknij i spróbuj ponownie.",+ "aiSetupChatGPTCallbackSignedIn": "Zalogowano do ChatGPT. Możesz zamknąć tę kartę i wrócić do OpenPencil.",+ "aiSetupChatGPTCallbackCancelled": "Logowanie do ChatGPT zostało anulowane. Możesz zamknąć tę kartę.",+ "aiSetupChatGPTCallbackStale": "Ten link logowania pochodzi z wcześniejszej próby. Zacznij od nowa w OpenPencil.",+ "aiSetupChatGPTUsage": "Odpowiedzi wliczają się do limitów użycia twojego planu ChatGPT.",+ "aiSetupSavedSignInHint": "Zostanie użyte zapisane logowanie.","aiSetupUseRecommended": "Użyj polecanej konfiguracji","aiSetupRolesDescription": "Wybierz model dla każdego rodzaju pracy. Spośród połączonych usług wybraliśmy polecane; pozostała konfiguracja się nie zmieni.","aiSetupGapDesign": "Żadna z wybranych opcji nie tworzy ani nie edytuje projektów.",diff --git a/packages/vue/src/i18n/locales/pl/common.json b/packages/vue/src/i18n/locales/pl/common.jsonindex 9f0f7c63a..e9a4f150c 100644--- a/packages/vue/src/i18n/locales/pl/common.json+++ b/packages/vue/src/i18n/locales/pl/common.json@@ -32,6 +32,7 @@"noResults": "Brak wyników","save": "Zapisz","done": "Gotowe",+ "task": "Zadanie","back": "Wstecz","supported": "Obsługiwane","unsupported": "Nieobsługiwane",diff --git a/packages/vue/src/i18n/locales/ru/ai.json b/packages/vue/src/i18n/locales/ru/ai.jsonindex a5a20fe6c..d298e6fd2 100644--- a/packages/vue/src/i18n/locales/ru/ai.json+++ b/packages/vue/src/i18n/locales/ru/ai.json@@ -4,10 +4,13 @@"maxAgentStepsRange": "Введите целое число от {min} до {max}.","connectionTestSuccess": "Подключение установлено. Модель доступна.","connectionTestMissingAPIKey": "Введите API-ключ перед проверкой.",+ "connectionTestMissingSignIn": "Войдите перед проверкой.","connectionTestMissingBaseURL": "Введите базовый URL перед проверкой.","connectionTestMissingModel": "Введите ID модели перед проверкой.","connectionTestInvalidBaseURL": "Недопустимый базовый URL. Используйте полный URL, например https://api.example.com/v1.","connectionTestAuthFailed": "Не удалось пройти аутентификацию. Проверьте API-ключ.",+ "connectionTestSignInExpired": "Срок входа истёк. Войдите снова.",+ "connectionTestPlanForbidden": "Ваш тариф не позволяет использовать эту модель. Выберите другую.","connectionTestInsufficientCredit": "На счёте провайдера недостаточно средств или квоты. Пополните его и повторите попытку.","connectionTestModelNotFound": "Модель не найдена. Проверьте ID модели.","connectionTestAPITypeMismatch": "Эта конечная точка, вероятно, не поддерживает выбранный тип API. Попробуйте Completions или Responses.",@@ -134,6 +137,8 @@"outputLimitAutomatic": "Автоматическая рекомендация","maxOutputTokens": "Максимум выходных токенов","chatAuthenticationFailed": "API-ключ провайдера недействителен или истёк. Замените его в настройках.",+ "chatSignInExpired": "Срок вашего входа истёк. Войдите снова в настройках.",+ "chatPlanForbidden": "Ваш тариф не позволяет использовать выбранную модель. Выберите другую в настройках.","chatForbidden": "Этот API-ключ не может использовать выбранную модель. Проверьте доступ к модели.","chatModelNotFound": "Выбранная модель недоступна. Выберите другую модель в настройках.","chatNetworkFailed": "OpenPencil не удалось связаться с провайдером. Проверьте соединение и адрес сервера.",@@ -235,18 +240,31 @@"aiSetupAlreadyConnected": "Всё выбранное уже подключено.","aiSetupOpenRouterSignIn": "Войти через OpenRouter","aiSetupOpenRouterWaiting": "Завершите вход в OpenRouter в браузере.",- "aiSetupOpenRouterReopen": "Открыть снова",+ "aiSetupSignInReopen": "Открыть снова","aiSetupOpenRouterOrKey": "Или вставьте ключ API","aiSetupOpenRouterBlocked": "Браузер заблокировал окно входа. Разрешите всплывающие окна для OpenPencil и попробуйте снова.",- "aiSetupOpenRouterCancelled": "Вход отменён.",- "aiSetupOpenRouterExpired": "Вход занял слишком много времени. Попробуйте снова.",+ "aiSetupSignInCancelled": "Вход отменён.",+ "aiSetupSignInExpired": "Вход занял слишком много времени. Попробуйте снова.","aiSetupOpenRouterFailed": "Не удалось войти в OpenRouter. Попробуйте снова или вставьте ключ API.","aiSetupOpenRouterSignedInTitle": "Вход в OpenRouter выполнен","aiSetupSavedKeyHint": "Оставьте поле пустым, чтобы использовать сохранённый ключ.","aiSetupOpenRouterKeyLabel": "· ключ «{label}»","aiSetupOpenRouterVerifying": "Проверяем ключ OpenRouter…","aiSetupOpenRouterNoCredits": "На этом аккаунте OpenRouter пока нет кредитов. Пополните баланс в OpenRouter, чтобы пользоваться платными моделями, например рекомендованной.",- "aiSetupOpenRouterChange": "Использовать другой аккаунт",+ "aiSetupSignInChange": "Использовать другой аккаунт",+ "aiSetupSignOut": "Выйти",+ "aiSetupAccessSubscriptions": "Подписки",+ "aiSetupAccessChatGPT": "Используйте модели своего плана ChatGPT в собственном агенте OpenPencil.",+ "aiSetupChatGPTSignIn": "Войти через ChatGPT",+ "aiSetupChatGPTWaiting": "Завершите вход в ChatGPT в браузере.",+ "aiSetupChatGPTSignedInTitle": "Вход в ChatGPT выполнен",+ "aiSetupChatGPTFailed": "Не удалось войти в ChatGPT. Попробуйте ещё раз.",+ "aiSetupChatGPTPortInUse": "Порт 1455 занят другим входом, например `codex login`. Завершите или закройте его и попробуйте снова.",+ "aiSetupChatGPTCallbackSignedIn": "Вход в ChatGPT выполнен. Можно закрыть эту вкладку и вернуться в OpenPencil.",+ "aiSetupChatGPTCallbackCancelled": "Вход в ChatGPT отменён. Можно закрыть эту вкладку.",+ "aiSetupChatGPTCallbackStale": "Эта ссылка для входа относится к прошлой попытке. Начните заново в OpenPencil.",+ "aiSetupChatGPTUsage": "Ответы расходуют лимиты вашего плана ChatGPT.",+ "aiSetupSavedSignInHint": "Будет использован сохранённый вход.","aiSetupUseRecommended": "Использовать рекомендуемую настройку","aiSetupRolesDescription": "Выберите модель для каждого вида работы. Мы подобрали рекомендуемые из подключённого; остальные ваши настройки не изменятся.","aiSetupGapDesign": "Ничто из выбранного не умеет создавать и редактировать дизайн.",diff --git a/packages/vue/src/i18n/locales/ru/common.json b/packages/vue/src/i18n/locales/ru/common.jsonindex 97144bd30..0c7b0a0d8 100644--- a/packages/vue/src/i18n/locales/ru/common.json+++ b/packages/vue/src/i18n/locales/ru/common.json@@ -32,6 +32,7 @@"noResults": "Ничего не найдено","save": "Сохранить","done": "Готово",+ "task": "Задача","back": "Назад","supported": "Поддерживается","unsupported": "Не поддерживается",diff --git a/packages/vue/src/i18n/locales/zh-cn/ai.json b/packages/vue/src/i18n/locales/zh-cn/ai.jsonindex 8c8269c75..03f559ea2 100644--- a/packages/vue/src/i18n/locales/zh-cn/ai.json+++ b/packages/vue/src/i18n/locales/zh-cn/ai.json@@ -4,10 +4,13 @@"maxAgentStepsRange": "请输入 {min} 到 {max} 之间的整数。","connectionTestSuccess": "连接成功。模型可访问。","connectionTestMissingAPIKey": "请在测试前输入 API 密钥。",+ "connectionTestMissingSignIn": "请在测试前登录。","connectionTestMissingBaseURL": "请在测试前输入基础 URL。","connectionTestMissingModel": "请在测试前输入模型 ID。","connectionTestInvalidBaseURL": "基础 URL 无效。请使用完整 URL,例如 https://api.example.com/v1。","connectionTestAuthFailed": "身份验证失败。请检查 API 密钥。",+ "connectionTestSignInExpired": "登录已过期,请重新登录。",+ "connectionTestPlanForbidden": "你的套餐无法使用此模型。请选择其他模型。","connectionTestInsufficientCredit": "提供商账户的余额或配额不足。请充值后重试。","connectionTestModelNotFound": "找不到模型。请检查模型 ID。","connectionTestAPITypeMismatch": "此端点似乎不支持所选的 API 类型。请尝试 Completions 或 Responses。",@@ -140,6 +143,8 @@"outputLimitAutomatic": "自动建议","maxOutputTokens": "最大输出词元数","chatAuthenticationFailed": "提供商API密钥无效或已过期。请在设置中替换。",+ "chatSignInExpired": "你的登录已过期,请在设置中重新登录。",+ "chatPlanForbidden": "你的套餐无法使用所选模型。请在设置中选择其他模型。","chatForbidden": "此API密钥无法使用所选模型。请检查模型访问权限。","chatModelNotFound": "所选模型不可用。请在设置中选择其他模型。","chatNetworkFailed": "OpenPencil无法连接提供商。请检查网络和端点。",@@ -235,18 +240,31 @@"aiSetupAlreadyConnected": "你选择的服务都已连接。","aiSetupOpenRouterSignIn": "使用 OpenRouter 登录","aiSetupOpenRouterWaiting": "请在浏览器中完成 OpenRouter 登录。",- "aiSetupOpenRouterReopen": "再次打开",+ "aiSetupSignInReopen": "再次打开","aiSetupOpenRouterOrKey": "或粘贴 API 密钥","aiSetupOpenRouterBlocked": "浏览器拦截了登录窗口。请允许 OpenPencil 弹出窗口后重试。",- "aiSetupOpenRouterCancelled": "登录已取消。",- "aiSetupOpenRouterExpired": "登录耗时过长,请重试。",+ "aiSetupSignInCancelled": "登录已取消。",+ "aiSetupSignInExpired": "登录耗时过长,请重试。","aiSetupOpenRouterFailed": "无法登录 OpenRouter。请重试或粘贴 API 密钥。","aiSetupOpenRouterSignedInTitle": "已登录 OpenRouter","aiSetupSavedKeyHint": "留空即可继续使用已保存的密钥。","aiSetupOpenRouterKeyLabel": "· 密钥“{label}”","aiSetupOpenRouterVerifying": "正在检查你的 OpenRouter 密钥…","aiSetupOpenRouterNoCredits": "这个 OpenRouter 账户还没有额度。请在 OpenRouter 充值后再使用推荐模型等付费模型。",- "aiSetupOpenRouterChange": "使用其他账户",+ "aiSetupSignInChange": "使用其他账户",+ "aiSetupSignOut": "退出登录",+ "aiSetupAccessSubscriptions": "订阅",+ "aiSetupAccessChatGPT": "在 OpenPencil 自带的智能体中使用你的 ChatGPT 套餐模型。",+ "aiSetupChatGPTSignIn": "使用 ChatGPT 登录",+ "aiSetupChatGPTWaiting": "请在浏览器中完成 ChatGPT 登录。",+ "aiSetupChatGPTSignedInTitle": "已登录 ChatGPT",+ "aiSetupChatGPTFailed": "无法登录 ChatGPT,请重试。",+ "aiSetupChatGPTPortInUse": "另一个登录(如 `codex login`)正在使用端口 1455。请完成或关闭它后重试。",+ "aiSetupChatGPTCallbackSignedIn": "已登录 ChatGPT。你可以关闭此标签页并返回 OpenPencil。",+ "aiSetupChatGPTCallbackCancelled": "ChatGPT 登录已取消。你可以关闭此标签页。",+ "aiSetupChatGPTCallbackStale": "此登录链接属于之前的尝试。请从 OpenPencil 重新开始。",+ "aiSetupChatGPTUsage": "回复会计入你的 ChatGPT 套餐用量限制。",+ "aiSetupSavedSignInHint": "将使用已保存的登录。","aiSetupUseRecommended": "使用推荐设置","aiSetupRolesDescription": "为每类工作选择模型。我们已从你连接的服务中选好推荐模型,其他已配置的内容保持不变。","aiSetupGapDesign": "你选择的服务都无法创建和编辑设计。",diff --git a/packages/vue/src/i18n/locales/zh-cn/common.json b/packages/vue/src/i18n/locales/zh-cn/common.jsonindex ca3f8db03..e4a634022 100644--- a/packages/vue/src/i18n/locales/zh-cn/common.json+++ b/packages/vue/src/i18n/locales/zh-cn/common.json@@ -32,6 +32,7 @@"noResults": "无结果","save": "保存","done": "完成",+ "task": "任务","back": "返回","supported": "支持","unsupported": "不支持",diff --git a/packages/vue/src/i18n/messages/ai.ts b/packages/vue/src/i18n/messages/ai.tsindex bfdf63846..e58249559 100644--- a/packages/vue/src/i18n/messages/ai.ts+++ b/packages/vue/src/i18n/messages/ai.ts@@ -47,11 +47,14 @@ export const aiMessageDefaults = {connectProvider: 'Connect an AI provider to start chatting.',connectionTestSuccess: 'Connected successfully. Model is reachable.',connectionTestMissingAPIKey: 'Enter an API key before testing.',+ connectionTestMissingSignIn: 'Sign in before testing.',connectionTestMissingBaseURL: 'Enter a base URL before testing.',connectionTestMissingModel: 'Enter a model ID before testing.',connectionTestInvalidBaseURL:'Base URL is invalid. Use a full URL like https://api.example.com/v1.',connectionTestAuthFailed: 'Authentication failed. Check your API key.',+ connectionTestSignInExpired: 'The sign-in has expired. Sign in again.',+ connectionTestPlanForbidden: 'Your plan can’t use this model. Choose another model.',connectionTestInsufficientCredit:'The provider account has insufficient credit or quota. Top it up and try again.',connectionTestModelNotFound: 'Model not found. Check the model ID.',@@ -193,6 +196,8 @@ export const aiMessageDefaults = {outputLimitAutomatic: 'Automatic recommendation',maxOutputTokens: 'Max output tokens',chatAuthenticationFailed: 'Your provider API key is invalid or expired. Replace it in Settings.',+ chatSignInExpired: 'Your sign-in has expired. Sign in again in Settings.',+ chatPlanForbidden: 'Your plan can’t use the selected model. Choose another model in Settings.',chatForbidden: 'This API key cannot use the selected model. Check its model access.',chatInsufficientCredit:'The provider account has insufficient credit or quota. Top it up and try again.',@@ -344,19 +349,35 @@ export const aiMessageDefaults = {aiSetupAlreadyConnected: 'Everything you selected is already connected.',aiSetupOpenRouterSignIn: 'Sign in with OpenRouter',aiSetupOpenRouterWaiting: 'Finish signing in to OpenRouter in your browser.',- aiSetupOpenRouterReopen: 'Open again',+ aiSetupSignInReopen: 'Open again',aiSetupOpenRouterOrKey: 'Or paste an API key',aiSetupOpenRouterBlocked:'Your browser blocked the sign-in window. Allow pop-ups for OpenPencil and try again.',- aiSetupOpenRouterCancelled: 'Sign-in was cancelled.',- aiSetupOpenRouterExpired: 'Sign-in took too long. Try again.',+ aiSetupSignInCancelled: 'Sign-in was cancelled.',+ aiSetupSignInExpired: 'Sign-in took too long. Try again.',aiSetupOpenRouterFailed: 'Couldn’t sign in to OpenRouter. Try again or paste an API key.',aiSetupOpenRouterSignedInTitle: 'Signed in to OpenRouter',aiSetupOpenRouterKeyLabel: params('· key “{label}”'),aiSetupOpenRouterVerifying: 'Checking your OpenRouter key…',aiSetupOpenRouterNoCredits:'This OpenRouter account has no credits yet. Add credits on OpenRouter to use paid models such as the recommended one.',- aiSetupOpenRouterChange: 'Use a different account',+ aiSetupSignInChange: 'Use a different account',+ aiSetupSignOut: 'Sign out',+ aiSetupAccessSubscriptions: 'Subscriptions',+ aiSetupAccessChatGPT: 'Use your ChatGPT plan’s models in OpenPencil’s own agent.',+ aiSetupChatGPTSignIn: 'Sign in with ChatGPT',+ aiSetupChatGPTWaiting: 'Finish signing in to ChatGPT in your browser.',+ aiSetupChatGPTSignedInTitle: 'Signed in to ChatGPT',+ aiSetupChatGPTFailed: 'Couldn’t sign in to ChatGPT. Try again.',+ aiSetupChatGPTPortInUse:+ 'Another sign-in, such as `codex login`, is using port 1455. Finish or close it, then try again.',+ aiSetupChatGPTCallbackSignedIn:+ 'Signed in to ChatGPT. You can close this tab and return to OpenPencil.',+ aiSetupChatGPTCallbackCancelled: 'ChatGPT sign-in was cancelled. You can close this tab.',+ aiSetupChatGPTCallbackStale:+ 'This sign-in link belongs to an earlier attempt. Start again from OpenPencil.',+ aiSetupChatGPTUsage: 'Replies count toward your ChatGPT plan’s usage limits.',+ aiSetupSavedSignInHint: 'Your saved sign-in will be used.',aiSetupUseRecommended: 'Use recommended setup',aiSetupRolesDescription:'Choose a model for each kind of work. We picked recommended ones from what you connected; anything else you configured stays as it is.'diff --git a/packages/vue/src/i18n/messages/common.ts b/packages/vue/src/i18n/messages/common.tsindex 27b59b60c..c83d4e8b4 100644--- a/packages/vue/src/i18n/messages/common.ts+++ b/packages/vue/src/i18n/messages/common.ts@@ -36,6 +36,8 @@ export const commonMessageDefaults = {noResults: 'No results',save: 'Save',done: 'Done',+ /** The accessible name of a task list's checkbox in rendered Markdown. */+ task: 'Task',back: 'Back',supported: 'Supported',unsupported: 'Not supported',diff --git a/src/app/ai/chat/failure.ts b/src/app/ai/chat/failure.tsindex 977eeb2f5..d90fdecfc 100644--- a/src/app/ai/chat/failure.ts+++ b/src/app/ai/chat/failure.ts@@ -9,6 +9,8 @@ export type AIChatFailureReason =| 'output-limit'| 'rate-limit'| 'request-failed'+ | 'sign-in-expired'+ | 'plan-forbidden'export type AIChatFailure = {reason: AIChatFailureReason@@ -108,9 +110,20 @@ export function classifyAIChatFinish(finishReason?: string): AIChatFailure | nulreturn finishReason === 'length' ? { reason: 'output-limit' } : null}-export function classifyAIChatError(error: unknown): AIChatFailure {+/** A provider signed in to has no key, so a refused credential is its sign-in or its plan. */+function signInFailureReason(reason: AIChatFailureReason): AIChatFailureReason {+ if (reason === 'authentication') return 'sign-in-expired'+ if (reason === 'forbidden') return 'plan-forbidden'+ return reason+}++export function classifyAIChatError(+ error: unknown,+ { signInOnly = false }: { signInOnly?: boolean } = {}+): AIChatFailure {+ const reason = failureReason(error)return {- reason: failureReason(error),+ reason: signInOnly ? signInFailureReason(reason) : reason,detail: errorText(error),statusCode: providerErrorStatus(error) ?? undefined,// A provider error after the stream starts arrives as StreamProviderError, not APICallError.diff --git a/src/app/ai/chat/session.ts b/src/app/ai/chat/session.tsindex a6d7c8f02..2026758db 100644--- a/src/app/ai/chat/session.ts+++ b/src/app/ai/chat/session.ts@@ -3,7 +3,7 @@ import type { ChatTransport, FinishReason, UIMessage } from 'ai'import type { ComputedRef, Ref } from 'vue'import { ref } from 'vue'-import { ACP_AGENTS } from '@open-pencil/core/constants'+import { ACP_AGENTS, AI_PROVIDERS } from '@open-pencil/core/constants'import type { ACPAgentID, AIProviderID } from '@open-pencil/core/constants'import { AgentSetupError, assertAgentReady } from '@/app/ai/agents/setup/readiness'@@ -263,7 +263,10 @@ export function createChatSessionManager({onError: (error) => {const reportedError = activeProviderError ?? erroractiveProviderError = null- failure.value = classifyAIChatError(reportedError)+ const signInOnly = AI_PROVIDERS.some(+ (provider) => provider.id === providerID.value && provider.signInOnly+ )+ failure.value = classifyAIChatError(reportedError, { signInOnly })const { errorName, errorCode, message, stack } = diagnosticErrorDetails(reportedError)recordChatFailed({ errorName, errorCode, message, stack }, diagnosticContext)},diff --git a/src/app/ai/models/catalog/chatgpt.ts b/src/app/ai/models/catalog/chatgpt.tsnew file mode 100644index 000000000..15c2d50b1--- /dev/null+++ b/src/app/ai/models/catalog/chatgpt.ts@@ -0,0 +1,27 @@+import type { ModelOption } from '@open-pencil/core/constants'++import {+ modelConnectionCredentialStore,+ resolveModelConnectionAPIKey+} from '@/app/ai/models/runtime'+import { aiModelSettings } from '@/app/ai/models/store'+import { chatGPTFetch } from '@/app/ai/providers/chatgpt/adapter'+import { fetchChatGPTModels } from '@/app/ai/providers/chatgpt/catalog'+import { parseChatGPTCredential } from '@/app/ai/providers/chatgpt/credential'+import { isTauri } from '@/app/tauri/env'+import { tauriFetch } from '@/app/tauri/http'++/** The models of the first ChatGPT sign-in, or null before anyone has signed in. */+export async function listChatGPTModels(): Promise<ModelOption[] | null> {+ for (const connection of aiModelSettings.value.connections) {+ if (connection.providerID !== 'chatgpt') continue+ const credential = parseChatGPTCredential(+ (await resolveModelConnectionAPIKey(connection.id)) ?? ''+ )+ if (!credential) continue+ const store = modelConnectionCredentialStore(connection.id)+ const signed = chatGPTFetch(credential, store, isTauri() ? tauriFetch : undefined)+ return fetchChatGPTModels(signed).catch(() => null)+ }+ return null+}diff --git a/src/app/ai/models/catalog/index.ts b/src/app/ai/models/catalog/index.tsindex 37f26be5f..c0994ce98 100644--- a/src/app/ai/models/catalog/index.ts+++ b/src/app/ai/models/catalog/index.ts@@ -6,6 +6,8 @@ import type { AIProviderID, ModelOption } from '@open-pencil/core/constants'import { cachedRemoteJSON } from '@/app/cache/remote'+import { listChatGPTModels } from './chatgpt'+const MODELS_DEV_URL = 'https://models.dev/api.json'const MODELS_DEV_CACHE_KEY = 'models-dev/catalog'const MODELS_DEV_CACHE_TTL_MS = 24 * 60 * 60 * 1000@@ -125,11 +127,24 @@ function mergeCuratedModels(curated: ModelOption[], catalog: ModelOption[]): Modreturn [...recommended, ...remaining]}+/** The account's own list in its order; recommended models keep their names and tags. */+function withCuratedNames(curated: ModelOption[], listed: ModelOption[]): ModelOption[] {+ const curatedById = new Map(curated.map((model) => [model.id, model]))+ return listed.map((model) => {+ const known = curatedById.get(model.id)+ return known ? { ...model, name: known.name, tag: known.tag } : model+ })+}+export async function listCatalogModels(providerID: AIProviderID,fetcher?: typeof fetch): Promise<ModelOption[]> {const curated = curatedProviderModels(providerID)+ if (providerID === 'chatgpt') {+ const listed = await listChatGPTModels()+ return listed ? withCuratedNames(curated, listed) : curated+ }const providerKeys = PROVIDER_KEYS[providerID]if (!providerKeys?.length) return curatedconst catalog = await modelsDevCatalog.get(fetcher)diff --git a/src/app/ai/models/catalog/schema.ts b/src/app/ai/models/catalog/schema.tsnew file mode 100644index 000000000..97eb61070--- /dev/null+++ b/src/app/ai/models/catalog/schema.ts@@ -0,0 +1,18 @@+import * as v from 'valibot'++import { REASONING_EFFORTS } from '@open-pencil/core/constants'+import type { ModelOption } from '@open-pencil/core/constants'++/** A model list as the app caches it after normalizing a provider's own catalog. */+export const modelOptionsSchema = v.array(+ v.object({+ id: v.string(),+ name: v.string(),+ tag: v.optional(v.string()),+ capabilities: v.optional(v.array(v.picklist(['tools', 'vision']))),+ recommendedMaxOutputTokens: v.optional(v.number()),+ releaseDate: v.optional(v.string()),+ status: v.optional(v.picklist(['active', 'beta', 'deprecated'])),+ minReasoningEffort: v.optional(v.picklist(REASONING_EFFORTS))+ })+) satisfies v.GenericSchema<unknown, ModelOption[]>diff --git a/src/app/ai/models/connection-test.ts b/src/app/ai/models/connection-test.tsindex f80729794..9a353fbd6 100644--- a/src/app/ai/models/connection-test.ts+++ b/src/app/ai/models/connection-test.ts@@ -1,11 +1,14 @@import { generateText } from 'ai'+import { AI_PROVIDERS } from '@open-pencil/core/constants'+import { isInsufficientCreditError, providerErrorStatus } from '@/app/ai/chat/failure'import {createLanguageModel,resolveLanguageModelID,type ModelConfig} from '@/app/ai/models/language-model'+import type { ModelCredentialStore } from '@/app/ai/providers/types'import { isTauri } from '@/app/tauri/env'export type ProviderConnectionTestResult =@@ -14,10 +17,13 @@ export type ProviderConnectionTestResult =export type ProviderConnectionTestFailureReason =| 'missing-api-key'+ | 'missing-sign-in'| 'missing-base-url'| 'missing-model'| 'invalid-base-url'| 'auth'+ | 'sign-in-expired'+ | 'plan-forbidden'| 'insufficient-credit'| 'model-not-found'| 'api-type'@@ -29,8 +35,14 @@ function isCompatibleProvider(providerID: ModelConfig['providerID']): boolean {return providerID === 'openai-compatible' || providerID === 'anthropic-compatible'}+function isSignInOnly(providerID: ModelConfig['providerID']): boolean {+ return AI_PROVIDERS.some((provider) => provider.id === providerID && provider.signInOnly)+}+function validateConfig(config: ModelConfig): ProviderConnectionTestFailureReason | null {- if (!config.apiKey.trim()) return 'missing-api-key'+ if (!config.apiKey.trim()) {+ return isSignInOnly(config.providerID) ? 'missing-sign-in' : 'missing-api-key'+ }if (isCompatibleProvider(config.providerID)) {if (!config.customBaseURL.trim()) return 'missing-base-url'try {@@ -93,21 +105,30 @@ function classifyError(error: unknown): ProviderConnectionTestFailureReason {return classifyStatus(providerErrorStatus(error), text) ?? classifyMessage(text) ?? 'unknown'}+/**+ * Sends a one-token request. A test of a saved credential passes its store, so a sign-in the+ * request refreshes keeps the new tokens instead of leaving a spent refresh token saved.+ */export async function testProviderConnection(- config: ModelConfig+ config: ModelConfig,+ credentials?: ModelCredentialStore): Promise<ProviderConnectionTestResult> {const invalidReason = validateConfig(config)if (invalidReason) return { ok: false, reason: invalidReason }try {await generateText({- model: createLanguageModel(config),+ model: createLanguageModel(config, credentials),prompt: 'Reply with OK.',maxOutputTokens: 1,abortSignal: AbortSignal.timeout(15_000)})return { ok: true }} catch (error) {- return { ok: false, reason: classifyError(error) }+ const reason = classifyError(error)+ if (reason !== 'auth' || !isSignInOnly(config.providerID)) return { ok: false, reason }+ // A provider signed in to has no key: a 403 is the plan, anything else the sign-in.+ const planForbidden = providerErrorStatus(error) === 403+ return { ok: false, reason: planForbidden ? 'plan-forbidden' : 'sign-in-expired' }}}diff --git a/src/app/ai/models/language-model.ts b/src/app/ai/models/language-model.tsindex c3c235e0e..27b979b93 100644--- a/src/app/ai/models/language-model.ts+++ b/src/app/ai/models/language-model.ts@@ -1,7 +1,7 @@import type { LanguageModel } from 'ai'import { modelProviderAdapter } from '@/app/ai/providers/registry'-import type { ModelConfig } from '@/app/ai/providers/types'+import type { ModelConfig, ModelCredentialStore } from '@/app/ai/providers/types'import type { FetchFunction } from '@/app/http/types'import { isTauri } from '@/app/tauri/env'import { tauriFetch } from '@/app/tauri/http'@@ -25,6 +25,13 @@ function desktopFetch(): FetchFunction | undefined {return isTauri() ? tauriFetch : undefined}-export function createLanguageModel(config: ModelConfig): LanguageModel {- return modelProviderAdapter(config.providerID).create(config, { fetch: desktopFetch() })+/** `credentials` is the connection's store, for providers whose sign-in refreshes. */+export function createLanguageModel(+ config: ModelConfig,+ credentials?: ModelCredentialStore+): LanguageModel {+ return modelProviderAdapter(config.providerID).create(config, {+ fetch: desktopFetch(),+ credentials+ })}diff --git a/src/app/ai/models/reasoning/floors.ts b/src/app/ai/models/reasoning/floors.tsindex 30b6467a7..d3b7a770d 100644--- a/src/app/ai/models/reasoning/floors.ts+++ b/src/app/ai/models/reasoning/floors.ts@@ -3,21 +3,10 @@ import * as v from 'valibot'import { AI_PROVIDERS, REASONING_EFFORTS } from '@open-pencil/core/constants'import type { AIProviderID, ModelOption, ReasoningEffort } from '@open-pencil/core/constants'+import { modelOptionsSchema } from '@/app/ai/models/catalog/schema'+import { cachedChatGPTModels } from '@/app/ai/providers/chatgpt/catalog'import { cachedRemoteJSON } from '@/app/cache/remote'-const cachedModelOptionsSchema = v.array(- v.object({- id: v.string(),- name: v.string(),- tag: v.optional(v.string()),- capabilities: v.optional(v.array(v.picklist(['tools', 'vision']))),- recommendedMaxOutputTokens: v.optional(v.number()),- releaseDate: v.optional(v.string()),- status: v.optional(v.picklist(['active', 'beta', 'deprecated'])),- minReasoningEffort: v.optional(v.picklist(REASONING_EFFORTS))- })-) satisfies v.GenericSchema<unknown, ModelOption[]>-const openRouterModelSchema = v.looseObject({id: v.optional(v.unknown()),name: v.optional(v.unknown()),@@ -104,7 +93,7 @@ async function fetchOpenRouterModels(fetcher: typeof fetch): Promise<ModelOptionconst openRouterModels = cachedRemoteJSON<ModelOption[]>({key: OPENROUTER_MODELS_CACHE_KEY,- schema: cachedModelOptionsSchema,+ schema: modelOptionsSchema,maxAgeMs: OPENROUTER_MODELS_CACHE_TTL_MS,load: async (fetcher) => {const models = await fetchOpenRouterModels(fetcher)@@ -119,6 +108,10 @@ export async function listProviderModels(if (providerID === 'openrouter') {return (await openRouterModels.get(fetcher)) ?? curatedOpenRouterModels}+ // The picker fetches the account's list; a runtime reads that copy instead of asking again.+ if (providerID === 'chatgpt') {+ return (await cachedChatGPTModels()) ?? curatedProviderModels(providerID)+ }return curatedProviderModels(providerID)}diff --git a/src/app/ai/models/runtime.ts b/src/app/ai/models/runtime.tsindex dab96b34d..3f50816de 100644--- a/src/app/ai/models/runtime.ts+++ b/src/app/ai/models/runtime.ts@@ -7,6 +7,7 @@ import { createLanguageModel, resolveLanguageModelID } from '@/app/ai/models/lanimport { resolveProviderModel } from '@/app/ai/models/reasoning/floors'import { modelConnection, resolveAIModelRole } from '@/app/ai/models/store'import type { AIModelConnection, AIModelRole, ResolvedAIModelRole } from '@/app/ai/models/types'+import type { ModelCredentialStore } from '@/app/ai/providers/types'import { appCredentialServices } from '@/app/settings/credentials/app'import {initializeCredentialMigration,@@ -68,6 +69,19 @@ export async function resolveModelConnectionAPIKey(connectionId: string): Promisreturn appCredentialServices.resolver.resolve(modelConnectionCredentialRef(connection))}+/** The stored credential of a connection, for a model whose sign-in refreshes. */+export function modelConnectionCredentialStore(connectionId: string): ModelCredentialStore {+ return {+ load: () => resolveModelConnectionAPIKey(connectionId),+ // A refreshed sign-in is not a key change, so the open chat keeps its transport.+ save: async (value) => {+ const connection = modelConnection(connectionId)+ if (!connection) return+ await appCredentialServices.manager.set(modelConnectionCredentialRef(connection), value)+ }+ }+}+export async function createAIModelRuntime(role: AIModelRole): Promise<AIModelRuntime | null> {const resolved = resolveAIModelRole(role)if (!resolved) return null@@ -101,13 +115,16 @@ export async function createAIModelRuntime(role: AIModelRole): Promise<AIModelRukind: 'direct',role: resolved,minReasoningEffort: known?.minReasoningEffort,- model: createLanguageModel({- providerID: resolved.connection.providerID,- apiKey,- modelID: resolved.profile.modelID,- customModelID: resolved.profile.customModelID,- customBaseURL: resolved.connection.customBaseURL,- customAPIType: resolved.connection.customAPIType- })+ model: createLanguageModel(+ {+ providerID: resolved.connection.providerID,+ apiKey,+ modelID: resolved.profile.modelID,+ customModelID: resolved.profile.customModelID,+ customBaseURL: resolved.connection.customBaseURL,+ customAPIType: resolved.connection.customAPIType+ },+ modelConnectionCredentialStore(resolved.connection.id)+ )}}diff --git a/src/app/ai/models/settings/onboarding/connections.ts b/src/app/ai/models/settings/onboarding/connections.tsindex 8c894e730..770d032a3 100644--- a/src/app/ai/models/settings/onboarding/connections.ts+++ b/src/app/ai/models/settings/onboarding/connections.ts@@ -4,6 +4,7 @@ import { reactive } from 'vue'import {aiModelSettings,modelConnectionCredentialStatus,+ modelConnectionCredentialStore,resolveModelConnectionAPIKey,type AIModelConnection} from '@/app/ai/models'@@ -31,9 +32,14 @@ export interface OnboardingConnectionState {test: ConnectionTestStatusreason: ProviderConnectionTestFailureReason | null/** Set once a key from signing in has been checked with the provider. */- account: OpenRouterKeyInfo | null+ account: OnboardingAccount | null}+/** The account a sign-in connected, as setup shows it. */+export type OnboardingAccount =+ | ({ provider: 'openrouter' } & OpenRouterKeyInfo)+ | { provider: 'chatgpt'; email?: string; plan?: string }+/** Local servers with a well-known OpenAI-compatible address. */export const ONBOARDING_SERVER_PRESETS = [{ id: 'ollama', name: 'Ollama', baseURL: 'http://localhost:11434/v1' },@@ -174,14 +180,17 @@ export function useOnboardingConnections({ plannedModel }: OnboardingConnectionsconst savedKey =!state.apiKey.trim() && saved ? await resolveModelConnectionAPIKey(saved.id) : nullif (!current()) return- const result = await testProviderConnection({- providerID,- apiKey: state.apiKey.trim() || savedKey || '',- modelID: plannedModel(providerID)?.modelID ?? '',- customModelID: state.customModelID.trim(),- customBaseURL: state.customBaseURL.trim(),- customAPIType: saved?.customAPIType ?? 'completions'- })+ const result = await testProviderConnection(+ {+ providerID,+ apiKey: state.apiKey.trim() || savedKey || '',+ modelID: plannedModel(providerID)?.modelID ?? '',+ customModelID: state.customModelID.trim(),+ customBaseURL: state.customBaseURL.trim(),+ customAPIType: saved?.customAPIType ?? 'completions'+ },+ savedKey && saved ? modelConnectionCredentialStore(saved.id) : undefined+ )if (!current()) returnstate.test = result.ok ? 'success' : 'error'state.reason = result.ok ? null : result.reasondiff --git a/src/app/ai/models/settings/onboarding/plan.ts b/src/app/ai/models/settings/onboarding/plan.tsindex d865dec11..c96873923 100644--- a/src/app/ai/models/settings/onboarding/plan.ts+++ b/src/app/ai/models/settings/onboarding/plan.ts@@ -16,6 +16,8 @@ export const ONBOARDING_AGENTS = ['acp:gemini-cli','harness:pi'] as const+/** Subscriptions OpenPencil's own agent signs in to; the sign-in needs the desktop app. */+export const ONBOARDING_SUBSCRIPTIONS = ['chatgpt'] as const/** API accounts, in the order onboarding prefers them when several are available. */export const ONBOARDING_API_PROVIDERS = ['anthropic', 'openai', 'google', 'openrouter'] as const/** Further API accounts the catalog supports, offered behind "More providers". */@@ -27,12 +29,14 @@ export const ONBOARDING_METERED_PROVIDER = 'openrouter'export type OnboardingAccess =| (typeof ONBOARDING_AGENTS)[number]+ | (typeof ONBOARDING_SUBSCRIPTIONS)[number]| (typeof ONBOARDING_API_PROVIDERS)[number]| (typeof ONBOARDING_MORE_API_PROVIDERS)[number]| typeof ONBOARDING_SERVER_PROVIDERconst ONBOARDING_ACCESS = new Set<string>([...ONBOARDING_AGENTS,+ ...ONBOARDING_SUBSCRIPTIONS,...ONBOARDING_API_PROVIDERS,...ONBOARDING_MORE_API_PROVIDERS,ONBOARDING_SERVER_PROVIDER@@ -87,7 +91,10 @@ export interface CurrentOnboardingModels {}export interface PlanOptions {- /** Agents run as local processes, so only the desktop app can use them. */+ /**+ * Agents run as local processes and subscription sign-in returns to a local port, so only the+ * desktop app can use them.+ */agentsAvailable: booleancurrent?: CurrentOnboardingModels}@@ -105,6 +112,14 @@ export function isOnboardingAgent(providerID: string): boolean {return providerID.startsWith('acp:') || providerID === 'harness:pi'}+/** Access that only the desktop app can use. */+export function needsDesktop(providerID: string): boolean {+ return (+ isOnboardingAgent(providerID) ||+ (ONBOARDING_SUBSCRIPTIONS as readonly string[]).includes(providerID)+ )+}+function isAgentModel(model: PlannedModel | null): boolean {return Boolean(model && isOnboardingAgent(model.providerID))}@@ -154,7 +169,7 @@ function hasVision(model: PlannedModel): boolean {}function availableAccess(answers: OnboardingAnswers, options: PlanOptions): OnboardingAccess[] {- return answers.access.filter((access) => options.agentsAvailable || !isOnboardingAgent(access))+ return answers.access.filter((access) => options.agentsAvailable || !needsDesktop(access))}/** A configured model stays while its access is still selected or onboarding cannot offer it. */@@ -177,6 +192,7 @@ function planDesign(if (keepable(current, access)) return currentconst preferred: OnboardingAccess[] = [...ONBOARDING_AGENTS,+ ...ONBOARDING_SUBSCRIPTIONS,...ONBOARDING_API_PROVIDERS,...ONBOARDING_MORE_API_PROVIDERS,ONBOARDING_SERVER_PROVIDER@@ -194,9 +210,11 @@ function planVision(): PlannedRole {if (current !== null && current !== 'design' && keepable(current, access)) return currentif (canFollowDesign('vision', design)) return 'design'- // A local server that reads images is preferred over a paid account.+ // A local server that reads images is preferred over a paid account, and a subscription+ // already paid for over one billed by use.const candidates: OnboardingAccess[] = [ONBOARDING_SERVER_PROVIDER,+ ...ONBOARDING_SUBSCRIPTIONS,...ONBOARDING_API_PROVIDERS,...ONBOARDING_MORE_API_PROVIDERS]@@ -279,10 +297,19 @@ export function planOnboarding(answers: OnboardingAnswers, options: PlanOptions)review: planReview(design, vision, current),fast: planFast(design, vision, current)}- // A selected agent is always shown, as only its card tells whether it is installed and signed- // in, and the person can make it the design model in review.- const agents = access.filter(isOnboardingAgent)- return { ...roles, connections: uniq([...planConnections(roles), ...agents]) }+ // Everything selected is connected, after what the planned models need: the person said they+ // have it, its card is where they sign in or enter a key, and once connected its models can+ // take any role in review. An account a configured model already uses is not asked for again;+ // an agent is still shown, as only its card tells whether it is installed and signed in.+ const configured = new Set(+ roleModels(current)+ .filter((model) => model.profileId)+ .map((model) => model.providerID)+ )+ const selected = access.filter(+ (providerID) => isOnboardingAgent(providerID) || !configured.has(providerID)+ )+ return { ...roles, connections: uniq([...planConnections(roles), ...selected]) }}/** Providers the planned models need connected, skipping models that are already configured. */diff --git a/src/app/ai/models/settings/onboarding/sign-in.ts b/src/app/ai/models/settings/onboarding/sign-in.tsindex 230dbfa32..f9d507895 100644--- a/src/app/ai/models/settings/onboarding/sign-in.ts+++ b/src/app/ai/models/settings/onboarding/sign-in.ts@@ -1,18 +1,70 @@import { tryOnScopeDispose } from '@vueuse/core'import { reactive } from 'vue'+import {+ parseChatGPTCredential,+ serializeChatGPTCredential+} from '@/app/ai/providers/chatgpt/credential'+import { signInWithChatGPT, type ChatGPTSignInFailure } from '@/app/ai/providers/chatgpt/sign-in'import { fetchOpenRouterKeyInfo } from '@/app/ai/providers/openrouter/key'import {signInWithOpenRouter,- type OpenRouterSignIn,type OpenRouterSignInFailure,type OpenRouterSignInOptions} from '@/app/ai/providers/openrouter/sign-in'+import type { SignIn } from '@/app/ai/providers/sign-in/attempt'-import type { OnboardingConnectionState } from './connections'+import type { OnboardingAccount, OnboardingConnectionState } from './connections'import type { OnboardingAccess } from './plan'-export type OnboardingSignInStatus = 'idle' | 'waiting' | 'verifying' | OpenRouterSignInFailure+type SignInFailure = OpenRouterSignInFailure | ChatGPTSignInFailure+export type OnboardingSignInStatus = 'idle' | 'waiting' | 'verifying' | SignInFailure+export type OnboardingSignInLabels = Pick<OpenRouterSignInOptions, 'keyLabel'>++/** An attempt that ends with the credential to save as the connection's key. */+type CredentialSignIn = SignIn<string, 'blocked' | 'port-in-use'>++interface SignInProvider {+ start: (signal: AbortSignal, labels: OnboardingSignInLabels) => CredentialSignIn+ /** Confirms the credential works and reads the account it belongs to. */+ verify: (key: string) => Promise<OnboardingAccount | null>+}++/** Providers setup can sign in to instead of asking for a key. */+export type OnboardingSignInProvider = 'openrouter' | 'chatgpt'++const SIGN_IN_PROVIDERS: Record<OnboardingSignInProvider, SignInProvider> = {+ openrouter: {+ start: (signal, labels) => signInWithOpenRouter({ ...labels, signal }),+ // The key is checked with OpenRouter directly, which costs nothing and needs no credits.+ verify: async (key) => {+ const info = await fetchOpenRouterKeyInfo(key).catch(() => null)+ return info && { provider: 'openrouter', ...info }+ }+ },+ chatgpt: {+ start: (signal) => {+ const sign = signInWithChatGPT(signal)+ return {+ reopen: sign.reopen,+ result: sign.result.then((result) =>+ result.ok ? { ok: true, value: serializeChatGPTCredential(result.value) } : result+ )+ }+ },+ // The token endpoint already accepted the sign-in; the account is in its tokens.+ verify: async (key) => {+ const credential = parseChatGPTCredential(key)+ return credential && { provider: 'chatgpt', email: credential.email, plan: credential.plan }+ }+ }+}++export function isOnboardingSignInProvider(+ providerID: OnboardingAccess+): providerID is OnboardingSignInProvider {+ return Object.hasOwn(SIGN_IN_PROVIDERS, providerID)+}interface OnboardingSignInOptions {connection: (providerID: OnboardingAccess) => OnboardingConnectionState@@ -24,7 +76,7 @@ export function useOnboardingSignIn({ connection, resetTest }: OnboardingSignInOconst statuses = reactive<Partial<Record<OnboardingAccess, OnboardingSignInStatus>>>({})const attempts = new Map<OnboardingAccess,- { controller: AbortController; sign: OpenRouterSignIn }+ { controller: AbortController; sign: CredentialSignIn }>()tryOnScopeDispose(() => {@@ -36,7 +88,11 @@ export function useOnboardingSignIn({ connection, resetTest }: OnboardingSignInOreturn statuses[providerID] ?? 'idle'}- async function complete(providerID: OnboardingAccess, sign: OpenRouterSignIn): Promise<void> {+ async function complete(+ providerID: OnboardingAccess,+ provider: SignInProvider,+ sign: CredentialSignIn+ ): Promise<void> {const current = () => attempts.get(providerID)?.sign === signconst result = await sign.resultif (!current()) return@@ -45,9 +101,8 @@ export function useOnboardingSignIn({ connection, resetTest }: OnboardingSignInOstatuses[providerID] = result.reasonreturn}- // The key is checked with OpenRouter directly, which costs nothing and needs no credits.statuses[providerID] = 'verifying'- const account = await fetchOpenRouterKeyInfo(result.key).catch(() => null)+ const account = await provider.verify(result.value)if (!current()) returnattempts.delete(providerID)if (!account) {@@ -55,7 +110,7 @@ export function useOnboardingSignIn({ connection, resetTest }: OnboardingSignInOreturn}resetTest(providerID)- Object.assign(connection(providerID), { apiKey: result.key, account })+ Object.assign(connection(providerID), { apiKey: result.value, account })statuses[providerID] = 'idle'}@@ -68,17 +123,15 @@ export function useOnboardingSignIn({ connection, resetTest }: OnboardingSignInO}/** Call directly from the click that starts sign-in, so the browser allows its popup. */- function signIn(- providerID: OnboardingAccess,- labels: Pick<OpenRouterSignInOptions, 'keyLabel'>- ): void {- if (providerID !== 'openrouter') return+ function signIn(providerID: OnboardingAccess, labels: OnboardingSignInLabels): void {+ if (!isOnboardingSignInProvider(providerID)) return+ const provider = SIGN_IN_PROVIDERS[providerID]attempts.get(providerID)?.controller.abort()const controller = new AbortController()- const sign = signInWithOpenRouter({ ...labels, signal: controller.signal })+ const sign = provider.start(controller.signal, labels)attempts.set(providerID, { controller, sign })statuses[providerID] = 'waiting'- void complete(providerID, sign)+ void complete(providerID, provider, sign)}function reopenSignIn(providerID: OnboardingAccess): void {diff --git a/src/app/ai/models/settings/profile-editor/connection.ts b/src/app/ai/models/settings/profile-editor/connection.tsindex 937bc4e89..df36a28af 100644--- a/src/app/ai/models/settings/profile-editor/connection.ts+++ b/src/app/ai/models/settings/profile-editor/connection.ts@@ -4,6 +4,7 @@ import { computed, ref, type Ref } from 'vue'import {findModelConnectionForDraft,modelConnectionCredentialStatus,+ modelConnectionCredentialStore,resolveModelConnectionAPIKey,type AIModelProfileDraft} from '@/app/ai/models'@@ -72,14 +73,17 @@ export function useProfileConnection({ draft, keyInput }: ConnectionOptions) {? await resolveModelConnectionAPIKey(connection.id): nullif (!current(request)) return- const result = await testProviderConnection({- providerID: target.providerID,- apiKey: replacement || existingKey || '',- modelID: target.modelID,- customModelID: target.customModelID,- customBaseURL: target.customBaseURL,- customAPIType: target.customAPIType- })+ const result = await testProviderConnection(+ {+ providerID: target.providerID,+ apiKey: replacement || existingKey || '',+ modelID: target.modelID,+ customModelID: target.customModelID,+ customBaseURL: target.customBaseURL,+ customAPIType: target.customAPIType+ },+ existingKey && connection ? modelConnectionCredentialStore(connection.id) : undefined+ )if (!current(request)) returnconnectionTestStatus.value = result.ok ? 'success' : 'error'connectionTestReason.value = result.ok ? null : result.reasondiff --git a/src/app/ai/models/settings/profile-editor/sign-in.ts b/src/app/ai/models/settings/profile-editor/sign-in.tsnew file mode 100644index 000000000..91aab2def--- /dev/null+++ b/src/app/ai/models/settings/profile-editor/sign-in.ts@@ -0,0 +1,59 @@+import { tryOnScopeDispose } from '@vueuse/core'+import { computed, ref, type Ref } from 'vue'++import {+ parseChatGPTCredential,+ serializeChatGPTCredential+} from '@/app/ai/providers/chatgpt/credential'+import {+ signInWithChatGPT,+ type ChatGPTSignIn,+ type ChatGPTSignInFailure+} from '@/app/ai/providers/chatgpt/sign-in'++export type ProfileSignInStatus = 'idle' | 'waiting' | ChatGPTSignInFailure++/**+ * Signing in for a provider that takes no pasted key. The credential lands in the key input,+ * so saving the profile stores it like a key.+ */+export function useProfileSignIn(keyInput: Ref<string>) {+ const status = ref<ProfileSignInStatus>('idle')+ let attempt: { controller: AbortController; sign: ChatGPTSignIn } | null = null++ /** The account signed in to during this edit; a saved sign-in is not read back. */+ const email = computed(() => parseChatGPTCredential(keyInput.value)?.email)+ const signedIn = computed(() => parseChatGPTCredential(keyInput.value) !== null)++ function cancel(): void {+ attempt?.controller.abort()+ attempt = null+ status.value = 'idle'+ }++ async function signIn(): Promise<void> {+ cancel()+ const controller = new AbortController()+ const sign = signInWithChatGPT(controller.signal)+ attempt = { controller, sign }+ const current = () => attempt?.sign === sign+ status.value = 'waiting'+ const result = await sign.result+ if (!current()) return+ attempt = null+ if (!result.ok) {+ status.value = result.reason+ return+ }+ keyInput.value = serializeChatGPTCredential(result.value)+ status.value = 'idle'+ }++ function reopen(): void {+ attempt?.sign.reopen()+ }++ tryOnScopeDispose(cancel)++ return { status, email, signedIn, signIn, reopen, cancel }+}diff --git a/src/app/ai/providers/chatgpt/adapter.ts b/src/app/ai/providers/chatgpt/adapter.tsnew file mode 100644index 000000000..54e742aa6--- /dev/null+++ b/src/app/ai/providers/chatgpt/adapter.ts@@ -0,0 +1,56 @@+import { createOpenAI } from '@ai-sdk/openai'+import { defaultSettingsMiddleware, wrapLanguageModel } from 'ai'++import { randomHex } from '@open-pencil/scene-graph/random'++import type { ModelCredentialStore, ModelProviderAdapter } from '@/app/ai/providers/types'+import type { FetchFunction } from '@/app/http/types'++import {+ parseChatGPTCredential,+ serializeChatGPTCredential,+ type ChatGPTCredential+} from './credential'+import { CHATGPT_CODEX_BASE_URL, ChatGPTSignInExpiredError, createCodexFetch } from './fetch'++/** A fetch signed by a stored ChatGPT sign-in, which keeps the tokens it refreshes. */+export function chatGPTFetch(+ credential: ChatGPTCredential,+ store?: ModelCredentialStore,+ fetchImpl?: FetchFunction,+ promptCacheKey?: string+): FetchFunction {+ return createCodexFetch({+ credential,+ fetch: fetchImpl,+ promptCacheKey,+ load: store && (async () => parseChatGPTCredential((await store.load()) ?? '')),+ save: store && ((next) => store.save(serializeChatGPTCredential(next)))+ })+}++/** ChatGPT accounts reach their models through the Codex backend's Responses API. */+export const chatGPTAdapter: ModelProviderAdapter = {+ create(config, runtime) {+ const credential = parseChatGPTCredential(config.apiKey)+ if (!credential) throw new ChatGPTSignInExpiredError()+ const provider = createOpenAI({+ // The signed fetch replaces this with the account's access token.+ apiKey: 'chatgpt',+ baseURL: CHATGPT_CODEX_BASE_URL,+ fetch: chatGPTFetch(credential, runtime.credentials, runtime.fetch, randomHex(16))+ })+ // The backend keeps nothing, so earlier replies must be sent whole: with `store` off the AI+ // SDK sends their items and encrypted reasoning instead of references to stored ones.+ return wrapLanguageModel({+ model: provider.responses(config.modelID),+ middleware: defaultSettingsMiddleware({+ settings: {+ providerOptions: {+ openai: { store: false, include: ['reasoning.encrypted_content'] }+ }+ }+ })+ })+ }+}diff --git a/src/app/ai/providers/chatgpt/catalog.ts b/src/app/ai/providers/chatgpt/catalog.tsnew file mode 100644index 000000000..302135cb2--- /dev/null+++ b/src/app/ai/providers/chatgpt/catalog.ts@@ -0,0 +1,111 @@+import { sortBy } from 'es-toolkit/array'+import * as v from 'valibot'++import { REASONING_EFFORTS } from '@open-pencil/core/constants'+import type { ModelOption, ReasoningEffort } from '@open-pencil/core/constants'++import { modelOptionsSchema } from '@/app/ai/models/catalog/schema'+import { readCacheJSON, writeCacheJSON } from '@/app/cache'+import { cachedRemoteJSON } from '@/app/cache/remote'+import type { FetchFunction } from '@/app/http/types'++import { CHATGPT_CODEX_BASE_URL } from './fetch'++/**+ * The backend lists only the models a Codex release supports, so the catalog asks as the+ * current release; an older version would hide newer models.+ */+const CODEX_RELEASE_URL = 'https://registry.npmjs.org/@openai/codex/latest'+const CODEX_RELEASE_CACHE_KEY = 'chatgpt/codex-release'+const CHATGPT_MODELS_CACHE_KEY = 'chatgpt/models'+const CACHE_TTL_MS = 24 * 60 * 60 * 1000+const REQUEST_TIMEOUT_MS = 10_000++const codexRelease = cachedRemoteJSON({+ key: CODEX_RELEASE_CACHE_KEY,+ schema: v.string(),+ maxAgeMs: CACHE_TTL_MS,+ load: async (fetcher) => {+ const response = await fetcher(CODEX_RELEASE_URL, {+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)+ })+ if (!response.ok) throw new Error(`Codex release request failed: ${response.status}`)+ const release = v.parse(+ v.pipe(v.string(), v.parseJson(), v.looseObject({ version: v.string() })),+ await response.text()+ )+ return release.version+ }+})++const chatGPTModelSchema = v.looseObject({+ slug: v.string(),+ display_name: v.optional(v.string()),+ visibility: v.optional(v.string()),+ priority: v.optional(v.number()),+ input_modalities: v.optional(v.array(v.string())),+ supported_reasoning_levels: v.optional(v.array(v.looseObject({ effort: v.string() })))+})+type ChatGPTModel = v.InferOutput<typeof chatGPTModelSchema>++// Entries are checked one by one, so one odd model keeps the rest.+const chatGPTModelsResponseSchema = v.pipe(+ v.string(),+ v.parseJson(),+ v.object({ models: v.array(v.unknown()) })+)++function minReasoningEffort(model: ChatGPTModel): ReasoningEffort | undefined {+ const levels = model.supported_reasoning_levels?.map((level) => level.effort)+ if (!levels?.length) return undefined+ return REASONING_EFFORTS.find((effort) => levels.includes(effort))+}++/** Models the account may pick, best first; hidden ones serve Codex's own features. */+export function normalizeChatGPTModels(entries: unknown[]): ModelOption[] {+ const listed = entries.filter(+ (entry): entry is ChatGPTModel => v.is(chatGPTModelSchema, entry) && entry.visibility === 'list'+ )+ return sortBy(listed, [(model) => model.priority ?? Number.MAX_SAFE_INTEGER]).map((model) => {+ const option: ModelOption = {+ id: model.slug,+ name: model.display_name || model.slug,+ capabilities: model.input_modalities?.includes('image') ? ['tools', 'vision'] : ['tools']+ }+ const minEffort = minReasoningEffort(model)+ if (minEffort) option.minReasoningEffort = minEffort+ return option+ })+}++/** The last catalog fetched for any signed-in account, without asking the backend. */+export function cachedChatGPTModels(): Promise<ModelOption[] | null> {+ return readCacheJSON(CHATGPT_MODELS_CACHE_KEY, modelOptionsSchema).catch(() => null)+}++/** Fetches the account's models with a fetch signed by its sign-in, then caches the list. */+export async function fetchChatGPTModels(+ signedFetch: FetchFunction+): Promise<ModelOption[] | null> {+ const cached = await readCacheJSON(+ CHATGPT_MODELS_CACHE_KEY,+ modelOptionsSchema,+ CACHE_TTL_MS+ ).catch(() => null)+ if (cached) return cached+ const version = await codexRelease.get()+ if (!version) return null+ const url = new URL(`${CHATGPT_CODEX_BASE_URL}/models`)+ url.searchParams.set('client_version', version)+ const response = await signedFetch(url, { signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS) })+ if (!response.ok) return null+ const parsed = v.safeParse(chatGPTModelsResponseSchema, await response.text())+ const models = parsed.success ? normalizeChatGPTModels(parsed.output.models) : []+ if (!models.length) return null+ await writeCacheJSON(CHATGPT_MODELS_CACHE_KEY, models).catch(() => undefined)+ return models+}++export function resetChatGPTCatalogForTests(): void {+ codexRelease.reset()+}diff --git a/src/app/ai/providers/chatgpt/credential.ts b/src/app/ai/providers/chatgpt/credential.tsnew file mode 100644index 000000000..6e74a1d09--- /dev/null+++ b/src/app/ai/providers/chatgpt/credential.ts@@ -0,0 +1,24 @@+import * as v from 'valibot'++/** A ChatGPT sign-in, kept as JSON in the connection's credential slot. */+const chatGPTCredentialSchema = v.object({+ access: v.pipe(v.string(), v.minLength(1)),+ refresh: v.pipe(v.string(), v.minLength(1)),+ /** When the access token expires, in epoch milliseconds. */+ expires: v.number(),+ accountId: v.pipe(v.string(), v.minLength(1)),+ email: v.optional(v.string()),+ /** The ChatGPT plan, such as `plus` or `pro`. */+ plan: v.optional(v.string())+})++export type ChatGPTCredential = v.InferOutput<typeof chatGPTCredentialSchema>++export function parseChatGPTCredential(text: string): ChatGPTCredential | null {+ const parsed = v.safeParse(v.pipe(v.string(), v.parseJson(), chatGPTCredentialSchema), text)+ return parsed.success ? parsed.output : null+}++export function serializeChatGPTCredential(credential: ChatGPTCredential): string {+ return JSON.stringify(credential)+}diff --git a/src/app/ai/providers/chatgpt/fetch.ts b/src/app/ai/providers/chatgpt/fetch.tsnew file mode 100644index 000000000..6c052ba42--- /dev/null+++ b/src/app/ai/providers/chatgpt/fetch.ts@@ -0,0 +1,203 @@+import { uniq } from 'es-toolkit/array'+import { omit } from 'es-toolkit/object'+import * as v from 'valibot'++import type { FetchFunction } from '@/app/http/types'++import type { ChatGPTCredential } from './credential'+import { CHATGPT_ORIGINATOR, ChatGPTTokenError, refreshChatGPTCredential } from './oauth'++/** The Codex backend serves the Responses API to ChatGPT accounts. */+export const CHATGPT_CODEX_BASE_URL = 'https://chatgpt.com/backend-api/codex'+/** Refreshes this long before the access token expires, so a request never carries a stale one. */+const REFRESH_MARGIN_MS = 60_000+const LITE_HEADER = 'x-openai-internal-codex-responses-lite'++export class ChatGPTSignInExpiredError extends Error {+ /** Read as an authentication failure, like a rejected API key. */+ readonly status = 401++ constructor() {+ super('The ChatGPT sign-in has expired. Sign in again from AI settings.')+ this.name = 'ChatGPTSignInExpiredError'+ }+}++export interface CodexFetchOptions {+ credential: ChatGPTCredential+ /** Reads the stored credential, which another model may have refreshed since this one began. */+ load?: () => Promise<ChatGPTCredential | null>+ /** Keeps a refreshed credential; OpenAI rotates refresh tokens, so losing one signs out. */+ save?: (credential: ChatGPTCredential) => Promise<void>+ fetch?: FetchFunction+ /** Groups one conversation's requests for the backend's prompt cache. */+ promptCacheKey?: string+}++/**+ * Refreshes in flight by refresh token. A refresh token works once, so models sharing a sign-in+ * join one refresh instead of spending it twice.+ */+const pendingRefreshes = new Map<string, Promise<ChatGPTCredential>>()++const REFUSED_STATUSES = new Set([400, 401, 403])+/** Codes that say the refresh token itself is spent, expired, or revoked. */+const REFUSED_CODES = new Set([+ 'invalid_grant',+ 'invalid_refresh_token',+ 'refresh_token_expired',+ 'refresh_token_reused',+ 'refresh_token_invalidated'+])++/**+ * The token endpoint answers a bad refresh token with 401 and `invalid_refresh_token`; like the+ * Codex CLI, any 401 ends the sign-in. Other statuses end it only for a refusing code.+ */+function refusesSignIn(error: unknown): boolean {+ if (!(error instanceof ChatGPTTokenError)) return false+ if (error.status === 401) return true+ return error.code === undefined+ ? REFUSED_STATUSES.has(error.status)+ : REFUSED_CODES.has(error.code)+}++function isFresh(credential: ChatGPTCredential): boolean {+ return credential.expires - Date.now() >= REFRESH_MARGIN_MS+}++async function refreshAndSave(+ credential: ChatGPTCredential,+ fetchImpl: FetchFunction,+ save: CodexFetchOptions['save']+): Promise<ChatGPTCredential> {+ let refreshed: ChatGPTCredential+ try {+ refreshed = await refreshChatGPTCredential(credential, fetchImpl)+ } catch (error) {+ // Only a refused refresh ends the sign-in; a busy or failing auth server leaves it valid.+ throw refusesSignIn(error) ? new ChatGPTSignInExpiredError() : error+ }+ // The old refresh token is spent either way, so a failed save still uses the new pair.+ await save?.(refreshed).catch((error: unknown) => {+ console.warn('Could not save the refreshed ChatGPT sign-in:', error)+ })+ return refreshed+}++const requestBodySchema = v.looseObject({+ stream: v.optional(v.boolean()),+ input: v.optional(v.array(v.unknown())),+ tools: v.optional(v.array(v.unknown())),+ reasoning: v.optional(v.looseObject({})),+ include: v.optional(v.array(v.string()))+})+type RequestBody = v.InferOutput<typeof requestBodySchema>++const systemMessageSchema = v.looseObject({ role: v.literal('system') })++/**+ * Rewrites a Responses request the way Codex sends it. The backend only streams and keeps+ * nothing, so reasoning comes back encrypted for the next turn. Current models take the Lite+ * format, which moves tools into a developer item and runs one tool call at a time.+ */+export function codexRequestBody(body: RequestBody, promptCacheKey?: string): RequestBody {+ const input = (body.input ?? []).map((item) =>+ v.is(systemMessageSchema, item) ? { ...item, role: 'developer' } : item+ )+ // Codex never limits output; plans meter usage instead.+ const tools = body.tools+ return {+ ...omit(body, ['tools', 'max_output_tokens']),+ stream: true,+ store: false,+ include: uniq([...(body.include ?? []), 'reasoning.encrypted_content']),+ ...(promptCacheKey && { prompt_cache_key: promptCacheKey }),+ parallel_tool_calls: false,+ reasoning: { ...body.reasoning, context: 'all_turns' },+ input: tools?.length+ ? [+ {+ type: 'additional_tools',+ role: 'developer',+ tools: [{ type: 'namespace', name: 'functions', description: '', tools }]+ },+ ...input+ ]+ : input+ }+}++const streamEventSchema = v.looseObject({ type: v.string(), response: v.optional(v.unknown()) })++/** The final response of an event stream, for callers that asked for one JSON answer. */+export function completedResponse(stream: string): unknown {+ for (const line of stream.split('\n')) {+ if (!line.startsWith('data: ')) continue+ const event = v.safeParse(v.pipe(v.string(), v.parseJson(), streamEventSchema), line.slice(6))+ if (event.success && event.output.type === 'response.completed') return event.output.response+ }+ return undefined+}++/**+ * A `fetch` for the AI SDK's OpenAI provider that signs requests with a ChatGPT account,+ * refreshes the sign-in when it is about to expire or is rejected, and speaks Codex's format.+ */+export function createCodexFetch(options: CodexFetchOptions): FetchFunction {+ const fetchImpl = options.fetch ?? fetch+ let credential = options.credential++ async function refresh(): Promise<void> {+ const stored = await options.load?.()+ if (stored && stored.refresh !== credential.refresh && isFresh(stored)) {+ credential = stored+ return+ }+ const token = credential.refresh+ let pending = pendingRefreshes.get(token)+ if (!pending) {+ pending = refreshAndSave(credential, fetchImpl, options.save).finally(() =>+ pendingRefreshes.delete(token)+ )+ pendingRefreshes.set(token, pending)+ }+ credential = await pending+ }++ function send(input: RequestInfo | URL, init: RequestInit, responses: boolean) {+ const headers = new Headers(init.headers)+ headers.set('authorization', `Bearer ${credential.access}`)+ headers.set('chatgpt-account-id', credential.accountId)+ headers.set('originator', CHATGPT_ORIGINATOR)+ if (responses) {+ headers.set('OpenAI-Beta', 'responses=experimental')+ headers.set('accept', 'text/event-stream')+ headers.set(LITE_HEADER, 'true')+ }+ return fetchImpl(input, { ...init, headers })+ }++ async function signed(input: RequestInfo | URL, init: RequestInit, responses: boolean) {+ if (!isFresh(credential)) await refresh()+ const response = await send(input, init, responses)+ if (response.status !== 401) return response+ await refresh()+ return send(input, init, responses)+ }++ return async (input, init = {}) => {+ const parsed = v.safeParse(+ v.pipe(v.string(), v.parseJson(), requestBodySchema),+ typeof init.body === 'string' ? init.body : ''+ )+ if (!parsed.success) return signed(input, init, false)+ const body = JSON.stringify(codexRequestBody(parsed.output, options.promptCacheKey))+ const response = await signed(input, { ...init, body }, true)+ if (!response.ok || parsed.output.stream === true) return response+ return new Response(JSON.stringify(completedResponse(await response.text()) ?? null), {+ status: response.status,+ headers: { 'content-type': 'application/json' }+ })+ }+}diff --git a/src/app/ai/providers/chatgpt/oauth.ts b/src/app/ai/providers/chatgpt/oauth.tsnew file mode 100644index 000000000..8772d3e2c--- /dev/null+++ b/src/app/ai/providers/chatgpt/oauth.ts@@ -0,0 +1,155 @@+import { decode, isValid } from 'js-base64'+import * as v from 'valibot'++import type { FetchFunction } from '@/app/http/types'++import type { PKCE } from '../sign-in/pkce'+import type { ChatGPTCredential } from './credential'++/**+ * ChatGPT sign-in is the OAuth PKCE flow the Codex CLI uses. OpenAI registers its client with+ * one redirect, a loopback listener on port 1455, so only the desktop app can receive it.+ */+export const CHATGPT_CLIENT_ID = 'app_EMoamEEZ73f0CkXaXp7hrann'+export const CHATGPT_AUTHORIZE_URL = 'https://auth.openai.com/oauth/authorize'+export const CHATGPT_TOKEN_URL = 'https://auth.openai.com/oauth/token'+export const CHATGPT_CALLBACK_PORT = 1455+export const CHATGPT_CALLBACK_PATH = '/auth/callback'+export const CHATGPT_REDIRECT_URI = `http://localhost:${CHATGPT_CALLBACK_PORT}${CHATGPT_CALLBACK_PATH}`+/** Names this app to the backend in its `originator` header and on the consent screen. */+export const CHATGPT_ORIGINATOR = 'open-pencil'+const SCOPE = 'openid profile email offline_access'+/** The custom claim OpenAI puts its account details in. */+const AUTH_CLAIM = 'https://api.openai.com/auth'++export class ChatGPTTokenError extends Error {+ constructor(+ readonly status: number,+ /** The error code of an OAuth error body, such as `invalid_grant`. */+ readonly code?: string+ ) {+ super(`ChatGPT token request failed with status ${status}`)+ this.name = 'ChatGPTTokenError'+ }+}++export function chatGPTAuthorizationURL(pkce: PKCE): string {+ const url = new URL(CHATGPT_AUTHORIZE_URL)+ url.searchParams.set('response_type', 'code')+ url.searchParams.set('client_id', CHATGPT_CLIENT_ID)+ url.searchParams.set('redirect_uri', CHATGPT_REDIRECT_URI)+ url.searchParams.set('scope', SCOPE)+ url.searchParams.set('code_challenge', pkce.challenge)+ url.searchParams.set('code_challenge_method', 'S256')+ url.searchParams.set('state', pkce.state)+ url.searchParams.set('id_token_add_organizations', 'true')+ url.searchParams.set('codex_cli_simplified_flow', 'true')+ url.searchParams.set('originator', CHATGPT_ORIGINATOR)+ return url.toString()+}++const authClaimSchema = v.object({+ [AUTH_CLAIM]: v.looseObject({+ chatgpt_account_id: v.optional(v.string()),+ chatgpt_plan_type: v.optional(v.string())+ })+})+const idTokenSchema = v.looseObject({ email: v.optional(v.string()), ...authClaimSchema.entries })+const tokenResponseSchema = v.object({+ access_token: v.pipe(v.string(), v.minLength(1)),+ refresh_token: v.pipe(v.string(), v.minLength(1)),+ expires_in: v.pipe(v.number(), v.minValue(0)),+ id_token: v.optional(v.string())+})++/** A JWT's payload, unverified: the app only reads what its own token endpoint just returned. */+function jwtPayload(token: string): unknown {+ const payload = token.split('.')[1]+ if (!payload || !isValid(payload)) return null+ const parsed = v.safeParse(v.pipe(v.string(), v.parseJson()), decode(payload))+ return parsed.success ? parsed.output : null+}++type ChatGPTAccount = Pick<ChatGPTCredential, 'accountId' | 'email' | 'plan'>++/** Reads the account a token pair belongs to; the access token always names it. */+export function chatGPTAccount(accessToken: string, idToken?: string): ChatGPTAccount | null {+ const access = v.safeParse(authClaimSchema, jwtPayload(accessToken))+ const accountId = access.success ? access.output[AUTH_CLAIM].chatgpt_account_id : undefined+ if (!accountId) return null+ const id = idToken ? v.safeParse(idTokenSchema, jwtPayload(idToken)) : null+ return {+ accountId,+ email: id?.success ? id.output.email : undefined,+ plan: id?.success ? id.output[AUTH_CLAIM].chatgpt_plan_type : undefined+ }+}++// RFC 6749 sends `error` as a string; OpenAI's refresh errors nest it as `error.code`.+const oauthErrorBodySchema = v.object({+ error: v.union([v.string(), v.looseObject({ code: v.string() })])+})++async function oauthErrorCode(response: Response): Promise<string | undefined> {+ const parsed = v.safeParse(+ v.pipe(v.string(), v.parseJson(), oauthErrorBodySchema),+ await response.text().catch(() => '')+ )+ if (!parsed.success) return undefined+ const { error } = parsed.output+ return typeof error === 'string' ? error : error.code+}++async function requestTokens(+ body: Record<string, string>,+ fetchImpl: FetchFunction,+ previous?: ChatGPTAccount+): Promise<ChatGPTCredential> {+ const response = await fetchImpl(CHATGPT_TOKEN_URL, {+ method: 'POST',+ headers: { 'content-type': 'application/x-www-form-urlencoded' },+ body: new URLSearchParams({ client_id: CHATGPT_CLIENT_ID, ...body }).toString()+ })+ if (!response.ok) throw new ChatGPTTokenError(response.status, await oauthErrorCode(response))+ const tokens = v.safeParse(tokenResponseSchema, await response.json())+ if (!tokens.success) throw new ChatGPTTokenError(response.status)+ const { access_token, refresh_token, expires_in, id_token } = tokens.output+ const account = chatGPTAccount(access_token, id_token)+ if (!account) throw new ChatGPTTokenError(response.status)+ return {+ access: access_token,+ refresh: refresh_token,+ expires: Date.now() + expires_in * 1000,+ accountId: account.accountId,+ email: account.email ?? previous?.email,+ plan: account.plan ?? previous?.plan+ }+}++export function exchangeChatGPTCode(+ code: string,+ verifier: string,+ fetchImpl: FetchFunction+): Promise<ChatGPTCredential> {+ return requestTokens(+ {+ grant_type: 'authorization_code',+ code,+ code_verifier: verifier,+ redirect_uri: CHATGPT_REDIRECT_URI+ },+ fetchImpl+ )+}++/** Trades the refresh token for a new pair; OpenAI rotates the refresh token each time. */+export function refreshChatGPTCredential(+ credential: ChatGPTCredential,+ fetchImpl: FetchFunction+): Promise<ChatGPTCredential> {+ return requestTokens(+ { grant_type: 'refresh_token', refresh_token: credential.refresh },+ fetchImpl,+ credential+ )+}diff --git a/src/app/ai/providers/chatgpt/sign-in.ts b/src/app/ai/providers/chatgpt/sign-in.tsnew file mode 100644index 000000000..7afaccbc2--- /dev/null+++ b/src/app/ai/providers/chatgpt/sign-in.ts@@ -0,0 +1,63 @@+import { invoke } from '@tauri-apps/api/core'+import * as v from 'valibot'++import { aiMessages } from '@open-pencil/vue/i18n'++import { openExternalLink } from '@/app/shell/ui'+import { tauriFetch } from '@/app/tauri/http'++import {+ startSignIn,+ type SignIn,+ type SignInCallback,+ type SignInFailure+} from '../sign-in/attempt'+import type { ChatGPTCredential } from './credential'+import { chatGPTAuthorizationURL, exchangeChatGPTCode } from './oauth'++export type ChatGPTSignInFailure = SignInFailure | 'port-in-use'+export type ChatGPTSignIn = SignIn<ChatGPTCredential, 'port-in-use'>++/** What `chatgpt_oauth_wait` returns once the redirect arrives, the wait ends, or it is cancelled. */+const loopbackOutcomeSchema = v.variant('kind', [+ v.object({ kind: v.literal('code'), code: v.string() }),+ v.object({ kind: v.picklist(['denied', 'expired', 'cancelled']) })+])++/**+ * Takes the loopback port the redirect returns to before the page opens; the desktop shell+ * checks the state and answers the browser.+ */+async function loopbackCallback(+ state: string+): Promise<SignInCallback | { failure: 'port-in-use' }> {+ const ai = aiMessages.get()+ // The browser shows these after the redirect, so they come in the app's language.+ const pages = {+ signedIn: ai.aiSetupChatGPTCallbackSignedIn,+ cancelled: ai.aiSetupChatGPTCallbackCancelled,+ stale: ai.aiSetupChatGPTCallbackStale+ }+ try {+ await invoke('chatgpt_oauth_listen', { state, pages })+ } catch (error) {+ if (error === 'port-in-use') return { failure: 'port-in-use' }+ throw error+ }+ return {+ open: openExternalLink,+ wait: async () => v.parse(loopbackOutcomeSchema, await invoke('chatgpt_oauth_wait')),+ // Frees the port; the state keeps a late cancel from ending a newer attempt.+ close: () => void invoke('chatgpt_oauth_cancel', { state }).catch(() => undefined)+ }+}++/** Signs in to ChatGPT in the system browser; the browser app cannot receive the redirect. */+export function signInWithChatGPT(signal: AbortSignal): ChatGPTSignIn {+ return startSignIn({+ signal,+ callback: loopbackCallback,+ authorizationURL: chatGPTAuthorizationURL,+ exchange: (code, verifier) => exchangeChatGPTCode(code, verifier, tauriFetch)+ })+}diff --git a/src/app/ai/providers/openrouter/oauth.ts b/src/app/ai/providers/openrouter/oauth.tsindex 0a78c9e84..57157c379 100644--- a/src/app/ai/providers/openrouter/oauth.ts+++ b/src/app/ai/providers/openrouter/oauth.ts@@ -1,22 +1,13 @@-import { fromUint8Array } from 'js-base64'import * as v from 'valibot'+import type { PKCE } from '../sign-in/pkce'+/** OpenRouter's OAuth PKCE flow: https://openrouter.ai/docs/guides/overview/auth/oauth */export const OPENROUTER_AUTH_URL = 'https://openrouter.ai/auth'export const OPENROUTER_KEYS_URL = 'https://openrouter.ai/api/v1/auth/keys'/** Authorization codes expire after ten minutes. */export const OPENROUTER_CODE_LIFETIME_MS = 10 * 60 * 1000-export interface OpenRouterPKCE {- verifier: string- challenge: string- state: string-}--export type OpenRouterCallback =- | { ok: true; code: string }- | { ok: false; reason: 'cancelled' | 'mismatch' }-export class OpenRouterKeyExchangeError extends Error {constructor(readonly status: number) {super(`OpenRouter key exchange failed with status ${status}`)@@ -24,24 +15,9 @@ export class OpenRouterKeyExchangeError extends Error {}}-function randomToken(bytes: number): string {- return fromUint8Array(crypto.getRandomValues(new Uint8Array(bytes)), true)-}--/** The S256 challenge for a verifier: the base64url SHA-256 digest, without padding. */-export async function pkceChallenge(verifier: string): Promise<string> {- const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(verifier))- return fromUint8Array(new Uint8Array(digest), true)-}--export async function createOpenRouterPKCE(): Promise<OpenRouterPKCE> {- const verifier = randomToken(48)- return { verifier, challenge: await pkceChallenge(verifier), state: randomToken(16) }-}-export function openRouterAuthorizationURL(callbackURL: string,- pkce: OpenRouterPKCE,+ pkce: PKCE,keyLabel: string): string {const url = new URL(OPENROUTER_AUTH_URL)@@ -53,14 +29,6 @@ export function openRouterAuthorizationURL(return url.toString()}-/** Reads the redirect OpenRouter sends back, rejecting one that belongs to another attempt. */-export function parseOpenRouterCallback(query: string, expectedState: string): OpenRouterCallback {- const params = new URLSearchParams(query)- if (params.get('state') !== expectedState) return { ok: false, reason: 'mismatch' }- const code = params.get('code')- return code ? { ok: true, code } : { ok: false, reason: 'cancelled' }-}-const keyExchangeSchema = v.object({ key: v.pipe(v.string(), v.minLength(1)) })/** Trades an authorization code for an API key; OpenRouter allows this from a browser. */diff --git a/src/app/ai/providers/openrouter/sign-in.ts b/src/app/ai/providers/openrouter/sign-in.tsindex 3fddda5d3..c68274bf8 100644--- a/src/app/ai/providers/openrouter/sign-in.ts+++ b/src/app/ai/providers/openrouter/sign-in.ts@@ -7,12 +7,17 @@ import { openExternalLink } from '@/app/shell/ui'import { WEB_APP_ORIGIN } from '@/constants'import {- createOpenRouterPKCE,+ callbackOutcome,+ startSignIn,+ type CallbackOutcome,+ type SignIn,+ type SignInCallback,+ type SignInFailure+} from '../sign-in/attempt'+import {exchangeOpenRouterCode,openRouterAuthorizationURL,- OPENROUTER_CODE_LIFETIME_MS,- parseOpenRouterCallback,- type OpenRouterPKCE+ OPENROUTER_CODE_LIFETIME_MS} from './oauth'/** Served from `public/`; it relays the redirect to the editor over this channel. */@@ -25,10 +30,8 @@ const OAUTH_CALLBACK_EVENT = 'oauth-callback'const POPUP_NAME = 'open-pencil-openrouter'const POPUP_FEATURES = 'popup,width=520,height=720'-export type OpenRouterSignInFailure = 'cancelled' | 'blocked' | 'expired' | 'failed'-export type OpenRouterSignInResult =- | { ok: true; key: string }- | { ok: false; reason: OpenRouterSignInFailure }+export type OpenRouterSignInFailure = SignInFailure | 'blocked'+export type OpenRouterSignIn = SignIn<string, 'blocked'>export interface OpenRouterSignInOptions {signal: AbortSignal@@ -39,138 +42,77 @@ export interface OpenRouterSignInOptions {/** What the desktop shell forwards from an `openpencil://oauth/<provider>?…` link. */const oauthCallbackSchema = v.object({ provider: v.string(), query: v.string() })-export interface OpenRouterSignIn {- /** Opens the OpenRouter sign-in page again for the same attempt. */- reopen: () => void- result: Promise<OpenRouterSignInResult>-}--class SignInAbortedError extends Error {- constructor() {- super('OpenRouter sign-in was cancelled')- this.name = 'SignInAbortedError'- }-}--async function abortable<T>(promise: Promise<T>, signal: AbortSignal): Promise<T> {- if (signal.aborted) throw new SignInAbortedError()- const aborted = createDeferred<never>()- const abort = () => aborted.reject(new SignInAbortedError())- signal.addEventListener('abort', abort, { once: true })- try {- return await Promise.race([promise, aborted.promise])- } finally {- signal.removeEventListener('abort', abort)- }-}--async function finish(- query: string | null,- pkce: OpenRouterPKCE,- signal: AbortSignal-): Promise<OpenRouterSignInResult> {- if (query === null) return { ok: false, reason: 'expired' }- const callback = parseOpenRouterCallback(query, pkce.state)- if (!callback.ok)- return { ok: false, reason: callback.reason === 'cancelled' ? 'cancelled' : 'failed' }- return {- ok: true,- key: await abortable(exchangeOpenRouterCode(callback.code, pkce.verifier), signal)- }-}--function settle(run: () => Promise<OpenRouterSignInResult>): Promise<OpenRouterSignInResult> {- return run().catch((error: unknown) => ({- ok: false as const,- reason: error instanceof SignInAbortedError ? ('cancelled' as const) : ('failed' as const)- }))-}--/** Waits for the callback page in this origin to relay the redirect query. */-function browserCallback(signal: AbortSignal): Promise<string | null> {- const channel = new BroadcastChannel(OPENROUTER_CALLBACK_CHANNEL)- let timer: ReturnType<typeof setTimeout> | undefined- const received = new Promise<string | null>((resolve) => {- timer = setTimeout(() => resolve(null), OPENROUTER_CODE_LIFETIME_MS)- channel.addEventListener('message', (event: MessageEvent<unknown>) => {- if (typeof event.data === 'string') resolve(event.data)- })- })- return abortable(received, signal).finally(() => {- clearTimeout(timer)- channel.close()- })+/** A redirect that resolves once, or as expired when the code's lifetime passes. */+function pendingRedirect() {+ const received = createDeferred<CallbackOutcome>()+ const timer = setTimeout(() => received.resolve({ kind: 'expired' }), OPENROUTER_CODE_LIFETIME_MS)+ return { received, stop: () => clearTimeout(timer) }}/**- * Opens OpenRouter in a popup that returns to this origin. Must be called from the click that- * starts sign-in, before anything is awaited, or the browser blocks the popup.+ * A popup that returns to this origin, whose callback page relays the redirect query. The popup+ * opens before anything is awaited, or the browser blocks it.*/-function browserSignIn({ signal, keyLabel }: OpenRouterSignInOptions): OpenRouterSignIn {- let popup = window.open('', POPUP_NAME, POPUP_FEATURES)- let authorizationURL = ''- const reopen = () => {- if (authorizationURL) popup = window.open(authorizationURL, POPUP_NAME, POPUP_FEATURES) ?? popup- }- const result = settle(async () => {- if (!popup) return { ok: false, reason: 'blocked' }- const pkce = await createOpenRouterPKCE()- const callbackURL = new URL(OPENROUTER_CALLBACK_PATH, window.location.origin).href- authorizationURL = openRouterAuthorizationURL(callbackURL, pkce, keyLabel)- popup.location.href = authorizationURL- try {- return await finish(await browserCallback(signal), pkce, signal)- } finally {+function popupCallback(state: string): Promise<SignInCallback | { failure: 'blocked' }> {+ const opened = window.open('', POPUP_NAME, POPUP_FEATURES)+ if (!opened) return Promise.resolve({ failure: 'blocked' })+ let popup = opened+ let navigated = false+ const { received, stop } = pendingRedirect()+ const channel = new BroadcastChannel(OPENROUTER_CALLBACK_CHANNEL)+ channel.addEventListener('message', (event: MessageEvent<unknown>) => {+ if (typeof event.data === 'string') received.resolve(callbackOutcome(event.data, state))+ })+ return Promise.resolve({+ open: (url) => {+ if (navigated) popup = window.open(url, POPUP_NAME, POPUP_FEATURES) ?? popup+ else popup.location.href = url+ navigated = true+ },+ wait: () => received.promise,+ close: () => {+ stop()+ channel.close()popup.close()}})- return { reopen, result }}/**- * Listens for the `openpencil://oauth/openrouter` link the hosted callback page opens; the- * desktop shell forwards its query as an `oauth-callback` event.+ * The system browser, whose hosted callback page opens an `openpencil://oauth/openrouter` link;+ * the desktop shell forwards its query as an `oauth-callback` event.*/-async function listenForDesktopCallback() {+async function deepLinkCallback(state: string): Promise<SignInCallback> {const { listen } = await import('@tauri-apps/api/event')- const received = createDeferred<string | null>()- const timer = setTimeout(() => received.resolve(null), OPENROUTER_CODE_LIFETIME_MS)+ const { received, stop } = pendingRedirect()const unlisten = await listen<unknown>(OAUTH_CALLBACK_EVENT, (event) => {const callback = v.safeParse(oauthCallbackSchema, event.payload)if (callback.success && callback.output.provider === 'openrouter') {- received.resolve(callback.output.query)+ received.resolve(callbackOutcome(callback.output.query, state))}})return {- query: (signal: AbortSignal) => abortable(received.promise, signal),- stop: () => {- clearTimeout(timer)+ open: openExternalLink,+ wait: () => received.promise,+ close: () => {+ stop()unlisten()}}}-/** Opens OpenRouter in the system browser, which returns to the app through a deep link. */-function desktopSignIn({ signal, keyLabel }: OpenRouterSignInOptions): OpenRouterSignIn {- let authorizationURL = ''- const reopen = () => {- if (authorizationURL) void openExternalLink(authorizationURL)- }- const result = settle(async () => {- const [pkce, callback] = await Promise.all([createOpenRouterPKCE(), listenForDesktopCallback()])- try {- const callbackURL = new URL(OPENROUTER_DESKTOP_CALLBACK_PATH, WEB_APP_ORIGIN).href- authorizationURL = openRouterAuthorizationURL(callbackURL, pkce, keyLabel)- await openExternalLink(authorizationURL)- return await finish(await callback.query(signal), pkce, signal)- } finally {- callback.stop()- }- })- return { reopen, result }-}-/** Signs in to OpenRouter with OAuth PKCE and returns a new API key for this app. */-export function signInWithOpenRouter(options: OpenRouterSignInOptions): OpenRouterSignIn {- return IS_TAURI ? desktopSignIn(options) : browserSignIn(options)+export function signInWithOpenRouter({+ signal,+ keyLabel+}: OpenRouterSignInOptions): OpenRouterSignIn {+ const callbackURL = IS_TAURI+ ? new URL(OPENROUTER_DESKTOP_CALLBACK_PATH, WEB_APP_ORIGIN).href+ : new URL(OPENROUTER_CALLBACK_PATH, window.location.origin).href+ return startSignIn({+ signal,+ callback: IS_TAURI ? deepLinkCallback : popupCallback,+ authorizationURL: (pkce) => openRouterAuthorizationURL(callbackURL, pkce, keyLabel),+ exchange: (code, verifier) => exchangeOpenRouterCode(code, verifier)+ })}diff --git a/src/app/ai/providers/registry.ts b/src/app/ai/providers/registry.tsindex 7ecabf292..1a0bd6971 100644--- a/src/app/ai/providers/registry.ts+++ b/src/app/ai/providers/registry.ts@@ -4,6 +4,7 @@ import { createOpenRouter } from '@openrouter/ai-sdk-provider'import type { AIProviderID } from '@open-pencil/core/constants'+import { chatGPTAdapter } from '@/app/ai/providers/chatgpt/adapter'import {createAnthropicCompatibleAdapter,createOpenAICompatibleAdapter@@ -28,6 +29,7 @@ const MODEL_PROVIDER_ADAPTERS = {},anthropic: createAnthropicCompatibleAdapter(),openai: createOpenAICompatibleAdapter(),+ chatgpt: chatGPTAdapter,google: {create(config, runtime) {return createGoogleGenerativeAI({ apiKey: config.apiKey, fetch: runtime.fetch })(diff --git a/src/app/ai/providers/sign-in/attempt.ts b/src/app/ai/providers/sign-in/attempt.tsnew file mode 100644index 000000000..a11bad9ec--- /dev/null+++ b/src/app/ai/providers/sign-in/attempt.ts@@ -0,0 +1,110 @@+import { noop, once } from 'es-toolkit'++import { createDeferred } from '@/app/runtime/deferred'++import { pkceChallenge, pkceSecrets, type PKCE } from './pkce'++export type SignInFailure = 'cancelled' | 'expired' | 'failed'+export type SignInResult<T, F extends string = never> =+ | { ok: true; value: T }+ | { ok: false; reason: SignInFailure | F }++export interface SignIn<T, F extends string = never> {+ /** Opens the provider's sign-in page again for the same attempt. */+ reopen: () => void+ result: Promise<SignInResult<T, F>>+}++/** What came back to the redirect: a code for this attempt, or why there is none. */+export type CallbackOutcome =+ | { kind: 'code'; code: string }+ | { kind: 'denied' | 'mismatch' | 'expired' | 'cancelled' }++/** Where the redirect returns: a popup, a deep link, or a loopback port. */+export interface SignInCallback {+ /** Shows the sign-in page; called again to reopen it. */+ open: (url: string) => void | Promise<void>+ wait: () => Promise<CallbackOutcome>+ /** Releases the popup, listener, or port. */+ close: () => void+}++export interface SignInFlow<T, F extends string = never> {+ signal: AbortSignal+ /**+ * Readies the redirect before the page opens. It is called before anything is awaited, so it+ * can open a popup within the click that started sign-in.+ */+ callback: (state: string) => Promise<SignInCallback | { failure: F }>+ authorizationURL: (pkce: PKCE) => string+ exchange: (code: string, verifier: string) => Promise<T>+}++const OUTCOME_FAILURES = {+ denied: 'cancelled',+ cancelled: 'cancelled',+ mismatch: 'failed',+ expired: 'expired'+} as const satisfies Record<Exclude<CallbackOutcome['kind'], 'code'>, SignInFailure>++/** Reads a standard redirect query, rejecting one that belongs to another attempt. */+export function callbackOutcome(query: string, expectedState: string): CallbackOutcome {+ const params = new URLSearchParams(query)+ if (params.get('state') !== expectedState) return { kind: 'mismatch' }+ const code = params.get('code')+ return code ? { kind: 'code', code } : { kind: 'denied' }+}++class SignInAbortedError extends Error {+ constructor() {+ super('Sign-in was cancelled')+ this.name = 'SignInAbortedError'+ }+}++async function abortable<T>(promise: Promise<T>, signal: AbortSignal): Promise<T> {+ if (signal.aborted) throw new SignInAbortedError()+ const aborted = createDeferred<never>()+ const abort = () => aborted.reject(new SignInAbortedError())+ signal.addEventListener('abort', abort, { once: true })+ try {+ return await Promise.race([promise, aborted.promise])+ } finally {+ signal.removeEventListener('abort', abort)+ }+}++/** Signs in with OAuth PKCE: opens the provider, waits for its redirect, and trades the code. */+export function startSignIn<T, F extends string = never>(flow: SignInFlow<T, F>): SignIn<T, F> {+ const { signal } = flow+ const secrets = pkceSecrets()+ const preparing = flow.callback(secrets.state)+ let reopen: () => void = noop++ const result = (async (): Promise<SignInResult<T, F>> => {+ let close: () => void = noop+ try {+ const callback = await preparing+ if ('failure' in callback) return { ok: false, reason: callback.failure }+ // Closed as soon as the attempt is cancelled, before a new attempt can claim the same port.+ close = once(callback.close)+ signal.addEventListener('abort', close, { once: true })+ const pkce = { ...secrets, challenge: await pkceChallenge(secrets.verifier) }+ if (signal.aborted) return { ok: false, reason: 'cancelled' }+ const url = flow.authorizationURL(pkce)+ reopen = () => void callback.open(url)+ await callback.open(url)+ const outcome = await abortable(callback.wait(), signal)+ if (outcome.kind !== 'code') return { ok: false, reason: OUTCOME_FAILURES[outcome.kind] }+ const value = await abortable(flow.exchange(outcome.code, pkce.verifier), signal)+ return { ok: true, value }+ } catch {+ return { ok: false, reason: signal.aborted ? 'cancelled' : 'failed' }+ } finally {+ signal.removeEventListener('abort', close)+ close()+ }+ })()++ return { reopen: () => reopen(), result }+}diff --git a/src/app/ai/providers/sign-in/pkce.ts b/src/app/ai/providers/sign-in/pkce.tsnew file mode 100644index 000000000..5c624529e--- /dev/null+++ b/src/app/ai/providers/sign-in/pkce.ts@@ -0,0 +1,23 @@+import { fromUint8Array } from 'js-base64'++/** An OAuth PKCE pair and the state that ties a redirect to the attempt that started it. */+export interface PKCE {+ verifier: string+ challenge: string+ state: string+}++function randomToken(bytes: number): string {+ return fromUint8Array(crypto.getRandomValues(new Uint8Array(bytes)), true)+}++/** The S256 challenge for a verifier: the base64url SHA-256 digest, without padding. */+export async function pkceChallenge(verifier: string): Promise<string> {+ const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(verifier))+ return fromUint8Array(new Uint8Array(digest), true)+}++/** The secrets of a PKCE pair, drawn at once; only the challenge needs to wait for hashing. */+export function pkceSecrets(): Pick<PKCE, 'verifier' | 'state'> {+ return { verifier: randomToken(48), state: randomToken(16) }+}diff --git a/src/app/ai/providers/types.ts b/src/app/ai/providers/types.tsindex 0eb83641f..7ead1ff0e 100644--- a/src/app/ai/providers/types.ts+++ b/src/app/ai/providers/types.ts@@ -13,8 +13,16 @@ export type ModelConfig = {customAPIType: 'completions' | 'responses'}+/** The stored credential of the connection a model belongs to. */+export type ModelCredentialStore = {+ load: () => Promise<string | null>+ save: (value: string) => Promise<void>+}+export type ModelProviderRuntime = {fetch?: FetchFunction+ /** Lets a provider whose sign-in refreshes keep the new credential. */+ credentials?: ModelCredentialStore}export interface ModelProviderAdapter {diff --git a/src/components/ChatPanel.vue b/src/components/ChatPanel.vueindex a456bed37..6eefe8704 100644--- a/src/components/ChatPanel.vue+++ b/src/components/ChatPanel.vue@@ -142,12 +142,18 @@ const failureMessage = computed(() => {return ai.value.chatRateLimitedcase 'request-failed':return ai.value.chatRequestFailed+ case 'sign-in-expired':+ return ai.value.chatSignInExpired+ case 'plan-forbidden':+ return ai.value.chatPlanForbiddendefault:return null}})const failureHasSettingsAction = computed(() =>- ['authentication', 'forbidden', 'model-not-found'].includes(chatFailure.value?.reason ?? '')+ ['authentication', 'forbidden', 'model-not-found', 'sign-in-expired', 'plan-forbidden'].includes(+ chatFailure.value?.reason ?? ''+ ))const status = computed(() => chat.value?.status ?? 'ready')const showContinue = computed(() => {diff --git a/src/components/markdown/MarkdownContent.vue b/src/components/markdown/MarkdownContent.vueindex 82b87806b..df31c618c 100644--- a/src/components/markdown/MarkdownContent.vue+++ b/src/components/markdown/MarkdownContent.vue@@ -9,6 +9,7 @@ import { animationsEnabled } from '@/app/shell/motion'import { resolvedAppTheme } from '@/app/shell/theme'import InlineCode from '@/components/markdown/InlineCode.vue'import MarkdownTooltip from '@/components/markdown/MarkdownTooltip.vue'+import TaskCheckbox from '@/components/markdown/TaskCheckbox.vue'import { markdownTheme, type MarkdownDensity } from '@/theme/markdown'const {@@ -28,7 +29,7 @@ const {const isDark = computed(() => resolvedAppTheme.value === 'dark')const ui = markdownTheme()-const markdownComponents = { code: InlineCode }+const markdownComponents = { code: InlineCode, input: TaskCheckbox }// The renderer's own tooltip doubles up with ours and does not follow the app's style.const uiComponents = { Tooltip: MarkdownTooltip }// Copy is the one table action that fits a chat reply; images open in the attachment viewer.diff --git a/src/components/markdown/TaskCheckbox.vue b/src/components/markdown/TaskCheckbox.vuenew file mode 100644index 000000000..308249bc2--- /dev/null+++ b/src/components/markdown/TaskCheckbox.vue@@ -0,0 +1,32 @@+<script setup lang="ts">+import { computed } from 'vue'+import type { MarkdownComponentProps } from 'vue-stream-markdown'++import { useI18n } from '@open-pencil/vue/i18n'++const { node } = defineProps<MarkdownComponentProps>()+const { common } = useI18n()++/** The renderer passes a task item's checkbox as `["input", attributes]`, checked as a string. */+const checked = computed(() => {+ const attributes: unknown = Array.isArray(node) ? node[1] : undefined+ return (+ typeof attributes === 'object' &&+ attributes !== null &&+ ':checked' in attributes &&+ attributes[':checked'] === 'true'+ )+})+</script>++<template>+ <!-- A task list's checkbox shows a reply's state and cannot be changed; it still needs a name. -->+ <input+ data-stream-markdown="input"+ class="mr-2 align-middle task-list-item-checkbox"+ type="checkbox"+ disabled+ :checked="checked"+ :aria-label="common.task"+ />+</template>diff --git a/src/components/settings/ai-setup/AISetupAccess.vue b/src/components/settings/ai-setup/AISetupAccess.vueindex 7d241a2a1..a360603fb 100644--- a/src/components/settings/ai-setup/AISetupAccess.vue+++ b/src/components/settings/ai-setup/AISetupAccess.vue@@ -11,6 +11,7 @@ import {ONBOARDING_API_PROVIDERS,ONBOARDING_MORE_API_PROVIDERS,ONBOARDING_SERVER_PROVIDER,+ ONBOARDING_SUBSCRIPTIONS,type OnboardingAccess} from '@/app/ai/models/settings/onboarding/plan'import SettingsLink from '@/components/settings/layout/SettingsLink.vue'@@ -77,6 +78,19 @@ function toggle(providerID: OnboardingAccess, checked: boolean): void {</template></AppAlert></section>+ <section v-if="agentsAvailable" :class="styles.group()">+ <h3 :class="styles.groupHeading()">{{ ai.aiSetupAccessSubscriptions }}</h3>+ <AppCheckboxCard+ v-for="subscription in ONBOARDING_SUBSCRIPTIONS"+ :key="subscription"+ :label="modelProviderName(subscription)"+ :description="ai.aiSetupAccessChatGPT"+ :model-value="access.includes(subscription)"+ @update:model-value="toggle(subscription, $event)"+ >+ <template #icon><ProviderLogo :provider="subscription" /></template>+ </AppCheckboxCard>+ </section><section :class="styles.group()"><h3 :class="styles.groupHeading()">{{ ai.aiSetupAccessAPI }}</h3><AppCheckboxCarddiff --git a/src/components/settings/ai-setup/AISetupConnection.vue b/src/components/settings/ai-setup/AISetupConnection.vueindex 65c200a2c..1e5b6227b 100644--- a/src/components/settings/ai-setup/AISetupConnection.vue+++ b/src/components/settings/ai-setup/AISetupConnection.vue@@ -17,7 +17,10 @@ import {ONBOARDING_SERVER_PROVIDER,type OnboardingAccess} from '@/app/ai/models/settings/onboarding/plan'-import type { OnboardingSignInStatus } from '@/app/ai/models/settings/onboarding/sign-in'+import {+ isOnboardingSignInProvider,+ type OnboardingSignInStatus+} from '@/app/ai/models/settings/onboarding/sign-in'import AgentSetup from '@/components/settings/agents/AgentSetup.vue'import PiSetup from '@/components/settings/agents/PiSetup.vue'import ProviderConnectionTestButton from '@/components/settings/provider/ProviderConnectionTestButton.vue'@@ -85,7 +88,9 @@ const agent = computed(() =>)const provider = computed(() => AI_PROVIDERS.find((candidate) => candidate.id === providerID))const server = computed(() => providerID === ONBOARDING_SERVER_PROVIDER)-const supportsSignIn = computed(() => providerID === 'openrouter')+const signInProvider = computed(() => (isOnboardingSignInProvider(providerID) ? providerID : null))+/** The provider takes no pasted key; signing in is the only way to connect it. */+const signInOnly = computed(() => provider.value?.signInOnly === true)const serverPreset = computed(() => serverPresetFor(state.customBaseURL))const keyHint = computed(() => {@@ -122,8 +127,10 @@ const keyHint = computed(() => {<template v-else><p v-if="recommended" :class="styles.help()">{{ ai.aiSetupMeteredNote }}</p>+ <p v-if="providerID === 'chatgpt'" :class="styles.help()">{{ ai.aiSetupChatGPTUsage }}</p><AISetupSignIn- v-if="supportsSignIn"+ v-if="signInProvider"+ :provider="signInProvider":account="state.account":status="signInStatus":disabled="disabled"@@ -139,8 +146,11 @@ const keyHint = computed(() => {@update="emit('update', $event)"@vision="emit('serverVision', $event)"/>+ <p v-if="signInOnly && hasSavedKey && !state.account" :class="styles.help()">+ {{ ai.aiSetupSavedSignInHint }}+ </p><ProviderSettingsKeyField- v-if="!state.account"+ v-if="!state.account && !signInOnly":model-value="state.apiKey":label="ai.apiKey":saved="false"@@ -152,7 +162,7 @@ const keyHint = computed(() => {@update:model-value="emit('update', { apiKey: $event })"/><ProviderConnectionTestButton- v-if="!state.account"+ v-if="!state.account && !signInOnly":status="state.test":reason="state.reason":disabled="disabled"diff --git a/src/components/settings/ai-setup/AISetupSignIn.vue b/src/components/settings/ai-setup/AISetupSignIn.vueindex 9c7d78fa3..85a3ef243 100644--- a/src/components/settings/ai-setup/AISetupSignIn.vue+++ b/src/components/settings/ai-setup/AISetupSignIn.vue@@ -5,17 +5,25 @@ import { computed } from 'vue'import { useI18n } from '@open-pencil/vue/i18n'import type { OnboardingConnectionState } from '@/app/ai/models/settings/onboarding/connections'-import type { OnboardingSignInStatus } from '@/app/ai/models/settings/onboarding/sign-in'+import type {+ OnboardingSignInProvider,+ OnboardingSignInStatus+} from '@/app/ai/models/settings/onboarding/sign-in'import AppButton from '@/components/ui/button/AppButton.vue'import AppAlert from '@/components/ui/feedback/AppAlert.vue'import theme from '@/theme/settings/ai-setup/flow'-/** Signing in to OpenRouter instead of pasting a key, and the account it signed in to. */+/**+ * Signing in to a provider, and the account it signed in to. OpenRouter's sign-in creates a key+ * that could also be pasted; ChatGPT has no key, so the sign-in is the only way to connect.+ */const {+ provider,account,status = 'idle',disabled = false} = defineProps<{+ provider: OnboardingSignInProvideraccount: OnboardingConnectionState['account']status?: OnboardingSignInStatusdisabled?: boolean@@ -24,11 +32,39 @@ const emit = defineEmits<{ signIn: []; reopen: []; cancel: []; signOut: [] }>()const { ai, common } = useI18n()const styles = tv(theme)()+const text = computed(() =>+ provider === 'chatgpt'+ ? {+ signIn: ai.value.aiSetupChatGPTSignIn,+ waiting: ai.value.aiSetupChatGPTWaiting,+ // The account is read from the tokens the sign-in returned, so nothing is left to check.+ verifying: ai.value.aiSetupChatGPTWaiting,+ signedIn: ai.value.aiSetupChatGPTSignedInTitle,+ failed: ai.value.aiSetupChatGPTFailed+ }+ : {+ signIn: ai.value.aiSetupOpenRouterSignIn,+ waiting: ai.value.aiSetupOpenRouterWaiting,+ verifying: ai.value.aiSetupOpenRouterVerifying,+ signedIn: ai.value.aiSetupOpenRouterSignedInTitle,+ failed: ai.value.aiSetupOpenRouterFailed+ }+)++const detail = computed(() => {+ if (account?.provider === 'chatgpt') return account.email+ if (account?.provider === 'openrouter' && account.label) {+ return ai.value.aiSetupOpenRouterKeyLabel({ label: account.label })+ }+ return undefined+})+const failure = computed(() => {if (status === 'blocked') return ai.value.aiSetupOpenRouterBlocked- if (status === 'cancelled') return ai.value.aiSetupOpenRouterCancelled- if (status === 'expired') return ai.value.aiSetupOpenRouterExpired- if (status === 'failed') return ai.value.aiSetupOpenRouterFailed+ if (status === 'cancelled') return ai.value.aiSetupSignInCancelled+ if (status === 'expired') return ai.value.aiSetupSignInExpired+ if (status === 'port-in-use') return ai.value.aiSetupChatGPTPortInUse+ if (status === 'failed') return text.value.failedreturn null})</script>@@ -39,25 +75,27 @@ const failure = computed(() => {<p role="status" :class="styles.signInStatus()"><icon-lucide-circle-check :class="styles.signedInIcon()" aria-hidden="true" /><span>- {{ ai.aiSetupOpenRouterSignedInTitle }}- <span v-if="account.label" :class="styles.signInDetail()">- {{ ai.aiSetupOpenRouterKeyLabel({ label: account.label }) }}- </span>+ {{ text.signedIn }}+ <span v-if="detail" :class="styles.signInDetail()">{{ detail }}</span></span></p>- <AppButton size="xs" @click="emit('signOut')">{{ ai.aiSetupOpenRouterChange }}</AppButton>+ <AppButton size="xs" @click="emit('signOut')">{{ ai.aiSetupSignInChange }}</AppButton></div>- <AppAlert v-if="account.freeTier" tone="warning" :heading="ai.aiSetupOpenRouterNoCredits" />+ <AppAlert+ v-if="account.provider === 'openrouter' && account.freeTier"+ tone="warning"+ :heading="ai.aiSetupOpenRouterNoCredits"+ /></template><template v-else><div v-if="status === 'waiting' || status === 'verifying'" :class="styles.signIn()"><p role="status" :class="styles.signInStatus()"><icon-lucide-loader-2 :class="styles.spinner()" aria-hidden="true" />- {{ status === 'waiting' ? ai.aiSetupOpenRouterWaiting : ai.aiSetupOpenRouterVerifying }}+ {{ status === 'waiting' ? text.waiting : text.verifying }}</p><div :class="styles.signInActions()"><AppButton v-if="status === 'waiting'" size="xs" variant="outline" @click="emit('reopen')">- {{ ai.aiSetupOpenRouterReopen }}+ {{ ai.aiSetupSignInReopen }}</AppButton><AppButton size="xs" @click="emit('cancel')">{{ common.cancel }}</AppButton></div>@@ -70,9 +108,11 @@ const failure = computed(() => {:disabled="disabled"@click="emit('signIn')">- {{ ai.aiSetupOpenRouterSignIn }}+ {{ text.signIn }}</AppButton><AppAlert v-if="failure" tone="warning" :heading="failure" />- <p :class="styles.groupHeading()">{{ ai.aiSetupOpenRouterOrKey }}</p>+ <p v-if="provider === 'openrouter'" :class="styles.groupHeading()">+ {{ ai.aiSetupOpenRouterOrKey }}+ </p></template></template>diff --git a/src/components/settings/mcp/MCPFailureAlert.stories.ts b/src/components/settings/mcp/MCPFailureAlert.stories.tsindex c558b64f1..3476e112e 100644--- a/src/components/settings/mcp/MCPFailureAlert.stories.ts+++ b/src/components/settings/mcp/MCPFailureAlert.stories.ts@@ -86,7 +86,7 @@ export const Outdated: Story = {const canvas = within(canvasElement)await expect(canvas.getByText(/The installed MCP server is v0\.15\.1/)).toBeVisible()await expect(canvas.getByRole('button', { name: 'Update MCP server' })).toBeVisible()- await expect(canvas.queryByTestId('settings-mcp-install-command')).toBeNull()+ await expect(canvas.queryByText(/npm (?:i|install) -g @open-pencil\/mcp/)).toBeNull()await expect(canvas.queryByRole('button', { name: 'Copy prompt for your agent' })).toBeNull()// Updating restarts the server, so Restart is not offered beside it.await expect(canvas.queryByRole('button', { name: 'Restart MCP server' })).toBeNull()@@ -109,7 +109,7 @@ export const NeedsNode: Story = {const canvas = within(canvasElement)await expect(canvas.queryByRole('button', { name: 'Install MCP server' })).toBeNull()await expect(canvas.getByRole('link', { name: 'Node.js' })).toBeVisible()- await expect(canvas.getByTestId('settings-mcp-install-command')).toBeVisible()+ await expect(canvas.getByText(/npm (?:i|install) -g @open-pencil\/mcp/)).toBeVisible()await expect(canvas.getByRole('button', { name: 'Copy prompt for your agent' })).toBeVisible()await expect(canvas.getByRole('button', { name: 'Check again' })).toBeVisible()}diff --git a/src/components/settings/models/ProfileEditor.vue b/src/components/settings/models/ProfileEditor.vueindex 23e72c24b..367c6e8e2 100644--- a/src/components/settings/models/ProfileEditor.vue+++ b/src/components/settings/models/ProfileEditor.vue@@ -6,6 +6,7 @@ import { useI18n } from '@open-pencil/vue/i18n'import { usePiSetup } from '@/app/ai/agents/setup/use'import { useModelProfileFeedback } from '@/app/ai/models/settings/profile-editor/feedback'+import { useProfileSignIn } from '@/app/ai/models/settings/profile-editor/sign-in'import { useModelProfileEditor } from '@/app/ai/models/settings/profile-editor/use'import { thinkingLevelOptions as buildThinkingLevelOptions } from '@/app/ai/models/thinking'import { useSettingsFormGuard } from '@/app/settings/navigation/use'@@ -15,6 +16,7 @@ import SettingsPage from '@/components/settings/layout/SettingsPage.vue'import SettingsSaveFeedback from '@/components/settings/layout/SettingsSaveFeedback.vue'import SettingsSection from '@/components/settings/layout/SettingsSection.vue'import ProviderSelect from '@/components/settings/provider-select/ProviderSelect.vue'+import ChatGPTSignInField from '@/components/settings/provider/ChatGPTSignInField.vue'import ProviderConnectionTestButton from '@/components/settings/provider/ProviderConnectionTestButton.vue'import ProviderSettingsField from '@/components/settings/provider/ProviderSettingsField.vue'import ProviderSettingsInput from '@/components/settings/provider/ProviderSettingsInput.vue'@@ -61,6 +63,7 @@ const {testConnection: runConnectionTest} = profileconst pi = usePiSetup(isHarness)+const signIn = useProfileSignIn(keyInput)const customModelPlaceholder = computed(() =>isHarness.value ? (pi.state.value?.defaultModel ?? 'provider/model') : 'e.g. llama-3.3-70b')@@ -72,6 +75,8 @@ useSettingsFormGuard({ dirty, busy, cancel: () => emit('done') })const CUSTOM_MODEL_VALUE = '__custom__'const advancedOpen = ref(Boolean(draft.customModelID.trim()))function updateProvider(id: AIProviderID) {+ // A sign-in still waiting must not land in another provider's key.+ signIn.cancel()profile.updateProvider(id)advancedOpen.value = id === 'harness:pi'}@@ -232,7 +237,20 @@ async function remove() {/></ProviderSettingsField>+ <ChatGPTSignInField+ v-if="providerDef.signInOnly"+ :saved="hasExistingKey"+ :signed-in="signIn.signedIn.value"+ :email="signIn.email.value"+ :status="signIn.status.value"+ :disabled="busy"+ @sign-in="signIn.signIn()"+ @reopen="signIn.reopen()"+ @cancel="signIn.cancel()"+ @sign-out="clearKey"+ /><ProviderSettingsKeyField+ v-elsev-model="keyInput":label="ai.apiKey":saved="hasExistingKey"diff --git a/src/components/settings/provider-select/ProviderSelect.vue b/src/components/settings/provider-select/ProviderSelect.vueindex 82bfba8cb..5307dfa19 100644--- a/src/components/settings/provider-select/ProviderSelect.vue+++ b/src/components/settings/provider-select/ProviderSelect.vue@@ -89,7 +89,8 @@ const groups = computed(() => {result.push({label: acpAgents.value.length ? ai.value.providerGroupProviders : undefined,- options: [...AI_PROVIDERS]+ // Signing in returns to a port on this computer, which only the desktop app can open.+ options: AI_PROVIDERS.filter((provider) => IS_TAURI || !provider.signInOnly).sort((left, right) => left.name.localeCompare(right.name)).map((provider) => ({value: provider.id,diff --git a/src/components/settings/provider/ChatGPTSignInField.vue b/src/components/settings/provider/ChatGPTSignInField.vuenew file mode 100644index 000000000..183ccf2ae--- /dev/null+++ b/src/components/settings/provider/ChatGPTSignInField.vue@@ -0,0 +1,74 @@+<script setup lang="ts">+import { computed } from 'vue'++import { useI18n } from '@open-pencil/vue/i18n'++import type { ProfileSignInStatus } from '@/app/ai/models/settings/profile-editor/sign-in'+import AppButton from '@/components/ui/button/AppButton.vue'+import AppAlert from '@/components/ui/feedback/AppAlert.vue'++/** A ChatGPT connection's credential: a sign-in saved earlier, one made now, or none. */+const {+ saved,+ signedIn,+ email,+ status = 'idle',+ disabled = false+} = defineProps<{+ saved: boolean+ signedIn: boolean+ email?: string+ status?: ProfileSignInStatus+ disabled?: boolean+}>()+const emit = defineEmits<{ signIn: []; reopen: []; cancel: []; signOut: [] }>()+const { ai, common } = useI18n()++const failure = computed(() => {+ if (status === 'cancelled') return ai.value.aiSetupSignInCancelled+ if (status === 'expired') return ai.value.aiSetupSignInExpired+ if (status === 'port-in-use') return ai.value.aiSetupChatGPTPortInUse+ if (status === 'failed') return ai.value.aiSetupChatGPTFailed+ return null+})+</script>++<template>+ <div class="flex flex-col gap-2" data-test-id="settings-chatgpt-sign-in">+ <p class="text-[10px] text-muted">{{ ai.aiSetupChatGPTUsage }}</p>+ <div v-if="status === 'waiting'" class="flex flex-wrap items-center gap-2">+ <p role="status" class="flex items-center gap-1.5 text-[11px] text-muted">+ <icon-lucide-loader-2 class="size-3.5 animate-spin" aria-hidden="true" />+ {{ ai.aiSetupChatGPTWaiting }}+ </p>+ <AppButton class="ml-auto" size="xs" variant="outline" @click="emit('reopen')">+ {{ ai.aiSetupSignInReopen }}+ </AppButton>+ <AppButton size="xs" @click="emit('cancel')">{{ common.cancel }}</AppButton>+ </div>+ <div v-else-if="signedIn || saved" class="flex flex-wrap items-center gap-2">+ <p role="status" class="flex items-center gap-1.5 text-[11px] text-surface">+ <icon-lucide-circle-check class="size-3.5 text-success" aria-hidden="true" />+ {{ ai.aiSetupChatGPTSignedInTitle }}+ <span v-if="email" class="text-muted">{{ email }}</span>+ </p>+ <AppButton class="ml-auto" size="xs" :disabled="disabled" @click="emit('signIn')">+ {{ ai.aiSetupSignInChange }}+ </AppButton>+ <AppButton size="xs" :disabled="disabled" @click="emit('signOut')">+ {{ ai.aiSetupSignOut }}+ </AppButton>+ </div>+ <AppButton+ v-else+ class="self-start"+ color="primary"+ variant="solid"+ :disabled="disabled"+ @click="emit('signIn')"+ >+ {{ ai.aiSetupChatGPTSignIn }}+ </AppButton>+ <AppAlert v-if="failure" tone="warning" :heading="failure" />+ </div>+</template>diff --git a/src/components/settings/provider/ProviderConnectionTestButton.vue b/src/components/settings/provider/ProviderConnectionTestButton.vueindex 07b9b10e7..2db1907a7 100644--- a/src/components/settings/provider/ProviderConnectionTestButton.vue+++ b/src/components/settings/provider/ProviderConnectionTestButton.vue@@ -25,6 +25,8 @@ const resultMessage = computed(() => {switch (reason) {case 'missing-api-key':return ai.value.connectionTestMissingAPIKey+ case 'missing-sign-in':+ return ai.value.connectionTestMissingSignIncase 'missing-base-url':return ai.value.connectionTestMissingBaseURLcase 'missing-model':@@ -33,6 +35,10 @@ const resultMessage = computed(() => {return ai.value.connectionTestInvalidBaseURLcase 'auth':return ai.value.connectionTestAuthFailed+ case 'sign-in-expired':+ return ai.value.connectionTestSignInExpired+ case 'plan-forbidden':+ return ai.value.connectionTestPlanForbiddencase 'insufficient-credit':return ai.value.connectionTestInsufficientCreditcase 'model-not-found':diff --git a/src/components/settings/provider/ProviderLogo.vue b/src/components/settings/provider/ProviderLogo.vueindex 350e22094..10dcddf5e 100644--- a/src/components/settings/provider/ProviderLogo.vue+++ b/src/components/settings/provider/ProviderLogo.vue@@ -22,6 +22,7 @@ const { provider } = defineProps<{ provider: string }>()const LOGOS: Record<string, Component> = {anthropic: IconAnthropic,openai: IconOpenAI,+ chatgpt: IconOpenAI,google: IconGemini,openrouter: IconOpenRouter,deepseek: IconDeepSeek,diff --git a/tests/app/ai/models/settings/onboarding/plan.test.ts b/tests/app/ai/models/settings/onboarding/plan.test.tsindex 4f779f0c7..408e498b1 100644--- a/tests/app/ai/models/settings/onboarding/plan.test.ts+++ b/tests/app/ai/models/settings/onboarding/plan.test.ts@@ -45,6 +45,38 @@ describe('planOnboarding', () => {expect(plan.design).toMatchObject({ providerID: 'openai', modelID: defaultModel('openai') })})+ test('prefers a ChatGPT plan over an API account for every role', () => {+ const plan = planOnboarding(+ answers({ goals: ['design', 'vision'], access: ['openai', 'chatgpt'] }),+ desktop+ )+ expect(plan.design).toMatchObject({ providerID: 'chatgpt', modelID: defaultModel('chatgpt') })+ expect(plan.vision).toBe('design')+ expect(plan.connections).toEqual(['chatgpt', 'openai'])+ })++ test('takes visual review from a ChatGPT plan when design runs on an agent', () => {+ const plan = planOnboarding(+ answers({ goals: ['design', 'vision'], access: ['acp:claude-code', 'chatgpt', 'openai'] }),+ desktop+ )+ expect(plan.vision).toMatchObject({ providerID: 'chatgpt' })+ })++ test('connects a selected ChatGPT plan that no planned model needs', () => {+ const plan = planOnboarding(answers({ access: ['acp:claude-code', 'chatgpt'] }), desktop)+ expect(plan.design).toMatchObject({ providerID: 'acp:claude-code' })+ expect(plan.connections).toEqual(['acp:claude-code', 'chatgpt'])+ expect(roleOptions('design', plan, []).map(roleChoiceKey)).toContain(+ `chatgpt::${defaultModel('chatgpt')}`+ )+ })++ test('ignores ChatGPT sign-in outside the desktop app', () => {+ const plan = planOnboarding(answers({ access: ['chatgpt', 'openai'] }), browser)+ expect(plan.design).toMatchObject({ providerID: 'openai' })+ })+test('reuses a vision-capable design model for visual review', () => {const plan = planOnboarding(answers({ goals: ['design', 'vision'], access: ['anthropic'] }),diff --git a/tests/app/ai/providers/chatgpt/adapter.test.ts b/tests/app/ai/providers/chatgpt/adapter.test.tsnew file mode 100644index 000000000..dd8ecb14a--- /dev/null+++ b/tests/app/ai/providers/chatgpt/adapter.test.ts@@ -0,0 +1,76 @@+import { describe, expect, test } from 'bun:test'++import { generateText } from 'ai'+import * as v from 'valibot'++import { chatGPTAdapter } from '@/app/ai/providers/chatgpt/adapter'+import { serializeChatGPTCredential } from '@/app/ai/providers/chatgpt/credential'++import { credential } from '#tests/helpers/ai/chatgpt'++const completed = (text: string) =>+ `data: ${JSON.stringify({+ type: 'response.completed',+ response: {+ id: 'resp_1',+ created_at: 0,+ model: 'gpt-6-luna',+ output: [+ { type: 'reasoning', id: 'rs_1', encrypted_content: 'sealed-1', summary: [] },+ {+ type: 'message',+ id: 'msg_1',+ role: 'assistant',+ content: [{ type: 'output_text', text, annotations: [] }]+ }+ ],+ usage: { input_tokens: 1, output_tokens: 1 }+ }+ })}\n\n`++const bodySchema = v.looseObject({ input: v.array(v.looseObject({})) })++describe('ChatGPT adapter', () => {+ test('sends an earlier reply and its sealed reasoning whole, since the backend keeps no items', async () => {+ const inputs: unknown[][] = []+ const key = serializeChatGPTCredential(credential())+ const model = chatGPTAdapter.create(+ {+ providerID: 'chatgpt',+ apiKey: key,+ modelID: 'gpt-6-luna',+ customModelID: '',+ customBaseURL: '',+ customAPIType: 'responses'+ },+ {+ fetch: async (_input, init) => {+ const body = v.parse(+ v.pipe(v.string(), v.parseJson(), bodySchema),+ typeof init?.body === 'string' ? init.body : ''+ )+ inputs.push(body.input)+ return new Response(completed('Hi'), {+ headers: { 'content-type': 'text/event-stream' }+ })+ }+ }+ )++ const first = await generateText({ model, prompt: 'hi' })+ await generateText({+ model,+ messages: [+ { role: 'user', content: 'hi' },+ ...first.response.messages,+ { role: 'user', content: 'bye' }+ ]+ })++ expect(inputs[1]).toContainEqual(expect.objectContaining({ role: 'assistant' }))+ expect(inputs[1]).toContainEqual(+ expect.objectContaining({ type: 'reasoning', encrypted_content: 'sealed-1' })+ )+ expect(inputs[1]).not.toContainEqual(expect.objectContaining({ type: 'item_reference' }))+ })+})diff --git a/tests/app/ai/providers/chatgpt/catalog.test.ts b/tests/app/ai/providers/chatgpt/catalog.test.tsnew file mode 100644index 000000000..4850b6c09--- /dev/null+++ b/tests/app/ai/providers/chatgpt/catalog.test.ts@@ -0,0 +1,45 @@+import { describe, expect, test } from 'bun:test'++import { normalizeChatGPTModels } from '@/app/ai/providers/chatgpt/catalog'++describe('ChatGPT model catalog', () => {+ test('lists the account’s visible models by priority with their lowest reasoning level', () => {+ const models = normalizeChatGPTModels([+ {+ slug: 'gpt-6-luna',+ display_name: 'GPT-6-Luna',+ visibility: 'list',+ priority: 5,+ input_modalities: ['text'],+ supported_reasoning_levels: [{ effort: 'medium' }, { effort: 'high' }]+ },+ { slug: 'codex-auto-review', visibility: 'hide', priority: 0 },+ {+ slug: 'gpt-6.1-sol',+ display_name: 'GPT-6.1-Sol',+ visibility: 'list',+ priority: 1,+ input_modalities: ['text', 'image'],+ supported_reasoning_levels: [{ effort: 'low' }, { effort: 'xhigh' }]+ },+ { slug: 'gpt-next', visibility: 'list' },+ { display_name: 'No slug', visibility: 'list' },+ 'not a model'+ ])+ expect(models).toEqual([+ {+ id: 'gpt-6.1-sol',+ name: 'GPT-6.1-Sol',+ capabilities: ['tools', 'vision'],+ minReasoningEffort: 'low'+ },+ {+ id: 'gpt-6-luna',+ name: 'GPT-6-Luna',+ capabilities: ['tools'],+ minReasoningEffort: 'medium'+ },+ { id: 'gpt-next', name: 'gpt-next', capabilities: ['tools'] }+ ])+ })+})diff --git a/tests/app/ai/providers/chatgpt/fetch.test.ts b/tests/app/ai/providers/chatgpt/fetch.test.tsnew file mode 100644index 000000000..42193bf26--- /dev/null+++ b/tests/app/ai/providers/chatgpt/fetch.test.ts@@ -0,0 +1,238 @@+import { describe, expect, test } from 'bun:test'++import type { ChatGPTCredential } from '@/app/ai/providers/chatgpt/credential'+import {+ ChatGPTSignInExpiredError,+ codexRequestBody,+ completedResponse,+ createCodexFetch+} from '@/app/ai/providers/chatgpt/fetch'+import { CHATGPT_TOKEN_URL, ChatGPTTokenError } from '@/app/ai/providers/chatgpt/oauth'++import { accessToken, credential, tokenResponse } from '#tests/helpers/ai/chatgpt'++const RESPONSES_URL = 'https://chatgpt.com/backend-api/codex/responses'++interface Sent {+ url: string+ headers: Headers+ body: string+}++/** Answers token refreshes with a new pair and every other request with `answer`. */+function backend(answer: (sent: Sent) => Response) {+ const sent: Sent[] = []+ const refreshes: string[] = []+ const fetchImpl = async (input: RequestInfo | URL, init?: RequestInit) => {+ const url = String(input)+ const body = typeof init?.body === 'string' ? init.body : ''+ if (url === CHATGPT_TOKEN_URL) {+ refreshes.push(new URLSearchParams(body).get('refresh_token') ?? '')+ return tokenResponse({+ access_token: accessToken,+ refresh_token: `refresh-${refreshes.length + 1}`,+ expires_in: 3600+ })+ }+ const request = { url, headers: new Headers(init?.headers), body }+ sent.push(request)+ return answer(request)+ }+ return { sent, refreshes, fetchImpl }+}++const ok = () => new Response('data: {}\n\n', { headers: { 'content-type': 'text/event-stream' } })++function streamingRequest(fetch: ReturnType<typeof createCodexFetch>, extra = {}) {+ return fetch(RESPONSES_URL, {+ method: 'POST',+ headers: { authorization: 'Bearer chatgpt' },+ body: JSON.stringify({ model: 'gpt-6-luna', stream: true, input: [], ...extra })+ })+}++describe('Codex request body', () => {+ test('streams without storing, keeps reasoning, and moves tools into a developer item', () => {+ const tool = { type: 'function', name: 'set_fill', parameters: {} }+ const body = codexRequestBody(+ {+ model: 'gpt-6-luna',+ stream: false,+ max_output_tokens: 1,+ reasoning: { effort: 'low' },+ tools: [tool],+ input: [+ { role: 'system', content: 'Be terse.' },+ { role: 'user', content: [{ type: 'input_text', text: 'Hi' }] }+ ]+ },+ 'cache-1'+ )+ expect(body).toEqual({+ model: 'gpt-6-luna',+ stream: true,+ store: false,+ include: ['reasoning.encrypted_content'],+ prompt_cache_key: 'cache-1',+ parallel_tool_calls: false,+ reasoning: { effort: 'low', context: 'all_turns' },+ input: [+ {+ type: 'additional_tools',+ role: 'developer',+ tools: [{ type: 'namespace', name: 'functions', description: '', tools: [tool] }]+ },+ { role: 'developer', content: 'Be terse.' },+ { role: 'user', content: [{ type: 'input_text', text: 'Hi' }] }+ ]+ })+ })++ test('adds no tool item when the request has no tools', () => {+ const body = codexRequestBody({ include: ['reasoning.encrypted_content'], input: [] })+ expect(body.input).toEqual([])+ expect(body.include).toEqual(['reasoning.encrypted_content'])+ expect(body).not.toHaveProperty('prompt_cache_key')+ })++ test('collapses an event stream into its completed response', () => {+ const stream = [+ 'event: response.created',+ 'data: {"type":"response.created"}',+ '',+ 'data: not json',+ 'data: {"type":"response.completed","response":{"id":"r1","output":[]}}',+ ''+ ].join('\n')+ expect(completedResponse(stream)).toEqual({ id: 'r1', output: [] })+ expect(completedResponse('data: {"type":"response.created"}\n')).toBeUndefined()+ })+})++describe('Codex fetch', () => {+ test('signs Responses requests with the account and the Codex headers', async () => {+ const server = backend(ok)+ await streamingRequest(createCodexFetch({ credential: credential(), fetch: server.fetchImpl }))+ const headers = server.sent[0]?.headers+ expect(headers?.get('authorization')).toBe('Bearer access-1')+ expect(headers?.get('chatgpt-account-id')).toBe('acct-1')+ expect(headers?.get('originator')).toBe('open-pencil')+ expect(headers?.get('openai-beta')).toBe('responses=experimental')+ expect(headers?.get('x-openai-internal-codex-responses-lite')).toBe('true')+ expect(server.refreshes).toEqual([])+ })++ test('signs other requests without the Responses headers', async () => {+ const server = backend(() => new Response('{"models":[]}'))+ const fetch = createCodexFetch({ credential: credential(), fetch: server.fetchImpl })+ await fetch('https://chatgpt.com/backend-api/codex/models?client_version=1')+ const headers = server.sent[0]?.headers+ expect(headers?.get('authorization')).toBe('Bearer access-1')+ expect(headers?.get('accept')).toBeNull()+ expect(headers?.get('x-openai-internal-codex-responses-lite')).toBeNull()+ })++ test('answers a non-streaming caller with the completed response', async () => {+ const server = backend(+ () =>+ new Response('data: {"type":"response.completed","response":{"id":"r1"}}\n\n', {+ headers: { 'content-type': 'text/event-stream' }+ })+ )+ const fetch = createCodexFetch({ credential: credential(), fetch: server.fetchImpl })+ const response = await streamingRequest(fetch, { stream: false })+ expect(JSON.parse(server.sent[0]?.body ?? '{}')).toMatchObject({ stream: true })+ expect(await response.json()).toEqual({ id: 'r1' })+ })++ test('refreshes a sign-in about to expire and saves the new tokens first', async () => {+ const saved: ChatGPTCredential[] = []+ const server = backend(ok)+ const fetch = createCodexFetch({+ credential: credential({ expires: Date.now() + 1000 }),+ fetch: server.fetchImpl,+ save: async (next) => {+ saved.push(next)+ }+ })+ await streamingRequest(fetch)+ expect(server.refreshes).toEqual(['refresh-1'])+ expect(saved.map((next) => next.refresh)).toEqual(['refresh-2'])+ expect(server.sent[0]?.headers.get('authorization')).toBe(`Bearer ${accessToken}`)+ })++ test('refreshes once and retries when the backend rejects the token', async () => {+ const server = backend((sent) =>+ sent.headers.get('authorization') === 'Bearer access-1'+ ? new Response('', { status: 401 })+ : ok()+ )+ const fetch = createCodexFetch({ credential: credential(), fetch: server.fetchImpl })+ const response = await streamingRequest(fetch)+ expect(response.status).toBe(200)+ expect(server.refreshes).toEqual(['refresh-1'])+ expect(server.sent).toHaveLength(2)+ })++ test('spends a refresh token once when models sharing a sign-in refresh together', async () => {+ const server = backend(ok)+ const stale = credential({ refresh: 'shared-refresh', expires: 0 })+ const first = createCodexFetch({ credential: stale, fetch: server.fetchImpl })+ const second = createCodexFetch({ credential: stale, fetch: server.fetchImpl })+ await Promise.all([streamingRequest(first), streamingRequest(second)])+ expect(server.refreshes).toEqual(['shared-refresh'])+ })++ test('takes a stored sign-in another model already refreshed', async () => {+ const server = backend(ok)+ const fetch = createCodexFetch({+ credential: credential({ expires: 0 }),+ fetch: server.fetchImpl,+ load: async () => credential({ access: 'access-2', refresh: 'refresh-2' })+ })+ await streamingRequest(fetch)+ expect(server.refreshes).toEqual([])+ expect(server.sent[0]?.headers.get('authorization')).toBe('Bearer access-2')+ })++ test('reports an expired sign-in when the refresh is refused', async () => {+ const fetch = createCodexFetch({+ credential: credential({ expires: 0 }),+ fetch: async () => new Response('', { status: 400 })+ })+ await expect(streamingRequest(fetch)).rejects.toBeInstanceOf(ChatGPTSignInExpiredError)+ })++ test('reports an expired sign-in only when the refresh token is refused', async () => {+ // The body auth.openai.com sends for an unknown refresh token.+ const revoked = createCodexFetch({+ credential: credential({ expires: 0, refresh: 'refresh-revoked' }),+ fetch: async () =>+ Response.json(+ { error: { type: 'invalid_request_error', code: 'invalid_refresh_token' } },+ { status: 401 }+ )+ })+ await expect(streamingRequest(revoked)).rejects.toBeInstanceOf(ChatGPTSignInExpiredError)++ const reused = createCodexFetch({+ credential: credential({ expires: 0, refresh: 'refresh-reused' }),+ fetch: async () => Response.json({ error: { code: 'refresh_token_reused' } }, { status: 400 })+ })+ await expect(streamingRequest(reused)).rejects.toBeInstanceOf(ChatGPTSignInExpiredError)++ const malformed = createCodexFetch({+ credential: credential({ expires: 0, refresh: 'refresh-malformed' }),+ fetch: async () => Response.json({ error: 'invalid_request' }, { status: 400 })+ })+ await expect(streamingRequest(malformed)).rejects.toBeInstanceOf(ChatGPTTokenError)+ })++ test('keeps the sign-in when the auth server fails to refresh it', async () => {+ const fetch = createCodexFetch({+ credential: credential({ expires: 0, refresh: 'refresh-busy' }),+ fetch: async () => new Response('', { status: 503 })+ })+ await expect(streamingRequest(fetch)).rejects.toBeInstanceOf(ChatGPTTokenError)+ })+})diff --git a/tests/app/ai/providers/chatgpt/oauth.test.ts b/tests/app/ai/providers/chatgpt/oauth.test.tsnew file mode 100644index 000000000..e3281edb0--- /dev/null+++ b/tests/app/ai/providers/chatgpt/oauth.test.ts@@ -0,0 +1,119 @@+import { describe, expect, test } from 'bun:test'++import {+ chatGPTAccount,+ chatGPTAuthorizationURL,+ ChatGPTTokenError,+ CHATGPT_TOKEN_URL,+ exchangeChatGPTCode,+ refreshChatGPTCredential+} from '@/app/ai/providers/chatgpt/oauth'++import { accessToken, idToken, jwt, tokenResponse } from '#tests/helpers/ai/chatgpt'++describe('ChatGPT OAuth', () => {+ test('builds the Codex authorization URL with the challenge and state', () => {+ const url = new URL(chatGPTAuthorizationURL({ verifier: 'v', challenge: 'c', state: 's' }))+ expect(url.origin + url.pathname).toBe('https://auth.openai.com/oauth/authorize')+ expect(Object.fromEntries(url.searchParams)).toEqual({+ response_type: 'code',+ client_id: 'app_EMoamEEZ73f0CkXaXp7hrann',+ redirect_uri: 'http://localhost:1455/auth/callback',+ scope: 'openid profile email offline_access',+ code_challenge: 'c',+ code_challenge_method: 'S256',+ state: 's',+ id_token_add_organizations: 'true',+ codex_cli_simplified_flow: 'true',+ originator: 'open-pencil'+ })+ })++ test('reads the account from the access token and the email and plan from the ID token', () => {+ expect(chatGPTAccount(accessToken, idToken)).toEqual({+ accountId: 'acct-1',+ email: '[email protected]',+ plan: 'plus'+ })+ expect(chatGPTAccount(accessToken)).toEqual({+ accountId: 'acct-1',+ email: undefined,+ plan: undefined+ })+ })++ test('rejects tokens that name no account', () => {+ expect(chatGPTAccount(jwt({ sub: 'x' }))).toBeNull()+ expect(chatGPTAccount('not-a-token')).toBeNull()+ expect(chatGPTAccount('a.!!!.c')).toBeNull()+ })++ test('exchanges the code as a form post and keeps the account', async () => {+ const requests: { url: string; body: string }[] = []+ const credential = await exchangeChatGPTCode('code-1', 'verifier-1', async (input, init) => {+ requests.push({ url: String(input), body: String(init?.body) })+ return tokenResponse({+ access_token: accessToken,+ refresh_token: 'refresh-1',+ expires_in: 3600,+ id_token: idToken+ })+ })+ expect(requests).toHaveLength(1)+ expect(requests[0]?.url).toBe(CHATGPT_TOKEN_URL)+ expect(Object.fromEntries(new URLSearchParams(requests[0]?.body))).toEqual({+ client_id: 'app_EMoamEEZ73f0CkXaXp7hrann',+ grant_type: 'authorization_code',+ code: 'code-1',+ code_verifier: 'verifier-1',+ redirect_uri: 'http://localhost:1455/auth/callback'+ })+ expect(credential).toMatchObject({+ access: accessToken,+ refresh: 'refresh-1',+ accountId: 'acct-1',+ email: '[email protected]',+ plan: 'plus'+ })+ expect(credential.expires).toBeGreaterThan(Date.now() + 3_500_000)+ })++ test('keeps the known email and plan when a refresh returns no ID token', async () => {+ let body = ''+ const refreshed = await refreshChatGPTCredential(+ {+ access: 'old',+ refresh: 'refresh-1',+ expires: 0,+ accountId: 'acct-1',+ email: '[email protected]',+ plan: 'plus'+ },+ async (_input, init) => {+ body = String(init?.body)+ return tokenResponse({+ access_token: accessToken,+ refresh_token: 'refresh-2',+ expires_in: 60+ })+ }+ )+ expect(Object.fromEntries(new URLSearchParams(body))).toEqual({+ client_id: 'app_EMoamEEZ73f0CkXaXp7hrann',+ grant_type: 'refresh_token',+ refresh_token: 'refresh-1'+ })+ expect(refreshed).toMatchObject({+ refresh: 'refresh-2',+ email: '[email protected]',+ plan: 'plus'+ })+ })++ test('fails on a rejected or malformed token response', async () => {+ const rejected = exchangeChatGPTCode('c', 'v', async () => new Response('', { status: 400 }))+ await expect(rejected).rejects.toBeInstanceOf(ChatGPTTokenError)+ const malformed = exchangeChatGPTCode('c', 'v', async () => tokenResponse({ access_token: 1 }))+ await expect(malformed).rejects.toBeInstanceOf(ChatGPTTokenError)+ })+})diff --git a/tests/app/ai/providers/openrouter/oauth.test.ts b/tests/app/ai/providers/openrouter/oauth.test.tsindex 6e7d5cf34..387666c0d 100644--- a/tests/app/ai/providers/openrouter/oauth.test.ts+++ b/tests/app/ai/providers/openrouter/oauth.test.ts@@ -4,20 +4,12 @@ import {exchangeOpenRouterCode,openRouterAuthorizationURL,OpenRouterKeyExchangeError,- OPENROUTER_KEYS_URL,- parseOpenRouterCallback,- pkceChallenge+ OPENROUTER_KEYS_URL} from '@/app/ai/providers/openrouter/oauth'import { fetchStub } from '#tests/helpers/fetch'describe('OpenRouter OAuth PKCE', () => {- test('derives the S256 challenge from the RFC 7636 example verifier', async () => {- expect(await pkceChallenge('dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk')).toBe(- 'E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM'- )- })-test('builds the authorization URL with the challenge, state, and key label', () => {const url = new URL(openRouterAuthorizationURL(@@ -36,15 +28,6 @@ describe('OpenRouter OAuth PKCE', () => {})})- test('accepts only the callback for the current attempt', () => {- expect(parseOpenRouterCallback('?code=abc&state=s1', 's1')).toEqual({ ok: true, code: 'abc' })- expect(parseOpenRouterCallback('?code=abc&state=other', 's1')).toEqual({- ok: false,- reason: 'mismatch'- })- expect(parseOpenRouterCallback('?state=s1', 's1')).toEqual({ ok: false, reason: 'cancelled' })- })-test('exchanges the code and verifier for a key', async () => {const requests: { url: string; body: unknown }[] = []const fetchImpl = fetchStub(async (input, init) => {diff --git a/tests/app/ai/providers/sign-in/attempt.test.ts b/tests/app/ai/providers/sign-in/attempt.test.tsnew file mode 100644index 000000000..e387e0d2f--- /dev/null+++ b/tests/app/ai/providers/sign-in/attempt.test.ts@@ -0,0 +1,146 @@+import { describe, expect, test } from 'bun:test'++import {+ callbackOutcome,+ startSignIn,+ type CallbackOutcome,+ type SignInCallback,+ type SignInFlow+} from '@/app/ai/providers/sign-in/attempt'+import { pkceChallenge } from '@/app/ai/providers/sign-in/pkce'+import { createDeferred } from '@/app/runtime/deferred'++interface FakeCallback extends SignInCallback {+ state: string+ opened: string[]+ /** Settles when the page first opens. */+ shown: Promise<undefined>+ closed: number+ redirect: (outcome: CallbackOutcome) => void+}++function fakeCallback(state: string): FakeCallback {+ const outcome = createDeferred<CallbackOutcome>()+ const shown = createDeferred<undefined>()+ const callback: FakeCallback = {+ state,+ opened: [],+ shown: shown.promise,+ closed: 0,+ redirect: outcome.resolve,+ open: (url) => {+ callback.opened.push(url)+ shown.resolve(undefined)+ },+ wait: () => outcome.promise,+ close: () => {+ callback.closed+++ }+ }+ return callback+}++/** A flow whose redirect the test drives; the exchange echoes the code and verifier. */+function fakeFlow(+ overrides: Partial<SignInFlow<string, 'busy'>> = {}+): SignInFlow<string, 'busy'> & { callbacks: FakeCallback[] } {+ const callbacks: FakeCallback[] = []+ return {+ signal: new AbortController().signal,+ callback: async (state) => {+ const callback = fakeCallback(state)+ callbacks.push(callback)+ return callback+ },+ authorizationURL: (pkce) =>+ `https://auth.example/?challenge=${pkce.challenge}&state=${pkce.state}`,+ exchange: async (code, verifier) => `${code}:${verifier}`,+ callbacks,+ ...overrides+ }+}++async function opened(flow: { callbacks: FakeCallback[] }): Promise<FakeCallback> {+ const [callback] = flow.callbacks+ await callback.shown+ return callback+}++describe('provider sign-in', () => {+ test('derives the S256 challenge from the RFC 7636 example verifier', async () => {+ expect(await pkceChallenge('dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk')).toBe(+ 'E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM'+ )+ })++ test('accepts only the redirect for the current attempt', () => {+ expect(callbackOutcome('?code=abc&state=s1', 's1')).toEqual({ kind: 'code', code: 'abc' })+ expect(callbackOutcome('?code=abc&state=other', 's1')).toEqual({ kind: 'mismatch' })+ expect(callbackOutcome('?error=access_denied&state=s1', 's1')).toEqual({ kind: 'denied' })+ })++ test('opens the page for the callback state, trades the code, and closes the callback', async () => {+ const flow = fakeFlow()+ const sign = startSignIn(flow)+ const callback = await opened(flow)+ const url = new URL(callback.opened[0])+ expect(url.searchParams.get('state')).toBe(callback.state)++ callback.redirect({ kind: 'code', code: 'abc' })+ const result = await sign.result+ expect(result.ok && result.value.startsWith('abc:')).toBe(true)+ expect(callback.closed).toBe(1)+ })++ test('reopens the same page', async () => {+ const flow = fakeFlow()+ const sign = startSignIn(flow)+ const callback = await opened(flow)+ sign.reopen()+ expect(callback.opened).toEqual([callback.opened[0], callback.opened[0]])+ callback.redirect({ kind: 'denied' })+ await sign.result+ })++ test('maps a redirect without a code to a failure', async () => {+ for (const [kind, reason] of [+ ['denied', 'cancelled'],+ ['mismatch', 'failed'],+ ['expired', 'expired']+ ] as const) {+ const flow = fakeFlow()+ const sign = startSignIn(flow)+ ;(await opened(flow)).redirect({ kind })+ expect(await sign.result).toEqual({ ok: false, reason })+ }+ })++ test('closes the callback the moment the attempt is cancelled', async () => {+ const controller = new AbortController()+ const flow = fakeFlow({ signal: controller.signal })+ const sign = startSignIn(flow)+ const callback = await opened(flow)+ controller.abort()+ expect(callback.closed).toBe(1)+ expect(await sign.result).toEqual({ ok: false, reason: 'cancelled' })+ expect(callback.closed).toBe(1)+ })++ test('reports a provider failure from readying the callback', async () => {+ const sign = startSignIn(fakeFlow({ callback: async () => ({ failure: 'busy' }) }))+ expect(await sign.result).toEqual({ ok: false, reason: 'busy' })+ })++ test('reports a failed exchange and still closes the callback', async () => {+ const flow = fakeFlow({+ exchange: async () => {+ throw new Error('rejected')+ }+ })+ const sign = startSignIn(flow)+ const callback = await opened(flow)+ callback.redirect({ kind: 'code', code: 'abc' })+ expect(await sign.result).toEqual({ ok: false, reason: 'failed' })+ expect(callback.closed).toBe(1)+ })+})diff --git a/tests/engine/app/ai/failure.test.ts b/tests/engine/app/ai/failure.test.tsindex 0bd1250c3..0cc224b1d 100644--- a/tests/engine/app/ai/failure.test.ts+++ b/tests/engine/app/ai/failure.test.ts@@ -50,6 +50,16 @@ describe('AI chat failures', () => {})})+ test('reports a refused sign-in or plan instead of a key for providers signed in to', () => {+ expect(classifyAIChatError({ statusCode: 401 }, { signInOnly: true }).reason).toBe(+ 'sign-in-expired'+ )+ expect(classifyAIChatError({ statusCode: 403 }, { signInOnly: true }).reason).toBe(+ 'plan-forbidden'+ )+ expect(classifyAIChatError({ statusCode: 429 }, { signInOnly: true }).reason).toBe('rate-limit')+ })+test('classifies provider errors reported after the stream started', () => {const streamError = new StreamProviderError({message: 'Too many requests',diff --git a/tests/helpers/ai/chatgpt.ts b/tests/helpers/ai/chatgpt.tsnew file mode 100644index 000000000..efffde895--- /dev/null+++ b/tests/helpers/ai/chatgpt.ts@@ -0,0 +1,32 @@+import { encode } from 'js-base64'++import type { ChatGPTCredential } from '@/app/ai/providers/chatgpt/credential'++const AUTH_CLAIM = 'https://api.openai.com/auth'++/** An unsigned JWT; the app reads its own token responses without verifying them. */+export function jwt(payload: Record<string, unknown>): string {+ return `${encode('{"alg":"none"}', true)}.${encode(JSON.stringify(payload), true)}.sig`+}++export const accessToken = jwt({ [AUTH_CLAIM]: { chatgpt_account_id: 'acct-1' } })+export const idToken = jwt({+ email: '[email protected]',+ [AUTH_CLAIM]: { chatgpt_plan_type: 'plus' }+})++export function credential(patch: Partial<ChatGPTCredential> = {}): ChatGPTCredential {+ return {+ access: 'access-1',+ refresh: 'refresh-1',+ expires: Date.now() + 60 * 60 * 1000,+ accountId: 'acct-1',+ email: '[email protected]',+ plan: 'plus',+ ...patch+ }+}++export function tokenResponse(body: Record<string, unknown>): Response {+ return new Response(JSON.stringify(body), { headers: { 'content-type': 'application/json' } })+}diff --git a/tools/checks/i18n/mixed-script-baseline.txt b/tools/checks/i18n/mixed-script-baseline.txtindex a4551ae5b..394aeb0f7 100644--- a/tools/checks/i18n/mixed-script-baseline.txt+++ b/tools/checks/i18n/mixed-script-baseline.txt@@ -1,5 +1,6 @@ja:ai.aiSetupAccessAPIja:ai.aiSetupAccessAgentsDesktop+ja:ai.aiSetupAccessChatGPTja:ai.aiSetupAccessServerDescriptionja:ai.aiSetupAgentAdapterMismatchja:ai.aiSetupAgentDescription@@ -14,6 +15,15 @@ ja:ai.aiSetupAgentPromptHintja:ai.aiSetupAgentToolsja:ai.aiSetupAgentToolsFailedja:ai.aiSetupAgentToolsHint+ja:ai.aiSetupChatGPTCallbackCancelled+ja:ai.aiSetupChatGPTCallbackSignedIn+ja:ai.aiSetupChatGPTCallbackStale+ja:ai.aiSetupChatGPTFailed+ja:ai.aiSetupChatGPTPortInUse+ja:ai.aiSetupChatGPTSignIn+ja:ai.aiSetupChatGPTSignedInTitle+ja:ai.aiSetupChatGPTUsage+ja:ai.aiSetupChatGPTWaitingja:ai.aiSetupConnectTitleja:ai.aiSetupGapAddOpenRouterja:ai.aiSetupGapCoveredByOpenRouter@@ -213,6 +223,7 @@ ja:updates.unavailableja:updates.upToDatezh-cn:ai.aiSetupAccessAPIzh-cn:ai.aiSetupAccessAgentsDesktop+zh-cn:ai.aiSetupAccessChatGPTzh-cn:ai.aiSetupAccessServerDescriptionzh-cn:ai.aiSetupAgentAdapterMismatchzh-cn:ai.aiSetupAgentDescription@@ -227,6 +238,15 @@ zh-cn:ai.aiSetupAgentPromptHintzh-cn:ai.aiSetupAgentToolszh-cn:ai.aiSetupAgentToolsFailedzh-cn:ai.aiSetupAgentToolsHint+zh-cn:ai.aiSetupChatGPTCallbackCancelled+zh-cn:ai.aiSetupChatGPTCallbackSignedIn+zh-cn:ai.aiSetupChatGPTCallbackStale+zh-cn:ai.aiSetupChatGPTFailed+zh-cn:ai.aiSetupChatGPTPortInUse+zh-cn:ai.aiSetupChatGPTSignIn+zh-cn:ai.aiSetupChatGPTSignedInTitle+zh-cn:ai.aiSetupChatGPTUsage+zh-cn:ai.aiSetupChatGPTWaitingzh-cn:ai.aiSetupConnectTitlezh-cn:ai.aiSetupGapAddOpenRouterzh-cn:ai.aiSetupGapCoveredByOpenRouter