Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 14 additions & 5 deletions apps/api/src/opendirector_api/agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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)}

Expand Down Expand Up @@ -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 = {}
Expand Down Expand Up @@ -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'),
Expand All @@ -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}')
Expand Down
2 changes: 2 additions & 0 deletions apps/api/src/opendirector_api/localization.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.',
Expand Down
3 changes: 2 additions & 1 deletion packages/core/src/opendirector/agent/native.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 []
Expand Down
31 changes: 30 additions & 1 deletion packages/core/src/opendirector/agent/runtime.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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'

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Claude Code can authenticate through a third-party API gateway without an Anthropic account login. Please keep it selectable when valid gateway credentials are configured, even if claude auth status reports loggedIn: false. Claude Code gateway docs

if engine == 'deepseek':
from opendirector.agent.deepseek import model_choices
try:
Expand Down Expand Up @@ -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'
Expand Down
11 changes: 9 additions & 2 deletions src/backend/chat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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<RuntimeInfo>(path(id) + `/runtimes/${runtime}/status`, { signal });
const query = refresh ? "?retry=true" : "";
const value = await request<RuntimeInfo>(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<RuntimeInfo[]>(path(id) + "/runtimes?probe=false", { signal });
return rows.map((item) => {
Expand Down
8 changes: 6 additions & 2 deletions src/canvas/AssistantPanel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -606,11 +607,14 @@ export function AssistantPanel({
)}
{message.role === "user" && !!message.assets?.length && <AttachmentStrip projectId={documentId} assets={message.assets.map(resolveAsset)} />}
{(message.status === "stopped" ||
message.status === "interrupted") && (
message.status === "interrupted" ||
message.status === "failed") && (
<small className="cw-assistant-message-status">
{message.status === "stopped"
? t("assistant.panel.stopped")
: t("assistant.panel.interrupted")}
: isAuthenticationFailure(message) || message.status === "failed"
? t("assistant.panel.failed")
: t("assistant.panel.interrupted")}
</small>
)}
</article>
Expand Down
3 changes: 2 additions & 1 deletion src/canvas/AssistantReply.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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<ChatTool["status"], MessageKey> = {
running: "assistant.reply.status.running",
Expand Down Expand Up @@ -185,7 +186,7 @@ export const AssistantReply = memo(function AssistantReply({
{!message.text &&
!message.tools?.length &&
message.status !== "streaming" && (
<p className="cw-chat-progress">{t("assistant.reply.empty")}</p>
<p className="cw-chat-progress">{assistantReplyFailure(message, t) ?? t("assistant.reply.empty")}</p>
)}
{!!message.text && message.status !== "streaming" && (
<div className="cw-chat-message-actions">
Expand Down
15 changes: 15 additions & 0 deletions src/canvas/assistantReplyFailure.ts
Original file line number Diff line number Diff line change
@@ -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";
}
2 changes: 1 addition & 1 deletion src/canvas/traceTurns.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
4 changes: 2 additions & 2 deletions src/canvas/turnTiming.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<TurnStatus, MessageKey> = {
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. */
Expand Down
8 changes: 8 additions & 0 deletions src/canvas/useAssistantChat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import {
type ConversationSummary,
chatRuntimeInventory,
chatRuntimeStatus,
forgetRuntimeStatus,
type AgentRuntime,
type RuntimeInfo,
streamChat,
Expand Down Expand Up @@ -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));
}
}
},
);
Expand Down
2 changes: 2 additions & 0 deletions src/i18n/messages/en-US/assistant.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down Expand Up @@ -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",
Expand Down
1 change: 1 addition & 0 deletions src/i18n/messages/en-US/trace.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.",
Expand Down
2 changes: 2 additions & 0 deletions src/i18n/messages/zh-CN/assistant.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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": "上传参考",
Expand Down Expand Up @@ -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": "用这条建议填写草稿",
Expand Down
1 change: 1 addition & 0 deletions src/i18n/messages/zh-CN/trace.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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": "该轮没有此类轨迹。",
Expand Down
37 changes: 37 additions & 0 deletions tests/assistantReplyFailure.test.ts
Original file line number Diff line number Diff line change
@@ -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>): 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);
});
8 changes: 5 additions & 3 deletions tests/chatRuntimes.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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" });
});

Expand All @@ -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"));
});
2 changes: 1 addition & 1 deletion tests/test_assistant_conversation_trace.py
Original file line number Diff line number Diff line change
Expand Up @@ -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])
Expand Down
Loading
Loading