diff --git a/apps/api/src/opendirector_api/agent.py b/apps/api/src/opendirector_api/agent.py index a75f2562a..aa4196492 100644 --- a/apps/api/src/opendirector_api/agent.py +++ b/apps/api/src/opendirector_api/agent.py @@ -22,7 +22,7 @@ from opendirector.agent.context import RunContext, RuntimeId from opendirector.agent.references import TurnReference, resolve_turn_references from opendirector.agent.citations import referenced_sources, with_trace_sources -from opendirector.agent.runtime import AgentRuntimes, runtime_available, configured_runtimes, runtime_spec, runtime_catalog, runtime_status +from opendirector.agent.runtime import AgentRuntimes, runtime_available, configured_runtimes, runtime_spec, runtime_catalog, runtime_status, note_authentication_failure, clear_authentication_failure from opendirector.agent.skills import skills from opendirector.agent import timing as agent_timing from opendirector.application.model_availability import requests_for @@ -137,7 +137,7 @@ def _timestamp(value): return value if isinstance(value, str) and value else None -TIMED_STATUSES = {'complete', 'stopped', 'interrupted'} +TIMED_STATUSES = {'complete', 'stopped', 'interrupted', 'failed'} class Conversations: @@ -641,8 +641,10 @@ async def available_runtimes(project_id: UUID, probe: bool = True): for item in runtime_catalog()] @router.get('/runtimes/{runtime}/status') - async def runtime_detail(project_id: UUID, runtime: Runtime): + async def runtime_detail(project_id: UUID, runtime: Runtime, retry: bool = False): await asyncio.to_thread(conversations.path, project_id) + if retry: + clear_authentication_failure(runtime) item = next(item for item in runtime_catalog() if item['id'] == runtime) return {**item, 'status': await runtime_status(runtime)} @@ -759,7 +761,7 @@ async def produce_one(chain: Chain, plan: dict) -> tuple[dict | None, str | None project_id = chain.project_id message = plan['message'] turn_id = UUID(message['id']) - text, status, error = '', 'complete', None + text, status, error, error_code = '', 'complete', None, None activities: list[dict] = [] edited_documents: dict[str, int] = {} sources: dict = {} @@ -858,6 +860,10 @@ async def renew_session() -> None: error = localized_error_for_language( plan.get('accept_language'), chinese=str(failure), status=failure.status, code=failure.code) + if failure.code == 'authentication_failed': + status = 'failed' + error_code = failure.code + note_authentication_failure(message['runtime']) else: error = localized_error_for_language( plan.get('accept_language'), @@ -869,12 +875,15 @@ async def renew_session() -> None: if activity['status'] == 'running': activity['status'] = 'interrupted' try: + if status == 'complete': + clear_authentication_failure(message['runtime']) saved = await asyncio.to_thread(conversations.update, project_id, finish={ 'id': str(uuid5(turn_id, 'assistant')), 'role': 'assistant', 'text': text, 'status': status, 'model': plan['model'], 'modelIsCliDefault': plan.get('model_is_cli_default', False), 'runtime': message['runtime'], 'thinking': plan['thinking'], 'tools': activities, 'sources': list(sources.values()), - **({'plan': steps} if steps is not None else {})}, conversation_id=chain.conversation_id, + **({'plan': steps} if steps is not None else {}), + **({'error': error, 'errorCode': error_code} if error else {})}, conversation_id=chain.conversation_id, finish_turn_id=turn_id, edited_documents=edited_documents) except Exception: logger.exception(f'agent.turn.unfinished project_id={project_id} turn_id={turn_id}') diff --git a/apps/api/src/opendirector_api/localization.py b/apps/api/src/opendirector_api/localization.py index 439b6b3bb..3fe4c5e61 100644 --- a/apps/api/src/opendirector_api/localization.py +++ b/apps/api/src/opendirector_api/localization.py @@ -45,6 +45,8 @@ 'higgsfield_references': 'Reference mode requires at least one image, video, or audio clip. Check the reference roles.', 'higgsfield_prompt': 'MAGI-2 prompts allow up to 15,000 characters. Text-to-video requires a prompt.', "desktop_auth_required": "The desktop connection has expired. Reopen the application.", + 'authentication_failed': 'Claude Code is not signed in. Run claude auth login in a terminal, then try again.', + 'prompt_optimization_empty': 'Enter a prompt to optimize.', 'prompt_optimization_refs': 'Prompt references changed. Try again.', 'prompt_optimization_node': 'Select an image or video node.', diff --git a/packages/core/src/opendirector/agent/native.py b/packages/core/src/opendirector/agent/native.py index 5bb49cba0..5aaa4d3b1 100644 --- a/packages/core/src/opendirector/agent/native.py +++ b/packages/core/src/opendirector/agent/native.py @@ -161,7 +161,8 @@ def command(runtime: str, work: Path, socket: str, token: str, model: str | None def text_events(runtime: str, raw: dict) -> list[dict]: if runtime == 'claude' and raw.get('error') == 'authentication_failed': - raise ProjectError('Claude Code 登录已过期,请在终端执行 claude auth login 后重试。', 401) + raise ProjectError('Claude Code 未登录,请在终端执行 claude auth login 后重试。', 401, + code='authentication_failed') if runtime == 'codex' and raw['type'] == 'error': # Codex also emits this event while reconnecting. Wait for turn.failed or process exit. return [] diff --git a/packages/core/src/opendirector/agent/runtime.py b/packages/core/src/opendirector/agent/runtime.py index f8d9f8899..a25196b75 100644 --- a/packages/core/src/opendirector/agent/runtime.py +++ b/packages/core/src/opendirector/agent/runtime.py @@ -1,6 +1,7 @@ """Runtime catalog and shared per-turn execution boundary.""" import asyncio import json +import os from collections.abc import AsyncIterator from contextlib import aclosing from dataclasses import asdict, dataclass, replace @@ -76,11 +77,37 @@ def runtime_catalog() -> list[dict]: for spec in RUNTIMES.values()] +# A failed turn can see credentials that `auth status` still reports as logged in +# (for example a rejecting Claude Code relay). Remember that until a successful +# turn or an explicit recheck, so the runtime list does not stay on "ready". +_authentication_failures: set[str] = set() + + +def note_authentication_failure(engine: str) -> None: + _authentication_failures.add(engine) + + +def clear_authentication_failure(engine: str) -> None: + _authentication_failures.discard(engine) + + +def claude_gateway_credentials_configured() -> bool: + """True when Claude Code can authenticate without a claude.ai login. + + Official gateway setup uses ANTHROPIC_AUTH_TOKEN or ANTHROPIC_API_KEY. + A base URL alone does not replace a credential. This checks process + environment only and does not call the gateway. + """ + return any(os.environ.get(name, '').strip() for name in ('ANTHROPIC_AUTH_TOKEN', 'ANTHROPIC_API_KEY')) + + async def runtime_readiness(engine: str) -> str: """Probe one engine. Installation is decided once, by `installation`.""" executable = installation(engine) if executable is None: return 'not_installed' + if engine in _authentication_failures: + return 'needs_login' if engine == 'deepseek': from opendirector.agent.deepseek import model_choices try: @@ -113,7 +140,9 @@ async def runtime_readiness(engine: str) -> str: logged_in = json.loads(output)['loggedIn'] except (ValueError, KeyError, TypeError): return 'unknown' - return 'ready' if logged_in is True else 'needs_login' + if logged_in is True or claude_gateway_credentials_configured(): + return 'ready' + return 'needs_login' return 'ready' if process.returncode == 0 else 'needs_login' except TimeoutError: return 'unknown' diff --git a/src/backend/chat.ts b/src/backend/chat.ts index c75bb3d31..6cc4f13b2 100644 --- a/src/backend/chat.ts +++ b/src/backend/chat.ts @@ -83,7 +83,9 @@ export interface ChatMessage { role: "user" | "assistant"; text: string; content?: ReferenceContent | null; - status: "complete" | "streaming" | "stopped" | "interrupted"; + status: "complete" | "streaming" | "stopped" | "interrupted" | "failed"; + error?: string | null; + errorCode?: string | null; assets?: ChatAsset[]; model?: string | null; modelIsCliDefault?: boolean; @@ -219,11 +221,16 @@ const discoveryTtlMs = 30_000; export async function chatRuntimeStatus(id: string, runtime: AgentRuntime, signal?: AbortSignal, refresh = false) { const cached = runtimeStatuses.get(runtime); if (!refresh && cached && cached.expires > Date.now()) return cached.value; - const value = await request(path(id) + `/runtimes/${runtime}/status`, { signal }); + const query = refresh ? "?retry=true" : ""; + const value = await request(path(id) + `/runtimes/${runtime}/status${query}`, { signal }); runtimeStatuses.set(runtime, { value, expires: Date.now() + discoveryTtlMs }); return value; } +export function forgetRuntimeStatus(runtime?: AgentRuntime | null) { + if (runtime) runtimeStatuses.delete(runtime); +} + export async function chatRuntimeInventory(id: string, signal?: AbortSignal) { const rows = await request(path(id) + "/runtimes?probe=false", { signal }); return rows.map((item) => { diff --git a/src/canvas/AssistantPanel.tsx b/src/canvas/AssistantPanel.tsx index 58f6f6149..249e2b2c9 100644 --- a/src/canvas/AssistantPanel.tsx +++ b/src/canvas/AssistantPanel.tsx @@ -12,6 +12,7 @@ import "./assistant-experience.css"; import "./assistant-workspace.css"; import { AttachmentStrip, AttachmentHover } from "./AssistantMedia"; import { AssistantReply } from "./AssistantReply"; +import { isAuthenticationFailure } from "./assistantReplyFailure.ts"; import type { ProjectEditorTarget } from "./assistantResultEditors.ts"; import { AssistantResultCard, AssistantTimelineResultCard } from "./AssistantResultCard"; import { useAssistantResults } from "./useAssistantResults.ts"; @@ -606,11 +607,14 @@ export function AssistantPanel({ )} {message.role === "user" && !!message.assets?.length && } {(message.status === "stopped" || - message.status === "interrupted") && ( + message.status === "interrupted" || + message.status === "failed") && ( {message.status === "stopped" ? t("assistant.panel.stopped") - : t("assistant.panel.interrupted")} + : isAuthenticationFailure(message) || message.status === "failed" + ? t("assistant.panel.failed") + : t("assistant.panel.interrupted")} )} diff --git a/src/canvas/AssistantReply.tsx b/src/canvas/AssistantReply.tsx index dae6a71f1..f845c9d5e 100644 --- a/src/canvas/AssistantReply.tsx +++ b/src/canvas/AssistantReply.tsx @@ -12,6 +12,7 @@ import { assistantCitationFormatter } from "./assistantCitations.ts"; import { defaultTranslate } from "./assistantTranslate.ts"; import { chatTurnTiming } from "./turnTiming.ts"; import { hidePartialSuggestionMarker, parseSuggestedReplies } from "./suggestedReplies.ts"; +import { assistantReplyFailure } from "./assistantReplyFailure.ts"; const STATUS: Record = { running: "assistant.reply.status.running", @@ -185,7 +186,7 @@ export const AssistantReply = memo(function AssistantReply({ {!message.text && !message.tools?.length && message.status !== "streaming" && ( -

{t("assistant.reply.empty")}

+

{assistantReplyFailure(message, t) ?? t("assistant.reply.empty")}

)} {!!message.text && message.status !== "streaming" && (
diff --git a/src/canvas/assistantReplyFailure.ts b/src/canvas/assistantReplyFailure.ts new file mode 100644 index 000000000..3695b471b --- /dev/null +++ b/src/canvas/assistantReplyFailure.ts @@ -0,0 +1,15 @@ +import type { ChatMessage } from "../backend/chat"; +import type { Translate } from "../i18n/I18nProvider.tsx"; + +/** Visible reason for a failed assistant turn, or null when the empty-reply placeholder applies. */ +export function assistantReplyFailure(message: ChatMessage, t: Translate): string | null { + if (message.errorCode === "authentication_failed") { + return t("assistant.reply.authenticationFailed"); + } + if (message.error && message.status !== "streaming") return message.error; + return null; +} + +export function isAuthenticationFailure(message: ChatMessage): boolean { + return message.errorCode === "authentication_failed" || message.status === "failed"; +} diff --git a/src/canvas/traceTurns.ts b/src/canvas/traceTurns.ts index 87f85c612..a77d74ac6 100644 --- a/src/canvas/traceTurns.ts +++ b/src/canvas/traceTurns.ts @@ -5,7 +5,7 @@ export type ConversationTurn = { text: string; runtime: string; model: string | null; - status: "streaming" | "complete" | "stopped" | "interrupted"; + status: "streaming" | "complete" | "stopped" | "interrupted" | "failed"; startedAt?: string | null; finishedAt?: string | null; durationMs?: number | null; diff --git a/src/canvas/turnTiming.ts b/src/canvas/turnTiming.ts index 0f38fed8d..ccfbb8489 100644 --- a/src/canvas/turnTiming.ts +++ b/src/canvas/turnTiming.ts @@ -2,11 +2,11 @@ import type { Translate } from "../i18n/I18nProvider.tsx"; import type { MessageKey } from "../i18n/types.ts"; -export type TurnStatus = "streaming" | "complete" | "stopped" | "interrupted"; +export type TurnStatus = "streaming" | "complete" | "stopped" | "interrupted" | "failed"; export const TURN_STATUS_KEYS: Record = { streaming: "trace.turn.status.streaming", complete: "trace.turn.status.complete", - stopped: "trace.turn.status.stopped", interrupted: "trace.turn.status.interrupted", + stopped: "trace.turn.status.stopped", interrupted: "trace.turn.status.interrupted", failed: "trace.turn.status.failed", }; /** 820 -> "820 ms", 12400 -> "12.4 s", 125000 -> "2m 5s", 3725000 -> "1h 2m". Unknown or invalid -> null. */ diff --git a/src/canvas/useAssistantChat.ts b/src/canvas/useAssistantChat.ts index 6886ff7a5..3c249024f 100644 --- a/src/canvas/useAssistantChat.ts +++ b/src/canvas/useAssistantChat.ts @@ -13,6 +13,7 @@ import { type ConversationSummary, chatRuntimeInventory, chatRuntimeStatus, + forgetRuntimeStatus, type AgentRuntime, type RuntimeInfo, streamChat, @@ -591,6 +592,13 @@ export function useAssistantChat( // The reply can finish before the next draft reaches autosave. if (messages) setValue((previous) => ({ ...previous, messages })); if (event.error) setError(displayError(event.error)); + const reply = [...(event.conversation?.messages ?? [])].reverse() + .find((message) => message.role === "assistant"); + if (reply?.errorCode === "authentication_failed" && reply.runtime) { + forgetRuntimeStatus(reply.runtime); + setRuntimes((items) => items.map((item) => item.id === reply.runtime + ? { ...item, status: "needs_login" } : item)); + } } }, ); diff --git a/src/i18n/messages/en-US/assistant.ts b/src/i18n/messages/en-US/assistant.ts index 3e7bfc22e..0581606f7 100644 --- a/src/i18n/messages/en-US/assistant.ts +++ b/src/i18n/messages/en-US/assistant.ts @@ -59,6 +59,7 @@ export const assistant = { "assistant.panel.refreshCatalog": "Read again", "assistant.panel.stopped": "Reply stopped", "assistant.panel.interrupted": "Reply interrupted", + "assistant.panel.failed": "Reply failed", "assistant.panel.send": "Send message", "assistant.panel.stop": "Stop reply", "assistant.panel.upload": "Upload reference", @@ -136,6 +137,7 @@ export const assistant = { "assistant.reply.task": "Task: ", "assistant.reply.plan": "Execution plan", "assistant.reply.empty": "This reply produced no content.", + "assistant.reply.authenticationFailed": "Claude Code is not signed in. Run claude auth login in a terminal, then try again.", "assistant.reply.copy": "Copy", "assistant.reply.suggestions": "Suggested replies", "assistant.reply.useSuggestion": "Use this suggestion as the draft text", diff --git a/src/i18n/messages/en-US/trace.ts b/src/i18n/messages/en-US/trace.ts index 906c76034..b0a9ca2ca 100644 --- a/src/i18n/messages/en-US/trace.ts +++ b/src/i18n/messages/en-US/trace.ts @@ -56,6 +56,7 @@ export const trace = { "trace.turn.status.complete": "Completed", "trace.turn.status.stopped": "Stopped", "trace.turn.status.interrupted": "Interrupted", + "trace.turn.status.failed": "Failed", "trace.loading": "Loading…", "trace.waiting": "Waiting for trace events…", "trace.notFound": "No trace of this type for this turn.", diff --git a/src/i18n/messages/zh-CN/assistant.ts b/src/i18n/messages/zh-CN/assistant.ts index 5363288c0..bd752a086 100644 --- a/src/i18n/messages/zh-CN/assistant.ts +++ b/src/i18n/messages/zh-CN/assistant.ts @@ -58,6 +58,7 @@ export const assistant = { "assistant.panel.refreshCatalog": "重新读取", "assistant.panel.stopped": "已停止回复", "assistant.panel.interrupted": "回复已中断", + "assistant.panel.failed": "回复失败", "assistant.panel.send": "发送消息", "assistant.panel.stop": "停止回复", "assistant.panel.upload": "上传参考", @@ -135,6 +136,7 @@ export const assistant = { "assistant.reply.task": "任务:", "assistant.reply.plan": "执行计划", "assistant.reply.empty": "本次回复未生成内容。", + "assistant.reply.authenticationFailed": "助手未登录:请在终端执行 claude auth login 后重试。", "assistant.reply.copy": "复制", "assistant.reply.suggestions": "建议回复", "assistant.reply.useSuggestion": "用这条建议填写草稿", diff --git a/src/i18n/messages/zh-CN/trace.ts b/src/i18n/messages/zh-CN/trace.ts index a726930fb..a279cd95c 100644 --- a/src/i18n/messages/zh-CN/trace.ts +++ b/src/i18n/messages/zh-CN/trace.ts @@ -56,6 +56,7 @@ export const trace = { "trace.turn.status.complete": "已完成", "trace.turn.status.stopped": "已停止", "trace.turn.status.interrupted": "已中断", + "trace.turn.status.failed": "失败", "trace.loading": "加载中…", "trace.waiting": "等待首条轨迹…", "trace.notFound": "该轮没有此类轨迹。", diff --git a/tests/assistantReplyFailure.test.ts b/tests/assistantReplyFailure.test.ts new file mode 100644 index 000000000..a375550e9 --- /dev/null +++ b/tests/assistantReplyFailure.test.ts @@ -0,0 +1,37 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import type { ChatMessage } from "../src/backend/chat.ts"; +import { assistantReplyFailure, isAuthenticationFailure } from "../src/canvas/assistantReplyFailure.ts"; +import { setActiveLocale } from "../src/i18n/messages.ts"; +import { defaultTranslate } from "../src/canvas/assistantTranslate.ts"; + +function message(overrides: Partial): ChatMessage { + return { + id: "reply", + role: "assistant", + text: "", + status: "interrupted", + ...overrides, + }; +} + +test("authentication failure shows a bilingual reason instead of the empty placeholder", () => { + const failed = message({ status: "failed", errorCode: "authentication_failed", error: "server text" }); + setActiveLocale("en-US"); + assert.equal( + assistantReplyFailure(failed, defaultTranslate), + "Claude Code is not signed in. Run claude auth login in a terminal, then try again.", + ); + assert.equal(isAuthenticationFailure(failed), true); + setActiveLocale("zh-CN"); + assert.equal( + assistantReplyFailure(failed, defaultTranslate), + "助手未登录:请在终端执行 claude auth login 后重试。", + ); +}); + +test("an empty completed reply still uses the empty placeholder", () => { + setActiveLocale("en-US"); + assert.equal(assistantReplyFailure(message({ status: "complete" }), defaultTranslate), null); + assert.equal(isAuthenticationFailure(message({ status: "interrupted" })), false); +}); diff --git a/tests/chatRuntimes.test.ts b/tests/chatRuntimes.test.ts index daa07baa7..01671ffd6 100644 --- a/tests/chatRuntimes.test.ts +++ b/tests/chatRuntimes.test.ts @@ -11,7 +11,7 @@ test("canvas changes reuse a known runtime status without probing the other harn t.mock.method(globalThis, "fetch", async (url: string) => { calls.push(url); if (url.endsWith("?probe=false")) return Response.json([codex, { ...codex, id: "claude" }]); - assert.ok(url.endsWith("/codex/status")); + assert.ok(/\/codex\/status(?:\?retry=true)?$/.test(url)); return Response.json({ ...codex, status: "ready" }); }); @@ -21,7 +21,9 @@ test("canvas changes reuse a known runtime status without probing the other harn assert.equal(target[0].status, "ready"); assert.equal(target[1].status, "checking"); await chatRuntimeStatus("target", "codex"); - assert.equal(calls.filter((url) => url.endsWith("/status")).length, 1); + assert.equal(calls.filter((url) => url.includes("/codex/status")).length, 1); await chatRuntimeStatus("target", "codex", undefined, true); - assert.equal(calls.filter((url) => url.endsWith("/status")).length, 2); + const statusCalls = calls.filter((url) => url.includes("/codex/status")); + assert.equal(statusCalls.length, 2); + assert.ok(statusCalls[1].endsWith("/status?retry=true")); }); diff --git a/tests/test_assistant_conversation_trace.py b/tests/test_assistant_conversation_trace.py index 6726bf6e8..5e1e7034b 100644 --- a/tests/test_assistant_conversation_trace.py +++ b/tests/test_assistant_conversation_trace.py @@ -420,7 +420,7 @@ def test_finish_write_delay_is_excluded_too(assistant, manual, tmp_path, monkeyp assert run_turn(conversations, project, manual)['durationMs'] == 250 -@pytest.mark.parametrize('status', ['complete', 'stopped', 'interrupted']) +@pytest.mark.parametrize('status', ['complete', 'stopped', 'interrupted', 'failed']) def test_every_terminal_status_excludes_the_initial_write(assistant, manual, tmp_path, monkeypatch, status): project, conversations = new_conversations(assistant, tmp_path) slow_writes(monkeypatch, manual, [2000]) diff --git a/tests/test_assistant_conversations.py b/tests/test_assistant_conversations.py index 8b60b537d..d3993ab3b 100644 --- a/tests/test_assistant_conversations.py +++ b/tests/test_assistant_conversations.py @@ -958,3 +958,60 @@ async def stream(self, run, gateway): with store.transaction() as db: assert db.execute('SELECT 1 FROM sessions WHERE id=?', (store.agent_session_key(run_session),)).fetchone() is None + + +def test_claude_authentication_failure_persists_a_visible_reason(assistant, monkeypatch): + from opendirector.agent import runtime + from opendirector.domain.projects import ProjectError + client, path, _ = assistant + runtime._authentication_failures.clear() + + async def stream(self, run): + raise ProjectError('Claude Code 未登录,请在终端执行 claude auth login 后重试。', 401, + code='authentication_failed') + yield # pragma: no cover + + monkeypatch.setattr(agent.AgentRuntimes, 'stream', stream) + cid = client.get(path).json()['conversationId'] + response = client.post(path + '/turns', json={'id': str(uuid4()), 'runtime': 'claude', + 'conversationId': cid, 'text': '这张图片上有什么?'}, headers={'Accept-Language': 'zh-CN'}) + assert response.status_code == 200, response.text + events = frames(response) + ending = events[-1] + assert ending['type'] == 'end' + assert ending['error'] and 'claude auth login' in ending['error'] + reply = ending['conversation']['messages'][-1] + assert reply['status'] == 'failed' + assert reply['errorCode'] == 'authentication_failed' + assert 'claude auth login' in reply['error'] + assert reply['text'] == '' + saved = client.get(path).json()['messages'][-1] + assert saved['status'] == 'failed' and saved['errorCode'] == 'authentication_failed' + english = frames(client.post(path + '/turns', json={'id': str(uuid4()), 'runtime': 'claude', + 'conversationId': cid, 'text': 'hello'}, headers={'Accept-Language': 'en-US'}))[-1] + assert 'not signed in' in english['error'].lower() + monkeypatch.setattr(runtime.native, 'executable', lambda name: '/bin/claude' if name == 'claude' else None) + assert asyncio.run(runtime.runtime_readiness('claude')) == 'needs_login' + runtime.clear_authentication_failure('claude') + # Without a real CLI probe after retry, an explicit clear lets a later successful + # turn be admitted; the status endpoint's retry flag is covered separately. + runtime._authentication_failures.clear() + + +def test_runtime_status_retry_clears_a_sticky_authentication_failure(assistant, monkeypatch): + from opendirector.agent import runtime + client, path, _ = assistant + runtime._authentication_failures.clear() + runtime.note_authentication_failure('claude') + monkeypatch.setattr(runtime.native, 'executable', lambda name: '/bin/claude' if name == 'claude' else '/bin/false') + async def ready(engine): + if engine in runtime._authentication_failures: + return 'needs_login' + return 'ready' if engine == 'claude' else 'not_installed' + monkeypatch.setattr(runtime, 'runtime_readiness', ready) + listed = client.get(path + '/runtimes').json() + claude = next(item for item in listed if item['id'] == 'claude') + assert claude['status'] == 'needs_login' + retried = client.get(path + '/runtimes/claude/status?retry=true').json() + assert retried['status'] == 'ready' + runtime._authentication_failures.clear() diff --git a/tests/test_native_runtime.py b/tests/test_native_runtime.py index b23ace852..7c74bff86 100644 --- a/tests/test_native_runtime.py +++ b/tests/test_native_runtime.py @@ -910,3 +910,45 @@ def test_codex_resume_requires_a_persisted_rollout(tmp_path, monkeypatch): rollout.parent.mkdir(parents=True) rollout.write_text('{}\n') assert native.codex_session_available(session) + + +def test_claude_authentication_failed_event_is_a_login_error(): + event = {'type': 'assistant', 'message': {'model': '', + 'content': [{'type': 'text', 'text': 'Not logged in · Please run /login'}]}, + 'error': 'authentication_failed', 'is_api_error_message': True} + with pytest.raises(ProjectError, match='claude auth login') as caught: + native.text_events('claude', event) + assert caught.value.status == 401 and caught.value.code == 'authentication_failed' + + +def test_claude_authentication_failure_stops_the_stream(tmp_path, monkeypatch): + script = python_cli(tmp_path / 'claude-auth', '''import json, sys +print(json.dumps({"type":"assistant","session_id":"auth-fail", + "message":{"model":"","content":[{"type":"text","text":"Not logged in · Please run /login"}]}, + "error":"authentication_failed","is_api_error_message":True})) +raise SystemExit(1) +''') + monkeypatch.setattr(native, 'executable', lambda _: script) + def command(kind, work, socket, token, model, model_url, catalog, **kwargs): + return [str(script), '-p'], {**os.environ} + monkeypatch.setattr(native, 'command', command) + + async def run(): + run = RunContext(runtime='claude', project_id=uuid4(), turn_id=uuid4(), + session=str(uuid4()), directory=tmp_path, config=None, messages=[{'role':'user','content':'hi'}], + selected_skills=[], thinking='auto', model_selections={}, runtime_model=None, skills=[]) + from opendirector.agent.gateway import ToolGateway + from opendirector.agent.tools import AgentTools + gateway = ToolGateway(AgentTools(None, None, None), run) + events = [] + try: + async for event in native.NativeRuntime().stream(run, gateway): + events.append(event) + except ProjectError as failure: + return events, failure + return events, None + + events, failure = asyncio.run(run()) + assert failure is not None + assert failure.code == 'authentication_failed' + assert events == [] diff --git a/tests/test_runtime_readiness.py b/tests/test_runtime_readiness.py index 63188c028..8ad40b5e1 100644 --- a/tests/test_runtime_readiness.py +++ b/tests/test_runtime_readiness.py @@ -12,6 +12,13 @@ pytestmark = pytest.mark.cpu +@pytest.fixture(autouse=True) +def _clear_authentication_failures(): + runtime._authentication_failures.clear() + yield + runtime._authentication_failures.clear() + + @pytest.mark.parametrize(('engine', 'output', 'exit_code', 'expected'), [ ('codex', '', 0, 'ready'), ('codex', '', 1, 'needs_login'), @@ -25,9 +32,58 @@ def test_login_readiness(tmp_path, monkeypatch, engine, output, exit_code, expec cli = python_cli(cli, f'print({output!r})\nraise SystemExit({exit_code})\n') cli.chmod(0o755) monkeypatch.setattr(runtime.native, 'executable', lambda _: cli) + monkeypatch.delenv('ANTHROPIC_AUTH_TOKEN', raising=False) + monkeypatch.delenv('ANTHROPIC_API_KEY', raising=False) assert asyncio.run(runtime.runtime_readiness(engine)) == expected +def _claude_auth_status_cli(tmp_path, logged_in, exit_code=1): + payload = '{"loggedIn":true}' if logged_in else '{"loggedIn":false}' + return python_cli(tmp_path / 'cli', f'print({payload!r})\nraise SystemExit({exit_code})\n') + + +@requires_posix() +@pytest.mark.parametrize('name, value', [ + ('ANTHROPIC_AUTH_TOKEN', 'sk-gateway'), + ('ANTHROPIC_API_KEY', 'sk-api'), +]) +def test_claude_stays_ready_with_gateway_credentials_when_auth_status_logged_out( + tmp_path, monkeypatch, name, value): + monkeypatch.setattr(runtime.native, 'executable', lambda _: _claude_auth_status_cli(tmp_path, False)) + monkeypatch.delenv('ANTHROPIC_AUTH_TOKEN', raising=False) + monkeypatch.delenv('ANTHROPIC_API_KEY', raising=False) + monkeypatch.setenv(name, value) + assert asyncio.run(runtime.runtime_readiness('claude')) == 'ready' + + +@requires_posix() +@pytest.mark.parametrize('env', [ + {}, + {'ANTHROPIC_BASE_URL': 'https://llm-gateway.example.com'}, + {'ANTHROPIC_AUTH_TOKEN': ''}, + {'ANTHROPIC_AUTH_TOKEN': ' '}, + {'ANTHROPIC_API_KEY': ''}, +]) +def test_claude_still_needs_login_without_a_gateway_credential(tmp_path, monkeypatch, env): + monkeypatch.setattr(runtime.native, 'executable', lambda _: _claude_auth_status_cli(tmp_path, False)) + monkeypatch.delenv('ANTHROPIC_AUTH_TOKEN', raising=False) + monkeypatch.delenv('ANTHROPIC_API_KEY', raising=False) + monkeypatch.delenv('ANTHROPIC_BASE_URL', raising=False) + for key, value in env.items(): + monkeypatch.setenv(key, value) + assert asyncio.run(runtime.runtime_readiness('claude')) == 'needs_login' + + +@requires_posix() +def test_authentication_failure_overrides_gateway_credentials(tmp_path, monkeypatch): + monkeypatch.setattr(runtime.native, 'executable', lambda _: _claude_auth_status_cli(tmp_path, True, 0)) + monkeypatch.setenv('ANTHROPIC_AUTH_TOKEN', 'sk-gateway') + runtime.note_authentication_failure('claude') + assert asyncio.run(runtime.runtime_readiness('claude')) == 'needs_login' + runtime.clear_authentication_failure('claude') + assert asyncio.run(runtime.runtime_readiness('claude')) == 'ready' + + def test_missing_install(monkeypatch): monkeypatch.setattr(runtime.native, 'executable', lambda _: None) assert asyncio.run(runtime.runtime_readiness('codex')) == 'not_installed' @@ -165,3 +221,13 @@ def path_lookup(): monkeypatch.setattr(jiuwenswarm, 'executable', path_lookup) assert asyncio.run(runtime.runtime_readiness('jiuwenswarm')) == 'ready' assert seen == [('protocol.capabilities', '/resolved/jiuwenswarm'), ('model.list', '/resolved/jiuwenswarm')] + + +@requires_posix() +def test_authentication_failure_overrides_a_logged_in_auth_status(tmp_path, monkeypatch): + cli = python_cli(tmp_path / 'cli', 'print(\'{"loggedIn":true}\')\n') + monkeypatch.setattr(runtime.native, 'executable', lambda _: cli) + runtime.note_authentication_failure('claude') + assert asyncio.run(runtime.runtime_readiness('claude')) == 'needs_login' + runtime.clear_authentication_failure('claude') + assert asyncio.run(runtime.runtime_readiness('claude')) == 'ready'