diff --git a/apps/api/src/opendirector_api/agent.py b/apps/api/src/opendirector_api/agent.py index b311d8f03..de0284c12 100644 --- a/apps/api/src/opendirector_api/agent.py +++ b/apps/api/src/opendirector_api/agent.py @@ -20,6 +20,7 @@ from opendirector.agent.catalog import model_choices from opendirector.agent.context import RunContext, RuntimeId +from opendirector.agent.interactions import Interaction, InteractionGate 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.skills import skills @@ -60,6 +61,12 @@ class Draft(BaseModel): skills: list[str] = Field(default_factory=list, max_length=1) +class InteractionAnswer(BaseModel): + model_config = ConfigDict(extra='forbid') + text: str = Field(default='', max_length=2000) + optionId: str | None = Field(default=None, max_length=80) + + class Turn(BaseModel): conversationId: UUID | None = None model_config = ConfigDict(extra='forbid') @@ -226,6 +233,68 @@ def stamped(message): result = public_conversation(value) return with_trace_sources(result, directory) + def set_interaction(self, project_id: UUID, interaction: Interaction, *, text: str = '') -> None: + """Persist one turn's authoritative interaction state. + + The message keeps its partial text so a reload shows the question with + the context that produced it. Only this turn's assistant record changes. + """ + with self.projects.local.transaction() as db: + self.projects._recover() + directory, _ = self.projects._find(db, project_id) + folder = child(directory, 'agent-runs') + folder.mkdir(exist_ok=True) + file = child(folder, 'conversation.json') + value = read_json(file) if file.exists() else {'messages': [], **Draft().model_dump()} + target = next((message for message in value['messages'] + if message.get('id') == interaction.messageId), None) + if target is None: + raise ProjectError('对话中没有对应这一轮的回复。', 409) + target['interaction'] = interaction.payload() + if interaction.status == 'pending': + target['status'] = 'awaiting_decision' + elif interaction.status == 'answered': + target['status'] = 'streaming' + if text: + target['text'] = text + durable_json(file, value) + + def reacquire_agent_session(self, project_id: UUID, session: str) -> None: + """Re-take the Agent write lease after a user decision paused the turn.""" + with self.projects.local.transaction() as db: + self.projects._recover() + directory, _ = self.projects._find(db, project_id) + self.projects.local.start_agent_session(db, project_id, directory, session) + + def interrupt_stale(self, project_id: UUID) -> dict: + """A restarted server has no live run, so an open wait is interrupted. + + This is a read-repair on conversation load: it prevents the UI from + offering an answer that no process can receive. + """ + with self.projects.local.transaction() as db: + self.projects._recover() + directory, _ = self.projects._find(db, project_id) + file = child(child(directory, 'agent-runs'), 'conversation.json') + if not file.exists(): + value = {'messages': [], **Draft().model_dump()} + value['conversationId'] = str(uuid5(project_id, 'assistant')) + return with_trace_sources(public_conversation(value), directory) + value = read_json(file) + changed = False + for message in value.get('messages', []): + if message.get('status') not in {'streaming', 'awaiting_decision'}: + continue + message['status'] = 'interrupted' + interaction = message.get('interaction') + if isinstance(interaction, dict) and interaction.get('status') == 'pending': + interaction['status'] = 'cancelled' + changed = True + if changed: + durable_json(file, value) + value['conversationId'] = value.get('conversationId') or str(uuid5(project_id, 'assistant')) + return with_trace_sources(public_conversation(value), directory) + def queue(self, project_id: UUID, session: str, message: dict, conversation_id: UUID | None = None) -> dict: """Store a supplementary message that runs after the active turn. @@ -482,6 +551,7 @@ class Chain: task: asyncio.Task | None = None stopped: bool = False last: dict | None = None + interactions: InteractionGate | None = None def agent_routes(projects, generation, configs, provider=None, *, active=None) -> APIRouter: @@ -572,9 +642,11 @@ def turn_jobs(project_id: UUID, turn_id: UUID): async def conversation(project_id: UUID): value = await asyncio.to_thread(conversations.update, project_id) running = active.get(project_id) - # A streaming message without a chain was interrupted (for example by a - # restart); with one, the client can attach to the turn it is running. - if running is not None: + # A streaming or awaiting message without a chain was interrupted (for + # example by a restart); with one, the client can attach to the turn. + if running is None: + value = await asyncio.to_thread(conversations.interrupt_stale, project_id) + else: value = {**value, 'activeTurnId': str(running.turn)} return value @@ -737,6 +809,10 @@ async def produce_one(chain: Chain, plan: dict) -> tuple[dict | None, str | None timing: dict = {} turn_started = time.monotonic() renewal: asyncio.Task | None = None + gate: InteractionGate | None = None + + async def persist_interaction(interaction: Interaction) -> None: + await asyncio.to_thread(conversations.set_interaction, project_id, interaction, text=text) async def renew_session() -> None: """Keep the project writable while a turn outlives the lease it started under.""" @@ -748,9 +824,30 @@ async def renew_session() -> None: except Exception: logger.exception(f'agent.session.renew.failed project_id={project_id}') + async def pause_for_user() -> None: + """A waiting decision must not hold the project against the user.""" + nonlocal renewal + if renewal is not None: + renewal.cancel() + with suppress(asyncio.CancelledError): + await renewal + renewal = None + await asyncio.to_thread(projects.local.release_agent_session, run_session) + + async def resume_after_user() -> None: + """Re-take the lease only after a valid answer is ready to continue.""" + nonlocal renewal + await asyncio.to_thread(conversations.reacquire_agent_session, project_id, run_session) + if renewal is None: + renewal = asyncio.create_task(renew_session()) + try: saved = plan['start'] chain.conversation_id = UUID(saved['conversationId']) + gate = InteractionGate(turn_id=turn_id, conversation_id=chain.conversation_id, + persist=persist_interaction, emit=chain.events.put, + wait=pause_for_user, resume=resume_after_user) + chain.interactions = gate chain.events.put({'type': 'start', 'conversation': saved}) renewal = asyncio.create_task(renew_session()) previous_sources = {source['id']: source for reply in saved['messages'][:-2] @@ -778,7 +875,8 @@ async def renew_session() -> None: session=run_session, directory=plan['directory'], config=plan['config'], messages=context, selected_skills=message.get('skills') or [], thinking=plan['thinking'], model_selections=plan['model_selections'], runtime_model=message.get('runtimeModel'), - skills=plan['available'], conversation_id=chain.conversation_id) + skills=plan['available'], conversation_id=chain.conversation_id, + interactions=gate) async with aclosing(runtimes.stream(run)) as stream: async for event in stream: if event['type'] == 'delta': @@ -825,6 +923,8 @@ async def renew_session() -> None: status=500, code='operation_rejected') logger.exception(f'agent.turn.failed project_id={project_id} turn_id={turn_id}') finally: + if gate is not None: + await gate.close() for activity in activities: if activity['status'] == 'running': activity['status'] = 'interrupted' @@ -873,8 +973,17 @@ async def run_chain(chain: Chain, plan: dict) -> None: break run_session = str(uuid4()) async with admission.setdefault(project_id, asyncio.Lock()): - dispatched = None if chain.stopped else await asyncio.to_thread( - conversations.dispatch, project_id, chain.session, run_session) + try: + dispatched = None if chain.stopped else await asyncio.to_thread( + conversations.dispatch, project_id, chain.session, run_session) + except ProjectError as failure: + # The user closed the tab while this turn waited. No + # later message can be admitted through that session; + # keep the finished turn readable and cancel the queue. + if failure.code != 'session_expired': + raise + await asyncio.to_thread(conversations.cancel_queued, project_id, None) + break if dispatched is None: break chain.turn = UUID(dispatched['message']['id']) @@ -921,6 +1030,17 @@ def rejected(turn_id: UUID, failure: ProjectError, accept_language: str | None) status=failure.status, code=failure.code)}) return StreamingResponse(events.follow(), media_type='text/event-stream') + @router.post('/interactions/{interaction_id}/answer') + async def answer_interaction(project_id: UUID, interaction_id: str, value: InteractionAnswer, + x_opendirector_session: UUID = Header()): + await asyncio.to_thread(conversations.path, project_id, str(x_opendirector_session)) + chain = active.get(project_id) + if chain is None or chain.interactions is None: + raise ProjectError('该询问已回答、取消或不存在。', 409) + if not await chain.interactions.answer(interaction_id, value.model_dump(exclude_none=True)): + raise ProjectError('该询问已回答、取消或不存在。', 409) + return {'ok': True, 'interactionId': interaction_id} + @router.post('/turns/{turn_id}/stop') async def stop(project_id: UUID, turn_id: UUID, x_opendirector_session: UUID = Header()): session = str(x_opendirector_session) diff --git a/docs/development/i18n.md b/docs/development/i18n.md index fc0837253..04723b98a 100644 --- a/docs/development/i18n.md +++ b/docs/development/i18n.md @@ -107,6 +107,7 @@ npm run check:i18n | 错误、状态与后端回执 | [errors.ts](../../src/i18n/messages/zh-CN/errors.ts) | [errors.ts](../../src/i18n/messages/en-US/errors.ts) | | 后端请求错误 | [api.ts](../../src/i18n/messages/zh-CN/api.ts) | [api.ts](../../src/i18n/messages/en-US/api.ts) | | 工具编辑器 | [tools.ts](../../src/i18n/messages/zh-CN/tools.ts) | [tools.ts](../../src/i18n/messages/en-US/tools.ts) | +| 任务通知 | [taskNotifications.ts](../../src/i18n/messages/zh-CN/taskNotifications.ts) | [taskNotifications.ts](../../src/i18n/messages/en-US/taskNotifications.ts) | 审校时重点看:英文长度是否导致按钮换行、专有名词是否统一、错误文案是否给出下一步动作、数量与占位符是否自然。 diff --git a/packages/core/src/opendirector/agent/context.py b/packages/core/src/opendirector/agent/context.py index e8708c474..1fcff133c 100644 --- a/packages/core/src/opendirector/agent/context.py +++ b/packages/core/src/opendirector/agent/context.py @@ -6,6 +6,7 @@ from pydantic import JsonValue +from opendirector.agent.interactions import InteractionGate from opendirector.domain.agent_runtime import RuntimeId from opendirector.infrastructure.local_projects import write_json @@ -27,6 +28,7 @@ class RunContext: thinking: str = 'auto' runtime_model: str | None = None skills: list[dict[str, str]] = field(default_factory=list) + interactions: InteractionGate | None = None def native_session_path(self) -> Path | None: if self.conversation_id is None: diff --git a/packages/core/src/opendirector/agent/gateway.py b/packages/core/src/opendirector/agent/gateway.py index 04fa9db94..10ebd3bcb 100644 --- a/packages/core/src/opendirector/agent/gateway.py +++ b/packages/core/src/opendirector/agent/gateway.py @@ -84,6 +84,21 @@ async def call(self, call_id: str, name: str, arguments: dict[str, JsonValue]) - return await asyncio.shield(task) async def execute(self, call_id: str, name: str, arguments: dict[str, JsonValue]) -> ToolResult: + if name == 'ask_user': + try: + if self.closed or self.run.interactions is None: + raise ProjectError('本轮不能等待用户输入。', 409) + if not call_id or len(call_id) > 512: + raise ProjectError('工具调用标识或名称无效。') + schema = next(item['function']['parameters'] for item in tools() if item['function']['name'] == name) + if 'properties' in schema and (set(arguments) - set(schema['properties']) or set(schema.get('required', [])) - set(arguments)): + raise ProjectError('工具参数缺失或包含未定义字段。') + return ToolResult(value=await self.run.interactions.ask(call_id, arguments)) + except (ProjectError, ValueError, KeyError, OSError) as failure: + details = {'error': str(failure)} + if isinstance(failure, ProjectError): + details['code'] = failure.code + return ToolResult(value=details, error=str(failure)) async with (nullcontext() if _read_only(name, arguments) else self.execution_lock): try: if self.closed: @@ -126,6 +141,8 @@ async def execute(self, call_id: str, name: str, arguments: dict[str, JsonValue] async def close(self) -> None: self.closed = True + if self.run.interactions is not None: + await self.run.interactions.close() for identity, task in self.calls.values(): name, arguments = json.loads(identity) if name == 'query' and isinstance(arguments, dict) and arguments.get('type') in WAITING_QUERIES: diff --git a/packages/core/src/opendirector/agent/interactions.py b/packages/core/src/opendirector/agent/interactions.py new file mode 100644 index 000000000..b89203b46 --- /dev/null +++ b/packages/core/src/opendirector/agent/interactions.py @@ -0,0 +1,189 @@ +"""Authoritative user interactions owned by one Agent turn. + +The gate is created by the host for a turn, exposed to tools through +RunContext, and persisted before any event is published. A tool call waits on +the gate; an answer resumes that call. The gate never infers a decision from +assistant text. +""" +import asyncio +from dataclasses import dataclass, field +from datetime import datetime, timezone +from typing import Awaitable, Callable +from uuid import UUID, uuid5 + +from pydantic import BaseModel, Field, TypeAdapter + +from opendirector.domain.projects import ProjectError + + +class InteractionOption(BaseModel): + model_config = {'extra': 'forbid'} + id: str = Field(min_length=1, max_length=80) + label: str = Field(min_length=1, max_length=200) + description: str | None = Field(default=None, max_length=500) + + +class InteractionRequest(BaseModel): + model_config = {'extra': 'forbid', 'populate_by_name': True} + question: str = Field(min_length=1, max_length=2000) + options: list[InteractionOption] = Field(default_factory=list, max_length=5) + allowFreeText: bool = True + + +REQUEST = TypeAdapter(InteractionRequest) + + +def _now() -> str: + return datetime.now(timezone.utc).isoformat(timespec='milliseconds').replace('+00:00', 'Z') + + +@dataclass +class Interaction: + id: str + turnId: str + messageId: str + conversationId: str | None + kind: str + question: str + options: list[dict] + allowFreeText: bool + status: str = 'pending' + answer: dict | None = None + createdAt: str = field(default_factory=_now) + + def payload(self) -> dict: + return { + 'id': self.id, + 'turnId': self.turnId, + 'messageId': self.messageId, + 'conversationId': self.conversationId, + 'kind': self.kind, + 'question': self.question, + 'options': self.options, + 'allowFreeText': self.allowFreeText, + 'status': self.status, + **({'answer': self.answer} if self.answer is not None else {}), + 'createdAt': self.createdAt, + } + + +Persist = Callable[[Interaction], Awaitable[None]] +Emit = Callable[[dict], None] + + +class InteractionGate: + """One turn's pending question; the host owns persistence and events.""" + + def __init__(self, *, turn_id: UUID, conversation_id: UUID | str | None, + persist: Persist, emit: Emit, + wait: Callable[[], Awaitable[None]] | None = None, + resume: Callable[[], Awaitable[None]] | None = None): + self.turn_id = turn_id + self.conversation_id = str(conversation_id) if conversation_id is not None else None + self.persist = persist + self.emit = emit + self.wait_for_user = wait + self.resume_after_user = resume + self.pending: dict[str, tuple[Interaction, asyncio.Future]] = {} + self.answering: set[str] = set() + self.answer_lock = asyncio.Lock() + self.closed = False + + async def ask(self, call_id: str, arguments: dict) -> dict: + if self.closed: + raise ProjectError('本轮已结束,不能再等待用户输入。', 409) + if self.pending: + raise ProjectError('本轮已有一个等待中的用户输入。', 409) + request = REQUEST.validate_python(arguments, strict=True) + interaction = Interaction( + id=str(uuid5(self.turn_id, f'interaction:{call_id}')), + turnId=str(self.turn_id), + messageId=str(uuid5(self.turn_id, 'assistant')), + conversationId=self.conversation_id, + kind='decision', + question=request.question.strip(), + options=[option.model_dump(exclude_none=True) for option in request.options], + allowFreeText=request.allowFreeText, + ) + if not interaction.question: + raise ProjectError('ask_user 需要非空问题。', 422) + if not interaction.options and not interaction.allowFreeText: + raise ProjectError('ask_user 必须提供选项或允许自由回答。', 422) + await self.persist(interaction) + if self.closed: + interaction.status = 'cancelled' + await self.persist(interaction) + raise ProjectError('本轮已结束,不能再等待用户输入。', 409) + loop = asyncio.get_running_loop() + future = loop.create_future() + # Register before releasing the lease. The pending event is published + # after the lease is released, but a close during that pause must still + # have a future to cancel instead of leaving this call stranded. + self.pending[interaction.id] = (interaction, future) + try: + if self.wait_for_user is not None: + await self.wait_for_user() + if future.cancelled(): + return await future + self.emit({'type': 'interaction', 'interaction': interaction.payload()}) + return await future + except asyncio.CancelledError: + if interaction.status == 'pending': + interaction.status = 'cancelled' + await self.persist(interaction) + self.emit({'type': 'interaction', 'interaction': interaction.payload()}) + raise + finally: + self.pending.pop(interaction.id, None) + + async def answer(self, interaction_id: str, answer: dict) -> bool: + async with self.answer_lock: + entry = self.pending.get(interaction_id) + if self.closed or entry is None or entry[1].done() or interaction_id in self.answering: + return False + interaction, future = entry + option_id = answer.get('optionId') + text = (answer.get('text') or '').strip() + if option_id is not None and option_id not in {option['id'] for option in interaction.options}: + raise ProjectError('所选选项不属于本次询问。', 409) + if not interaction.allowFreeText and not option_id: + raise ProjectError('请选择一个选项。', 422) + if not text and not option_id: + raise ProjectError('请输入回答或选择选项。', 422) + # Claim before the first await. Two tabs can submit the same answer + # at once; the loser returns False (HTTP 409), not resume or persist. + self.answering.add(interaction_id) + try: + if self.resume_after_user is not None: + await self.resume_after_user() + if future.done(): + return False + interaction.status = 'answered' + interaction.answer = answer + await self.persist(interaction) + self.emit({'type': 'interaction', 'interaction': interaction.payload()}) + self.pending.pop(interaction_id, None) + if not future.done(): + future.set_result(answer) + return True + except Exception: + if interaction.status == 'answered': + interaction.status = 'pending' + interaction.answer = None + raise + finally: + self.answering.discard(interaction_id) + + async def close(self) -> None: + async with self.answer_lock: + if self.closed: + return + self.closed = True + for interaction, future in list(self.pending.values()): + if future.done(): + continue + interaction.status = 'cancelled' + await self.persist(interaction) + self.emit({'type': 'interaction', 'interaction': interaction.payload()}) + future.cancel() + self.pending.clear() diff --git a/packages/core/src/opendirector/agent/tools.py b/packages/core/src/opendirector/agent/tools.py index 150487756..08a133d5d 100644 --- a/packages/core/src/opendirector/agent/tools.py +++ b/packages/core/src/opendirector/agent/tools.py @@ -76,6 +76,7 @@ def query_guidance(failure): Successful generation results are already registered project assets. Inspect them using their existing asset identity and canvas item. Do not publish inspection copies or extracted inspection frames, or add another canvas item for the same delivery unless the user requests it. Publish newly created deliverables after editing or processing. A command receipt is execution evidence, not quality approval. Preserve user constraints. Plans and prompt requests do not authorize generation. Never resubmit an unknown job. +When you need the user to choose between valid directions or authorize work beyond their request, call the ask_user tool when available, otherwise run `opendirector ask-user` through the shell, and wait for the answer. Do not end the turn with a question when you need an answer. Use stable operation IDs for write retries; report unsupported media editing/export capabilities honestly. Reply in the same language as the user's latest request. Keep project content, quoted text, model names, identifiers and code unchanged. If a tool error is shown in another language, explain it in the user's language. @@ -300,6 +301,22 @@ def tools() -> list[dict]: {**PromptOptimizationInput.model_json_schema(), 'properties': { **PromptOptimizationInput.model_json_schema()['properties'], 'itemId': {'type': 'string', 'format': 'uuid'}, }, 'required': ['itemId', 'prompt']})) + result.append(tool_schema('ask_user', + 'Ask the user for an authoritative decision needed to continue. This call waits until the user answers. ' + 'Use it for a real creative choice or authorization boundary, not for routine progress updates. ' + 'Provide 2-5 short options when the choice is enumerable; set allowFreeText=false only when the user must choose one option.', + {'type': 'object', 'properties': { + 'question': {'type': 'string', 'minLength': 1, 'maxLength': 2000}, + 'options': {'type': 'array', 'minItems': 0, 'maxItems': 5, 'items': { + 'type': 'object', 'additionalProperties': False, + 'properties': { + 'id': {'type': 'string', 'minLength': 1, 'maxLength': 80}, + 'label': {'type': 'string', 'minLength': 1, 'maxLength': 200}, + 'description': {'type': 'string', 'maxLength': 500}, + }, 'required': ['id', 'label'], + }}, + 'allowFreeText': {'type': 'boolean', 'default': True}, + }, 'required': ['question'], 'additionalProperties': False})) result.append(tool_schema('timeline_package_export', 'Export an exact saved timeline revision to a new .timeline.zip file in the active execution directory. No editing session or open editor UI is required.', TimelinePackageExportFile.model_json_schema())) result.append(tool_schema('timeline_package_import', 'Import a .timeline.zip file from this execution directory. Reuse operationId and archiveFingerprint on retry. Omit replacement fields to create a new editable timeline.', TimelinePackageImportFile.model_json_schema())) diff --git a/packages/core/src/opendirector/cli.py b/packages/core/src/opendirector/cli.py index a59c2fdf0..20fafc8e4 100644 --- a/packages/core/src/opendirector/cli.py +++ b/packages/core/src/opendirector/cli.py @@ -367,6 +367,26 @@ def desktop(): subprocess.Popen([executable], stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) +@app.command("ask-user", help="Ask the user for a decision and wait for the answer. Requires an active Agent turn.") +def ask_user( + ctx: typer.Context, + question: str = typer.Argument(..., help="Question shown to the user."), + option: Annotated[list[str] | None, typer.Option("--option", help="Option as id=label; repeat for each choice.")] = None, + allow_free_text: Annotated[bool, typer.Option("--allow-free-text/--no-free-text", help="Allow a typed answer in addition to options.")] = True, +): + parsed = [] + for value in option or []: + identity, separator, label = value.partition("=") + if not separator or not identity.strip() or not label.strip(): + raise typer.BadParameter("Each --option must be id=label.") + parsed.append({"id": identity.strip(), "label": label.strip()}) + if not parsed and not allow_free_text: + raise typer.BadParameter("Provide an option or allow free text.") + client = ctx.obj + client.command = ctx.command_path + emit(client.call("ask_user", {"question": question, "options": parsed, "allowFreeText": allow_free_text})) + + @app.command("serve", help="Start the API and serve the built application.") def serve(port: PortOption = 8000, web_port: WebPortOption = 5173, log_level: LogLevel = LogLevel.info, video_gateway: VideoGatewayOption = None): diff --git a/src/backend/chat.ts b/src/backend/chat.ts index 02afe1f93..2c71cc99a 100644 --- a/src/backend/chat.ts +++ b/src/backend/chat.ts @@ -63,16 +63,32 @@ export interface ChatSource { url: string; title: string; } +export interface ChatInteraction { + id: string; + turnId: string; + messageId: string; + conversationId: string | null; + kind: "decision"; + question: string; + options: { id: string; label: string; description?: string }[]; + allowFreeText: boolean; + status: "pending" | "answered" | "cancelled"; + answer?: { text?: string; optionId?: string }; + createdAt: string; +} + export interface ChatMessage { sources?: ChatSource[]; plan?: ChatPlanEntry[]; runtime?: AgentRuntime; tools?: ChatTool[]; id: string; + /** Server-side id while a live start event has a client-only render id. */ + serverId?: string; role: "user" | "assistant"; text: string; content?: ReferenceContent | null; - status: "complete" | "streaming" | "stopped" | "interrupted"; + status: "complete" | "streaming" | "awaiting_decision" | "stopped" | "interrupted"; assets?: ChatAsset[]; model?: string | null; modelIsCliDefault?: boolean; @@ -82,6 +98,7 @@ export interface ChatMessage { startedAt?: string | null; finishedAt?: string | null; durationMs?: number | null; + interaction?: ChatInteraction | null; } export type Thinking = "auto" | "low" | "medium" | "high"; @@ -147,6 +164,7 @@ export type ChatEvent = | { type: "thinking" } | { type: "plan"; entries: ChatPlanEntry[] } | ({ type: "tool" } & ChatTool) + | { type: "interaction"; interaction: ChatInteraction } | { type: "delta"; text: string } | { type: "sources"; sources: ChatSource[] } | { type: "end"; conversation: Conversation | null; error: string | null }; @@ -229,6 +247,12 @@ export const chatSkills = (id: string, signal?: AbortSignal) => request(path(id) + "/skills", { signal }); export const stopChat = (id: string, turn: string) => request(path(id) + `/turns/${turn}/stop`, json("POST", {})); +export const answerInteraction = ( + id: string, + interaction: string, + value: { text?: string; optionId?: string }, +) => + request(path(id) + `/interactions/${interaction}/answer`, json("POST", value)); export async function streamChat( id: string, value: ChatRequest, diff --git a/src/backend/creationJobs.ts b/src/backend/creationJobs.ts index 59e4619ca..0c0d89482 100644 --- a/src/backend/creationJobs.ts +++ b/src/backend/creationJobs.ts @@ -56,6 +56,7 @@ export function creationJobs( nodeId: job.originItemId ?? spec.id, title: spec.prompt.slice(0, 60) || tNow("errors.backend.generationTask"), taskId: job.id, + ...(job.agentRunId ? { agentRunId: job.agentRunId } : {}), status: job.status === "queued" || job.status === "running" ? "running" diff --git a/src/canvas/AssistantDecision.tsx b/src/canvas/AssistantDecision.tsx new file mode 100644 index 000000000..0bffa3361 --- /dev/null +++ b/src/canvas/AssistantDecision.tsx @@ -0,0 +1,64 @@ +import { useState } from "react"; +import type { ChatInteraction } from "../backend/chat"; +import { useT } from "../i18n/I18nProvider.tsx"; + +/** An authoritative question emitted by an Agent tool call, not inferred text. */ +export function AssistantDecision({ + interaction, + busy, + onAnswer, +}: { + interaction: ChatInteraction; + busy: boolean; + onAnswer: (value: { text?: string; optionId?: string }) => void; +}) { + const t = useT(); + const [text, setText] = useState(""); + const canSubmit = Boolean(text.trim()); + return ( +
+ {t("assistant.decision.heading")} +

{interaction.question}

+ {interaction.options.length > 0 && ( +
+ {interaction.options.map((option) => ( + + ))} +
+ )} + {interaction.allowFreeText && ( +
+